DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Code to the Interface, Even if the Interface is a Class

Learn about coding to the interface: how to accomplish it, and what it means.

Michael Mainguy user avatar by
Michael Mainguy
·
Apr. 27, 12 · Tutorial
Like (1)
Save
Tweet
Share
18.62K Views

Join the DZone community and get the full member experience.

Join For Free

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.


Interface (computing)

Published at DZone with permission of Michael Mainguy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • PostgreSQL: Bulk Loading Data With Node.js and Sequelize
  • A Real-Time Supply Chain Control Tower Powered by Kafka
  • The Quest for REST
  • How Do the Docker Client and Docker Servers Work?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: