EDIT
Ive rephrased the question so it better reflects what im trying to do
I'm trying to create a suite of classes that all inherit from 1 "superclass" or "baseclass".
However i'm looking for a way around having to implement the code for each method, in every single class since it seems to be theres a lot of duplication.
Here is the Super class:
public abstract class WebObject
{
string Id { get; set; }
string Name { get; set; }
public void Click() { Console.WriteLine("Clicking object"); }
public string GetAttribute() { return "An attribute"; }
public void SetAttribute(string attribute, string value)
{
//code to set attribute
}
}
I've also created a couple of interfaces:
interface IReadable
{
string GetText();
}
interface IWriteable
{
void SetText(string value);
}
Here is an example derived class:
public class TextBox: WebObject, IWriteable, IReadable
{
}
Of course the above class contains an error. It does not implement IWriteable or IReadable.
So I could do something like:
public class TextBox: WebObject, IWriteable, IReadable
{
public void SetText(string value)
{
//Implemented code
}
public string GetText()
{
//Implemented code
return "some value";
}
}
Which would compile fine...
However the problem here is that SetText and GetText contain a lot of code. I don't want to have to copy this every single time I want to implement the method. Id rather just write the code once and have it called any time I need to use that method.
I know we cant do multiple inheritance in C# and Java. So my original thought was simply to create a suite of static classes with the code for SetText and GetText Shown here:
public static class Setter
{
public static void SetText(string value)
{
//Code to set text
}
}
public static class Getter
{
public static string GetText()
{
//Code to get text
return "";
}
}
Then changing my TextBox class to the following:
public class TextBox: WebObject, IWriteable, IReadable
{
public void SetText(string value)
{
Setter.SetText(value);
}
public string GetText()
{
return Getter.GetText();
}
}
I cant help but feel this is a pretty long winded solution. It accomplishes what I want in that TextBox has the vanilla methods plus the 2 it implements itself.
But my question is, can I achieve the same goal using a more concise design?
Footnotes
Each object actually implements several of common methods. Take TextBox, ComboBox and SelectBox they all should be able to SetText, however only CombBox and SelectBox should be able to use Select.
The cleanest way to do what you are asking is to implement protected helper methods within your base class that decompose the problem of "a lot of duplication" into smaller pieces that can be composed in your concrete method implementations, like this:
public abstract class WebObject {
protected void SetTextImpl() { /* Implementation */ }
protected void GetTextImpl() { /* Implementation */ }
}
Then in your derived classes, implement only the applicable interfaces and appropriate methods:
public class TextBox: WebObject, IWriteable, IReadable {
public void SetText() { SetTextImpl(); }
public void GetText() { GetTextImpl(); }
}
public class Span: WebObject, IReadable {
public void GetText() { GetTextImpl(); }
}
If you know that all the subclasses will be IReadable, you can simplify further:
public abstract class WebObject : IReadable {
protected void SetTextImpl() { /* Implementation */ }
protected void GetTextImpl() { /* Implementation */ }
// Implement IReadable -- this could be combined with GetTextImpl() but
// is implemented separately for consistency.
public void GetText() { GetTextImpl(); }
}
public class TextBox: WebObject, IWriteable {
public void SetText() { SetTextImpl(); }
}
public class Span: WebObject, IReadable {
}
If the code for those two methods will always be the same or mostly the same, you could create another abstract class (ex: WebObjectReadWrite) that inherits from WebObject and implements the interface.
public abstract class WebObjectReadWrite : WebObject, IReadable, IWritable
{
// Could be made virtual if some subclasses need to overwrite default implementation.
public void Read()
{
// Implementation
}
// Could be made virtual if some subclasses need to overwrite default implementation.
public void Write()
{
// Implementation
}
}
public class TextBox : WebObjectReadWrite
{
}
This could, however, lead to multiple inheritance problems or inheritance relationships that don't make sense. Another option is to use the strategy pattern (in way) to delegate the read / write operations to other classes that can be reused.
public class TextBox : WebObject, IReadable, IWriteable
{
private IReadable _readable = new TextReader();
private IWriteable _writeable = new TextWriter();
public void Read()
{
_readable.Read();
}
public void Write()
{
_writable.Write();
}
}
public class Span : WebObject, IReadable
{
// Reused class.
private IReadable _readable = new TextReader();
public void Read()
{
_readable.Read();
}
}
public class TextReader : IReadable
{
public void Read()
{
// Reusable implementation
}
}
This isn't quite the strategy pattern because you are not allowing the caller to choose the implementation of IReadable and IWriteable. However, it does allow you to reuse IReadable and IWriteable classes.
Related
I have an abstract class with methods with logic.
Then i have childs but not all childs can have all methods from the abstract class. I have been thinking of a design pattern that allows me to keep the logic instead of using interfaces but can't think of anyhting other then using a static class with methods. But it would make my code very sloppy.
Another way of formulating my question is: How do i use interfaces with logic in them...
public abstract class Company
{
public virtual void Dowork1()
{
//logic
}
public virtual void Dowork2()
{
//logic
}
public virtual void Dowork3()
{
//logic
}
}
public class ItCompany : Company
{
//DoWork2 NOT callable
}
public class ManagementCompany : Company
{
//DoWork1 NOT callable
}
A pillar of object oriented programming is Liskov substitution principle. In practical terms this means that any implementation of Company need to implement all the methods. I.e. one implementation of a company should be possible to substitute for any other.
You seem to be concerned about implementation inheritance, i.e. allow any of the implementations to reuse the same logic without the need to reimplement it. This can be problematic since it couples the base class to the derived classes. However, you should be able to do what you describe by making the implementations protected.
public abstract class Company
{
protected virtual void DoworkImpl1()
{
//logic
}
protected virtual void DoworkImpl2()
{
//logic
}
protected virtual void DoworkImpl3()
{
//logic
}
}
This lets each implementation define what parts they want to expose:
public class ItCompany : Company
{
public void Dowork1() => DoworkImpl1();
public void Dowork3() => DoworkImpl3();
}
You may also add different interfaces for each type of company if you want to, as shown in other answers. However, if Company does not expose any public methods, you cannot really do anything with a object of the base type, except check what specific type it is, and this is often indicative of a problem in the class design. I would recommend reading Eric Lipperts article on Wizards and Warriors for some perspective.
A possible replacement is to move logic to static methods, for example using extension methods or default interface methods:
public static class CompanyHelpers{
public static void Dowork1(this ICompany company){
// Logic
}
}
This can be very useful with well designed interfaces that expose a minimal set of functions, and provides most extra functionality via extension methods. See LINQ for an example. But it may or may not be applicable in your specific situation.
I think you are looking at the problem from the wrong side. Let me rename your methods to make it more clear.
public abstract class Company
{
public virtual void ManagementWork()
{
//logic
}
public virtual void ItWork()
{
//logic
}
public virtual void BuildCompany()
{
//general logic
}
}
public class ItCompany : Company
{
//ManagementWork NOT callable
}
public class ManagementCompany : Company
{
//ItWork NOT callable
}
It would be better this way
public abstract class Company
{
public virtual void BuildCompany()
{
//general logic
}
}
public class ItCompany : Company
{
public virtual void ItWork()
{
//logic
}
}
public class ManagementCompany : Company
{
public virtual void ManagementWork()
{
//logic
}
}
I guess this is the better way :
interface IDoableWorkOne
{
void DoWork1();
}
interface IDoableWorkTwo
{
void DoWork2();
}
interface IDoableWorkThree
{
void DoWork3();
}
interface ICompany
{
//Other Company Shared Logics
}
public class ManagementCompany: IDoableWorkTwo, IDoableWorkThree, ICompany
{
/// Do your Business
}
public class ItCompany : IDoableWorkOne, IDoableWorkThree, ICompany
{
/// Do Your Business
}
Hope this helps.
Trying to stick with inheritance in such situation makes me think that you are trying to use the wrong tool for your job.
You may achieve code reuse by favoring composition over inheritance and refactor your code as follow:
public sealed class Company
{
public void Dowork1()
{
//logic
}
public void Dowork2()
{
//logic
}
public void Dowork3()
{
//logic
}
}
public sealed class ItCompany
{
private readonly Company _company;
public ItCompany(Company company) => _company = company;
//Call DoWork1 and DoWork3 whenever you want from _company
}
public sealed class ManagementCompany
{
private readonly Company _company;
public ManagementCompany (Company company) => _company = company;
//Call DoWork2 and DoWork3 whenever you want from _company
}
This code has the same benefits of code reuse than inheritance but without the burden of trying to hide normally public inherited methods.
Also you can be sure that no one ever can alter Company's behavior (such a central piece of logic for you) since the class is sealed, unlike solutions trying to stick with inheritance that allow overriding DoworkX() methods.
So, Im studying Design Patterns, and Im studying the Template Method.
From how I understood it, It is a set of Methods (The skeleton) wrapped in a Method (Operation) on an Abstract Class (If done via heritage), where different Concrete Subclasses write their own implementation of those methods (Not all of them).
But I have a doubt, what happens if some, maybe 2 methods of the skeleton are not used by a certain concretion?, Here I have an example I made, which totally violates the SRP:
using System;
namespace TemplatePattern
{
public abstract class Coffee
{
public void MakeCoffee()
{
HeatWater();
PutCoffee();
if (HaveMilk())
{
PutMilk();
}
if (HaveGratedChocolate())
{
PutGratedChocolate();
}
PutSweetener();
ServeCoffee();
}
internal void HeatWater()
{
Console.WriteLine($"I heated the water");
}
internal void ServeCoffee()
{
Console.WriteLine($"Coffee Served");
}
internal void PutCoffee()
{
Console.WriteLine("I put 2 spoons of Coffee");
}
internal virtual void PutMilk() { }
internal virtual void PutGratedChocolate() { }
internal abstract void PutSweetener();
public virtual bool HaveMilk()
{
return false;
}
public virtual bool HaveGratedChocolate()
{
return false;
}
}
}
Concrete class SimpleCoffeeWithMilk:
using System;
namespace TemplatePattern
{
public class SimpleCoffeWithMilk : Coffee
{
public override bool HaveMilk()
{
return true;
}
internal override void PutSweetener()
{
Console.WriteLine($"I put 1 spoon of Sugar");
}
internal override void PutMilk()
{
Console.WriteLine($"I put 100Cc of Milk");
}
}
}
Another Concrete class:
using System;
namespace TemplatePattern
{
public class CoffeeWithChocolate : Coffee
{
public override bool HaveGratedChocolate()
{
return true;
}
internal override void PutGratedChocolate()
{
Console.WriteLine("Put Chocolate");
}
internal override void PutSweetener()
{
Console.WriteLine($"Put Sugar");
}
}
}
Main Entry Point:
using System;
namespace TemplatePattern
{
class Program
{
static void Main(string[] args)
{
SimpleCoffeWithMilk coffeWithMilk = new SimpleCoffeWithMilk();
CoffeeWithChocolate coffeeWithChocolate = new CoffeeWithChocolate();
coffeWithMilk.MakeCoffee();
Console.WriteLine("\n\n");
coffeeWithChocolate.MakeCoffee();
Console.ReadLine();
}
}
}
The idea is to get rid of those If's Statements, is there any way of doing this with the template method, where some of the methods execute depending of the concrete class?
I was thinking in creating interfaces like ICoffeeWithMilk with PutMilk() method on it and implement that interface on my SimpleCoffeeWithMilk concrete class, but watching the UMLs, the Template Method for what I saw does not rely on Interfaces.
Edit: Now that I think of it, I cant use an interface as, the template method relates to a set of ordered methods in the operation, so these methods are out of the operation.
Edit 2: Ok, I was thinking that PutMilk() and PutGratedChocolate() are Hook methods, maybe I can make them abstract methods and in the concrete classes dont put any implementation, not even the not implemented exception class. With this they can exists without any if statements in my Template Method. But I think, Im not sure this violates the Liskov Substitution Principle.
Edit 3: Well... I was thinking, again, and came to the conclusion that, if those methods are virtual and have no implementation on the abstract class, I shouldn't worry about asking, if the concrete class uses that method, then you write the algorithm, if you don't use it, then dont, and it will do nothing, it will go to the next step.
Just remove the if statements and let the concretions make the decision by implementing them, like so:
public abstract class Coffee
{
public void MakeCoffee()
{
PutMilk();
}
protected abstract void PutMilk();
}
public class SimpleCoffeWithMilk : Coffee
{
public override void PutMilk()
{
Console.WriteLine($"I put 100Cc of Milk");
}
}
public class SimpleCoffeNoMilk : Coffee
{
public override void PutMilk()
{
//no op
}
}
As to your concern with this solution, I don't think it violates Liskov. The LSP states that a subtype must be substitutable for any other inheritors of it's base class, which these cases are. You can call PutMilk for either, and they will put all of the milk that is appropriate to their specialization of the interface. None of that variation impacts the calling method. To be clear, you can contrive an example that would do that, but in this case you are not going to run into a problem there.
You can transfer the selection statement (if statement in this case) to your templates but cannot get rid of them if you need to check some condition. Weather you do it like this
public abstract class Coffee
{
public abstract bool HaveMilk();
public void MakeCoffee()
{
if (HaveMilk())
{
PutMilk();
}
}
}
public class SimpleCoffeWithMilk : Coffee
{
public bool HaveMilk()
{
return true;
}
public override void PutMilk()
{
Console.WriteLine($"I put 100Cc of Milk");
}
}
or like this
public abstract class Coffee
{
public void MakeCoffee()
{
PutMilk();
}
}
public class SimpleCoffeWithMilk : Coffee
{
public bool HaveMilk()
{
return true;
}
public override void PutMilk()
{
if (HaveMilk())
{
Console.WriteLine($"I put 100Cc of Milk");
}
}
}
I strongly believe the latter is what you are looking for.
Good day,
I have a base class with a virtual method that needs to be overridden per implementation, but I would like to call the base method first before overriding.
Is there a way to accomplish this without having to actually call the method.
public class Base
{
public virtual void Method()
{
//doing some stuff here
}
}
public class Parent : Base
{
public override void Method()
{
base.Method() //need to be called ALWAYS
//then I do my thing
}
}
I cannot always rely that the base.Method() will be called in the override, so I would like to enforce it somehow. This might be a design pattern of some kind, any approach to accomplish the result will do.
One way is to define a public method in the base class, which calls another method that can be (or must be) overridden:
public class Base
{
public void Method()
{
// Do some preparatory stuff here, then call a method that might be overridden
MethodImpl()
}
protected virtual void MethodImpl() // Not accessible apart from child classes
{
}
}
public class Parent : Base
{
protected override void MethodImpl()
{
// ToDo - implement to taste
}
}
You can use the decorator design pattern, applying this pattern you can attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality:
public abstract class Component
{
public abstract void Operation();
}
public class ConcreteComponent1 : Component
{
public override void Operation()
{
//logic
}
}
public abstract class ComponentDecorator : Component
{
protected readonly Component Component;
protected ComponentDecorator(Component component)
{
Component = component;
}
public override void Operation()
{
if(Component != null)
Component.Operation();
}
}
public class ConcreteDecorator : ComponentDecorator
{
public ConcreteDecorator(Component component) : base(component)
{
}
public override void Operation()
{
base.Operation();
Console.WriteLine("Extend functionality");
}
}
Hope this helps!
This question already has answers here:
Interface vs Base class
(38 answers)
Closed 8 years ago.
I'm a bit new to OO programming and I'm trying to understand all facets of this kind of practice : inheritance, polymorphism and such, but there's a thing my brain DOESN'T WANT to fully understand: Interfaces.
I can understand the benefits of using interfacing instead of class-inheritance (mostly because a class can't inherit from multiple parents) but here's where I'm stuck:
Let's say I have something like this:
/** a bunch of interfaces **/
public interface IMoveable
{
void MoveMethod();
}
public interface IKilleable()
{
void KillMethod();
}
public interface IRenderable()
{
void RenderMethod();
}
/** and the classes that implement them **/
public class ClassOne : IMoveable
{
public void MoveMethod() { ... }
}
public class ClassTwo: IMoveable, IKilleable
{
public void MoveMethod() { ... }
public void KillMethod() { ... }
}
public class ClassThree: IMoveable, IRenderable
{
public void MoveMethod() { ... }
public void RenderMethod() { ... }
}
public class ClassFour: IMoveable, IKilleable, IRenderable
{
public void MoveMethod() { ... }
public void KillMethod() { ... }
public void RenderMethod() { ... }
}
By using interfaces here, I would have to declare MoveMethod, KillMethod and RenderMethod each time, in each classes... That means duplicating my code. There must be something wrong, because I don't find this really practical.
So should I implement interfaces only on a few classes? Or should I find a way to mix inheritance and interfaces?
Interfaces are like a contract to a class.. If some class states that it supports such an interface, it must have it's method defined as you properly sampled. Interfaces are great to expose common things that don't easily cross different class implementations.
Now, from your samples, you may be best to do a combination to prevent duplicate code by subclassing from a class and ALSO an interface. So you can get parent-structure code constant and expand as needed.
/** Based on same interfaces originally provided... and the classes that implement them **/
public class ClassOne : IMoveable
{
public void MoveMethod() { ... }
}
public class ClassTwo: ClassOne, IKilleable
{
// Move Method is inherited from ClassOne, THEN you have added IKilleable
public void KillMethod() { ... }
}
public class ClassThree: ClassOne, IRenderable
{
// Similar inherits the MoveMethod, but adds renderable
public void RenderMethod() { ... }
}
public class ClassFour: ClassTwo, IRenderable
{
// Retains inheritance of Move/Kill, but need to add renderable
public void RenderMethod() { ... }
}
I have an Interface:
public interface IMessager
{
void ShowMessage();
}
Is there any way to implement this interface using extension methods?
public static class Extensions
{
public static void ShowMessage(this MyClass e)
{
Console.WriteLine("Extension");
}
}
and a class that implement it:
public class MyClass:IMessager
{
public void ShowMessage()
{
ShowMessage(); // I expect that program write "Extension" in console
}
}
But when I run the program I get the System.StackOverflowException.
The code you posted is just a method calling itself recursively (hence the StackOverflowException).
I'm not entirely sure what you're trying to accomplish but to answer your question
Is there any way to implement this interface using extension methods?
No.
To be a bit more pragmatic about this though, if your aim is to only write your method once you have a few options:
1. Call the extension explicitly
public class MyClass:IMessager
{
public void ShowMessage()
{
Extensions.ShowMessage(this);
}
}
although as pointed out in comments, this basically defeats the point of using the extension method. Additionally there is still "boiler-plate code" such that every time you implement your interface you have to call the static method from within the method (not very DRY)
2. Use an abstract class instead of an interface
public abstract class MessengerBase
{
public void ShowMethod() { /* implement */ }
}
public class MyClass : MessengerBase {}
...
new MyClass().ShowMethod();
This issue with this though is that you can't inherit from multiple classes.
3. Use extension on the interface
public interface IMessenger { /* nothing special here */ }
public class MyClass : IMessenger { /* also nothing special */ }
public static class MessengerExtensions
{
public static void ShowMessage(this IMessenger messenger)
{
// implement
}
}
...
new MyClass().ShowMessage();