I have been using a pattern in a lot of places (mainly C#) that I would like to know the name of.
Here is an example of it in C#:
public enum ThingType
{
A,
B,
C
}
public interface IThing
{
ThingType Type
{ get; }
}
public class ThingA : IThing
{
public ThingType Type => ThingType.A;
}
public class ThingB : IThing
{
public ThingType Type => ThingType.B;
}
public class ThingC : IThing
{
public ThingType Type => ThingType.C;
}
As long as all implementations of IThing
have a corresponding member in the enum, I can safely cast to the actual type of an IThing
after checking the value of IThing.Type
.
public void HandleThing(IThing thing)
{
switch(thing.Type)
{
case ThingType.A:
ThingA a = (ThingA)thing;
// Doing something with a...
break;
case ThingType.B:
ThingB b = (ThingB)thing;
// Doing something with b...
break;
case ThingType.C:
ThingC c = (ThingC)thing;
// Doing something with c...
break;
}
}
I apologize if this question is a duplicate, I went through a few pages of search results for multiple different search phrases and I couldn't find this question already.
This pattern is called type discriminator.
It was very useful before OOP languages, for example to simulate polymorphic types with the help of discriminated unions. It is still heavily used and justified:
This pattern is however not to be recommended in OOP as a first choice if you're not in one of the situation above. It might lead to an antipattern when it encourages people to think in a case-based manner with lots of specific details instead of abstracting the problem and using a truly polymorphic design:
X
class implementations are in a separate library so they don't even know that there is a GUI at all. Adding a common interface method would require adding a dependency on the GUI library and passing the GUI into the interface method on X. The requirements of the library preclude having any assembly references to a specific GUI framework. — Mar 05, 2020 at 18:55 External links referenced by this document: