February 06, 2006

Java Pet Peeves #2:Useless assignments

Boy; am I moaning today :)

So my second pet peeve is unnecessary assignments within Java.

Essentially; all member variables will be assigned to a default value (Object=null, int=0, boolean=false), whilst all local variables will have no initialisation.

Thus, the following two classes will be equivalent:

public class ClassThatUnderstandsHowJavaWorks {
  private Object o;
  private boolean b;
  private int i;

public class ClassThatDoesntUnderstandHowJavaWorks {
  private Object o = null;
  private boolean b = false;
  private int i = 0;

I have heard the argument that the second form is more explicit. I don't but this because it means every time you write a member variable you need to write extra crud. Every time! It would be far better to educate people once and write neat code, than write bad code over and over.

The other aspect of initialisation is allowing the compiler to help you. For example, if you have a variable which should always be initialised within an if clause, how many people would write:

  String message = null;
  if (someCondition) {
    message = "a message";
  } else (someOtherCondition) {
    message = "some other message";

This code will compile, and work; but will allow the situation for message to be null (if neither condition is used). If the assumption is that one of the two conditions will always be true, the compiler cannot help you.

Remove the initial initialisation and the code won't compile:

  String message;
  if (someCondition) {
    message = "a message";
  } else (someOtherCondition) {
    message = "some other message";

because the compiler will catch the fact that there is a route through your code that will leave message in an uninitialised state. Forcing you to rethink your if condition.

- One comment Not publicly viewable

  1. private Object o = null;

    This is a bad habit I picked up from C :)

    14 Mar 2006, 08:24

Add a comment

You are not allowed to comment on this entry as it has restricted commenting permissions.

February 2006

Mo Tu We Th Fr Sa Su
Jan |  Today  | Mar
      1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28               

Search this blog



Most recent comments

  • Interesting… While I'm not completely convinced in such microbenchmarks, I'm pretty sure that 1ms … by Alexander Snaps on this entry
  • Hello. I bought the book yesterday. I was trying to find the source code for chapter 11 and chapter … by Suleman on this entry
  • http://woosight.net/account/login?username=demo by live mashup demo on this entry
  • Thanks mate ….. This blog was really helpful. by Maaz Hurzuk on this entry
  • Ty. Not directly helpful for my problem, but pointed me in the right direction. You will also get th… by Mike E. on this entry

Blog archive

Not signed in
Sign in

Powered by BlogBuilder