Elegant Swift: Default Parameters vs The Builder Pattern

I was re-reading Effective Java (it is a rainy Sunday afternoon in Vancouver, and if you are stuck at home, and you happen to be European, and therefore you don’t really care about what Americans call “football”, re-reading Effective Java is not as bad as it sounds) when I soon stumbled upon an example that I think highlights the elegance of Swift (and, to be completely fair, also Kotlin’s).

Effective Java’s Item #2 says: Consider a builder when faced with many constructor parameters. Which makes total sense, if you ask me.

I am not going to discuss or justify the Builder Pattern now, but let’s just assume that it is more than justified.

The canonical implementation of the pattern, and I am going to take the liberty of using the code sample used in Effective Java without any modification, would read like the following (servings and servingSize are the only mandatory parameters, the rest are all optional)

If we follow the pattern to the letter, it translates into Swift like this:

Which is a lot of boilerplate, no matter how you look at it.

We have discussed Swift’s Default Parameters before in this blog, but in the context of Dependency Injection, in particular when focusing on testability.

But the thing is that Default Parameters, like many other Swift artifacts (or constructs, or whatever is the right word to refer to “stuff that Swift provides and makes your life easier”) can make code much more concise, readable and easier to understand and reason about while removing some of the bloating that certain languages (I’m looking at you, Java) are known for.

Because when providing default values to all the optional parameters, this is how our NutritionFacts look.

Much better, eh?

One Reply to “Elegant Swift: Default Parameters vs The Builder Pattern”

  1. Better for this use case. But Builder main use case is to separate the “parameter recollection” from the building point. You can pass around a Builder, adding data on each phase and finally call build() to get a nice new object. This is not posible with the initializer with optional parameters approach. So, yes it is nicer, but for me, you are solving other problem 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *