I'm working on an engine which is meant to be configurable by the user (not end user, the library user) to use different components.
For example, let's say the class Drawer
must have an ITool
, Pencil
or Brush
, and an IPattern
, Plain
or Mosaic
. Also, let's say a Brush
must have an IMaterial
of either Copper
or Wood
Let's say the effect of choosing Pencil
or Brush
is really drastically different, and the same goes for the IPattern
type. Would it be a bad idea to code the Drawer
class with Generic concepts like this :
public class Drawer<Tool, Pattern> where Tool: ITool where Pattern : IPattern { ... }
public class Brush<Material> where Material : IMaterial { ... }
One could then use that class like :
Drawer<Pencil, Mosaic> FirstDrawer = new Drawer<Pencil, Mosaic>();
Drawer<Brush<Copper>, Mosaic> SecondDrawer = new Drawer<Brush<Copper>, Mosaic>();
I mostly used generic for collections and such and haven't really see generics used for that kind of thing. Should I?
Generic methods in non-generic classYes, you can define a generic method in a non-generic class in Java.
A generic class can extend a non-generic class.
The Cons of Generic DrugsMedicines can look different: Trademark laws prohibit a generic drug from looking exactly like its brand-name version, so if you've switched to a generic drug, its shape, color or size may be different from what you're accustomed to taking.
The generic collections are type-safe and checked at compile-time. These generic collections allow the datatypes to pass as parameters to classes. The Compiler is responsible for checking the compatibility of the types.
It does not really make sense using generics unless the engine you are creating have methods with arguments or return types of the generic type. I.e. you would expect there to be a propertie and methods like
public <Material> Material { get; }
public void Draw(<Tool> pen);
(I am currently in a Java mode so please correct the C# syntax if wrong!)
From what I can tell from the example you are only using generics for the constructor of the classes. Since you are relying on the interfaces in your implementation the use of generics does not really add value.
Perhaps I am mistaken but generics is really for type safety checked at compile time and to avoid a lot of (risky) type casting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With