Tuesday, September 22, 2020

Spot the Bug - FOR Loops

The next bug in the Spot the Bug series is one that is seen quite often from new programmers. Can you spot the bug?

This code contains a class that adds two 2x2 matrices together. The class also includes a print method for displaying the matrices in the console. The main program passes in two sample matrices to add together. The bug in this code is that the indices in the AddTwoMatrices method are flipped for the additionalResult object.

This bug is common with new programmers. Unfortunately there is no C# language construct to prevent us from creating this kind of bug. I've included it in this series because it presents a great conversation for a mentor to have with a new developer about programming techniques that can be employed to lessen the chances that a bug like this gets released.

The first thing I would highlight is that this code needs unit tests. Math operations are straightforward to test because they should be operations that have no side effects. The code doing the math operation should also be pure, meaning for the same set of inputs, it always produces the same output. These conditions make unit testing math methods straightforward and these methods should always have accompanying unit tests.

The other thing I would highlight here is that better variable naming may make it easier to see the bug when it does get introduced. (Generally speaking, I don't mind simple counter variables like these in FOR loops being single-letter variables.) More descriptive variable names for the loop counters will make it easier to read the code and reason about the code, making it easier for a developer to see a problem as it is being introduced.

Here is the code with the bug corrected and more descriptive variables to make it more readable.

Even though C# doesn't provide mechanisms to prevent this type of bug, there are some good programming techniques that can be taught and discussed when bugs like this arise.

No comments:

Post a Comment