Benefits of supporting tools

One of the deliverables to our current client is a project template, containing tools to guide them to build better software, ensuring lower bug occurrence and system integrity.
One tool we are using is Findbugs. One day, when running it, we came across an interesting issue, Findbugs was complaining that a class in a project was exposing its internal state, subjecting it to unexpected modifications. The class contained a single constructor with parameters setting its initial state and a set of getter methods. Any Java developer used to getters and setters pattern would say that the code below is valid.

What would happen if you create a Person instance passing as parameter, pre-defined name and dateOfBirth variables and then, perform operations over these variables, modifying its states? And what if you retrieve these attributes (through getter methods), assigning them to new variables and start performing operations over them? For the name attribute it wouldn’t be a problem, since String objects are immutable, but certainly both cases would affect the dateOfBirth attribute, corrupting the state of the object.

One of the solutions to this problem would be to make getter methods always return a new object, copy of the original one and during object construction, initialize instance variables with new objects, copy from the original ones passed as constructor parameters.

So, unless the objects you are implementing are good citizens and contains side-effect-free functions, you should consider programming in a more defensive way, to avoid unexpected behaviors in your project and also make use of tools like Findbugs to turn the development easier. Checkstyle and Cobertura are a good start.

2 Comments »

  1. Dries said,

    June 19, 2008 @ 12:39 pm

    Be aware of possible NullPointerExceptions if dateOfBirth is null, so the suggestion is the include a null check (in both getter and setter)!

  2. alexandre said,

    June 19, 2008 @ 2:30 pm

    Hi Dries, thanks for your comment.
    Indeed you are right, I could have been more defensive checking for null state but this is not the purpose of the example.
    Just adding another possibility to the problem above, we could declare the fields as final, so that they should be initialized when the objected is constructed and cannot be changed.

RSS feed for comments on this post · TrackBack URI

Leave a Comment