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?
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.
The distinction isn't always clearcut but here are a few clues:
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.
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