문제

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?

도움이 되었습니까?

해결책

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>(...)

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 softwareengineering.stackexchange
scroll top