Posts

Showing posts from December, 2020

The Cone of Code Uncertainty

Image
As hurricanes approach the shores of North America, we are barraged with maps of possible tracks those storms can take. Those tracks start pretty close together, but diverge widely the further into the future they predict. Simplified, those storm tracks form a cone of uncertainty . A storm in the Atlantic could slide into the Gulf of Mexico and land anywhere from the Texas-Mexico border to Panama City Beach, FL. It all depends on a myriad of tiny factors to turn the storm this way or that. As time progresses, the storm moves along, and the cone of uncertainty shrinks. Its eventual location becomes clearer to predict, and we can more effectively target resources. Cone of Uncertainty for Hurricane Ike, source Much like hurricanes, running code lives in a cone of uncertainty. A function or method call is a mysterious black box until we have a result. If something goes wrong, we must delve into this cone of code uncertainty to find the problem. We use log statements and de

Assuming Maintainability

Bugs are bad assumptions. Making assumptions explicit leads to more direct, easier to maintain code. Bugs are bad assumptions. Therefore, to reduce bugs and make code more maintainable, we need to make our assumptions as explicit as we can. We make our assumptions explicit in five ways: comments, tests, conditionals, assertions, and encapsulation with the type system. Each of these ways gives us progressively more assurance that our explicit assumptions are enforced in the code base. They also give us progressively earlier feedback when our code fails to live up to our assumptions. Comments Comments are the simplest way to express an assumption in the code. We write out, in plain language, what our assumption is. We can then read those assumptions quickly when need to use that piece of code. For example, we can state assumptions in method-level comments that describe our parameters. /** * Divide the dividend by the divisor. * @param dividend the number to d

Assuming Debugging

Bugs are bad assumptions . Debugging is the process of testing our assumptions until we discover the invalid one(s). Once found, we can then correct those bad assumptions. The following code generates blog post author statistics for a popular blog site. The statistics show which days of the week authors are making posts. Most of the authors post every day, and extra on Fridays and Saturdays to capture the weekend audience. It has at least one bug. @GET @Path("/authors/{email}/weekly-stats") public UserWeeklyStats calculateWeeklyStats(@PathParam("email") final String email) { final User user = this.userService.byEmail(email); final Map<LocalDate, List<Post>> postsByDate = this.postService.thisWeekGroupedByDateFor(user.id()); if (postsByDate.isEmpty()) { return null; } final Map<DayOfWeek, List<Post>> postsByDayOfWeek = new HashMap<>(); postsByDate.forEach((date, post) -> post