Good class design by example

前端 未结 4 1252
忘了有多久
忘了有多久 2021-01-30 14:17

I am trying to work out the best way to design a class that has its properties persisted in a database. Let\'s take a basic example of a Person. To create a new per

4条回答
  •  [愿得一人]
    2021-01-30 14:54

    This should be checked by using business rules.

    I mean if you want a very re-usable business model, business objects should be re-used elsewhere in different areas, and this may mean same class "A" could be fine in state "X" in some business, but in another situation, same class "A", will be fine in state "Y".

    There's a good design pattern allowing you to implement business validators called Specification:

    • http://en.wikipedia.org/wiki/Specification_pattern

    This can be implemented in a lot of ways, but one of most compact ones is by building rules with lambda expressions.

    For example:

    someAInstance => someAInstance.Name != null && someAInstance.Age > 30
    

    Another way is using existing object validation libraries, like NHibernate Validator, which can be used standalone without NHibernate and allows you to put attributes in class' properties like [NotNull], [NotNullNotEmpty], and more complex rules, and you can either use built-in ones or you can build your own ones.

    Learn more by reading this article (there you'll find a list of out-of-the-box validation rules):

    • http://nhforge.org/wikis/validator/nhibernate-validator-1-0-0-documentation.aspx

    Note that one of most important advantages of NH Validator is it can be used in any layer, not only data or business layer, and as you can use it without NHibernate, you've a light-weight, easy-to-use and multi-layered object validator.

提交回复
热议问题