Categories
C#

Curly {braces} Matter!

Blocks like “if“, “for“, “while“, and “using” (and others) should always use the curly braces “{” and “}“.

Code is for humans to read, and compilers to compile. Right?

By properly adding these braces ahead of time before they are needed, you future-proof the code and make the code’s intention (the logic) clear to any future programmer (including yourself).

This is not from an OCD formatting-enthusiast perspective. This is from decades of experience with C# and other {}-like languages.

Sure, one liners do work and they do reduce the total count of lines, but they are prone to bugs that are not immediately apparent to other programmers, compilers, code formatters, or via indentation.

If you use them, that is fine. Just be aware of the potential for issues in the future when someone edits the code.

BTW, If you can provide a reproducible example that causes C# code fail to compile, break, bug out, or crash by adding the proper braces, then please let me know! I’d greatly appreciate it.

Formatters cannot detect the original intent of the programmer. If even a single line of logic is missed (or ran when it should not), then the results of the function, method, or even the whole program could be affected.

Please, Do not write code to the lowest common denominator.

(I’ll link a gist if I ever get a better example completed.)
Here is a simplified example.

public static void RolRorRolRol( ref this UInt64 ul, Int32 n ) {
	if ( n > 2 )
		ul = ( ul << 3 ) | ( ul >> ( 64 - 3 ) );
	if ( ul < 10 )
		ul = ( ul << ( 64 - 4 ) ) | ( ul >> 4 );
	ul = ( ul << 5 ) | ( ul >> ( 64 - 5 ) );
	ul = ( ul << 6 ) | ( ul >> ( 64 - 6 ) );
}

Here is the “corrected” example.

public static void RolRorRolRol( ref this UInt64 ul, Int32 n ) {
	if ( n > 2 ) {
		ul = ( ul << 3 ) | ( ul >> ( 64 - 3 ) );
	}

	if ( ul < 10 ) {
		ul = ( ul << ( 64 - 4 ) ) | ( ul >> 4 );
		ul = ( ul << 5 ) | ( ul >> ( 64 - 5 ) );
	}

	ul = ( ul << 6 ) | ( ul >> ( 64 - 6 ) );
}

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s