Code Style
[Extra 1]
We've now, somewhat suprisingly, covered everything that was in the earliest third generation languages in terms of core language features. With these basic elements (primitive variables, operators, loops and branching commands) you could construct a wild variety of scientific programs, from "Hello Lab Colleagues" to landing someone on the moon.
This is, then, a good time to take a breather and to focus on making sure we're approaching code in the right way. Getting into good practice now will make staying on top of coding much much easier in the future. So, in these extra slides we're going to look at coding style.
Further info:
The Java code conventions are online at: Code Conventions for the Java Programming Language.
Interview with poet and coder, Richard Gabriel.
A series on writing good code by Janice Heiss: Part 1; Part 2; Part 3.
For some good books that will help with making your code clear, efficient, and elegant, see our Recommended texts list.
Quiz:
Look at the following code:
System.out.println((new Point()).x);
What's going on is ____________________________.
- beyond me, my friend
- that we're printing the default x value of a Point object, but without giving the object a name
- that we're using the Point class in some way to get an x value without making an object
- something to do with vectors
Correct! We don't always have to assign a label to an object, if we're just going to use it once, though this is quite rare. Here we make
a new Point object with new Point()
, but rather than attaching it to a label, we just use it directly to get its x value. The code
is the equivalent of:
Point pt1 = new Point();
System.out.println(pt1.x);
but without the labelling. This is one rare case where we have a variable without having a lowercase name for it.