Friday, November 16, 2007

What is wrong with public fields?

Public fields are bad for your OO. If your datafields are public anyone can do
dansaccount.balance = dansaccount.balance - 4711; which would be pretty disastrous for my private economy.

Instead we protect our data by wrapping them in getters/setters, which enable us to do
dansaccount.setBalance(dansaccount.getBalance() - 4711); which is equally as disastrous to my economy.

If we claim to encapsulate our data and provide set/get, we could equally well use public fields to me. The only difference is forcing us to a really non-intuitive syntax of assignment: security through obscurity in other words.

Of course public fields are bad OO, we just have to know why.

The interesting part is not encapsulation of data, it is encapsulation of behaviour. Let us have a look around our system and see at how many places our data is interpreted in a non-trivial way. Probably we will find a few places where a string is interpreted as an order-number and a non-trivial format is enforced. If that logic (might just be one line of code) is spread out through the system, it does not matter how well you protect your data with setters, you have bad encapsulation anyway.

What bad encapsulation leads to is most of the time duplicated functionality, i e same functionality written at several places, because the programmer did not find the first implementation. Note that this does not necessarily mean duplicated code, the order-number check might be rewritten slightly different every time.

So, public fields are bad, but not in a way that get/set solves.