tags:

views:

69

answers:

5

Hi.

Let's say I've got a class called House with the two fields

name
address

Each of these fields has got a getter and a setter.

Now I want another method in the House class called setValues. This method should set the fields with properties from a passed object of a different type.

There would be two ways on how to create this method. First way:

private void setHouse(HouseTransfer transer){
   name = transfer.getName();
   address = transfer.getAddress();
}

Or the second option:

private void setHouse(HouseTransfer transer){
   setName(transfer.getName());
   setAddress(transfer.getAddress());
}

Which one is more "best practice"?

+3  A: 

I would use the individual getters/setters inside of the setHouse method (which is your second option).

The fact that you have setters indicates that there is some kind of encapsulation involved around that operation. Rather than re-write the code to enforce that encapsulation, re-use what you already have.

Justin Niessner
+1. For example you may have some event notification within the setters (which is not necessarily a good practice, but I've seen it a lot)
Bozho
A: 
private void setHouse(HouseTransfer transer){
   this.name = transfer.getName();
   this.address = transfer.getAddress();
}  

I feel this is more readable /

org.life.java
+4  A: 

At a certain level of granularity, software design is more subjective matter than one of black-and-white absolutes. I do not believe there is an absolute "best practice" here.

That being said, I personally would use the second form. The basic idea of having a setter method is that at some point you might need some some special logic around setting that value (e.g. formatting input, sanitation, validation, etc). So it makes the most sense to always rely on any such logic being in one central place, rather than scattered throughout you code anywhere this variable is set.

If you have a truly trivial example, where the setter is simply setting the value and know absolutely that no other logic will ever be added, then you could certainly use the first form for simplicity. Put there's not real performance hit to the second form, so I personally would just use that.

Steve Perkins
+2  A: 

Jon's answer to that question (Taken from another question about using getters/setters which is not a duplicate to this one)

You don't always need getters/setters, but if you have some, there's usually a good reason why you've implemented them and in that case: use them.

Andreas_D
A: 

Perhaps if you are getting and setting in two different places you might consider factoring out your getter and setter to a common interface. This can make later customisations easier, right?

AlexW