An interesting C linked list idiom

I’ve used similar to this to insert into a binary tree. Because when iterating the tree, you usually stop when your pointer becomes NULL (you ran off the tree). So to insert, you have 3 options, 1: use a variable which tracks the previous value of your iterating pointer. 2: stop when the pointer you … Read more

How to automatically register a class on creation

You can indeed do this using the curiously recursive template idiom. It requires nothing from whoever is extending the class that can’t be enforced by the compiler: template<class T> struct Animal { Animal() { reg; //force specialization } virtual std::string name() = 0; static bool reg; static bool init() { T t; AnimalManager::registerAnimal(t.name()); return true; … Read more

`if key in dict` vs. `try/except` – which is more readable idiom?

Exceptions are not conditionals. The conditional version is clearer. That’s natural: this is straightforward flow control, which is what conditionals are designed for, not exceptions. The exception version is primarily used as an optimization when doing these lookups in a loop: for some algorithms it allows eliminating tests from inner loops. It doesn’t have that … Read more

Named Parameter idiom in Java

The best Java idiom I’ve seem for simulating keyword arguments in constructors is the Builder pattern, described in Effective Java 2nd Edition. The basic idea is to have a Builder class that has setters (but usually not getters) for the different constructor parameters. There’s also a build() method. The Builder class is often a (static) … Read more

Python idiom to return first item or None

Python 2.6+ next(iter(your_list), None) If your_list can be None: next(iter(your_list or []), None) Python 2.4 def get_first(iterable, default=None): if iterable: for item in iterable: return item return default Example: x = get_first(get_first_list()) if x: … y = get_first(get_second_list()) if y: … Another option is to inline the above function: for x in get_first_list() or []: … Read more

What does if __name__ == “__main__”: do in Python?

Short Answer It’s boilerplate code that protects users from accidentally invoking the script when they didn’t intend to. Here are some common problems when the guard is omitted from a script: If you import the guardless script in another script (e.g. import my_script_without_a_name_eq_main_guard), then the latter script will trigger the former to run at import … Read more