Name

PRG-01: Encapsulate business rules and formulas behind accurately named functions

Synopsis

This might be one of the most important best practices you will ever read—and, we hope, follow. There is only one aspect of every software project that never changes: the fact that everything always changes. Business requirements, data structures, user interfaces: all of these things change and change frequently. Your job as a programmer is to write code that adapts easily to these changes.

So whenever you need to express a business rule (such as, “Is this string a valid ISBN?”), put it inside a subroutine that hides the individual steps (which might change) and returns the results (if any).

And whenever you need a formula (such as, “the total fine for an overdue book is the number of days overdue times $.50”), express that formula inside its own function.

Example

Suppose that you must be at least 10 years old to borrow books from the library. This is a simple formula and very unlikely to change. We set about building the application by creating the following logic:

      IF  v_dob > DATE_SUB(now(  ), INTERVAL 10 YEAR) THEN
        SELECT 'Borrower must be at least 10 yrs old';
      ELSE
        INSERT INTO borrower
          (firstname,surname,date_of_birth)
        VALUES( v_firstname, v_surname, v_dob);
      END IF;

Later, while building a batch-processing script that checks and loads over 10,000 borrower applications, we include the following check in the program:

 load_data:BEGIN IF DATEDIFF(now( ), v_dob)/365 < 10 THEN select ('Borrower ...

Get MySQL Stored Procedure Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.