Suppose we have the following classes:
As you see, it's an implementation of the State Pattern.
Basically, the Order
class proxies the pay()
and cancel()
method calls to it's concrete OrderState
instance.
After executing their part of business logic, the PendingOrderState
and PaidOrderState
call setState
on the Order
instance to switch to other state.
Question(s):
Is it a code smell, that the public API of the
Order
class is "polluted" bysetState
, a method which should only be used internally by theOrderState
instances?If the answer to the above question is "Yes", then how can the
setState
be encapsulated away from other clients of the Order class (like a hypotheticalCustomer
class, who is only concerned withpay
andcancel
methods of theOrder
)?
Possible Solution:
A possible solution that comes to my mind is introducing some kind of OrderWrapper
class, that would wrap the Order
class and only expose the pay()
and cancel()
methods.
P.S
Sorry for the sloppy attempt at UML :).