Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 579
Mohitt Avatar asked Jun 17 '15 10:06

Mohitt


People also ask

How do you call a method sequentially in Java?

Method method; try { method = this. getClass(). getMethod("met" + i); method. invoke(this); } catch (SecurityException e) { // ... }

What occurs after a method call is made?

The current method call halts. The arguments of the newly called method are pushed to the stack. The method code runs. After the method finished running, the stack is again emptied and the old stack contents is again restored.

What are the different ways to call a method in Java?

To call a method in Java, simply write the method's name followed by two parentheses () and a semicolon(;). If the method has parameters in the declaration, those parameters are passed within the parentheses () but this time without their datatypes specified.

Is method call in same method?

Yes you can. It is called recursion .


1 Answers

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.

like image 90
Waog Avatar answered Sep 21 '22 03:09

Waog