4

Lately I've been torn when trying writing classes regarding the number of parameters requested.

A very simple constructor example:

Burger(bun, meat, cheese, lettuce)
    this.bun = bun
    this.meat = meat
    ...

Vs

Burger(grocery)
    this.bun = grocery.bun
    this.meat = grocery.meat
    ...

Both ways are valid approaches. The first way shows exactly what's going into the burger, breaks down the arguments into more general classes so it makes for less coupling, and I think is generally easier to test because the object graph is simpler.

But the second way is a lot simpler, cleaner, and perhaps the burger can require a lot more ingredients, then the arguments in the first way can balloon immensely.

I'd like to know which way would be recommended in a situation like this? Go for the cleaner but more coupled code, or the more verbose way.

Neil
  • 51
  • 2

1 Answers1

5

passing 4+ parameters to any method or constructor is not a good idea or a good design.

I remember that Joshua Bloch (Effective Java) recommend Builder Pattern to this situation (Item 2)

Item 2: Consider a builder when faced with many constructor parameters