Good class design by example

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

    First, I'd put two distinct public constructor to Person:

    namespace BusinessLayer
    {
        class Person
        {
            public Person(string firstName, string lastName): this(firstName, lastName, DateTime.Now)
            {}
    
            public Person(string firstName, string lastName, DateTime birthDate)
            {
                FirstName = firstName;
                LastName = lastName;
                DateOfBirth = birthDate;
            }
    
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public DateTime DateOfBirth { get; set; }
        }
    }
    

    this allows you to write both

    var p = new Person("Marilyin", "Manson");
    var p2 = new Person("Alice", "Cooper", new DateTime(...));
    

    and

    var p = new Person { FirstName="Marilyn", LastName="Manson" };
    

    I can't see why you should limit to only one form.

    As for the DatabaseComponent I'd strongly suggest to write a method that allows you to save a Person instead of the signature you are implicitly declaring.

    That's because, should one day change the way a Person is defined, you'd probably have to change the code in each point you invoke Save() method. By saving just a Person, you only have to change the Save() implementation.

    Don't you plan to use an ORM by the way?

提交回复
热议问题