On Thu, 08 Feb 2018 16:17:08 +1100 Rob Pike <r...@golang.org> wrote:
Rob Pike writes:
> 
> Isn't the visitor pattern just a way to implement type switch in languages
> that don't implement type switch?
> 
> That's certainly how I saw it when using C++. Go has a type switch, and so
> has no need for the visitor pattern, a perfect example of the principle
> that a design pattern is just a way to work around shortcomings in the
> language.

In Go you can implement the visitor pattern without using a
type switch. This allows you to add new type of objects
without changing any other code -- just add the functions you
need.  See below.

Having had to debug someone else's C++ code which made heavy
of the visitor pattern, I can tell you it was quite difficult
to understand, particularly as it had global side-effects and
as it was beaten into shape over time, the code had gotten
quite messy[1].

My advice to C++/Java refugees: don't use the visitor pattern.
And if you do, don't have side-effects or complicated logic!
Actually don't use any GoF patterns! Go has its own idioms.

Example: // Just sketching the idea... 

type Node struct {
        kids    []*Node
        val     Value
}

type Visitor interface {
        func Visit(val interface{})
}

func (t *Tree) Walk(Visitor v) {
        v.Visit(t.val)
        for _, k := range t.kids {
                k.walk(v)
        }
}

type V1 struct {
}

type Stringer interface {
        String() string
}

type Sizer interface {
        Size() int
}

func (v1 V1)Visit(val interface{}) {
        v, ok := val.(Stringer)
        if !ok { panic("...") }
        fmt.Println(v.String())
}

type V2 struct{
}

func (v2 V2)Visit(val interface{}) {
        v, ok := val.(Sizer)
        if !ok { panic("...") }
        fmt.Println(v.Size())
}

var v1 V1
var v2 V2

...
        t *Tree
        ...
        t.walk(v1)
        t.walk(v2)

[1] I ended up rewriting it from scratch by simply observing
its behavior. There were many other problems as well such as
linear search and what not.  The rewrite took fraction of a
second and cut down everyone's build time by 3 minutes!

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to