patterncsharpModerate
One time property reading
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
Is such construction ok to use, or I should change it with something?
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.
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.