Avoid Manual Initialization

Too many software libraries require that you manually initialize them before use. As illustration:

window = library.createLibraryObject()

Why require your users to remember initialization busywork? createLibraryObject should initialize the library, refcounting the initialization if necessary.

The primary benefit is cognitive. If a library requires initialization, its objects and functions have an additional, externally-visible behavior: “If not initialized, return error.”

If the library’s internal state is managed implicitly, it does not leak out of the API. createLibraryObject should lazily initialize the library on object construction. Optionally, on object destruction, it can deinitialize the library.

A secondary benefit of lazy initialization is performance: interactive desktop applications rarely need immediate access to all of its subsystems. By deferring as much initialization as possible, application startup time is reduced.

[This post is a test of my new host: prgmr.com]

3 thoughts on “Avoid Manual Initialization”

  1. Hey Chad, what if my library has a bunch of parameters to be set only once before creating any objects? For example, things like logging settings, number of threads to create, etc. In that case does it make sense to require an init function that takes these params? Or should I make it optional and just use default values if the user doesn’t call init?

  2. I’d suggest intelligent defaults, but give the option to configure the library. In the IMVU code, we sometimes create a “Runtime” object that you must instantiate and pass to your other objects. The Runtime would contain the state you mentioned. Runtime can enforce that only one exists, if necessary. If not, just let your users create multiple Runtimes. This makes automated testing much easier.

Leave a Reply

Your email address will not be published. Required fields are marked *