Java – Should Interfaces Be Created for Data Transfer Objects?

javaobject-oriented-design

Is it a good idea or a bad idea to create an interface for data transfer objects? Presuming that the object is usually mutable.

Though my example is in Java, it should be applicable to any other language that has similar concepts.

interface DataTransferObject  {
    String getName();
    void setName(String name);
}

class RealDataTransferObject  implements DataTransferObject {

    String name;
    String getName() {
        return name;
    } 
    void setName(String name) {
        this.name = name;
    }
}

Of course, this is a simplified example, in real life there may be more fields.

Best Answer

The general answer is no, because you should never add code without having a specific, concrete reason for it, and there is no general reason for such an interface.

That being said, sometimes there can be a good reason. But in all cases I have seen, these interfaces were partial, covering only one or a few properties shared by multiple classes I wanted to use polymporphically without giving them a common superclass. Typical candidates are an Id property to use in some sort of registry or a Name property to display to the user. But it can be useful in any case where you want some code to handle everything that has an X - just create an XSource interface that contains the getX (and, only if required, the setX) methods.

But a separate interface for every model class, containing all the properties? I can't imagine a good reason to do that. A bad reason would be a badly designed framework that requires it; Entity EJBs did just that, if I remember correctly. Thankfully they were so bad they never gained much traction and are deprecated since EJB 3.0

Sidenote: please avoid using the term "value object" to describe Java beans with only trivial getters and setters - it conflicts with the more common definition of value object as something with no identity that is usually immutable. A better term would be DTO or model class - though in the latter case note that anemic domain models are considered an antipattern.