Aligma
Aligma

Reputation: 572

Best approach for initialising a class with a property that must exist

Example classes

public class Company {
    public Details Details { get; set; }
    public List<Employeee> Employees { get; set; }

    public Company() { 
    }
}

public class Details {
    public string Name { get; set; }
    public string Url { get; set; }

    public Details() {
    }
}

Usage somewhere in the code...

var c = new Company();
c.Details = new Details();
c.Details.Name = "Example";
c.Details.Url = "http://example.org/";

It doesn't make sense to have a company without having details.

One thought I had was to

This seems like a common problem, I was wondering if there is a standard way of dealing with it which will result in testable classes. I wasn't sure what to search for.

Upvotes: 0

Views: 46

Answers (1)

Hille
Hille

Reputation: 2299

If I understand you correctly, I think the best approach would be to create only a constructor with the Details as parameters.

Example:

public class Company
{
    public Details Details { get; set; }
    public List<Employeee> Employees { get; set; }

    public Company(string Name, string Url)
    {
        this.Details = new Details(Name, Url);
    }
    
    public Company(Details Details)
    {
        this.Details = Details;
    }
}

public class Details
{
    public string Name { get; set; }
    public string Url { get; set; }

    public Details(string Name, string Url)
    {
        // If the validation fails, throw an error
        if (string.IsNullOrWhiteSpace(Name))
            throw new ArgumentException($"'{nameof(Name)}' cannot be null or empty", nameof(Name));
        if (string.IsNullOrWhiteSpace(Url))
            throw new ArgumentException($"'{nameof(Url)}' cannot be null or empty", nameof(Url));

        this.Name = Name;
        this.Url = Url;
    }
}

Upvotes: 1

Related Questions