How strict should be interfaces (a good interface design) - c#

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;
....
}

Related

C# static service or implement interface

I have two case:
-Use static service
public class TestService {
public static bool FunctionA(int b) {
return b > 0;
}
}
-Use interface
public interface ITestSerice {
bool FunctionA(int b);
}
public class TestService : ITestService {
public bool FunctionA(int b) {
return b > 0;
}
}
Static class is very simple. But I often see more people using the interface (or higher than Dependency Injection). Please explain to me why and when to use the interface? (which is better?)
Sorry if my english is too bad :D
If you use a static method, then the code which calls that method is tied to that particular implementation.
If your class uses that method via an interface, this allows you to use a different implementation of that interface.
The static method makes your tho classes closely-coupled. The interface approach makes them loosely-coupled.
What is the difference between loose coupling and tight coupling in the object oriented paradigm?
The answer to the question why developers generally prefer dependency on interfaces instead of static implementations, sits in one of the SOLID principles called Dependency inversion principle.
I'll try to give you an example:
Let's imagine you have a store. And you want to buy juice making machine and start selling the juice. Let's imagine that in your town there are several variants of machines, and for each variant there are different juice flavor pots with different forms, which makes them irreplaceable in terms of machines. Let's imagine you want to sell all flavors in your store, in that way you would need to have 4 or 5 different machines. Wouldn't it be great if all flavor producers have one standard for flavor pots, so you can use one machine for any of those flavors?
So in my example the unified flavor pot's standard is interface. Having the standard makes your juice machine independent of the flavor pot implementation, so at any time you can change the flavor in your machine or even create your own flavor.
Please explain to me why and when to use the interface?
It boils down to Pull vs Push - meaning is it your class responsible for defining or pulling service implementation or some else is taking responsibility to inject or push that service implementation ?
If you going to use static version, then you basically coupled your class with that service implementation only.
Biggest point is to consider if you can unit test your class without concrete dependency of service implementation - which you cannot if you use static version.
If you use Interface version - you can provide mock implementation of service while writing unit test for class. make sense ?
which is better?
Using Interface.

Would one Method per Interface be a Reasonable Design Choice?

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.

Ways to specify whether a feature is supported in contract

I have an interface -though it could also be an abstract class- that should allow its implementers to specify whether they support a particular feature and I'm looking for the best way to achieve that.
There are several choices here:
Looking at BCL, I see that the Stream class has properties like CanRead and CanSeek, which can be used to check if a feature is supported and throws a NotSupportedException, if I do something that is not supported.
public interface IHandler
{
bool SupportsA { get; }
bool SupportsB { get; }
void A();
void B();
}
This would be an appropriate approach for me, though I have more than a few features that may or may not be supported and I prefer not to define a "SupportsX" property for each one.
I'm also very fond of bitwise Enum values and I think that another way would be:
[Flags]
public enum HandlerFeature
{
None = 0
A = 1,
B = 2,
C = 4
}
public interface IHandler
{
HandlerFeature Features { get; }
void A();
void B();
void C();
}
And an extension method like this could be written:
bool Supports<T>(this T handler, HandlerFeature feature) where T : IHandler
Which I think would also be much prettier than the other approach but, I couldn't help but think that if every Enum value would correspond a member in the contract, I should be able to mark those members more explicitly. Then I thought about attributes:
public interface IHandler
{
[HandlerRequires(Feature.None)]
HandlerFeature Features { get; }
[HandlerRequires(Feature.A)]
void A();
[HandlerRequires(Feature.B)]
void B();
[HandlerRequires(Feature.A | Feature.B)]
void AB();
[HandlerRequires(Feature.C)]
void C();
}
Although I don't know how to leverage an attribute like this in runtime, it definitely makes the interface definition looks explicit enough.
Is there a best-practice for this?
Or another approach you recommend?
Or anything wrong with the ones I specified?
If you have to build an interface that must use all this stuff, I recommend that you do it with Booleans because the developer has to specify a value for that property when he or she is implementing that interface. Using a flagged enum or attributes can result in classes where e.g. method A is not implemented but the developer simply forgot to set the Attribute or enum correctly. In this case, the compiler would not emit an error.
Anyway, I would advise you to not construct such a "fat" interface. I would encourage you to read about the "Interface Segregation Principle" which is part of the SOLID principles of object-oriented design (Google it, you'll find several articles). It states that clients should not be forced to depend on methods they do not use. The consequence of this is that you use multiple small interfaces instead of one that clasps several aspects. Now I don't know the context your working in but if your interface integrates several cross-cutting concerns like e.g. logging besides its basic business capabilities, I would strongly recommend to throw out logging of the interface and use the Decorator pattern instead (also, Google this if you don't know it :-) ).
Hope this helps.

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