C# Corner Listing #3: Watch Out for Side Effects (C#)

public class HelperClass
{
	private string resultFromCalculation;

	public string Result
	{
		get 
			{ 
				if (resultFromCalculation == null)
					resultFromCalculation = 
						reallyLongCalculation();
			return resultFromCalculation; 
			}
	} 

	private string reallyLongCalculation()
	{
		return "this took a long time";
	}
}
Listing 3: This implementation only computes the result when client code asks for it. That’s fine, but this rather naïve implementation might exhibit race conditions in a multithreaded program. When you introduce side effects in later releases, you need to ensure that those side effects do not cause problems for client code.
comments powered by Disqus

Featured

Subscribe on YouTube