Chapter 2. Write Short Units of Code
Any fool can write code that a computer can understand. Good programmers write code that humans can understand.
Limit the length of code units to 15 lines of code.
Do this by not writing units that are longer than 15 lines of code in the first place, or by splitting long units into multiple smaller units until each unit has at most 15 lines of code.
This improves maintainability because small units are easy to understand, easy to test, and easy to reuse.
Units are the smallest groups of code that can be maintained and executed independently. In Java, units are methods or constructors. A unit is always executed as a whole. It is not possible to invoke just a few lines of a unit. Therefore, the smallest piece of code that can be reused and tested is a unit.
Consider the code snippet presented next. Given a customer identifier in a URL, this code generates a list of all of the customerâs bank accounts along with the balance of each account. The list is returned as a string formatted according to the JSON standard, and also includes the overall total balance. It checks the validity of the bank account numbers using a checksum and skips invalid numbers. See the sidebar âThe 11-Check for Bank Account Numbersâ for an explanation of the checksum used.
Get Building Maintainable Software, Java Edition 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.