This question usually follows a coding exercise such as calculating the area of a rectangle. The honest answer: without validation, yes — the method happily returns a nonsensical result. With a negative width and a positive height, the area is negative; with both negative, the area is positive, which is even more misleading because it looks valid. public double Area(double width, double height) => width * height; Area(-5, 4); // -20 (meaningless) Area(-5, -4); // 20 (looks valid but the input was wrong) A length cannot be negative in this domain, so the right approach is to validate inputs and fail fast. Option 1 — guard clauses that throw (most common) public sealed class Rectangle : IShape { public Rectangle(double width, double height) { ArgumentOutOfRangeException.ThrowIfNegativeOrZero(width); // .NET 8+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(height); Width = width; Height = height; } public double Width { get; } public double Height { get; } public double Area() => Width * Height; } Validating in the constructor means an invalid Rectangle can never exist, so Area() never needs to check again (the "always valid" object principle). Also consider NaN and infinity for doubles (double.IsFinite). Option 2 — return a result instead of throwing For user input, where invalid values are expected, return a validation result (TryCreate pattern or Result<T>) and show a friendly message rather than throwing. Option 3 — make invalid values unrepresentable Use a value object (a Length record that validates itself), or unsigned types for counts. (uint is not ideal for lengths because it does not handle decimals and conversions can wrap around silently.) What not to do - Silently convert with Math.Abs: it hides bugs and may produce wrong business results. - Return -1 or 0 as an error code: callers forget to check. At the API boundary Validate request DTOs ([Range(0.01, double.MaxValue)] or FluentValidation) and return 400 Bad Request with a clear message, while the domain object keeps its own guard as defence in depth. Testing Add unit tests for zero, negative, very large values and NaN, asserting the expected exception or validation result.
Ravindra Wadile · · 0 likes