Write Behavioral Code
Writing behavioral code is the holy grail of clean code. Behavioral code adds a functional abstraction layer over the implementation.
Traditional coding focuses on the how, with specific steps that achieve a desired outcome. This code is tightly coupled and difficult to maintain, usually implemented in an imperative way. When you make changes in one area you could have unforeseen consequences elsewhere, making updates and maintenance fixes a complex and time-consuming endeavor.
Behavioral code shifts the focus to the system’s expected behavior (aka, the what), abstracting away implementation specifics and focusing on the desired outcome.
Consider the following algorithm in Java:
public int sumOfSquaresOfEvenNumbers(List<Integer> numbers) { int sum = 0; for (int number : numbers) { if (number % 2 == 0) { sum += number * number; } } return sum; }
Here’s a more declarative and behavioral version,closer to the math domain using maps and filters:
public int sumOfSquaresOfEvenNumbers(List<Integer> numbers) { return numbers.stream() .filter(number -> number % 2 == 0) .mapToInt(number -> number * number) .sum(); }
Defining the Behavior of an Object
Whenever you need to model a real-world domain object, you should start with the expected behavior like in this example:
public class Robot { public void move(int deltaX, int deltaY) { } public void grab(PhysicalObject object) { } public void rechargeBattery() ...
Get Write Behavioral Code 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.