2

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

Charlyzzz
  • 590
  • 1
  • 4
  • 8
  • 1
    I recommend you this reading https://www.goinggo.net/2016/10/reducing-type-hierarchies.html – Yandry Pozo Nov 16 '16 at 03:47
  • It depends on what you expect to do with `isLight()`. For a hard-coded size, I'd use a function since it would scale across various types satisfying the `file` interface, and there would be a consistent definition of what "light" means. If you define it as a method, all types wanting to satisfy the `file` interface would need to define the implementation of `isLight()` method. Varying definitions of what constitutes "light" might arise if you use a method, but that might be desirable. A 10 MB video might be "light" for example while a 10 MB "plain text" file could be a few sections of a book. –  Nov 17 '16 at 03:19
  • You might also define a method that returns a value that constitutes what the maximum size of a "light" file could be, and a plain `isLight(f file) bool` function could use that method in combination with the `size()` method to return, e.g., `f.size() < f.maxLight()`. This would allow you to define the behavior of `isLight()` as a function, unlike a method defined on the `file` interface, while still allowing the flexibility of the method. –  Nov 17 '16 at 03:22

0 Answers0