Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use generics to define relationships between types?

Tags:

java

generics

Getting into a little bit of confusion here when to use generics. I've looked at Java Generics? but still have a few questions.

Say I have:

public class Honda implements ICar(){
}

public class Opel implements ICar(){
}

Should I use:

public class Person{
    ICar car;
    .
    .
    public Person (ICar c){
        car = c;
    }
}

or

public class Person<T extends ICar>{
    T car;
    .
    .
    public Person(T c){
        car = c;
    }
}

or does it depend on the tasks performed?

Are generics only for aggregation relationships (containers etc); that is, are they just used for collections?

like image 325
mezamorphic Avatar asked Jul 11 '12 16:07

mezamorphic


2 Answers

A person is generally not parameterized with a type of car. Only very annoying persons are defined by their car. Persons change cars too (in time). So I would not parameterize the class, if only for the semantics.

Think about what you try to mimic from the real world, before going into such programming details.

like image 101
Maarten Bodewes Avatar answered Oct 15 '22 09:10

Maarten Bodewes


The distinction isn't always clearcut but here are a few clues:

  1. Try to think of them as "type parameters" (Which they are.) They are associated with the class but they're not necessarily related to it. (Look at the collections framework for example.)
  2. Type parameters can only be used if they don't change throughout an object's lifetime. This sounds quite obvious, but it's a very handy rule to decide when NOT to use generics. (Example is a person who can change cars.)
  3. On the other hand, if not many instances will use the type parameter, if it's too optional, that's not a good idea either. (A lot of people might not have cars at all.)

And finally, a general thought that I found really useful: if you're unsure, don't be afraid to prototype it. Write the code both ways and check which one looks simpler and easier to comprehend. Show it to someone else without any explanations or maybe wait a day or two and then re-read the code yourself. Then throw the other one away. Throwing away code is good.

like image 35
biziclop Avatar answered Oct 15 '22 08:10

biziclop