tags:

views:

86

answers:

4

Where is the proper place to perform validation given the following scenario/code below:

In MethodA only: since this is the public method which is meant to be used by external assemblies? In MethodA and B since both these can be accessed outside the class? Or Methods A, B and C since method C may be used by another internal method (but it might not efficient since the programmer can see the code for MethodC already and therefore should be able to know the valid parameters to pass)?

Thanks for any input.

public class A  
{     
    public void MethodA(param)  
    {  
         MethodB(param);  
    }  

    internal void MethodB(param)
    {
          MethodC(param);
    }

    private void MethodC(param)
    {
    }
}
+1  A: 

Parameter validation should always be performed regardless of the caller's location (inside or outside of the assembly). Defensive programming, one can say.

Otávio Décio
A: 

There isn't a 'proper' place, except to adhere to DRY principles and avoid copying the validation code to several places. I'd normally suggest that you delay validation to the latest possible stage, as then if the parameter is never used you don't need to spend time validating it though. This also gives the validation some locality to the place it is used, and you never need to think 'oh, has this parameter been validated yet?' as the validation is right there.

workmad3
+1  A: 

MethodC; that way the parameter always gets checked, even if someone comes along later and adds a call to MethodC from within class A, or they make MethodC public. Any exception should be bubbled up to where it can be best dealt with.

gkrogers
A: 

Given that a more likely senario would involve each method having different parameters and also probably some

if (P1 == 1) { MethodA(P2) } else { MethodB(P2) }

type logic in hte longer term it makes more sense to validate each parameter at the point of entry, escpecially as you may want different error handling depending on where hte method was called.

If the validation logic for a given parameter start to get complex ( i.e. more than five lines of code) then consider a private method to validate that parameter.

James Anderson