Steps to Write a Function

◀ Understand What the Function Should Do▶ Write a function - Practice #1
Amazon Just like writing a program, writing a function should be done on paper and coded on a computer. The four steps of writing a function is:
  • Step 1: write a skeleton of the function, including determining preconditions and postconditions
  • Step 2: write a summary of variables and refine the skeleton of the function as necessary
  • Step 3: determine interrelations and states of variables
  • Step 4: code, test, and optimize; go back to any previous step as necessary
Having worked through the previous chapter, you shouldn’t have difficulty understanding the requirements of each step. One thing to note is that we no longer need to worry about scopes of variables because each variable to be used is declared inside the function.

As we all know, the design of a function is critical to writing a good function. Step 4 follows the design step 1 through 3 develop; so don’t hurry through them. If while coding you realize that a much better design exists and you decide to use that design, you will need to go back to step 1 and some of your work, if not all, goes down the drain.

The key to judging whether a function design is sound is to go through it carefully, asking yourself whether you really need to do the current task. You will get better and better at this if you do this every time you write a function.

After you complete step 2, you are encouraged to go through the skeleton with a sample set of arguments in mind. Careful review could reveal hidden errors and potential bugs.

Next let’s practice writing a function efficiently!

Questions? Let me know!