Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I automatically reset a boolean when any method other is called in C#?

Tags:

c#

flags

set

call

Using C#, I need to do some extra work if function A() was called right before function C(). If any other function was called in between A() and C() then I don't want to do that extra work. Any ideas that would require the least amount of code duplication?

I'm trying to avoid adding lines like flag = false; into every function B1..BN.

Here is a very basic example:

bool flag = false;

void A()
{
    flag = true;
}

void B1()
{
    ...
}

void B2()
{
    ...
}

void C()
{
    if (flag) 
    {
        //do something
    }
}

The above example was just using a simple case but I'm open to using something other than booleans. The important thing is that I want to be able to set and reset a flag of sorts so that C() knows how to behave accordingly.

Thank you for your help. If you require clarification I will edit my post.

like image 804
gtaborga Avatar asked Dec 23 '22 04:12

gtaborga


2 Answers

Why not just factor your "Extra work" into a memoised function (i.e. one that caches its results)? Whenever you need that work you just call this function, which will short circuit if the cache is fresh. Whenever that work becomes stale, invalidate the cache. In your rather odd examples above, I presume you'll need a function call in each of the Bs, and one in C. Calls to A will invalidate the cache.

If you're looking for away around that (i.e. some clever way to catch all function calls and insert this call), I really wouldn't bother. I can conceive of some insane runtime reflection proxy class generation, but you should make your code flow clear and obvious; if each function depends on the work being already done, just call "doWork" in each one.

like image 77
Adam Wright Avatar answered Apr 27 '23 11:04

Adam Wright


Sounds like your design is way too tightly coupled if calling one method changes the behavior of another such that you have to make sure to call them in the right order. That's a major red flag.

Sounds like some refactoring is in order. It's a little tricky to give advice without seeing more of the real code, but here is a point in the right direction.

Consider adding a parameter to C like so:

void C(bool DoExtraWork) {
  if (DoExtraWork)...
}

Of course "DoExtraWork" should be named something meaningful in the context of the caller.

like image 28
JohnFx Avatar answered Apr 27 '23 12:04

JohnFx