jjrscott

Code layout and display

Often, discussion about programming languages devolves into arguments on aesthetic grounds. For example, there is a discussion within the Apple development community with regards to the differing merits of Objective-C and Swift. While these languages are different in many ways, I am sure that one primary (mostly unspoken) reason for switching is Objective-C’s syntax - i.e. square brackets.

This saddens me as I think we could have taken the better step of editing the abstract syntax tree instead. By way of example, I’ve written the same code in Objective-C and Swift. Then at the end, I’ve transformed the original Objective-C into something prettier (I replaced the square brackets). Note that these changes are reversible; These are a visualisation of the underlying files.

This also neatly resolves another now pointless disagreement: indentation style. The Objective-C uses the Allman style while the Objective-C with revised layout and display uses the K&R style. The compiler cares about the style exactly as much as it cares about your keyword colouring scheme - i.e. not at all.

Objective-C

// View.h
#import <UIKit/UIKit.h>

@interface View : UIView
@end
// View.m
#import "View.h"

@implementation View

- (nullable UIView *)resizableSnapshotViewFromRect:(CGRect)rect
                                afterScreenUpdates:(BOOL)afterUpdates
                                     withCapInsets:(UIEdgeInsets)capInsets
{
    UIView *view = [super resizableSnapshotViewFromRect:rect
                                     afterScreenUpdates:afterUpdates
                                          withCapInsets:capInsets];
    view.backgroundColor = [UIColor redColor];
    return view;
}

@end

Swift

// View.swift
import UIKit

class View {
    func resizableSnapshotView(from rect: CGRect, afterScreenUpdates afterUpdates: Bool, withCapInsets capInsets: UIEdgeInsets) -> UIView? {
        let view: UIView? = super.resizableSnapshotView(from: rect, afterScreenUpdates: afterUpdates, withCapInsets: capInsets)
        view?.backgroundColor = UIColor.red
        return view
    }
}

Objective-C with revised layout and display

Remember that a program generated everything you see (which could have been the IDE). Even if you did store this text in a file, you could convert it into the Objective-C that clang understands by using a simple preprocessor.

// View.h
import UIKit

interface View : UIView {
}
// View.m
import View

implementation View {
    func resizableSnapshotViewFromRect(_ rect: CGRect, afterScreenUpdates afterUpdates: BOOL, withCapInsets capInsets: UIEdgeInsets) -> nullable UIView {
        UIView view = super.resizableSnapshotViewFromRect(rect, afterScreenUpdates:afterUpdates, withCapInsets:capInsets)
        view.backgroundColor = UIColor.redColor
        return view
    }
}