As Alan Kay puts it (paraphrasing): "setters turn an object back into a data structure"
As Alan Kay puts it (paraphrasing): "setters turn an object back into a data structure"
I agree that if you class Foo with a property:
public string Bar {get; set; }
and used as:
foo.Bar = "baz"
It does look like just another data structure. But what's the difference between that and having a method:
public void setBar(string value) { _bar = value; }
It is just as easy to add logic to the property later on:
public string Bar{ get{ return _bar; }; set { ...some logic; _bar = value; }
As it is:
public void setBar(string value) { ..some logic; _bar = value; }
In fact, they both compile to roughly the same thing.
class Foo { Foo(string bar) { _bar = bar; } //Foo is the constructor }
The benefit being that once an object is created, it is guaranteed to be in a valid state.
But by classical OO an object represents state + behavior. So why not do both?
Assign the value in the constructor to guarantee that the object is always in a valid state and use a property (if the object is an entity as opposed to a value object), when it needs to change?
The problem becomes using setters where that's not the case, often to support tooling that is dependent on constructing objects from serialized state (which often also involves the same kind of abuse of getters, to which exactly the same concerns apply.)
Even if a method does nothing but set an internal field of an object, in my eyes it's not a setter if it performs an actual high level task and doesn't expose the internal structure. IE:
monster.setDead(true);
Is a setter. While monster.Kill();
Is not to me, even if it does the exact same thing inside. The latter doesn't bother me about internal details like some boolean field called "dead".It's a subtle and almost pedantic distinction, but I hope you see where I'm coming from, and can appreciate the mindshift change from "this is a box full of fields" to "this is an entity".
It's used mostly because novice Rubyists are told that that's how you make a variable accessible, not that that's how you make it read-writable. In C#, on the other hand, when you create a property that's the moral equivalent, there's a lot more of a focus on creating getter-only properties that reveal state but don't let you munge it.
Ruby is also pretty bad about using #freeze and #taint, but the latter is a lost cause.