dimanche 11 décembre 2016

Call multiple method with same out and different input in loop

I have multiple methods with different input parameters and same outputs.

I call Method1 with input type of number and then check its result, if the result is valid next method gets called ( this time with input type of string) and so on.

In this example i have three methods, but if i have 10 methods or 20 methods with different inputs and same outputs i have to write redundant code, how can i prevent these redundant codes?

this is sample of methods:

public ValidationResult Method1(int number)
{
    var validationResult = new validationResult();
    if(number > 10)
    {
        validationResult.Errors.Add(new ValidationFailure("", "Invalid Number"));
    }
    return validationResult;
}

public ValidationResult Method1(string name)
{
    var validationResult = new validationResult();
    if(name.Length > 20)
    {
        validationResult.Errors.Add(new ValidationFailure("", "Invalid name"));
    }
    return validationResult;
}

public ValidationResult Method1(double average)
{
    var validationResult = new validationResult();
    if(average < 14)
    {
        validationResult.Errors.Add(new ValidationFailure("", "Invalid average"));
    }
    return validationResult;
}

And i call this methods as following:

var validationResult = Method1(20);
if (!validationResult.IsValid)
{
    return validationResult.FirstError();
}
validationResult = Method2("Samsung");
if (!validationResult.IsValid)
{
    return validationResult.FirstError();
}   
validationResult = Method3(15.5);

if (!validationResult.IsValid)
{
    return validationResult.FirstError();
}

Aucun commentaire:

Enregistrer un commentaire