Subject: Var access question... 2006-11-01 - By Mike New
Back > Hi list, I'm wondering if it's a good practice to access fields (in > the same class) through its names and not by its accessors, e.g. > > public class ComplexNumber { > private double U; > private double V; > > // constructor deleted > > public double real() { > return U; > } > > public double imaginary() { > return V; > } > > public double magnitude() { > return (Math.sqrt(Math.pow(U, 2) + Math.pow(V, 2))); > // access here must be U or real(), same with V > } > > public double arg() throws ArithmeticException { > return (Math.atan(V / U)); > // access here must be U or real(), same with V > } > > public ComplexNumber times(ComplexNumber Z) { > return new ComplexNumber(U * Z.U - V * Z.V, U * Z.V + V * Z.U); > } > } > > I think it accomplish to OOP rules (encapsulation), the object itself > manages its state interacting with its fields and no other can change > their > properties, but I've seen many samples that use getters methods to access > values, I don't know why...any clue ???
Providing a getter has the advantage that you can change the behaviour without changing the class' API. So getMyObject() might at first look like this:
// myObject should be initialized already public MyObject getMyObject() { return myObject; }
but later you might want to lazily initialize it, so you could change it to this:
public MyObject getMyObject() { if(myObject == null) { myObject = initializeMyObject(); }
return myObject; }
Giving other objects direct access to myObject would make the above change much more difficult, and you'd HAVE to initialize it early on, such as in the constructor.
I have several examples where I might not need an object which is expensive to initialize (i.e. a file specified by a URL), so I want to populate the variable only when necessary.
Other arguments are that encapsulation is just cleaner, making the class easier to use and understand. The value of this shouldn't be underestimated, IMO.
Mike > > =========================================================================== > To unsubscribe, send email to listserv@(protected) and include in the > body > of the message "signoff J2EE-INTEREST". For general help, send email to > listserv@(protected) and include in the body of the message "help". >
-- ---- ---- ------ _/ /// // -- ---- ---- ---- --
=========================================================================== To unsubscribe, send email to listserv@(protected) and include in the body of the message "signoff J2EE-INTEREST". For general help, send email to listserv@(protected) and include in the body of the message "help".
|
|