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.
Method method; try { method = this. getClass(). getMethod("met" + i); method. invoke(this); } catch (SecurityException e) { // ... }
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.
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.
Yes you can. It is called recursion .
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:
start()
has to return a WatchStopper
with the stop method.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With