Code Smells ♨️– Fallacious Comment

Martin Jurran
Software Design Patterns
2 min readFeb 13, 2024

Comments are different from normal code because they don’t actually do anything when the program runs.

Sometimes, when we change the code, we forget to update the comments around it. This can cause problems if the comments don’t match what the code is doing.

Ideally, we should write comments that explain why we’re doing something instead of just what we’re doing. These types of comments are less likely to become outdated.

“Comments can be erroneous for a variety of reasons, including obsolete knowledge, incomplete information, and simple mistakes. The best prevention for fallacious comments is to establish a development process that constrains comments to describe only the code that follows them and to require comments to be maintained along with code.” (Steve McConnell, Code Complete — Google Books)

It’s also not a good idea to have comments that only explain what the code is doing because this can be a sign that the code needs to be refactored.

Causation

Sometimes when developers are in a rush to finish their work, they might forget to update the comments in the code.

They might think that everything is correct because their unit tests are passing, but comments can’t be tested automatically like code.

This means that mistakes in comments might not be noticed until someone reads them and realizes they don’t match what the code is actually doing. It’s important to take the time to double-check everything, even if it feels like you’re in a hurry, to make sure that your code is easy to understand and maintain.

Example

Smelly

public void CreateAddress(string firstName, string lastName, string street, string city, string state, string zip)
{
// Create a new address object
Address newAddress = new Address();

// Set the properties of the address object
newAddress.FirstName = firstName;
newAddress.LastName = lastName;
newAddress.Street = street;
newAddress.City = city;
newAddress.State = state;
newAddress.Zip = zip;

// Save the new address to the database
_db.Add(newAddress);
_db.SaveChanges();
}

Solution

public void AddNewAddressToDatabase(string customerFirstName, string customerLastName, string streetAddress, string cityAddress, string stateAddress, string zipCode)
{
// Create a new address object with the provided parameters
Address newAddress = new Address()
{
FirstName = customerFirstName,
LastName = customerLastName,
Street = streetAddress,
City = cityAddress,
State = stateAddress,
Zip = zipCode
};

// Save the new address object to the database using Entity Framework
_dbContext.Addresses.Add(newAddress);
}

Refactoring

Remove Inconsistency

(Photo by the author, Illustrations by Takashi Mifune under free use)

--

--

Martin Jurran
Software Design Patterns

Personal blog of a Software Engineer | Azure DevOps, C#/.NET, JavaScript