Java programmers: Code to the interface, even if the interface is a class

After spending a considerable amount of time trying to figure out how to refactor some particularly hairly (hairy + gnarly) data access code, I thought I'd share some insight into a popular misconception about what coding to the interface actually means.

Let's say we're writing a data access layer and we have something called the UserDAO. a simple implementation might be something like:

public class User {
    public int id;
    public String name;
}
public class UserDao {
    public boolean save(User toBeSaved) {
    
    }
   
}

I'm going to dodge the issue of the user class not having getters and setters and thus not following the javabean spec and talk about the UserDao Interface. Yes, you heard me, the UserDao class effectively is an interface in this example. Sit down and just think about that for a minute, once you've done that, move to the next paragraph.

A great (GREAT) many java developers might not get to this paragraph because they'll immediately start reacting to the idea that the UserDao isn't a java interface, it's a java class. This is an implementation detail and I'm here to tell you that you have already started down a path of increased complexity. Why? because most java developers will, instead of just using the above two classes, add another layer of indirection.

public interface UserDao {
    public boolean save(User toBeSaved);
   
}
and change the UserDao to implement this class:
public class UserDaoImpl implements UserDao {
    public boolean save(User toBeSaved) {
    
    }
   
}

Which in my experience is of no value in a large percentage of use cases (let's call it 90% of the time). This is a mistake! I know that "best practices" from just about every source you'll find say this is a good idea, but I'm here to tell you that you are taking on debt and you should CAREFULLY weigh the cumulative cost of that debt. The biggest problem is that in non-trivial systems, this has adds unnecessary complexity to the design and makes things more difficult to decypher. There are other problems, but my biggest problem with this assumption is that not just the added complexity, but the knee jerk non-thought that goes into adding the complexity for no good reason. Imagine if you have 90 DAOs and 90 interfaces and every change to the interface requires a change in two places.

But Mike! people will say, what if my current implementation uses hibernate and I want to switch to ibatis? Fine, I'd answer, change the implementation of the save and get methods in your simple UserDao to use the other library. An example would be to use composition in the Dao to hook to the particular implementation you need (example use spring autowired beans).

public class UserDao {
    @Autowired
    private HibernateSession hibernateSession:
    public boolean save(User toBeSaved) {
        return hibernateSession.save(toBeSaved);
    }
   
}
and when we decide to use ibatis
public class UserDao {
    @Autowired
    private IbatisSession ibatisSession;
    public boolean save(User toBeSaved) {
        return ibatisSession.save(toBeSaved);
    }
}

I realize it's not really that simple (I don't know ibatis well enough, sorry), but my point is that the class in this example is GOOD ENOUGH as the interface. My rejection of the "automatically use a java interface" is because there are good reasons to USE an interface, but this example is NOT one of them.

So when is a good time to use an java interface? The time to use interfaces is when you have multiple things that need a shared interface (set of operations), but they don't necessarily have the same concrete class backing them. This design detail is java's way of handling multiple inheritance. In the context of most J2EE apps, DAOs are not a good use of the concept, a better example would be something like getting audit information for multiple entities:

public interface Auditable {
    public String getAuditString();
}
public class User implements Auditable {
    public int id;
    public String name;
    public getAuditString() {
        return "User " + id + " with name " + name;
    }
}

public class Account implements Auditable {
    public int id;
    public String accountNumber;
    public getAuditString() {
        return "Account " + id + " with account number " + accountNumber;
    }
}



public class AuditDao {
    public void audit(Auditable toBeAudited) {
        System.out.println("performing operation on:  " + toBeAudited.getAuditString());
    }
}
public class UserDao {
    @Autowired
    private HibernateSession hibernateSession:
    @Autowired
    private AuditDao auditor;
    public boolean save(User toBeSaved) {
        auditDao.audit(toBeSaved);
        return hibernateSession.save(toBeSaved);
    }
}


public class AccountDao {
    @Autowired
    private HibernateSession hibernateSession:
    @Autowired
    private AuditDao auditor;
    public boolean save(Account toBeSaved) {
        auditDao.audit(toBeSaved);
        return hibernateSession.save(toBeSaved);
    }
}

I realize there are better ways to implement this particular variation, but my point is that the auditable interface requires to implementation by completely different classes to happen at runtime. Hiding things behind interfaces should only be done if necessary and can provide realistic known value in the present or real future. Switching implementations can often be done in other ways when you spend time to think about your design. Java interfaces are for enabling multiple concrete classes to have the same interface, NOT necessarily for simply defining the interface of a concrete class. With good design, a class will hide it's inner details and the interface is just extra complexity.

Comments

Moandji Ezana said…
I totally agree with you. Java Interfaces should generally express a capability, while the interface expresses the contract.

Popular posts from this blog

Push versus pull deployment models

the myth of asynchronous JDBC

Installing virtualbox guest additions on Centos 7 minimal image