简体   繁体   中英

Golang invoking methods with varying parameters

I have a use case where I need to execute a sequence of methods with varying params, and if I encounter a specific return value, then I need to stop the execution. There are roughly around 50 methods like this.

To give you an example here is my use case.

func Method1(param1 type1, param2 type2, param3 type3) bool {
    // here i use only param1 and other 2 params are not being used. 
    if some condition on param1 {
        return true
    }
    return false
}
func Method2(param1 type1, param2 type2, param3 type3) bool {
    // here i use param2 and param3. Param1 is not used 
    if some condition on param2 and param3 {
        return true
    }
    return false
}

The caller method looks like this.

    rejectionFuncs := []func(type1,type2,type3) bool {
        Method1, Method2,
    }

    for _, s := range rejectionFuncs {
        rejected := s(param1, param2, param3)
        if rejected {
            return false
        }
    }

I could only think of this way executing series of methods in elegant fashion, but the downside of this I could see there are many methods where params are not being used. If run on code qualify checks, these methods complain that I am not using params.

Is there any way I could simplify the code here?

Not using params is not an error, in fact that is often the case when you want to implement an interface which has methods with params, but your specific implementation does not (need to) use them.

One thing you could simplify in your case is to wrap the params in a struct, and you only need to pass the struct (or pointer to struct) to the functions. That will also make your code quality checker calm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM