开发者

Using getters() or using direct field access within a POJO?

Given a simple POJO does it really make a difference or are there possible side effects in using either one of the following:

total = getPriorAmount() + getC开发者_运维知识库urrentAmount();

OR

total = this.priorAmount + this.currentAmount;

When used within the POJO.


There are always side effects :-)

In this case it may be a simple POJO now. But in 2 weeks (month, years) someone may add some conditional logic to your getter methods and getCurrentAmount() may no longer be the same as this.currentAmount (the latter may be a last known "cached" value, for example and getter method may recalculate it).

That's why it's always a good idea to code to interface, even if interface in this case is the object itself (e.g. its public getters).


While there is little difference from an operational standpoint, I would say it definitely a best practice to use a method rather than the direct reference. You never know when the simple code you are writing today will grow to the point where the direct reference will be broken by someone doing something more elaborate with the local variable (caching, recaling it from other data, ect).


Generally, no it does not matter.

I would use the second example as it removes indirection and you know exactly what value you are accessing. You might decide later that you want to perform additional computation on the value before returning it, thus changing the meaning of the getter method. (Although in that case, you should create new getter method that returns the new value... but let's say you were tired and just added a line in that same getter by accident.) Now, you would be getting a value that you might or might now expect. If this might be what you want and you want this to be applied across your code then good, if not then you have a problem or you'll be getting the wrong result without knowing about it.


Unfortunately, Java does not support the uniform access principle (other languages, like C#, Scala and Ruby, do), and therefore we are stuck with the ugly and cumbersome getter / setter syntax.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜