Java Design Issue: Enforce method call sequence

后端 未结 12 559
青春惊慌失措
青春惊慌失措 2021-02-02 05:27

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

12条回答
  •  囚心锁ツ
    2021-02-02 05:49

    I suggest something like:

    interface WatchFactory {
        Watch startTimer();
    }
    
    interface Watch {
        long stopTimer();
    }
    

    It will be used like this

     Watch watch = watchFactory.startTimer();
    
     // Do something you want to measure
    
     long timeSpentInMillis = watch.stopTimer();
    

    You can't invoke anything in wrong order. And if you invoke stopTimer twice you get meaningful result both time (maybe it is better rename it to measure and return actual time each time it invoked)

提交回复
热议问题