Originally published by Robert Beisert at fortcollinsprogram.robert-beisert.com

Patterns: Yin and Yang

How many programmers whine that C is dangerous because of memory leaks? How many programmers rely on IDEs because they can’t keep track of how many layers of brackets they’re using?

All of this stress is easily defeated with a little bit of Eastern Philosophy.

Yin: Beginnings

In the binary unifying force of the cosmos, there are the forces of yin and yang. These elements are equal complements to one another – where one exists, the other necessarily exists.

The element of Yin is the feminine element, and it is associated with beginnings and creation. For our purposes, the Yin is all things which begin a course of action.

These are the opening brackets and braces.

These are the allocation functions.

These are the function prototypes and “happy path” logic.

All of these things, which define and begin courses of action, are Yin.

Yang: Endings

Yang, on the other hand, is a masculine element associated with action, completion, and death. For our purposes, the Yang is everything that closes off a course or path of action.

These are the closing brackets and braces.

These are the free or destruction functions.

These are function definitions and error-handling paths.

All of these things are Yang.

Yin and Yang are One

In the Eastern philosophy of the Tao (literally, the “way”), yin and yang are balanced forces that continue in a circle for eternity. The elements pursue one another – destruction follows creation, and a new creation is born out of the old destruction. The masculine and feminine forces of the cosmos require one another for total balance and perfect harmony in the universe.

So, too, it is in our code.

When we create an opening brace, we must immediately define the closing brace, so that the balance is preserved.

When we allocate a resource, we must immediately define its time and place of destruction, so that balance is preserved.

When we prototype a function, we must immediately define its features, so that balance is preserved.

By keeping the two halves of our operations united, we ensure that we never have to chase down the imbalances between them.

Lesson: Creation and destruction are tied together, so we should define them at the same time.

photo by: