Search code examples
javaoopdesign-patterns

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.


Solution

  • We commonly use StopWatch from Apache Commons StopWatch check the pattern how they've provided.

    IllegalStateException is thrown when the stop watch state is wrong.

    stop

    public void stop()

    Stop the stopwatch.

    This method ends a new timing session, allowing the time to be retrieved.

    Throws:

    • IllegalStateException - if the StopWatch is not running.

    Straight forward.