Property Observers Are a Terrible Idea

A very quick rant to get catharsis after a frustrating morning.

A "property observer" is a special method on a class that is called internally whenever a property is accessed. They're called property observers in the swift programming language, but they also exist in python (@property), php (accessors and mutators in eloquent), and many other places.

I personally believe these are an awful idea. They break a major rule of good programming: don't have hidden control flow.

When a typical developer reads `user.name = name`, they don't think to themselves "I bet that's calling a hidden method". There's no method name to indicate what occurs during the setting of the property, or whether an exception can be thrown. They can't use their IDE to click through to the method definition like with a normal method. It looks like an incredibly simple operation, but for all we know it queries the database.

Here's my suggested alternative:
If the constructor is getting too long, use a builder, they're rad. If you need a lot of getters, you're probably writing some code that's more coupled than you want it to be.

Subscribe to BenIsOnTheInternet

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe