$30 off During Our Annual Pro Sale. View Details »

Clean Coding in Swift

Clean Coding in Swift

Styling tips and strategies to clean up your Swift code, with help from Erica Sadun's book.

Mark Wilkinson

April 18, 2018
Tweet

More Decks by Mark Wilkinson

Other Decks in Programming

Transcript

  1. The Swift Way
    clean coding

    View Slide

  2. You’re telling a story
    - Daniel Steinberg

    View Slide

  3. What’s in a good story?
    •Succinct Titles and Section Headers
    •Sentences that convey meaning.
    •Grouping those sentences into a thought,
    or a paragraph.

    View Slide

  4. Succinct Titles and Headers
    (or better method signatures)

    View Slide

  5. better methods sigs

    View Slide

  6. pop-quiz
    ?

    View Slide

  7. Not succinct

    View Slide

  8. View Slide

  9. { braces and (parens) }
    2 styles of bracing
    C style (K&R) and C#
    (Allman)

    View Slide

  10. { bracing alignments }
    C-K&R Style
    C#-Allman

    View Slide

  11. No right or wrong choice
    Apple and most Swift developers
    continue with the C-K&R style
    Stay consistent, don’t mix
    the 2

    View Slide

  12. Speaking of alignments

    View Slide

  13. Anyone miss this?

    View Slide

  14. Knock yourself out
    (still prefer obj-c alignment of
    colons, but oh well)

    View Slide

  15. Proper alignment helped
    readability in Objective-c
    and it continues to help in
    Swift

    View Slide

  16. Parentheses ()
    Hugging is best
    Avoid

    View Slide

  17. Parentheses? ()
    Avoid them when there’s only
    1 condition to an if or else if

    View Slide

  18. Statements that convey
    meaning

    View Slide

  19. Convey the meaning don’t
    expect the reader to deduce

    View Slide

  20. Group sentences into
    thoughts, or paragraphs

    View Slide

  21. Collections: Sugar or
    Generics?

    View Slide

  22. •Prefer Collection ‘Sugar’ in initializing or
    identifying the collection type ([Any] vs
    Array)
    •Prefer Generic form if you need to specify
    where Sugar inference doesn’t work (Set
    for instance)
    •The community at large seems to prefer
    [AnyHashable:Any] over Dictionary<,>, so it is
    what it is.

    View Slide

  23. if let cascading

    View Slide

  24. f*n awesome block syntax

    View Slide

  25. View Slide

  26. •Embrace the closure argument sugar, avoid
    param names when the types are inferred
    •Prefer however named arguments when the
    implementation inside the block is nontrivial
    •Only use $0 when the params are worthless
    •Put your single closure as the last parameter to
    a method to get the last argument styling
    Erica’s rules

    View Slide

  27. Recognition above Recall

    View Slide

  28. on guard

    View Slide

  29. More cleaning

    View Slide

  30. •Replace common and (overlooked) if statements
    and if let pyramids with early-fail guard
    statements
    •Put multiple guard conditions on their own lines,
    allows breakpointing each line, commenting out
    conditions etc.
    •Even better, break each condition into it’s own
    guard statement

    View Slide

  31. •The selling point of guard usage is early failure,
    and finding bugs during development
    •Pair guard with assertionFailures to find
    exceptions early
    •guard statements help reduce if-let pyramids
    •They let the logic in a method focus on what
    needs to be done instead of checking for
    missing/nil conditions.
    Use guard

    View Slide

  32. optional unwrapping
    •Erica recommends not adding ‘valid’ or
    ‘unwrapped’ to the variable that is now valid.
    •This creates a scenario where validResponse might
    have existed somewhere else and is re-purposed
    •I personally keep using this style so proceed with
    caution.

    View Slide

  33. clean repurpose
    unwrapping

    View Slide

  34. Use assertions
    • assertionFailures should be used in place of many
    NSLog and print statements.
    • You the developer need to find crashing conditions
    early not in QA
    • Go through every console log (NSLog, print) and
    replace error reporting or add to them with an
    assertFailure

    View Slide

  35. • A great place to use them is in fail early guard statements
    • They are of course stripped out for a release build
    (assuming you’re using different builds)
    • fail early and stop to solve failures early not at the last
    minute or in a bug ticket

    View Slide

  36. Ternaries, or please stop
    • Ternary statements are just cryptic if-else conditions.
    • They can get more complex, and do nothing other
    than force another developer to decrypt them.
    • Harder to debug with breakpoints
    • Just refactor them out to if-else or guard statements.

    View Slide

  37. Finalize and seal
    • By default you should finalize your classes
    • Final prevents subclassing, which is the source of endless
    problems in the OO world.
    • Tells another developer you had no intention for this class to
    be subclassed and overrode.
    • Lack of subclassing introduces better patterns like protocols
    and containment

    View Slide

  38. If you have to subclass
    Prefer the abstract class
    pattern
    But there is no abstract
    keyword in Swift

    View Slide

  39. Those pesky
    baseViewControllers
    • The most common subclass is the viewController
    • Usually have properties that they all need, and
    most commonly, error reporting and alert showing

    View Slide

  40. Move to a protocol with
    extensions

    View Slide

  41. • The ViewController is still only 1 subclass deep.
    • It now implements a useful protocol with extended
    behavior
    • Add new protocols with their own extensions for other
    specific behaviors
    • This prevents massive god-base-classes

    View Slide

  42. other developers
    Mark Wilkinson

    View Slide

  43. You’ll influence other
    developers, which in turn will
    influence more down the line

    View Slide

  44. Smell the roses, not the code,
    embrace your personal style
    - Erica Sadun

    View Slide