0

I have this C# solution in which we use a certain pattern. A function returns true/false whether it succeed, and some value. If the function returned false, the value may not be used. Thus in the scope where such a function (with this particular pattern) is called, the IsSuccessful boolean must be evaluated.

We work with VS2013 + ReSharper 9. Is there a way to automatically check whether this pattern is obeyed in the code? If it is not possible with these tools, are there other tools? My last resort would be to write a unit test that performs this static code analysis.

Code example:

public ReturnValue<T> MyMethod()
{
    try
    {
        ....
        return new ReturnValue<T>(someValue);
    }
    catch(Exception ex)
    {
        return new ReturnValue<T>(ex);
    }
}

var returnValue = MyMethod();
if(!returnValue.IsSuccesful)
{
    //Log error
    return; //Can't go on, previous function failed
}

//Is successful continue code

public class ReturnValue<T>
{
    public bool IsSuccessful { get; private set; }
    public T Value { get; private set; }

    public ReturnValue<T>(Exception ex)
    {
        IsSuccessful = false;
    }

    public ReturnValue<T>(T valueToReturn)
    {
        IsSuccessful = true;
        Value = valueToReturn;
    }
}

Edit:

I semi-solved my issue. Upon creation of the object the current stacktrace is saved (new StackTrace()). Upon destruction of the object (when the garbage collectors cleans it up), it is checked whether the IsSuccesful property of the object was ever evaluated during its lifespan. If not, a warning with the stacktrace is logged.

Mike de Klerk
  • 11,906
  • 8
  • 54
  • 76
  • Sidenote: unit tests don't do static code analysis, they're completely different. Static analysis doesn't actually execute the code. – Dmitry Grigoryev Jul 01 '15 at 10:29
  • @DmitryGrigoryev I could write a unit test, that takes all C# files from solution and analyzes them without invoking any actual code of the solution. Then my unit test does static code analysis without executing the actual code. I'm not concerned about what religion preaches about how unit tests should be used. I use the mechanism of unit testing in anyway useful to me/the project. – Mike de Klerk Jul 01 '15 at 11:44
  • 2
    These wouldn't be called tunit tests. I'm not being religious about it, just consistent in terminology. – Dmitry Grigoryev Jul 01 '15 at 11:53
  • Could you provide a concrete code sample? – ulrichb Jul 01 '15 at 18:01
  • @ulrichb Yes I did, thank you for asking. – Mike de Klerk Jul 01 '15 at 18:25

0 Answers0