For exampe, method of my class should validate input values before using. Suggest, 2 parameters of method are :
int start
int count
We should validate, that start
not less than 0 (should be 0 or greater), count
should be in range 0..999. If these 2 parameters are valid, we continue executing our method, otherwise throw an exception BillComInvalidRangeException
:
public class BillComInvalidRangeException : Exception
{
const string invalidRangeMessage = "The range is not valid. 'Start' should be greater than 0, 'Count' in range 0..999.";
public BillComInvalidRangeException(int start, int count) : base($"{invalidRangeMessage} Passed 'Start' : {start}, 'Count' : {count}")
{
}
}
I want to follow SRP and create one more class, named ValidateListRange
. I can implement it in 3 approaches:
validate values in method:
public bool Validate(int start, int count)
{
return !(start < 0
|| count < 0
|| count > 999);
}
and then just to use:
var validateObject = new ValidateListRange();
if (!validateObject.Validate(start, count))
throw new BillComInvalidRangeException(start, count);
validate values in static method:
public static bool Validate(int start, int count)
{
return !(start < 0
|| count < 0
|| count > 999);
}
then for using:
if (!ValidateListRange.Validate(start, count))
throw new BillComInvalidRangeException(start, count);
more shorter record with the same functional. Then our ValidateListRange
class is the simple Util class, which can include many methods (validate, generate etc) like this around the project.
But with non static class we have one huge benefit - we can work with interface and then pass necessary validate object without changing our project source code. For example, in the future we should validate 9999, not 999 and we can write a new implementation of ValidateListRange class. If it's necessary
Which approach is better? Or any another approach?
Oleg, I am not sure how stuck you are on throwing that specific exception, but have you considered?:
FluentValidation (https://www.nuget.org/packages/fluentvalidation)
Code Contracts (https://learn.microsoft.com/en-us/dotnet/framework/debug-trace-profile/code-contracts)