Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one detect mutation in a C# function?

I've been reading articles on how to program in a functional (i.e F#) style in C#, for example, foregoing loops for recursion and always returning a copy of a value/object instead of returning the same variable with a new state.

For example, what sort of code inspection things should I watch out for? Is there any way to tell if a method on a BCL class causes a mutation?

like image 940
MatthewMartin Avatar asked Mar 01 '23 19:03

MatthewMartin


2 Answers

The tool NDepend can tell you where you have side effect. It can also ensure automatically that a class is immutable (i.e no side effect on its object instances) or a method is pure (i.e no side effects during the execution of the method. Disclaimer: I am one of the developers of the tool.

In short, trick is to define an attribute, such as, MyNamespace.ImmutableAttribute and to tag classes that you wish to be immutable.

[Immutable]class MyImmutableClass {...}

If the class is not immutable, or more likely, if one day a developer modifies it and breaks its immutability, then the following Code Rule over LINQ Query (CQLinq) will suddenly warn:

warnif count > 0 
from t in Application.Types
where !t.IsImmutable && t.HasAttribute("MyNamespace.ImmutableAttribute")
select t

On a side note, I wrote an article on immutability/purity/side-effects and NDepend usage: Immutable Types: Understand Them And Use Them

like image 98
Patrick from NDepend team Avatar answered Mar 07 '23 16:03

Patrick from NDepend team


Here are two things that would help you find variables and fields whose values are getting changed. Mutability is more complex than this, of course (for example these won't find calls to add to collections) but depending on what you're looking for, they may be helpful.

  1. Make all of your fields readonly; then they can only be set from the constructor, and not changed thereafter.

  2. Pick up a copy of ReSharper. It expands on Visual Studio's syntax highlighting, and has an option to set up custom highlighting for mutable local variables. This will let you see at a glance whether locals are being modified.

like image 35
Joe White Avatar answered Mar 07 '23 15:03

Joe White