If I could do magic I would conjure up a C# code analysis tool; let’s call it XYZ. Here’s an example of some code you could give as input to XYZ:
public class MyClass
{
private int myInt;
[Functional]
public int GetDoubleOfMyInt()
{
return 2*myInt;
}
[SideEffect: myInt]
public void IncrementMyInt()
{
myInt++;
}
}
Notice the tags on the two methods. XYZ would verify that GetDoubleOfMyInt() is indeed purely functional (in the sense that it merely computes an integer) and that IncrementMyInt has the side effect of assigning a value to myInt. If you swapped the two tags XYZ would issue two errors.
My questions:
1. Does something ressembling XYZ actually exist?
2. If you were asked to implement it, where would you start?
Code Contracts essentially does what you are asking. (http://msdn.microsoft.com/en-us/devlabs/dd491992)
Code Contracts allow you to decorate your code with attributes and calls that allow the compiler and IDE to statically analyse your code. You can find Code Contracts within the
System.Diagnostics.Contractsnamespace, but to take advantage of full static type checking, you need at least the Premium edition SKU of Visual Studio (I think).A quick example, your
Functionalattribute essentially is the same asPure:Which tells the analyser that the method makes no state changes. You can also do pre and post conditions on your methods, e.g.:
There is a lot of depth in Code Contracts, and worth a good reading.