Skip to main content
3 of 5
added 16 characters in body
candied_orange
  • 114.6k
  • 27
  • 222
  • 352

Should setters only set the values of class properties, and not perform any other logic?

No.

Following this rule makes setters pointless to have. The only reason we put up with this tragic preemptive clutter is because some languages (also looking at you Java) have forced us to provide setters even when their side effects don't exist yet because allowing direct assignment to public fields establishes an interface that would have to change to allow us to add side effects like validation. Other languages, like C#, allow the using code to stay the same: o.x = -1; In c# that might throw an exception at you. In C++ that would have to be o->setX(-1); to do that.

A client shouldn't have to change to add this. That's why, when you're stuck in a language that doesn't let you add these later, you have to start out with setters. Even when you don't need them now. This is manual aspect oriented programming for languages that can't do it themselves. We do this so we get the chance to do something before or after the value is set. Even if we don't know what that something is going to be yet. Even when we don't need it now. We're doing this to be prepared for when we do.

We create setters that have no side effects only because our language doesn't have the flexibility to let us cleanly add them later without breaking clients. If you forbid ever adding the side effect this whole annoying exercise is pointless.

Well, except for breakpoints. They can be handy places to set breakpoints. But other than that, this makes them pointless!

candied_orange
  • 114.6k
  • 27
  • 222
  • 352