Performance vs. Laziness – Why Use Setters from Within a Class?

performance

I notice that web related code uses setter methods to set class fields instead of setting them directly since they are in scope. I find this to be a bit odd. Using setters is certainly safer, but if unit tests are implemented then bugs will be found. And it's not worth the extra stack call, imo.

Does any production code do this or is this just what you see in sample code online?

Edit: I have to make clear that I'm only talking about the case whereby the setter consists solely of a single assignment expression and nothing more.

Best Answer

You should follow the open/closed principle. Not using the setter means your class is not open to extension, because subclasses overriding the setter to maintain internal consistency by adding some according logic within the call will not have that logic executed and thus wind up with an inconsistent state.

As opposed to that, the argument with the extra call is virtually void.
Either the setter is overriden in a subclass, which means not using it is strictly not an option. Or the setter is not overriden, in which case any decent (JIT) optimizer will be able to inline it and thus achieve the same performance.

Related Topic