Skip to main content
3 of 7
added 414 characters in body
durron597
  • 7.6k
  • 10
  • 38
  • 67

I disagree with all three of the opinions. If Client can never be null, then don't even make it possible for it to be null!

  1. Set the value of Client in the constructor
  2. Throw a NullReferenceException or an IllegalArgumentException in the setter.

So your code would be something like:

public class Room
{
    private Client theClient;

    public Room(Client client) {
        this.theClient = client;
    }

    public Client Client { 
        get { return theClient; }
        set 
        {
            if (value == null) 
                throw new NullReferenceException();
            theClient = value;
        }
    }

    public long ClientId
    {
        get
        {
            return theClient.Id;
        }
    }
}
public class Client 
{
    public long Id { get; set; }
}

This is unrelated to your code, but you would probably be better off using an immutable version of Room by making theClient final, and then if the client changes, making a new room. This will improve the thread safety of your code in addition to the null safety of the other aspects of my answer. See this discussion on mutable vs immutable

durron597
  • 7.6k
  • 10
  • 38
  • 67