I am a huge proponent of self-documenting code (when at all possible). I prefer to have code be self evident by the very nature of the names of the variables, methods, etc.
For instance:
if (TheSky.IsBlue && TheGrass.IsGreen)
BeHappy();
I have run into a situation that has defied all attempts to name the method in a way that illustrates what it does. The problem is that the method is required to do two things.
I have a class that must maintain its own state, however it must have a method that both verifies a condition, and changes the state via a thread safe lock to prevent race conditions.
It basically looks like the code below:
public class TimeWindow
{
private static object lockObject = new object();
private DateTime Timestamp;
private int WindowCounter;
// What do I call this? CanWeDoSomething() implies that it is merely
// calculating a true/false state, not mutating state.
//
// I don't want to call it
// CanWeDoSomethingAndDecrementItIfWeActuallyDoIt() as that is
// just too annoying, and it messes up the self-documenting nature
// since if (CanWeDoSomethingAndDecrementItIfWeAcutallyDoIt()) describes
// two actions, but only one of them is a Boolean condition, so it doesn't
// really fit in with the if statement.
public bool CanWeDoSomething(int WindowSeconds) {
lock(lockObject) {
if ((DateTime.Now - TimeStamp).TotalSeconds > WindowSeconds) {
Timestamp = DateTime.Now;
WindowCounter = 0;
}
if (WindowsCounter < 10) {
++WindowCounter;
return true;
}
return false;
}
}
}
As you can see, I have to perform the test (to retrieve the Boolean) and modify state at the same time. If I didn't do this, then a race condition is possible where the value can be changed by another thread in between checking it's value and mutating its state.
The naming is important because if it implies no state change, then people call the method multiple times without realizing that it also changes state.
Can anyone suggest a name that adequately documents what the method is doing, without making it overly complex? The name should indicate that it's mutating the object as well as performing an action that is a Boolean state.
Alternatively, if you can suggest a better way to accomplish this in a thread safe manner that would work better, that would be good too.