Maintain function parameter readability in Swift
with max 2 parameters only
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:
- naming of the function does not match with what it executes
- have many parameters
- 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
func submitForm(name: String, class: String, age: Int, height: Float, weight: Float, fatherName: String, motherName: String, schoolFee: Float, homeRoomTeacher: String) {
//post request an API using added parameters
}
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.
Using struct as parameters
well pretty good, it improve the readability of the function.
but maybe I can improve it a little further
summoning Tupple to the rescue
func submitForm(schoolRegistrationForm: SchoolRegistrationForm, userProperties: (userId: String, region: Region)) {
//post request an API using added parameters
}
with this adjustment now I can use it like this
submitForm(schoolRegistrationForm: SchoolRegistrationForm(), userProperties: ("gideon1", .indonesia))
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 :)