The Design of Software (CLOSED)

A public forum for discussing the design of software, from the user interface to the code architecture. Now closed.

The "Design of Software" discussion group has been merged with the main Joel on Software discussion group.

The archives will remain online indefinitely.

Why are we using interfaces?

A business framework that we use to build our apps contains several interface definitions.  It's C#.  The thing is, though, that these interfaces are all only implemented by ONE single class each.  It's usually a pair, like interface ISomething and class Something.

The interfaces define everything that is in the class, and nothing less.  There are also no static methods in the classes that implement the interfaces, because you can't put static methods in an interface...

That leads to really bizarre things, like instance methods that operate only on other instances of the same class, passed as arguments.  For instance: the method to sort a list of certain objects is an instance method... so you end up doing something like this:

if (ThingList.Length > 0)
  ThingList[0].Sort(ThingList, otherstuff);

... the if statement is absolutely necessary because you can't sort without an instance.

Can you think of a good reason that these interfaces should exist, instead of just using regular class hierarchies?
Going nuts
Friday, March 30, 2007
 
 
It allows for reimplementation of classes, as long as the class implements the required interfaces, it can be passed to preexisting methods which work on such interfaces as if it was a natural thing (code one thing months, years, later and it still works with old code).

It's premature flexibility programming, which probably will not pay off a whole lot, but it's there "just in case"...

Those tricks come from Java BTW. Java and C#/.NET can differ a lot though, because C#/.NET sometimes can be more pragmatic in some designs, albeit a lot of work has been invested in C#/.NET to make it work, and it still hasn't stopped, as new versions of them are still planned for the next months.
Lostacular
Friday, March 30, 2007
 
 
I've seen this too.

Usually it is meant for something like a "plug in" architecture.

It also seems to be more common among Java programmers using C#.
l belk
Friday, March 30, 2007
 
 
They shouldn't use interfaces that way. In my opinion it's anti-pattern. Especially if you use static typing language like C# or VB.NET, it's so dead easy to add interfaces if needed.
lubos
Friday, March 30, 2007
 
 
Are the interfaces public? Are the implemented classes internal? Is there a factory that creates the classes that implement the the interface?

The main use of an interface is to define a contract (or the API). This could be done at the design phase, the UI people can code against the interface (i.e. databind) and the business logic people can implement the corresponding class. Helps keep separation between presentation and logic and helps parallel development.

Personally, even though I tend to be the person who does the UI and the business logic, I like to do create the interface first making me think about how the UI and BL agree to work with each other.

Later on, if I am not happy with the BL implementation, I can reimplement and swap.
Damo
Friday, March 30, 2007
 
 
Lostacular and Damo have good thoughts here.

lubos on the other hand is wrong. Yes it's easy to add an interface - but by then you may have used features of the concrete class that you wouldn't want in the interface, and so you go and have to recode.
DJ Clayworth
Friday, March 30, 2007
 
 
It's really hard to tell anything from the original description because you don't really tell us what the interfaces are used for. But from the "Business Framework" description it sounds like interfaces are probably warranted. You wouldn't want to be using a framework that required you to use specific concrete classes because it wouldn't be extensible at all.
anon
Friday, March 30, 2007
 
 
In the Ada language, you used to have a "Specification" and a "Body" for each class.

So in your example, the Interface can serve as a "specification" for what must be implemented in a class which implements that interface.

And as long as the Interface doesn't change, the class has some flexibility as to how it implements it.

It turns out, for large systems implemented by multiple people, it can be very handy to have each person implement to the Interface, instead of requiring them to have intimate knowledge of the class that implements the interface.
AllanL5
Friday, March 30, 2007
 
 
It is annoying when people do that. They define interfaces with only 1 implementation which is generally just overengineering. It's usually better in my experience unless you know for sure up front that there will be multiple different implementations to just do it the easy way the first time with just the concrete class. Later if new requirements are uncovered then the original code can be easily refactored to implement some interface.

The big problem with defining the interface up front with just the single implementation is that the original programmer doesn't know what the future uses will be, so he has to guess at the interface signatures. Naturally he always gets it wrong, so when the thing does need to be extended in the future the original interface definition is no good anyway and just ends up getting chucked. I agree that an interface with just one concrete implementation is typically an anti pattern.
cbmc64 Send private email
Friday, March 30, 2007
 
 
Interfaces are a good idea in some circumstances - they allow mock implementations for testing, plug-in style for flexibility, decoupling of application layers, etc.

However, a slavish duplication of *every* class as an interface is a sign of a lack of understanding: "I've heard interfaces are good so I'm going to do it everywhere."
Mike S Send private email
Friday, March 30, 2007
 
 
C# has no multiple-inheritance.  If you need MI (to avoid re-implementation), then this is a workaround
Cade Roux Send private email
Friday, March 30, 2007
 
 
Everybody is talking about "flexibility" or adding something later...

It's been over 1.5 years and there has never been more than one specific class implementing any particular interface.

And as for "flexibility" or the future, why wouldn't inheritance work for that?  That's what OO is all about.
Going nuts
Friday, March 30, 2007
 
 
> And as for "flexibility" or the future, why wouldn't inheritance work for that?  That's what OO is all about.

The interface publishes the requirements which are simpler to be met than a full class which can behave in hidden ways. Also, the class probably has many more methods which you would need to re-implement. Lastly, some constructs like "private, protected, final" might make it hard to inherit from a certain class.

Interfaces being available and used also might make it unavoidable for you to implement some of them from time to time. So it's not a black and white choice. :(

Finally, when you have an interface, you might guess what it should do and implement it well without you having to have access to the source code of the class which implements the interface. It's one of the advantages when you work with code from other people which may come without source code, even so when they are so paranoid and make everything "private, protected, final" making subclassing some of their classes close to useless.

Let's remember that the "early binding" of the static typed languages like C# make you declare your types which forces you into a strict coding standard, of "all or nothing" when it's about types. The interfaces may work to give you a chance of adapting your code in this "all or nothing" static typing affair. :-) "Love me or leave me." That's what the faking multiple inheritance with interfaces means, probably.
Lostacular
Friday, March 30, 2007
 
 
BTW, isn't "mixing" ala Ruby's available in C# already? It could work for the "multiple inheritance" problem.
Lostacular
Friday, March 30, 2007
 
 
I generally think the make an interface then a default instance approach is very strong for higher level services. The problem is can be used inappropriately.

And I don't think the whole premature thing applies when you are making a system that will be used by millions for many decades. You have to be more sensitive to change than if you have local code you can do anything you want with.

By making an interface you become sure all the abstractions work together. When you make concrete instances it is way too easy to make shortcuts you wouldn't make if you were forced to think of things working together and the interface level.

But I don't get this:

if (ThingList.Length > 0)
  ThingList[0].Sort(ThingList, otherstuff);

Why does it have to check?
son of parnas
Friday, March 30, 2007
 
 
Is it possible that they're using unit testing and so need the interfaces to construct mock objects?
Bruce Rennie
Friday, March 30, 2007
 
 
"""But I don't get this:

if (ThingList.Length > 0)
  ThingList[0].Sort(ThingList, otherstuff);

Why does it have to check?"""

Because Sort is an *instance* method.  You need an instance of IThing to use this sorting method.  There is absolutely no reason for it to be an instance method, except that static methods can't be defined in an interface, and the concrete class (the only one that implements the interface) doesn't do ANYTHING that's not in the interface.

I'm quite aware of what Interfaces are intended to be used for.  I've used them *extensively* in my own coding.  The best case for an interface is when you want multiple dissimilar classes which can't feasible or shouldn't share a base class to have the same behaviors.

Interfaces should be adjectives, like Runnable, Comparable, Enumerable, etc., which give pretty clear ideas about what a class implementing that interface should do.  In our framework the interfaces are things like (anonymized) "IChair" with a "Chair" concrete class implementing it, and "ISofa" with a "Sofa" concrete class implementing it.  Chair and Sofa do not inherit from Furniture...

So far nobody has given me a good reason why this structure is good or necessary.
Going nuts
Friday, March 30, 2007
 
 
> So far nobody has given me a good reason why this structure is good or necessary.

You've already said interfaces should be adjectives so it's unlikely you'll find a good reason. Interfaces are services and anything can be a service. For example, let's say I want to replace the string class with my own because it has much better memory performance. Using string as interface means my string will work everywhere. There is no stringable. It's just an abstraction.
son of parnas
Friday, March 30, 2007
 
 
"""For example, let's say I want to replace the string class with my own because it has much better memory performance. Using string as interface means my string will work everywhere. There is no stringable. It's just an abstraction."""

But string is not, and would never be, an interface!  How can you use String as an interface?  Are you really talking about literal C#/Java interfaces?
Going nuts
Friday, March 30, 2007
 
 
> But string is not, and would never be, an interface!

Why not? Let's say I am using C++ on an embedded system. The typical string implementation is very poor. So I make a better one that uses our memory allocator etc. What is so special about the system supplied string that you wouldn't want to replace it?
son of parnas
Friday, March 30, 2007
 
 
What I'm saying is that String is just plain *not an interface* in .NET or Java.  It's just not.  Period.  String is a class, not an interface.

However, String implements several interfaces, so you could theoretically make something _like_ a String in Java that implements CharSequence, Comparable, and Serializable.  But string itself is NOT an interface.
Going nuts
Friday, March 30, 2007
 
 
> What I'm saying is that String is just plain *not
> an interface* in .NET or Java.  It's just not.  Period.

Ok, well you've convinced me. Stomping your feet and holding your breath is what did it.
son of parnas
Friday, March 30, 2007
 
 
> Ok, well you've convinced me. Stomping your feet and
> holding your breath is what did it.

Alright.  Let's just clear this up as simply as possible:

 http://msdn2.microsoft.com/en-us/library/system.string.aspx

 http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html

If you can show me that those sources indicate anything other than STRING IS A CLASS NOT AN INTERFACE then I'll concede that you're right.  Otherwise, I'm sorry you fail to grasp the basic concepts of the languages in question here.
Going nuts
Friday, March 30, 2007
 
 
> STRING IS A CLASS NOT AN INTERFACE

Of course it's not a class in the language. But it could be and for good reasons that aren't adjectival.
son of parnas
Friday, March 30, 2007
 
 
Hmm...  skimming through the discussion, I think some people are taking taking the words "class" and "interface" too literally, and some, too loosely.

As an analogy, if I'm teaching a class and I'm sketching out some code on the whiteboard and I say, "ok, we want to make this block of code a function since we use it from several different places..." does that mean the class has to implement it as a function as opposed to a subroutine, a procedure or a method?

I'm inclined to think that the original programmer thought of an interface as well... similar to a function prototype or someplace where he can define the expected inputs and outputs (design by contract). It just so happens, perhaps do to unfamiliarity with C#, that he used the literal interface to code his figurative interfaces.

As others have mentioned, this can be good and this can be bad. Based on what's been said so far, I think it's somewhat neutral. It makes the code awkward to read at times, but it doesn't sound like it drastically improves or hinders the execution of the program.
TheDavid
Friday, March 30, 2007
 
 
Any time you have a generalized concept that may have many valid implementations is a good time to consider an interface. For example, I routinely code database accesses points as an interface. As others have mentioned, it allows for mock objects during testing but it also allows me to plug and play with SQL server, Oracle et al *without* having to touch my business objects.

Equally, interfaces are good for things like lists. Whether it is a sorted vector, linked, double linked, b-plus, b-star, etc. it can be swapped out with impunity because the business classes are coded to the List interface.

Granted, it can be over/miss used, but the general idea is a good one.
Just A Guy
Friday, March 30, 2007
 
 
If the method signature is the same as the interface, and if you can access the method through its signature, than a separate interface is totally redundant.
Tony Marston Send private email
Saturday, March 31, 2007
 
 
People always talk about how you should have a well-defined interface so that you are free to change the implementation willy-nilly.  That seems quite backwards to me.  In my experience the implementation changes a whole lot more than the implementation.  Now of course it is not possible to change the interface without changing the implementation at least a little bit, but I'm sure you can figure out what I am getting at.  I guess it depends on the situation and what type of program you are making.  I get the essence of what I am doing in my head and it translates pretty easily into an algorithm.  Now I need to make it connect to some other part of my program, but how?  How does this third part come into play?
Tom C
Saturday, March 31, 2007
 
 
"How does this third part come into play?"

Well, that is the gist of the issue.

When you code an implementation first and an interface later (or not at all), you're generally trying to solve a very specific problem first, and some time later trying to recycle your existing solution to solve similar problems. This is very common and practical in bottom-up development methodologies.

A top-down methodology instead tries to identify the types of problems you're likely to encounter first, and determine what they have in common. The implied structure becomes the interfaces (speaking figuratively, not literally) and the solution is written with these "third parts" in mind.

Admittingly, it's easier to do it the bottom-up approach, but you need to be careful when rewriting your specific solutions to become generic solutions; there's a tendency to get carried away and make it so complex that it becomes difficult to debug and troubleshoot. The top-down requires a lot more work early in the process, but the result typically tends to be very clean, well organized code that hardly needs any future modifications.

Unfortunately, in reality, the ideal approach is somewhere between these two extremes, and its ultimately the experience of the programmer and the task being accomplished that determines to what degree interfaces are used.
TheDavid
Monday, April 02, 2007
 
 
if (ThingList.Length > 0)
  ThingList[0].Sort(ThingList, otherstuff);

Why do instances of class Thing (or class Thing itself) know anything about sorting? Why isn't the sorting behavior defined on the ThingList class? Or, if ThingList is a standard .NET List, then one of the built-in Sorting methods like Array.Sort or whatever.  Seems to me that the root of all this trouble starts here.

As far as the "interfaces are adjectives" business, this is only true of so-called "marker interfaces."  Generally, these kinds of interfaces are used to provide compatibility with some service.  For example, the Sorting framework needs to be able to compare two items, so if you want your stuff to work with the Sorting Framework, you have to implement the necessary Comparable interfaces.

Interaces have a much more important function than simply specifying plug points: Dependency Inversion.  This technique, properly used, greatly reduces coupling in a system.  Robert Martin has a good write up of the principle at: http://www.objectmentor.com/resources/articles/dip.pdf

Now obviously, if you know for sure you won't ever need to vary an implementation of some abstract concept, and you have full control of all the source code, this sort of thing might be overkill. But, if you need to do comprehensive testing, or you need to deploy code into a lot of potential scenarios, this concept can be a real life saver.

I wish Microsoft had followed this principle when constructing the various GUI libraries .NET comes equipped with.  There have been many times when I'd have liked to implement the Control interface while inheriting from some other base class.  Can't do it, though, because the WinForms/WebForms designers didn't make things abstract enough.
Franklin Send private email
Monday, April 02, 2007
 
 
> "interfaces are adjectives"

More specifically, "an object to which a verb can be applied", which makes sense if classes are nouns and methods are verbs.

The examples above ("ISortable") are passive: the nouns are sorted.

You can also have interfaces for active verbs, e.g. Dog might implement the IHunt interface, not IHuntable.
Christopher Wells Send private email
Tuesday, April 03, 2007
 
 
One reason to have an interface, even if there is only one instantiating class, is to deal with circular references.

If project A defines an interface which is then implemented in project B, then project B can have a reference to project A while things in project A can use the interface to get to (the one class in) project B.
Don Edwards Send private email
Tuesday, April 03, 2007
 
 
"If the method signature is the same as the interface, and if you can access the method through its signature, than a separate interface is totally redundant."

It allows part of the spec to be compiled.  (Let the computer catch the errors.)  It allows for more than one implementation while keeping them consistent.

Sincerely,

Gene Wirchenko
Gene Wirchenko Send private email
Wednesday, April 04, 2007
 
 
< It allows part of the spec to be compiled. >

This is irrelevant in languages such as PHP which are not compiled. I can see no advantage in having a separate interface definiton as well as a method signature. I can access a method directly via its signature, therefore a separate interface is totally redundant.
Tony Marston Send private email
Wednesday, April 04, 2007
 
 
Going nuts, I feel your pain.  I have been in that situation as a consultant.  I came into a large C# application that was full of interfaces for things that would never have more than one implementation.

It is a misunderstanding.  People misunderstand what interfaces are used for and they start using them willy nilly. The truth is that most SUCCESSFUL software applications are being refactored all the time and major release once every couple years.  Of course a lot of applications don't last more than couple years, so it is an obvious argument that planning for the future in software is about balance, and engineers too often over do it.

As for interfaces, I use them when needed.  The simple rule is analyze your nouns, Noun\Proper Nouns.  I have an interface called IPrinter and multiple printer classes (HP, Dell, Epson etc..).  It is that simple, keep it that way.
Dan Murphy Send private email
Wednesday, April 04, 2007
 
 
A separate interface can also be regarded as a contract. The person who wrote the interface says "the class WILL have THESE methods, with THESE parameters and return types", and has to go through an extra process (checking out, modifying, and checking in) the interface. Depending on what you are using for source control, the interface may have different security so that the programmer writing a class which implements that interface has to jump through extra hoops in order to alter that contract.

Thus, the people who write the code which will call methods of said class, can trust the interface more.

Is that benefit worth the extra work? I think I would usually say no - but I can see where sometimes it could be.
Don Edwards Send private email
Wednesday, April 04, 2007
 
 
Well, I see an idiot programmer.

if (ThingList.Length > 0)
  ThingList[0].Sort(ThingList, otherstuff);

Surely "ThingList" knows how to do "sorting" and "Thing" provides the "am I greater or less than or equal to another Thing" test.

The above code should look like this:

ThingList.Sort();

(There are other styles, but making Thing know about the type of list that it's in is a really amazingly bad idea - even if Thing is just a concrete class with no special "interface" or whatever.)

Also, the Sort() method really ought to be able to cope with an empty list - after all, a sorted empty list is easy to calculate, but if Sort() crashes when called with an empty list then there will be a deevloper who forgets one check and causes a crash. There's no need for that risk, because if the test is being done anyway, Sort() can do it, and thus avoid ever crashing.

In an extreme situation, Sort() may take a function object that compares two Thing instances, leading to code like this:

ThingList.Sort( new MySpecialComparison() );

(Or something. If you don't want Thing to know about ordering, then you can make the comparison function mandatory, and you can specify it in the list's constructor so you don't have to create it each time you do sorting. You have plenty of options that aren't as brain-dead as making Thing do its own sorting and dependant on the type of the list.)

Shocking deficiencies in ThingList and a design that makes baby Jesus cry are the source of the problem here - not the use of "interfaces".

Wednesday, April 04, 2007
 
 
< A separate interface can also be regarded as a contract. The person who wrote the interface says "the class WILL have THESE methods, with THESE parameters and return types" >

I still do not see the point. You have Method A which has a list of arguments and a return type. This is known as a method "signature" in a lot of languages. You then have Interface A which does nothing but describe the signature for Method A.

My point is that if I can access a method by using its signature, why the heck do I need to go though a separate interface which does nothing but refer me to the signature? I do not NEED a separate interface to access a method, therefore the separate interface is redundant.
Tony Marston Send private email
Tuesday, April 10, 2007
 
 
Creating an interface for each class lets you follow the basic ADT principle of "interface is independent from implementation".

Think back to C, where you include .h files and link in the corresponding .o files compiled from .c files. Throughout your own code you're only using prototypes declared in .h files, which really don't do anything on their own except keep the compiler happy. This lets you redo entire .c files and leaves the dependent code unaffected, as long as the corresponding .h stays the same.

Same thing can be done for objects, which is what interfaces, or even abstract classes, let you do. When your entire codebase only depends on interfaces, you can change ANY implementation you want, and the only things that change are your "new" operations and factories (IJunk = new Junk() vs. IJunk = new JunkMach2() - everything else in your code should only care about objects of type IJunk).

If you could live with this kind of thing in C, I'm sure it's more than possible in Java or C#.
Marc Miz Send private email
Tuesday, April 10, 2007
 
 
That was a terrible analogy.  OOP interfaces are really nothing like .h files which are merely an implementation hack required by the fact that C/C++ are macro assemblers in evening gown.  Those .h prototypes are declarations of existing types and functions.  They don't introduce new semantics, they are just another facet of one and the same chunk of code.  By contrast, OOP interface classes do introduce new semantics.  They are new and different chunks of code, in addition to the chunk of code that contains the implementation class.
Chris Nahr Send private email
Wednesday, April 11, 2007
 
 
My point was that there's motivation behind separating interface from implementation - it doesn't matter what language you're using.
Marc Miz Send private email
Wednesday, April 11, 2007
 
 
Yes, but you're not doing that when you're creating .h files in C.  That's merely a sad technical necessity due to the fact that C/C++ doesn't have a proper module system.  A .h prototype is the equivalent of the first line of a Java method -- it's not the equivalent of a separate interface class.

The exact analogy for interfaces would be to create abstract classes for all of your original C++ classes, have the latter implement those abstract classes, and only ever access objects through these abstract classes.  Are you doing that, or would you advocate doing that?
Chris Nahr Send private email
Thursday, April 12, 2007
 
 
< My point was that there's motivation behind separating interface from implementation - it doesn't matter what language you're using. >

It depends how you look at it. There is the "interface" or API, sometimes known as the method/function signature. This identifies the function name, its arguments, and what it returns. This is what appears in the documentation, so programmers know what each API does and how to call it.

The "implementation" is nothing more than the code behind the signature. It is possible to change the implementation without changing the signature. This is a "feature" of ALL programming languages.

In some languages the method signature *IS* the interface, but in other languages the signature and the interface are separate, and you must define both before the software will work. Some programmers will insist on using separate interfaces even if the language does not require it, simply because they have always done it that way.

My point is quite simple - if the language does not require a separate thing called an "interface" because any method can be accessed through its signature, then a separate interface serves no useful purpose and is therefore redundant.
Tony Marston Send private email
Thursday, April 12, 2007
 
 
Getting back to the original question: "Why are we using interfaces?".  The answer is because right now we are working our way through the "dependency injection" fad.  A group of people are inflating this simple, ancient concept (the idea of taking an interface as opposed to instantiating an object) in an attempt to create an entire development methodology.  See Spring, Java.

Once the revenues from these snake-oil sales die down you'll start to see interfaces used in a more appropriate and traditional manner again.
Matt Send private email
Friday, April 13, 2007
 
 
<i>< A separate interface can also be regarded as a contract. The person who wrote the interface says "the class WILL have THESE methods, with THESE parameters and return types" >

I still do not see the point. You have Method A which has a list of arguments and a return type. This is known as a method "signature" in a lot of languages. You then have Interface A which does nothing but describe the signature for Method A.

My point is that if I can access a method by using its signature, why the heck do I need to go though a separate interface which does nothing but refer me to the signature?</i>

The contract specifies that the class WILL have these methods - but "will" is both imperative and future. The class hasn't been written yet. Does your code (which needs an instance of that class) at least compile? Can you throw together a stub class so you can unit-test your code, and know that the results will be applicable to the real class?

With the interface - yes.

Without it - no.
Don Edwards Send private email
Friday, April 13, 2007
 
 
< The contract specifies that the class WILL have these methods - but "will" is both imperative and future. The class hasn't been written yet. >

I do not write interfaces which are separate from the method signature. I write the code (the implementation) and the signature (API or interface) at the same time.

< Does your code (which needs an instance of that class) at least compile? >

I do not work with a compiled language, and I do not work with a language that requires interfaces which are separate from the method signature. I can write a bunch of code, enclose it in a method with a unique signature and access it through that signatue. Because separate interfaces are not "required" I do not use them.
Tony Marston Send private email
Saturday, April 14, 2007
 
 

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics
 
Powered by FogBugz