DEV Community

Joshua Lunsford
Joshua Lunsford

Posted on

Build a Different Burger

Main Points

  • Minimize initial arguments with defaults
  • Option to getBurger() at any point in the process

I liked Nishan's Burger Builder article. It utilizes patterns I have been using for years. But it seems I only utilized this chaining pattern with classes and rarely otherwise. Lately I have not been using the class keyword for more functional style of programming. If I had to create a burger builder in the app I'm currently working on at the very moment, here is what it would look like.

'use strict'

const burger = (opts = {}) => {
    let {
        size = 14,
        cheese = false,
        pepperoni = false,
        lettuce = false,
        tomato = false
    } = opts

    const getBurger = () => Object.assign({},{
        size,
        cheese,
        pepperoni,
        lettuce,
        tomato
    })

    const add = topping => ({
        'cheese': () => cheese = true,
        'pepperoni': () => pepperoni = true,
        'lettuce': () => lettuce = true,
        'tomato': () => tomato = true
    }[topping]())

    return {
        getBurger,
        add
    }
}

const myBurger = burger(14)
myBurger.add('cheese')
myBurger.add('lettuce')
myBurger.add('tomato')
myBurger.add('pepperoni')
console.log(myBurger.getBurger())
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
nishparadox profile image
Nishan Pantha

Cool. Thanks for referencing my post.
But it all boils down to use cases​ in the end.
Using a separate builder class enforces the immutability I suppose. The way I see is: it abstracts the object creation effectively.

Collapse
 
roddi profile image
Ruotger Deecke

I would always avoid stringly-typed interfaces. Neither the compiler nor any other tool can check the correctness of your calls.

I also think that both of you are overthinking things. Having a class that needs more than 5 things fed to its constructor is a big red flag and might be your real problem. I'm pretty sure you only use a few of all the possible combinations of objects.

If this is about dependency injection I always use a dependency structure that keeps all needed dependencies and can be passed as one parameter.