-3

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Rudziankoŭ
  • 10,681
  • 20
  • 92
  • 192
  • 2
    There's no way to answer this question. The proper solution depends on countless variables. How are you using these interfaces? Why do they need to be the same interface in the first place? How are they used? Should `Set` even be part of the interface? Etc etc. Without an intimate understanding of your application, there's no way to answer this. – Jonathan Hall Mar 05 '18 at 13:46
  • Do you want to keep both methods? Or you want a single, merged `Set()` method? – icza Mar 05 '18 at 13:46
  • @icza, I want single but flexible method – Rudziankoŭ Mar 05 '18 at 13:48
  • @Rudziankoŭ Then that comes down to [Optional Parameters?](https://stackoverflow.com/questions/2032149/optional-parameters) – icza Mar 05 '18 at 13:50
  • Answered my own question, could you please review? – Rudziankoŭ Mar 05 '18 at 14:08

2 Answers2

3

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
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Ivan Rubanau
  • 374
  • 2
  • 12
0

Another opportunity just came in mind is unite interfaces into one:

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

And ignore redundant argument in method signature if necessary:

func (c *cache) Set(key, value interface{}, _ time.Duration) bool {
Rudziankoŭ
  • 10,681
  • 20
  • 92
  • 192