Search code examples
c#restrictions

Is it possible to apply restrictions to several methods in C#


I have a script as follow :

Int MethodOne (int param) {
    If (param > 5) {
        Return 0;
    }
    Return param;
}

Int MethodTwo (int param) {
    If (param > 5) {
        Return 0;
    }
    Return param * anotherVariable;
}

Is it possible to apply the conditional 'method should not execute if param > 5' to all my methods without rewriting it inside every method?


Solution

  • One way is not to pass an int (see primitive obsession)

    public class NotMoreThanFive 
    {
      public int Value {get; private set;}
      public NotMoreThanFive(int value) 
      {
        Value = value > 5 ? 0 : value;
      }
    }
    

    now

    Int MethodOne (NotMoreThanFive param) {
        Return param.Value;
    }
    
    Int MethodTwo (NotMoreThanFive param) {
        Return param.Value * anotherVariable;
    }