Function (Programming) CS Thinking Example 2

Follow the full solution, then compare it with the other examples linked below.

Example 2

medium
Why is it better to write a function `calculateTax(amount, rate)` than to repeat the tax calculation code everywhere?

Solution

  1. 1
    Step 1: Reusability โ€” the function can be called from multiple places with different arguments.
  2. 2
    Step 2: Maintainability โ€” if the tax formula changes, we update only one function instead of every occurrence.
  3. 3
    Step 3: Readability โ€” `calculateTax(100, 0.2)` is clearer than `100 * 0.2` scattered throughout the code.

Answer

Functions improve reusability, maintainability, and readability.
Functions encapsulate logic, reduce code duplication, and make programs easier to understand and maintain. This is a core principle of good software design.

About Function (Programming)

A named, reusable block of code that performs a specific task, taking input (parameters) and optionally returning output (a return value). Functions allow you to write a piece of logic once and use it many times throughout a program.

Learn more about Function (Programming) โ†’

More Function (Programming) Examples