Category: Effective Objective-C

  • Effective XCode UI Testing

    UI testing is a great way to ensure that your UI interactions keep working as you’re adding new features or refactoring your app’s codebase –  it keeps your app functional.

    Writing and running UI tests is kind of different from doing unit testing. You are actually interacting with your app rather than performing tests against a certain API. UI tests are often implemented as blackbox tests and you don’t even have to know the codebase. In Xcode UI tests run in its own App and they use two core technologies:  XCTest framework and Accessibility.

     XCode UI testing  has been around for a few years, but was unstable, flaky and hard to use – but things are getting better now. However there are still some issues. In this post I want to show some patterns how you can improve your UI tests.

    Resetting your app’s State

    As mentioned before, our UI tests will be running in an entirely different process, so we have zero access to our own code, which is very much by design.

    However each App contains state that is stored in UserDefaults or even Core Data. For our UI tests we want this state to be at a defined state before they start. So it is important our App knows when it is started in UI testing mode and can reset it’s state.

    Therefore we provide a launch argument when we start your App  in testing mode and check for this argument in the App delegate didFinishLaunchingWithOptions method.

    
    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]?) -> Bool {
    
        if CommandLine.arguments.contains("--uitesting") {
            resetState()
        }
    
        // ...Finish setting up your app
    
        return true
    }
    
    

    And our UI test class looks like this:

    
    class MyUITest: XCTestCase {
        var app: XCUIApplication!
    
        override func setUp() {
            super.setUp()
    
            // Since UI tests are more expensive to run, it's
            // usually a good idea to exit if a failure was encountered
            continueAfterFailure = false
    
            app = XCUIApplication()
    
            // We send a command line argument to our app,
            // to enable it to reset its state
            app.launchArguments.append("--uitesting")
        }
    
        // ... your testing methods
    
    }
    

    Speedup Animations

    Real time animations are central for human testers. However animations are not important for automated UI testing – in fact they are even time and CPU intensive. Therefore we often want to turn off animations for automated UI testing. Luckily this can be done by simply increasing the speed of Core Animation itself. And the best part: This is not even private API!

    UIApplication.sharedApplication.keyWindow.layer.speed = 100;
    

    This can be done in a central ViewController where the keyWindow is already initialized. Note: Do not call this code in the app delegate because the keyWindow is not initialized yet.

    Speedup of animations can reduce testing time up to 10%.

  • When Code Smells – change it

    When your  code smells it is often not awful code that makes your hold your nose. Rather it’s a simple indication that something may need to be changed. However when you don’t change  and ignore  you probably will end with a project of unmaintainable code. So you better learn to change smelling code. This is what Kent Beck and Martin Fowler did in their Refactoring book. They created a list of smells and what to do about them.

    General Code Smells

    Here is a list of common code smells for Objective-C and how to fix them. Most of them are language independent but there are also special Objective-C smells.

    Duplicated Code

    Number one in the stink parade is duplicated code. If you see the same code structure in more than one place, you can be sure that your program will be better if you find a way to unify them.

    Extracting this code into methods and invoke the code from both places. Another common duplication problem is when you have the same expression in two sibling subclasses. You can eliminate this duplication by using extract method in both classes and pull up the method to their superclass. If you have duplicated code in two unrelated classes consider using to extract the code in its own class.

    Long Methods

    The object oriented programs that live best and longest are those with short methods.  The longer a procedure is, the more difficult it is to understand and test. And if you have a good name for a method you don’t need to look at the body and are much faster in reading code. 99% of the time, all you have to do to shorten a method is extract method. Find parts of the method that seem to go nicely together and make a new one. Long lists of parameter objects can be slmmed down by parsing whole objects or introduce parameter Objects.

    Large Class

    When a class is trying to do too  much it often shows up as too many instance variables. When a class has too many instance variables, duplicated code cannot be far behind. Delegation is often the solution to the problem extract to a class or subclass. In Objective-C and Cocoa this can be done with the well known delegation pattern. If your class is a GUI class you may need to make data and behaviour to a separate domain object.

    Long Parameter List

    In the “Pascal Programming Days” we were taught to pass in everything as parameters. This was understandable because the alternative was global data, and global data and state is really evil, Objects change this situation because if you don’t have something you need, you can always ask another object to get it for you. So you only pass the object. Use the whole Object and preserve it or introduce Parameter Objects.

    Divergent Change and Shotgun Surgery

    Divergent change occurs when one class is commonly changed in different ways for different reasons. To clean this up you identify everything that changes for a particular class and use Extract Class to put them together. Shotgun surgery is similar to divergent change but is the opposite. You whiff this when every time you make a kind of change, you have to make a lot of little changes to a lot of different classes. Then the changes are all over the place they are hard to find, and it’s easy to miss an important change. In this case you will move methods and fields to put all the changes into a single class.

    Switch Statements

    One of the most obvious symptoms of object-oriented code is its comparative lack of switch statements. The problem with switch statements is essentially that of duplication. Often you find the same switch statement scattered about a program in different places. If you add a new clause to the switch, you have to find all the others. Most time you see a switch statement you should consider polymorphism. Often the switch statement switches on a type code. So extract the switch statement into methods and then move the methods to get it onto the class where the polymorphism is needed.

    Message Chains

    You see message chains when a client asks one object for another object, which the client then asks for yet another object, which the client then asks for yet another another object, and so on. Navigating this way means the client is coupled to the structure of the navigation and all queried objects. Any change to the intermediate relationships cause the client to have to change. Extensive use of message chains is the best sign that the Law of Demeter has been broken. In particular, an object should avoid invoking methods of a member object returned by another method. Instead write a wrapper method that calls this method. Often a better alternative is to see what the resulting object is used for. See weather you can use extract method to take a piece of the code that uses it and then move method to push it down the chain.

    Delegation abuse

    One of the prime features of objects is encapsulation. Encapsulation often comes with delegation. However this can go too far. When you look at a class’s interface and find half the methods are delegating to another class. After a while it is better to talk to the object that really knows what’s going on. If only a few method aren’t doing much, use inline method to inline them into the caller.

    Comments

    Comments are often used when code becomes wired. So Comments can lead us to bad code. When you feel the need to write a comment, first try to refactor the code so that any comment becomes superfluous. If your comment explains why a block of code does try to extract the block into its own method. If the method is already extracted but you still need  a comment to explain what it does, use rename method. If you need to state some preconditions about the required state use assertions.

  • State machines to the rescue

    Today I came across code that implemented a complex  login process. The login flow was quite complex but what made the code really difficult to understand was how it was implemented. Notifications, delegates, and long  case switch statements were used to implement the login flow.

    This got me thinking, how many times in my developer career have I actually used a state machine? The answer is I did a just a few times in my professional career. But why are developers afraid or unaware of using state machines? It would make our life and especially the life of our co-workers  much easier.

    This post is meant to create more awareness about state machines in the app developer crowd. If you don’t know what state machines are, please read up on them first. Wikipedia is a good place to start, as always. State machine are also described in  Design Pattern.

    State machines are awesome

    The main reason for using state machines is to help the design process. It is much easier to figure out all the possible edge conditions by drawing out the state machine on paper. This will make sure that your application will have less bugs and less undefined behavior. Also, it clearly defines which parts of the internal state of your object are exposed as external API.

    Moreover, state machines have decades of math and CS research behind them about analyzing them, simplifying them, and much more. Once you realize that in management state machines are called business processes, you’ll find a wealth of information and tools at your disposal.

    Recognizing the state machine pattern

    Most apps contain several examples of state machines, including login and registration,  ordering or payment. The problem is that you might not necessarily think of them as state machines while designing your application. Therefore, it is good to have some indicators to recognize them early on. The easiest way is to look at your data model:

    • Adding a state or status field to your model is the most obvious sign of a state machine.
    • Boolean fields are usually also a good indication, like published, or paid. Also timestamps that can have a NULL value like published_at and paid_at are a usable sign.
    • Finally, having records that are only valid for a given period in time, like subscriptions with a start and end date.

    When you decide that a state machine is the way to go for your problem at hand, there are many tools available to help you implement it. I found TransitionKit for Objective-C or SwiftState pretty cool. There are also state machine compilers but I won’t advice using them.

    YAGNI?

    You’ve probably heard of the YAGNI principle, it stands for: You Ain’t Gonna Need It. Especially in Agile projects developers try not to build solutions until they need them.  However when your state machine has more than 4 states and 6 transitions you will gone need a state machine. Especially when you want to make sure your software stays stable and can be supported the next few years.

    Hopefully, reading this text has made you more aware of state machines and you will be applying them more often.

  • Randomness generation with Objective-C and Swift

    Randomness is the lack of pattern or predictability. We can be sure of one thing, however: in the closed, digital universe of CPU cycles there is no true randomness, only pseudo randomness.

    Pseudorandomness, is often implemented in a way very similar to a cryptographic hash, as a deterministic function that returns a value based on the current time (salted by some initial seed value). Also like hash functions, there are a number of pseudorandom number generators, each of which are optimized for particular performance characteristics: uniformity, periodicity, and computational complexity.

    Rather than bore you with any more long-winded treatises on the nature of randomness, we’re going to tackle this in FAQ-style. For more interested readers check out The Art of Computer Programming Vol. 2 Random Numbers.

    arc4random() and its related functions are the ones you will need. Specifically, to generate a random number which avoids modulo bias.

    How to generate a random int between 0 and N – 1?

    NSInteger r = arc4random_uniform(N);
    

    How to generate a random int between 1 and N?

    NSInteger r = arc4random_uniform(N) + 1;
    

    How to generate a double between 0 and 1?

    If you are generating a random double or float, another good option is the more obscure rand48 family of functions, including drand48(3). Note: rand 48 functions, unlike arc4random functions, require an initial value to be seeded before generating random numbers. This seed function, srand48(3), should only be run once.

    srand48(time(0));
    double r = drand48();
    

    How do I generate a random character?

    If you are operating on a known, contiguous range of Unicode characters, such as the lowercase letters (U+0061 — U+007A), you can do a simple conversion from a char:

    NSString *letter = [NSString stringWithFormat:@"%c",
                          arc4random_uniform(26) + 'a'];
    

    How to pick a random character from an NSString?

    NSString *vowels = @"aeiouy";
    NSString *letter = [vowels substringWithRange:NSMakeRange(
                            arc4random_uniform([vowels length]), 1)];
    

    Why Should I Use arc4random(3) instead of rand(3) or random(3)?

    C functions are typically denoted with a number 3 inside of parentheses, following the organizational convention of man pages. rand is a standard C function and part of the POSIX standard. arc4random is provided on BSD and derived platforms.

    • arc4random does not require an initial seed, making it that much easier to use.
    • arc4random has a range up to 0x100000000 (4294967296), whereas rand and random top out at RAND_MAX = 0x7fffffff (2147483647).
    • rand has often been implemented in a way that regularly cycles low bits, making it more predictable.
  • The Objective-C error model

    Many modern languages have exceptions. If you come from Java you’ll most likely using exceptions all the way to handle error cases. For objective-C you are going to have to go back and forget everything you knew about exceptions and start from scratch. Even the terms exception and error are used conversely.

    The first thing to note is that Automatic Reference Counting (ARC) is not exception safe by default. In practice, this means that any objects that should be released at the end of a scope in which an exception is thrown will not be released. With the compiler flag -fobjc-arc-exceptions it is possible to enable exception-safe code to be generated. However this introduces extra code that has to be run even for the scenario in which no exceptions are thrown.

    Objective-C has taken the approach to use exceptions for the rare scenario in which recovery should be avoided and an exception cause the application to exit. This means that complex exception-safe code with resource releasing does not have to be included. Exception are  to be used for fatal errors only i.e. when a method of an abstract class is not implemented.

    
    - (void)abstractMethod { 
      NSString *reason = 
      [NSString stringWithFormat:
           @"%@ must be overridden", NSStringFormSelector(_cmd)] 
      @throw [NSException exceptionWithName: NSInternalInconsistencyException 
                                   reason: reason, 
                                 userInfo: nil];
    

    If exceptions are about to be used only for fatal error, what about other errors? The
    paradigm chosen by Objective-C to indicate non fatal errors either to return nil from methods when an error has occurred or to use NSError. A good
    example of returning nil is an non successful initialiser i.e. with wrong
    parameter.

    - (id)initWithValue:(id)value {
       if((self = [super init])) {
         if (![value class] isKindOfClass: [MyExpectedClass class]) {
            self = nil;
         } else {
             // Initialize instance
         } 
       }
       return self;
    } 
    

    In this scenario a caller of the initialiser will understand that there has been an error, because no instance will have been created.

    An NSError object encapsulates richer and more extensible error information than is possible using only an error code or error string. An NSError object encapsulates the following information:

      • Error domain (String)
        The domain in which the error occurred. This is usually a global variable that can be used to uniquely define the source of the error. Here is a list of predefined error domains: NSPOSIXErrorDomain, NSOSStatusErrorDomain, NSMachErrorDomain, NSCocoarErrorDomain.
      • Error code (integer) 
        A code that uniquely defines within a certain error domain what error has occurred. Often, an enum is used to define the set of errors that can occur within a certain error domain. HTTP requests that fail might use the HTTP status code for this value, for example. As listed here error codes are declared and documented in one or more header files for each major domain.
      • User info (Dictionary): 
        Extra information about the error, such as a localized description and another error representing the error that caused this error to occur.

    The first way in which errors are commonly used in API design is though the use of delegate protocols. When an error occurs, an error object is passed to its delegate through one of the protocol’s methods. For example, NSURLConnection includes the following method as part of its delegate protocol , NSURLConnectionDelegate:

    - (void)connection:(NSURLConnection*)connection
      didFailWithError:(NSError*)error
    

    The other common way in which NSError is used is through an out-parameter passed to a method. It looks like this:

    - (BOOL)doSomething:(NSError**)error
    

    The error variable bing passed to the method is a pointer to a pointer to an NSError. This enables the method to return an NSError object in addition to its return value.It’s used like this:

    NSError *error = nil;
    BOOL ret = [object doSomething:&error];
    if (error) {
      // There was an error handle it
    }
    

    Often, methods that return an error like this also return a boolean to indicate success or failure so that you can check the boolean only if you don’t care about the error.

    BOOL ret = [object doSomething:nil];
    if (ret) {
      // There was an error handle it
    }
    

    In reality, when using ARC, the compiler translates the NSError** in the method signature to NSError*__autoreleasing*; this means that the object pointed to will be autoreleased at the end of the method.

  • Prefere Typed Constants versus Pre-processor #define

    When you write testing code you will often want to define a constant. Typical constants that you might want to factor out are your test fixtures.

    Often Objective-C programmers take the approach of defining the constant like this:


    #define USER_NAME @"Tom"

    This is a preprocessor directive and will be replaced by the preprocess by the corresponding string “Tom”. If this define would be declared a header file the preprocessor will blindly replace all occurrences of USER_NAME.

    To solve this problem you should make use of the compiler. There is always a better way to define a constant than using a preprocessor define.


    static const NSString* kUserName = @"Tom";

    Note that with this style, there is type information, wich is beneficial because it clearly defines what the constant is. Also note how the constant is named. The usual convention for constants is to prefix with the letter k for constants that are local to translation unit (.m files). For constants that are exposed outside of a class, it is usual to prefix with the class name to avoid name clashing conflicts. Event the static const as it stands should not appear in header file. Since Objective-C has no namespaces, it would declare a global variable called kUserName.

    Therefore define translation unit specific constants within an implementation file as static const. These constants will not be exposed to the global namespace.

    Define global constants as external in a header file, and define them in the associated implementation file. These constants will appear in the global symbol table, so their names should be namespaced, usually by prefixing them with the class name to which they correspond.


    // SCTestData.h
    extern const NSString* SCTestDataUserName;

    // SCTestData.m
    const NSString* SCTestDataUserName = @”Tom”