Kobby Khaisian
Kobby Khaisian

Reputation: 51

How to decide whether a method should belong to which class?

I have 3 classes:

The product_list class has an array list, which stores product objects.

If I have a viewProduct method, it should belong to customer class or product_list class?

With my own concept, a viewProduct method should belong to customer class, because customer views products. But in code-wise, how a method in customer class gets data from product_list class?

Upvotes: 2

Views: 1024

Answers (1)

peterh
peterh

Reputation: 1

A class is a data structure, bound together with the algorithms working on it.

Thus, if you decide where to put a method, the rule of thumb is this: select the class, on whose data structures it works the most. If you do it well, it should not even access the data members of other classes directly, only their methods.

Also from the name of the method is it visible, that you are right, that viewProduct should belong to customer: if it would belong to a product, then the viewProduct name would be redundant. Then a view name would be better.

You example does not say anything, how customers relate to specific products. For example, if you would develop a webshop, then the customers would likely choose a product from a list which your controllers generated for them.

Your specification lacks the mechanism, how customers relate to products. Think on it, and you will know the answer.

Upvotes: 1

Related Questions