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.
Related
So i'm following a C# beginner tutorial at dotnetcademy.net and one of the exercises is to Implement an abstract class.
and the goals are:
1. Create a class named SpaceStation that is abstract
2. On that abstract class, add a abstract method called FireLaser
3. Create a derived class called DeathStar that implements the FireLaser method to write "Pew pew" to the Console followed by a new line.
the code that you start with is:
using System;
// Implement your classes here
public class Program
{
public static void Main()
{
}
}
so i wrote this but it says on return that "Since 'DeathStar.FireLaser()' returns void, a return keyword must not be followed by an object expression"
but i don't know what else to write, i've tried multiple other things
using System;
// Implement your classes here
public abstract class SpaceStation
{
public abstract void FireLaser();
}
public class DeathStar : SpaceStation
{
public override void FireLaser()
{
return Console.WriteLine("Pew pew");
}
}
public class Program
{
public static void Main()
{
}
}
So if anybody has a solution so i can reflect it on what i wrote that would be nice or if anybody can say what it should be instead.
Remove the return statement from the overridden FireLaser method:
public class DeathStar : SpaceStation
{
public override void FireLaser()
{
Console.WriteLine("Pew pew");
}
}
A method marked as void does not return anything. The return keyword is usually used to return a result from a method. Therefore it usually does not make sense in a void method. Removing the return keyword from your statement will resolve your compiler error.
public class DeathStar : SpaceStation
{
public override void FireLaser()
{
Console.WriteLine("Pew pew");
}
}
Note that the return keyword can be used in a void method to end the method. However, its usage is generally discouraged because it can result code that returns from multiple places and this can be confusing. When used in this manner, you still do not return an actual value. return would be the only part of the statement. Consider the following code:
public void ProcessSomeWork(SomeWork work)
{
if(work.IsCompleted)
{
return;
}
work.DoSomething();
DoSomethingElseToWork(work);
}
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!
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.
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 a abstract class named Vehicle:
public abstract class Vehicle {
public void run() {
addToRunningVehicleList();
}
}
I want that every classes that extends Vehicle must call super.run() if they override run method. For example:
public class Car {
#Override
public void run() { // Error here because does not call super.run()
carRunningAnimation();
}
}
Is it possible in OOP concept, or Java/C#?
EDIT: Following Petar Ivanov, I have this code:
public abstract class Vehicle {
public final void run() {
Log.e("Run", "Add To List");
runImp();
}
public void runImp() {}
}
public class Car extends Vehicle {
#Override
public void runImp() {
Log.e("Run", "Run in Car");
}
}
However, it's not very good for public APIs. When extending Vehicle, the end-users must override runImp, but then they have to call run() method, so I have to make public both run and runImp, which make nothing better.
Here is how I would do it (C#):
public abstract class Vehicle {
public void Run() {
//code that will always run
addToRunningVehicleList();
//code that can be overriden
RunImpl();
}
protected virtual void RunImpl() { }
}
public class Car : Vehicle {
protected override void RunImpl() {
carRunningAnimation();
}
}
You can make the RunImpl protected to make sure it can't be called outside the subclasses of Vehicle.
If you need to require certain code to run in addition to the child class' implementation, perhaps you need to split this into multiple methods:
(C# example)
public abstract class Vehicle
{
public void Run()
{
// Code that always runs before...
RunCore();
// Code that always runs after...
}
protected virtual void RunCore()
{
}
}
Remember who you are designing for. If it's an internal piece of code a comment will suffice. If it's a public API and you want people to inherit then you need to write a piece of documentation telling them to do it.
In C# you can do some sneaky stuff with virtual and non-virtual methods but in Java as all inheritence is virtual it's a lot harder to enforce this without using an abstract base class.
Using an ABT may limit your ability to provide further inheritence and force modification of other code.