SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Downloaden Sie, um offline zu lesen
Writing clean code
Mobiquity - Ángel García (Mobile developer)
What is all this about?
Table of contents
• What is clean code?
• Why is readability important?
• Code style
• Code formatting
• Naming conventions
• Code comments
• Code structure
• Control sentences
• Functions and methods
• Classes
• Architecture level
• Modules
• Software patterns
• Programming paradigms
• Tools
Before we start
A bit of context
• No universal definition
!
• Difference between clean code, working code and good code
• Clean code: readable, maintainable, extensible
• Working code: does what it is supposed to do
• Good code: combination of clean and working code
What is clean code?
Working
code
Clean
code
Good
code
Why is readability important?
• The process of changing code:
1.Find component
2.Find affected lines
3.Write
4.Test
!
• Reading —> 80/20
!
• Readability:
• Save your time
• Improve maintenance
• Increase extensibility
Code formatting
ReAD Ing iS nO t Al Wa iS aS E as Y As IT cO uLd bE
Code formatting
{"id":10,"childs":[{"id":1,"title":"A"},{"id":2,"title":"B"}],"active": true,"title":
"Hello World”}
{
"id": 10,
"childs": [
{
"id": 1,
"title": "A"
},
{
"id": 2,
"title": "B"
}
],
"active": true,
"title": "Hello World"
}
Code formatting
• Brain is good on recognising patterns
• Vertical space
• Horizontal space
• Expressions
• Casing
!
• Text search along project
!
• Follow language styles
!
• Be consistent
Naming conventions
What the hell does this mean?
Naming conventions
• The importance of naming. What does this code do?
!
func doMyStuff(param1: Bool, param2: Bool, param3:Int) -> Int {
if param3 > 0 {
var a = 0
if param3 % 2 == 0 && param2 {
a = param3
}
else if param3 % 2 == 1 && param1 {
a = param3
}
return a + doMyStuff(param1, param2, param3 - 1)
}
else {
return 0
}
}
!
doMyStuff(true, true, 4)
Naming conventions
• The importance of naming. What does this code do?
!
func summation(fromNumber:Int, includeEven: Bool = true, includeOdd: Bool = true) -> Int {
if fromNumber > 0 {
var currentSum = 0
if fromNumber % 2 == 0 && includeOdd {
currentSum = fromNumber
}
else if fromNumber % 2 == 1 && includeEven {
currentSum = fromNumber
}
return currentSum + summation(fromNumber - 1, includeEven: includeEven, includeOdd:
includeOdd)
}
else {
return 0
}
}
!
summation(4)
Naming conventions
• Names should be explicit and clear
temp.active = YES;
product.active = YES;
!
!
• Provide context
inactiveProducts.count;
!
!
• Avoid shortcuts
!
• Avoid Business/Technical names when possible
!
• Follow language conventions (ivars, setters/getters, casing,…)
!
• Be consistent (remove/delete, create/insert,…)
Code comments
“Now hiring now.
Right now we are hiring now”
Code comments
• Issues
• Can be outdated (misleading)
• Require language switch
!
• Types
• Redundant
//Start reachability notifications
[[Reachability reachabilityForInternetConnection] startNotifier];
!
!
• Separate blocks with different responsibilities
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)index {
//Create cell
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
…
//Configure cell
…
return cell;
}
!
• Commented-out code
Code comments
• Code is not self-explanatory
• Code has side effects
//Careful! setting delegate reloads table content
self.tableView.delegate = self;
!
• Domain specific (complex math, business rules,…)
• Public APIs in libs
/**
Loads Purchase history and returns MOReceipts
@param block Block executed when the history is loaded. Contains parsed MOReceipts
@param errorBlock Block executed when an error occurs
*/
- (void)updateReceiptsOnSuccess:(MOResponseArrayBlock)block error:
(MOErrorBlock)errorBlock;
!
• In general, avoid comments
Control sentences
Where the linear flow ends
Control sentences
• Format
• Conditionals:
• Simple expressions —> variables
if (price - price * discountPercentage + discountAmount < minimumPrice) {
println("Difficult clause")
}
!
let amountToPay = price - price * discountPercentage + discountAmount
if (amountToPay < minimumPrice) {}
!
• Do not use more than 3 or 4 expressions
• Prefer positive clauses
var notForbidden = false
if !notForbidden {}
!
!
• Do not use assignments or side effects
if ((x = y * 2) != 0) {}
if (self = [super init]) {}
if (condition && [self destroyObject]) {}
Control sentences
• Avoid Spaghetti code (nested depth < 3)
if (condition1) {
if (condition2) {
for(i = 0; i < 10; i++) {
if (condition4) {
if (condition5) {
}
return;
}
}
}
}
!
!
• Collapse when possible
if (condition1) {
if (condition2) {
}
}
!
if (condition1 && condition2) {
}
!
• Do not use goto, break, continue
Control sentences
• “if”statements
• Avoid empty cases
• Avoid obvious“else if”clauses
if flag {
}
else if !flag {
println("Difficult to read")
}
• “for”loops
• Do not abuse
for (;condition;) { /*...*/ }
• Do not modify the conditional variable inside
for (i = 0; i < 10; i++) {
i *= 2;
}
!
• Ternary operators
• Only use for assignments
condition? [self method1] : [self method2];
name = user.name? : @"Anonymous";
!
• Must be extremely simple
Functions and methods
Your code in small steps
Functions and methods
• Clear naming
summation(4)
!
• 1 Level of abstraction
let dates = downloadAndParse(“http://myrurl.com”)
!
• Single Responsibility Principle (SRP)
“Every context should have a single responsibility, and that responsibility should be entirely encapsulated by the context”
- Wikipedia
!
• No side effects
!
• Explicit error handling
- (BOOL)writeToURL:(NSURL *)aURL
options:(NSDataWritingOptions)mask
error:(NSError **)errorPtr;
Functions and methods
• Parameters
• Prefer over instance variables (or globals/statics)
• Avoid output
• Reduce amount (<4)
[NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeWidth multiplier:0.5
constant:0.0]
!
• 1 point of exit
!
• Remove empty methods or only calling super
!
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
Classes
Your building blocks
Classes
• SRP. Check yourself:
• Name should describe responsibility
• Describe functionality without “and”,“or”,“but”,“if”
• Do you have flags?
!
• Open-Close principle
“Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification” - Wikipedia
!
• Hide all implementation details
• Simplify public headers/methods/properties
!
• Explicit dependencies
!
• Sort you methods and properties (public/private)
Classes
• Avoid statics
!
• Use polymorphism
if (a.isKindOfClass(MyClass)) {
!
!
• Take advantage of categories
MyProjectUtils.convertToUrlEncoding("hello")
StringUtils.convertToUrlEncoding(“hello")
“hello".convertToUrlEncoding()
!
"hello".drawInRect(rect:rect, withAttributes: attributes)
!
• Sort your toolbox!
Modules
Integrating all the pieces
Modules
• SoC
“Design principle for separating a computer program into distinct sections, such that each section addresses a separate
concern. A concern is a set of information that affects the code of a computer program”. Wikipedia
!
• Explicit
• API
• Callbacks (protocols, blocks,…)
• Threads
!
• Split by functionality vs type
!
• Hide internals
!
• Structure your data
- (NSDictionary *)findNearestPersonToLocation:(NSArray *)coordinates;
- (Person *)findNearestPersonToLocation:(CLLocationCoordinate2D)coordinate;
Modules
• Dependencies
• Law of Demeter
“LoD can be succinctly summarized in one of the following ways:
• Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.
• Each unit should only talk to its friends; don't talk to strangers.
• Only talk to your immediate friends.”. Wikipedia
!
aVar.getB().getC()
!
!
• Avoid cycles
!
• Prefer Interfaces vs concrete classes
!
• Isolate lifecycle
!
• Make proper use of Software patterns
A B C
Software patterns
Everybody can ride a bike
Software patterns
• Robust, flexible and well known solutions
!
• Reduce cognitive load
“Among psychologists it is widely acknowledged that, compared to "cold" learning, people learn more effectively when
they can build on what they already understand”. Wikipedia.
!
• Some of most interesting:
• MVC / MVVM
• Inheritance / Composition
• Inversion Of Control / Dependency Injection
• Delegate/Observer
• Factory
• Chain Of Responsibility
• ….
MVC
• Model
• Contains information in Plain objects
• Connects to endpoints, DB,.…
• View
• Draws the screen
• Receives/passes events to/from controllers
• Controller
• Connects the View and the Model layers
!
• Most common pitfalls in iOS
• Massive controllers (DataSources, components,…)
• Controllers doing Model/View work
• View & Controller coupling
!
• Alternative: MVVM (Model-View-ViewModel)
Inheritance vs Composition
• Inheritance is good for“is-a”relations
• Use composition as default
Inheritance Composition
Difficult to keep SRP Easy to keep SRP
Details from base class to subclasses Close components
Massive base classes Small components
Behaviour on compilation time Behaviour on runtime
Inversion of Control / Dependency Injection
• Increase reusability of modules
• Lifecycle controlled on system level
• IoC
• Invert relation code-3rd party
• Generic API definitions
• Dependencies are provided
• DI
• Dependencies are injected (constructors, setters)
!
class TextEditor {
var checker = SpellCheckerES() //TextEditor coupled with ES checker
}
!
class TextEditor {
var checker: SpellChecker
init(checker: SpellChecker) {
self.checker = checker //Implementation of checker decided by DI controller
}
}
Programming paradigms
Learning from others
Aspect Oriented Programming
• Ideal for cross-cutting concerns
!
• Hooks code before/after methods
!
• Aspects (https://github.com/steipete/Aspects)
[UIViewController aspect_hookSelector:@selector(viewWillAppear:)
withOptions:AspectPositionAfter
usingBlock:^(id<AspectInfo> aspectInfo, BOOL animated) {
NSLog(@"View Controller will appear");
} error:nil];
Reactive programming
• Ideal for event-driven datasources
!
• Automatic propagation of changes
!
• Reduces/hides state
• Time independent code
!
• Reactive Cocoa (https://github.com/ReactiveCocoa/ReactiveCocoa)
RAC(self.logInButton, enabled) = [RACSignal
combineLatest:@[
self.usernameTextField.rac_textSignal,
self.passwordTextField.rac_textSignal,
RACObserve(LoginManager.sharedManager, loggingIn)
]
reduce:^(NSString *username, NSString *password, NSNumber *loggingIn) {
return @(username.length > 0 && password.length > 0 && !loggingIn.boolValue);
}];
Functional programming
• Mimic mathematical functions
!
• Avoids state
!
• Outputs only dependent on inputs
• No side effects
• Parallelizable
• Predictable (race conditions)
!
• Chainable operations
!
let evenSum = Array(1...10)
.filter { (number) in number % 2 == 0 }
.reduce(0) { (total, number) in total + number }
Tools
Computers can also help you
Tools
• Uncrustify (http://uncrustify.sourceforge.net/)
!
• OCLint (http://oclint.org/)
!
• Sonar for Objective-C (https://github.com/octo-technology)
!
• Objc-dependency-visualizer (https://github.com/PaulTaykalo/objc-dependency-visualizer)
References
• Clean code: A handbook of Agile Software Craftsmanship
!
!
!
!
!
!
!
!
!
!
• Objc.io (http://www.objc.io/)
Thank you!
Q&A

Weitere ähnliche Inhalte

Was ist angesagt?

Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code PrinciplesYeurDreamin'
 
Clean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software CraftsmanshipClean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software CraftsmanshipIvan Paulovich
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best PracticesTheo Jungeblut
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafThymeleaf
 
Introduction to SOLID Principles
Introduction to SOLID PrinciplesIntroduction to SOLID Principles
Introduction to SOLID PrinciplesGanesh Samarthyam
 
SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design PrinciplesAndreas Enbohm
 
Clean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithClean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithVictor Rentea
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Scott Wlaschin
 
Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Scott Wlaschin
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean codeVictor Rentea
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental PrinciplesIntro C# Book
 

Was ist angesagt? (20)

Clean code
Clean codeClean code
Clean code
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code Principles
 
Clean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software CraftsmanshipClean Architecture Essentials - Stockholm Software Craftsmanship
Clean Architecture Essentials - Stockholm Software Craftsmanship
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
 
Clean code
Clean codeClean code
Clean code
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
 
Clean Code
Clean CodeClean Code
Clean Code
 
Introduction to SOLID Principles
Introduction to SOLID PrinciplesIntroduction to SOLID Principles
Introduction to SOLID Principles
 
SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design Principles
 
Clean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithClean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a Monolith
 
Clean code
Clean code Clean code
Clean code
 
Clean code
Clean codeClean code
Clean code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)Functional Design Patterns (DevTernity 2018)
Functional Design Patterns (DevTernity 2018)
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
 

Ähnlich wie Writing clean code

Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_reviewEdureka!
 
Introduction to JavaScript design patterns
Introduction to JavaScript design patternsIntroduction to JavaScript design patterns
Introduction to JavaScript design patternsJeremy Duvall
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#Hawkman Academy
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean CodingMetin Ogurlu
 
Writing Testable Code
Writing Testable CodeWriting Testable Code
Writing Testable Codejameshalsall
 
Test Driven Development - Workshop
Test Driven Development - WorkshopTest Driven Development - Workshop
Test Driven Development - WorkshopAnjana Somathilake
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tipsBill Buchan
 
Keep Code Left - How to write better code in almost any language
Keep Code Left - How to write better code in almost any languageKeep Code Left - How to write better code in almost any language
Keep Code Left - How to write better code in almost any languageMick Andrew
 
Web technologies-course 12.pptx
Web technologies-course 12.pptxWeb technologies-course 12.pptx
Web technologies-course 12.pptxStefan Oprea
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basicsLovelitJose
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018Mike Harris
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesInductive Automation
 
ITB2017 - Slaying the ORM dragons with cborm
ITB2017 - Slaying the ORM dragons with cbormITB2017 - Slaying the ORM dragons with cborm
ITB2017 - Slaying the ORM dragons with cbormOrtus Solutions, Corp
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesInductive Automation
 

Ähnlich wie Writing clean code (20)

Perfect Code
Perfect CodePerfect Code
Perfect Code
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_review
 
Refactoring
RefactoringRefactoring
Refactoring
 
Introduction to JavaScript design patterns
Introduction to JavaScript design patternsIntroduction to JavaScript design patterns
Introduction to JavaScript design patterns
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean Coding
 
Writing Testable Code
Writing Testable CodeWriting Testable Code
Writing Testable Code
 
Test Driven Development - Workshop
Test Driven Development - WorkshopTest Driven Development - Workshop
Test Driven Development - Workshop
 
Clean code
Clean codeClean code
Clean code
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tips
 
Keep Code Left - How to write better code in almost any language
Keep Code Left - How to write better code in almost any languageKeep Code Left - How to write better code in almost any language
Keep Code Left - How to write better code in almost any language
 
Web technologies-course 12.pptx
Web technologies-course 12.pptxWeb technologies-course 12.pptx
Web technologies-course 12.pptx
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
 
Production-ready Software
Production-ready SoftwareProduction-ready Software
Production-ready Software
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
ITB2017 - Slaying the ORM dragons with cborm
ITB2017 - Slaying the ORM dragons with cbormITB2017 - Slaying the ORM dragons with cborm
ITB2017 - Slaying the ORM dragons with cborm
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 

Kürzlich hochgeladen

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
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
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
 
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
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
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
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
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
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
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
 
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
 
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
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
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
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 

Kürzlich hochgeladen (20)

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 ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
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...
 
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
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
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
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
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
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
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...
 
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 ...
 
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
 
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
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
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
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

Writing clean code

  • 1. Writing clean code Mobiquity - Ángel García (Mobile developer)
  • 2. What is all this about?
  • 3. Table of contents • What is clean code? • Why is readability important? • Code style • Code formatting • Naming conventions • Code comments • Code structure • Control sentences • Functions and methods • Classes • Architecture level • Modules • Software patterns • Programming paradigms • Tools
  • 4. Before we start A bit of context
  • 5. • No universal definition ! • Difference between clean code, working code and good code • Clean code: readable, maintainable, extensible • Working code: does what it is supposed to do • Good code: combination of clean and working code What is clean code? Working code Clean code Good code
  • 6. Why is readability important? • The process of changing code: 1.Find component 2.Find affected lines 3.Write 4.Test ! • Reading —> 80/20 ! • Readability: • Save your time • Improve maintenance • Increase extensibility
  • 7. Code formatting ReAD Ing iS nO t Al Wa iS aS E as Y As IT cO uLd bE
  • 8. Code formatting {"id":10,"childs":[{"id":1,"title":"A"},{"id":2,"title":"B"}],"active": true,"title": "Hello World”} { "id": 10, "childs": [ { "id": 1, "title": "A" }, { "id": 2, "title": "B" } ], "active": true, "title": "Hello World" }
  • 9. Code formatting • Brain is good on recognising patterns • Vertical space • Horizontal space • Expressions • Casing ! • Text search along project ! • Follow language styles ! • Be consistent
  • 10. Naming conventions What the hell does this mean?
  • 11. Naming conventions • The importance of naming. What does this code do? ! func doMyStuff(param1: Bool, param2: Bool, param3:Int) -> Int { if param3 > 0 { var a = 0 if param3 % 2 == 0 && param2 { a = param3 } else if param3 % 2 == 1 && param1 { a = param3 } return a + doMyStuff(param1, param2, param3 - 1) } else { return 0 } } ! doMyStuff(true, true, 4)
  • 12. Naming conventions • The importance of naming. What does this code do? ! func summation(fromNumber:Int, includeEven: Bool = true, includeOdd: Bool = true) -> Int { if fromNumber > 0 { var currentSum = 0 if fromNumber % 2 == 0 && includeOdd { currentSum = fromNumber } else if fromNumber % 2 == 1 && includeEven { currentSum = fromNumber } return currentSum + summation(fromNumber - 1, includeEven: includeEven, includeOdd: includeOdd) } else { return 0 } } ! summation(4)
  • 13. Naming conventions • Names should be explicit and clear temp.active = YES; product.active = YES; ! ! • Provide context inactiveProducts.count; ! ! • Avoid shortcuts ! • Avoid Business/Technical names when possible ! • Follow language conventions (ivars, setters/getters, casing,…) ! • Be consistent (remove/delete, create/insert,…)
  • 14. Code comments “Now hiring now. Right now we are hiring now”
  • 15. Code comments • Issues • Can be outdated (misleading) • Require language switch ! • Types • Redundant //Start reachability notifications [[Reachability reachabilityForInternetConnection] startNotifier]; ! ! • Separate blocks with different responsibilities - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)index { //Create cell UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier]; … //Configure cell … return cell; } ! • Commented-out code
  • 16. Code comments • Code is not self-explanatory • Code has side effects //Careful! setting delegate reloads table content self.tableView.delegate = self; ! • Domain specific (complex math, business rules,…) • Public APIs in libs /** Loads Purchase history and returns MOReceipts @param block Block executed when the history is loaded. Contains parsed MOReceipts @param errorBlock Block executed when an error occurs */ - (void)updateReceiptsOnSuccess:(MOResponseArrayBlock)block error: (MOErrorBlock)errorBlock; ! • In general, avoid comments
  • 17. Control sentences Where the linear flow ends
  • 18. Control sentences • Format • Conditionals: • Simple expressions —> variables if (price - price * discountPercentage + discountAmount < minimumPrice) { println("Difficult clause") } ! let amountToPay = price - price * discountPercentage + discountAmount if (amountToPay < minimumPrice) {} ! • Do not use more than 3 or 4 expressions • Prefer positive clauses var notForbidden = false if !notForbidden {} ! ! • Do not use assignments or side effects if ((x = y * 2) != 0) {} if (self = [super init]) {} if (condition && [self destroyObject]) {}
  • 19. Control sentences • Avoid Spaghetti code (nested depth < 3) if (condition1) { if (condition2) { for(i = 0; i < 10; i++) { if (condition4) { if (condition5) { } return; } } } } ! ! • Collapse when possible if (condition1) { if (condition2) { } } ! if (condition1 && condition2) { } ! • Do not use goto, break, continue
  • 20. Control sentences • “if”statements • Avoid empty cases • Avoid obvious“else if”clauses if flag { } else if !flag { println("Difficult to read") } • “for”loops • Do not abuse for (;condition;) { /*...*/ } • Do not modify the conditional variable inside for (i = 0; i < 10; i++) { i *= 2; } ! • Ternary operators • Only use for assignments condition? [self method1] : [self method2]; name = user.name? : @"Anonymous"; ! • Must be extremely simple
  • 21. Functions and methods Your code in small steps
  • 22. Functions and methods • Clear naming summation(4) ! • 1 Level of abstraction let dates = downloadAndParse(“http://myrurl.com”) ! • Single Responsibility Principle (SRP) “Every context should have a single responsibility, and that responsibility should be entirely encapsulated by the context” - Wikipedia ! • No side effects ! • Explicit error handling - (BOOL)writeToURL:(NSURL *)aURL options:(NSDataWritingOptions)mask error:(NSError **)errorPtr;
  • 23. Functions and methods • Parameters • Prefer over instance variables (or globals/statics) • Avoid output • Reduce amount (<4) [NSLayoutConstraint constraintWithItem:view1 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:view2 attribute:NSLayoutAttributeWidth multiplier:0.5 constant:0.0] ! • 1 point of exit ! • Remove empty methods or only calling super ! - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { } return self; }
  • 25. Classes • SRP. Check yourself: • Name should describe responsibility • Describe functionality without “and”,“or”,“but”,“if” • Do you have flags? ! • Open-Close principle “Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification” - Wikipedia ! • Hide all implementation details • Simplify public headers/methods/properties ! • Explicit dependencies ! • Sort you methods and properties (public/private)
  • 26. Classes • Avoid statics ! • Use polymorphism if (a.isKindOfClass(MyClass)) { ! ! • Take advantage of categories MyProjectUtils.convertToUrlEncoding("hello") StringUtils.convertToUrlEncoding(“hello") “hello".convertToUrlEncoding() ! "hello".drawInRect(rect:rect, withAttributes: attributes) ! • Sort your toolbox!
  • 28. Modules • SoC “Design principle for separating a computer program into distinct sections, such that each section addresses a separate concern. A concern is a set of information that affects the code of a computer program”. Wikipedia ! • Explicit • API • Callbacks (protocols, blocks,…) • Threads ! • Split by functionality vs type ! • Hide internals ! • Structure your data - (NSDictionary *)findNearestPersonToLocation:(NSArray *)coordinates; - (Person *)findNearestPersonToLocation:(CLLocationCoordinate2D)coordinate;
  • 29. Modules • Dependencies • Law of Demeter “LoD can be succinctly summarized in one of the following ways: • Each unit should have only limited knowledge about other units: only units "closely" related to the current unit. • Each unit should only talk to its friends; don't talk to strangers. • Only talk to your immediate friends.”. Wikipedia ! aVar.getB().getC() ! ! • Avoid cycles ! • Prefer Interfaces vs concrete classes ! • Isolate lifecycle ! • Make proper use of Software patterns A B C
  • 31. Software patterns • Robust, flexible and well known solutions ! • Reduce cognitive load “Among psychologists it is widely acknowledged that, compared to "cold" learning, people learn more effectively when they can build on what they already understand”. Wikipedia. ! • Some of most interesting: • MVC / MVVM • Inheritance / Composition • Inversion Of Control / Dependency Injection • Delegate/Observer • Factory • Chain Of Responsibility • ….
  • 32. MVC • Model • Contains information in Plain objects • Connects to endpoints, DB,.… • View • Draws the screen • Receives/passes events to/from controllers • Controller • Connects the View and the Model layers ! • Most common pitfalls in iOS • Massive controllers (DataSources, components,…) • Controllers doing Model/View work • View & Controller coupling ! • Alternative: MVVM (Model-View-ViewModel)
  • 33. Inheritance vs Composition • Inheritance is good for“is-a”relations • Use composition as default Inheritance Composition Difficult to keep SRP Easy to keep SRP Details from base class to subclasses Close components Massive base classes Small components Behaviour on compilation time Behaviour on runtime
  • 34. Inversion of Control / Dependency Injection • Increase reusability of modules • Lifecycle controlled on system level • IoC • Invert relation code-3rd party • Generic API definitions • Dependencies are provided • DI • Dependencies are injected (constructors, setters) ! class TextEditor { var checker = SpellCheckerES() //TextEditor coupled with ES checker } ! class TextEditor { var checker: SpellChecker init(checker: SpellChecker) { self.checker = checker //Implementation of checker decided by DI controller } }
  • 36. Aspect Oriented Programming • Ideal for cross-cutting concerns ! • Hooks code before/after methods ! • Aspects (https://github.com/steipete/Aspects) [UIViewController aspect_hookSelector:@selector(viewWillAppear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo, BOOL animated) { NSLog(@"View Controller will appear"); } error:nil];
  • 37. Reactive programming • Ideal for event-driven datasources ! • Automatic propagation of changes ! • Reduces/hides state • Time independent code ! • Reactive Cocoa (https://github.com/ReactiveCocoa/ReactiveCocoa) RAC(self.logInButton, enabled) = [RACSignal combineLatest:@[ self.usernameTextField.rac_textSignal, self.passwordTextField.rac_textSignal, RACObserve(LoginManager.sharedManager, loggingIn) ] reduce:^(NSString *username, NSString *password, NSNumber *loggingIn) { return @(username.length > 0 && password.length > 0 && !loggingIn.boolValue); }];
  • 38. Functional programming • Mimic mathematical functions ! • Avoids state ! • Outputs only dependent on inputs • No side effects • Parallelizable • Predictable (race conditions) ! • Chainable operations ! let evenSum = Array(1...10) .filter { (number) in number % 2 == 0 } .reduce(0) { (total, number) in total + number }
  • 40. Tools • Uncrustify (http://uncrustify.sourceforge.net/) ! • OCLint (http://oclint.org/) ! • Sonar for Objective-C (https://github.com/octo-technology) ! • Objc-dependency-visualizer (https://github.com/PaulTaykalo/objc-dependency-visualizer)
  • 41. References • Clean code: A handbook of Agile Software Craftsmanship ! ! ! ! ! ! ! ! ! ! • Objc.io (http://www.objc.io/)