-1

I have a question regarding generalization. I know when it is needed to be done, but is it worth having an extra class for 1 field?

e.g.:

StatisticsCustomer has fields: Customer customer and int projectCount StatisticsCountry has fields: Country country and int projectCount

What is best in this situation? Creating an extra class just for projectCount or keeping it twice in the two classes?

Nikola
  • 367
  • 1
  • 9
  • 1
    Do you foresee the necessity to add other fields to either which will differ in the near or distant future? If so, they are two separate objects both physically and conceptually and must be treated as such in your code. Better still to have a third class Statistics which holds fields common to all, even if you have no immediate plans to generalize. – Neil Jun 06 '13 at 12:09
  • What are you thinking of doing with projectCount? Wrapping it in it's own class? Also, how are you using it? – Aaron Kurtzhals Jun 06 '13 at 13:27

2 Answers2

4

You are giving far too little context to make that decision.

That said, whether to model things as different classes of the same class has little to do with how many different fields they have, and very much with how you expect to use them in your program. The canonical example is a Point class with Cartesian versus polar coordinates; both will probably have two numeric private fields, but those two pairs of numbers don't mean the same, so it would be terrible to use only one class and try to keep track of what the fields mean - two structurally identical classes that are different according to the type system are clearly the right thing to do.

In your example, all I can say is that I can see no circumstance in which you would want to treat a customer and a country interchangeably, except maybe if all you want to do is create viewgraphs of distributed data where the type of data doesn't matter at all (maybe you work in the U.N. statistics office?). In almost any program I can imagine, customers and countries need to be kept separate, and using the type system to make that distinction is virtually always a good idea.

Kilian Foth
  • 107,706
  • 45
  • 295
  • 310
4

Why not a generic class that works for any type of statistics? So that you always have a single class.

public class Statistics<E>
{ 
   private E element;
   private int projectCount;

   ...
}

Statistic<Customer> myStCustomer = new Statistic<Customer>(...)
Statistic<Country> myStCountry = new Statistic<Country>(...)
mgoeminne
  • 1,158
  • 6
  • 11
  • That may work in specific circumstances, but I'm guessing "Customer" or "Country" don't hold statistical information but rather the object itself, meaning there will be additional fields/methods added in order to extract these statistics. – Neil Jun 06 '13 at 13:03