Super Functions Mean Super Problems

A game-changer habit in Software Craftsmanship

“Writing clean code is what you must do in order to call yourself a professional. There is no reasonable excuse for doing anything less than your best.”

Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship

I guess this quote was crucial in my professional career as a Software Engineer. Coding is more than just writing lines of instructions to perform a task. Coding is full of concepts. Though it takes time to learn the complexes, one essential skill is to use functions (or methods) to group up and better structure the code writing. Two simple habits may improve your code writing experience whenever creating any functions: Meaningful Names and Do One Thing. The goal of this article is to present how to practice them in order to better develop Software.

Issue Example

Reading some random source code, you found a function named saveForm. Without looking inside, any programmer would take for granted that only instructions regarding saving steps were placed into this function. Running tests, the Software behaves unexpectedly. Debugging to see where the problem lies, you realize this function not only saves the form but also validates its fields and might trigger failures that prevent the goal of saving.

Have a look at the following code snippet:

public static void main(String[] args) {
NumberUtils.addTwoNumbers(null, null);
}

private static class NumberUtils {

public static int addTwoNumbers(String inputOne, String inputTwo) {
int numberOne;
int numberTwo;
if (inputOne != null) {
if (inputTwo != null) {
if (!inputOne.isEmpty() && !inputTwo.isEmpty()) {
numberOne = Integer.valueOf(inputOne);
numberTwo = Integer.valueOf(inputTwo);
} else {
return 0;
}
} else {
return 0;
}
} else {
return 0;
}
return numberOne + numberTwo;
}
}

So, what does the above addTwoNumbers do in fact?

  • Validate inputs
  • Convert inputs from string to integer
  • Return 0 for invalid inputs
  • (Finally & Possibly) Add two numbers

In programming, creating a function to add two numbers is a simple task. Writing code in a comprehensible way to achieve this purpose might not be. By making sure that functions only do only one thing you can give them a meaningful name, avoid code duplication, and last but not least, design better test cases.

Bonus Habit

Speaking about great habits and taking advantage of the previous issue, every time you can not create a function from zero, code refactoring will be needed. Consider practicing Code refactoring as another important habit since this is the process of modifying existing code without changing its functionality. This might include reorganizing the code to make it more readable, maintainable, or even efficient by removing redundant and unnecessary code. The main objective of refactoring is to improve the overall quality of the codebase, making it easier to understand, modify, and (as previously mentioned) test.

In other other words, why is code refactoring so important? Pretty simple:

You can’t write more code if you can’t understand what’s already written.

Meaningful Names & Do One Thing Habits

Here are four steps to enhance how addTwoNumbers is written:

  1. Add a try-catch block

You don’t want your entire Software to crash because of an unhandled error. By leaving an explicit conversion without a try-catch block, whenever someone sets inputOne or inputTwo with any value that is not an integer, the function would crash trying to convert these inputs.

public static int addTwoNumbers(String inputOne, String inputTwo) {
int numberOne = 0;
int numberTwo = 0;
if(inputOne != null) {
if(inputTwo != null) {
if(!inputOne.isEmpty() && !inputTwo.isEmpty()){
try {
numberOne = Integer.valueOf(inputOne);
numberTwo = Integer.valueOf(inputTwo);
} catch (Exception exception) {
return 0;
}
} else {
return 0;
}
} else {
return 0;
}
} else {
return 0;
}
return numberOne + numberTwo;
}

2. Validate each input separately

public static int addTwoNumbers(String inputOne, String inputTwo) {
int numberOne = 0;
if(inputOne != null && !inputOne.isEmpty()) {
try {
numberOne = Integer.valueOf(inputOne);
} catch (Exception exception) {
return 0;
}
}

int numberTwo = 0;
if(inputTwo != null && !inputTwo.isEmpty()) {
try {
numberTwo = Integer.valueOf(inputTwo);
} catch (Exception exception) {
return 0;
}
}

return numberOne + numberTwo;
}

3. Create a function to do one thing with a meaningful name

After splitting each input validation, it becomes a much more visible similarity between what is done to inputOne and inputTwo. Now create a new function just for validation with a proper name.

public static int addTwoNumbers(String inputOne, String inputTwo) {
int numberOne = validateInput(inputOne);
int numberTwo = validateInput(inputTwo);
return numberOne + numberTwo;
}

public static int validateInput(String input){
try {
return Integer.valueOf(input);
} catch (Exception exception) {
return 0;
}
}

4. Increment the refactoring

A few steps later and addTwoNumbers still doesn’t have a meaningful name to describe its true objective. If a function is supposed to add two numbers, then it shouldn’t be validating inputs on its scope. Remember:

“Functions should do one thing. They should do it well. They should do it only.”

Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship

The ultimate step here is to move the validation outside of the addition, thus only one thing will be executed per function.

This is how your final version should look like:

public static void main(String[] args) {
final int numberOne = NumberUtils.validateInput("2");
final int numberTwo = NumberUtils.validateInput("3");
final int result = NumberUtils.addTwoNumbers(numberOne, numberTwo);
}

public static class NumberUtils {

public static int addTwoNumbers(int numberOne, int numberTwo) {
return numberOne + numberTwo;
}

public static int validateInput(String input){
try {
return Integer.valueOf(input);
} catch (Exception exception) {
return 0;
}
}
}

As a Developer, you have to take care of your code. Always. The habits presented here are crucial to engineering scalable Software. But don’t go big at once on your tweaks looking for the perfect code writing experience. Keep in mind that it’s also your duty to provide Stakeholders with valuable Software increments and to solve this dilemma, balance will be required.

Want to share your Clean Code story? Tell me more about it in the comments. Thank you for clapping & sharing if you enjoyed it, and don’t forget to follow me to stay tuned for upcoming articles! =}

References

Level Up Coding

Thanks for being a part of our community! Before you go:

🚀👉 Join the Level Up talent collective and find an amazing job


Super Functions Mean Super Problems was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Victor Oliveira

A game-changer habit in Software Craftsmanship

“Writing clean code is what you must do in order to call yourself a professional. There is no reasonable excuse for doing anything less than your best.”
Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship

I guess this quote was crucial in my professional career as a Software Engineer. Coding is more than just writing lines of instructions to perform a task. Coding is full of concepts. Though it takes time to learn the complexes, one essential skill is to use functions (or methods) to group up and better structure the code writing. Two simple habits may improve your code writing experience whenever creating any functions: Meaningful Names and Do One Thing. The goal of this article is to present how to practice them in order to better develop Software.

Issue Example

Reading some random source code, you found a function named saveForm. Without looking inside, any programmer would take for granted that only instructions regarding saving steps were placed into this function. Running tests, the Software behaves unexpectedly. Debugging to see where the problem lies, you realize this function not only saves the form but also validates its fields and might trigger failures that prevent the goal of saving.

Have a look at the following code snippet:

public static void main(String[] args) {
NumberUtils.addTwoNumbers(null, null);
}

private static class NumberUtils {

public static int addTwoNumbers(String inputOne, String inputTwo) {
int numberOne;
int numberTwo;
if (inputOne != null) {
if (inputTwo != null) {
if (!inputOne.isEmpty() && !inputTwo.isEmpty()) {
numberOne = Integer.valueOf(inputOne);
numberTwo = Integer.valueOf(inputTwo);
} else {
return 0;
}
} else {
return 0;
}
} else {
return 0;
}
return numberOne + numberTwo;
}
}

So, what does the above addTwoNumbers do in fact?

  • Validate inputs
  • Convert inputs from string to integer
  • Return 0 for invalid inputs
  • (Finally & Possibly) Add two numbers

In programming, creating a function to add two numbers is a simple task. Writing code in a comprehensible way to achieve this purpose might not be. By making sure that functions only do only one thing you can give them a meaningful name, avoid code duplication, and last but not least, design better test cases.

Bonus Habit

Speaking about great habits and taking advantage of the previous issue, every time you can not create a function from zero, code refactoring will be needed. Consider practicing Code refactoring as another important habit since this is the process of modifying existing code without changing its functionality. This might include reorganizing the code to make it more readable, maintainable, or even efficient by removing redundant and unnecessary code. The main objective of refactoring is to improve the overall quality of the codebase, making it easier to understand, modify, and (as previously mentioned) test.

In other other words, why is code refactoring so important? Pretty simple:

You can’t write more code if you can’t understand what’s already written.

Meaningful Names & Do One Thing Habits

Here are four steps to enhance how addTwoNumbers is written:

  1. Add a try-catch block

You don’t want your entire Software to crash because of an unhandled error. By leaving an explicit conversion without a try-catch block, whenever someone sets inputOne or inputTwo with any value that is not an integer, the function would crash trying to convert these inputs.

public static int addTwoNumbers(String inputOne, String inputTwo) {
int numberOne = 0;
int numberTwo = 0;
if(inputOne != null) {
if(inputTwo != null) {
if(!inputOne.isEmpty() && !inputTwo.isEmpty()){
try {
numberOne = Integer.valueOf(inputOne);
numberTwo = Integer.valueOf(inputTwo);
} catch (Exception exception) {
return 0;
}
} else {
return 0;
}
} else {
return 0;
}
} else {
return 0;
}
return numberOne + numberTwo;
}

2. Validate each input separately

public static int addTwoNumbers(String inputOne, String inputTwo) {
int numberOne = 0;
if(inputOne != null && !inputOne.isEmpty()) {
try {
numberOne = Integer.valueOf(inputOne);
} catch (Exception exception) {
return 0;
}
}

int numberTwo = 0;
if(inputTwo != null && !inputTwo.isEmpty()) {
try {
numberTwo = Integer.valueOf(inputTwo);
} catch (Exception exception) {
return 0;
}
}

return numberOne + numberTwo;
}

3. Create a function to do one thing with a meaningful name

After splitting each input validation, it becomes a much more visible similarity between what is done to inputOne and inputTwo. Now create a new function just for validation with a proper name.

public static int addTwoNumbers(String inputOne, String inputTwo) {
int numberOne = validateInput(inputOne);
int numberTwo = validateInput(inputTwo);
return numberOne + numberTwo;
}

public static int validateInput(String input){
try {
return Integer.valueOf(input);
} catch (Exception exception) {
return 0;
}
}

4. Increment the refactoring

A few steps later and addTwoNumbers still doesn’t have a meaningful name to describe its true objective. If a function is supposed to add two numbers, then it shouldn’t be validating inputs on its scope. Remember:

“Functions should do one thing. They should do it well. They should do it only.”
Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship

The ultimate step here is to move the validation outside of the addition, thus only one thing will be executed per function.

This is how your final version should look like:

public static void main(String[] args) {
final int numberOne = NumberUtils.validateInput("2");
final int numberTwo = NumberUtils.validateInput("3");
final int result = NumberUtils.addTwoNumbers(numberOne, numberTwo);
}

public static class NumberUtils {

public static int addTwoNumbers(int numberOne, int numberTwo) {
return numberOne + numberTwo;
}

public static int validateInput(String input){
try {
return Integer.valueOf(input);
} catch (Exception exception) {
return 0;
}
}
}

As a Developer, you have to take care of your code. Always. The habits presented here are crucial to engineering scalable Software. But don’t go big at once on your tweaks looking for the perfect code writing experience. Keep in mind that it's also your duty to provide Stakeholders with valuable Software increments and to solve this dilemma, balance will be required.

Want to share your Clean Code story? Tell me more about it in the comments. Thank you for clapping & sharing if you enjoyed it, and don’t forget to follow me to stay tuned for upcoming articles! =}

References

Level Up Coding

Thanks for being a part of our community! Before you go:

🚀👉 Join the Level Up talent collective and find an amazing job


Super Functions Mean Super Problems was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Victor Oliveira


Print Share Comment Cite Upload Translate Updates
APA

Victor Oliveira | Sciencx (2023-02-27T01:38:05+00:00) Super Functions Mean Super Problems. Retrieved from https://www.scien.cx/2023/02/27/super-functions-mean-super-problems/

MLA
" » Super Functions Mean Super Problems." Victor Oliveira | Sciencx - Monday February 27, 2023, https://www.scien.cx/2023/02/27/super-functions-mean-super-problems/
HARVARD
Victor Oliveira | Sciencx Monday February 27, 2023 » Super Functions Mean Super Problems., viewed ,<https://www.scien.cx/2023/02/27/super-functions-mean-super-problems/>
VANCOUVER
Victor Oliveira | Sciencx - » Super Functions Mean Super Problems. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/02/27/super-functions-mean-super-problems/
CHICAGO
" » Super Functions Mean Super Problems." Victor Oliveira | Sciencx - Accessed . https://www.scien.cx/2023/02/27/super-functions-mean-super-problems/
IEEE
" » Super Functions Mean Super Problems." Victor Oliveira | Sciencx [Online]. Available: https://www.scien.cx/2023/02/27/super-functions-mean-super-problems/. [Accessed: ]
rf:citation
» Super Functions Mean Super Problems | Victor Oliveira | Sciencx | https://www.scien.cx/2023/02/27/super-functions-mean-super-problems/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.