Determine if the method was first or second?

I want to implement a method that has different behavior when called the first time and then when it is called a second time.

How to do it?

+3


source to share


6 answers


Instance methods in Java have access to the state of a class. Add a variable indicating whether the methods were previously called and use that to choose between the two paths to take inside the method:

class FirstTimeCaller {
    private boolean isFirstTime = true;
    void methodWithState() {
        if (isFirstTime) {
            ... // Do first-time thing
            isFirstTime = false;
        } else {
            ... // Do the other thing
        }
    }
}

      



This works, for example, with methods of the same object: the first call will be made on the first call methodWithState

for each new class object FirstTimeCaller

.

If you want to implement the same behavior for a static method, or if you want the first call on some instance to do a different thing and all subsequent calls to do something else, make a isFirstTime

field static

.

+5


source


You can just create a variable

int counter = 0; // This means the method has not been called yet

      

And when the method is called, just execute this code:



counter++; // Increment by 1 for each new call

      

And you have multiple method calls stored in the "counter" variable, so you can choose what to do with it.

+2


source


To expand the list of possible solutions, you can also consider the State-Pattern :

public class Sandbox {

    private Runnable delegate = () -> {
        System.out.println("First Time");
        delegate = () -> System.out.println("Second Time");
    };

    public synchronized void doIt() {
        delegate.run();
    }
}

      

+2


source


public class MethodLogic implements Callable<String> {
    private boolean called = false;

    public String call() {
        if (!called) {
            called = true;
            return "first";
        } else {
            return "not first";
        }
    }
}

      

Later use it like

Callable<String> method = new MethodLogic();
System.out.println(method.call());
System.out.println(method.call());

      

+1


source


If you are calling in a multithreaded context, you must be careful about concurrent access. You can for example use AtomicBoolean:

public class FirstAndSecondTime {

    private static final AtomicBoolean FIRST_TIME = new AtomicBoolean(true);

    public void perform() {
        if (FIRST_TIME.compareAndSet(true, false)) {
            //execute first time logic here
        } else {
            //execute 2-n time logic here
        }
    }

}

      

+1


source


Using a static class:

public class MyStaticClass {
private static boolean firstTime = true;

public static void myMethod() {
    if (firstTime) {
        System.out.println("First time");
    } else {
        firstTime = false;
        System.out.println("NOT first time");
    }
}

      

}

Then you will use it like this:

MyStaticClass.myMethod(); //-> prints "First time"
MyStaticClass.myMethod(); //-> prints "NOT first time"
MyStaticClass.myMethod(); //-> prints "NOT first time"

      

This is how the Singleton design pattern looks like with lazy initialization:

public final class Singleton {
private static Singleton instance = null;

private Singleton() {}

public static Singleton getInstance() {
    if (instance == null) {
        if (instance == null) {
            instance = new Singleton();
        }
    }
    return instance;
}

      

}

You probably shouldn't be using this (unless you are using it for a Singleton, I guess), but use a field for an object:

public class MyMessagePrinter {
private int counter = 0;

public void printMessage() {
    if (this.counter > 0) {
        System.out.println("Fist time");
    } else {
        System.out.println("NOT first time");
    }
}
}

      

Using it like this:

MyMessagePrinter myPrinter = new MyMessagePrinter();
myPrinter.print(); //-> prints "First time"
myPrinter.print(); //-> prints "NOT first time"
myPrinter.print(); //-> prints "NOT first time"

      

Please note that the code is not thread safe

+1


source







All Articles