Little Coding Tricks And Tips

Miscellaneous coding tricks and tips for fun, profit, and ridicule......okay, skip the ridicule:


This is usually more efficient resource-wise:

  upperCase(subString(targetString,...))
than this:

  subString(upperCase(targetString),...)
because the case conversion is applied to a shorter string.


  If (isBlank(aa) && isBlank(bb) && isBlank(cc)) ...
can be shortened to:

  If (isBlank(aa . bb . cc)) ...     // single dot is concatenate
But ONLY if the language does not have "poison-pill" null strings. If the language does have poison-pill null strings, then one null turns the entire expression into a null expression even if one of the variables in the concatenate expression is not blank. It's a bad feature of a language in my opinion. Null strings themselves are a dumb idea. (Generally I make the "isBlank" function treat nulls as blanks if given a choice. And, efficiency is not commented on here.)


An old one from my C days...

The construct (x ? 1 : 0) can be used to "normalize" a number, reducing it to one or zero. This can also be done as: (!!x)

Also works on C++ objects that have an ! operator.

Careful not to make it too obscure. Sometimes a longer form is far more readable maintenance-wise.

In C99 or later and C++, a simple conversion to bool does the same without odd constructions. The bool type can only have the values 0 or 1. Note that this is not necessarily so for BOOL, Bool, Boolean, or other non-standard definitions inherited from older C versions.


Which brings us to the next tip: STOP USING C89!


Next tip?...


See also: LanguageGotchas


EditText of this page (last edited October 21, 2013) or FindPage with title or text search