I like the documentation to be the part of a system:
public class Position
{
/// <summary>
/// ...
///
/// A value within a range -180 and 180
/// </summary>
public double Longitude { get; set; }
/// <summary>
/// ...
///
/// A value within a range -90 and 180
/// </summary>
public double Latitude { get; set; }
}
All dependent modules must be tested to comply with the specification of their dependency. Test-driven development is one way. Contract-driven development is another.
If you insist on "defencive programming" with run-time checks of values, then simply use a constructor:
public class Position
{
/// <summary>
/// ...
///
/// A value within a range -180 and 180
/// </summary>
public double Longitude { get; private set; }
/// <summary>
/// ...
///
/// A value within a range -90 and 180
/// </summary>
public double Latitude { get; private set; }
public Position(double longitude, double latitude)
{
if (longitude < -180 || longitude > 180)
{
throw new ArgumentOutOfRangeException();
}
if (latitude < -90 || latitude > 90)
{
throw new ArgumentOutOfRangeException();
}
Longitude = longitude;
Latitude = latitude;
}
}
Or use a builder:
public class Position
{
public double Longitude { get; private set; }
public double Latitude { get; private set; }
/// <summary>
/// Protects from invalid positions. Use <see cref="Position.Builder"/>
/// </summary>
private Position() { }
/// <summary>
/// Builds valid positions
/// </summary>
public class Builder
{
public double Longitude { get; set; }
public double Latitude { get; set; }
public Position Build()
{
if (Longitude < -180 || Longitude > 180)
{
throw new ArgumentOutOfRangeException();
}
if (Latitude < -90 || Latitude > 90)
{
throw new ArgumentOutOfRangeException();
}
return new Position() { Latitude = this.Latitude, Longitude = this.Longitude };
}
}
}
Usage:
Position p = new Position.Builder()
{
Latitude = 2,
Longitude = 5
}.Build();
Summary:
- Run-time checks ("defensive programming"):
- Public setter with check (see other answers)
- Public constructor with check
- "Builder pattern" with builder performing checks
- Test-time checks:
- Test-driven
- Contract-driven
double
with an implicit cast. – SLaks Feb 5 '14 at 17:09