Good class design by example

前端 未结 4 1313
忘了有多久
忘了有多久 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:59

    Only use constructors if some fields are mandatory since it's an effective way to make sure that those fields are specified.

    I'm unsure as to whether the fields should be public or not

    Fields usually means member variables and those should always be private. As for properties I would stick with get/set for database objects.

    I'm also wondering how I should be dealing with the optional properties of the class. Once the fields have been populated how do I then save them to the DB?

    Saving things to the database is a whole different story. I would not try to invent my own layer but to use an existing one. There are a whole set of different ORM:s out there from very simple to very feature complete.

    Take a look at PetaPoco for a lightweight alternative or nHibernate for a more feature complete alternative.

    Validation

    One common way to make sure that mandatory fields are correctly specified and got valid values are to use a validation framework. There is one built into .net called DataAnnotations. Google it and look at some examples.

提交回复
热议问题