3 Writing reusable code with functions and subroutines

This chapter covers

  • What procedures are and why we use them
  • How procedures break down into two kinds: functions and subroutines
  • Writing procedures that don’t cause side effects
  • Writing procedures that work on both scalars and arrays

In the previous chapter, you learned about the core elements of Fortran: declaration of scalar and array variables, do loops to iterate parts of the code a desired number of times, and arithmetic expressions and assignments. We used them to write a simple simulator that predicts the motion of an object in space and time due to background flow. As we learn new Fortran features, we’ll continuously expand and improve our app to produce more realistic simulations. This chapter introduces functions and subroutines, which will help us manage the complexity of our growing app.

This chapter is all about scaling a growing app while maintaining simplicity through code reuse. Our minimal working app has so far been organized as a single program, with a number of statements that the program executes top to bottom. This is the imperative style of programming--you’re telling the computer what to do, one statement after another. This approach worked well because we tackled a relatively simple problem. However, we’ll now prepare for a more realistic fluid dynamics simulation, which will require more moving parts and complexity.

3.1 Toward higher app complexity

3.1.1 Refactoring the tsunami simulator

3.1.2 Revisiting the cold front problem

3.1.3 An overview of Fortran program units

3.2 Don’t repeat yourself, use procedures

3.2.1 Your first function

3.2.2 Expressing finite difference as a function in the tsunami simulator

3.3 Modifying program state with subroutines

3.3.1 Defining and calling a subroutine

3.3.2 When do you use a subroutine over a function?

3.3.3 Initializing water height in the tsunami simulator

3.4 Writing pure procedures to avoid side effects

3.4.1 What is a pure procedure?

3.4.2 Some restrictions on pure procedures

3.4.3 Why are pure functions important?

3.5 Writing procedures that operate on both scalars and arrays

3.6 Procedures with optional arguments

3.7 Tsunami simulator: Putting it all together

3.8 Answer key

3.10 Further reading

sitemap