OO design patterns to use for validation

前端 未结 4 1727
感情败类
感情败类 2021-01-31 21:38

I am in the process of writing some validation code based on these assumptions:

  • Validation code must be in an external class
    • i.e. no data class contains
4条回答
  •  猫巷女王i
    2021-01-31 22:02

    If you're doing any sort of of GUI work, you should take a look at JGoodies Validation: http://www.jgoodies.com/downloads/libraries.html (also some articles here: www.jgoodies.com/articles/).

    I would create a validator for any class that needs validation. You can actually create more than one validator if you need different ways of validating, e.g. strict or not. You can group common functionality and methods into classes like AbstractValidator and ValidationResult (which may have a list of errors, severity, etc.).

    Be wary of over-design. Try starting with something simple like:

    new UserValidator().validate(user)
    

    or to validate a view:

    new UserPanelValidator().validate(userPanel)
    

    It does depend on your architecture though. For example, if you automatically propagate input from the view to the domain, then you don't need to do as much validation at the view level.

提交回复
热议问题