I would like to know which of the following 2 versions is the "more correct" according to the cohesion principle.
Version #1: my main thought was answering the question (what can/does a customer do?)
Version #2: here I was thinking that methods relating to orders such as(view order, cancel order...) should be defined in the class order too.
CodePudding user response:
Cohesion is about related responsibilities and clear purpose. The more different, unrelated responsibilities, the less cohesive a class is (see also this other SO question). A pragmatic advice from OOP pioneer Rebecca Wirfs-Brock and Alan McKean is in their book Object Design (which they now made available for free):
A good test of whether an object is well formed is that its responsibilities form a cohesive unit. Does it stick to its purpose? Are its responsibilities clearly stated? Do they match its role?
Option #1 is not cohesive. The responsibilities of Customer
is about profile management, authentication, and order management. One could claim that the two first are related, but the last one does clearly not belong there. By the way, option #1 does not comply with the single responsibility principle, nor even with fundaments of encapsulation (Customer
can access Order
's internals, worse: it has to). This last observation let us conclude that Order needs the Customer for managing it, and Customer
could not work with a different Order
, which shows a strong coupling in addition to low cohesion.
Option #2 is cohesive. Customer
is only about managing the customer (including login and logout), and Order
is only about managing the orders.
As a side remark: your option #1 is not realistic from an UML point of view, since all the properties are private, but no operation exist to access them ;-)