Think in Functions, Not Code
Think in Functions, Not Code
Imagine someone asks you to build an online shopping application. Would you immediately start writing Python code? Experienced programmers almost never do. Instead, they first ask a different question. "What are the individual tasks that this application must perform? " The application should allow users to log in. It should search for products. It should add products to a cart. It should calculate the total bill. It should process the payment. It should generate an invoice. Notice what has happened. Without writing a single line of code, the large problem has already been broken into several smaller problems. This is exactly why functions exist. A function is simply a named block of code designed to perform one specific task. Rather than solving an entire problem at once, we solve one small problem inside a function. Then we combine many functions to build the complete application. Think of constructing a house. Nobody builds the entire house in one step. One team lays the foundation. Another constructs the walls. Another installs the electrical wiring. Another paints the rooms. Each team has a clearly defined responsibility. When every team finishes its own work, the house is complete. Programming follows the same philosophy. Each function should have one responsibility. One function validates a password. Another calculates a discount. Another sends an email. Another saves data to a database. Keeping functions focused makes programs easier to understand, easier to test, and much easier to maintain. Every function also has a simple structure. It has a name, so other programmers know what it does. It can receive parameters, which are pieces of information supplied to the function. It performs some work. And finally, it may return a result back to the caller. If you think about it, a function behaves very much like a machine. You give it an input, it performs a well-defined task, and it produces an output. As your applications become larger, you'll discover that many functions naturally belong to certain objects. A function that belongs to an object is called a method. So methods are not a completely new idea—they are simply functions that are owned by a class or an object. This is why experienced programmers don't begin by asking, "What code should I write? " They begin by asking, "What functions does this problem need? " Once the functions are identified, writing the program becomes much simpler. But even with well-designed functions, another challenge remains. What if the same operation has to be performed hundreds or even thousands of times? Writing the same instructions repeatedly would make programming slow and inefficient. To solve that problem, programming languages introduce one of their most powerful ideas—loops.
