SlideShare una empresa de Scribd logo
1 de 39
Descargar para leer sin conexión
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
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
@DEREKLEEROCK
Thank you!
Tokyo iOS Meetup January 2017

Más contenido relacionado

La actualidad más candente

Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMRafael Winterhalter
 
Writing Clean Code (Recommendations by Robert Martin)
Writing Clean Code (Recommendations by Robert Martin)Writing Clean Code (Recommendations by Robert Martin)
Writing Clean Code (Recommendations by Robert Martin)Shirish Bari
 
Oracle apex training
Oracle apex trainingOracle apex training
Oracle apex trainingVasudha India
 
Tổng quan ASP.NET CORE - NIVIKI.COM
Tổng quan ASP.NET CORE - NIVIKI.COMTổng quan ASP.NET CORE - NIVIKI.COM
Tổng quan ASP.NET CORE - NIVIKI.COMKhoa Nguyen
 
Integration Testing in AEM
Integration Testing in AEMIntegration Testing in AEM
Integration Testing in AEMconnectwebex
 
SOLID Principle & Design Pattern.pdf
SOLID Principle & Design Pattern.pdfSOLID Principle & Design Pattern.pdf
SOLID Principle & Design Pattern.pdfrony setyawansyah
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesBrett Meyer
 
Paving the road with Jakarta EE and Apache TomEE - JCON 2021
Paving the road with Jakarta EE  and Apache TomEE - JCON 2021Paving the road with Jakarta EE  and Apache TomEE - JCON 2021
Paving the road with Jakarta EE and Apache TomEE - JCON 2021César Hernández
 
Executable UML and SysML Workshop
Executable UML and SysML WorkshopExecutable UML and SysML Workshop
Executable UML and SysML WorkshopEd Seidewitz
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernatehr1383
 
Software devops engineer in test (SDET)
Software devops engineer in test (SDET)Software devops engineer in test (SDET)
Software devops engineer in test (SDET)Sriram Angajala
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsJava Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsIMC Institute
 

La actualidad más candente (20)

Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVM
 
Writing Clean Code (Recommendations by Robert Martin)
Writing Clean Code (Recommendations by Robert Martin)Writing Clean Code (Recommendations by Robert Martin)
Writing Clean Code (Recommendations by Robert Martin)
 
Oracle apex training
Oracle apex trainingOracle apex training
Oracle apex training
 
Flyweight pattern
Flyweight patternFlyweight pattern
Flyweight pattern
 
Actor Model
Actor ModelActor Model
Actor Model
 
Spring data
Spring dataSpring data
Spring data
 
Tổng quan ASP.NET CORE - NIVIKI.COM
Tổng quan ASP.NET CORE - NIVIKI.COMTổng quan ASP.NET CORE - NIVIKI.COM
Tổng quan ASP.NET CORE - NIVIKI.COM
 
Integration Testing in AEM
Integration Testing in AEMIntegration Testing in AEM
Integration Testing in AEM
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
SOLID Principle & Design Pattern.pdf
SOLID Principle & Design Pattern.pdfSOLID Principle & Design Pattern.pdf
SOLID Principle & Design Pattern.pdf
 
ASP.NET Core Unit Testing
ASP.NET Core Unit TestingASP.NET Core Unit Testing
ASP.NET Core Unit Testing
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance Techniques
 
Paving the road with Jakarta EE and Apache TomEE - JCON 2021
Paving the road with Jakarta EE  and Apache TomEE - JCON 2021Paving the road with Jakarta EE  and Apache TomEE - JCON 2021
Paving the road with Jakarta EE and Apache TomEE - JCON 2021
 
Executable UML and SysML Workshop
Executable UML and SysML WorkshopExecutable UML and SysML Workshop
Executable UML and SysML Workshop
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
Ngrx slides
Ngrx slidesNgrx slides
Ngrx slides
 
Software devops engineer in test (SDET)
Software devops engineer in test (SDET)Software devops engineer in test (SDET)
Software devops engineer in test (SDET)
 
Unit 4
Unit 4Unit 4
Unit 4
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsJava Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom Tags
 

Similar a Writing Clean Code in Swift

Social Analytics with MongoDB
Social Analytics with MongoDBSocial Analytics with MongoDB
Social Analytics with MongoDBPatrick Stokes
 
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY SyntaxRubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY SyntaxDr Nic Williams
 
The Art Of Readable Code
The Art Of Readable CodeThe Art Of Readable Code
The Art Of Readable CodeBaidu, Inc.
 
Elasticsearch sur Azure : Make sense of your (BIG) data !
Elasticsearch sur Azure : Make sense of your (BIG) data !Elasticsearch sur Azure : Make sense of your (BIG) data !
Elasticsearch sur Azure : Make sense of your (BIG) data !Microsoft
 
Yevhen Tatarynov "From POC to High-Performance .NET applications"
Yevhen Tatarynov "From POC to High-Performance .NET applications"Yevhen Tatarynov "From POC to High-Performance .NET applications"
Yevhen Tatarynov "From POC to High-Performance .NET applications"LogeekNightUkraine
 
He stopped using for/while loops, you won't believe what happened next!
He stopped using for/while loops, you won't believe what happened next!He stopped using for/while loops, you won't believe what happened next!
He stopped using for/while loops, you won't believe what happened next!François-Guillaume Ribreau
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeWim Godden
 
Fast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDBFast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDBMongoDB
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeWim Godden
 
Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principlesEdorian
 
Developing and Deploying Apps with the Postgres FDW
Developing and Deploying Apps with the Postgres FDWDeveloping and Deploying Apps with the Postgres FDW
Developing and Deploying Apps with the Postgres FDWJonathan Katz
 
MongoDB Solution for Internet of Things and Big Data
MongoDB Solution for Internet of Things and Big DataMongoDB Solution for Internet of Things and Big Data
MongoDB Solution for Internet of Things and Big DataStefano Dindo
 
Lab pratico per la progettazione di soluzioni MongoDB in ambito Internet of T...
Lab pratico per la progettazione di soluzioni MongoDB in ambito Internet of T...Lab pratico per la progettazione di soluzioni MongoDB in ambito Internet of T...
Lab pratico per la progettazione di soluzioni MongoDB in ambito Internet of T...festival ICT 2016
 
Beyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the codeBeyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the codeWim Godden
 
The Ring programming language version 1.3 book - Part 82 of 88
The Ring programming language version 1.3 book - Part 82 of 88The Ring programming language version 1.3 book - Part 82 of 88
The Ring programming language version 1.3 book - Part 82 of 88Mahmoud Samir Fayed
 
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...Flink Forward
 
Building a Location-based platform with MongoDB from Zero.
Building a Location-based platform with MongoDB from Zero.Building a Location-based platform with MongoDB from Zero.
Building a Location-based platform with MongoDB from Zero.Ravi Teja
 
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみたスマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみたTaro Matsuzawa
 
AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)Paul Chao
 

Similar a Writing Clean Code in Swift (20)

Social Analytics with MongoDB
Social Analytics with MongoDBSocial Analytics with MongoDB
Social Analytics with MongoDB
 
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY SyntaxRubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
 
The Art Of Readable Code
The Art Of Readable CodeThe Art Of Readable Code
The Art Of Readable Code
 
Elasticsearch sur Azure : Make sense of your (BIG) data !
Elasticsearch sur Azure : Make sense of your (BIG) data !Elasticsearch sur Azure : Make sense of your (BIG) data !
Elasticsearch sur Azure : Make sense of your (BIG) data !
 
Yevhen Tatarynov "From POC to High-Performance .NET applications"
Yevhen Tatarynov "From POC to High-Performance .NET applications"Yevhen Tatarynov "From POC to High-Performance .NET applications"
Yevhen Tatarynov "From POC to High-Performance .NET applications"
 
He stopped using for/while loops, you won't believe what happened next!
He stopped using for/while loops, you won't believe what happened next!He stopped using for/while loops, you won't believe what happened next!
He stopped using for/while loops, you won't believe what happened next!
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
 
Fast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDBFast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDB
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
 
Save time by applying clean code principles
Save time by applying clean code principlesSave time by applying clean code principles
Save time by applying clean code principles
 
Developing and Deploying Apps with the Postgres FDW
Developing and Deploying Apps with the Postgres FDWDeveloping and Deploying Apps with the Postgres FDW
Developing and Deploying Apps with the Postgres FDW
 
Python training for beginners
Python training for beginnersPython training for beginners
Python training for beginners
 
MongoDB Solution for Internet of Things and Big Data
MongoDB Solution for Internet of Things and Big DataMongoDB Solution for Internet of Things and Big Data
MongoDB Solution for Internet of Things and Big Data
 
Lab pratico per la progettazione di soluzioni MongoDB in ambito Internet of T...
Lab pratico per la progettazione di soluzioni MongoDB in ambito Internet of T...Lab pratico per la progettazione di soluzioni MongoDB in ambito Internet of T...
Lab pratico per la progettazione di soluzioni MongoDB in ambito Internet of T...
 
Beyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the codeBeyond PHP - It's not (just) about the code
Beyond PHP - It's not (just) about the code
 
The Ring programming language version 1.3 book - Part 82 of 88
The Ring programming language version 1.3 book - Part 82 of 88The Ring programming language version 1.3 book - Part 82 of 88
The Ring programming language version 1.3 book - Part 82 of 88
 
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...
 
Building a Location-based platform with MongoDB from Zero.
Building a Location-based platform with MongoDB from Zero.Building a Location-based platform with MongoDB from Zero.
Building a Location-based platform with MongoDB from Zero.
 
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみたスマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
 
AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)
 

Más de Derek Lee Boire

Why I ❤️ Kotlin Multiplatform (and want YOU to also ❤️ Kotlin Multiplatform)
Why I ❤️ Kotlin Multiplatform (and want YOU to also ❤️ Kotlin Multiplatform)Why I ❤️ Kotlin Multiplatform (and want YOU to also ❤️ Kotlin Multiplatform)
Why I ❤️ Kotlin Multiplatform (and want YOU to also ❤️ Kotlin Multiplatform)Derek Lee Boire
 
Effective BDD Testing 効果的なBDDテスト [iOS]
Effective BDD Testing 効果的なBDDテスト [iOS]Effective BDD Testing 効果的なBDDテスト [iOS]
Effective BDD Testing 効果的なBDDテスト [iOS]Derek Lee Boire
 
Standing the Test of Time: The Date Provider Pattern
Standing the Test of Time: The Date Provider PatternStanding the Test of Time: The Date Provider Pattern
Standing the Test of Time: The Date Provider PatternDerek Lee Boire
 
Minimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team ProductivityMinimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team ProductivityDerek Lee Boire
 
Common Challenges & Best Practices for TDD on iOS
Common Challenges & Best Practices for TDD on iOSCommon Challenges & Best Practices for TDD on iOS
Common Challenges & Best Practices for TDD on iOSDerek Lee Boire
 
Adjusting to Auto Layout (Tutorial / Tips for iOS Auto Layout)
Adjusting to Auto Layout (Tutorial / Tips for iOS Auto Layout)Adjusting to Auto Layout (Tutorial / Tips for iOS Auto Layout)
Adjusting to Auto Layout (Tutorial / Tips for iOS Auto Layout)Derek Lee Boire
 

Más de Derek Lee Boire (6)

Why I ❤️ Kotlin Multiplatform (and want YOU to also ❤️ Kotlin Multiplatform)
Why I ❤️ Kotlin Multiplatform (and want YOU to also ❤️ Kotlin Multiplatform)Why I ❤️ Kotlin Multiplatform (and want YOU to also ❤️ Kotlin Multiplatform)
Why I ❤️ Kotlin Multiplatform (and want YOU to also ❤️ Kotlin Multiplatform)
 
Effective BDD Testing 効果的なBDDテスト [iOS]
Effective BDD Testing 効果的なBDDテスト [iOS]Effective BDD Testing 効果的なBDDテスト [iOS]
Effective BDD Testing 効果的なBDDテスト [iOS]
 
Standing the Test of Time: The Date Provider Pattern
Standing the Test of Time: The Date Provider PatternStanding the Test of Time: The Date Provider Pattern
Standing the Test of Time: The Date Provider Pattern
 
Minimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team ProductivityMinimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team Productivity
 
Common Challenges & Best Practices for TDD on iOS
Common Challenges & Best Practices for TDD on iOSCommon Challenges & Best Practices for TDD on iOS
Common Challenges & Best Practices for TDD on iOS
 
Adjusting to Auto Layout (Tutorial / Tips for iOS Auto Layout)
Adjusting to Auto Layout (Tutorial / Tips for iOS Auto Layout)Adjusting to Auto Layout (Tutorial / Tips for iOS Auto Layout)
Adjusting to Auto Layout (Tutorial / Tips for iOS Auto Layout)
 

Último

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 

Último (20)

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 

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 …
  • 5.
  • 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 first 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: ▸ Defining 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. ▸ Clarification 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
  • 38.
  • 39. @DEREKLEEROCK Thank you! Tokyo iOS Meetup January 2017