Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloads vs generic arguments

I have a question. In the framework, that was largely written before the generics came, you often see a function with lots of overloads to do something with different types.

a)

Parse(int data)
Parse(long data)
Parse(string data)
..etc

That seems to be to be ok as it helps keeping code small for each method and so. On the other hand, now with generics you can do the following:

b)

Parse<T>(T data)

and then have some kind of ifs/switch statements with typeof() to try to infer what the types are and what to do with them.

What is best practise? Or what are the ideias that'd help me choose between a) and b)?

like image 598
devoured elysium Avatar asked Aug 24 '09 16:08

devoured elysium


1 Answers

IMHO, if you need if/switch statements, you should better overload. Generics should be used where the implementation does not depend on the concrete type to still reuse it.

So as a general rule:

  • overload if there will be a separate implementation for each type
  • use generics if you can have a single implementation that works for all possible types.
like image 178
Stefan Steinegger Avatar answered Oct 27 '22 00:10

Stefan Steinegger