Getters and Setters are better than public properties

I ran into something that bit me in the butt the other day and I have been meaning to talk about it.

Getters and Setters are better than public properties!

In theory, it seems like a property of a class that should be freely written and mostly read from should be a public property. It is easier code to read and as long as nothing changes, easy to maintain.

But there is the rub. Easier to maintain. What happens if you decide to change the name of the property? You basically break everyone who is using your class. What happens if you want to close off write access only? You can’t do that with public properties. Theoretically you could do that with magic functions but we won’t get into that discussion here.

With getters and setters, I can easily change the names of properties internally without disturbing the classes API so to speak. For instance, if I have a class that is modeled after some database entity and then the entity is changed dramatically (as what happened to me), then I wouldn’t be in trouble if the properties were set with getters and setters.

I realize that this might seem unruly for large entities, but this can be quickly done with a script that will run through the getters and setters and set them up. Think about it! Code that writes your code. As a side note, I do it all the time to generate different bash scripts, etc…

This post does not take into account performance issues and there may be some instance of public properties that I have not accounted for, but in this writer’s opinion getters and setters, although slightly more time consuming in the long run, are much better for maintainability which is crucial in large applications.