Bitpath

Lesson 2 · Unit 02

Builders and options

Named settings, one table of defaults, one final check

12 exercisesabout 3 min

What you practise

  • Ten optional arguments, an options object, a builder that validates at the end, defaults in one place

Try a question from this lesson

Pick one

One of these arguments is the timeout in seconds. Which one?

s = Server("db", 80, True, False, 30, 3)
const s = new Server(
  "db", 80, true, false, 30, 3,
);
const s = new Server(
  "db", 80, true, false, 30, 3,
);

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Name the options

When a call has more than two or three settings, name them. Python has keyword arguments; JavaScript and TypeScript pass one options object.

The call now documents itself, the order stops mattering, and anything left out falls back to a default.

s = Server("db", port=80, tls=True,
           timeout=30)
const s = new Server("db", {
  port: 80,
  tls: true,
  timeout: 30,
});
const s = new Server("db", {
  port: 80,
  tls: true,
  timeout: 30,
});

Python noteA bare * in the signature, as in def __init__(self, name, *, port=80), forces callers to write the names.

TypeScript noteThe options parameter gets a type with optional fields, such as { port?: number; tls?: boolean }, so a misspelt option is a compile error.

Concept

Builder

Some objects are assembled over several steps. A builder collects the settings one call at a time and produces the finished thing in build().

Nothing half-made escapes, and build() is the one place to check that the settings make sense together.

q = Query("users")
q.where("age > 30")
q.limit(10)
print(q.build())
const q = new Query("users");
q.where("age > 30");
q.limit(10);
console.log(q.build());
const q = new Query("users");
q.where("age > 30");
q.limit(10);
console.log(q.build());

9 more exercises in the app

  • 3× type the answer
  • 3× multiple choice
  • 1× fill the blanks
  • 1× true or false
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy