Improved Code Quality

This lesson explains how the use of functions improves the code quality.

Code quality through functions #

Functions can improve the quality of code. Smaller functions with fewer responsibilities lead to programs that are easier to read and maintain.

Code duplication is harmful #

One aspect that is highly detrimental to program quality is code duplication. Code duplication occurs when there is more than one piece of code in the program that performs the same task.
Although this is sometimes done intentionally by copying lines of code around, it may also happen accidentally when writing separate pieces of code.

One of the problems with pieces of code that duplicate essentially the same function is that they present multiple chances for bugs to crop up. It can be hard to make sure that we have fixed all the places where we introduced the problem, as they may be spread around. Conversely, when the code appears in only one place in the program, then we only need to fix it at that one place to get rid of the bug once and for all.

Functions are closely related to the craft aspect of programming. We should always be on the lookout for code duplication and continually try to identify commonalities in code that could be moved to individual functions.

Example #

Let’s start with a program that contains some code duplication. Let’s see how that duplication can be removed by moving code into functions. The following program reads numbers from the input. It first displays them in the order that they have been read and then displays them in sorted numerical order:

Get hands-on with 1200+ tech skills courses.