Skip to content

Latest commit

 

History

History
72 lines (58 loc) · 2.11 KB

QW0003.md

File metadata and controls

72 lines (58 loc) · 2.11 KB

QW0003: Decorate pure functions

Pure methods do not make any visible state changes. Its only purpose is to return a value. If it returns a value, and that value is subsequently ignored, then there was no reason to call the method in the first place. Therefore, the warning would always indicate a mistake.

By enabling CA1806 the compiler will inform on ignoring the return value.

As it is - in most cases - hard to determine if a function is pure, or impure, this rule enforces the code to also decorate all impure methods. This ensures that the developer has to explicitly decorate all methods.

This rule should only be enabled, for libraries, where that burden is worth it.

Non-compliant

public class Noncompliant
{
    public int PureFunction() => 42; // Noncompliant
}

Compliant

public class Compliant
{
    [Pure]
    public int PureFunction() => 42;

    [Obsolete]
    public int Obsolete() => 0; // Obsolete methods are ignored.

    public void Void() { } // Void methods are impure per definition.

    public bool TryParse(string str, out object result) // Methods with out parameters are expected to be impure.
    {
        if (str is null)
        {
            result = default;
            return false;
        }
        else
        {
            result = str;
            return true;
        }
    }

    public int GuardPositive(int number) => number; // Guarding is expected to be impure.

    [Impure]
    public int ImpureMethod(int input) => 69; // Decorated with (something derived from) an ImpureAttribute.

    [DoesNotReturn]
    public int Throws() => throw new NotSupportedException(); // Decorated to indicate that there will be no answer.

    [CustomAssertion]
    public T SomeAssertion<T>(T subject) => subject; // Decorated with something indicating an assertion is done.
}

public class Guard
{
    public T NotNull<T>(T obj) => obj; // Methods on a Guard class are expected to be impure.
}

[Obsolete]
public class ObsoleteClass
{
    public int Function() => 42; Obsolete classes are ignored.
}