programacion-indentacion

What is code indentation

  • 4 min

Indentation refers to the technique of adding an initial space (indent) at the beginning of lines of code, which helps to visually delimit blocks and control structures.

To indent, spaces or tabs are added at the beginning of lines of code to highlight the hierarchy of control structures, such as loops, conditions, and functions.

Proper indentation makes code easier to understand and maintain, as it helps quickly identify code blocks and the relationships between them. Furthermore, it facilitates error detection and improves collaboration in programming projects.

Some people prefer tabs, some prefer three spaces, some prefer four. I won’t get into that debate (you wouldn’t believe how radical some people get about that).

Personally, I don’t mind. What is important is that you are consistent with the style you choose within the same project, and aligned with the style guidelines of the company or organization you collaborate with.

Non-significant Indentation

Non-significant indentation is used in programming languages like C#, Java, and C++. In these languages, code indentation has no semantic meaning and only has visual effects to improve readability.

In these languages, the code structure is defined by the use of braces {} or other specific keywords like end to delimit code blocks.

public static void CalculateDiscount(decimal price)
{
	// <---- that indentation is purely visual
	if (price > 100)
	{
		decimal discount = price * 0.1m;
		decimal finalPrice = price - discount;
		Console.WriteLine("A discount of 10% is applied");
	}
	else
	{
		Console.WriteLine("No discount is applied");
	}
}
Copied!

In fact, most IDEs provide auto-formatting tools, which allow applying indentation to the code automatically, without having to do anything more than press a button or a key combination.

Significant Indentation

On the other hand, significant indentation is used in languages like Python or CoffeScript. In these, code blocks are defined by the indentation itself, instead of using braces or other keywords to delimit them.

def calculate_discount(price):
	# here the indentation defines the block
    if price > 100:
        discount = price * 0.1
        final_price = price - discount
        print("A discount of 10% is applied")
    else:
        print("No discount is applied")
Copied!

As almost always exists, there is no one option better than the other (otherwise, both wouldn’t exist). Each has its advantages and disadvantages.