5. Making Things Modular

5.1. Introduction to Grouping and Separation

This module is about breaking things apart and as much as that, it's also about putting things together. Okay. This sounds almost meaningless, but it isn't. This is another thing we do all the time. It's a way we naturally think. When we group things together, we're also separating them from something else. Think of a book for example. By grouping pages into chapters, you're also making those chapters separate each other.

If you organize your possessions, your clothes or your books, you're both grouping some things together and by nature separating them from something else. Here's my group of fiction books in Fig 5.1.1 separate from my group of nonfiction books.

Image

Fig 5.1.1: Grouping and separation of books

Not only that, but groups can contain other groups. Within my non-fiction group there's travel, there's languages, and there's technical. So, we group and we separate. It makes it easier to understand what we have to manage, what we have, and to find what we want. But in code, what does this mean?

If we have a lot of code and we just wrote it as one continuous list of statements, even if we used if statements and loops, reading, it would be like reading a very technical book written as one massive bunch of sentences with no paragraphs or chapters. You could read it, but there'd be no way to understand the structure of it. So, we don't do this.

First, we can separate our code into multiple files. That's one way to make it easier to manage. But we don't stop there. Within those files, the code can be grouped and divided into different meaningful sections, such as code to connect to a database, code that calculates interest, code that handles the user interface or code that takes care of error messages. See Fig. 5.1.2.

Image

Fig 5.1.2: How we separate code into multiple files

Not only do we group and separate our code, we want ways to group and separate our data. To go from having those individual variables like score, name or balance, to being able to say, here's the group data for all our employees, here's the data for sales for last year, which contains the grouped information for sales for each month, which itself contains the group information about sales for each week.

Image

Fig 5.1.3: Summary of topics to be covered in this chapter, with special focus on Object Orientation

In this chapter we'll begin with functions. They are ways to take some codes that belong together (a section of code) and give it a name so we can reuse it many times. I'll cover the benefits of functions including powerful techniques like recursion. I'll talk about grouping data, see what we can do with composite data types and collections.

I’ll finish with a special focus on object orientation, another way to group and separate our code and data, using a set of ideas common in most popular modern programming languages.