OOP Should all properties have getters and setters

design-patterns, oop

Solution

Getter and setter should be always used. The reason of getter or setter is not to provide a public interface to internal properties, rather to provide a control over read/write of a property. They provide abstraction over the class properties.

Even your class properties is private you need getter and setter. This allows to control the value just before assigning or reading.

Think about a class you designed long ago where you do some common calculation for each read.

class A{
    private decimal x;
    public void do_stuff(){
        decimal a = this.x/70;
        // process with a
    }
    public void do_anoter_stuff(){
        decimal a = this.x/70;
        // process again a
    }
}

Now you want to change the factor (70). how do you do it? change it in every place? Better design it this way.

class A{
    private decimal x;
    private get_x(){ return this.x/70; }
    public void do_stuff(){
        // process with get_x()
    }
    public void do_anoter_stuff(){
        // process again get_x()
    }
}

The fact is blindly using getter and setters for every property is evil. The rule of thumb is. Declare all properties as private with private getter and setter. Later change the visibility of the getters and setters only to allow access from outer world when needed

Problem

I have always provided getters and setters for most class properties. Although i have read that this is bad - http://www.codeweavers.net/getters-and-setters-are-evil/ Doesnt dependency injection and unit testing require that most properties have a setter?

Original source