Sometimes ordinary Object Oriented principles are over-engineering.  If code is not intended for reuse and member variables are only referenced in a few places, it is not always necessary to encapsulate them using getters and setters or to abstract them into complex interfaces.  When you ask why you often hear “in case someone wants to do something with them later, we will be ready”.

In most instances a small refactoring activity later can achieve the same result, but on demand.  Don't write code for Justin*.

Normally when a programmer creates a bean, the getters and setters map straight through to the underlying member variable. The methods have the same name as the member variable, and if the name of the variable changes, all the getters and setters change also.  

If the bean is only for use storing simple types, and these parameters are unlikely to change, an old C-style structure is appropriate to save time (ie. with public values and no methods).

So if there is no plan to reuse the class, it is OK to make it public with no methods.  This way the object is clearly identified as a C-style “struct”.

// used only for putting into the statistical map as the value:
public class RenderStat
{
    public long timeIn;
    public long timeOut;
    public long byteSize;
    :
}

This rule doesn't mean you have permission to deviate from the Java Bean spec and make all your classes public without getters and setters – there are good reasons to encapsulate internal implementations with accessor methods and most good IDEs will generate them for you with a few key presses. In a certain rare cases such as this one, the class is not intended for reuse or inheritance, internal implementation is unlikely to change so getters and setters would add no value.  Always evaluate the nature of the classes you are creating and build as little or as much structure around them as you need to.

*Justin Case, the famous programmer

blog comments powered by Disqus