Refactoring - Extract Method

Motivation: Producing methods that efficiently communicate what they do and how they do what they do. It consists of calls to well-named methods that are all at the same level of detail.

public float CalculateMovieRanking(float rating, int totalVotes, int minVotesRequired, float meanVotes)
{
    if (rating > 10 && rating < 0)
        throw new Exception("The rating should be in range of 0 and 10");
    if (minVotesRequired < 3000)
        throw new Exception("Minimum votes required for the calculation is 3000");
    if (totalVotes < minVotesRequired)
        throw new Exception("The total votes can not be less than minimum votes required");
    if (meanVotes > 10 && meanVotes < 0)
        throw new Exception("The mean votes should be in range of 0 and 10");

    float movieRanking = (rating*totalVotes +  minVotesRequired*meanVotes) / (totalVotes + minVotesRequired);
    return movieRanking;
}

Refactor as:
public float CalculateMovieRanking(float rating, int totalVotes, int minVotesRequired, float meanVotes)
{
    ValidateParameters(rating, totalVotes, minVotesRequired, meanVotes);

    float movieRanking = (rating * totalVotes + minVotesRequired * meanVotes) / (totalVotes + minVotesRequired);
    return movieRanking;         
}

private static void ValidateParameters(float rating, int totalVotes, int minVotesRequired, float meanVotes)
{
    if (rating > 10 && rating < 0)
        throw new Exception("The rating should be in range of 0 and 10");
    if (minVotesRequired < 3000)
        throw new Exception("Minimum votes required for the calculation is 3000");
    if (totalVotes < minVotesRequired)
        throw new Exception("The total votes can not be less than minimum votes required");
    if (meanVotes > 10 && meanVotes < 0)
        throw new Exception("The mean votes should be in range of 0 and 10");
}

Comments

Popular posts from this blog

Performance Test Run Report Template

Understanding Blockchain

Bugs Management in Agile Project