Proxy design pattern in iOS

My thoughts on the proxy design pattern in iOS

What this article is all about

I might have to disappoint you, but this is not going to be tutorial on using the proxy design pattern. It’s going to be more like a discussion about how it is used internally in the Cocoa framework and how we can take that as example and consider that advice (or not) in our projects. So if you are just interested in what a Proxy is and how it’s used… Honestly, I have no idea what you are doing here. Just read the Wikipedia page or something 😛

The proxy design pattern

Just so we are on the same page on this, lets look at the definition for the proxy design pattern:

A proxy, in its most general form, is a class functioning as an interface to something else.

This is taken right from that Wikipedia page I mentioned. Reading it, though, gives a very vague definition of the proxy design pattern. A person with a wilder imagination would say many things in programming are proxies. Hmm, and maybe he’d be right.

Anyway, I like to think of a proxy as a “wrapper” that keeps the iterface from the orginal class. Naturally, who am I to say what a proxy is, and what not. I’m sure there are at least 5 counterexamples that prove my definition is incorrect. It’s overly simplistic, but I think it’s good to start with.

Mentioning wrappers… are they actually a design pattern? Turns out… they are! Check it out in Wikipedia! Ok, yeah, it’s just an alias for the Adapter design pattern, but it’s something!

I hate seeing memes in blog articles, so feel free to open it externally

The problem with proxies

I have a problem with the second part of my definition:

A proxy is like a wrapper that keeps the interface from the original class

— Me, one paragraph above

For simple classes, or more specifically classes with simple and short interfaces, that’s fine. If you look at the example given in the Wiki article, the public interface for the class is only one method. It’s extremely easy to mimic the same interface in the proxy. But what if we wanted to proxy a class that is way more complex. For instance UIView. We would have to copy every public method from UIView. That’s quite a lot. And it’s fragile – new methods can appear with every SDK release. And most of those copied methods would probably do the same thing – just call the real functionality. And I don’t think this example is exaggerated in any way. After all, It could be often useful to proxy a large object.

One possible solution would be to extract the interface as a protocol and have the original class and the proxy conform to it. But, really, that doesn’t make it better. The thing about protocols is, you still need to provide implementations for those methods. Again, there is a lot of copying going on.

Note I know protocols have default implementation in Swift 3, and that’s really cool, but that doesn’t really solve the problem.

It seems at this point we have hit a rock and we start to understand why proxies are not so common in our coding life. Or have we?

UIAppearance

The story about proxies ended for me for quite a while. I couldn’t find a solution to the problem of the common interface. It was recently that I remembered it while working on my previous article about app branding. If you check the documentation for UIAppearance, it says:

Use the UIAppearance protocol to get the appearance proxy for a class.

right from the start. Well, what do you know – here’s a prime example of the proxy design pattern. Moreover, UIAppearance proxies large, complex objects like UILabel and UIView. Basically most UI classes. So not ony does it mimic the interface of a complex class, but even several of those. Now this is worth some additional investigation.

What kind of object is UIAppearance?

The experiment

We cannot just open UIAppearance’s source code, but at least we can look at it’s declaration. I found the first instance of UIAppearance in my code and clicked on “Jump to definition”:

    public protocol UIAppearance : NSObjectProtocol {

    /* To customize the appearance of all instances of a class, send the relevant appearance modification messages to the appearance proxy for the class. For example, to modify the bar tint color for all UINavigationBar instances:
        [[UINavigationBar appearance] setBarTintColor:myColor];

        Note for iOS7: On iOS7 the tintColor property has moved to UIView, and now has special inherited behavior described in UIView.h.
        This inherited behavior can conflict with the appearance proxy, and therefore tintColor is now disallowed with the appearance proxy.
      */
    public static func appearance() -> Self

Hm, so it is actually a protocol. That’s something, but doesn’t really tell us a lot about who and how implements it. But what is that at the end of the snippet?

public static func appearance() -> Self

That can lead to somwhere. If you ever worked with UIAppearance, you know you typically call it using:

UILabel.appearance().<set something>

In this example, of course UILabel is only one of many classes that support UIAppearance. And if you go to UILabel’s header, you’d find that it conforms to the UIAppearance protocol. Interesting! So if you call UILabel.appearance()… you get a UILabel instance back. Indeed, the line let labelAppearance:UILabel = UILabel.appearance() compiles fine and in runtime, we can inspect that labelAppearance is really an object of type UILabel. Additionally, it is always the same object.

Well that’s a little disappointing. Does it mean that UILabel has a static label variable that holds all the appearance information and all set properties there are also reflected on new instances when they are created?

Next experiment – if UILabel.appearance() is a label itself, can we actually put it on screen and see what gets displayed:

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let labelAppearance = UILabel.appearance()
        labelAppearance.frame = CGRect(x: 20, y: 50, width: 100, height: 40)
        self.view.addSubview(labelAppearance)
    }

Easily enough, the code compiles and runs. But then:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSMethodSignature getArgumentTypeAtIndex:]: index (2) out of bounds [0, 1]'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000011290e34b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010fc7e21e objc_exception_throw + 48
    2   CoreFoundation                      0x00000001128cbd5c -[NSMethodSignature getArgumentTypeAtIndex:] + 204
    3   UIKit                               0x0000000110ab14af +[NSObject(UIAppearanceAdditions) _installAppearanceSwizzlesForSetter:] + 293
    4   UIKit                               0x0000000110ab517f -[_UIAppearance _beginListeningForAppearanceEventsForSetter:] + 248
    5   UIKit                               0x0000000110ab53f9 -[_UIAppearance _handleSetterInvocation:] + 188
    6   CoreFoundation                      0x0000000112893a2e ___forwarding___ + 526
    7   CoreFoundation                      0x0000000112893798 _CF_forwarding_prep_0 + 120
    8   UIKit                               0x00000001103b0d75 -[UIView(Internal) _addSubview:positioned:relativeTo:] + 584
    ...

I guess the theory about UILabel.appearance() really being a label is slowly fading away. But that doesn’t make the reality any less disappointing. Lets look at the stack trace.

First of all, the exception description looks like a standard array index out of bounds assertion. Already, it seems UIAppearance just keeps an array of applied styles. But how?

Continuing on, we can start looking at the method calls. On 8th place, we see a call to addSubview. This is no surprise since the documentation specifically says that UIAppearance styles are applied when a view is added to a window. Next, 3 to 5, seems interesting. Invocation… Swizzles…?

Invocations probably refer to NSInvocation, a class encapsulating method calls. It’s a bit obscure, but if you’ve had to save methods along with parameters for later calls in (lets say) a dictionary, you might have had to use NSInvocation.

Swizzling, on the other hand, is something many of us know from the Objective-C runtime. Swizzling refers to the process of replacing a class’s method implementation with another one, effectively changing the class in runtime.

The results

At this point, we can make a pretty good guess as to how UIAppearance does its magic. It collects styling calls as NSInvocation objects in an array. Then, it uses method swizzling to override setters and apply those invocations to all new instances of the styled class. To make the compiler happy, especially in Swift, the appearance method from the UIAppearance protocol makes sure to return an object of the same class. That way all the class’ methods are accessible and statements such as:

UINavigationBar.appearance().barTintColor = themeColor

become possible. But in reality the underlying object is not an instance of that class, but a proxy collecting invocations, ready to apply them to any subsequent instances.

Next steps

We didn’t need to get too deep into Cocoa in order to understand how UIAppearance was implemented. Just some fiddling with its declaration and lldb was enough. Of course, for a lot of things we had to use our imagination and make assumptions. For instance, we inferred implementation details based on method names and undeterministic behavior.

However, a more powerful investigation method that works especially good in Objective-C, is looking at the class dumps. As you probably know, Objective-C is relatively easy to decompile. So there are tools available that will generate the source code based on compiled binaries. Moreover, for built-in libraries, dumps are readily available in Github. So before those libraries and frameworks get re-written in Swift, we can take advantage.

If you want to confirm our findings about UIAppearance or you still have questions regarding its implementation, a good place to start would be UIKit’s source code, and UIAppearanceProxy specifically, that you can find here

Thanks to Shoumikhin for suggesting that in the comment section!

Takeaways

The key takeaway for me here is that there is no clean easy solution to the problem at hand. When you proxy a class, it is your responsibility to carry the interface over to the proxy. And if that interface is non-trivial, the practicality of this approach starts to fade away. And while the proxy design pattern in iOS is definitely possible and also somewhat endorced by the Cocoa framework, it is not a simple and elegant implementation. It heavily relies on Objective-C and its ability to “shapeshift” at runtime.

So whether or not you would use it, heavily depends on how comfortable and open to the Objective-C runtime you are. I, personally, avoid it in my code and I get really suspecious about third party frameworks using it without a really good reason.

Singleton vs. single instance

Today on DevMonologue we are going to be talking about a design concept that has been bothering me for a while. It is not only related to iOS development, but programming in general.

I wouldn’t say I’m a expert in software architecture. But in my experience, I find that the issue of singleton vs. single instance is something many projects suffer from and many people don’t realize it.

That’s why I want to share my thoughts about how to avoid some major design flaws. As I said, I don’t necessarily quarantee everything written here is 100% true in all cases, so all feedback is greatly appreciated. I’d love to see this article become a discussion with people sharing their experience and maybe provide solutions to common problems in this field. So don’t be shy and write us a few lines in the comment section 😉

What’s that “Singleton vs. single instance” nonsense all about?

With all the “sentimental” stuff out of the way, let get to the point. What do I mean by “Singleton vs. single instance”?

The origin of “Singleton vs. single instance”

Now, I’m not sure (historically) who introduced that term, but I can tell you where I read about it in the first place. It was in a book called “Working effectively with legacy code” by Michael Feathers. If you don’t already know about that book, I advise you to check it out. There are loads of useful tips in it, and even if you consider that you’re not working with legacy code, you will benefit from that book, believe me.

The definition

The principle behind “Singleton vs. single instance” is really simple. It just specifies that wherever you’re normally using singleton objects, you should consider just having a single instance. What do I mean by that?

A singleton is a class that enforces the rule that there can only be a single object of it and most often that object can be accessed throughout the program.

A “single instance” on the other hand means that the class itself is not a singleton, but (on a higher level), you just make sure there is only one instance.

At first glance, it might seem that this is not that important, and even that a singleton is better suited for the job because it is more explicit about its proper use. Lets see if I can convince you otherwise…

The cons

Breaking capsulation

In both cases the class is only supposed to have a single object. But a singleton actively enforces that, whereas the “single instance” is too naive and just assumes its users will know not to create multiple objects. As we all know, it is always better to be as explicit as possible when it comes to such scenarios, so as far as capsulation is concerned, the singleton wins.

Ease of use

Developers are lazy and (rightfully so) like easier interfaces. And you cannot beat a singleton as far as easy access is concerned. All you have to do is import the singleton class (if you have to), call the method that returns the shared instance and you’re good. It doesn’t get better than that. With a “single instance” you will need to figure out who has that object and how you can get to it.

Now, ease of use is not always a good thing. And I hope a warning sign went up in your brain while you were reading the last paragraph. But more about that later.

The pros

“Singleton vs. single instance” in Test-driven development

Like many of the topics you will find in the “Working effectively with legacy code” book, this one is connected to TDD. But even if you don’t approve of TDD, don’t close the tab just yet. Even though “Singleton vs. single instance” greatly simplifies test-driven development, it can also be a powerful design decision in all projects.

In TDD in general, it is very important that every test runs in isolation and the environment is reset between them. That makes singletons especially problematic. Since there is only one object which persists throughout the lifetime of the application, you cannot ensure what state a previous test has left the singleton in (Also note that most IDEs have the ability to run unit tests in parallel and generally don’t ensure tests are run in sequence). There are ways to get around that, but generally, while using test-driven developement it is “Singleton vs. single instance” – 0:1.

Restricted access

This is the opposite of the “Ease of use” that we were discussing above. But why should we try to make it hard to access an object.

Well, there is an inherent problem with universal access. If all parts of an application can access an object, it is often hard to know what the problem is when something bad happens. If you track a bug to a singleton object method that 30 other objects call, it is not easy to find where the problem comes from.

Another problem is that if you make it really easy for people to use your class, they will use it… constantly. And this leads to exatly what I wrote about in the previous paragraph – everybody seems to be calling methods from the singleton class.

Now, for generic and common functionality these things are ok and shouldn’t cause problems. It’s not like you should never use a singleton. But I feel like people (including me) are overusing them. And I’ll give you an example:

An example of a “Singleton vs. single instance” issue

To me, the singleton design pattern is extremely useful, but many developers seem to be abusing its power. When you opt to use it for your classes, you better think really hard before you determine that’s what’s required. Is it absolutely necessary to only have one instance… will it break your architecture if two of them exist? Or is it just that one instance is probably sufficient?

The most common abuse of the singleton pattern happens when people just need a global variable. Since global variables are (for good reason) condemned by modern programming standards, but they are still useful, developers can be tempted to create a singleton just so that an object is globally acessible. So, lets ask the question from the previous paragraph:

Is it absolutely necessary to only have one instance… or is it just that one instance is probably sufficient?

No, it isn’t necessary!

However, this a rather primitive example of a poor “Singleton vs. single instance” choice. Whereas you should definitely stay away from such situations, you are unlikely to get into serious trouble with them. To get into the real problem, we will need to dig deeper.

Let consider our beloved MVC pattern. Particularly the Controller part – our business logic. How many projects have you seen or participated in, that made heavy use of singletons in their business logic. Be honest about it. CommunicationsManager, DataManager, NotificationsManager, LoginManager… these are all very likely to be singletons. But should they?

Lets think about the last one, LoginManager, for a second. It is probably an object that manages a user session – perhaps it contains a token, cookie, user credentials?
Most applications will only allow a single user to be logged in at the same time. So, there really should be only one instance of the LoginManager class, right? And the singleton pattern fits really well, doesn’t it? Let ask the same question about singletons in this case:

Is it absolutely necessary to only have one instance… or is it just that one instance is probably sufficient?

Well yes, yes it is! Having two LoginManagers would be an error! And yet, something’s fishy around here. What about this use case:

  • Login
  • Logout
  • Login again with different credentials

Oh! It would seem that LoginManager should, indeed, have only one instance, but that instance might not be the same throughout the applications life. So, the question we should have been asking is actually:

Is it absolutely necessary to only have one instance that doesn’t change through-out the course of the application’s life?

So what happens in most projects (in my experience) is that the LoginManager instance (for example) stays the same between logins. To make that work, upon logout, all user information is deleted from the instance. It should be fairly easy. How hard can it be? A user session is only identifiable via several items – maybe a token or a username. But what about those pre-cached user friend lists… or avatar… or password. This kind of code always seems to break during maintainance. You cannot rely on your colleagues (or even you) to always remember to clear data upon logout. It just doesn’t work that way.

And next time, when you forget to clear that user token… what will happen? You might even end up logging the wrong user in!

Now, if only our LoginManager was not a singleton… We would just delete the object when the user logs out and be done with it. We wouldn’t be that concerned that the class might not be clearing all data during logout.

I guess the moral if this story is that similar to real life, nothing is forever in software development. So don’t get too attached to your objects. Otherwise they will break your heart into small pieces!

And on that sad note, I think that’s it for today’s monologue about Singleton vs. single instance. Thanks for reading!