Refactoring - Chain Constructors

Motivation: Chain the constructors together to minimize the duplicate code without having to resort to initialization method.  Initialization method is troublesome because only constructor can modify read only members.

public class Movie
{
    private readonly string title;
    private readonly string genre;
    private readonly string director;

    public Movie(string title, string genre)
    {
        this.title = title;
        this.genre = genre;
    }

    public Movie(string title, string genre, string director)
    {
        this.title = title;
        this.genre = genre;
        this.director = director;
    }    
}

Refactor as:

public class Movie
{
    private readonly string title;
    private readonly string genre;
    private readonly string director;

    public Movie(string title, string genre)
    {
        this.title = title;
        this.genre = genre;
    }

    public Movie2(string title, string genre, string director):this(title, genre)
    {
        this.director = director;
    }
}

Comments

Popular posts from this blog

Performance Test Run Report Template

Understanding Blockchain

Bugs Management in Agile Project