开发者

Setting values of an object

Let's say I've got a class called Ho开发者_JAVA技巧use 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"?


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.


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.


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜