How much work should be done in a constructor?

后端 未结 18 1149
离开以前
离开以前 2020-11-27 17:40

Should operations that could take some time be performed in a constructor or should the object be constructed and then initialised later.

For example when constructi

18条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 18:09

    Historically, I have coded my constructors so that the object is ready to use once the constructor method is complete. How much or how little code is involved depends on the requirements for the object.

    For example, let's say I need to display the following Company class in a details view:

    public class Company
    {
        public int Company_ID { get; set; }
        public string CompanyName { get; set; }
        public Address MailingAddress { get; set; }
        public Phones CompanyPhones { get; set; }
        public Contact ContactPerson { get; set; }
    }
    

    Since I want to display all the information I have about the company in the details view, my constructor will contain all of the code necessary to populate every property. Given that is a complex type, the Company constructor will trigger the execution of the Address, Phones and Contact constructor as well.

    Now, if I am populating a directory listing view, where I may only need the CompanyName and the main phone number, I may have a second constructor on the class that only retrieves that information and leaves the remaining information empty, or I may just create a separate object that only holds that information. It really just depends on how the information is retrieved, and from where.

    Regardless of the number of constructors on a class, my personal goal is to do whatever processing is necessary to prepare the object for whatever tasks may be imposed upon it.

提交回复
热议问题