During a recent interview I was asked to write a program that takes a list of different vehicles, or whatever, that implement a honk interface, use an abstract class, and then have a different honk for the different vehicles. This is what I came up with so far, and it works fine as long as I call the methods independently. But when I try to put them into an IEnumerable, and then iterate through, it displays the honk for the abstract class, not the individual classes. Can someone explain what I am doing wrong?
using System;
using System.Collections.Generic;
namespace ConsoleHonk
{
class Program
{
static void Main(string[] args)
{
var myList = GetVehicles();
//This doesn't display the correct honk
myList.ForEach(x => x.honk());
}
private static List<IHonker> GetVehicles()
{
var myList = new List<IHonker>();
var myTruck = new Truck();
var myCar = new Car();
var myGoose = new Goose();
myList.Add(myTruck);
myList.Add(myGoose);
myList.Add(myCar);
return myList;
}
}
class Goose : HonkClass
{
public virtual void honk()
{
Console.WriteLine("Quack");
}
}
class Car : HonkClass
{
}
class Truck:HonkClass
{
public virtual void honk()
{
Console.WriteLine("Honk-Honk");
}
}
interface IHonker
{
string horn { get; set; }
void honk();
}
public abstract class HonkClass:IHonker
{
public void honk()
{
Console.WriteLine("Beep");
}
public string horn { get; set; }
}
}
In this case you need an abstract base class because it's a requirement for your interview. However, generally in this situation, if you do not have that artificial constraint, you should not use a base class at all. You can just have the individual vehicles directly implement the interface.
In general you shouldn't use a base class without good reason. For one thing, C# supports implementing multiple interfaces but does not support multiple inheritance. So you can have a class implement both interfaces IHonkable and ISteerable, but not inherit from both classes HonkableBase and SteerableBase.
The problem with your code is that the Honk methods aren't overriding the abstract class's, they're hiding it. The difference in behaviour is exactly what you describe:
public class HidingVehicle : HonkClass
{
public void Honk()
{
Console.Writeline("Hiding honk!");
}
}
public class OverridingVehicle : HonkClass
{
public override void Honk()
{
Console.Writeline("Overriding honk!");
}
}
public class HonkClass
{
public virtual void Honk()
{
Console.Writeline("Base honk!");
}
}
Then a method might be:
var myHidingVehicle = new HidingVehicle();
var myOverridingVehicle = new OverridingVehicle();
myHidingVehicle.Honk(); //"Hiding honk!"
myOverridingVehicle.Honk(); //"Overriding honk!"
HonkClass hiddenVehicle = myHidingVehicle;
HonkClass overridenVehicle = myOverridingVehcile;
hiddenVehicle.Honk(); //"Base honk!"
overridenVehicle.Honk(); //"Overriding honk!"
As you can see from the code, the difference is in the overriding keyword.
Hiding can be deliberate, but it's very rarely desirable as it breaks polymorphism. If it you do want to hide, and you're sure there isn't a better option, you can use the new keyword in the method declaration to hide the compiler warning and make it clear to anyone reading the code that you're hiding.
Related
I am writing a tranformer that takes some input and gives an output.I need to call a specific tranformer based on my input type.
public static myentrypoint( template t);
{
//I could do something like this.
switch(t)
{
case t1:
transformt1(..);
case t2:
transformt1(..);
....
}
}
Trasform1 : Itransform
{
tranform1(...);
}
Trasform2 : Itransform
{
tranform2(...);
}
I need to map which function to call based on what my template is. I can do a switch but are there more cleaner ways to do this using some design patterns ? I was thinking a of writing a static dictionary. I am new to OOP so any suggestions would be great.
If template is a class, and each template potentially has a different transform, then why not just include the transform function inside of your template class?
public static myentrypoint( ITemplate t);
{
t.transform();
}
The way that I do these types of situations is through the use of Generics. (Shameless self-promotion of a blog post)
Basically, you'll have your base class set up like this:
public abstract class Transformer<T>
where T : Template
{
public abstract void Transform(T item);
}
Then you derive for each of your types like this:
public class Transformer1 : Tansformer<Template1>
{
public void Transform(Template1 item)
{
}
}
public class Transformer2 : Transformer<Template2>
{
public void Transform(Template2 item)
{
}
}
Then you'll just need a factory to give you the correct Transformer.
public class TransformFactory
{
public Transformer<T> GetTransformer<T>(T item)
{
if (item is Template1)
return new Transformer1();
else if (item is Template2)
return new Transformer2();
// ...
}
}
The benefit of this approach is that you'll be able to encapsulate all behavior on that specific type in the concrete implementations. If there is any common behavior on them all, you can do that in the abstract base.
Invoking methods based on a parameter without switch-case statements in C#
In OOP, based on the [open/close principle] which says that software entities such as classes and functions should be open for extension, but closed
for modification.
Methods which use switch-case statement would call this principle into question. In order to implement this principle inside the codes without
causing changes in their functionality.
We use a pattern named "Delegate Dictionary Pattern".
For example, we have an entity named Template that keep input values as well as some of Transform classes for processing this Template.
Template class for keeping input value
public class Template
{
public int TransformNo { get; set; }
public string Title { get; set; }
}
ITransform interface for transform abstract
public interface ITransform
{
void Do(Template template);
}
Transform1 as a concrete class of ITransform
public class Transform1 : ITransform
{
public void Do(Template template)
{
Console.WriteLine($"Transform : {template.TransformNo}, TemplateTitle : { template.Title}");
}
}
Transform2 as a concrete class of ITransform
public class Transform2 : ITransform
{
public void Do(Template template)
{
Console.WriteLine($"Transform : {template.TransformNo}, TemplateTitle : { template.Title}");
}
}
TransformCordinator class for coordinating template of *ITransformer**
public class TransformCordinator
{
Dictionary<int, Action<Template>> transformMap = new Dictionary<int, Action<Template>>();
public TransformCordinator()
{
transformMap.Add(1, x => new Transform1().Do(x));
transformMap.Add(2, x => new Transform2().Do(x));
}
public void Do(Template template)
{
transformMap[template.TransformNo](template);
}
}
// example
class Program
{
static void Main(string[] args)
{
var transformCordinator = new TransformCordinator();
transformCordinator.Do(new Template() { TransformNo = 1, Title = "Hi!" });
Console.ReadLine();
}
}
I was tinkering around with some code and out of curiosity I wanted to know how I can tackle this problem should I ever stumble upon it.
The problem is that I want to have an Interface and a generic (Factory) class that can only create objects that inherit from that interface. There exists concrete classes which implement that interface which are intended to be used by the generic factory; however, I do not want anyone to add to create their own implementations of the interface but I do want them to be able to create their own instances of the objects which inherit from that interface.
I have a piece of code which illustrates what I am trying to do; however, it does not compile because of the inconsistent accessibility. Here is a piece of code which illustrates what I am inquiring about
using System;
using InterfaceTest.Objects;
namespace InterfaceTest
{
class Program
{
static void Main(string[] args)
{
CreatureFactory<Person> p = new CreatureFactory<Person>();
p.Create();
Console.ReadLine();
}
}
}
namespace InterfaceTest.Objects
{
interface LivingCreature
{
int Age { get; set; }
}
public class Person : LivingCreature
{
public int Age
{
get;
set;
}
}
public class CreatureFactory<T> where T : class, LivingCreature, new()
{
public T Create()
{
return new T();
}
}
}
Im not sure if it is possible. I am running into a unique issue dealing with a clients api.
I am needing to extend a class and add a bool property that does not exist in the base class.
below is an example of what I am trying to accomplish.
public class baseClass
{
//.. No Editable Access
}
public class Extended
{
public bool flaggedAsDeleted(this baseClass bc)
{
//Idealy was looking for get; set; but I know that don't work
return true;// Need to know if possible to set property on baseClass or Alternative
}
public void flagAsDeleted(this baseClass bc)
{
flaggedAsDeleted = true;
}
}
public class program
{
public void doit()
{
baseClass bc = new baseClass();
bc.flagAsDeleted();
}
}
If you're trying to actually extend a class, you do it like this:
public class BaseClass
{
//.. No Editable Access
}
public class Extended : BaseClass
{
public bool FlaggedAsDeleted { get; set; }
}
If you're trying to add data to an existing class, you have two options:
Inheritance - as seen above.
Encapsulation - create a new object that holds an instance of the type you're adding to.
C# provides a feature called Extension Methods, which allows you to seemingly add methods to existing classes. However, these are really just syntactic sugar, as you're still constrained to the class's public API.
public class BaseClass
{
public int Value { get; set; }
}
public static class ExtensionMethods
{
public static void Increment(this BaseClass b)
{
b.Value += 1;
}
}
Extension methods do not allow you to add data to an existing class though.
This is not unique. This is a common problem solved using a Design Pattern called decorator.
I try to achieve the following: I have an interace called IAxis that forces my class TheAxis to have certain methods. In addition I want to implement some kind of abstract class based on a parameter. To explain this will write it down in code:
class TheAxis : IAxis
{
public TheAxis(){ }
public void IMoveToPos(int pos) {} //This is forced by the Interface
}
As the instance of this class is called it should be able to choose which methods to include, similar to virtual methods but not overriding existing methods but adding already coded ones from another class. I am looking for something like this:
abstract class GateAxis
{
public void CloseGate() { IMoveToPos(0); }
}
abstract class XAxis
{
public void MoveToStart() { IMoveToPos(100); }
}
TheGateAxis = new Axis() as GateAxis;
Now I want to be able to use TheGateAxis.Closegate(); but NOT TheGateAxis.MoveToStart();
if I call
TheXAxis = new Axis() as XAxis;
I want to be able to use TheXAxis.MoveToStart(); but NOT TheXAxis.CloseGate();
The Methods Given in XAxis or GateAxis donĀ“t need any methods from TheAxis except the onces given by the interface.
Is it possible to do somethign like that? To add Methods to a class depending on a parameter given while instancing the class?
I hope you get what I am trying to do as I do hard to explain.
Best,
Kevin
Well, if you want classes sharing few methods from a base class, and other being separate, you could do
//an interface (optional)
public interface IAxis {
void MoveToPos(int pos);
}
public abstract class AxisBase : IAxis {
public void MoveToPos(int pos) {
//implementation
}
}
//optionally you can do an IGateAxis interface, inheriting (or not) from IAxis
public interface IGateAxis : IAxis {
void CloseGate();
}
//classes inheriting from AxisBase, implementing IGateAxis
public class GateAxis : AxisBase, IGateAxis {
public void CloseGate() {
MoveToPos(0);
}
}
//another interface, not inheriting from IAxis
public interface IXAxis {
void MoveToStart();
}
//another class inheriting from AxisBase
public class XAxis : AxisBase, IXAxis {
public void MoveToStart() {
MoveToPos(100);
}
}
usage
var gateAxis = new GateAxis();
gateAxis.CloseGate();
//and you can do
gateAxis.MoveToPos(250);
var xAxis = new XAxis();
xAxis.MoveToStart();
//and you can do
xAxis.MoveToPos(40);
with the IGateAxis interface
IGateAxis gateAxis = new GateAxis();
gateAxis.CloseGate();
gateAxis.MoveToPos(1);
with the IXAxis interface
IXAxis xAxis = new XAxis();
gateAxis.MoveToStart();
//but you can't do
//gateAxis.MoveToPos(10);
//as IXAxis doesn't know about this method.
// super class
abstract class TheAxis : IAxis {
public TheAxis() { }
public void IMoveToPos(int pos) { } //This is forced by the Interface
}
abstract class GateAxis : TheAxis {
public virtual void CloseGate() { IMoveToPos(0); }
}
abstract class XAxis : TheAxis {
public virtual void MoveToStart() { IMoveToPos(100); }
}
Now if you derive a class from GateAxis it'll only have access to the interface methods and the methods from GateAxis. Same goes for TheAxis.
Dynamically adding methods, and removing them is not something that you can do in "normal" C# . There is no any OOP pattern that can simulate this.
What you can do, is using ExpandoObject to be able to achieve exactly what you're trying to achieve.
Represents an object whose members can be dynamically added and
removed at run time.
By the way I would not encourage of using it as you are in statical type language domain, so may be it's a godd idea to revise your architectiure a little bit and don't jump in dynamic language domain using C#.
I think the best way to solve this is to use interfaces and a single (base) class.
public interface IAxis {
void MoveToPos(int pos);
}
public interface IGateAxis {
void CloseGate();
}
public interface IXAxis {
void MoveToStart();
}
public class TheAxis : IAxis, IGateAxis, IXAxis {
public TheAxis(){ }
void IAxis.MoveToPos(int pos) {}
void IGateAxis.CloseGate() { ((IAxis)this).MoveToPos(0); }
void IXAxis.MoveToStart() { ((IAxis)this).MoveToPos(100); }
}
IGateAxis gateAxis = new ThisAxis();
gateAxis.CloseGate();
IXAxis xAxis = new ThisAxis();
xAxis.MoveToStart();
This way you can specify which methods are available to certain types of axis. Also, you could force the creation of axis through a factory pattern, or even a single static method, just to facilitate the creation of axis.
Assuming you have more than 3 methods, the easiest way that I see is to simply create a proxy that acts as a chain of responsibility:
public class AxisProxy : IAxis
{
public AxisProxy(params IAxis[] implementations) {
this.implementations = implementations;
}
private IAxis[] implementations;
public virtual void CloseGate()
{
foreach (var item in implementations)
{
try { item.CloseGate(); } catch (NotSupportedException) {}
}
throw new NotSupportedException();
}
public virtual void MoveToStart()
{
foreach (var item in implementations)
{
try { item.MoveToStart(); } catch (NotSupportedException) {}
}
throw new NotSupportedException();
}
}
You can create a base implementation of Axis to make sure all default implementations throw the exception. Derived implementations implement specific functionality.
You can then use it by simply calling
IAxis myAxis = new AxisProxy(new GateAxis(), new XAxis());
NOTE: In this case I would seriously consider changing the types to 'bool'; if you call these methods frequently, exception performance will add up... Also, since the NotSupportedException is not going to change, you can keep a per-method list to remove implementations that throw.
I have been going through some code seen that a colleague of mine is using 'marker classes' to control program logic (see contrived example below). It seems to work well, and the code reads really nicely, but there is just something about it that smells...
namespace ConsoleApplication4983
{
public class MyClass
{
static void Main()
{
var c = new MyClass();
c.DoSomething(new Sequential());
c.DoSomething(new Random());
}
public void DoSomething(ProcessingMethod method)
{
if (method is Sequential)
{
// do something sequential
}
else if (method is Random)
{
// do something random
}
}
}
public class ProcessingMethod {}
public class Sequential : ProcessingMethod {}
public class Random : ProcessingMethod {}
}
What would be a better way of achieving the same effect? Enums? Attributes?
Marker interfaces are a better practice as they offer much more flexibility.
However in this specific case I think that virtual dispatch is a better solution.
using System;
namespace ConsoleApplication4983
{
public class MyClass
{
static void Main()
{
var c = new MyClass();
c.DoSomething(new Sequential());
c.DoSomething(new Random());
}
public void DoSomething(ProcessingMethod method)
{
method.Foo();
}
}
public class ProcessingMethod
{
public virtual void Foo() { }
}
public class Sequential : ProcessingMethod
{
public override void Foo() { }
}
public class Random : ProcessingMethod
{
public override void Foo() { }
}
}
What you'd like to do is replace this with a strategy pattern. A strategy defines how something is done -- i.e., an algorithm.
public interface IProcessingMethod
{
void Process();
}
public class SequentialProcess : IProcessingMethod
{
public void Process( IProcessable obj )
{
do something sequentially with the obj
}
}
public class ParallelProcess : IProcessingMethod
{
public void Process( IProcessable obj )
{
do something in parallel with the obj
}
}
public interface IProcessable
{
void Process( IProcessingMethod method );
}
public class MyClass : IProcessable
{
public void Process( IProcessingMethod method )
{
method.Process( this );
}
}
...
var obj = new MyClass();
obj.Process( new SequentialProcess() );
Now if I have a new type of ProcessingMethod, I simply need to create the class for that method and change the code that determines what processing method is injected to the Process method of my IProcessable object.
He was almost there, but not quite, and that's probably what you're seeing. The if statement on the type is the bad smell. The do something should have been on the ProcessingMethod base class and each type that extended it should have their own version.
public void DoSomething(ProcessingMethod method) {
method.DoSomething();
}
I see that this question is old, but I feel that all the answers missed the point.
If the example fully illustrates the extent of the required functionality, then the appropriate construct to use here would be an Enum type. Enum types are value types; they function essentially like named numerical constants, with great IDE autocomplete support. Here is the example modified to use an Enum type:
namespace ConsoleApplication4983
{
public class MyClass
{
static void Main()
{
var c = new MyClass();
c.DoSomething(ProcessingMethod.Sequential);
c.DoSomething(ProcessingMethod.Random);
}
public void DoSomething(ProcessingMethod method)
{
if (method == ProcessingMethod.Sequential)
{
// do something sequential
}
else if (method == ProcessingMethod.Random)
{
// do something random
}
}
}
public enum ProcessingMethod
{
Sequential,
Random
}
}
The other answers are making reference to more elaborate patterns. I think they read too much into the term "marker class". Sometimes strategy pattern, virtual dispatch etc. are a good way to go, but in this case I think an Enum is the simplest improvement to be made to this code.
How about delegating the processing logic to the specific subclass? ProcessingMethod would have some abstract method that is implemented by each subclass.
public void DoSomething(ProcessingMethod method)
{
method.Process();
}
public abstract class ProcessingMethod
{
public abstract void Process();
}
public class Sequental : ProcessingMethod
{
public override void Process()
{
// do something sequential
}
}
public class Random : ProcessingMethod
{
public override void Process()
{
// do something random
}
}
Yeah, this smells bad. If you want to do something parallel:
public class Parallel : ProcessingMethod{}
then you're going to have to change a lot of code.
The Framework Design Guidelines book recommends against using marker interfaces (and presumably marker classes), preferring attributes intead. Having said that, the book does go on to say that using is (as you've done) is much quicker than using reflection to check for an attribute.