I was playing arround in Go and stumbled upon this dilemma:
(Keep in mind that this is purely conceptual and my goal is try to minize logic repetition and so)
Imagine I had to model two type of files: binary and text. First, each should know how to calculate their size, so I declared two structs and their methods
type file interface {
size() int
...
}
type text struct {
...
}
func (t text) size() int {
...
}
type binary struct {
...
}
func (b binary) size() int {
...
}
So far, so good. The next requirement is to check if they are light (their size is less than some fixed size). In OOP I would use a superclass to avoid repetition, but since I need access to size()
method, I can't use a struct and embeed it.
I have two possible options:
Define a function
isLight(f file) bool
, but this kind of ruin the interface because it wont show that files should know if they are light.Try to mimic some OOP composition, but the resulting code looks less readable than it should (perhaps not in the snippet, but adding some more methods make it looks like 'middle man' code smell because content only redirects the message to the corresponding struct)
type file interface {
size() int
isLight() bool
}
type typeOfContent interface {
size() int
}
type content struct {
file
type typeOfContent
}
func (c content) size() int {
return type.size()
}
func (c content) isLight() int {
return c.size() < 100
}
Which is the 'Go way' of doing this?
Cheers!
Erwin