Where should validation logic be implemented?

前端 未结 6 543
花落未央
花落未央 2021-02-06 07:09

When developing my interfaces (contracts) and the concrete implementations of them, both the data models as well as repositories, I find myself questioning where the validation

6条回答
  •  醉梦人生
    2021-02-06 07:40

    Where should validation logic be implemented?

    Everywhere.

    • You should validate at the UI level so the user gets immediate, useful feedback (ie, fill out a webform and next to it have javascript say, "password too short" so you don't get needless trips to the server)
    • You should validate ANY input into the main software from the user interface. Never trust the user interface, especially on large projects or on web sites - they may be bypassed, or they may be developed by a different team.
    • You should validate inputs to functions/methods/classes. These have inherent limitations that have nothing to do with project requirements (other than it be able to manage the range of inputs required). The idea here is to encourage safe code re-use. Take a class, and you know it's going to fail if you go outside its parameters - and it will tell you if it does so.
    • There are a variety of other areas where validation should take place (DB, backup/restore, ancillary communication channels, etc)

    It may seem like a lot of work, or extra overhead, but the reality is that there are good reasons to re-validate everything along the chain, the least of which is catching bugs before they become a problem.

    -Adam

提交回复
热议问题