HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

One time property reading

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
onereadingpropertytime

Problem

I have following code that is used of one time skipping some functionality(actually do something only one time until SkipSomeStuff is true):

private bool _skipSomeStuff;
public bool SkipSomeStuff
{
  set 
  { 
    _skipSomeStuff = value; 
  }
  get 
  { 
    if (_skipSomeStuff) 
    {
        _skipSomeStuff = false;
        return true;        
    }
    return false;
  }
}


Is such construction ok to use, or I should change it with something?

Solution

It is very confusing to set a property just to discover that it returns something else just after you set it. Properties are supposed to keep the value you give them. (At least logically)

And since your SkipSomeStuff property is public, you have no guarantee you won't access that property by accident before the intended recipient accesses it, and the stuff isn't skipped after all.

How about keeping the skipSomeStuff member, but set it using a method called SkipStuffNextTime() or something like that? Nobody will misunderstand the intent of your code that way, and only the code it's relevant for will access and reset it.

private bool skipSomeStuff = false;

public void SkipStuffNextTime() {
    skipSomeStuff = true;
}

public void DoSomeStuff() {
    if (skipSomeStuff) {
        skipSomeStuff = false;
        return;
    }
    // do the stuff
}

Code Snippets

private bool skipSomeStuff = false;

public void SkipStuffNextTime() {
    skipSomeStuff = true;
}

public void DoSomeStuff() {
    if (skipSomeStuff) {
        skipSomeStuff = false;
        return;
    }
    // do the stuff
}

Context

StackExchange Code Review Q#8232, answer score: 10

Revisions (0)

No revisions yet.