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 an
ArgumentNullException
in the constructor.
So your code would be something like:
public class Room
{
private Client theClient;
public Room(Client client) {
if(client == null) throw new ArgumentNullException();
this.theClient = client;
}
public Client Client {
get { return theClient; }
set
{
if (value == null)
throw new ArgumentNullException();
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
readonly
, 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 immutablethis discussion on mutable vs immutable