hey guys, I’ve been looking at dimeRocker’s C# code and I’m puzzled by a design pattern that’s ubiquitous:
static string _somevariable;
public static string somevariable {
get { return _somevariable; }
set { _somevariable = value; }
}
I see how it works, but my question is “why?” – the setters and getters just set and return the value explicitly. it seems to me that this would be exactly the same as having one single public static string somevariable.
What is the value behind a scheme like this?
Because then you can check when someone uses them or when someone changes them using break points, call stacks, log messages.
Also you can add restrictions and limitations to make sure people aren’t randomly reassigning variables.
ah, that does make sense. interesting… thanks!
A good example of this might be if your variable might be a divisor at one point or another. You don’t want someone setting it to zero, or you’ll get a division by zero error, or worse, your function might return “NaN”. Very Bad Thing™. So instead, if it somehow gets set to zero, you can change it to something equally acceptable at assignment time, and you continue merrily along. This is known as validation, and it can save you a LOT of headaches. Trust me on that.