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
!
- Set the value of
Client
in the constructor - Throw a
NullReferenceException
or anIllegalArgumentException
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