When Order Matters

Last time, I talked about inlining of single-call functions. In fact, there are situations where even for functions called multiple times, inlining functions into a larger one is beneficial.

Say you are processing a change on a think-cell chart. If the user changed the color, you need to apply the color and may have to invert text to keep it legible on a potentially changed background:

ApplyColor();
InvertText();

If the user changed data, you also need to place the labels to a new position. Inversion of text depends on its background, which depends on the text's position. So PlaceLabels must be followed by InvertText:

ApplyDataChange();
PlaceLabels();
InvertText();

In reality, the sequence of such operations can be much longer. The order of them has been carefully crafted so that all dependencies are respected. In some situations, you can skip some of them, but the order should always stay the same.

If we split up the operations into separate functions, we must be careful that this order is adhered to at all call sites. It violates the DRY (Don't Repeat Yourself) principle that we have to ensure this order in many places in the program.

The solution is to put all operations into a single function in the correct order, and pass one or more parameters that control which subset is actually run. If the operations do not require parameters, the parameters may be just a bitmask. If they do, each operation can be controlled by an optional parameter pack, which if it is null, means skipping the operation.

At think-cell, of course we learned this approach the hard way, after gotten bitten by calling functions in the wrong order a few times…

P.S. I learned that other people have similar ideas regarding inlining: http://number-none.com/blow/blog/programming/2014/09/26/carmack-on-inlined-code.html

— by Arno Schödl

Do you have feedback? Send us a message at devblog@think-cell.com !

Sign up for blog updates

Don't miss out on new posts! Sign up to receive a notification whenever we publish a new article.

Just submit your email address below. Be assured that we will not forward your email address to any third party.

Please refer to our privacy policy on how we protect your personal data.

Share