Java Design Issue: Enforce method call sequence

后端 未结 12 601
青春惊慌失措
青春惊慌失措 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:59

    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.

提交回复
热议问题