1. 4
  1. 1

    Back when I was a tutor/TA at uni the most common issue was simply the problem of how people were introduced to “singleton” which is almost invariably “getInstance().doThing()” rather than recognizing that the actual intent is to use getInstance() in place of calling the object constructor. The result is people using it to launder global variables.

    ObjC has singletons idiomatically as the +alloc-init pair can be written to return whatever they want, including the same object. That said people still end up using the global singleton instance directly in many cases anyway.

    1. 3

      The result is people using it to launder global variables.

      Is a singleton not just a global?

      1. 2

        Yeah, singletons are globals with encapsulation.

        1. 1

          Yes, but as I have interpreted it - from the 90s/2000s pattern mania is that the idea is only the site that would otherwise be instantiating a new object is meant to be aware of it being such. Everything else gets their instance pointer from that, and after the “creation” refers to that object. That means in future your getInstance method can switch to providing new objects and everything just keeps working.

          In practice everyone just scatters “getInstance” everywhere but then says “it’s a design pattern! Not a global!”

        2. 2

          Objective-C also has the nice property that +initialize always runs before the first message to a class, blocking all other threads, so you can create the singleton there and unconditionally return it on the other paths.

          In C++, I tend to implement singletons by returning a function-local static, which will be initialised in the first call to the function. This avoids a heap allocation, and has a lightweight check on the fast path (single load and check of a bit, then branch).