0

I am trying to write a function that is only supposed to be executed once, the second time it is called. The only way that I can think of is:

int i = 0;
if (i == 1) {
    print("executed");
}
i++;

Anybody know of the best practice to write a function like this?

aejhyun
  • 612
  • 1
  • 6
  • 19
  • 4
    This smells like an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Can you tell us what you're actually trying to do? You may get better suggestions that way. – BJ Myers Mar 17 '16 at 02:26
  • Well, you're going to have to give a language. If you call that function as written it couldn't possibly keep `i`'s state since `i` will go out of scope when it returns. – ChiefTwoPencils Mar 17 '16 at 02:26
  • Haha yea. I think it is an XY problem, though, I think the reason why I asked it this way was because there will be other times in the future where I will come across similar problems such as these (because I have already in the past several times), that knowing the best practice will, kind of, prepare me for future scenarios with their small quarks and differences. – aejhyun Mar 17 '16 at 02:31
  • This seems like a general problem... Java and Swift aren't related to this question, really. – OneCricketeer Mar 17 '16 at 02:32
  • @cricket_007, while their specific choices (at least one AFAIK) aren't related due to the fact the way they're attempting to go about it isn't possible. But if they chose C++ it would be. – ChiefTwoPencils Mar 17 '16 at 02:41
  • Why the *second* time? If it was the first time, you could initialize a return value via an anonymous init block. – user207421 Mar 17 '16 at 02:42
  • if you are sure you want to execute it only once, then set a flag the first time it is executed. Don't use a counter. Chances of error increase!! – Karthik Mar 17 '16 at 06:50

3 Answers3

1

In Swift language, A well known way of doing one time execution in a safe way is to use dispatch_once:

var token: dispatch_once_t = 0
func test() {
    dispatch_once(&token) {
        println("This is printed only on the first call to test()")
    }
    println("This is printed for each call to test()")
}

for _ in 0..<4 {
    test()
}

/* Output:
This is printed only on the first call to test()
This is printed for each call to test()
This is printed for each call to test()
This is printed for each call to test()
This is printed for each call to test()
*/

For an interesting discussion on this- see: Example of dispatch_once in Swift

Community
  • 1
  • 1
Shripada
  • 6,296
  • 1
  • 30
  • 30
-1

In Java, you can achieve them with a flag.

As you mentioned in you question, you can check the function is called or not with a flag. But beware of the thread-safety problem. Your function may be called over once if your code is not thread-safety. For example, you may write a code like this:

class NotThreadSafety {
    private static boolean isFunctionCalled = false;
    public static void shouldOnlyCalledOnce() {
        if (!isFunctionCalled) {
            System.out.println("I think I should called only once!!");
            isFunctionCalled = true;
        }
    }
}

If you called this function in multi-threads like this:

ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0; i != 5; ++i) {
    exec.execute(new Runnable() {
        @Override
        public void run() {
            NotThreadSafety.shouldOnlyCalledOnce();
        }
    });
}
exec.shutdown();

You output may be like:

I think I should called only once!!

I think I should called only once!!

I think I should called only once!!

I think I should called only once!!

I think I should called only once!!

You need to add synchronized keyword to shouldOnlyCalledOnce() function, it will prevent race condition on isFunctionCalled field.

Community
  • 1
  • 1
Nier
  • 638
  • 7
  • 15
  • I separate them with the flag method because they are not considered as **functions**, just as I mentioned at the beginning of the second section. However, initialization is a way to make sure the code can only be **executed once**, which is mentioned in OP's question. That's why I put then in the answer and show their limitations. – Nier Mar 17 '16 at 06:25
  • 1
    You're right. I delete them from the answer. Thanks for response. – Nier Mar 17 '16 at 06:55
-2

Option 1: You should use the Singleton pattern if you always want to return the same value, singleton pattern gives you the oportunity to call your function once, so your function will execute once the same code an will always return the same value every time. Below you can find a good example in java.

https://en.wikipedia.org/wiki/Singleton_pattern

Option 2: If you want to be more restrictive, create a delegate and put it into a stack, so you can control how many times you call that function depending on the push operations that you perform over the stack. In your case you will put the delegate just once

Zinov
  • 3,817
  • 5
  • 36
  • 70
  • 2
    Idempotence is the property of certain operations in mathematics and computer science, that can be applied multiple times without changing the result beyond the initial application. The singleton pattern only guarantees that there will be just 1 instance of a given class, not that the class methods will be idempotent. – Micho Mar 17 '16 at 02:40