Functions or ‘procedures’ in some programming languages and ‘methods’ in most OOP languages are a set of instructions bundled together to achieve a specific outcome.
Functions are a good way to avoid repetition of code in programs.
We can Pass some values (parameters or arguments) to them and return some calculated values from them as well.
Functions act as a basic building block for any program and it is very important that we write functions in a right manner that the next person can easily understand.
what is right way? well if you go on exploring you might find a lot of articles as to how to write a function, here is my piece on what a well structured function should look like.
//naming a function is the most important task, besides the actual functionality😜
function nameThatDescribesWhatTheFunctionDoes (catSound, dog){
//defaulting arguments, avoids dealing with undefined arguments
catSound = catSound || "meow"
//type checking or error handling
if(!dog || typeof(dog) !== object || Array.isArray(dog)){
console.warn('Function requires dog argument to be an object');
return false
}
// Returning early, to reduce the CPU cycles or Memory usage
if(someScenarioThatNegatesToRunThisFunction){
return true
}
//Declare the variables that will be used in the funciton logic, this avoid the getting the values by chaining feilds
//and make the code more readable
const eldestPupper = dog.children[0]
let isCat = false
let {sam,tom} = dog.names
//Function logic section(the actual point of the function)
if(eldestPupper.sound === catSound){
isCat = true
}
//Returning the result of logic
return isCat;
}
There are many sections separated by comments in this function, each section can be skipped if not needed or can be much longer as well depending on the use-case, But this is generally the order you go in.
You might have several “early returns” in the “Function logic section” depending on the length.
Though it is possible to default arguments in the function definition (cat = “meow”, dog) , this violates the “Clean code” principle: “One Idea Per Line”.
This keeps the definitions short and clean, easier to scan quickly when functions are collapsed, but this is my opinion and you might like to default your arguments in a different way.
Why i emphasised on defaulting arguments inside the function is because it allows for much more complex argument defaults, like when you have a detailed object.
Either way, This is how i feel a function should be written and you might have some other ideas, feel free to share in comments.
Top comments (0)