The farce known as “object oriented programming”

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com, or follow me on Twitter.

Jayway has a nice critique of how much real-life object oriented programming departs from the beautiful theory:

One thing I have realized is that in Java we use classes for many purposes. In a typical web application written in Java using something like Spring framework you will often find:

Data transfer objects (DTO:s)

Services (REST API, controllers, DAO:s)

Rich objects (if you’re lucky!)

A DTO is just a struct and contains no behavior. To minimize the boilerplate in Java I tend to implement DTO:s using public final fields. I like the fact that the DTO:s act as a schema. For example this acts as documentation of the output of a REST service. However, I have found that most client developers don’t care about the schema and are instead interested in sample data. Sometimes you also see DTO:s as part of database access. These DTO:s are sometimes referred to as anemic domain objects, but essentially they are the same.

A Service (or Spring Bean) is typically a singleton that contains some methods and some collaborators injected as fields using dependency injection. The different collaborators are other services that implement certain interfaces. Besides implementing an interface a Service only act as a placeholder which collects related methods and perhaps some shared private methods. A problem with the singleton pattern is that newbie developers doesn’t realize the consequences of sharing the same instance between multiple threads. They store state in private fields to avoid having to pass along one or more objects to several methods. Very convenient, but very wrong.

By Rich object I mean what you typically think of when you think of an object in an object oriented language. That is something that encapsulates some data and exposes some behavior related to this data. By the way, I don’t consider getters and setters as behavior! They also tend to break encapsulation. However, rich object classes is quite rare in most projects. Instead we have DTO:s as input and output to our services. We expose the database using a DAO that takes other DTO:s as input and output.

Post external references

  1. 1
    http://www.jayway.com/2013/02/05/learn-clojure-using-records-and-protocols/
Source