Tutorial :Single method for multiple types?


In cases where you have a function that works for many different custom types with the same implementation, is it ok to use a design pattern like this?:

type1 implicitly casts to type0  type2 implicitly casts to type0  type3 implicitly casts to type0    Operate ( type0 )  

and call:

type1 a  type2 b  type3 c    Operate ( a )  Operate ( b )  Operate ( c )  

Are there any problems with this technique? Performance wise, clarity, etc?

EDIT: Also by implicit cast, I meant custom implemented casts for the type with no data loss, just convenience. Say you have a Pixel class, then sending an instance of this to a method that takes a Point2 automatically casts the pixel to a Point2.


This is a perfectly normal practice.

Performance wise, I don't believe there are any issues.

Clarity wise, because of Intellisense, you're unlikely to have issues with this either.


That's the basis of how interfaces work.

public interface IBlah {      void DoSomething();  }  public class Type1 : IBlah {      void DoSomething() { /* implementation */ }  }  public class Type2 : IBlah {      void DoSomething() { /* implementation */ }  }  public class Type3 : IBlah {      void DoSomething() { /* implementation */ }  }    public class Foo {      void Operate(IBlah blah) {          blah.DoSomething();      }  }  


Casting usually creates a new object, which is unnecessary in this case

The more OOP way to do this would be through a base class or an interface.

class Type1 : IOperatableType {}  class Type2 : IOperatableType {}  class Type3 : IOperatableType {}    void Operate ( IOperatableType a )  


class Type1 : Type0 {}  class Type2 : Type0 {}  class Type3 : Type0 {}    void Operate ( Type0 a )  

The calling method (Operate in this case) depends on using its parameters' methods or properties. If these properties/methods are defined across all types (type1, type2, type3), consider using an interface that defines common functionality. If the implementation of the properties and methods are the same, save yourself from repeated code and consider inheriting from a base class.

Also, when trying to understand your code, developers are more likely to first look at a class diagram, which allows them to see the relationship between classes, or at least the class definition (which will show the base types and implemented interfaces) rather than looking into (implicit/explicit) operators to see which class is castable to which other class.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »