Talk:Getters and setters

From CSSEMediaWiki
Jump to: navigation, search

I've never been a fan of the getter/setters everywhere design maximum. The obvious annoying case is the trivial getters/setters:

private int foo;
public int get_foo(void)
{
    return foo;
}
public void set_foo(int foo)
{
    this.foo = foo;
}

This doesn't help you at all, and just makes it more annoying to access the variable outside of the class. If your getters and setters look like the above you should just make foo public, since it basically is anyway. The two main arguments against this are: "What if we change foo's setter later to have additional constraints?" and "What if we change the type of foo?"

The second argument is bogus, since even if you have a getter/setter, you will elsewhere have some code like this:

int bar;

bar = some_foo_object.get_foo();

So, if you change the type of foo, you still have to change the type used elsewhere. The answer to the first question is: _when_ this happens, make foo private and use a getter and setter. The obvious complaint here is: "but I have accessed foo in hundreds of places, and it will take forever to change them all". Tough. Anyone who makes this complaint either cannot use their editor properly, or needs to learn some basic scripting. There will be worse changes than this that you have to make to software. I consider this to be part of the YAGNI (You Ain't Gonna Need It) principle: If are variable doesn't have any constraints on its getter/setter then just make everybody's lives easier and make it public. Make your code clear and easy to use for, religiously follow design maxims second :-) ~ Ryan

Personal tools