SlideShare a Scribd company logo
WRITING CLEAN CODE
IN SWIFT
TOKYO IOS MEETUP
JANUARY, 2017 DEREK LEE
ANY FOOL CAN
WRITE CODE THAT A
COMPUTER CAN
UNDERSTAND. GOOD
PROGRAMMERS
WRITE CODE
THAT HUMANS CAN
UNDERSTAND.
Martin Fowler
… a blog post?
… a research paper?
… a presentation?
SO HOW WOULD YOU WRITE …
DRAFT→REVISE
Writing Clean Code in Swift
REFACTORING
REVISE
TDD:
RED
GREEN
REFACTOR
How much time do you think you spend
reading code versus writing code?
THE RATIO OF TIME SPENT
READING VS. WRITING IS
WELL OVER 10:1.
Robert C. Martin, aka “Uncle Bob”
WRITING CLEAN CODE IN SWIFT
7 12HOURS MINUTES
Here are three ways in which you can
immediately improve the readability
of your Swift code
#1
USE DESCRIPTIVE
NAMES
#1 USE DESCRIPTIVE NAMES
NAMES SHOULD BE…
▸ Intention-revealing: Why it exists, what it does, how it is
used
▸ Pronounceable: Easy to read, not cryptic, using standard
acronyms
▸ Consistent: Choose a single word for a domain concept
and stick with it
#1 USE DESCRIPTIVE NAMES
RENAMING IS CONSIDERED REFACTORING
▸ Finding the right name the first time is rare.
▸ Names can and should be revised as needed.
▸ Xcode and AppCode have some automated tools to help
with this process.
#1 USE DESCRIPTIVE NAMES
REFACTORING NAMES: XCODE
▸ ⌃ + ⌘ + E → Rename Variable
#1 USE DESCRIPTIVE NAMES
REFACTORING NAMES: APP CODE
▸ Shift + F6 → Rename (on pretty much anything)
#1 USE DESCRIPTIVE NAMES
func calculate(date1: Date, date2: Date) -> String {
var diff: TimeInterval = 0
if (date2 > date1) {
diff = date2.timeIntervalSince(date1)
} else {
return "No time remaining"
}
let s = Int(diff) % 60
let m = Int(diff / 60) % 60
let h = Int(diff / 3600) % 24
let d = Int(diff / 86400)
return "(d) days, (h) hours, (m) minutes, and (s) seconds remaining"
}
#1 USE DESCRIPTIVE NAMES
func calculate(date1: Date, date2: Date) -> String {
var diff: TimeInterval = 0
if (date2 > date1) {
diff = date2.timeIntervalSince(date1)
} else {
return "No time remaining"
}
let s = Int(diff) % 60
let m = Int(diff / 60) % 60
let h = Int(diff / 3600) % 24
let d = Int(diff / 86400)
return "(d) days, (h) hours, (m) minutes, and (s) seconds remaining"
}
let date1 = Date(timeIntervalSince1970: 1484360070) // Jan 14 2017 11:14:30 AM
let date2 = Date(timeIntervalSince1970: 1484557200) // Jan 16 2017 18:00:00 PM
calculate(date1: date1, date2: date2) // 2 days, 6 hours, 45 minutes, 30 seconds
calculate(date1: date2, date2: date1) // No time remaining
#1 USE DESCRIPTIVE NAMES
func formatRemainingTime(pastDate: Date, futureDate: Date) -> String {
var secondsDifference: TimeInterval = 0
if (pastDate < futureDate) {
secondsDifference = date2.timeIntervalSince(date1)
} else {
return "No time remaining"
}
let secondsRemaining = Int(secondsDifference) % 60
let minutesRemaining = Int(secondsDifference / 60) % 60
let hoursRemaining = Int(secondsDifference / 3600) % 24
let daysRemaining = Int(secondsDifference / 86400)
let formattedRemainingTime =
String(daysRemaining) + " days, " +
String(hoursRemaining) + " hours, " +
String(minutesRemaining) + " minutes, and " +
String(secondsRemaining) + " seconds remaining"
return formattedRemainingTime
}
#1 USE DESCRIPTIVE NAMES
func formatRemainingTime(pastDate: Date, futureDate: Date) -> String {
guard (futureDate > pastDate) else {
return "No time remaining"
}
let secondsDifference = futureDate.timeIntervalSince(pastDate)
let secondsRemaining = Int(secondsDifference) % 60
let minutesRemaining = Int(secondsDifference / 60) % 60
let hoursRemaining = Int(secondsDifference / 3600) % 24
let daysRemaining = Int(secondsDifference / 86400)
let formattedRemainingTime =
String(daysRemaining) + " days, " +
String(hoursRemaining) + " hours, " +
String(minutesRemaining) + " minutes, and " +
String(secondsRemaining) + " seconds remaining"
return formattedRemainingTime
}
#2
ORGANIZE YOUR
OBJECTS
#2 ORGANIZE YOUR OBJECTS
USE ‘MARK’ ANNOTATIONS FOR CODE ORGANIZATION
▸ // MARK: -
▸ Can be used for:
▸ Defining common parts of objects
▸ Protocol Conformance
▸ Private Methods
DEFINE PROPERTIES SEPARATE FROM PROTOCOL CONFORMANCE
#2 ORGANIZE YOUR OBJECTS
DEFINE PROPERTIES SEPARATE FROM PROTOCOL CONFORMANCE
{
Properties

+

Initialization
#2 ORGANIZE YOUR OBJECTS
DEFINE PROPERTIES SEPARATE FROM PROTOCOL CONFORMANCE
{
Properties

+

Initialization
{Protocol

Conformance
#2 ORGANIZE YOUR OBJECTS
DEFINE PROPERTIES SEPARATE FROM PROTOCOL CONFORMANCE
{
Properties

+

Initialization
{Protocol

Conformance
{Private 

Methods
#2 ORGANIZE YOUR OBJECTS
VIEW CONTROLLER: SHOW DOCUMENT ITEMS: ^ + 6
#2 ORGANIZE YOUR OBJECTS
VIEW CONTROLLER: SHOW DOCUMENT ITEMS: ^ + 6
#2 ORGANIZE YOUR OBJECTS
VIEW CONTROLLER: SHOW DOCUMENT ITEMS: ^ + 6
#2 ORGANIZE YOUR OBJECTS
XCODE SNIPPETS
#2 ORGANIZE YOUR OBJECTS
#3
AVOID
COMMENTS
EVERY TIME YOU
WRITE A COMMENT,
YOU SHOULD
GRIMACE AND FEEL
THE FAILURE OF
YOUR ABILITY OF
EXPRESSION.
Uncle Bob
CREATE A NEW
METHOD INSTEAD
When you feel the need to write a comment…
#3 AVOID COMMENTS
A SIMPLE COMPARISON
OR
// Check to see if the employee is eligible for full benefits
if (employee.isHourly && employee.age > 65) {
}
if (employee.isEligibleForFullBenefits()) {
}
#3 AVOID COMMENTS
HOW ABOUT DATES?
// Jan 14 2017 11:14:30 AM
let date1 = Date(timeIntervalSince1970: 1484360070)
let Jan_14_2017_11_14_30_AM = Date(timeIntervalSince1970: 1484360070)
OR
#3 AVOID COMMENTS
IS THERE SUCH THING AS A GOOD REASON FOR COMMENTS?
▸ Documentation for frameworks or libraries.
▸ Clarification outside of your control (e.g. library usage).
▸ Warning of consequences.
▸ See ‘Clean Code’ for a few more examples.
#3 AVOID COMMENTS
WRITING CLEAN CODE IN SWIFT
SUMMARY
1. Use Descriptive Names
2. Organize Your Objects
3. Avoid Comments
Writing Clean Code in Swift
@DEREKLEEROCK
Thank you!
Tokyo iOS Meetup January 2017

More Related Content

PPTX
Clean code: SOLID (iOS)
PDF
Final Year Project Synopsis: Post Quantum Encryption using Neural Networks
PDF
Client Initiated Backchannel Authentication (CIBA) and Authlete’s Approach
PDF
Decentralized Electronic Health Record
PDF
Standing the Test of Time: The Date Provider Pattern
PDF
Writing clean code
PDF
Pragmatic Swift
PDF
Perfomatix - iOS swift coding standards
Clean code: SOLID (iOS)
Final Year Project Synopsis: Post Quantum Encryption using Neural Networks
Client Initiated Backchannel Authentication (CIBA) and Authlete’s Approach
Decentralized Electronic Health Record
Standing the Test of Time: The Date Provider Pattern
Writing clean code
Pragmatic Swift
Perfomatix - iOS swift coding standards

Similar to Writing Clean Code in Swift (20)

PPTX
Swift as an OOP Language
PDF
Minimizing Decision Fatigue to Improve Team Productivity
PDF
Swift - the future of iOS app development
 
PDF
Introduction to Swift 2
PDF
A swift introduction to Swift
PDF
Pooya Khaloo Presentation on IWMC 2015
ZIP
Day 2
PDF
Deep Dive Into Swift
PDF
Good Coding Practices with JavaScript
PDF
Apple Swift API Design Guideline
PDF
Think sharp, write swift
PPTX
Code Quality Management iOS
PDF
Testable Code
PDF
iOSNeXT.ro - 10 reasons you'll love Swift - Paul Ardeleanu
PDF
Workshop Swift
PDF
Clean code in JavaScript
PDF
iOS best practices
PDF
Building complex input screens
 
PDF
Programming with Objective-C
PDF
Introduction to ECMAScript 2015
Swift as an OOP Language
Minimizing Decision Fatigue to Improve Team Productivity
Swift - the future of iOS app development
 
Introduction to Swift 2
A swift introduction to Swift
Pooya Khaloo Presentation on IWMC 2015
Day 2
Deep Dive Into Swift
Good Coding Practices with JavaScript
Apple Swift API Design Guideline
Think sharp, write swift
Code Quality Management iOS
Testable Code
iOSNeXT.ro - 10 reasons you'll love Swift - Paul Ardeleanu
Workshop Swift
Clean code in JavaScript
iOS best practices
Building complex input screens
 
Programming with Objective-C
Introduction to ECMAScript 2015
Ad

Recently uploaded (20)

PDF
Jenkins: An open-source automation server powering CI/CD Automation
PPTX
Benefits of DCCM for Genesys Contact Center
PPTX
10 Hidden App Development Costs That Can Sink Your Startup.pptx
DOCX
The Five Best AI Cover Tools in 2025.docx
PPTX
Dynamic Solutions Project Pitch Presentation
PDF
Perfecting Gamer’s Experiences with Performance Testing for Gaming Applicatio...
PPTX
What to Capture When It Breaks: 16 Artifacts That Reveal Root Causes
PPTX
How a Careem Clone App Allows You to Compete with Large Mobility Brands
PDF
Best Practices for Rolling Out Competency Management Software.pdf
PPTX
Save Business Costs with CRM Software for Insurance Agents
PPTX
Using Bootstrap to Make Accessible Front-Ends(2).pptx
PDF
The Future of Smart Factories Why Embedded Analytics Leads the Way
PDF
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
PDF
Microsoft Teams Essentials; The pricing and the versions_PDF.pdf
PDF
Become an Agentblazer Champion Challenge Kickoff
PDF
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
PDF
Best Mobile App Development Company in Lucknow - Code Crafter Web Solutions
PDF
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
PDF
Build Multi-agent using Agent Development Kit
PPTX
Hire Expert Blazor Developers | Scalable Solutions by OnestopDA
Jenkins: An open-source automation server powering CI/CD Automation
Benefits of DCCM for Genesys Contact Center
10 Hidden App Development Costs That Can Sink Your Startup.pptx
The Five Best AI Cover Tools in 2025.docx
Dynamic Solutions Project Pitch Presentation
Perfecting Gamer’s Experiences with Performance Testing for Gaming Applicatio...
What to Capture When It Breaks: 16 Artifacts That Reveal Root Causes
How a Careem Clone App Allows You to Compete with Large Mobility Brands
Best Practices for Rolling Out Competency Management Software.pdf
Save Business Costs with CRM Software for Insurance Agents
Using Bootstrap to Make Accessible Front-Ends(2).pptx
The Future of Smart Factories Why Embedded Analytics Leads the Way
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
Microsoft Teams Essentials; The pricing and the versions_PDF.pdf
Become an Agentblazer Champion Challenge Kickoff
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Best Mobile App Development Company in Lucknow - Code Crafter Web Solutions
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
Build Multi-agent using Agent Development Kit
Hire Expert Blazor Developers | Scalable Solutions by OnestopDA
Ad

Writing Clean Code in Swift

  • 1. WRITING CLEAN CODE IN SWIFT TOKYO IOS MEETUP JANUARY, 2017 DEREK LEE
  • 2. ANY FOOL CAN WRITE CODE THAT A COMPUTER CAN UNDERSTAND. GOOD PROGRAMMERS WRITE CODE THAT HUMANS CAN UNDERSTAND. Martin Fowler
  • 3. … a blog post? … a research paper? … a presentation? SO HOW WOULD YOU WRITE …
  • 8. How much time do you think you spend reading code versus writing code?
  • 9. THE RATIO OF TIME SPENT READING VS. WRITING IS WELL OVER 10:1. Robert C. Martin, aka “Uncle Bob” WRITING CLEAN CODE IN SWIFT
  • 11. Here are three ways in which you can immediately improve the readability of your Swift code
  • 13. #1 USE DESCRIPTIVE NAMES NAMES SHOULD BE… ▸ Intention-revealing: Why it exists, what it does, how it is used ▸ Pronounceable: Easy to read, not cryptic, using standard acronyms ▸ Consistent: Choose a single word for a domain concept and stick with it
  • 14. #1 USE DESCRIPTIVE NAMES RENAMING IS CONSIDERED REFACTORING ▸ Finding the right name the rst time is rare. ▸ Names can and should be revised as needed. ▸ Xcode and AppCode have some automated tools to help with this process.
  • 15. #1 USE DESCRIPTIVE NAMES REFACTORING NAMES: XCODE ▸ ⌃ + ⌘ + E → Rename Variable
  • 16. #1 USE DESCRIPTIVE NAMES REFACTORING NAMES: APP CODE ▸ Shift + F6 → Rename (on pretty much anything)
  • 17. #1 USE DESCRIPTIVE NAMES func calculate(date1: Date, date2: Date) -> String { var diff: TimeInterval = 0 if (date2 > date1) { diff = date2.timeIntervalSince(date1) } else { return "No time remaining" } let s = Int(diff) % 60 let m = Int(diff / 60) % 60 let h = Int(diff / 3600) % 24 let d = Int(diff / 86400) return "(d) days, (h) hours, (m) minutes, and (s) seconds remaining" }
  • 18. #1 USE DESCRIPTIVE NAMES func calculate(date1: Date, date2: Date) -> String { var diff: TimeInterval = 0 if (date2 > date1) { diff = date2.timeIntervalSince(date1) } else { return "No time remaining" } let s = Int(diff) % 60 let m = Int(diff / 60) % 60 let h = Int(diff / 3600) % 24 let d = Int(diff / 86400) return "(d) days, (h) hours, (m) minutes, and (s) seconds remaining" } let date1 = Date(timeIntervalSince1970: 1484360070) // Jan 14 2017 11:14:30 AM let date2 = Date(timeIntervalSince1970: 1484557200) // Jan 16 2017 18:00:00 PM calculate(date1: date1, date2: date2) // 2 days, 6 hours, 45 minutes, 30 seconds calculate(date1: date2, date2: date1) // No time remaining
  • 19. #1 USE DESCRIPTIVE NAMES func formatRemainingTime(pastDate: Date, futureDate: Date) -> String { var secondsDifference: TimeInterval = 0 if (pastDate < futureDate) { secondsDifference = date2.timeIntervalSince(date1) } else { return "No time remaining" } let secondsRemaining = Int(secondsDifference) % 60 let minutesRemaining = Int(secondsDifference / 60) % 60 let hoursRemaining = Int(secondsDifference / 3600) % 24 let daysRemaining = Int(secondsDifference / 86400) let formattedRemainingTime = String(daysRemaining) + " days, " + String(hoursRemaining) + " hours, " + String(minutesRemaining) + " minutes, and " + String(secondsRemaining) + " seconds remaining" return formattedRemainingTime }
  • 20. #1 USE DESCRIPTIVE NAMES func formatRemainingTime(pastDate: Date, futureDate: Date) -> String { guard (futureDate > pastDate) else { return "No time remaining" } let secondsDifference = futureDate.timeIntervalSince(pastDate) let secondsRemaining = Int(secondsDifference) % 60 let minutesRemaining = Int(secondsDifference / 60) % 60 let hoursRemaining = Int(secondsDifference / 3600) % 24 let daysRemaining = Int(secondsDifference / 86400) let formattedRemainingTime = String(daysRemaining) + " days, " + String(hoursRemaining) + " hours, " + String(minutesRemaining) + " minutes, and " + String(secondsRemaining) + " seconds remaining" return formattedRemainingTime }
  • 22. #2 ORGANIZE YOUR OBJECTS USE ‘MARK’ ANNOTATIONS FOR CODE ORGANIZATION ▸ // MARK: - ▸ Can be used for: ▸ Dening common parts of objects ▸ Protocol Conformance ▸ Private Methods
  • 23. DEFINE PROPERTIES SEPARATE FROM PROTOCOL CONFORMANCE #2 ORGANIZE YOUR OBJECTS
  • 24. DEFINE PROPERTIES SEPARATE FROM PROTOCOL CONFORMANCE { Properties
 +
 Initialization #2 ORGANIZE YOUR OBJECTS
  • 25. DEFINE PROPERTIES SEPARATE FROM PROTOCOL CONFORMANCE { Properties
 +
 Initialization {Protocol
 Conformance #2 ORGANIZE YOUR OBJECTS
  • 26. DEFINE PROPERTIES SEPARATE FROM PROTOCOL CONFORMANCE { Properties
 +
 Initialization {Protocol
 Conformance {Private 
 Methods #2 ORGANIZE YOUR OBJECTS
  • 27. VIEW CONTROLLER: SHOW DOCUMENT ITEMS: ^ + 6 #2 ORGANIZE YOUR OBJECTS
  • 28. VIEW CONTROLLER: SHOW DOCUMENT ITEMS: ^ + 6 #2 ORGANIZE YOUR OBJECTS
  • 29. VIEW CONTROLLER: SHOW DOCUMENT ITEMS: ^ + 6 #2 ORGANIZE YOUR OBJECTS
  • 32. EVERY TIME YOU WRITE A COMMENT, YOU SHOULD GRIMACE AND FEEL THE FAILURE OF YOUR ABILITY OF EXPRESSION. Uncle Bob
  • 33. CREATE A NEW METHOD INSTEAD When you feel the need to write a comment… #3 AVOID COMMENTS
  • 34. A SIMPLE COMPARISON OR // Check to see if the employee is eligible for full benefits if (employee.isHourly && employee.age > 65) { } if (employee.isEligibleForFullBenefits()) { } #3 AVOID COMMENTS
  • 35. HOW ABOUT DATES? // Jan 14 2017 11:14:30 AM let date1 = Date(timeIntervalSince1970: 1484360070) let Jan_14_2017_11_14_30_AM = Date(timeIntervalSince1970: 1484360070) OR #3 AVOID COMMENTS
  • 36. IS THERE SUCH THING AS A GOOD REASON FOR COMMENTS? ▸ Documentation for frameworks or libraries. ▸ Clarication outside of your control (e.g. library usage). ▸ Warning of consequences. ▸ See ‘Clean Code’ for a few more examples. #3 AVOID COMMENTS
  • 37. WRITING CLEAN CODE IN SWIFT SUMMARY 1. Use Descriptive Names 2. Organize Your Objects 3. Avoid Comments
  • 39. @DEREKLEEROCK Thank you! Tokyo iOS Meetup January 2017