Posts

Showing posts with the label Assumed Bugs Series

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...

Assuming the Bugs

Writing code is all about making assumptions. Sometimes those assumptions are explicit, but more often we make those assumptions implicitly. We make assumptions about what kinds of parameters we will receive. We make assumptions about what kinds of values methods and functions will return. We make assumptions about the global state. The correctness of our code relies on the correctness of these assumptions. Bad assumptions can wreck our applicatons. We assumed that method never returns null, but turns out it does. Now we have an unexpected NullPointerException crashing through our stack. We assume that we will always average at least one element. Turns out someone wants to average zero elements. Boom, division by zero, ArithmeticException . We make so many assumptions through our codebases, at least a few are going to be wrong. Really, there are many, many assumptions that are wrong. These are bugs. These bad assumptions are all of our bugs. Usually, our assumptions are i...