Using Class Interfaces - Hannes's Mind Maze

Using Class Interfaces

The UML definition of an class interfaces is that's it used to describe the external visible behaviours of a class. Now my question, should a public class have an interface for it's exposed methods or not? I believe so but what's a good practice regarding the use of interfaces? Lets also say that everything is straight forward meaning no COM+, GAC, etc to simplify the problem.
Published Thursday, February 09, 2006 7:59 AM by hannes
Filed under:

Comments

# re: Using Class Interfaces

Thursday, February 09, 2006 2:01 PM by roaan
Hmm.
I think the "academic" answer is that the class should have an interface. There are tools that evaluate your class according to "best practices" which will give you beter marks if your classes implement interfaces.
That said however I disagree. You should only use interfaces if there is a likelihood that you want to support multiple (simultaneous) implementations for a single interface. If an interface will not have more than one implementation then the class should not have an interface.

I have the following issues with having an interface for every class
- You are in essence doubling the number of files you have, and thus double the
amount of maintenance you have to incur
- If you add a method to the class, you must add it to the interface as well. This
seems pretty pointless if it is going to be the only class that implements the
interface
- IDE support is not that great for interfaces. Remember, since you have the interface
you must use the interface.
I.e.
Foo x= new Foo(); // Should NEVER do this
IFoo x= new Foo(); // Since you have the interface, use it
Unfortunately this means you pass IFoo around. If, in your code, you then ask the
IDE to "go to definition" of a method on this interface it will go to the interface, as
it should. This is painfull however since there is only one class and you would have
liked to go to the single implementation of this method.

If you have or will have more than one implementation for an interface, then yes go for it, but otherwise you're just making your life more difficult for absolutely no benefit.

# re: Using Class Interfaces

Thursday, February 09, 2006 2:58 PM by hannes
Good point you make about over complicating your solution with adding really unnecessary interfaces. The reason I like interfaces is because of the design--by-contract principal. But I only use it on exposed class-methods. It pointless to use it for protected class or class members.

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above:
Powered by Community Server (Commercial Edition), by Telligent Systems