I have a simple design question:
assume you have two variables in a class, e.g.
[pseudocode]
class MyObject {
String a;
String b;
function setA() {
}
function getA() {
}
function setB() {
}
function getB() {
}
}
Assume that the getter & setter are not just simple getter & setter ,
there are some algorithms inside, but the algorithms are the same for
a & b (but apply to different variable - a & b), so we are duplicating
codes in the above example, i.e. in setA and setB
so should we do something like?
function set(target, value) {
// do the common stufft
target = value;
}
function setA(value) {
this.set( this.a, value );
}
function setB(value) {
this.set( this.b, value );
}
do you think this design is good?
thanks.
Knute Johnson - 25 Feb 2007 16:58 GMT
> I have a simple design question:
>
[quoted text clipped - 48 lines]
>
> thanks.
In this case I would use the latter option. The whole
purpose of getters and setters is to isolate the actual
variable from the outside of the class.
The First method won't work outside of the current
package either because a and b are not visible there.
knute...
Lew - 25 Feb 2007 17:02 GMT
> assume you have two variables in a class, e.g.
> public class MyObject {
[quoted text clipped - 3 lines]
>
> public void setA( String v ) {
set( a, v );
> }
>
> public String getA() {
...
> }
>
> public void setB( String v ) {
set( b, v );
> }
>
> public String getB() {
...
> }
private void set( String x, String v )
{
...
}
> }
>
> do you think this design is good?
Perfectly valid. The choice to do this refactoring depends on how complicated
the logic is in set( String x, String v ). Might not be worth it for a
one-liner. OTOH, there are reasons even then.
- Lew
Patricia Shanahan - 25 Feb 2007 17:03 GMT
...
> function setB(value) {
> this.set( this.b, value );
> }
>
> do you think this design is good?
No, because it won't work. Java uses call-by-value, so the set method
only gets a copy of each of its parameters.
However, you could do:
function setB(value) {
b = set(value);
}
where set does the common calculations, and returns the resulting value.
If it needs the old value of b, pass that in as a parameters.
Patricia
Lew - 25 Feb 2007 21:54 GMT
howa wrote:
> ...
>> function setB(value) {
>> this.set( this.b, value );
>> }
>>
>> do you think this design is good?
> No, because it won't work. Java uses call-by-value, so the set method
> only gets a copy of each of its parameters.
OTOH, if a and b are not immutable (foolish of me not to notice that) then
set( x, v ) could alter internal state of x.
OTOOH, your suggestion is the better design.
- Lew