Java Design Issue: Enforce method call sequence


There is a question which was recently asked to me in an interview.

Problem: There is a class meant to profile the execution time of the code. The class is like:

Class StopWatch {

    long startTime;
    long stopTime;

    void start() {// set startTime}
    void stop() { // set stopTime}
    long getTime() {// return difference}


The client is expected to create an instance of the StopWatch and call methods accordingly. User code can mess up the use of the methods leading to unexpected results. Ex, start(), stop() and getTime() calls should be in order.

This class has to be "reconfigured" so that user can be prevented from messing up the sequence.

I proposed use of custom exception if stop() is called before start(), or doing some if/else checks, but interviewer was not satisfied.

Is there a design pattern to handle these kind of situations?

Edit: The class members and method implementations can be modified.

Best Solution

First there is the fact that implementing an own Java profiler is a waste of time, since good ones are available (maybe that was the intention behind the question).

If you want to enforce the correct method order at compile time, you have to return something with each method in the chain:

  1. start() has to return a WatchStopper with the stop method.
  2. Then WatchStopper.stop() has to return a WatchResult with the getResult() method.

External Construction of those helper classes as well as other ways of accessing their methods have to be prevented of course.