Skip to content

Instantly share code, notes, and snippets.

@blair55
Created January 10, 2014 10:30
Show Gist options
  • Select an option

  • Save blair55/8349741 to your computer and use it in GitHub Desktop.

Select an option

Save blair55/8349741 to your computer and use it in GitHub Desktop.
Why State is Dangerous
public class Number
{
private int _n;
public Number(int n)
{
_n = n;
}
public int Exponential()
{
return Convert.ToInt32(Math.Round(Math.Exp(_n), 0));
}
public void BadSetter(int n)
{
_n = n;
}
public static void SettingIsReallyBad(Number n)
{
n.BadSetter(20);
}
}
public class Program
{
static void Main(string[] args)
{
var n = new Number(5);
// uncomment the following lines and see how
// the result of the same method call changes!
// 1. here you have some idea that a value might change
// n.BadSetter(10);
// 2. here there is no way of knowing that state has changed
// Number.SettingIsReallyBad(n);
var result = n.Exponential();
Console.WriteLine(result);
Console.ReadLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment