How would you code a washing machine?

Posted by Dan on Stack Overflow See other posts from Stack Overflow or by Dan
Published on 2010-06-18T03:35:12Z Indexed on 2010/06/18 3:43 UTC
Read the original article Hit count: 308

Filed under:
|
|
|

Imagine I have a class that represents a simple washing machine. It can perform following operations in the following order: turn on -> wash -> centrifuge -> turn off. I see two basic alternatives:

A)

I can have a class WashingMachine with methods turnOn(), wash(int minutes), centrifuge(int revs), turnOff(). The problem with this is that the interface says nothing about the correct order of operations. I can at best throw InvalidOprationException if the client tries to centrifuge before machine was turned on.

B)

I can let the class itself take care of correct transitions and have the single method nextOperation(). The problem with this on the other hand, is that the semantics is poor. Client will not know what will happen when he calls the nextOperation(). Imagine you implement the centrifuge button’s click event so it calls nextOperation(). User presses the centrifuge button after machine was turned on and ups! machine starts to wash. I will probably need a few properties on my class to parameterize operations, or maybe a separate Program class with washLength and centrifugeRevs fields, but that is not really the problem.

Which alternative is better? Or maybe there are some other, better alternatives that I missed to describe?

© Stack Overflow or respective owner

Related posts about java

Related posts about .NET