Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modeling a hierarchy of related things without language support for type hierarchies

I'm new to Go, and one of the first things I want to do is to port my little marked-up-page-generation library to Go. The primary implementation is in Ruby, and it is very much "classical object orientation" in its design (at least as I understand OO from an amateur programmer's perspective). It models how I see the relationship between marked-up document types:

                                      Page
                                   /        \
                          HTML Page          Wiki Page
                         /         \
              HTML 5 Page           XHTML Page

For a small project, I might do something like this (translated to the Go I now want):

p := dsts.NewHtml5Page()
p.Title = "A Great Title"
p.AddStyle("default.css")
p.AddScript("site_wide.js")
p.Add("<p>A paragraph</p>")
fmt.Println(p) // Output a valid HTML 5 page corresponding to the above

For larger projects, say for a website called "Egg Sample", I subclass one of the existing Page types, creating a deeper hierarchy:

                                 HTML 5 Page
                                      |
                               Egg Sample Page
                             /        |        \
               ES Store Page    ES Blog Page     ES Forum Page

This fits well into classical object-oriented design: subclasses get a lot for free, and they just focus on the few parts that are different from their parent class. EggSamplePage can add some menus and footers that are common across all Egg Sample pages, for example.

Go, however, does not have a concept of a hierarchy of types: there are no classes and there is no type inheritance. There's also no dynamic dispatch of methods (which seems to me to follow from the above; a Go type HtmlPage is not a "kind of" Go type Page).

Go does provide:

  • Embedding
  • Interfaces

It seems those two tools should be enough to get what I want, but after several false starts, I'm feeling stumped and frustrated. My guess is that I'm thinking about it wrong, and I'm hoping someone can point me in the right direction for how to do this the "Go way".

This is a specific, real problem I'm having, and as such, any suggestions about solving my particular problem without addressing the broader question are welcome. But I'm hoping the answer will be in the form of "by combining structures, embedding, and interfaces in such-and-such a manner, you can easily have the behavior you want" rather than something that sidesteps that. I think many newcomers to Go transitioning from classical-OO languages likely go through a similar period of confusion.

Normally I would show my broken code here, but I've got several versions, each with their own problems, and I don't imagine including them will actually add any clarity to my question, which is already getting quite long. I will of course add code if it turns out to seem useful.

Things I've done:

  • Read much of The Go FAQ (especially the parts that seemed relevant)
  • Read much of Effective Go (especially the parts that seemed relevant)
  • Searched Google with many combinations of search terms
  • Read various posts on golang-nuts
  • Written much inadequate Go code
  • Looked through the Go standard library source code for any examples that seemed similar

To be a little more explicit about what I'm looking for:

  • I want to learn the idiomatic Go way of dealing with hierarchies like this. One of my more effective attempts seems the least Go-like:

    type page struct {
        Title     string
        content   bytes.Buffer
        openPage  func() string
        closePage func() string
        openBody  func() string
        closeBody func() string
    }
    

    This got me close, but not all the way. My point right now is that it seems like a failed opportunity to learn the idioms Go programmers use in situations like this.

  • I want to be as DRY ("Don't Repeat Yourself") as is reasonable; I don't want a separate text/template for each type of page when so much of each template is identical to others. One of my discarded implementations works this way, but it seems it would become unmanageable once I get a more complex hierarchy of page types as outlined above.

  • I'd like to be able to have a core library package that is usable as-is for the types that it supports (e.g. html5Page and xhtmlPage), and is extensible as outlined above without resorting to copying and editing the library directly. (In classical OO, I extend/subclass Html5Page and make a few tweaks, for example.) My current attempts haven't seemed to lend themselves to this very well.

I expect the correct answer won't need much code to explain the Go way of thinking about this.

Update: Based on the comments and answers so far, it seems I wasn't so far off. My problems must be a little less generally design-oriented than I thought, and a little more about exactly how I'm doing things. So here's what I'm working with:

type page struct {
    Title    string

    content  bytes.Buffer
}

type HtmlPage struct {
    page

    Encoding   string
    HeaderMisc string

    styles   []string
    scripts  []string
}

type Html5Page struct {
    HtmlPage
}

type XhtmlPage struct {
    HtmlPage

    Doctype string
}

type pageStringer interface {
    openPage()   string
    openBody()   string
    contentStr() string
    closeBody()  string
    closePage()  string
}

type htmlStringer interface {
    pageStringer

    openHead()   string
    titleStr()   string
    stylesStr()  string
    scriptsStr() string
    contentTypeStr() string
}

func PageString(p pageStringer) string {
    return headerString(p) + p.contentStr() + footerString(p)
}

func headerString(p pageStringer) string {
    return p.openPage() + p.openBody()
}

func HtmlPageString(p htmlStringer) string {
    return htmlHeaderString(p) + p.contentStr() + footerString(p)
}

func htmlHeaderString(p htmlStringer) string {
    return p.openPage() +
        p.openHead() + p.titleStr() + p.stylesStr() + p.scriptsStr() + p.con    tentTypeStr() +
        p.openBody()
}

This works, but it has several problems:

  1. It feels really awkward
  2. I'm repeating myself
  3. It might not be possible, but ideally I'd like all Page types to have a String() method that does the right thing, rather than having to use a function.

I strongly suspect that I'm doing something wrong and that there are Go idioms that could make this better.

I'd like to have a String() method that does the right thing, but

func (p *page) String( string {
    return p.headerString() + p.contentStr() + p.footerString()
}

will always use the page methods even when used through an HtmlPage, due to lack of dynamic dispatch anywhere but with interfaces.

With my current interface-based page generation, not only do I not get to just do fmt.Println(p) (where p is some kind of Page), but I have to specifically choose between fmt.Println(dsts.PageString(p)) and fmt.Println(dsts.HtmlPageString(p)). That feels very wrong.

And I'm awkwardly duplicating code between PageString() / HtmlPageString() and between headerString() / htmlHeaderString().

So I feel like I'm still suffering design issues as a result of to some extent still thinking in Ruby or Java rather than in Go. I'm hoping there's a straightforward and idiomatic Go way to build a library that has something like the client interface I've described.

like image 409
Darshan Rivka Whittle Avatar asked Jul 13 '12 08:07

Darshan Rivka Whittle


2 Answers

Inheritance combines two concepts. Polymorphism and code sharing. Go separates these concepts.

  • Polymorphism('is a') in Go is achieved by using interfaces.
  • Code sharing in Go is achieved by embedding and functions that act on interfaces

A lot of people coming from OOP languages forget about functions and get lost using just methods.

Because Go separates these concepts you have to think about them individually. What is the relationship between 'Page' and 'Egg Sample Page'. It is an "is a" relationship or is it a code sharing relationship?

like image 198
Jesse Avatar answered Nov 01 '22 01:11

Jesse


First, a warning : deep hierarchies are painful to adapt in all languages. Deep hierarchical structural modeling is often a trap : it's intellectually satisfying at first but ends as a nightmare.

Then, Go has embedding, which is really a composition but provides most of what is generally needed with (potentially multiple) inheritance.

For example, let's look at this :

type ConnexionMysql struct {
    *sql.DB
}

type BaseMysql struct {
    user     string
    password string
    database string
}

func (store *BaseMysql) DB() (ConnexionMysql, error) {
    db, err := sql.Open("mymysql", store.database+"/"+store.user+"/"+store.password)
    return ConnexionMysql{db}, err
}

func (con ConnexionMysql) EtatBraldun(idBraldun uint) (*EtatBraldun, error) {
    row := con.QueryRow("select pv, pvmax, pa, tour, dla, faim from compte where id=?", idBraldun)
    // stuff
    return nil, err
}

// somewhere else:
con, err := ms.bd.DB()
defer con.Close()
// ...
somethings, err = con.EtatBraldun(id)

As you can see, with just embedding I could :

  • easily generate an instance of the "subclass" ConnexionMysql
  • define and use my own functions, like EtatBraldun
  • still use functions defined on *sql.DB, like Close of QueryRow
  • if needed (not present here) add fields to my subclass and use them

And I could embedd more than one type. Or "subtype" my ConnexionMysql type.

In my opinion it's a good compromise and it helps avoiding the traps and rigidity of deep inheritance hierarchies.

I say it's a compromise, because it's clear Go isn't an OOP language. The lack of function overriding, as you saw, prevents the usual solution of having methods in a "superclass" composing the calls of "subclasses" methods.

I understand this may be disturbing, but I'm not sure I really miss the weight and verbosity of the usual hierarchy based solutions. As I said, there are fine at first but painful when it gets complex. That's why I suggest you try the Go way :

Go interfaces can be used to reduce the need for inheritance. In fact your page could be an interface (or more idiomatically a few interfaces) and a struct :

type pageOpenerCloser interface {
    openPage  func() string
    closePage func() string
    openPage  func() string
    closePage func() string
}

type page struct {
    Title     string
    content   bytes.Buffer
}

As you can't rely on a String() method defined on an implementation of pageOpenerCloser to simply call a closeBody method defined on the same implementation, you must use functions, not methods to do part of the work, what I see as composition : you must pass your instance of pageOpenerCloser to a Composing functions that will call the right implementations.

This means

  • you're encouraged to have atomic and orthogonal interface definitions
  • interfaces are defined by their (simple) actions
  • interface functions aren't supposed to call other functions on the same instance
  • you're not encouraged to have a deep hierarchy with intermediate levels defined by implementation/algorithms
  • big "composing" algorithms shouldn't be overrided or generally written more than once

I feel this reduces the clutter and helps make a Go program small and understandable.

like image 39
Denys Séguret Avatar answered Nov 01 '22 01:11

Denys Séguret