Implementing ISP design pattern in C# - 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.

Related

Adding methods to existing class - inheritance/injection

I have a dozen service classes that were built for WCF, e.g.:
public class BookingService : IBookingService
{
public void BookTheThing(int ThingID) { .. }
}
We are aiming to reuse these classes as direct libraries (not WCF) and create a separate service library which would allow us preserve and expose those existing methods and add new ones. Here are 2 possibilities I've come up with based on my limited experience:
*Option#1 - Inject original class and create identical methods to expose it's functionality:
public class BookingServiceNew : IBookingServiceNew
{
public BookingServiceNew(IBookingService service) { _baseService = service; }
public void BookTheThing(int ThingId) { _baseService.BookTheThing(ThingId); }
public bool OurNewMethod1(int ThingId) { return true; }
public int OurNewMethod2(int ThingId) { return 1; }
}
*Option#2 - Inherit original service class, which would automatically expose its methods as part of the class, and then add our own stuff
public class BookingServiceNew : BookingService, IBookingServiceNew
{
public bool OurNewMethod1(int ThingId) { return true; }
public int OurNewMethod2(int ThingId) { return 1; }
}
Option#1 seems like it will have some more code and duplication having to create a stub for every method in the implentation and interface. Option#2 seems like it could have some issues with dependency injection on the client, where working against IBookingServiceNew would only provide access to OurNewMethod1 & OurNewMethod2.
Again, these options I've come with are based on my very limited experience and I would appreciate your thoughts and suggestions on a better approach/practice/pattern to follow.
Thanks
I'd recommend going with option 1 (composition) over inheritance. Yes, this requires additional boilerplate code to expose each method of the inner service. However, this code has no logic so we're not really "repeating" anything. Furthermore, by using composition you gain a ton of flexibility down the line; if you decide you don't want to expose the same interface in IBookingServiceNew as in IBookingService you can simply remove/change those methods without modifying the original BookingService implementation. You can also easily swap in a new implementation of IBookingService (e. g. a mock in a unit test).
In contrast, using class inheritance to avoid the boilerplate saves some code in the short run, at a big cost to flexibility and maintenance. For one, you give up the ability to extend a different base class in the future. Now, your BookingService class must be designed for inheritance; you'll have to be careful about which internal methods and state are exposed to the subclass, and you need to worry about introducing conflicts with methods in the derived class. In general, the API exposed by a class which you expect to be extended is much more complex and harder for the consumer to understand than the one exposed by an interface. As a general rule, I try to avoid using class inheritance unless I will actually be making use of polymorphism (as opposed to just including methods from the base class). In this case, you're already using interfaces, so you have no need for the class polymorphism.
Finally, note that your concern about IBookingServiceNew not exposing the methods on IBookingService is easily addressed by either (1) putting those methods on IBookingServiceNew as well or (2) having IBookingServiceNew extend IBookingService.
What about extension methods?
public static class BookingServiceExtensions
{
public static bool OurNewMethod1(this IBookingService service, int ThingId)
{
...
}
}

when we need interface c# [duplicate]

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.

OOD, inheritance, and Layer Supertype

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?

Interfaces — What's the point?

The reason for interfaces truly eludes me. From what I understand, it is kind of a work around for the non-existent multi-inheritance which doesn't exist in C# (or so I was told).
All I see is, you predefine some members and functions, which then have to be re-defined in the class again. Thus making the interface redundant. It just feels like syntactic… well, junk to me (Please no offense meant. Junk as in useless stuff).
In the example given below taken from a different C# interfaces thread on stack overflow, I would just create a base class called Pizza instead of an interface.
easy example (taken from a different stack overflow contribution)
public interface IPizza
{
public void Order();
}
public class PepperoniPizza : IPizza
{
public void Order()
{
//Order Pepperoni pizza
}
}
public class HawaiiPizza : IPizza
{
public void Order()
{
//Order HawaiiPizza
}
}
No one has really explained in plain terms how interfaces are useful, so I'm going to give it a shot (and steal an idea from Shamim's answer a bit).
Lets take the idea of a pizza ordering service. You can have multiple types of pizzas and a common action for each pizza is preparing the order in the system. Each pizza has to be prepared but each pizza is prepared differently. For example, when a stuffed crust pizza is ordered the system probably has to verify certain ingredients are available at the restaurant and set those aside that aren't needed for deep dish pizzas.
When writing this in code, technically you could just do
public class Pizza
{
public void Prepare(PizzaType tp)
{
switch (tp)
{
case PizzaType.StuffedCrust:
// prepare stuffed crust ingredients in system
break;
case PizzaType.DeepDish:
// prepare deep dish ingredients in system
break;
//.... etc.
}
}
}
However, deep dish pizzas (in C# terms) may require different properties to be set in the Prepare() method than stuffed crust, and thus you end up with a lot of optional properties, and the class doesn't scale well (what if you add new pizza types).
The proper way to solve this is to use interface. The interface declares that all Pizzas can be prepared, but each pizza can be prepared differently. So if you have the following interfaces:
public interface IPizza
{
void Prepare();
}
public class StuffedCrustPizza : IPizza
{
public void Prepare()
{
// Set settings in system for stuffed crust preparations
}
}
public class DeepDishPizza : IPizza
{
public void Prepare()
{
// Set settings in system for deep dish preparations
}
}
Now your order handling code does not need to know exactly what types of pizzas were ordered in order to handle the ingredients. It just has:
public PreparePizzas(IList<IPizza> pizzas)
{
foreach (IPizza pizza in pizzas)
pizza.Prepare();
}
Even though each type of pizza is prepared differently, this part of the code doesn't have to care what type of pizza we are dealing with, it just knows that it's being called for pizzas and therefore each call to Prepare will automatically prepare each pizza correctly based on its type, even if the collection has multiple types of pizzas.
The point is that the interface represents a contract. A set of public methods any implementing class has to have. Technically, the interface only governs syntax, i.e. what methods are there, what arguments they get and what they return. Usually they encapsulate semantics as well, although that only by documentation.
You can then have different implementations of an interface and swap them out at will. In your example, since every pizza instance is an IPizza you can use IPizza wherever you handle an instance of an unknown pizza type. Any instance whose type inherits from IPizza is guaranteed to be orderable, as it has an Order() method.
Python is not statically-typed, therefore types are kept and looked up at runtime. So you can try calling an Order() method on any object. The runtime is happy as long as the object has such a method and probably just shrugs and says »Meh.« if it doesn't. Not so in C#. The compiler is responsible for making the correct calls and if it just has some random object the compiler doesn't know yet whether the instance during runtime will have that method. From the compiler's point of view it's invalid since it cannot verify it. (You can do such things with reflection or the dynamic keyword, but that's going a bit far right now, I guess.)
Also note that an interface in the usual sense does not necessarily have to be a C# interface, it could be an abstract class as well or even a normal class (which can come in handy if all subclasses need to share some common code – in most cases, however, interface suffices).
For me, when starting out, the point to these only became clear when you stop looking at them as things to make your code easier/faster to write - this is not their purpose. They have a number of uses:
(This is going to lose the pizza analogy, as it's not very easy to visualise a use of this)
Say you are making a simple game on screen and It will have creatures with which you interact.
A: They can make your code easier to maintain in the future by introducing a loose coupling between your front end and your back end implementation.
You could write this to start with, as there are only going to be trolls:
// This is our back-end implementation of a troll
class Troll
{
void Walk(int distance)
{
//Implementation here
}
}
Front end:
function SpawnCreature()
{
Troll aTroll = new Troll();
aTroll.Walk(1);
}
Two weeks down the line, marketing decide you also need Orcs, as they read about them on twitter, so you would have to do something like:
class Orc
{
void Walk(int distance)
{
//Implementation (orcs are faster than trolls)
}
}
Front end:
void SpawnCreature(creatureType)
{
switch(creatureType)
{
case Orc:
Orc anOrc = new Orc();
anORc.Walk();
case Troll:
Troll aTroll = new Troll();
aTroll.Walk();
}
}
And you can see how this starts to get messy. You could use an interface here so that your front end would be written once and (here's the important bit) tested, and you can then plug in further back end items as required:
interface ICreature
{
void Walk(int distance)
}
public class Troll : ICreature
public class Orc : ICreature
//etc
Front end is then:
void SpawnCreature(creatureType)
{
ICreature creature;
switch(creatureType)
{
case Orc:
creature = new Orc();
case Troll:
creature = new Troll();
}
creature.Walk();
}
The front end now only cares about the interface ICreature - it's not bothered about the internal implementation of a troll or an orc, but only on the fact that they implement ICreature.
An important point to note when looking at this from this point of view is that you could also easily have used an abstract creature class, and from this perspective, this has the same effect.
And you could extract the creation out to a factory:
public class CreatureFactory {
public ICreature GetCreature(creatureType)
{
ICreature creature;
switch(creatureType)
{
case Orc:
creature = new Orc();
case Troll:
creature = new Troll();
}
return creature;
}
}
And our front end would then become:
CreatureFactory _factory;
void SpawnCreature(creatureType)
{
ICreature creature = _factory.GetCreature(creatureType);
creature.Walk();
}
The front end now does not even have to have a reference to the library where Troll and Orc are implemented (providing the factory is in a separate library) - it need know nothing about them whatsoever.
B: Say you have functionality that only some creatures will have in your otherwise homogenous data structure, e.g.
interface ICanTurnToStone
{
void TurnToStone();
}
public class Troll: ICreature, ICanTurnToStone
Front end could then be:
void SpawnCreatureInSunlight(creatureType)
{
ICreature creature = _factory.GetCreature(creatureType);
creature.Walk();
if (creature is ICanTurnToStone)
{
(ICanTurnToStone)creature.TurnToStone();
}
}
C: Usage for dependency injection
Most dependency injection frameworks work when there is a very loose coupling between the front end code and the back end implementation. If we take our factory example above and have our factory implement an interface:
public interface ICreatureFactory {
ICreature GetCreature(string creatureType);
}
Our front end could then have this injected (e.g an MVC API controller) through the constructor (typically):
public class CreatureController : Controller {
private readonly ICreatureFactory _factory;
public CreatureController(ICreatureFactory factory) {
_factory = factory;
}
public HttpResponseMessage TurnToStone(string creatureType) {
ICreature creature = _factory.GetCreature(creatureType);
creature.TurnToStone();
return Request.CreateResponse(HttpStatusCode.OK);
}
}
With our DI framework (e.g. Ninject or Autofac), we can set them up so that at runtime a instance of CreatureFactory will be created whenever an ICreatureFactory is needed in an constructor - this makes our code nice and simple.
It also means that when we write a unit test for our controller, we can provide a mocked ICreatureFactory (e.g. if the concrete implementation required DB access, we don't want our unit tests dependent on that) and easily test the code in our controller.
D: There are other uses e.g. you have two projects A and B that for 'legacy' reasons are not well structured, and A has a reference to B.
You then find functionality in B that needs to call a method already in A. You can't do it using concrete implementations as you get a circular reference.
You can have an interface declared in B that the class in A then implements. Your method in B can be passed an instance of a class that implements the interface with no problem, even though the concrete object is of a type in A.
Examples above don't make much sense. You could accomplish all above examples using classes (abstract class if you want it to behave only as a contract):
public abstract class Food {
public abstract void Prepare();
}
public class Pizza : Food {
public override void Prepare() { /* Prepare pizza */ }
}
public class Burger : Food {
public override void Prepare() { /* Prepare Burger */ }
}
You get the same behavior as with interface. You can create a List<Food> and iterate that w/o knowing what class sits on top.
More adequate example would be multiple inheritance:
public abstract class MenuItem {
public string Name { get; set; }
public abstract void BringToTable();
}
// Notice Soda only inherits from MenuItem
public class Soda : MenuItem {
public override void BringToTable() { /* Bring soda to table */ }
}
// All food needs to be cooked (real food) so we add this
// feature to all food menu items
public interface IFood {
void Cook();
}
public class Pizza : MenuItem, IFood {
public override void BringToTable() { /* Bring pizza to table */ }
public void Cook() { /* Cook Pizza */ }
}
public class Burger : MenuItem, IFood {
public override void BringToTable() { /* Bring burger to table */ }
public void Cook() { /* Cook Burger */ }
}
Then you can use all of them as MenuItem and don't care about how they handle each method call.
public class Waiter {
public void TakeOrder(IEnumerable<MenuItem> order)
{
// Cook first
// (all except soda because soda is not IFood)
foreach (var food in order.OfType<IFood>())
food.Cook();
// Bring them all to the table
// (everything, including soda, pizza and burger because they're all menu items)
foreach (var menuItem in order)
menuItem.BringToTable();
}
}
Simple Explanation with analogy
No interface (Example 1):
No interface (Example 2):
With an interface:
The Problem to Solve: What is the purpose of polymorphism?
Analogy: So I'm a foreperson on a construction site. I don't know which tradesperson is going to walk in. But I tell them what to do.
If it's a carpenter I say: build wooden scaffolding.
If it's a plumber, I say: Set up the pipes
If it's a BJP government bureaucrat, I say, three bags full of cash, sir.
The problem with the above approach is that I have to: (i) know who's walking in that door, and depending on who it is, I have to tell them what to do. This typically makes code harder to maintain or more error prone.
The implications of knowing what to do:
This means if the carpenter's code changes from: BuildScaffolding() to BuildScaffold() (i.e. a slight name change) then I will have to also change the calling class (i.e. the Foreperson class) as well - you'll have to make two changes to the code instead of (basically) just one. With polymorphism you (basically) only need to make one change to achieve the same result.
Secondly you won't have to constantly ask: who are you? ok do this...who are you? ok do that.....polymorphism - it DRYs that code, and is very effective in certain situations:
with polymorphism you can easily add additional classes of tradespeople without changing any existing code. (i.e. the second of the SOLID design principles: Open-close principle).
The solution
Imagine a scenario where, no matter who walks in the door, I can say: "Work()" and they do their respect jobs that they specialise in: the plumber would deal with pipes, and the electrician would deal with wires, and a bureaucrat could specialise in extracting bribes and making double work for everyone else.
The benefit of this approach is that: (i) I don't need to know exactly who is walking in through that door - all i need to know is that they will be a type of tradie and that they can do work, and secondly, (ii) i don't need to know anything about that particular trade. The tradie will take care of that.
So instead of this:
if(electrician) then electrician.FixCablesAndElectricity()
if(plumber) then plumber.IncreaseWaterPressureAndFixLeaks()
if(keralaCustoms) then keralaCustoms.askForBribes()
I can do something like this:
ITradesman tradie = Tradesman.Factory(); // in reality i know it's a plumber, but in the real world you won't know who's on the other side of the tradie assignment.
tradie.Work(); // and then tradie will do the work of a plumber, or electrician etc. depending on what type of tradesman he is. The foreman doesn't need to know anything, apart from telling the anonymous tradie to get to Work()!!
What's the benefit?
The benefit is that if the specific job requirements of the carpenter etc change, then the foreperson won't need to change his code - he doesn't need to know or care. All that matters is that the carpenter knows what is meant by Work(). Secondly, if a new type of construction worker comes onto the job site, then the foreman doesn't need to know anything about the trade - all the foreman cares is if the construction worker (.e.g Welder, Glazier, Tiler etc.) can get some Work() done.
Summary
An interface allows you to get the person to do the work they are assigned to, without you having the knowledge of exactly who they are or the specifics of what they can do. This allows you to easily add new types (of trade) without changing your existing code (well technically you do change it a tiny tiny bit), and that's the real benefit of an OOP approach vs. a more functional programming methodology.
If you don't understand any of the above or if it isn't clear ask in a comment and i'll try to make the answer better.
Here are your examples reexplained:
public interface IFood // not Pizza
{
public void Prepare();
}
public class Pizza : IFood
{
public void Prepare() // Not order for explanations sake
{
//Prepare Pizza
}
}
public class Burger : IFood
{
public void Prepare()
{
//Prepare Burger
}
}
In the absence of duck typing as you can use it in Python, C# relies on interfaces to provide abstractions. If the dependencies of a class were all concrete types, you could not pass in any other type - using interfaces you can pass in any type that implements the interface.
The Pizza example is bad because you should be using an abstract class that handles the ordering, and the pizzas should just override the pizza type, for example.
You use interfaces when you have a shared property, but your classes inherit from different places, or when you don't have any common code you could use. For instance, this is used things that can be disposed IDisposable, you know it will be disposed, you just don't know what will happen when it's disposed.
An interface is just a contract that tells you some things an object can do, what parameters and what return types to expect.
Consider the case where you don't control or own the base classes.
Take visual controls for instance, in .NET for Winforms they all inherit from the base class Control, that is completely defined in the .NET framework.
Let's assume you're in the business of creating custom controls. You want to build new buttons, textboxes, listviews, grids, whatnot and you'd like them all to have certain features unique to your set of controls.
For instance you might want a common way to handle theming, or a common way to handle localization.
In this case you can't "just create a base class" because if you do that, you have to reimplement everything that relates to controls.
Instead you will descend from Button, TextBox, ListView, GridView, etc. and add your code.
But this poses a problem, how can you now identify which controls are "yours", how can you build some code that says "for all the controls on the form that are mine, set the theme to X".
Enter interfaces.
Interfaces are a way to look at an object, to determine that the object adheres to a certain contract.
You would create "YourButton", descend from Button, and add support for all the interfaces you need.
This would allow you to write code like the following:
foreach (Control ctrl in Controls)
{
if (ctrl is IMyThemableControl)
((IMyThemableControl)ctrl).SetTheme(newTheme);
}
This would not be possible without interfaces, instead you would have to write code like this:
foreach (Control ctrl in Controls)
{
if (ctrl is MyThemableButton)
((MyThemableButton)ctrl).SetTheme(newTheme);
else if (ctrl is MyThemableTextBox)
((MyThemableTextBox)ctrl).SetTheme(newTheme);
else if (ctrl is MyThemableGridView)
((MyThemableGridView)ctrl).SetTheme(newTheme);
else ....
}
In this case, you could ( and probably would ) just define a Pizza base class and inherit from them. However, there are two reasons where Interfaces allow you to do things that cannot be achieved in other ways:
A class can implement multiple interfaces. It just defines features that the class must have. Implementing a range of interfaces means that a class can fulfil multiple functions in different places.
An interface can be defined in a hogher scope than the class or the caller. This means that you can separate the functionality, separate the project dependency, and keep the functionality in one project or class, and the implementation of this elsewhere.
One implication of 2 is that you can change the class that is being used, just requiring that it implements the appropriate interface.
Consider you can't use multiple inheritance in C#, and then look at your question again.
I did a search for the word "composition" on this page and didn't see it once. This answer is very much in addition to the answers aforementioned.
One of the absolutely crucial reasons for using interfaces in an Object Oriented Project is that they allow you to favour composition over inheritance. By implementing interfaces you can decouple your implementations from the various algorithms you are applying to them.
This superb "Decorator Pattern" tutorial by Derek Banas (which - funnily enough - also uses pizza as an example) is a worthwhile illustration:
https://www.youtube.com/watch?v=j40kRwSm4VE
Interface = contract, used for loose coupling (see GRASP).
If I am working on an API to draw shapes, I may want to use DirectX or graphic calls, or OpenGL. So, I will create an interface, which will abstract my implementation from what you call.
So you call a factory method: MyInterface i = MyGraphics.getInstance(). Then, you have a contract, so you know what functions you can expect in MyInterface. So, you can call i.drawRectangle or i.drawCube and know that if you swap one library out for another, that the functions are supported.
This becomes more important if you are using Dependency Injection, as then you can, in an XML file, swap implementations out.
So, you may have one crypto library that can be exported that is for general use, and another that is for sale only to American companies, and the difference is in that you change a config file, and the rest of the program isn't changed.
This is used a great deal with collections in .NET, as you should just use, for example, List variables, and don't worry whether it was an ArrayList or LinkedList.
As long as you code to the interface then the developer can change the actual implementation and the rest of the program is left unchanged.
This is also useful when unit testing, as you can mock out entire interfaces, so, I don't have to go to a database, but to a mocked out implementation that just returns static data, so I can test my method without worrying if the database is down for maintenance or not.
Interfaces are for applying connection between different classes. for example, you have a class for car and a tree;
public class Car { ... }
public class Tree { ... }
you want to add a burnable functionality for both classes. But each class have their own ways to burn. so you simply make;
public class Car : IBurnable
{
public void Burn() { ... }
}
public class Tree : IBurnable
{
public void Burn() { ... }
}
You will get interfaces, when you will need them :) You can study examples, but you need the Aha! effect to really get them.
Now that you know what interfaces are, just code without them. Sooner or later you will run into a problem, where the use of interfaces will be the most natural thing to do.
An interface is really a contract that the implementing classes must follow, it is in fact the base for pretty much every design pattern I know.
In your example, the interface is created because then anything that IS A Pizza, which means implements the Pizza interface, is guaranteed to have implemented
public void Order();
After your mentioned code you could have something like this:
public void orderMyPizza(IPizza myPizza) {
//This will always work, because everyone MUST implement order
myPizza.order();
}
This way you are using polymorphism and all you care is that your objects respond to order().
I'm surprised that not many posts contain the one most important reason for an interface: Design Patterns. It's the bigger picture into using contracts, and although it's a syntax decoration to machine code (to be honest, the compiler probably just ignores them), abstraction and interfaces are pivotal for OOP, human understanding, and complex system architectures.
Let's expand the pizza analogy to say a full fledge 3 course meal. We'll still have the core Prepare() interface for all our food categories, but we'd also have abstract declarations for course selections (starter, main, dessert), and differing properties for food types (savoury/sweet, vegetarian/non-vegetarian, gluten free etc).
Based on these specifications, we could implement the Abstract Factory pattern to conceptualise the whole process, but use interfaces to ensure that only the foundations were concrete. Everything else could become flexible or encourage polymorphism, yet maintain encapsulation between the different classes of Course that implement the ICourse interface.
If I had more time, I'd like to draw up a full example of this, or someone can extend this for me, but in summary, a C# interface would be the best tool in designing this type of system.
Here's an interface for objects that have a rectangular shape:
interface IRectangular
{
Int32 Width();
Int32 Height();
}
All it demands is that you implement ways to access the width and height of the object.
Now let's define a method that will work on any object that is IRectangular:
static class Utils
{
public static Int32 Area(IRectangular rect)
{
return rect.Width() * rect.Height();
}
}
That will return the area of any rectangular object.
Let's implement a class SwimmingPool that is rectangular:
class SwimmingPool : IRectangular
{
int width;
int height;
public SwimmingPool(int w, int h)
{ width = w; height = h; }
public int Width() { return width; }
public int Height() { return height; }
}
And another class House that is also rectangular:
class House : IRectangular
{
int width;
int height;
public House(int w, int h)
{ width = w; height = h; }
public int Width() { return width; }
public int Height() { return height; }
}
Given that, you can call the Area method on houses or swimming-pools:
var house = new House(2, 3);
var pool = new SwimmingPool(3, 4);
Console.WriteLine(Utils.Area(house));
Console.WriteLine(Utils.Area(pool));
In this way, your classes can "inherit" behavior (static-methods) from any number of interfaces.
What ?
Interfaces are basically a contract that all the classes implementing the Interface should follow. They looks like a class but has no implementation.
In C# Interface names by convention is defined by Prefixing an 'I' so if you want to have an interface called shapes, you would declare it as IShapes
Now Why ?
Improves code re-usability
Lets say you want to draw Circle, Triangle.
You can group them together and call them Shapesand have methods to draw Circle and Triangle
But having concrete implementation would be a bad idea because tomorrow you might decide to have 2 more Shapes Rectangle & Square. Now when you add them there is a great chance that you might break other parts of your code.
With Interface you isolate the different implementation from the Contract
Live Scenario Day 1
You were asked to create an App to Draw Circle and Triangle
interface IShapes
{
void DrawShape();
}
class Circle : IShapes
{
public void DrawShape()
{
Console.WriteLine("Implementation to Draw a Circle");
}
}
Class Triangle: IShapes
{
public void DrawShape()
{
Console.WriteLine("Implementation to draw a Triangle");
}
}
static void Main()
{
List <IShapes> shapes = new List<IShapes>();
shapes.Add(new Circle());
shapes.Add(new Triangle());
foreach(var shape in shapes)
{
shape.DrawShape();
}
}
Live Scenario Day 2
If you were asked add Square and Rectangle to it, all you have to do is create the implentation for it in class Square: IShapes and in Main add to list shapes.Add(new Square());
An interface defines a contract between the provider of a certain functionality and the correspondig consumers. It decouples the implementation from the contract (interface). You should have a look at object oriented architecture and design. You may want to start with wikipedia: http://en.wikipedia.org/wiki/Interface_(computing)
There are a lot of good answers here but I would like to try from a slightlt different perspective.
You may be familiar with the SOLID principles of object oriented design. In summary:
S - Single Responsibility Principle
O - Open/Closed Principle
L - Liskov Substitution Principle
I - Interface Segregation Principle
D - Dependency Inversion Principle
Following the SOLID principles helps to produce code that is clean, well factored, cohesive and loosely coupled. Given that:
"Dependency management is the key challenge in software at every scale" (Donald Knuth)
then anything that helps with dependency management is a big win. Interfaces and the Dependency Inversion Principle really help to decouple code from dependencies on concrete classes, so code can be written and reasoned about in terms of behaviours rather than implementations. This helps to break the code into components which can be composed at runtime rather than compile time and also means those components can be quite easily plugged in and out without having to alter the rest of the code.
Interfaces help in particular with the Dependency Inversion Principle, where code can be componentized into a collection of services, with each service being described by an interface. Services can then be "injected" into classes at runtime by passing them in as a constructor parameter. This technique really becomes critical if you start to write unit tests and use test driven development. Try it! You will quickly understand how interfaces help to break apart the code into manageable chunks that can be individually tested in isolation.
Soo many answers!
Giving my best shot. hehe.
So to begin, yes you could have used a concrete base and derived class here. In that case, you would have to do an empty or useless implementation for the Prepare method in the base class also making this method virtual and then the derived classes would override this Prepare method for themselves. This case, the implementation of Prepare in Base class is useless.
The reason why you chose to use an Interface is because you had to define a contract, not an implementation.
There is a IPizza type and it provides a functionality to Prepare. This is contract. How it is prepared is the implementation and it is not your lookout. It is responsibility of the various Pizza implementations.
An interface or an abstract class is preferred here over a concrete base class because you had to create an abstraction, i.e., the Prepare method. You cannot create an abstract method in a concrete base class.
Now you could say, why not use an abstract class?
So, when you need to achieve 100% abstraction, you need to go with Interface. But when you need some abstraction along with a concrete implementation, go with abstract class. It means.
Example: Lets say all your pizzas will have a base and base preparation will be the same process. However, all pizza types and toppings will vary. In this case you could create an Abstract class with an abstract method Prepare and a concrete method PreparePizzaBase.
public abstract class Pizza{
// concrete method which is common to all pizzas.
public PizzaBase PreparePizzaBase(){
// code for pizza base preparation.
}
public abstract void Prepare();
}
public class DeluxePizza: Pizza{
public void Prepare(){
var base=PreparePizzaBase();
// prepare deluxe pizza on pizza base.
}
}
The main purpose of the interfaces is that it makes a contract between you and any other class that implement that interface which makes your code decoupled and allows expandability.
Therese are ask really great examples.
Another, in the case of a switch statement, you no longer have the need to maintain and switch every time you want rio perform a task in a specific way.
In your pizza example, if want to make a pizza, the interface is all you need, from there each pizza takes care of it's own logic.
This helps to reduce coupling and cyclomatic complexity. You have to still implement the logic but there will be less you have to keep track of in the broader picture.
For each pizza you can then keep track of information specific to that pizza. What other pizzas have doesn't matter because only the other pizzas need to know.
The simplest way to think about interfaces is to recognize what inheritance means. If class CC inherits class C, it means both that:
Class CC can use any public or protected members of class C as though they were its own, and thus only needs to implement things which do not exist in the parent class.
A reference to a CC can be passed or assigned to a routine or variable that expects a reference to a C.
Those two function of inheritance are in some sense independent; although inheritance applies both simultaneously, it is also possible to apply the second without the first. This is useful because allowing an object to inherit members from two or more unrelated classes is much more complicated than allowing one type of thing to be substitutable for multiple types.
An interface is somewhat like an abstract base class, but with a key difference: an object which inherits a base class cannot inherit any other class. By contrast, an object may implement an interface without affecting its ability to inherit any desired class or implement any other interfaces.
One nice feature of this (underutilized in the .net framework, IMHO) is that they make it possible to indicate declaratively the things an object can do. Some objects, for example, will want data-source object from which they can retrieve things by index (as is possible with a List), but they won't need to store anything there. Other routines will need a data-depository object where they can store things not by index (as with Collection.Add), but they won't need to read anything back. Some data types will allow access by index, but won't allow writing; others will allow writing, but won't allow access by index. Some, of course, will allow both.
If ReadableByIndex and Appendable were unrelated base classes, it would be impossible to define a type which could be passed both to things expecting a ReadableByIndex and things expecting an Appendable. One could try to mitigate this by having ReadableByIndex or Appendable derive from the other; the derived class would have to make available public members for both purposes, but warn that some public members might not actually work. Some of Microsoft's classes and interfaces do that, but that's rather icky. A cleaner approach is to have interfaces for the different purposes, and then have objects implement interfaces for the things they can actually do. If one had an interface IReadableByIndex and another interface IAppendable, classes which could do one or the other could implement the appropriate interfaces for the things they can do.
Interfaces can also be daisy chained to create yet another interface. This ability to implement multiple Interfaces give the developer the advantage of adding functionality to their classes without having to change current class functionality (SOLID Principles)
O = "Classes should be open for extension but closed for modification"
To me an advantage/benefit of an interface is that it is more flexible than an abstract class. Since you can only inherit 1 abstract class but you can implement multiple interfaces, changes to a system that inherits an abstract class in many places becomes problematic. If it is inherited in 100 places, a change requires changes to all 100. But, with the interface, you can place the new change in a new interface and just use that interface where its needed (Interface Seq. from SOLID). Additionally, the memory usage seems like it would be less with the interface as an object in the interface example is used just once in memory despite how many places implement the interface.
Interfaces are used to drive consistency,in a manner that is loosely coupled which makes it different to abstract class which is tightly coupled.That's why its also commonly defined as a contract.Whichever classes that implements the interface has abide to "rules/syntax" defined by the interface and there is no concrete elements within it.
I'll just give an example supported by the graphic below.
Imagine in a factory there are 3 types of machines.A rectangle machine,a triangle machine and a polygon machine.Times are competitive and you want to streamline operator training.You just want to train them in one methodology of starting and stopping machines so you have a green start button and red stop button.So now across 3 different machines you have a consistent way of starting and stopping 3 different types of machines.Now imagine these machines are classes and the classes need to have start and stop methods,how you going to drive consistency across these classes which can be very different? Interface is the answer.
A simple example to help you visualize,one might ask why not use abstract class? With an interface the objects don't have to be directly related or inherited and you can still drive consistency across different classes.
public interface IMachine
{
bool Start();
bool Stop();
}
public class Car : IMachine
{
public bool Start()
{
Console.WriteLine("Car started");
return true;
}
public bool Stop()
{
Console.WriteLine("Car stopped");
return false;
}
}
public class Tank : IMachine
{
public bool Start()
{
Console.WriteLine("Tank started");
return true;
}
public bool Stop()
{
Console.WriteLine("Tank stopped");
return false;
}
}
class Program
{
static void Main(string[] args)
{
var car = new Car();
car.Start();
car.Stop();
var tank = new Tank();
tank.Start();
tank.Stop();
}
}
class Program {
static void Main(string[] args) {
IMachine machine = new Machine();
machine.Run();
Console.ReadKey();
}
}
class Machine : IMachine {
private void Run() {
Console.WriteLine("Running...");
}
void IMachine.Run() => Run();
}
interface IMachine
{
void Run();
}
Let me describe this by a different perspective. Let’s create a story according to the example which i have shown above;
Program, Machine and IMachine are the actors of our story. Program wants to run but it has not that ability and Machine knows how to run. Machine and IMachine are best friends but Program is not on speaking terms with Machine. So Program and IMachine make a deal and decided that IMachine will tell to Program how to run by looking Machine(like a reflector).
And Program learns how to run by help of IMachine.
Interface provides communication and developing loosely coupled projects.
PS: I’ve the method of concrete class as private. My aim in here is to achieve loosely coupled by preventing accessing concrete class properties and methods, and left only allowing way to reach them via interfaces. (So i defined interfaces’ methods explicitily).

How would one implement many classes that have the same methods that do things different?

I am a developer who works primarily with embedded devices (programmed with C and assembly). My C# and OOP knowledge is very limited (although I can fake my way through it when necessary). I have five devices that interface with a PC via USB. The PC does some calculations and sends a result to the device. The same calculations are performed for each device, but the calculations are done differently. For each device, I have a C# Windows Forms application that does some work and sends data back and forth to the device. Currently, I'm trying to get the five different applications merged into one so we can easily make changes, add new devices easily, and have a standard user interface. My problem is that I don't exactly know the best way to do it since I don't know which device will be used until run time. I'm trying to avoid a bunch of if statements and I would like to be able to put each device in a separate file. Here is some psudo-code of what I'm talking about.
class Device //This is what EVERY device can do
{
...
DoWork1();
DoWork2();
DoWork3();
...
}
class Device1
{
...
DoWork1(); //This is how the work is done for this device
DoWork2();
DoWork3();
...
}
class Device2
{
...
DoWork1(); //This is how the work is done for this device (not the same way as Device1)
DoWork2();
DoWork3();
}
public partial class frmMain : Form
{
private (some kind of object or something) CurrentDevice;
public frmMain()
{
...
//Determine what device (could be one of five) is currently being used
CurrentDevice = (which device is currently being used)
//Could be CurrentDevice = new Device1();
}
}
private void Button1_Click()
{
CurrentDevice.DoWork1(); //But this could be Device1.DoWork1() or Device2.DoWork1(), depending on what device is currently being used (which was determined in the frmMain constructor)
}
I'm not really sure, but I'm thinking I could use an interface or maybe inherit the Device1 class for the Device class and override the methods...But I don't know how I would have one generic way of saying CurrentDevice.DoWork1() since CurrentDevice could be Device1 or Device2.
Any ideas would be greatly appreciated. I'm using Visual Studio 2008 with .NET 3.5 on Windows XP SP3 and Windows 7.
I hope I described the problem well enough. If not, or if I didn't mention something that I should, please let me know. I'm new to stackoverflow and C#.
Thank you,
Michael
In your case, you're basically defining a inheritance hierarchy that can either consist of an abstract base class and two derived types or an interface with two implementors of it. For example
public abstract class BaseDevice
{
public abstract void DoWork1();
}
public class Device1 : BaseDevice
{
public override void DoWork1()
{
// provide implementation here
}
}
// also create Device2 : BaseDevice and implement
OR you could utilize an interface definition
public interface IDevice
{
void DoWork1();
}
public class Device1 : IDevice
{
public void DoWork1()
{
// provide implementation
}
}
Which methodology you pick is up to you. You would perhaps favor an abstract base class if, for example, you wanted to define some behavior or properties with implementations that were common throughout the hierarchy. With an abstract class, you can provide implementations. An interface is an empty contract, you cannot provide any common behaviors, only a definition for what behaviors or properties may be present.
Either way you go, you would refer to instances of the more derived type via the abstract or interface base. In this manner, you don't care what the implementing type is, only what it can do (it's methods or properties).
Example:
BaseDevice device1 = new Device1();
BaseDevice device2 = new Device2();
// maybe you have a list?
List<BaseDevice> devices = new List<BaseDevice> { device1, device2 };
foreach (BaseDevice device in devices)
{
device.DoWork1(); // notice you don't care about the actual type, just the behavior
}
I was a little confused at first because in this case the pc does calculations the devices only receive the result. So as I understand it you need different implementations of something on the PC, not the devices themselves.
The real trick here is not about using an interface or inheritance - you already figured that out. The trick is getting the right implementation type, and you use a factory for that part.
But you do have to decide on inheritance vs interface as well.
Use inheritance only if that "something" is truly part of a common, but also meaningful family. Inheritance should have a very strong "is a" element.
OTOH many objects could exist that might do a calculation but that you might not want to make a family. This is where composition is useful. To get that by inheritance you would need to have them share a common base class. Here you can use composition to allow each object to use a common interface to allow the pc to perform the calculation.
I suggest this approach.
You should have a reference to a common, generic interface, IDoCalculation, or some such, that defines a method signature that will be called in the same way for any device.
Next you have to get the device specific implementation for that interface, this is where each device can have a different implementation. Create a class for each device type/implementation.
Now the trick is to get the class you need without having to know what it is. To once again keep the details hidden and make the method calls generic, you can create a parameterized Factory. This factory accepts a parameter that describes what device the pc needs a calculation for. It then interprets that parameter and based on that creates a specific class that implements IDoCalculation. This is returned and you are done.
I leave it to you to figure out how these objects need to be organized into different assemblies...
//Common interface
public interface IDoCalculation
{
//Use whatever method signatures you need
int DoCalculation();
}
public class DeviceImplementation1 : IDoCalculation
{
#region IDoCalculation Members
public int DoCalculation()
{
//Device 1 Specific code goes here
}
#endregion
}
public class DeviceImplementation2 : IDoCalculation
{
#region IDoCalculation Members
public int DoCalculation()
{
//Device 2 Specific code goes here
}
#endregion
}
// A simple factory that does not require a lot of OOP understanding.
public class DeviceCalculationFactory
{
//Return a correct implementor based on the device type passed in
public IDoCalculation GetCalculationImplementationInstance(string devicetype)
{
switch (devicetype)
{
case "Device1":
return new DeviceImplementation1();
case "Device2":
return new DeviceImplementation2();
default:
//TODO ???
return null;
}
}
}
// A simple client that calls the methods and then send the results
public class DeviceManager
{
//To do the calculation, get an implementor for the correct device type from the factory - Presumably the PC knows the device of interest, example "Device1"
public void DoTheCalculationThing(string deviceType)
{
DeviceCalculationFactory factory = new DeviceCalculationFactory();
IDoCalculation calculation = factory.GetCalculationImplementationInstance(deviceType);
int result = calculation.DoCalculation();
// now send the result to the device
}
}
You might be interested in looking at some design patterns for this.
http://www.oodesign.com/
Specifically Abstract Factory and Template Method. I think one of those might be what you're looking for.
http://www.oodesign.com/abstract-factory-pattern.html
http://www.oodesign.com/template-method-pattern.html
As I understand it, you want to be able to have a base class, then inherit the base class functions and define them in subclasses. One of those patterns would probably work for your scenario.
Anthony Pegram's answer is excellent but you may want to take it a step further. It is conceivable that although it appears that all your devices are performing the same tasks you may find that some do not, in fact, perform all the tasks and yet others perform even more.
In such cases you may be tempted to alter the interface to add another DoWork5 or DoWork6 method and simply raise NotImplemented exceptions on types that do not have the particular behaviour.
This is troublesome for many reasons. I would suggest (should you find yourself in this position) to take a look at making your roles explicit. You do this by creating interfaces that represent a particular role (or set of behaviours --- ties in with the interface segregation principle).
So you could have IMediaPlayer with Play, Pause, Rewind and another IMediaRecorder with a Record method. In this way you implement the relevant roles on your concrete classes.
HTH

Categories