Parameter Validation Best Practices

后端 未结 5 2741
一生所求
一生所求 2021-02-20 09:05

Imagine you have an application which is some kind of front-end to all your business logic. This front-end has a lot of DLLs upon which it depends, and the methods in t

5条回答
  •  旧时难觅i
    2021-02-20 09:34

    Usually parameter checks are very cheap, even if called thousands of times. For example test if a value is null, a string or Collection is emtpy a number is in a given range.

    But beware that checks may be expensive, so think twice: Evaluating a regex on a large string, checking if a file exists, checking that all elements in a collection meets a certain criteria.

    I would also only recommend checking only in public or protected methods. Note that all public methods with unchecked parameters are potential risks!

    EDIT/another thought: If a method does not use the parameters but is just passing it to another method then you may also omit the checking. Only the method which is actually using these parameters for itself should do the checking.

    This is because if the requirements of the parameters change you need to change the validations in multiple places, risking inconsistency.

提交回复
热议问题