Work in the constructor

When a new instance of a class is created that has logic in the constructor, it is often very difficult to test that class. If for some reason, you need to set up a test scenario that requires different values or behavior than that which is set up in the constructor, it will be quite difficult to proceed. It would be best to minimize the work done in the constructor and extract helper methods or some other scenario more easily tested and better implemented elsewhere.

Keep in mind that particular patterns may prove to be better alternatives to setting up a specific class or function. You should familiarize yourself with common software patterns and how to best implement them. This will help you grow an application by working to solve similar problems that have been resolved by others before you. By utilizing known software patterns, you can more easily communicate your intent with the code within the system.

The builder pattern, for example, might be employed to construct an object with the proper values set that would otherwise be added to the constructor.

Take the following example of the Car class:

public Car(string make, string model, int doors)
{
Make = make;
Model = model;
Doors = doors;
}

You could easily write a builder class to construct a specific type of car, such as a ToyotaCamryBuilder or FordMustangBuilder. Creating a new instance of either a Toyota Camry or a Ford Mustang would be quite easy, simple, and clean. Not to mention, it would be quite easy to test.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.114.244