C# static service or implement interface - c#

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.

Related

Implementing ISP design pattern in C#

I am trying to use Robert C. Martin principle of ISP.
From Wikipedia,
The ISP was first used and formulated by Robert C. Martin while
consulting for Xerox. Xerox had created a new printer system that
could perform a variety of tasks such as stapling and faxing. The
software for this system was created from the ground up. As the
software grew, making modification became more and more difficult so
that even the smallest change would take a redeployment cycle of an
hour, which made development nearly impossible.
The design problem was that a single Job class was used by almost all
of the tasks. Whenever a print job or a stapling job needed to be
performed, a call was made to the Job class. This resulted in a 'fat'
class with multitudes of methods specific to a variety of different
clients. Because of this design, a staple job would know about all the
methods of the print job, even though there was no use for them.
The solution suggested by Martin utilized what is called the Interface Segregation Principle today. Applied to the Xerox software,
an interface layer between the Job class and its clients was added
using the Dependency Inversion Principle. Instead of having one large
Job class, a Staple Job interface or a Print Job interface was created
that would be used by the Staple or Print classes, respectively,
calling methods of the Job class. Therefore, one interface was created
for each job type, which were all implemented by the Job class.
What I am trying to understand is how the system functioned and what Martin proposed to change it.
interface IJob
{
bool DoPrintJob();
bool DoStaplingJob();
bool DoJob1();
bool DoJob2();
bool DoJob3();
}
class Job : IJob
{
// implement all IJob methods here.
}
var printClient = new Job(); // a class implemeting IJob
printClient.DoPrintJob(); // but `printClient` also knows about DoStaplingJob(), DoJob1(), DoJob2(), DoJob3() also.
I could try up to this point and got stuck up here
an interface layer between the Job class and its clients was added using the Dependency Inversion Principle - Wikipedia lines - (Interface layer ?)
1Instead of having one large Job class, a Staple Job interface or a Print Job interface was created that would be used by the Staple or Print classes, respectively, calling methods of the Job class - ( then calling methods of the Job class - ok, create separate interface and then why to call the methods of job class ?)
What Martin did next? (Some corrected code skeletons would help me understand this).
Based on the answers, I was able to proceed as below. Thanks Sergey and Christos.
interface IPrintJob
{
bool DoPrintJob();
}
interface IStapleJob
{
bool DoStapleJob();
}
interface IJob : IPrintJob, IStapleJob
{
bool DoPrintJob();
bool DoStaplingJob();
}
var printClient = new PrintJob(); //PrintJob implements the IPrintJob interface
var stapleClient = new StableJob(); // StapleJob implements the IStapleJob interface
Ok Great. What does the IJob interface do, Why is it used ? It can be removed right?
ISP is not a design pattern - its a design principle. And it helps to avoid implementing interfaces which are not required by clients. E.g. in your case you have client which needs only printing. But you have IJob interface with bunch of methods which don't needed by this client. Why would I implement DoStaplingJob, DoJob1, DoJob2 and DoJob3 if I want only printing? So, solution is creating small interface which satisfies my need:
public interface IPrintingJob
{
bool DoPrintJob();
}
Original interface will look like:
public interface IJob : IPrintingJob
{
bool DoStaplingJob();
bool DoJob1();
bool DoJob2();
bool DoJob3();
}
Now all clients which want only printing, will implement IPrintginJob interface, without being bothered with other members of IJob interface. You can continue spliting IJob interface to smaller interfaces, if you will have clients which don't need whole functionality of IJob interface.
UPDATE: From client point of view. Depending on big interface is not very convenient. E.g. you have client which wants only printing. You can depend on IJob interface and pass Job class instance to this client:
public void Foo(IJob job)
{
job. // intellisense will show confusing bunch of members you don't need here
}
With many small interfaces, you can depend only on IPrintingJob interface, and still pass big Job class as implementation of this interface:
public void Foo(IPrintingJob printingJob)
{
printingJob. // intellisense will show single member. easy and handy
}
Another benefit is easy refactoring. Later you can extract printing functionality from Job class to other small class like PrintingJob. And you will be able to pass its instance to clients which need only printing.
At first the ISP prinicple states, as we read on Wikipedia:
no client should be forced to depend on methods it does not use
That being said, we should only declare interfaces that will be consisted of members, that will be used all from the types that will implement them. So intead of having one big interface consisting of 10 methods signatures, which will will not be implemented by all the the types that implement the interface is a bad practice. Hence you have to split this big interface to smaller one and each type that wants to implement a specific behaviour should implement the corresponding interface. That makes things more clear and more modular.
A code exammple it could make the things more clear.
Let we have the following interface:
public interface BigInterface
{
void MethodA();
void MethodB();
void MethodC();
void MethodD();
void MethodE();
}
and let we have two classes:
public class classA : BigInterface
{
}
and
public class classB : BigInterface
{
}
Now both classes should provide an implementation of the five methods of the BigInterface, despite the fact the a subset of the methods makes sense for classA and another subset makes sense for classB. That's certainly a really bad practice, if you have implemented something like this.
In order to be more concrete, let's say that both classes have to implement methodA and methodB and only classA have to implement methodC and only classB have to implement methodD and methodE. Then according to the ISP principle you could organize you code to the following one:
public interface ICommomInterface
{
void MethodA();
void MethodB();
}
public interface ISpecificInterface1
{
void MethodC();
}
public interface ISpecificInterface2
{
void MethodD();
void MethodE();
}
and the classes declaration's should be:
public class classA: ICommonInterface, ISpecificInterface1
{
}
public class classB: ICommonInterface, ISpecificInterface2
{
}
Note: As correctly, Sergey posted before me, ISP is a principle and it is not a design pattern.

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

Mock .NET classes using wrapper classes

I have a class that takes a MethodInfo instance and extracts some information from it, but I would like to mock this class. At the moment it is difficult because it takes a MethodInfo, so my plan was to create a wrapper for the MethodInfo class and implement an interface on it. For example:
public interface IMethodInfo
{
string Name { get; }
}
public class MethodInfoProxy : IMethodInfo
{
private readonly MethodInfo _method;
public MethodInfoProxy(MethodInfo method)
{
_method = method;
}
public string Name { get { return _method.Name; } }
}
public class MyClass
{
public MyClass(IMethodInfo method)
{
...
}
}
Another example would be the File.Exists method. The thought would be to create a IFile.Exists and put it on a FileProxy class that would simply delegate to File.Exists.
As I'm new to the whole unit testing world I would like to know if this would be considered a good approach to take?
You have two options here:
Use a mocking framework like Microsoft Moles or TypeMock Isolator that can mock static and sealed classes. This is great because you don't end up changing your code just to isolate the code under test from its dependencies.
Defining interfaces for behaviours that you want to mock, and then creating a default implementation that wraps a static call, or other difficult-to-test api. This is the approach you've suggested and one that I've used a lot. The key thing, when defining these interfaces is to pass the real/mock implementation of the interface into the test class via some form of dependency injection - usually constructor injection. Some people make the mistake of constructing the object within the class being tested and that makes it impossible to test. A good rule of thumb is that when you see objects being constructed in your business code, then that is a code smell - not always a bad thing, but definitely something to view with suspicion. There's a great video about this stuff: The Clean Code Talks - "Global State and Singletons".
There's a bit of a religious war between those who think testing shouldn't change the code and those that think it should. Dependency injection, which is essential if you are going to mock by creating interfaces, leads to code with high cohesion and loose coupling and an intuitive API. But the other approach isn't precluded from these benefits - it's just not so automatic.
I recommend trying to pull the dependencies out of the class - instead of supplying a MethodInfo (or a proxy), just supply the Name.
When that isn't practical, you can either write proxy classes that use an adapter interface (as you've suggested) or use a black-magic tool like TypeMock or Moles (just kidding about the black magic part: I just don't have any experience with them).
If you plan to use the proxy approach, be sure to take a look at the SystemWrapper library, which already handles about twenty classes from the .NET framwork.
You could create a wrapper around each of the class that you use but it would be extremely expensive. It's better to use a mocking framework such as the moles framework by Microsoft http://research.microsoft.com/en-us/projects/pex/ which can also stub out static methods.
A Mock class (or a fake class) would be a class you make to satisfy dependencies and make your test more deterministic by ruling out problems in your dependencies.
public interface IMethodInfo
{
string Name { get; }
}
Your mock class:
FakeMethodInfo : IMethodInfo
{
string Name {get {return "FakeMethod";}}
}
Now, in your unit test, pass the FakeMethodInfo class where you need an IMethodInfo.
The whole purpose is that you know FakeMethodInfo just returns a string so if something fails, it is not the problem.
Don't know what context MethodInfo has in your program. A better example would be
interface IUser
{
string UserName {get;}
}
If it were implemented in a class you would get the actual username from a data base.
Now, if you make a fake one, and pass it around, you kinda simulate a user logged in without a real user, and you rule out that any problem has to do with `IUser.
See this large answer I posted on why you would use mocking. And an example with Moq.:
Difference between Dependency Injection and Mocking framework (Ninject vs RhinoMock or Moq)
For faster creating of wrapper classes, you can use one of the Scaffold code generator I created.
https://www.nuget.org/packages/Digitrish.WrapperGenerator/
This will generate Interface that you can use to any mocking framework and concrete wrapper class for the real implementation.

Help designing a order manager class

So I have an order manager class that looks like:
public class OrderManager
{
private IDBFactory _dbFactory;
private Order _order;
public OrderManager(IDBFactory dbFactory)
{
_dbFactory = dbFactory;
}
public void Calculate()
{
_order.SubTotal
_order.ShippingTotal
_order.TaxTotal
_order.GrandTotal
}
}
Now, the point here is to have a flexible/testible design.
I am very concerned about being able to write solid unit tests around this Calculate method.
Considerations:
1. Shipping has to be abstracted out, be loose coupled since the implementation of shipping could vary depending on USPS, UPS, fedex etc. (they have their own API's).
2. same goes with calculating tax
Should I just create a Tax and Shipping Manager class, and have a tax/shipping factory in the constructor? (exactly how I have designed my OrderManager) class?
(the only thing that I can think of, in terms of what I am "missing", is IoC, but I don't mind that and don't need that extra level of abstraction in my view).
Well, you are already moving towards dependency injection in your approach, so why not go the whole hog and use some sort of IoC container to handle this for you?
Yes, if you want it abstrated out, then create a separate class for it. If you want to truly unit test what is left, abstract out an interface and use mock testing. The problem is, the more you abstract out like this, the more plumbing together there is to do and the more you will find yourself wishing you were using an IoC framework of some kind.
You are suggesting constructor injection, which is a common approach. You also come across property injection (parameterless constructor, set properties instead). And there are also frameworks that ask you to implement an initialization interface of some kind that allows the IoC framework to do the initialization for you in a method call. Use whatever you feel most comfortable with.
I do think an IOC would help with the plumbing of instantiating the correct concrete classes but you still need to get your design the way you want it. I do think you need to abstract away the shipping with an interface that you can implement with a class for each of your shippers (USPS, UPS, FEDEx, etc) and could use a Factory class (ShippingManager) to pass the correct one out or depend on the IOC to do that for you.
public interface IShipper
{
//whatever goes into calculating shipping.....
decimal CalculateShippingCost(GeoData geo, decimal packageWeight);
}
You could also just inject an IShipper and ITaxer concrete classes into your OrderManager and you calculate method just calls into those classes....and can use an IOC nicely to handle that.
Just a thought:
Your Calculate() method taking no parameters, returning nothing and acting on private fields is not how I would do it. I would write it as a static method that takes in some numbers, an IShippingProvider and an ITaxJurisdiction and returns a dollar total. That way you have an opportunity to cache the expensive calls to UPS and your tax tables using memoization.
Could be that I'm prejudiced against public methods that work like that. They have burned me in the past trying to bind to controls, use code generators, etc.
EDIT: as for dependency injection/IOC, I don't see the need. This is what interfaces were made for. You're not going to be loading up a whole array of wacky classes, just some implementations of the same weight/zipcode combo.
That's what I would say if I were your boss.
I would take the Calculate method out into a class. Depending on your circumstances OrderCalculator might need to be aware of VAT, Currency, Discounts, ...
Just a thought.

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