Skip to content

The visitor pattern #4

Closed
Closed
@bali182

Description

@bali182

With how the visitor pattern is currently represented here I honestly don't see the benefits of this pattern used properly. Basically it doesn't offer anything over this:

function visit(e, callback) {
  if (e instanceof Operation) {
    return callback(e)
  }
  throw new TypeError('not an Operation')
}

The current version would work in languages with static typing since you can have multiple overloads of the identically named visit methods, but in javascript this is not possible.

So what I'd recommend instead is this:

class Operation {
  accept(visitor) {
    throw new Error('You should really implement this')
  }
}

class Sum extends Operation {
  accept(visitor) {
    return visitor.visitSum(this)
  } 
}

class Min extends Operation {
  accept(visitor) {
    return visitor.visitMin(this)
  } 
}

// ...

This way in your visitor you can properly distinguish (and in a way are forced to) all the subclasses.

Now a more javascript-idiomatic way (in my opinion at least) would be to have something like this:

class Operation { /*...*/ }
class Sum extends Operation { /*...*/ }
class Min extends Operation { /*...*/ }
class Num extends Operation { /*...*/ }

const createVisitor = (config = {}) => (input, ...args) => {
  const method = input instanceof Operation
    ? config[input.constructor.name] || config.Any || (() => { })
    : config.Unknown || (() => { })
  return method.call(config, input, ...args)
}

const visitor = createVisitor({
  Sum(sum) {
    return "It's a Sum"
  },
  Min(min) {
    return "It's a Min"
  },
  Any(op) {
    return "I don't care what it is, but it's an Operation"
  },
  Unknown(alien) {
    throw new Error("I don't know what it is")
  }
})

expect(visitor(new Sum())).toBe("It's a Sum")
expect(visitor(new Min())).toBe("It's a Min")
expect(visitor(new Num())).toBe("I don't care what it is, but it's an Operation")
expect(visitor(new Operation())).toBe("I don't care what it is, but it's an Operation")
expect(() => visitor(null)).toThrowError("I don't know what it is")

This is very far from the traditional visitor pattern, but achieves the same thing.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions