How to Code in Style?

You may have hit that issue in a college project or other hobby project you did with others. You wrote a certain class or a module and a few weeks later, a colleague tries to update it and he tries to update the names or the style of the code. You may have engaged in an argument about the best way to write a certain function because of that. The reality of it is that there are several ways to write a certain piece of code and people will prefer different styles for many reasons.

People may disagree about where to place the braces in a block of code: 

for i in 0…100 {

    doSomething(i)

}

vs. 

for i in 0…100

{

    doSomething(i)

}

But disagreements may impact things that are more fundamental such as error handling. Assume that you are writing a function that validates some inputs and then creates an order. Should the validation logic throw an exception when it fails to create an order? Or should it returns a null order object and rely on the user code to handle a null value. This disagreement has a fundamental impact on the design of the code and we may not have an answer that handles all the cases. If you are validating user input on a client form, it may be useful to throw an exception and have the calling code show an error message to the user. But if you are writing a batch job handling a lot of data, you may want to ignore validation failures and just return a null object and rely on the calling code to skip nulls. 

To prevent these arguments from happening over and over, many teams and organizations create coding style guides. A style guide tells everyone in the team who uses a certain programming language on how to handle certain cases.

Coding styles will govern things such as class and variable names, which language features to use, patterns to use and avoid, and many other issues that can cause friction between team members.

For example, I recommend going through Google’s C++ style guide. The guide gives you rules for the naming of classes and objects, how to layout header files, how to pass data to functions, and how to return objects. It also prohibits the use of some language features such as exceptions due to performance impact.

When you join a new organization, you should learn about the coding style for the organization. Following the rules may be painful in the beginning, especially if some of the rules contradict something you are accustomed to doing or believing in, such as C++ exceptions. But following a standard set of style rules is an important mark of a professional organization. It avoids repeated arguments between team members and makes it easy for different team members to read and understand each other’s code. It makes things predictable which is important when you share the same codebase with others.