Search code examples
gointerfaceabstraction

Abstraction patterns in go


I have two interfaces. They are almost the same, the only difference is the Set method:

type Cache1 interface {
    Set(key, value interface{}, ttl time.Duration) bool
}

type Cache2 interface {
    Set(key, value interface{}) bool
}

Any idea how to unite them into one abstraction? Surely I can add ttl time.Duration to the second interface, but it will useless there and will worsen code readability. Could you please suggest sophisticated pattern if such exist?


Solution

  • I guess, you should care of interface segregation principle while merging those methods.

    Technically, you are able to merge them by wrapping all arguments to SetRequest or something. Interface will be sort of

    type Cache interface {
        Set(request SetRequest) bool
    }