Saturday, September 04, 2010

What do you mean by "Everything"?

I had a great meeting with someone the other day who, during the course of our conversation, questioned my statement in my post below1 that "Everything does not need to be a Class".  His rationale was that if something had attributes, it should be a class. I realized that this point of mine needed clarification.

I like Classes that represent some real-world object; whether tangible (car) or intangible (transaction). It's a thing that has real attributes which, when taken as a whole, comprise that thing.  So sure, create a Class and instantiate it a few times as needed to get a few things happily bouncing around your system. If it has an analogue in the physical world, it's an excellent candidate for a Class.

What I object to can be shown by example: A Class composed of a collection data transformation functions. Why does this need to be an Object? It's a module full of functions, really, and does not need the additional layer of Class in there to wrap the methods. This Class doesn't represent a thing, and doesn't have attributes. I'd recommend module-level functions.

Another example is best demonstrated by a process that does the following:
1. Generate some JSON for consumption by a web client
2. Wrap this JSON in an instance of a class (no other attributes).
3. Send this object to the client.
4. The client unwraps the JSON from the object
5. The client consumes the JSON.

I object that there needs to be an Object here.  I'd rather see
1. Generate some JSON for consumption by a web client.
2. Send the JSON to the client
3. The client consumes the JSON.

I fully realize that all of this sounds (and is) absolutely elementary.  And yet, I run into over-Objectification more frequently than I believe is desirable. (The whole wrap-JSON-in-an-object was rationalized by the engineer, "Everything in the system is an object, and I wanted to be consistent".  Someone else was optimizing for the future, "We might need more stuff sent to the front-end someday. This makes it a no-brainer for the next engineer".)

"If all you have is an OOP, everything looks like a Class".  I believe that engineers should have a whole box of tools from which to choose, and OO is one of those tools among others. When everything in your system is an object, it's clear that your toolbag contains only one tool. Even worse is when every object inherits from some other object, sometimes in stacks of 5, 7, 12 Classes high. (e.g., no use of object-composition whatsoever: conflation of the "Is-A" ad "Has-A" relationship concepts, conflation of data and function, etc).  And, once again, ultimately we're engineers in a business; our responsibility is not at all to the gods of OO, it is to the business.  It's very valuable to learn when a Class is absolutely appropriate and awesome, and when It Is Not.