You can to more with it than just hit “Generate Getters and Setters”

Jan 18th, 20071 Comment

I’ll put aside my distaste for getters and setters and just assume they are a fact of life. And, for me now, they are — all of the data classes in the project I inherited have them. Okay, I can deal. And it seems that each one has internal classes representing data that is a part of the data. Not ideal, but I can live with it.

But this is the crap I don’t want to deal with:

 owner = item.getLastUpdate().getOwner().getName();

But what is even worse:

owner=null;
if (item.getLastUpdate()!=null ) {
if (item.getLastUpdate().getOwner()!=null) {
owner = item.getLastUpdate().getOwner().getName();
}}}

This is comical the first time you see it. It makes me want to scream the fifth time. But by the tenth time I just want to cry.

You see, just because you have a class has that a bunch of private properties and the results of “Generate Getters and Setters” does not mean that the class has to stay like that. You can add your own methods that may make life easier. Like so:

 public String getLastOwnerName() {
if (this.getLastUpdate()==null) { return null; }
if (this.getLastUpdate().getOwner()==null) { return null; }
return this.getLastUpdate().getOwner().getName();
}

You might be alarmed that this getter has no setter. That’s okay — you will survive. It’s worth it if you can replace the above if statement that is in your code ten times with the following:

owner = item.getLastOwnerName();

Wow — isn’t that so much nicer? And, what is even better is that, if how to change how you get the last owner name, you only have to change one method, not ten. How about that!

This concludes my rant.

One Response to “You can to more with it than just hit “Generate Getters and Setters””

  1. ghostetler says:

    Oh wow, I am so alarmed that this getter has no setter. My day is ruined now.

Leave a Reply

You must be logged in to post a comment.