Maintain function parameter readability in Swift

with max 2 parameters only

Gideon Benz
Style Theory Engineering & Data
3 min readJun 10, 2020

--

Sometimes function is use to execute specific task either calculation, configuration of a view, or others. it helps us a lot in doing some repetitive specific task, making our codes neat that increase the readability for other developers who might review your code. but some time I find it hard to read a function.

for me it’s hard to read if:

  1. naming of the function does not match with what it executes
  2. have many parameters
  3. naming for the arguments are ambiguous

for this time, I’m going to talk about how to reduce function’s parameters and also I will be sharing my mistake and improvement in order to solve this

here are examples issue when I was creating a function:

my common mistake function

by looking at submitForm function I had thought like why not using struct and create a SchoolRegistrationForm, but what if SchoolRegistrationForm is not the only object we need in the function? maybe in iOS development some of you might familiar with userId / region / something that are not actually have direct ussage in a function.

hmmmm that’s a lot of parameters…

Using struct as parameters

a simple post request function

well pretty good, it improve the readability of the function.

but maybe I can improve it a little further

unsplash.com / Christian Escobar

summoning Tupple to the rescue

with this adjustment now I can use it like this

Why is this kind of function is good?

the function only contain 2 parameters well Uncle Bob tell us that three is the maximum arguments in a function, which is great we can break it down to 2 parameters.

Tips

tupple is commonly use to make a compound value and for this case I make it as an argument named userProperties. make sure you’re not abusing tupple to much, you should consider using struct if the variable have the same purpose

Wrap Up

Function is one of the most common thing in development. it’s our job to keep our function readability so every developers might understand with a single glance of an eye. there’re many factors about readability in function and one of it is too many arguments so because of it sometime some of you might having trouble when reading a single function. if we are usual to consider and learn about impact & meaning of your creation you might get rid of this problem in no time.

Thank you for your time on reading my medium post, Hope it can be helpful :)

--

--