Tuesday, 18 April 2006

Student Java gotchas

We've been doing a lot of marking lately, it being the holidays, which is always a revealing experience. The results have been pleasing, but having to go through Java code caused me to remember how many small idioms students wrongly replicate. OOP so often ends up being all about style and detail and much of that can elude a beginner, because there's so much to learn about programming when you start.

My two favourite annoyances are unnecessary setters and getters and the following use of boolean expressions:

while / if(x == true) { ... }

The latter just says that the student doesn't really understand how expressions are evaluated, which is pretty fundamental, although I've seen the same "mistake" in production code too.

The first thing about setters and getters is slightly more subtle. A field should be declared private if either it is or should never be used by another object or if it has some class or object invariant associated with it. A field with no associated invariants can be declared public. In fact, this is probably preferable, as declaring a field to be public tells anyone using your API that that particular field definately has no invariants associated with it that they need to think about.

No comments:

Post a Comment