jeudi 23 septembre 2021

Adding a new implementation without having to touch an existing code - how?

There're 2 entities in a Go program: country states and years. A program calculates some data by receiving input from a user. The list of country states is constant, whereas years, as the time goes on, of course not.

I want to structure my program in such a way that it'll be flexible from the point of view of adding new year without changing the existing code. How would I do it? I need an architecture pattern for such a case, that is.

I want to avoid something like this:

func CalculateData(cs, year) -> ReturnDataStructure {
    if year == 2000 {
        return calculateDataFor2000(cs)
    } else if year == 2001 {
        return calculateDataFor2001(cs)
    } else if year == 2002 {
        return calculateDataFor2002(cs)
    } else //and so on


    // as years go by, add a new year...
    } else if year == 2052 {
        return calculateDataFor2052(cs)
    }

    //....
}

Instead I want to be able to add only: I'd add an implementation, perhaps in a separate file, without having to touch the existing code, as the years go by. That is, the function CalculateData(...) should become this flexible for it work properly and it shouldn't know how many years there are. The years must not be hard-coded.

How would one do it?

Aucun commentaire:

Enregistrer un commentaire