Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract class or interface. Which way is correct?

There are two way for choosing between abstract class or interface. Microsoft solution and Oracle solution:


Microsoft, design guideline:

Do use abstract (MustInherit in Visual Basic) classes instead of interfaces to decouple the contract from implementations.

http://msdn.microsoft.com/en-us/library/ms229013.aspx


Oracle, The Java Tutorials:

If an abstract class contains only abstract method declarations, it should be declared as an interface instead.

http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html


My question is which way is correct? Microsoft or Oracle solution? Note that I think choose between abstract class or interface should not depends on programming language (Java or C#).

like image 956
Amir Saniyan Avatar asked Feb 11 '12 20:02

Amir Saniyan


1 Answers

If I recall my blog reading correctly, the Microsoft advice to use abstract classes stems from the ability to reuse implementation with an abstract class, something you can't do with an interface.

Note also that the Microsoft page you linked to is specifically guidance for writing code libraries for sharing/reuse across multiple projects. The likelihood in this situation is that you'll be writing all the implementations of the interface yourself, probably within the same assembly. Good practices for working on a single product or system will vary somewhat.

One common approach that I've seen across a number of codebases in a number of languages is this:

  • Define an interface to specify the contract
  • Create an abstract class implementing the contract to provide any common implementation useful to all descendants
  • Implementations of the contract then have the option to start from the base class for convenience, or just to implement the interface if they want full control

A fourth step common in the .NET world is to provide convenience extension functions built on the interface.

like image 115
Bevan Avatar answered Oct 14 '22 10:10

Bevan