Friday, July 10, 2009

Decoupled design

Okay, so the question got asked on the Microsoft Forums about what was most appropriate, an interface, or an abstract class, so I thought that I'd bring that discussion over here for further discussion.

My response was to decouple, you would definitely use an Interface.

I was responded to with the question, but doesn't Inversion of Control containers now take care of abstraction, of de-coupling. I have to agree that it quite probably does.

That got me thinking, if you did use inversion of control, and always used abstract classes with no implementation, you would effectively have an interface. So why not use abstract classes everywhere? For me, it all comes down to clarity - the naming of an interface means that it is easy to understand it's function. An abstract class, on the other hand could be something ranging from effectively the interfacing class as described above, to something with lots of references to other abstract classes.

This is where I stand firm - my definition would be correct, if only to prevent that very thing from happening. When the implementation is part of a big team, those sorts of things can easily creep in, and before you know it, that beautiful, loosely coupled architecture is now reduced to a monolith.

So my advice here is always use interfaces, if you need an abstract class, create one, but only ever reference it using the interface. This bit here is another place where it is nice to have an interface - what if the base implementation changes? You can still create another base implementation class, and so long as the contract is unchanging, only that need change.

Coupling of code is all about the coupling of implementation from one to another - the very thing you have to avoid with SOA implementations and the like. The service call must be completely encapsulated.

No comments: