Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Generics in a non-collection-like Class

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?

like image 845
Tipx Avatar asked Sep 08 '10 05:09

Tipx


People also ask

Can you have a generic method in a non-generic class?

Generic methods in non-generic classYes, you can define a generic method in a non-generic class in Java.

Can a generic class be a subclass of a non-generic class?

A generic class can extend a non-generic class.

What is the disadvantages of using generics?

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.

Why do we need generics in collection?

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.


1 Answers

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.

like image 183
Christoffer Soop Avatar answered Oct 16 '22 12:10

Christoffer Soop