More Thoughts on Object Oriented Code
In talking with another dev this week, I think I have my simplest summary of object-oriented code yet: when you are writing well written object oriented code, you’ll know it by the questions being asked by your code.
So what does this mean?
A good example is the following:
FormData formData = GetFormData();
// Object-oriented? Not really:
bool isValid = FormDataUtil.IsValid(formData);
bool isValid = formData.IsValid();
It’s very subtle, but it’s very easy to observe because you simply need to ask yourself if you are asking the questions to the right objects. We don’t ask FormDataUtil if the formData is valid, we ask the formData directly.
Primarily, what this will reflect is the principle of encapsulation.
When you are asking the right questions to the right objects, you’ll find that the code is easier to read, easier to maintain, less fragile, and more natural to reuse.
If the code is well written, as first time users, we don’t have to know that there is a class explicitly designed to validate the form data; we can find it easily on the class itself.
I don’t think it gets any simpler than that and yet it is, to me, the very essence of what it means to write object-oriented code.