lundi 17 décembre 2018

Are nullable properties, or properties allowed to be null, code smell (in OOP languages)?

I often see classes like

public class Person
{
    string FirstName { get; set; }

    string MiddleName { get; set; }

    string LastName { get; set; }

    int Age { get; set; }
}

where one of the properties, say MiddleName in this example (because some people aren't given a middle name at birth), is allowed to be null. In my opinion this is wrong because any consumers of the class have to know that the property "might" be null and perform checks like

public void PrintName(Person p)
{
    Console.WriteLine(p.FirstName);

    if (p.LastName != null)
    {
        Console.WriteLine(p.MiddleName);
    }

    Console.WriteLine(p.LastName);
}

How I handle this is by using composition like

public interface IPerson
{
    string FirstName { get; }

    string LastName { get; }

    int Age { get; }
}

public interface IMiddleNamed
{
    string MiddleName { get; }
}

and

public void PrintName(IPerson p)
{
    Console.WriteLine(p.FirstName);

    if (p is IMiddleNamed)
    {
        Console.WriteLine((p as IMiddleNamed).MiddleName);
    }

    Console.WriteLine(p.LastName);
}

That is the case even if my models represent data contracts (e.g. "value bags" that are serialized/deserialized through inter-service communication).

In the same way I avoid classes that has null-able value types like

public class Something
{
    public int SomeInt { get; set; }

    public double? SomeDouble { get; }
}

for the same reason.

However I'm wondering if this is like "OOP overengineering" as it clearly adds a lot of development time.

Aucun commentaire:

Enregistrer un commentaire