I'm trying to get into the habit of coding to an interface rather than an implementation and whilst in most cases I can see the reasoning there are a few where I struggle.
Take this really simple example:
public interface IAuditLog
{
void AddLog(string log);
}
public class AuditLog : IAuditLog
{
public void AddLog(string log)
{
//implementation
}
}
To call the audit log class:
public partial class AuditLogPage : System.Web.UI.Page
{
protected void btnAddLog_Click(object sender, EventArgs e)
{
IAuditLog objAuditLog = new AuditLog();
objAuditLog.AddLog("test log");
}
}
I still have to use AuditLog when instantiating, so what's the point? If the AddLog method signature changes i'm still going to have to go through all my pages that use it and amend the code. Am I missing the point?
Thanks for any help in advance,
Wilky.
In the example if you switched out FileAuditLogger() with DatabaseAuditLogger() or EventLogAuditLogger() you can switch implementations without having to rewrite your code.
Typically you'd use an IoC container (Autofac, StructureMap, Unity, etc.) to automatically wire up the object instantiation. So instead of calling new AuditLog() you would call IoC.Container.Resolve<IAuditLog>()
Let me know if you'd like more information.
Let imagine that there there are two AuditLog classes
class AuditLogToDatabase : IAuditLog // writes to database
and another is
class AuditLogToFile : IAuditLog // writes to file
like
protected void btnAddLog_Click(object sender, EventArgs e)
{
IAuditLog objAuditLog = AuditLogFactory.GetAuditLog();
objAuditLog.AddLog("test log");
}
now you can inject any class based on some configuration at run time without changing the actual implementation
This doesn't necessarily mean that you have to actually use a C# interface. An interface in OOP terms is the publicly visible façade of an API. It's a contract and externally visible results of operations should be specified. How exactly it works beneath the surface should be irrelevant so that you can swap out the implementation at any time.
Of course, in that regard an interface is a method of being able to use different implementations, but so is an abstract base class or even a non-abstract class others can derive from.
But more to the exact point of your question: Of course, when instantiating a class its type must be known, but you don't necessarily have to create the class instance there. You could set an IAuditLog from the outside or get it via a factory class, etc. where you wouldn't know, at that exact point in the code, what exact type you're getting (except that it's compatible with IAuditLog).
This is actually useful when you create the AuditLog instance from a method say like a Factory method and you have more than one AuditLogXXX classes derived from the IAuditLog interface.
So, instead of using this code:
IAuditLog objAuditLog = new AuditLog();
You would actually use this code when you program to an interface:
IAuditLog objAuditLog = LogFactory.GetAuditLog(); //This call is programmed to an interface
where GetAuditLog() is an interface typed method defined on the LogFactory class as below:
class LogFactory
{
public IAuditLog GetAuditLog() // This method is programmed to an interface
{
//Some logic to make a choice to return appropriate AuditLogXXX instance from the factory
}
}
Related
I'm building a program that will be processing messages from various topics. Since the data on each topic is different, I need dedicated classes that consumes data from any given topic. I want to do so using a base class that handles the communicates with the messaging system, and derived classes that implement the handling of the message:
public abstract class MessageConsumer<T>
{
public void Start(){/*omitted*/}
/* Other abstract properties and methods here to support template pattern*/
}
The Start method will tell the MessageConsumer to start pulling in new message. Examples of derived classes are:
public class CreatedMessageConsumer : MessageConsumer<CreatedMessage>
{
/*Implementation omitted*/
}
public class DeletedMessageConsumer : MessageConsumer<DeletedMessage>{}
In the code snippet above, I omitted the required constructor arguments, but it's easy to imagine how a DiContainer can be useful here. I use Autofac. The registration of CreatedMessageConsumer and DeletedMessageConsumer using Autofac works well.
My problem is how to resolve all classes that derives from MessageConsumer<>.
This SO post discusses how to resolve a given derived type, but I want to resolve all types that derive from MessageConsumer. Subsequently I want to call the Start method on all of them, e.g. something like
foreach(var consumer in container.Resolve<IEnumerable<MessageConsumer<??>>())
{
consumer.Start();
}
However, because I cannot provide the generic argument, it will not compile. Any idea how to do this? I'm using Autofac 4.2.1.
If you do not care about the generic argument, (which you don't otherwise you would have specified a generic argument in your last code block), then:
Define an interface (with method Start)
Implement that on your type(s)
Add it to the As chain where you define your Autofac registrations
Resolve the new interface
Updated code:
public interface IStartable {
void Start();
}
public abstract class MessageConsumer<T> : IStartable
{
public void Start(){/*omitted*/}
/* Other abstract properties and methods here to support template pattern*/
}
Caling code:
foreach(var consumer in container.Resolve<IEnumerable<IStartable>>())
{
consumer.Start();
}
New to OOP here. I have defined an interface with one method, and in my derived class I defined another public method. My client code is conditionally instantiating a class of the interface type, and of course the compiler doesn't know about the method in one of the derived classes as it is not part of the underlying interface definition. Here is what I am talking about:
public interface IFileLoader
{
public bool Load();
}
public class FileLoaderA : IFileLoader
{
public bool Load();
//implementation
public void SetStatus(FileLoadStatus status)
{
//implementation
}
}
public class FileLoaderB : IFileLoader
{
public bool Load();
//implementation
//note B does not have a SetStatus method
}
public enum FileLoadStatus
{
Started,
Done,
Error
}
// client code
IFileLoader loader;
if (Config.UseMethodA)
{
loader = new FileLoaderA();
}
else
{
loader = new FileLoaderB();
}
//does not know about this method
loader.SetStatus (FileStatus.Done);
I guess I have two questions:
What should I be doing to find out if the object created at run-time has the method I am trying to use? Or is my approach wrong?
I know people talk of IOC/DI all the time. Being new OOP, what is the advantage of using an IOC in order to say, "when my app asks
for an IFileLoader type, use concrete class x", as opposed to simply
using an App.Config file to get the setting?
Referring to your two questions and your other post I'd recommend the following:
What should I be doing to find out if the object created at run-time has the method I am trying to use? Or is my approach wrong?
You don't necessarily need to find out the concrete implementation at runtime in your client code. Following this approach you kinda foil the crucial purpose of an interface. Hence it's rather useful to just naïvely use the interface and let the concrete logic behind decide what's to do.
So in your case, if one implementation's just able to load a file - fine. If your other implementation is able to the same and a bit more, that's fine, too. But the client code (in your case your console application) shouldn't care about it and just use Load().
Maybe some code says more than thousand words:
public class ThirdPartyLoader : IFileLoader
{
public bool Load(string fileName)
{
// simply acts as a wrapper around your 3rd party tool
}
}
public class SmartLoader : IFileLoader
{
private readonly ICanSetStatus _statusSetter;
public SmartLoader(ICanSetStatus statusSetter)
{
_statusSetter = statusSetter;
}
public bool Load(string fileName)
{
_statusSetter.SetStatus(FileStatus.Started);
// do whatever's necessary to load the file ;)
_statusSetter.SetStatus(FileStatus.Done);
}
}
Note that the SmartLoader does a bit more. But as a matter of separation of concerns its purpose is the loading part. The setting of a status is another class' task:
public interface ICanSetStatus
{
void SetStatus(FileStatus fileStatus);
// maybe add a second parameter with information about the file, so that an
// implementation of this interface knows everything that's needed
}
public class StatusSetter : ICanSetStatus
{
public void SetStatus(FileStatus fileStatus)
{
// do whatever's necessary...
}
}
Finally your client code could look something like the follwing:
static void Main(string[] args)
{
bool useThirdPartyLoader = GetInfoFromConfig();
IFileLoader loader = FileLoaderFactory.Create(useThirdPartyLoader);
var files = GetFilesFromSomewhere();
ProcessFiles(loader, files);
}
public static class FileLoaderFactory
{
public static IFileLoader Create(bool useThirdPartyLoader)
{
if (useThirdPartyLoader)
{
return new ThirdPartyLoader();
}
return new SmartLoader(new StatusSetter());
}
}
Note that this is just one possible way to do what you're looking for without having the necessity to determine IFileLoader's concrete implementation at runtime. There maybe other more elegant ways, which furthermore leads me to your next question.
I know people talk of IOC/DI all the time. Being new OOP, what is the advantage of using an IOC [...], as opposed to simply using an App.Config file to get the setting?
First of all separating of classes' responsibility is always a good idea especially if you want to painlessly unittest your classes. Interfaces are your friends in these moments as you can easily substitute or "mock" instances by e.g. utilizing NSubstitute. Moreover, small classes are generally more easily maintainable.
The attempt above already relies on some sort of inversion of control. The main-method knows barely anything about how to instantiate a Loader (although the factory could do the config lookup as well. Then main wouldn't know anything, it would just use the instance).
Broadly speaking: Instead of writing the boilerplate factory instantiation code, you could use a DI-Framework like Ninject or maybe Castle Windsor which enables you to put the binding logic into configuration files which might best fit your needs.
To make a long story short: You could simply use a boolean appSetting in your app.config that tells your code which implementation to use. But you could use a DI-Framework instead and make use of its features to easily instantiate other classes as well. It may be a bit oversized for this case, but it's definitely worth a look!
Use something like:
if((loader as FileLoaderA) != null)
{
((FileLoaderA)loader).SetStatus(FileStatus.Done);
}
else
{
// Do something with it as FileLoaderB type
}
IoC is normally used in situations where your class depends on another class that needs to be setup first, the IoC container can instantiate/setup an instance of that class for your class to use and inject it into your class usually via the constructor. It then hands you an instance of your class that is setup and ready to go.
EDIT:
I was just trying to keep the code concise and easy to follow. I agree that this is not the most efficient form for this code (it actually performs the cast twice).
For the purpose of determining if a particular cast is valid Microsoft suggests using the following form:
var loaderA = loader as FileLoaderA;
if(loaderA != null)
{
loaderA.SetStatus(FileStatus.Done);
// Do any remaining FileLoaderA stuff
return;
}
var loaderB = loader as FileLoaderB
if(loaderB != null)
{
// Do FileLoaderB stuff
return;
}
I do not agree with using is in the if. The is keyword was designed to determine if an object was instantiated from a class that implements a particular interface, rather than if a cast is viable. I have found it does not always return the expected result (especially if a class implements multiple interfaces through direct implementation or inheritance of a base class).
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why would I want to use Interfaces?
Why I need Interface?
I want to know where and when to use it?
For example,
interface IDemo
{
// Function prototype
public void Show();
}
// First class using the interface
class MyClass1 : IDemo
{
public void show()
{
// Function body comes here
Response.Write("I'm in MyClass");
}
}
// Second class using the interface
class MyClass2 : IDemo
{
public void show()
{
// Function body comes here
Response.Write("I'm in MyClass2");
Response.Write("So, what?");
}
These two classes has the same function name with different body.
This can be even achieved without Interface.
Then why we need an Interface where and when to use it?
In your simple case, you could achieve something similar to what you get with interfaces by using a common base class that implements show() (or perhaps defines it as abstract). Let me change your generic names to something more concrete, Eagle and Hawk instead of MyClass1 and MyClass2. In that case you could write code like
Bird bird = GetMeAnInstanceOfABird(someCriteriaForSelectingASpecificKindOfBird);
bird.Fly(Direction.South, Speed.CruisingSpeed);
That lets you write code that can handle anything that is a *Bird*. You could then write code that causes the Bird to do it's thing (fly, eat, lay eggs, and so forth) that acts on an instance it treats as a Bird. That code would work whether Bird is really an Eagle, Hawk, or anything else that derives from Bird.
That paradigm starts to get messy, though, when you don't have a true is a relationship. Say you want to write code that flies things around in the sky. If you write that code to accept a Bird base class, it suddenly becomes hard to evolve that code to work on a JumboJet instance, because while a Bird and a JumboJet can certainly both fly, a JumboJet is most certainly not a Bird.
Enter the interface.
What Bird (and Eagle, and Hawk) do have in common is that they can all fly. If you write the above code instead to act on an interface, IFly, that code can be applied to anything that provides an implementation to that interface.
Interfaces are mostly needed when you have components that are dependent on one another.
A common example is a logging controller and some logger classes.
class LoggingController {
private ILogger _logger
// expecting an interface here removes the dependency
// to a specific implemenentation.
// all it cares about is that the object has a Log() method
public LoggingController(ILogger logger) {
_logger = logger;
}
public void Log() { _logger.Log(); }
}
interface ILogger {
void Log();
}
class DbLogger : ILogger {
public void Log(){ //log into db }
}
class TxtLogger : ILogger {
public void Log(){ //log into a txt file }
}
At runtime, the logging controller can be injected with any implementation of the ILogger, and it is completely unaware of what the logger actually does to actually log stuff.
The other benefit of programming to interfaces is that it allows for easier unit testing.
The controller can easily be unit tested by injecting a mock logger which would also implement the interface.
Here are a couple of good links.
http://www.daniweb.com/software-development/csharp/threads/114364/why-use-interfaces
http://fci-h.blogspot.com/2008/03/oop-design-concepts-interfaces_05.html
Elaboration: Basically they provide more abstraction. If you have an object say Alien and in this case all Aliens are from outer space. Well not all Aliens are exactly the same but they all consume food and use energy. The way they consume food and use energy may be different but to keep a base Alien class and have interfaces that abstract away from that class makes more sense than to have separate classes for each type.
Core logic can be kept the same in the base class and interfaces can change parts when needed.
I have a question concerning holding common code in a base class and having the derived class call it, even though the derived class's trigger method has been dispatched from the base. So, base->derived->base type call stack.
Is the following look OK, or does it smell? I have numbered the flow steps...
public abstract class LayerSuperType
{
public void DoSomething() // 1) Initial call from client
{
ImplementThis(); // 2) Polymorphic dispatch
}
protected abstract void ImplementThis();
protected void SomeCommonMethodToSaveOnDuplication(string key) // 4)
{
Configuration config = GetConfiguration(key);
}
}
public class DerivedOne : LayerSuperType
{
protected virtual void ImplementThis() // 2)
{
SomeCommonMethodToSaveOnDuplication("whatever"); // 3) Call method in base
}
}
public class DerivedTwo : LayerSuperType
{
protected virtual void ImplementThis() // 2)
{
SomeCommonMethodToSaveOnDuplication("something else"); // 3) Call method in base
}
}
That looks absolutely fine. Perfect example of why you'd use an abstract class over an interface. It's a bit like a strategy pattern and I have used this fairly regularly and successfully.
Make sure that what the class doing is still dealing with one 'concern' though, only doing one task. If your base class does repository access but the objects are representing documents, don't put the functionality in the base class, use a separate repository pattern/object.
Looks like a very simplified Template Method Pattern where your sub-classes do some specific kinds of things at the right points in the implementation of your algorithm, but the overall flow is directed by a method on the base class. You've also provided some services to your sub-classes in the form of base class methods; that's ok too as long as you're good as far as SOLID goes.
Why not public abstract void DoSomething() and forget about ImplementThis() altogether?
The only reason I can see to leave ImplementThis() is if you want to maintain a consistent interface with DoSomething() which later on down the road will allow the signature of ImplementThis() to change without a breaking change to callers.
I agree that you should maintain a single concern with the class's responsibility but from an overall OOP perspective this looks fine to me. I've done similar on many occasions.
It does smell a little that SomeCommonMethodToSaveOnDuplication is being called in two different ways. It seems to be doing two unrelated things. Why not have two methods?
I am really interested in some architectural methods. I like DI and IOC, but I don't understand costructor injection; why is it so complicated. I've written the code below which uses constructor injection:
namespace DependencyInjection
{
class Program
{
static void Main(string[] args)
{
ConstructorInjectionClass myCtx = new ConstructorInjectionClass(new PdfFormat());
myCtx.Print();
Console.Read();
}
}
public interface IFormat
{
void Print();
}
public class PdfFormat : IFormat
{
public void Print()
{
Console.WriteLine("Pdf Format Print is completed...");
}
}
// Constructor Injection
public class ConstructorInjectionClass
{
private IFormat _format;
public ConstructorInjectionClass(IFormat format)
{
_format = format;
}
public void Print()
{
_format.Print();
}
}
I've written some code below. I think it's simple.
public interface IFormat
{
void Print();
}
public class PdfFormat : IFormat
{
public void Print()
{
Console.WriteLine("Pdf Format Print is completed...");
}
}
public interface ISave
{
void Add();
}
public class Sql: ISave
{
public void Add()
{
Console.WriteLine("Adding to SQL is completed...");
}
}
// Constructor Injection
public class ConstructorInjectionClass
{
public ConstructorInjectionClass(IFormat format)
{
format.Print();
}
public ConstructorInjectionClass(ISave saver)
{
saver.Add();
}
Why should I use constructor injection? Advantages or disadvantages of these two methods?
The first example is constructor injection. You are injecting the class with the responsibility for printing into the class.
In the second example you are creating a new class with one of 2 arguments and using the argument in the constructor. This is bad for several reasons:
Your constructor should not really do significant work, this is either saving or printing in the constructor
Your different constructors are doing different this. The constructor should only create a new instance of your class.
It is not clear that the different constructors will actually do something when they are given different objects.
If you pass the objects to the constructor and then it just calls them, why would you not just have the code that is constructing this class call the methods on ISave and IPrint implementations. After all it must have them to be able to pass them to the method. If your object holds these internally then they could have been provided when your object was constructed (like in your composition root) and the client code that calls Print on your object would not need to know anything about the fact that the ISave and IPrint implementations exist,
Constructor injection is about you class asking for the dependencies it has in it's constructor, so it is clear what the dependencies are. By requiring the dependencies rather than creating them it becomes simpler to test the class as you can inject mock dependencies for testing purposes.
The first option is good, and if you want to add saving then you should add an extra argument to the constructor to take a ISave interface as well as the IPrint interface and have a method Save which will delegate to the ISave implmentation.
By having the dependencies injected and by programming to an interface it makes it easier to change the functionality later on. You could, for example, make it pring to a file easily (by changing the IPrint interface you pass in or change it to save to an xml file or a webservice by changing the ISave implementation you pass it. This make you class loosely coupled to the save and print implemenations
I would read this excellent answer for more guidance on DI/IOC
Well, as with any pattern, constructor injection should be used when and only when it's a good idea to use it. Your example code is kind of strange...
Your first example is spot on. Your class has a method called Print which has a dependency on another class to do the printing. Rather than instantiate this dependency, it requires that the dependency be supplied in its constructor. This is a classic example of the Dependency Inversion Principle. Basically: "Require, don't instantiate."
Your second example isn't quite clear, though. What is your class really doing? What's it for? It has two constructors which perform an action on their dependencies, but why? Nowhere else in the class is there a dependency on instances of these types. So why have the wrapper class in the first place? It seems more... contrived... than your first example. It's unclear what the architecture of the code is trying to accomplish, and therefore as it stands not a good use of constructor injection.
Lets say that you want to inject dependencies... you could do this via constructor injection or via property setters. I think one of the advantages to constructor injection is that IOC's use this strategy. So if you aren't sure you want to go IOC but you want to do DI then should probably use constructor injection to make the transition to IOC latter... easier... if you should change your mind...