Would one Method per Interface be a Reasonable Design Choice? - c#

Does it make sense to have interfaces like IAddable, IRemovable, IIndexable, to support each operation or would this sort of approach ultimately lead to unmanageable code?

Imagine you want to implement a sort-of NumberBucket that is like a collection for numbers.
You could create a somewhat fat interface like this one:
public interface INumberBucket
{
void Add(int number);
void Remove(int number);
}
And you could implement it with no problems:
public class NumberBucket : INumberBucket
{
public void Add(int number)
{
Console.WriteLine($"Adding {number}");
}
public void Remove(int number)
{
Console.WriteLine($"Removing {number}");
}
}
But then later on you decide you need to implement a ReadonlyNumberBucket where numbers cannot be removed:
public class ReadonlyNumberBucket : INumberBucket
{
public void Add(int number)
{
Console.WriteLine($"Adding {number}");
}
public void Remove(int number)
{
throw new NotImplementedException();
}
}
Well, now there is no logical implementation for Remove so you have have to make it a no-op or make it throw. This violates the Liskov Substitution Principle.
Had you decalred two focused interfaces: IAddable and IRemovable you could have just not implemented IRemovable. This is the basis for the Interface Segregation Principle.
So, to answer your question: yes - it is reasonable but it may be a while before you see a return on your investment however. And just like #PhilipStuyck wrote in the comments:
[..] The question is if this example is applicable in your situation. The very first interface in this answer might be good enough for you and splitting it might be overdesign. Overdesign is also a code smell. You gotta know when to apply which pattern. Based on the short explanation in the question I cannot tell.

It depends on level of a "control" you have in your application design. If you have items that may be "Addable" but not "Devidable", what you say makes pretty much sense.
But if in your app domain, all items usually support basic operations you describe, don't see a reason to move them into the separate interfaces.

I saw some comments about the fact that the Liskov substitution might be broken if you let all methods inside an interface. To be honest, even Microsoft violates the Liskov substitution principle sometimes. For example, they made the Array to implement IList even that some methods on this interface are not supported by the Array type (for example if you cast an array to IList, the "Add" method throws an exception of type NotSupportedException).
The MOST important thing is this: Do you see any logical relation between your methods ? at least they must belong to a certain category or something. if so, group them together into an interface. In your case, IAddable and IRemovable seem for me that are somehow corelated because they both represent something simmilar: an object can be MOVED (added or removed) from some basket. The IIndexable for me seems like a "bonus" like something that you can add but is not mandatory. So if I would be your architect I would put IIndexable methods in a separate interface.
Anyway if in a far future an object would be "addable" but will not support "remove" then you could easelly solve this problem by splitting your interface in two and make our old interface to inherit them both : IAddable, IRemovable. I tend to "segregate" interfaces at the right moment, i don't like splitting my interfaces from the very start of my architecture.
So, remember:
In the beginning, segregate only what's obvious then segregate when the situation requires a segregation or even you can choose for the sake of readability / framework understanding to NOT segregate (as microsoft did because for them, an array is a kind of List and this should remain like so).
Patterns and principles like SOLID are just a very powerfull guideance but rules are made sometimes to be broken. Keep this in mind.

Related

How strict should be interfaces (a good interface design)

I am not sure if this even fits on StackOverflow, or maybe rather on Programmers#StackExchange. If this should rather go there, let me know in a comment below and I will move it :)
Anyway - back to the point. I have never done much programming using interfaces and Constructor/Property dependency injection etc. So I do know too much about it. I have been reading some articles though, mainly this, and found this an interesting technique to make my software more flexible and testable.
So off I go and start refactoring an existing application (C#), and I come across a dilemma, which one of the 2 below choices is better:
Choice 1 - minimum dependency requirements in a function. Leave some injection for constructor (implementation decision when using the interface)
public interface IDriver
{
bool Start();
bool Stop();
bool Read(uint[] signal1, uint[] signal2);
}
public class MyDriver : IDriver
{
public MyDriver(ISettings settings)
{
//remember ISettings in a local var
}
//interface implementation
}
Choice 2 - all required dependencies in a function call.
public interface IDriver
{
bool Start();
bool Stop();
bool Read(ISettings settings, uint[] signal1, uint[] signal2);
}
public class MyDriver : IDriver
{
//implementation of the interface
}
Now the choice 2 might be wrong , right? because some implementations might actually not need the ISettings to work. The fact that my implementation of IDriver uses ISettings at the moment does not mean that it will in a year or so, so the logical approach would be to use method 1.
So my question would be: how strict should I make my interfaces, and how to not get mixed up between an interface and an implementation? I do not want the implementation to influence how I design my interfaces.
Also, does anyone know of good articles about the topic?
Thanks.
Interfaces should be defined and owned by the clients that consume the interfaces. As Agile Principles, Patterns, and Practices explain, "clients […] own the abstract interfaces" (chapter 11). Thus, if the client only requires this to work (your option 1):
public interface IDriver
{
bool Start();
bool Stop();
bool Read(uint[] signal1, uint[] signal2);
}
then that should be the interface. Everything else is an implementation detail, and should go in the constructor.
More than strictness, it is a question of contractual necessity.
Is ISettings contractually needed for your Read functionality? Probably NO.
think of it as no different than the signal1 and signal2 variables. The reason you have signal1 and signal2 in the Read method definition of the Interface is because they are part of the contract and mandatory for every implementation of the interface to use as inputs.
But ISettings sounds like something that a particular implementation would need whereas some others won't. (like Loggers, CacheManagers, Repositories etc.)
So you're right and more often than not, Approach #1 will be preferable. It keeps the interfaces clean & confined to the exact contractual input/outputs.
Thorough study of system requirment solves many problems and helps you design the application with more confidence. So first, think more and more until you reach a point when you can argue and reason about what you're going to do.
Secondly IMHO, the both approaches are OK. The first one as 'raja' pointed out is clean and succient and I don't repeat what he says again. But consider this situation: if later the IDriver implementors somehow need to be configured. Then passing some sort of setting to them solves many problems. Even if at the current moment you think it is unneccessary (and I admit it is what YAGNI principle says), you can provide empty setting (NullObject pattern):
public Driver : IDriver
{
public bool Read(ISettings settings, uint[] signal1, uint[] signal2)
{
if (settings.PreventSomeThing)
{
.....
}
}
}
public NullSetting : ISetting
{
public bool PreventSomething = false;
....
}

interfacing: simplified

i've been doing some research on interfaces and a simple layman's explanation for what it truly is. when searching through seas of books For some reason people love using overly complex explanations and jargon to explain truly simple concepts (guess it makes them feel big) and i have a gut feeling it's the same in this case.
so from what i could grasp, it seems like interfaces are nothing more than a way to reserve method names, their return type if any, and the type and amount of arguments they accept. so when a class implements an interface (or interfaces) it is forced to define the body of each method from the interface(s). Am i on the nose with this one or do i need to keep digging?
p.s. i know javascript doesn't have support for interfaces, but i still need to understand the concept because there are quite a few places where it's shown how to emulate to an extent.
For some reason people love using overly complex explanations and jargon to explain truly simple concepts (guess it makes them feel big)
Consider eschewing the editorial comments that impute bad motives to people who are trying to help you. That's a really bad way to try to get people to help you.
It seems like interfaces are nothing more than a way to reserve method names, their return type if any, and the type and number of arguments they require. So when a class implements an interface (or interfaces) it is forced to define the body of each method from the interface(s). Am i on the nose with this one or do i need to keep digging?
You are on the right track but you err in the details. In C#, for example, an implementing class is not required to provide a body. The method which corresponds to the interface method could, for example, be an abstract method in an abstract class, which would then not have a body. And in C# an interface can require members other than methods; properties, events and indexers, for example.
A more concise and typical way to express the idea that interfaces impose a requirement that a type supply members that match certain signatures is to say that the interface represents a contract that must be fulfilled by its implementer. But that might be too complex and jargonish for your gut to stomach.
I explain the concept to lay people using an analogy that most people understand - plastic molding.
The interface defines the shape of an object in the exact same way a mold will provide the shape of the finished product.
You could inject a mold with White plastic, blue plastic, something exotic like an Epoxy or clay.
What matters is, no matter what they are actually made of, they all have the same exact consistent shape to the purchaser of the product.
For code, this means no matter what code is used to implement the interface, they all follow the same consistent contract/shape to the end user.
I hope that might help a little.
Edit -
To extend the analogy to Abstract classes, imagine the next step in the molding process. You run a White, blue, and red plastic production run, but then each item needs to be painted at a separate factory, we just ship them out.
The item is not finished, but it does have its shape defined. Someone later will come and fill out the details that our factory left blank.
These items cannot be sold until they get that last painting step.
In code, the abstract implementation of the interface provides some (or none) of the implementation, but leaves another descendant class to complete the contract, and in the same way no one can create an instance of the class until the contract has been completed.
In the same way though, you can still refer to an abstract class in code, just like you can refer to the unpainted mold item as a "White molded thing" wither or not it is painted!
Edit 2
Here's a short example
void Main()
{
//IMold mold = new IMold(); // error - can't create instance of an interface
//Fruit fruit = new Fruit(); // error - can't create instance of an abstract class
Apple apple1 = new Apple(); // good
Orange orange1 = new Orange(); // good
Fruit apple2 = (Fruit)apple1; // good - Apples are fruit
Fruit orange2 = (Fruit)orange1; // good - oranges are fruit
IFruitMold apple3 = (IFruitMold)apple2; // good - Apples fit the Mold
IFruitMold orange3 = (IFruitMold)orange2; // good - Oranges also fit the mold
//now I can do this:
//Notice that `fruits` is of type IList<T> but the new is List<T>
//This is the exact concept we are talking about
//IList<T> is some kind of set of items that can be added or subtracted from
//but we don't have to care about the implementation details of *HOW* this is done
IList<IFruitMold> fruits = new List<IFruitMold>();
fruits.add(apple3);
fruits.add(orange3);
foreach( var fruit in fruits )
{
fruit.PlasticColor.Dump(); // ok I can read
fruit.PlasticColor = ""; // error - no Set defined in the interface
// depending on the **implementation details** of what type of fruit this is true or false
// we don't care in the slightest, we just care that we have some IFruitMold instances
fruit.RequiresPainting.Dump();
}
}
interface IFruitMold
{
string PlasticColor { get; }
bool RequiresPainting { get; }
}
abstract class Fruit : IFruitMold
{
private string m_PlasticColor = string.Empty;
public string PlasticColor { get; private set; }
public abstract bool RequiresPainting { get; }
}
//notice that we only define the abstract portion of the base class
//it defined PlasticColor for us already!
//the keyword `override` is required - it is to make it clear that
//this member is overriding a member from it's parent.
class Apple : Fruit
{
public override bool RequiresPainting { get { return true; } }
}
class Orange : Fruit
{
public override bool RequiresPainting { get { return false; } }
}
Yes, in a nutshell interfaces are there to declare and promise everyone else that a class will have certain methods.
This is good when you create generalized methods and function, where you want a more abstract design. All you want to know is that your function can receive an object that had methods A B and C.
Interface is just a simple empty class, that show the contract on how you real class should look. I think you have the concept ok.
They don't reserve anything (I don't understand what you mean by that), is just a way so when you build your class around the interface, you have a prior knowledge of how will your class look like. And also you can know before which methods will it have.
when a class implements an interface (or interfaces) it is forced to define the body of each method from the interface(s).
Yes. Interfaces are contracts. They let others know that your class implements certain functionality.
I would say its more than reserving the method name it is a way of making a contract that the method will exist and the caller will not need to know what it does but it will still be available to be called
A good example would be a pen and pencil both can implement an Iwriter interface with a write method but whoever calls the write method doesn't need to know that one uses ink and one uses lead the caller will just know that it is going to write words on the paper.
Interfaces provide a uniform way of interaction with a set of objects.
No matter what the object is, if it implements the interface we know that it will respond to a method defined in the interface. In this way, we can create objects that represent different things in a project and still interact with them in the same way. The actual implementation of the methods defined in the interface can be completely different, but they will take the same inputs and provide the same type of output.
Basically an interface is a contract which can define properties (getters and setters) or methods (with whatever parameters you require). If an object 'implements' the interface it needs to define a concrete implementation for ALL the properties and methods defined in the interface.
For unit testing or Inversion of Control containers interfaces really come into there own as you can call methods/properties on the interface without knowing anything about the object which actually implements it.
Interface is used to provide common functionality among a set of completely unrelated objects.
Lets say we have a bunch of animal objects and we need to separate pets from that bunch. The task of separation becomes really simple if we enforce a contract such that all the animals which are pets needs to implement IPet interface.

What is the name of this bad practice / anti-pattern?

I'm trying to explain to my team why this is bad practice, and am looking for an anti-pattern reference to help in my explanation. This is a very large enterprise app, so here's a simple example to illustrate what was implemented:
public void ControlStuff()
{
var listOfThings = LoadThings();
var listOfThingsThatSupportX = new string[] {"ThingA","ThingB", "ThingC"};
foreach (var thing in listOfThings)
{
if(listOfThingsThatSupportX.Contains(thing.Name))
{
DoSomething();
}
}
}
I'm suggesting that we add a property to the 'Things' base class to tell us if it supports X, since the Thing subclass will need to implement the functionality in question. Something like this:
public void ControlStuff()
{
var listOfThings = LoadThings();
foreach (var thing in listOfThings)
{
if (thing.SupportsX)
{
DoSomething();
}
}
}
class ThingBase
{
public virtual bool SupportsX { get { return false; } }
}
class ThingA : ThingBase
{
public override bool SupportsX { get { return true; } }
}
class ThingB : ThingBase
{
}
So, it's pretty obvious why the first approach is bad practice, but what's this called? Also, is there a pattern better suited to this problem than the one I'm suggesting?
Normally a better approach (IMHO) would be to use interfaces instead of inheritance
then it is just a matter of checking whether the object has implemented the interface or not.
I think the anti-pattern name is hard-coding :)
Whether there should be a ThingBase.supportsX depends at least somewhat on what X is. In rare cases that knowledge might be in ControlStuff() only.
More usually though, X might be one of set of things in which case ThingBase might need to expose its capabilities using ThingBase.supports(ThingBaseProperty) or some such.
IMO the fundamental design principle at play here is encapsulation. In your proposed solution you have encapsulated the logic inside of the Thing class, where as in the original code the logic leaks out into the callers.
It also violates the Open-Closed principle, since if you want to add new subclasses that support X you now need to go and modify anywhere that contains that hard-coded list. With your solution you just add the new class, override the method and you're done.
Don't know about a name (doubt such exists) but think of each "Thing" as a car - some cars have Cruise Control system and others do not have.
Now you have fleet of cars you manage and want to know which have cruise control.
Using the first approach is like finding list of all car models which have cruise control, then go car by car and search for each in that list - if there it means the car has cruise control, otherwise it doesn't have. Cumbersome, right?
Using the second approach means that each car that has cruise control come with a sticker saying "I has cruise control" and you just have to look for that sticker, without relying on external source to bring you information.
Not very technical explanation, but simple and to the point.
There is a perfectly reasonable situation where this coding practice makes sense. It might not be an issue of which things actually support X (where of course an interface on each thing would be better), but rather which things that support X are ones that you want to enable. The label for what you see is then simply configuration, presently hard-coded, and the improvement on this is to move it eventually to a configuration file or otherwise. Before you persuade your team to change it I would check this is not the intention of the code you have paraphrased.
The Writing Too Much Code Anti-Pattern. It makes it harder to read and understand.
As has been pointed out already it would be better to use an interface.
Basically the programmers are not taking advantage of Object-Oriented Principles and instead doing things using procedural code. Every time we reach for the 'if' statement we should ask ourselves if we shouldn't be using an OO concept instead of writing more procedural code.
It is just a bad code, it does not have a name for it (it doesn't even have an OO design). But the argument could be that the first code does not fallow Open Close Principle. What happens when list of supported things change? You have to rewrite the method you're using.
But the same thing happens when you use the second code snippet. Lets say the supporting rule changes, you'd have to go to the each of the methods and rewrite them. I'd suggest you to have an abstract Support Class and pass different support rules when they change.
I don't think it has a name but maybe check the master list at http://en.wikipedia.org/wiki/Anti-pattern knows? http://en.wikipedia.org/wiki/Hard_code probably looks the closer.
I think that your example probably doesn't have a name - whereas your proposed solution does it is called Composite.
http://www.dofactory.com/Patterns/PatternComposite.aspx
Since you don't show what the code really is for it's hard to give you a robust sulotion. Here is one that doesn't use any if clauses at all.
// invoked to map different kinds of items to different features
public void BootStrap
{
featureService.Register(typeof(MyItem), new CustomFeature());
}
// your code without any ifs.
public void ControlStuff()
{
var listOfThings = LoadThings();
foreach (var thing in listOfThings)
{
thing.InvokeFeatures();
}
}
// your object
interface IItem
{
public ICollection<IFeature> Features {get;set;}
public void InvokeFeatues()
{
foreach (var feature in Features)
feature.Invoke(this);
}
}
// a feature that can be invoked on an item
interface IFeature
{
void Invoke(IItem container);
}
// the "glue"
public class FeatureService
{
void Register(Type itemType, IFeature feature)
{
_features.Add(itemType, feature);
}
void ApplyFeatures<T>(T item) where T : IItem
{
item.Features = _features.FindFor(typof(T));
}
}
I would call it a Failure to Encapsulate. It's a made up term, but it is real and seen quite often
A lot of people forget that encasulation is not just the hiding of data withing an object, it is also the hiding of behavior within that object, or more specifically, the hiding of how the behavior of an object is implemented.
By having an external DoSomething(), which is required for the correct program operation, you create a lot of issues. You cannot reasonably use inheritence in your list of things. If you change the signature of the "thing", in this case the string, the behavior doesn't follow. You need to modify this external class to add it's behaviour (invoking DoSomething() back to the derived thing.
I would offer the "improved" solution, which is to have a list of Thing objects, with a method that implements DoSomething(), which acts as a NOOP for the things that do nothing. This localizes the behavior of the thing within itself, and the maintenance of a special matching list becomes unnecessary.
If it were one string, I might call it a "magic string". In this case, I would consider "magic string array".
I don't know if there is a 'pattern' for writing code that is not maintainable or reusable. Why can't you just give them the reason?
In order to me the best is to explain that in term of computational complexity. Draw two chart showing the number of operation required in term of count(listOfThingsThatSupportX ) and count(listOfThings ) and compare with the solution you propose.
Instead of using interfaces, you could use attributes. They would probably describe that the object should be 'tagged' as this sort of object, even if tagging it as such doesn't introduce any additional functionality. I.e. an object being described as 'Thing A' doesn't mean that all 'Thing A's have a specific interface, it's just important that they are a 'Thing A'. That seems like the job of attributes more than interfaces.

C# has abstract classes and interfaces, should it also have "mixins"?

Every so often, I run into a case where I want a collection of classes all to possess similar logic. For example, maybe I want both a Bird and an Airplane to be able to Fly(). If you're thinking "strategy pattern", I would agree, but even with strategy, it's sometimes impossible to avoid duplicating code.
For example, let's say the following apply (and this is very similar to a real situation I recently encountered):
Both Bird and Airplane need to hold an instance of an object that implements IFlyBehavior.
Both Bird and Airplane need to ask the IFlyBehavior instance to Fly() when OnReadyToFly() is called.
Both Bird and Airplane need to ask the IFlyBehavior instance to Land() when OnReadyToLand() is called.
OnReadyToFly() and OnReadyToLand() are private.
Bird inherits Animal and Airplane inherits PeopleMover.
Now, let's say we later add Moth, HotAirBalloon, and 16 other objects, and let's say they all follow the same pattern.
We're now going to need 20 copies of the following code:
private IFlyBehavior _flyBehavior;
private void OnReadyToFly()
{
_flyBehavior.Fly();
}
private void OnReadyToLand()
{
_flyBehavior.Land();
}
Two things I don't like about this:
It's not very DRY (the same nine lines of code are repeated over and over again). If we discovered a bug or added a BankRight() to IFlyBehavior, we would need to propogate the changes to all 20 classes.
There's not any way to enforce that all 20 classes implement this repetitive internal logic consistently. We can't use an interface because interfaces only permit public members. We can't use an abstract base class because the objects already inherit base classes, and C# doesn't allow multiple inheritance (and even if the classes didn't already inherit classes, we might later wish to add a new behavior that implements, say, ICrashable, so an abstract base class is not always going to be a viable solution).
What if...?
What if C# had a new construct, say pattern or template or [fill in your idea here], that worked like an interface, but allowed you to put private or protected access modifiers on the members? You would still need to provide an implementation for each class, but if your class implemented the PFlyable pattern, you would at least have a way to enforce that every class had the necessary boilerplate code to call Fly() and Land(). And, with a modern IDE like Visual Studio, you'd be able to automatically generate the code using the "Implement Pattern" command.
Personally, I think it would make more sense to just expand the meaning of interface to cover any contract, whether internal (private/protected) or external (public), but I suggested adding a whole new construct first because people seem to be very adamant about the meaning of the word "interface", and I didn't want semantics to become the focus of people's answers.
Questions:
Regardless of what you call it, I'd like to know whether the feature I'm suggesting here makes sense. Do we need some way to handle cases where we can't abstract away as much code as we'd like, due to the need for restrictive access modifiers or for reasons outside of the programmer's control?
Update
From AakashM's comment, I believe there is already a name for the feature I'm requesting: a Mixin. So, I guess my question can be shortened to: "Should C# allow Mixins?"
The problem you describe could be solved using the Visitor pattern (everything can be solved using the Visitor pattern, so beware! )
The visitor pattern lets you move the implementation logic towards a new class. That way you do not need a base class, and a visitor works extremely well over different inheritance trees.
To sum up:
New functionality does not need to be added to all different types
The call to the visitor can be pulled up to the root of each class hierarchy
For a reference, see the Visitor pattern
Cant we use extension methods for this
public static void OnReadyToFly(this IFlyBehavior flyBehavior)
{
_flyBehavior.Fly()
}
This mimics the functionality you wanted (or Mixins)
Visual Studio already offers this in 'poor mans form' with code snippets. Also, with the refactoring tools a la ReSharper (and maybe even the native refactoring support in Visual Studio), you get a long way in ensuring consistency.
[EDIT: I didn't think of Extension methods, this approach brings you even further (you only need to keep the _flyBehaviour as a private variable). This makes the rest of my answer probably obsolete...]
However; just for the sake of the discussion: how could this be improved? Here's my suggestion.
One could imagine something like the following to be supported by a future version of the C# compiler:
// keyword 'pattern' marks the code as eligible for inclusion in other classes
pattern WithFlyBehaviour
{
private IFlyBehavior_flyBehavior;
private void OnReadyToFly()
{
_flyBehavior.Fly();
}
[patternmethod]
private void OnReadyToLand()
{
_flyBehavior.Land();
}
}
Which you could use then something like:
// probably the attribute syntax can not be reused here, but you get the point
[UsePattern(FlyBehaviour)]
class FlyingAnimal
{
public void SetReadyToFly(bool ready)
{
_readyToFly = ready;
if (ready) OnReadyToFly(); // OnReadyToFly() callable, although not explicitly present in FlyingAnimal
}
}
Would this be an improvement? Probably. Is it really worth it? Maybe...
You just described aspect oriented programming.
One popular AOP implementation for C# seems to be PostSharp (Main site seems to be down/not working for me though, this is the direct "About" page).
To follow up on the comment: I'm not sure if PostSharp supports it, but I think you are talking about this part of AOP:
Inter-type declarations provide a way
to express crosscutting concerns
affecting the structure of modules.
Also known as open classes, this
enables programmers to declare in one
place members or parents of another
class, typically in order to combine
all the code related to a concern in
one aspect.
Could you get this sort of behavior by using the new ExpandoObject in .NET 4.0?
Scala traits were developed to address this kind of scenario. There's also some research to include traits in C#.
UPDATE: I created my own experiment to have roles in C#. Take a look.
I will use extension methods to implement the behaviour as the code shows.
Let Bird and Plane objects implement a property for IFlyBehavior object for an interface IFlyer
public interface IFlyer
{
public IFlyBehavior FlyBehavior
}
public Bird : IFlyer
{
public IFlyBehaviour FlyBehavior {get;set;}
}
public Airplane : IFlyer
{
public IFlyBehaviour FlyBehavior {get;set;}
}
Create an extension class for IFlyer
public IFlyerExtensions
{
public void OnReadyToFly(this IFlyer flyer)
{
flyer.FlyBehavior.Fly();
}
public void OnReadyToLand(this IFlyer flyer)
{
flyer.FlyBehavior.Land();
}
}

Good Case For Interfaces

I work at a company where some require justification for the use of an Interface in our code (Visual Studio C# 3.5).
I would like to ask for an Iron Clad reasoning that interfaces are required for. (My goal is to PROVE that interfaces are a normal part of programming.)
I don't need convincing, I just need a good argument to use in the convincing of others.
The kind of argument I am looking for is fact based, not comparison based (ie "because the .NET library uses them" is comparison based.)
The argument against them is thus: If a class is properly setup (with its public and private members) then an interface is just extra overhead because those that use the class are restricted to public members. If you need to have an interface that is implemented by more than 1 class then just setup inheritance/polymorphism.
Code decoupling. By programming to interfaces you decouple the code using the interface from the code implementing the interface. This allows you to change the implementation without having to refactor all of the code using it. This works in conjunction with inheritance/polymorphism, allowing you to use any of a number of possible implementations interchangeably.
Mocking and unit testing. Mocking frameworks are most easily used when the methods are virtual, which you get by default with interfaces. This is actually the biggest reason why I create interfaces.
Defining behavior that may apply to many different classes that allows them to be used interchangeably, even when there isn't a relationship (other than the defined behavior) between the classes. For example, a Horse and a Bicycle class may both have a Ride method. You can define an interface IRideable that defines the Ride behavior and any class that uses this behavior can use either a Horse or Bicycle object without forcing an unnatural inheritance between them.
The argument against them is thus: If
a class is properly setup (with its
public and private members) then an
interface is just extra overhead
because those that use the class are
restricted to public members. If you
need to have an interface that is
implemented by more than 1 class then
just setup inheritance/polymorphism.
Consider the following code:
interface ICrushable
{
void Crush();
}
public class Vehicle
{
}
public class Animal
{
}
public class Car : Vehicle, ICrushable
{
public void Crush()
{
Console.WriteLine( "Crrrrrassssh" );
}
}
public class Gorilla : Animal, ICrushable
{
public void Crush()
{
Console.WriteLine( "Sqqqquuuuish" );
}
}
Does it make any sense at all to establish a class hierarchy that relates Animals to Vehicles even though both can be crushed by my giant crushing machine? No.
In addition to things explained in other answers, interfaces allow you simulate multiple inheritance in .NET which otherwise is not allowed.
Alas as someone said
Technology is dominated by two types of people: those who understand what they do not manage, and those who manage what they do not understand.
To enable unit testing of the class.
To track dependencies efficiently (if the interface isn't checked out and touched, only the semantics of the class can possibly have changed).
Because there is no runtime overhead.
To enable dependency injection.
...and perhaps because it's friggin' 2009, not the 70's, and modern language designers actually have a clue about what they are doing?
Not that interfaces should be thrown at every class interface: just those which are central to the system, and which are likely to experience significant change and/or extension.
Interfaces and abstract classes model different things. You derive from a class when you have an isA relationship so the base class models something concrete. You implement an interface when your class can perform a specific set of tasks.
Think of something that's Serializable, it doesn't really make sense (from a design/modelling point of view) to have a base class called Serializable as it doesn't make sense to say something isA Serializable. Having something implement a Serializable interface makes more sense as saying 'this is something the class can do, not what the class is'
Interfaces are not 'required for' at all, it's a design decision. I think you need to convince yourself, why, on a case-by-case basis, it is beneficial to use an interface, because there IS an overhead in adding an interface. On the other hand, to counter the argument against interfaces because you can 'simply' use inheritance: inheritance has its draw backs, one of them is that - at least in C# and Java - you can only use inheritance once(single inheritance); but the second - and maybe more important - is that, inheritance requires you to understand the workings of not only the parent class, but all of the ancestor classes, which makes extension harder but also more brittle, because a change in the parent class' implementation could easily break the subclasses. This is the crux of the "composition over inheritance" argument that the GOF book taught us.
You've been given a set of guidelines that your bosses have thought appropriate for your workplace and problem domain. So to be persuasive about changing those guidelines, it's not about proving that interfaces are a good thing in general, it's about proving that you need them in your workplace.
How do you prove that you need interfaces in the code you write in your workplace? By finding a place in your actual codebase (not in some code from somebody else's product, and certainly not in some toy example about Duck implementing the makeNoise method in IAnimal) where an interface-based solution is better than an inheritance-based solution. Show your bosses the problem you're facing, and ask whether it makes sense to modify the guidelines to accommodate situations like that. It's a teachable moment where everyone is looking at the same facts instead of hitting each other over the head with generalities and speculations.
The guideline seems to be driven by a concern about avoiding overengineering and premature generalisation. So if you make an argument along the lines of we should have an interface here just in case in future we have to..., it's well-intentioned, but for your bosses it sets off the same over-engineering alarm bells that motivated the guideline in the first place.
Wait until there's a good objective case for it, that goes both for the programming techniques you use in production code and for the things you start arguments with your managers about.
Test Driven Development
Unit Testing
Without interfaces producing decoupled code would be a pain. Best practice is to code against an interface rather than a concrete implementation. Interfaces seem rubbish at first but once you discover the benefits you'll always use them.
You can implement multiple interfaces. You cannot inherit from multiple classes.
..that's it. The points others are making about code decoupling and test-driven development don't get to the crux of the matter because you can do those things with abstract classes too.
Interfaces allow you to declare a concept that can be shared amongst many types (IEnumerable) while allowing each of those types to have its own inheritance hierarchy.
In this case, what we're saying is "this thing can be enumerated, but that is not its single defining characteristic".
Interfaces allow you to make the minimum amount of decisions necessary when defining the capabilities of the implementer. When you create a class instead of an interface, you have already declared that your concept is class-only and not usable for structs. You also make other decisions when declaring members in a class, such as visibility and virtuality.
For example, you can make an abstract class with all public abstract members, and that is pretty close to an interface, but you have declared that concept as overridable in all child classes, whereas you wouldn't have to have made that decision if you used an interface.
They also make unit testing easier, but I don't believe that is a strong argument, since you can build a system without unit tests (not recommended).
If your shop is performing automated testing, interfaces are a great boon to dependency injection and being able to test a unit of software in isolation.
The problem with the inheritance argument is that you'll either have a gigantic god class or a hierarchy so deep, it'll make your head spin. On top of that, you'll end up with methods on a class you don't need or don't make any sense.
I see a lot of "no multiple inheritance" and while that's true, it probably won't phase your team because you can have multiple levels of inheritance to get what they'd want.
An IDisposable implementation comes to mind. Your team would put a Dispose method on the Object class and let it propagate through the system whether or not it made sense for an object or not.
An interface declares a contract that any object implementing it will adhere to. This makes ensuring quality in code so much easier than trying to enforce written (not code) or verbal structure, the moment a class is decorated with the interface reference the requirements/contract is clear and the code won't compile till you've implemented that interface completely and type-safe.
There are many other great reasons for using Interfaces (listed here) but probably don't resonate with management quite as well as a good, old-fashioned 'quality' statement ;)
Well, my 1st reaction is that if you've to explain why you need interfaces, it's a uphill battle anyways :)
that being said, other than all the reasons mentioned above, interfaces are the only way for loosely coupled programming, n-tier architectures where you need to update/replace components on the fly etc. - in personal experience however that was too esoteric a concept for the head of architecture team with the result that we lived in dll hell - in the .net world no-less !
Please forgive me for the pseudo code in advance!
Read up on SOLID principles. There are a few reasons in the SOLID principles for using Interfaces. Interfaces allow you to decouple your dependancies on implementation. You can take this a step further by using a tool like StructureMap to really make the coupling melt away.
Where you might be used to
Widget widget1 = new Widget;
This specifically says that you want to create a new instance of Widget. However if you do this inside of a method of another object you are now saying that the other object is directly dependent on the use of Widget. So we could then say something like
public class AnotherObject
{
public void SomeMethod(Widget widget1)
{
//..do something with widget1
}
}
We are still tied to the use of Widget here. But at least this is more testable in that we can inject the implementation of Widget into SomeMethod. Now if we were to use an Interface instead we could further decouple things.
public class AnotherObject
{
public void SomeMethod(IWidget widget1)
{
//..do something with widget1
}
}
Notice that we are now not requiring a specific implementation of Widget but instead we are asking for anything that conforms to IWidget interface. This means that anything could be injected which means that in the day to day use of the code we could inject an actual implementation of Widget. But this also means that when we want to test this code we could inject a fake/mock/stub (depending on your understanding of these terms) and test our code.
But how can we take this further. With the use of StructureMap we can decouple this code even more. With the last code example our calling code my look something like this
public class AnotherObject
{
public void SomeMethod(IWidget widget1)
{
//..do something with widget1
}
}
public class CallingObject
{
public void AnotherMethod()
{
IWidget widget1 = new Widget();
new AnotherObject().SomeMethod(widget1);
}
}
As you can see in the above code we removed the dependency in the SomeMethod by passing in an object that conforms to IWidget. But in the CallingObject().AnotherMethod we still have the dependency. We can use StructureMap to remove this dependency too!
[PluginFamily("Default")]
public interface IAnotherObject
{
...
}
[PluginFamily("Default")]
public interface ICallingObject
{
...
}
[Pluggable("Default")]
public class AnotherObject : IAnotherObject
{
private IWidget _widget;
public AnotherObject(IWidget widget)
{
_widget = widget;
}
public void SomeMethod()
{
//..do something with _widget
}
}
[Pluggable("Default")]
public class CallingObject : ICallingObject
{
public void AnotherMethod()
{
ObjectFactory.GetInstance<IAnotherObject>().SomeMethod();
}
}
Notice that no where in the above code are we instantiating an actual implementation of AnotherObject. Because everything is wired for StructurMap we can allow StructureMap to pass in the appropriate implementations depending on when and where the code is ran. Now the code is truely flexible in that we can specify via configuration or programatically in a test which implementation we want to use. This configuration can be done on the fly or as part of a build process, etc. But it doesn't have to be hard wired anywhere.
Appologies as this doesn't answer your question regarding a case for Interfaces.
However I suggest getting the person in question to read..
Head First Design Patterns
-- Lee
I don't understand how its extra overhead.
Interfaces provide flexibility, manageable code, and reusability. Coding to an interface you don't need to worry about the concreted implementation code or logic of the certain class you are using. You just expect a result. Many class have different implementation for the same feature thing (StreamWriter,StringWriter,XmlWriter)..you do not need to worry about how they implement the writing, you just need to call it.

Categories