Re: classes question
- From: Mark Thomas <anon>
- Date: Thu, 27 Apr 2006 16:35:20 +0100
Wojtek Bok wrote:
Thomas Weidenfeller wrote:I think the question that you should be asking yourself is why does one object *need* access to another object's state. Ideally the object itself should do all processing that involves its own state - that's what Thomas was talking about in his first statement. If getters and setters are needed, it implies that some object is performing processing involving another object's state, and perhaps indicates that the design needs refactoring. Getters & setters are a violation of encapsulation and should be avoided.Typically, the method changes the state as a side effect of doing
something, but it has (unfortunately) also become very popular to
provide methods which just change an object's state, but doing nothing else.
This statement with:
In Java, methods just changing an object's internal variable/state are
called setters. Methods just reporting an object's state/variable are
called getters.
confuses me.
Getters and setters are there to change the state. Sometimes they also do some ancillary processing, but mostly they change the values of private variables.
So in the first statement you label this as a bad thing, while in the second statement you endorse it. So which is it?
Not trying to start a flame-war here. Just confused.
I exclusively use getters/setters for all access to object variables (state change). This has saved me where I needed a setter to also change another state variable. A trivial example which assumes that the setting of the name is done once, whereas retrieving the full name happens many times:
Original:
public void setGivenName(String name)
{
ivGivenName = name;
}
Changed:
public void setGivenName(String name)
{
ivGivenName = name;
ivFullName = ivGivenName + " " + ivSurname;
}
Just my tuppence-worth
Mark
.
- References:
- classes question
- From: linuxnooby
- Re: classes question
- From: Thomas Weidenfeller
- Re: classes question
- From: Wojtek Bok
- classes question
- Prev by Date: Re: classes question
- Next by Date: Re: classes question
- Previous by thread: Re: classes question
- Next by thread: Java won't render.
- Index(es):
Relevant Pages
|