Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Code Style -- Interfaces vs. Abstract Classes

A new collaborator of mine who was reviewing some code I'd written told me that she wasn't used to seeing interfaces used directly in Java code, e.g.:

public interface GeneralFoo { ... }

public class SpecificFoo implements GeneralFoo { ... }

public class UsesFoo {
     GeneralFoo foo = new SpecificFoo();
}

instead, expecting to see

public interface GeneralFoo { ... }

public abstract class AbstractFoo implements GeneralFoo { ... }

public class SpecificFoo extends AbstractFoo { ... }

public class UsesFoo {
     AbstractFoo foo = new SpecificFoo();
}

I can see when this pattern makes sense, if all SpecificFoos share functionality through AbstractFoo, but if the various Foos have entirely different internal implementations (or we don't care how a specific Foo does Bar, as long as it does it), is there any harm in using an interface directly in code? I realize this is probably a tomato/tomato thing to some extent, but I'm curious if there's an advantage to the second style, or disadvantage to the first style, that I'm missing.

like image 262
Alterscape Avatar asked Feb 16 '11 15:02

Alterscape


2 Answers

If you have no need for an abstract class with certain details common to all implementations, then there's no real need for an abstract class. Complexity often gets added to applications because there is some perceived need to support future features that haven't yet been defined. Stick with what works, and refactor later.

like image 63
Mike Yockey Avatar answered Nov 04 '22 04:11

Mike Yockey


No, she's inexperienced, not right. Using interfaces is preferred, and writing redundant abstract super classes for the sake of redundancy is redundant.

UsesFoo should care about the behaviour specified by the interface, not about the super class of its dependencies.

like image 26
Christoffer Hammarström Avatar answered Nov 04 '22 05:11

Christoffer Hammarström