HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoMinor

Get reputation Badge from given score

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
badgereputationscoregetfromgiven

Problem

I have written code that gets the reputation badge from given score like this:

I use an if-else statement here:

func GetReputationBadge2(score int) string {

    badge := "badges-off.jpg"
    if score >= 50001 { // Diamond
        badge = "diamond-1.gif"
        if score >= 500001 {
            badge = "diamond-5.gif"
        } else if score >= 200001 {
            badge = "diamond-4.gif"
        } else if score >= 150001 {
            badge = "diamond-3.gif"
        } else if score >= 100001 {
            badge = "diamond-2.gif"
        }
    } else if score >= 4501 { // Gold
        badge = "gold-1.gif"
        if score >= 45001 {
            badge = "gold-5.gif"
        } else if score >= 30001 {
            badge = "gold-4.gif"
        } else if score >= 15001 {
            badge = "gold-3.gif"
        } else if score >= 10001 {
            badge = "gold-4.gif"
        }
    }

    return badge
}


I was kinda thinking that I could make it better using a switch-case statement:

func GetReputationBadge(score int) string {

    badge := "badges-off.jpg"
    caseSwitch := true
    switch caseSwitch {
    case score >= 50001:
        badge = "diamond-1.gif"

        switch caseSwitch {
        case score >= 500001:
            badge = "diamond-5.gif"
        case score >= 200001:
            badge = "diamond-4.gif"
        case score >= 150001:
            badge = "diamond-3.gif"
        case score >= 100001:
            badge = "diamond-2.gif"

        }

    case score >= 4501:
        badge = "gold-1.gif"

        switch caseSwitch {
        case score >= 45001:
            badge = "gold-5.gif"
        case score >= 30001:
            badge = "gold-4.gif"
        case score >= 15001:
            badge = "gold-3.gif"
        case score >= 10001:
            badge = "gold-2.gif"

        }

    default:
        return badge
    }

    return badge
}


Notice that I'm comparing boolean in the switch-case statement. Which are better for

Solution

For just a few items, the difference is small. If you have many items you should definitely use a switch.

This question might help: https://stackoverflow.com/questions/29566229/go-switch-string-efficiency

Context

StackExchange Code Review Q#148205, answer score: 2

Revisions (0)

No revisions yet.