Programming: The case for optionality

Ambiguity is a complexity

Two direction panels: one saying “Optional”, pointing left, the other saying “Mandatory”, pointing right.
Two direction panels: one saying “Optional”, pointing left, the other saying “Mandatory”, pointing right.
Do the right thing.

Unspoken magic values

defaultOptions = {   // Prototype
firstName: false,
lastName: true
}


formatPeople (people, options) {
options = {...defaultOptions, options}
const first = options.firstName ? people.firstName : ''
const last = options.lastName ? people.lastName : ''
formatted = `${first}${first && last ? ' ' : ''}${last}`
return formatted
}
formatPeople (people1, {firstName: true})
formatPeople (people, options) {
const first = options.firstName ? people.firstName : ''
const last = options.lastName ? people.lastName : ''
return `${first}${first && last ? ' ' : ''}${last}`
}
formatPeople (people1, {firstName: false, lastName: true})

The API that may do nothing

function f (param?) {
if (param) { // Or if (!param) return
// All code
}
}
f(x)
y = null
f(y) // How do I know if it won't do anything?
f() // Should not be allowed, but it is
function f (param) {
// handle param
}
if (x) {
f (x)
}
function f (param1, param2?) {
if (param2) {
// handle params
}
}
x = buildX() // costly
y = undefined
f(x, y) // You built x for nothing

Signing two contracts at a time

function f (param1, param2?) {
handleParam1(param1) // Could be at function end as well
if (param2) {
handleParam2(param2)
}
}
function f1 (param1) {
handleParam1(param1)
}
function f2 (param1, param2) {
f1(param1)
handleParam2(param2)
}

Conclusion

Written by

Software engineer for three decades, I would like to share my memory. Also author of https://rr0.medium.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store