Northcentral Technical College Introduction To Programming
10-152-310
Introduction to Programming with JavaScript NTC 10-152-310

Learning Plan 5 Process Three Characters - Two Functions

# Example: Process Three Characters - Two and Four Functions

#### File: /Learning Plan 5/example5.html

### 1. Problem Statement

> Design a program that will prompt a terminal operator for three characters, accept those characters as input, sort them into ascending sequence and output them to the screen. The program is to continue to read characters until 'X,X,X' is entered.

### 2. Program Planning Lists

- The Planning Lists

### 3. Initial Program - One Function

- Here's the program that we want to break up with functions.

- That's a bit clumsy, time for surgery.

### 4. First Breakup

- One good way to simplify this would be to reduce the size of the loop. Keeping loop code small is always a good idea. When it's small we can better see errors and follow the logic.
- We're going to just take the `if` statements and put them into another algorithm and replace them with a call to the new function.
- We'll also have to take the variables and make them global.

### 5. Now a much better version!

- What could be better?
- First, we need to DRY (Don't Repeat Yourself!) up this program! There is duplicated code that will go in its own function.
- Also, it's a really good idea to have our mainline function not have very much lower-level code, if any. So, let's take out everything and replace it with function calls.
- Here's the new program.
- Here's the code:

- Here's the output (once I uncomment the function call)

- Much better! We don't have any code being duplicated.
- We also had a bonus. Did you notice that the function sortThreeCharacters() looked exactly the same in both versions? That's because they are the same function! I didn't have to write a new version, the first version was in the file and I just used it again.
- Look at all the functions. Each one looks very simple. This is what we're after, each function does just one thing.
- If we find that a function does too much then we can make more functions.
- Note: The functions are declared before they are called.