The Missing Manual For Swift Development Bart Jacobs
User Manual:
Open the PDF directly: View PDF .
Page Count: 269 [warning: Documents this large are best viewed by clicking the View PDF Link!]
- Welcome
- Part 1: Foundation
- Part 2: Swift
- Part 3: Projects
- Part 4: Workflow
- Part 5: Team
- Part 6: Career
- Part 7: Products
- Part 8: You
- Part 9: Learning
TheMissingManualforSwiftDevelopment
BartJacobs
Thisbookisforsaleathttp://leanpub.com/the-missing-manual-for-swift-
development
Thisversionwaspublishedon2017-09-27
*****
ThisisaLeanpubbook.Leanpubempowersauthorsandpublisherswith
theLeanPublishingprocess.LeanPublishingistheactofpublishingan
in-progressebookusinglightweighttoolsandmanyiterationstoget
readerfeedback,pivotuntilyouhavetherightbookandbuildtraction
onceyoudo.
*****
©2017CodeFoundryBVBA
TableofContents
Welcome
Part1:Foundation
1YourFoundation
WhatIsYourFoundation
ThereIsNoClearPath
2WheretoStart
SettingYourselfUpforSuccess
APathWithoutDistractions
ChooseYourTeacherWisely
3KnowYourTools
Xcode
DeveloperPortal
Provisioning
Instruments
CommandLine
ThirdPartyTools
4AdoptBestPractices
WhatAreBestPractices
Patterns
Anti-patterns
GoodPracticesforSwift
BeCritical
5Security
MakeItHard
PlainText
ObfuscatingInformation
FetchingSensitiveInformation
Encryption
Privacy
LoggingandDebugging
EducatingYourClient
6Don’tIgnoreYourFoundation
UndertheHood
Dependencies
Don’tIgnoretheFundamentals
7RespecttheSDK
KnowYourLimitations
RespecttheSDK
9DesignPatterns
Model-View-Controller
Model-View-ViewModel
Singletons
DependencyInjection
References,Delegation,andNotifications
MasterThesePatterns
6Protocol-OrientedProgramming
7ReactiveProgramming
Part2:Swift
1LearnSwiftWithanOpenMind
ReferenceTypesandValueTypes
Protocol-OrientedProgramming
TypeSafety
BestPractices
ForgetWhatYouKnow
2BeCritical
3EmbracingOptionals
WarningSign
EleganceandBeauty
SwifttotheRescue
EmbraceOptionals
4MindtheExclamationMark
UseCases
ConvenienceandLaziness
Don’tBeLazy
WhenIUsetheExclamationMark
APersonalChoice
5ExclamationMarksandFatalErrors
ClarityOverSubtleness
ChoosingforClarity
6SmellyCode
ForcedUnwrappingandConversion
MonsterClasses
MassiveMethods
IgnoringErrors
Singletons
StringLiterals
IsYourCodeSmelly
7ValueTypesandReferenceTypes
What’stheFuss
AnExample
BenefitsofValueTypes
WhentoUseValueTypes
8CatchingErrors
WhenShouldYouHandleErrors
WhereShouldYouHandleErrors
NotifyingtheUser
MonitoringApplicationHealth
Don’tIgnoreThem
9UsingFatalErrorstoWriteElegantSwift
WhattoDoWhenYouDon’tKnowWhattoDo
GuardingAgainstUnexpectedEvents
UseFatalErrorsSparingly
ClarityandElegance
Part3:Projects
1ABrandNewProject
Step1:SettingUptheProject
Step2:OrganizingtheProject
Step3:AddingaREADME.md
Step4:BuildandRun
Step5:Addinga.gitignore
Step6:PuttingtheProjectUnderSourceControl
Step7:PushingtheProjecttoGitHub
Step8:OptionalSteps
2ProjectStructure
AnExample
ViewControllers
TestTarget
OnDisk
WhatDoIGain
Tools
Caveats
3ProjectHygiene
ProjectsEvolve
ObsoleteFiles
Comments
Documentation
Don’tCommitEverything
GuidelinesandExceptions
4DocumentEverything
StartWiththeBasics
MakeItEasy
WhattoDocument
UptoDate
MakeItaCoreTool
I’maTeamofOne
MakeItaHabit
TimeIsMoney
Part4:Workflow
1Testing
WheretoStart
CodeCoverage
WritingBetterCode
DependencyInjection
XcodeandTesting
MyCurrentTestSetup
WhatAreYouTesting
ItTakesTime
2ContinuousIntegration
WhatIsIt
WhyIsThisUseful
LongHangingFruit
AvoidHumanTinkering
TestFlight
PainlessReleases
MakeItRobust
Transparency
LearningCurve
3Refactoring
TechnicalDebt
BuildingfortheFuture
TheFallacyofSunkCost
StartingAnew
4SourceControl
TheBasics
Don’tBreakTheseRules
Commits
Stashing
Patching
GitFlow
SomeTips
5Dependencies
MinimizeDependencies
WhatIsaDependency
FewerDependencies
MappingtheLiabilitiesofaProject
Don’tMakeYourLifeTooEasy
RollingYourOwn
ChooseWisely
BecomingaBetterDeveloper
WatchOutfortheDefaults
ChallengeYourself
6Automation
Scripting
BuildPhases
AutomatedTesting
Documentation
ContinuousIntegration
fastlane
KeepItSimple
7Privacy
ProtectingtheUser’sPrivacy
WhoDoYouWorkWith
GivingtheUserControl
ThirdPartySDKs
ChooseWisely
8WhattoDoWhenYouInheritaSoftwareProject
FirstThingsFirst
BuildandRun
CollectData
Dependencies
WorkingontheProject
DocumentEverything
AndBeyond
9Speed,Quality,andTechnicalDebt
SpeedandQuality
TechnicalDebt
Focus
HowtoGetRidofTechnicalDebt
TakingShortcuts
Part5:Team
1CodeReviews
JustStart
CalendarandAgenda
MakeThemActionable
KeepThemSmall
BePrepared
Tools
ThatHurts
ConvincingManagement
Frequency
ButIt’sJustMe
GiveItaTry
2AdoptaStyleGuide
WhyHaveOne
Automation
RoughTransition
3WorkingInaTeam
HiretheRightPeople
Leadership
Communication
GiveItTime
Respect
WhenThingsHittheFan
OwnershipandResponsibility
ShareandAsk
4BeingaLeader
ListenandBeOpen
Modesty,Humility,andRespect
WorkasaTeam
WorkingWithPeople
FollowYourGut
Lead
Part6:Career
1OpenSource
StartSmall
TakingthePlunge
Documentation
TakingItSeriously
GivingUpControl
TakingResponsibility
2YouAretheConstantinYourCareer
PuttingYourselfFirst
SettingGoals
LearningRequiresanInvestment
TakeCareofYourself
LookingBack
3BuildThatApplication
BuildandShip
ShowWhatYouCan
StayAhead
RinseandRepeat
BuildThatApplication
4ProtectYourProductivity
WorkingFromHome
WorkingInanOffice
MinimizingInterruptions
FindaQuietPlace
DealWithIt
5BuildingYourPortfolio
ScratchanItch
SettingGoals
LearntheBasics
ButStartCreating
6HowBadlyDoYouWantIt
Contribute
Build
Maintain
PlanandManage
GainExperience
BeYourself
HowBadlyDoYouWantIt
WhatAboutYou
7FreelancingandSubcontracting
FreelancingandSubcontracting
BeingPicky
FiringClients
Part7:Products
1Ship,Ship,Ship
It’sHard
HowtoShipConsistently
InternalDeadlines
RemoveFrictionandClutter
2TalktoYourCustomers
SolveaProblem
GroundZero
IsThisforYou
ButIt’sFantastic
ARecipeforSuccess
3WhatIsStoppingYouFromShipping
WhyIsThisImportant
StartSmall
RemoveClutter
4MotivationWillGetYouOnlyHalfway
MotivationWon’tCutIt
RunningaMarathon
PullingthePlug
StartandPersevere
ChallengeYourself
5HowtoMakeaLivingasaMobileDeveloper
PaidUpFront
Freemium
Advertising
In-AppPurchases
Subscriptions
Donations
FindingtheRightBusinessModel
ExperimentButBeSmart
Evolution
Part8:You
1BeingandStayingProductive
MaintainingFocus
ProtectYourProductivity
DistractionIsAddictive
TakeCareofYourself
2StopLookingfortheSilverBullet
AnExample
InvestigateandTest
StopLookingfortheSilverBullet
3YouAreNotanImposter
WhatIsIt
WhyDoIBringThisUp
CuringImposterExperience
TalkAboutIt
It’sCommon
Don’tBelieveEverythingYouRead
Don’tLetItAffectYou
SuccessThroughFailure
Part9:Learning
1ChooseYourTeacherWisely
InformationOverload
WhotoTrust
Focus,Focus,Focus
NeverStopLearning
2TakingaShortcut
Internship
FreelancingandSubcontracting
Learn,Learn,Learn
Build,Build,Build
ChooseWisely
3SomeThingsAreHard
CutYourselfSomeSlack
4LearntheRules,ThenBreakThem
Examples
GrowingasaDeveloper
CreatingSomethingBetter
Welcome
Thetitleofmybook,TheMissingManualforSwiftDevelopment,
accuratelydescribeswhatIhaveinstoreforyou.It’stheguideIwishI
hadwhenIstartedoutasasoftwaredevelopersyearsandyearsago.
TheMissingManualforSwiftDevelopmentisasummaryofwhatI’ve
learnedovertheyearsbuildingsoftwareforApple’secosystem.Manyof
thelessonsinmybookIlearnedfromexpertsintheirfieldand,
unfortunately,justasmanyIlearnedthehardway.Ihopethatsomeof
thetopicsinthisbookcanhelpyouonyourwaytobecomeremarkablein
whatyoudo.That’syourgoal.Isitnot?
WritingafewlinesofSwiftissurprisinglyeasy.Onceyoustarttodig
deeper,though,youdiscoverthatbuildinganapplicationforApple’s
ecosystemismorechallengingthanitseems.TheMissingManualfor
SwiftDevelopmentoutlinesthechallengesyoufacealongyourjourney
andhowtoovercomethem.
SomeofthemoreobvioustopicsIcoverincludedependency
management,sourcecontrol,codereviews,continuousintegration,style
guides,workinginateam,tooling,projectorganizationand
documentation,andreleasestrategies.
ThetopicsIfoundmostinterestingtowriteabout,however,aremore
meta,suchaswhentobreaktherules,freelancingandsubcontracting,
stayingproductiveasadeveloper,shippingprojects,leavingyourcomfort
zone,anddealingwithchallengingproblems.
Mybookdoesn’tincludemanycodesnippetsorsampleprojects.The
goalofthisbookistoprovideinsightsandanswerstoquestionsthatare
oftenoverlookedorignored.
TheMissingManualforSwiftDevelopmentisforeverytypeof
developer,butitprimarilyfocusesonSwiftandCocoadevelopment.If
you’redevelopingforApple’secosystem,thenyou’llfindalotofuseful
information,regardlessofyourexperience.
Thereareveryfewshortcutsinsoftwaredevelopment.Youpayaprice
formostoftheshortcutsyoureadabout,onewayoranother.Butthere
areahandfulofshortcutsthatcanspeedupyourlearningandyour
career.Apropereducationisoneofthem.
Ihopethatmybookhelpsyouinsomeway,bigorsmall.Ifitdoes,then
letmeknow.I’dlovetohearfromyou.
Enjoy,
Bart
PART1:FOUNDATION
1YourFoundation
DevelopersthatcometoApple’splatformshavemanydifferent
backgrounds,andsomeofusarebetterpreparedthanothers.
Regardlessofyourbackground,though,youcanmakesurethatyou’rea
goodfitforApple’secosystembyinvestinginyourfoundation.That’sthe
subjectofthischapter.
Thismaysoundboringatfirst,andforsomeitisboring,butit’sessential
ifyouplantocreaterobust,scalableapplicationsandifyouwanttohave
alongcareerinthemobilespace.
There’saslewofreasonswhydevelopersaredrawntoApple’s
ecosystem.Manyofusmakethejumpbecauseoftheshinystuff.ARKit
andCoreMLaregoodexamplesofwhatIliketorefertoasshinystuff.
Bothareamazingtechnologies,andI’msureyou’veseenstunning
examplesofdeveloperstakingadvantageofARKit.ARKitandCoreML
arethecherriesonthecake.Andthecakeisyourfoundation.Without
thecake,therearenocherries.
WhatIsYourFoundation
Thefoundationiswhathappenstointerestmemost.Itisn’tascompelling
orvisuallystunningasARKit,butit’sessentialforeverysingle
application.Notonlyisthatwhyit’ssoimportant,butthat’salsowhyit’s
worthinvestingtimeinyourfoundation.Itpaysdividendsforalongtime.
Let’sstartwiththelanguage.
Swift
AsaSwiftdeveloper,thefirstcomponentofyourfoundationshouldbe
thelanguageyouusedayindayout.Swift.Sinceyou’rereadingthis,I’m
goingtoassumethatyoualreadyhaveagoodgraspoftheSwift
languageor,ataminimum,you’vebrowsedTheSwiftProgramming
Languageandyou’vewrittenahandfuloflinesinaplayground.
I’msureIdon’tneedtoconvinceyouoftheimportanceofknowingand
understandingtheSwiftlanguage.Howareyougoingtowriteafantastic
novelifyoudon’tmasterthelanguagethenoveliswrittenin?Whywould
thisbeanydifferentforsoftwaredevelopment?
Butthisdoesn’tmeanyouneedtospenddays,weeks,ormonths
learningtheSwiftlanguage.Irecommendadifferentapproachthat’s
morefunandmorepractical.Idon’tlikespendinghoursordayslearning
anewlibrary,framework,orAPI.IlearnbestbyapplyingwhatIreadand
learn.ThesameistruefortheSwiftlanguage.
Startwiththebasicsanduseit.Youcanpickupthebasicsofany
languageinnotime.But,aswithanylanguage,youonlygetwhatyou’ve
learnedbyapplyingit.ThatmeanswritingSwift.YoucanuseSwiftina
playgroundorstartwithasimpleCocoaapplication.Appledidafantastic
jobbyintroducingplaygroundsalongsidetheunveilingoftheSwift
language.Usethem.LaunchXcode,createaplayground,andplaywith
Swift.
Optionals
Manydeveloperswillgothroughaphaseinwhichtheystrugglewiththe
language.That’sfine.Letyourselfbefrustratedforawhile.It’snatural,
anditmeansthatyou’renoticingaspectsofSwiftthatarecoretothe
language.Beskepticalandaskquestions.
Basedonconversationswithstudentsandreaders,optionalsareoneof
themostcommonobstaclesdevelopersneedtoovercome.Igenuinely
loveoptionals,butItoowasfrustratedwhentheyfirstcrossedmypath.
Thiswasn’tsurprisingconsideringmybackgroundinObjective-C.Asyou
probablyknow,Objective-Cisn’tasstrictaboutnilpointers.Dealingwith
nilisanentirelydifferentstorywhenyou’rewritingSwift.
Ifyou’restillstrugglingwithoptionalsordon’tseehowtheyfitinthe
language,thenIneedtoaskyoutotrustthelanguagefornow.Itwillclick
atsomepoint,butyouneedtoembraceoptionals.Don’tusethe
exclamationmarktoplowyourwaythroughaforestofoptionals.
Optionalsareanintegralpartofthelanguageandanessential
componentofoneofSwift’skeyfeatures,safety.
StepUpYourGame
Themoreyouusethelanguage,themoreyoustarttoappreciateit.What
ItendtodoisgraduallyaddmorecomplexitytothecodeIwrite.Learn
aboutvaluetypesandreferencetypes.Discoverwhatprotocolsareand
whythey’reuseful.Youmaywanttoexploregenericsatsomepoint.Take
acloselookatenumerationsandfindoutwhythey’resomuchmore
powerfulthantheirObjective-Ccounterparts.
IfyouthinkyouknowtheSwiftlanguage,thenIrecommendtaking
anotherlookatTheSwiftProgrammingLanguage.EverytimeIread
Apple’sguide,Ilearnsomethingnew.Mostofthetimes,Icandirectly
applyittothecodeIwritedaytoday.Iloveit.Swiftwasdesignedtobe
moreexpressive,anditfeelsricherthanObjective-C.That’ssomething
youcanandshouldtakeadvantageofinthecodeyouwrite.
Concepts
EvenifyoustilluseObjective-C,thereareconceptsthatyouneedto
knowabout,regardlessofthelanguageyouuse.Theseconceptsare
oftenscarytonewdevelopers,suchasmemorymanagement,
asynchronousprogramming,andgrandcentraldispatch.Theseare
conceptsandtechnologiesthatareoftenignoredoroverlooked.
Unfortunately,thisleadstomemoryleaks,crashes,andalotof
frustration.
Thisfrustrationoftenleavesabadtasteinyourmouth,anditcaneven
affectyourfondnessforthelanguageandtheplatform.There’snothing
asfrustratingasdebugginganissuecausedbysomethingyoudon’tfully
understand.Ithappenedtomemanytimes,anditsimplyisn’tfun.Itpays
offtoinvesttimeinlearningtheinsandoutsofthesefundamentals.Italk
moreaboutthislaterinthebook.
SDK
YoucandoquiteabitwiththeSwiftlanguagethatdoesn’tinvolveApple.
ThelanguageisavailableonLinux,andthereareseveralframeworks
thatyoucanusetobuildwebAPIspoweredbySwift.Therearealsoa
numberoftoolsandlibrariesyoucanusetowritescriptsusingSwift,
suchasMarathon,Rainbow,andCommander.
ButmostofususeSwifttopowermobileordesktopapplications,which
meansweneedtobecomefamiliarwithabunchoftools,frameworks,
andlibraries.ThemostcommononesareFoundation,thebreadand
butterofeveryCocoadeveloper,UIKitandAppKit,andseveralother
ones,suchasCoreData,AVFoundation,CloudKit,andHealthKit.The
timeyouspendexploringandlearningabouttheseframeworksand
librariesistimewellspent.
DesignPatterns
Therearedozensanddozensofdesignpatternsyoucanpickand
choosefromandahandfulofthesedesignpatternsareusedbythe
frameworksandlibrariesyouuseonadailybasis.Ataminimum,you
needtoknowaboutandbecomefamiliarwiththesefundamentaldesign
patterns.Letmegiveyouaquickoverviewofthemostimportantones.
Laterinthisbook,Izoominonafewofthesedesignpatterns.
Model-View-Controller
Thefirstdesignpatternyouinevitablycomeintocontactwithwhenyou
createyourfirstprojectinXcodeistheModel-View-Controllerpattern.
It’sthispatternthatpowersmostCocoaapplications.Ifyou’vebeen
readingCocoacastsforawhile,thenyouknowthatI’mnotaravingfanof
thisdesignpattern.Itfallsshortinanumberofways,andImostlyuse
theModel-View-ViewModelpatterninstead.
TheModel-View-Controllerpatterniseasytopickup,andit’sagoodfit
forbuildingCocoaapplications.Apple’sSDKsareimpregnatedwiththis
patternandmostofushaveusedtheModel-View-Controllerpatternfor
yearsandyears,andnotonlyforbuildingCocoaapplications.It’sa
widelyused,versatiledesignpatternthathasearneditsstripesover
severaldecades.
Delegation
AnotherverycommonpatternyouencounterinApple’sframeworksand
librariesisdelegation.Theconceptissimple,anditpromotesloose
couplingandcodereusability.Ifyou’veusedtableviewsinyour
application,thenyou’realreadyfamiliarwithdelegation.Atableviewisn’t
responsibleforrespondingtouserinteraction.Itdelegatesthistasktoa
delegateobject.Whenausertapsarowinthetableview,thetableview
notifiesitsdelegateaboutthisevent.It’suptothedelegateobject,aview
controller,forexample,todecidehowtheapplicationshouldrespond.
Thedatasourcepatternissimilar.It’susedtopopulateatableviewwith
data.Atableviewisaprettydumbobject.That’sagoodthingbecauseit
promotesreusability.Itasksitsdatasourcewhatdataitneedstopresent
totheuser.Thetableviewonlyknowshowtopresentthedatait’sgiven
byitsdatasource.
Notifications
Whiledelegationisagoodfitforobjectsthathaveaone-to-one
relationship,notificationsareidealfordistributingmessagestooneor
moreunrelatedobjects.Knowandunderstandwhatthedifferencesare.
Delegationandnotificationsaren’tinterchangeabledesignpatterns.
Likedelegation,notificationsareverycommoninApple’sframeworks
andlibraries.They’reanessentialingredientofeveryCocoaapplication.
KVCandKVO
Key-valuecodingandkey-valueobservingarerelatedconceptsthat
powertheCocoaframeworks.Unfortunately,they’realmostalways
overlookedbydevelopersnewtoCocoa.Forthatreason,Ispendsome
extratimediscussingtheseconceptslaterinthebook.Makesureyou
don’tskipKVCandKVOifyou’renotquitesurewhattheyare.
Xcode
Oneofthefirsttasksyouneedtotakecareofifyoudecidetobuilda
Cocoaapplicationisdownloading,installing,andlaunchingXcode.
DevelopersrarelytakethetimetolearntheinsandoutsofApple’s
powerfulIDE(IntegratedDevelopmentEnvironment).Spendsometime
exploringthebasicsofXcode.Therearemany,manytips,tricks,and
featuresyouonlypickupafterusingXcodeforawhile,butit’s
neverthelessimportanttolearnthebasics.
ThereIsNoClearPath
Weliveintimeswherewe’rebombardedwithinformation.Ifyou’re
learninganewtechnology,framework,ortool,youonlyneedtoentera
fewwordsintoGoogle,andyou’representedwithdozensifnothundreds
ofresources,manyofthemfree.Theproblemisthatmostofusstruggle
withthisabundanceofinformation.Whichresourceshouldwechoose?
Howdoweseparatethegoodfromthebad?ShouldIlearnsomething
elsefirst?
Themobilespaceisevolvingatsucharapidpacethatmanyofusare
scramblingtokeepup.Tobehonest,Idon’tfeelthat.Thereasonis
simple.Iinvestinmyfoundation,andthatcontinuestopaydividends.
Learninganewframeworkwithasolidfoundationtorelyonismuch
easier.Ican’trepeatthisenough,investinyourfoundation.Every.Single.
Day.
Onceyouhavethatfoundation,everythingautomaticallybecomeseasier.
You’llnoticethatthere’snothingyoucannotmaster.Apple’s
documentationnolongerlooksmysterious.Itstartstomakesense.
Focus
WhenApplereleasedtheiPhonein2007,wedidn’thaveanSDKtowork
with.Themoreexperienceddevelopersamongusreverseengineered
theoperatingsystemandbuiltapplicationsforthefirstiPhone.Tenyears
later,Applehasgivendevelopersaccesstoarichecosystemwiththe
toolsweneedtobuildamazingsoftware.AsaCocoadeveloper,youcan
buildsoftwareforyourcomputer,yourphone,yourtablet,yourwatch,
andevenforyourtelevision.Theseareamazingtimes.But,again,it’s
easytobeoverwhelmed.Focusisimportant.
IknowseveraldevelopersthatbuildsoftwareforbothApple’sand
Google’secosystems.Whilethismayseemappealing,itisn’tsomethingI
recommend.It’sverychallengingtostayuptodateaboutoneplatformlet
alonetwo.Therecertainlyareadvantagestothisapproach,butit’smore
importantthanevertospecialize.
Yourattentionisavaluableasset,andIrecommendtofocus,focus
aggressively.IfyouremployerexpectsyoutobeuptodateoniOS,tvOS,
macOS,andwatchOS,thenthey’reexpectingtoomuch.Chancesare
thatthey’renottechnicalordon’tknowmuchaboutApple’secosystem.
Gonearethedaysthatyouknoweveryframeworkandlibraryinsideout.
IchoosetofocusonApple’secosystem,withastrongemphasisoniOS.I
alsobuildtvOSandwatchOSapplications,andtheoccasionalmacOS
application,butthosearen’tmymainfocus.Thisfocusallowsmetobuild
robust,performantapplications.
Appleappliesthatsamefocus,oritusedto.ChoosinganewApple
computerusedtobeasimpletaskbecauseyouonlyhadahandfulof
options.Whilethat’snolongertrue,itemphasizesthepoweroffocusand
simplicity.Andit’sthereasonIchoosetobuildacareeronApple’s
ecosystem.
WhichPathtoFollow
Themostcommonquestion,orfrustration,Ihearfromdevelopersnewto
CocoaandSwiftis“WhereshouldIstart?”There’ssomuchtolearn,or
that’showitseems.Youhavethelanguage,thetools,theframeworks,
theAppStore.Theredoesn’tappeartobeaclearpath;there’sonlyalot
ofinformation.PlatformslikeStackOverflowarefantastic,butit’s
importanttolearntodigestend-to-endinformation.
Theredoesn’tseemtobeaclearpath,there’sonlyalotof
information.
Italkmoreaboutthislaterinthebook,butIneedtorepeatmyselfby
sayingthatfocusisessential.Ifyou’restartingoutasadeveloper,then
makesureyou’renotjumpingfromtopictotopic.Chooseaprovenpath.
AresourceIoftenrecommendtodevelopersisthebookaboutCocoa
developmentpublishedbyBigNerdRanch.It’sthisbookbyAaron
HillegassthattaughtmeCocoadevelopment.Aaronandhisteamhave
decadesofexperienceteachingpeopleCocoadevelopment.
Therearethreereasonsforchoosingatrustedsource.First,youlearn
thefundamentals.Second,youcanignoretheabundanceofinformation
andfocus.Third,you’resureyou’relearningthingstherightway.Big
NerdRanch,forexample,hasbeenaroundforalmosttwodecades,an
eternityinthetechnologyindustry.
Focus,focus,focus.That’swhat’sgoingtokeepyousaneintoday’s
world.That’soneofthefirstthingsIteachthestudentsIcoach.It’sfineto
ignoremostofwhatyoureadandfocusononethingatatime.Your
productivitywillskyrocket,andyourconfidencewillfollowsuit.
2WheretoStart
Inthischapter,IdescribethepathIrecommendtopeoplethatarenewto
CocoaandSwiftdevelopment.Ifyou’renewtoprogramming,thenI
recommendtakingabasiccourseonprogrammingfirst.
ThepathIpresentinthischapterrequiresyoutolearnacollectionof
skills,patterns,andparadigms.Rememberfromthepreviouschapter
thatit’sessentialthatyouremainfocused.It’stemptingtojumpfromtopic
totopicbecausethere’salotyouneedtolearn.
SettingYourselfUpforSuccess
BeforeweexplorethepathtolearnCocoaandSwiftdevelopment,it’s
importanttounderstandthatittakestime.Notonlydoesittaketimeto
learnthevarioustopicsIcoverinthischapter,ittakestimetolet
everythingsinkin.
Youwillencounterconceptsthatonlyclickaday,aweek,oramonth
afteryou’vereadabouttheminabookorseenthemexplainedina
video.Don’tletyourselfbecomefrustratedifyoudon’tgeteverything
rightaway.That’sperfectlynormal.
Don’tletyourselfbecomefrustratedifyoudon’tgeteverythingright
away.That’sperfectlynormal.
TheSwiftlanguageiseasytopickup,butthefinerdetailsandmore
advancedfeaturesaremorechallenging.TheCocoaSDKwithitsmany
frameworksandAPIscanseemdaunting,butifyouknowwhattofocus
onwhenandunderstandwhyyou’relearningsomething,thenthepieces
ofthepuzzlestarttofittogether,showingyouthebiggerpicture.
APathWithoutDistractions
ThepathIalmostalwaysrecommendtostudentsnewtoCocoaand
Swiftdevelopmentshowsyouhowtobuildanapplicationfromstartto
finish.Istronglybelievethateverydeveloperneedstobecomefamiliar
witheverystepofbuildinganddeployinganapplication.
Ifyoudecidetoworkatalargercompanyasanemployee,youprobably
won’thavetodealwitheverystepofthisprocess.However,knowing
aboutandunderstandingthestepsinvolvedtobuildanapplicationisan
integralpartofyourfoundation.It’sessentialthatyouunderstandevery
stepoftheprocess,andthere’snobetterwaytolearnthestepsthanto
gothroughtheprocessyourself.
Step1:LearntheLanguage
Thefirststepisthemostobviousone,learningtheSwiftlanguage.
Learningthelanguageandtheframeworksatthesametimeisn’t
somethingIrecommend,unlessyou’realreadyfamiliarwithObjective-C.
That’swhyIalwaysrecommendtolearnthebasicsoftheSwiftlanguage
first.TheSwiftProgrammingLanguageisaverygoodstartingpointand
it’swhatIrecommendyouread.Ifyou’renewtoSwiftandObjective-C,I
recommendskippingASwiftTourbecauseitwillconfuseyoumorethan
itwillteachyou.
TheSwiftProgrammingLanguageisavailablefromtheSwiftwebsite
andyoucandownloaditforfreefromiTunes.Butdon’ttakethebookand
readitfromcovertocover.Takeoutyourcomputer,installXcode,and
writecode.Leteverythingsinkinbyapplyingwhatyoulearn.Youonly
learnthelanguagebywritingit,usingitssyntax,andbecomingfamiliar
withthevariousconcepts.Write,write,write.
Thisalsomeansit’stimetoinstallXcode.VisittheAppleDeveloper
websiteanddownloadacopyofXcode.YoucanalsodownloadXcode
fromtheMacAppStore.FireupXcode,createaplayground,andwrite
codeasyoureadTheSwiftProgrammingLanguage.Thisisoneofthe
bestapproachestolearnthelanguage.
IbrowseTheSwiftProgrammingLanguageseveraltimesaweek.
Becauseitcontainssomuchinformation,it’svirtuallyimpossibletolearn
andunderstandeverythingaboutthelanguageafteroneread.
Whenisittimetocontinuetothenextstep?You’rereadytomoveonif
youunderstandthebasicsofthelanguage.Howdoyouknowifyoudo?
Itmeansthatyouunderstandandcanapplythefollowingconceptsand
paradigms.
Youunderstandthedifferencebetweenvariablesandconstants,and
youknowwhenit’sappropriatetousewhich.
Youknowwhatoptionalsare,whythey’reintegraltothelanguage,
andyoualsounderstandwhattheexclamationmarkstandsfor.You
alsoneedtounderstandoptionalchaining,safelyunwrapping,and
themeaningofnil.
Youunderstandandcanusestrings,arrays,dictionaries,andsets.
Youalsoknowaboutobjectliteralsandhowtocreatethem.
Youcanusecontrolflowtoaddcomplexitytothecodeyouwrite.
Youunderstandthebasicsoffunctionsandclosures,andyoucan
usethem.
Youknowwhatclasses,structures,andenumerationsareandwhat
setsthemapart.
Youunderstandwhatreferencetypesandvaluetypesare,youknow
theprosandconsofeach,andyougetwhatsetsthemapart.
Youunderstandthebasicsofprotocols.Youcandefineaprotocol
andcreateatypethatconformstothatprotocol.
Youalsoknowaboutextensionsandhowtousethem.
You’lllearnalotmorealongtheway,suchaserrorhandling,inheritance,
propertiesandmethods.Youshouldnowbereadytobuildyourfirst
application.
Step2:BuildanApplication
OnceyouhaveabasicunderstandingoftheSwiftlanguage,it’stimeto
startbuildingsomethingthatrunsonaniPhoneoraniPad.Eventhough
playgroundsarefantastictolearnSwift,youstartedthisjourneytobuild
applications.Oneofthemostexcitingmomentsofmyjourneyasa
softwaredeveloperwasthedayIranmyfirstapplicationonaphysical
device.
Iencourageyoutocreateyourfirstapplicationassoonasyouhavea
goodgraspofthelanguage.Theapplicationwon’tdomuch,butitputs
thelanguageandtheframeworkstogether.Itshouldalsogetyouexcited
aboutwhat’stocome.There’snothingasexcitingasrunningyourvery
firstapplicationonyourphoneortablet.
Step3:ExploretheSDK
Theapplicationyoubuildinthepreviousstepwon’tmakeadentinthe
universe,butitwhetsyourappetite.It’stimetobecomefamiliarwiththe
frameworksandtoolsyouneedtobuildrobustapplications,which
includeslearningabouttheFoundationframework,theSwiftstandard
library,andUIKit(iOS)orAppKit(macOS).Agoodbookorcourseon
Cocoadevelopmentcoverstheimportantaspectsoftheseframeworks
andtools.
ForiOSdevelopers,it’sessentialtobefamiliarwithviewsandview
controllers.Understandhowaviewrelatestoaviewcontrollerandhow
bothfitintotheModel-View-Controllerpattern.Whileyoucouldcreatethe
userinterfaceincode,Idon’trecommendthis.Applepushesdevelopers
tostoryboardsandthat’ssomethingyouneedtobecomefamiliarwith.
Butdon’tignoreXIBfiles.They’reafinealternativeifyoudon’tlike
workingwithstoryboards.
AutoLayoutisalayoutenginethatmakesbuildinguserinterfaceseasier.
Youneedtobecomefamiliarwithconstraints,layoutguides,andview
hierarchies.Don’tskipthisstep.Manydevelopersdoandpaytheprice
later.
AlmosteveryiOSapplicationincludesatablevieworacollectionview.
Asyoulearnhowtheywork,youalsopickupthedelegationanddata
sourcepatterns,whichwediscussedinthepreviouschapter.
NavigationcontrollersareanotheressentialingredientofmostiOS
applications.Itmaybechallengingtowrapyourheadaroundthe
concept,butonceitclicksyou’llfindthemeasytouse.Thesameapplies
totabbarcontrollers.
Storingdataisataskofmostapplications.Therearemanysolutions
available.ThesimplestsolutionprovidedbytheCocoaSDKisthe
defaultssystem.Thedefaultssystemisnothingmorethanakey-value
store.You’llfindyourselfusingitveryoften.Ialsorecommendlearning
aboutmoreadvancedtypesofdatapersistence,suchasstoringdataina
fileondiskorinadatabase.
Laterinthischapter,Iemphasizehowimportantitistochoosea
resourcethatteachesyouthesefundamentals.Itpaystoinvestinagood
bookorcourse.You’reinvestinginyourfoundation.
Step4:MoreChallenges
Afteryouunderstandthefundamentalscoveredinthepreviousstep,it’s
timeforaslightdetourtolearnaboutafewmoreadvanced,yetessential,
aspects,includingmemorymanagement,asynchronousprogramming,
anddatapersistence.Thesearemoreadvancedtopics,butyouneedto
learnthemasthey’reaningredientofeveryapplicationthathasabitof
complexitytoit.
Irepeat,pickagoodbookorcoursetolearntheseconcepts.It’llmake
yourjourneythatmucheasier.Memorymanagementandmultithreading
arenoteasytograspforaninexperienceddeveloper.Butbelieveme
whenIsaythatyoucandothis.
Step5:BuildThatApplication
It’stimetoaccelerateyourlearningbybuildinganapplication.Thisstep
isthecherryonthecake.YoustartwithanemptyXcodetemplateand
starttranslatingyourideatoafunctionalproduct.Itdoesn’tmatterwhat
ideayouhavebutitneedstobechallenging.
Itdoesn’tneedtobeunique,though.Agoodexampleisanapplicationto
takenotesorviewtheweather.Thegoalistoapplywhatyouhave
learnedintheprevioussteps.
Beprepared.Youwillrunintoproblemsandyouwillneedtolearnsome
moretofinishtheproject.Itwilltakeyoudaysorweekstocompletethis
step.Ihopethisdoesn’tscareyoubecausethat’stherealityofsoftware
development.
Ifyou’readeveloper,thenyou’llneedtocontinuelearningonadaily
basis.Thisisinevitable,especiallyinaspacethatmovesabreakneck
speed.
Step6:WhatAboutTesting
Testingisoftenskippedforsomereason.Iftestingwereadifficult
subject,I’dunderstandwhythatis.Butitisn’t.Ifeelit’susuallyskipped
becauseitisn’tacooltopic.Don’tskipthisstep.Testingisn’tashardas
youthink.Laterinthisbook,wecovertestinginabitmoredetail.
Step7:Publish
Ifyourapplicationisreadytobesharedwiththeworld,it’stimetopublish
itonApple’sAppStore.Thisisquitechallengingbecauseyouneedto
useabunchoftoolstopublishyourapplication.Youneedtovisitthe
DeveloperPortal,provisionyourapplication,andprepareyourapplication
iniTunesConnect.Thisisn’trocketscience,butitcanbefrustratingthe
firsttimeyoutrytousethesetools.Don’tworry,though.Youcandothis
too.
ChooseYourTeacherWisely
Whileyoucangothroughthesestepsonyourown,Irecommendthat
youlookforhelp.YoucanlearntheSwiftlanguagebyreadingTheSwift
ProgrammingLanguage.LearningtheCocoaSDKisabitmore
challenging.That’sthestepinwhichmostdeveloperslosetrack.
Pickupabookorcoursethatcoversthefundamentalsinsuchawaythat
youlearneverythingyouneedtobuildasimpleyetfunctionalapplication.
LaterinthisbookItalkabouttheimportanceofchoosingyourteacher.
Makesureyoulearnfromsomeoneyoutrust.Thatsomeoneteachesyou
bestpracticesandtheyalsoshowyouwhichpracticestoavoid.Your
teacherkeepsyousaneandconfidentasyoulearnyourcraft.
IcanrecommendanythingpublishedbyBigNerdRanch,suchasiOS
Programming:TheBigNerdRanchGuide.Thatsaid,therearevarious
booksandcoursesthatareverygood.Don’tpickanybookorcourse.
Makesureyouteamupwithsomeonewhoknowshisorherstuff.
Don’tpickorchooserandomtutorialsyoufindontheweb.Istrongly
recommendchoosingforasolutionthatshowyouthecompletepath.The
resultisalmostalwaysconfusionandfrustrationifyoupickandchoose.
Thisapproachisfineonceyou’venailedthefundamentals.Asa
beginner,though,Irecommendstickingwithaprovensolution.
Ifyouhavemoneytospendandyouwanttospeedupyourlearning,you
canenrollinabootcamptoimmerseyourselfinSwiftdevelopment.The
resultisthatyoulearnalotinaveryshortperiod.
3KnowYourTools
Animportantpartofyourfoundationisknowingthetoolsyouworkwith.
AndthisgoesbeyondjustXcode.Ialwaysencouragedevelopers,
regardlessofthecompanyyouworkfor,toknowabouteveryaspectof
building,testing,andshippingaCocoaapplication.Thischaptercovers
thetoolsyouneedtoknowaboutandbecomefamiliarwith.Let’sstart
withtheworkhorseofeveryCocoadeveloper,Xcode.
Xcode
XcodeisthemostpopularIDEforbuildingCocoaapplications.Thereare
alternatives,suchasJetBrains’AppCode,butIwon’tcoverthoseinthis
book.WhileXcodehasservedmewellovertheyears,thereis,andhas
alwaysbeen,roomforimprovement.
Whileit’simportantthatyoubecomefamiliarwithXcode’suserinterface,
it’snotimportanttospendhoursordayslearningtheinsandoutsof
Xcode.Myexperiencehastaughtmethatdevelopersusuallydon’thave
ahardtimegettinguptospeedwithXcode.Thebasicsarethesamefor
mostIDEsandyoulearnaboutthemoreintricatefeaturesofXcodeover
time.
Butthatdoesn’tmeanyoushouldn’tdigabitdeeperfromtimetotime.
Xcodehasaslewofhiddenfeaturesandkeyboardshortcuts.It’sworth
spendinganhourhereandtherereadinguponXcode,watchinga
WWDCsession,orsimplyplayingaroundwithXcode’suserinterface.
I’dliketohighlightafewcomponentsofXcodethatdeservespecial
attentionandthatyouneedtoknowabout.
Documentation
Documentationisadeveloper’sbreadandbutter.Xcode’sbuilt-in
documentationbrowserhasn’talwaysbeengreat.Fortunately,Xcode’s
documentationbrowserreceivedanoverhaulinXcode8and9.Iusedto
useDashtoexploretheCocoaSDK,butI’veswitchedtothebuilt-in
documentationbrowsersinceXcode8.It’snicelystructured,fast,easyto
use,anditsupportstabs.
Youcanbringupthedocumentationbrowserfromwithinthesource
editorbypressingOptionandclickingasymbol.Thisshowsyoua
summaryofthesymbol.Youcanopenthedocumentationbrowserby
clickingoneofthelinksinthepop-upwindow.
Xcode’sDocumentationBrowser
Xcode’sDocumentationBrowser
YoucanalsoopenthedocumentationbrowserbypressingShift+
Command+0orchoosingDeveloperDocumentationfromXcode’s
Windowmenu.
Devices
TheWindowmenualsogivesyouaccesstotheDevicesand
Simulatorswindow.Thisisusefulifyouneedtodownloadthecontainer
ofanapplicationoraddasimulator.
Organizer
Xcode’sOrganizerismorepowerfulthanmanydevelopersknowor
think.Itshowsyoualistofarchives,butitalsoprovideseasyaccessto
crashreports.ThecrashreportsneatlytieintoXcode’ssourceeditor,
whichisveryconvenientfordebuggingfatalissues.
Xcode’sOrganizer
Theorganizeralsoallowsyoutoexportyourapplicationorsenditto
iTunesConnectfortestingordeploymenttoApple’sAppStore.
DeveloperPortal
EventhoughXcodecancommunicatewithApple’sserversonyour
behalf,yousometimesneedtovisitApple’sdeveloperportaltotakecare
ofspecifictasks,suchascreatingacertificateorconfiguringanAppID.
ItusedtobetedioustoworkwiththeDeveloperPortal.Thishasbecome
easierandXcodetakescareofmanytrivialtasks,suchasadding
capabilitiestoanAppIDandgeneratingprovisioningprofiles.
Provisioning
Mostdeveloperscringewhensomeonedropsthewordprovisioning.An
applicationneedstobeprovisionedforittorunonadevice.Thisisa
necessaryevilifyou’redevelopingforApple’secosystem.It’stedious,it
drivesyoumadfromtimetotime,butit’simportantthatyouunderstand
whyit’snecessary,howitworks,andhowyoucanresolvecommon
issues.
Thisisoneofthosetopicsthat’susuallyskippedorignored,thatis,until
thingshitthefan.Youdon’twanttolearnaboutprovisioningthemoment
youneedtodeployahotfixtotheAppStore.Ifyouhavesomedowntime,
spendanhourreadingaboutandlearningtheinsandoutsofapplication
provisioning.You’llbethankfulthatyoudidwhenthingsgohaywire.
Instruments
Xcodeshipswithseveralotherdeveloperstools,includingInstruments.
Instrumentsisoneofthemostunderusedandundervaluedtoolsina
Cocoadeveloper’stoolbox.It’spowerful,versatile,andagreathelpfor
debuggingmorecomplexissues.
WhileInstrumentsisuseful,Iwouldn’tfocusonthistoolfromdayone.In
fact,Iwouldn’tinvestmuchtimeinitinyourfirstyearunlessyouneedit
fordebugging.Therearemoreimportantthingstolearninthefirstyearof
yourjourney.Onceyou’refamiliarwithXcodeandCocoadevelopment,
though,it’scertainlyworthinvestingtimeinexploringInstruments.
CommandLine
Whileit’spossibletocreateCocoaapplicationswithoutknowingathing
aboutthecommandline,I’vealwaysfounditabigassettobefamiliar
with,andnotafraidof,thecommandline.InteractingwithCocoaPodsor
Carthage,forexample,ismostlydonefromthecommandline.Some
developersswearbythecommandlineformanyothertasks,suchas
sourcecontrolandrunningtests.
Thisisn’tsomethingyouneedtoinvesttimeinrightnow,buthavean
openmindabouttheuseofthecommandline.Ifyouhavesometimeto
spare,thenexploreafewtutorialsaboutthecommandlineandhowyou
canuseittoyouradvantage.
ThirdPartyTools
EventhoughXcodeworksfineforCocoadevelopment,thereareseveral
toolsthatmakebuildingCocoaapplicationseasierandmoreenjoyable.I
don’thaveanyaffiliationwiththecompaniesthatcreatetheseproducts.
Tower
TowerismyfavoriteGitclientanditgetsbetterwitheveryrelease.Iuse
thecommandlineforsimpleGitoperations,butmostofthetimeIuse
Towertogetthejobdone.It’saperfectfitformyworkflow.
Reveal
YouprobablyknowthatXcodeincludesaviewdebugger,allowingyouto
inspecttheviewhierarchyofaCocoaapplication.Revealisastandalone
applicationthatperformsasimilartask,butitdoesthismuch,much
better.Revealhasbeenaroundforseveralyearsanditalsoincludes
supportfortvOSapplications.
Charles
Charlesisacross-platformapplicationforinspectingnetworktraffic.It
isn’talwayseasytogetitupandrunningwithaphysicaldevice,but,
oncesetup,itworksverywellandcanbealifesaverfordebugging
networkissues.
PaintCode
Writingdrawingcodeistediousandverbose.PaintCodemakesthisa
breeze.PaintCodeisadrawingapplicationthatconvertsyourartwork
intodrawingcodeforseveralplatforms.Itsupportsarangeoflanguages,
includingSwiftandObjective-C.
4AdoptBestPractices
WheneversomeonesignsupforCocoacasts,Iaskthemwhatthey’dlike
toachieveinthenextthree,six,ortwelvemonths.Manydeveloperstell
metheywanttobecomeabetterSwiftdeveloper.Thisisavague
ambitionandIusuallyaskthemwhatthatmeansforthem.Whatdoesit
meantobecomeabetterSwiftdeveloper?
Acommonansweristhattheywanttolearnaboutpatternsandbest
practices.That’saninterestinganswerbecauseitshowsthattheyhave
theambitiontogrowasadeveloperandtheyknowthattheircurrent
codecanusesomeimprovements.
WhatAreBestPractices
Thetermbestpracticesisoverusedinmyopinion.Iprefertousethe
termgoodpractices.WhatIlikeaboutsoftwaredevelopmentisthat
there’srarelyonesolutiontosolveaproblem.Thatalsoimpliesthatthere
arenobestpractices,onlygoodpracticesandhabits.
AppleunveiledSwiftonlythreeyearsago.Unlessyou’reChrisLattner,
thelanguageisstillverynewtous.Manyofusarestilllookingforgood
practicestoadopt.Buthowdoyouspotagoodpractice?Some
developersintuitivelyspotagoodpracticewhentheyseeone.It’softena
solutiontoaproblemthatfeelsright.Itlookselegantand,moreoften
thannot,it’seasytoimplement.
Takedependencyinjectionasanexample.ThisisoneofthepatternsI
teachinmybookLearntheFourSwiftPatternsISwearBy.Eventhough
manydevelopershaveahardtimewrappingtheirheadaroundthe
concept,dependencyinjectioniseasytoadoptandimplement.It’sacure
fortightcouplingandaneffectivesolutiontoridaprojectofsingletons.
Goodpracticesaren’tnecessarilytheeasiestormostconvenient
solutionsyoufind.Haveyouheardaboutthesingletonpattern?This
patterniseasytoadoptandit’sveryconvenienttouseinaproject.But
there’sacaveat.Convenienceissometimesacodesmell.Imentionthis
severaltimesinthebook.Ifsomething’sconvenient,thenyoumayneed
tostepbackandtakeahardlook.
Youshouldn’tavoidconvenience,butyouneedtobecriticalaboutthe
patternsyouuseandthepracticesyouadopt.Evenifyouhavelittle
experience,youneedtoscrutinizewhatyoupickup.Itusuallyonlytakes
ahealthydoseofcommonsensetodistinguishapatternfromananti-
pattern.Becriticalandbehonestwithyourself.
Patterns
Patternsareanimportantaspectofsoftwaredevelopment.They’re
provenrecipestosolveproblems.Theyallowyoutogetworkdone
insteadofreinventingthewheeloverandover.
Laterinthebook,IzoominonseveralpatternsIstronglyrecommend
youtakealookat.Theyhavebecomeanintegralpartofmy
developmentworkflow.Itdoesn’tmeanthatyouneedtouseoradopt
thesepatternsinyourprojects,butitcanbeeye-openingtoexplorethem
andlearnfromthem.
Anti-patterns
ThereareveryfewpatternsIrecommendthatyouavoidaltogether.
They’reoftenreferredtoasanti-patterns.There’sonepatternthatIhave
astrongopinionabout,thesingletonpattern.WhileIdon’tconsiderthe
singletonpatternabadpatternorananti-pattern,Iadvisetouseit
sparingly.Very,verysparingly.
Theprimaryreasonthesingletonpatternhasabadreputationismisuse.
Acommonreasondevelopersadoptthesingletonpatternisconvenience.
DoyourememberwhatIsaidaboutconvenience?
Youprobablyknowthattheuseofglobalsisananti-patterninmost
programminglanguages.Thesingletonpatterngivesyouglobalaccess
tothesingletonobject.Doesn’tthisstarttosmell?Unfortunately,thisside
effectofthesingletonpatternistheprimaryreasonmanydevelopers
adoptthepattern.Don’tdothat.
GoodPracticesforSwift
AsImentionedearlier,withthereleaseofSwift,manyofusstarted
lookingforandreadingaboutgoodpractices.Theyweredifficulttofindat
first,but,asthelanguageevolved,it’sclearwhatyoushouldand
shouldn’tdo.
EmbraceOptionals
Forsome,Swiftisalmostsynonymoustooptionals.Forothers,optionals
aresynonymoustofrustration.Optionalsareanessentialaspectof
Swift’sobsessionwithsafety.Andthat’sagoodthing.Theabilitytosend
messagestonilinObjective-Cisconvenient,butit’sheavilymisused.
It’sveryoftenaneasywayoutfordevelopers.
Swiftputsastoptothis.Thelanguageisveryclearaboutthemeaningof
nil,theabsenceofavalue,andit’suptoyoutodealwithit.Plainand
simple.
DevelopersnewtoSwiftoftentakerefugetotheexclamationmark.This
isn’tsomethingIrecommend.Infact,asImentionelsewhereinthebook,
Iseemostusesoftheexclamationasananti-pattern.Theexclamation
markisanecessaryelementoftheSwiftlanguage,but,aswithevery
invention,it’softenmisused.
LearntheLanguage
ThemostcommonreasondevelopersstrugglewithSwiftisbecausethey
don’tknowthelanguageyet.There’snothingwrongwiththatsincemany
ofusarestilllearning.However,wheneverIfindmyselfcursingthe
compilerforyetanothermysteriouserrormessage,Ilookforasolution.
Thelanguageisstillyoung,buttheearlydaysofthelanguage,whenit
wasbarelyusable,areover.
Swift3and4areajoytouseandIdon’tveryoftenfindmyselfstruggling
withthelanguageitself.Ibrowsethelanguageguideorlookfora
solutionontheweb.There’salmostcertainlyasolutionthatfitsyour
currentneed.
That’salsowhyIrecommendinvestinginyoureducation.Iknowthat
workcangetinthewayfromtimetotime,butIstronglyrecommend
allocatingachunkoftimeeverydayoreveryweekdedicatedtolearning
somethingnew.AndIdon’tmeanlearninganewshinyframework,such
asARKit.Investinyourfoundation.Thatdoesn’tsoundasfancyas
ARKit,butitmakesyourjobmorefuninmanysubtleways.
Swift’sCoreIngredients
ThemoreIuseSwift,themoreIfallinlovewiththelanguage.Value
typesareoneoftheaspectsIadoreaboutSwift.Wehavestructsand
enumsinObjective-C,butthey’renotnearlyaspowerfuloreasytouse
astheircounterpartsinSwift.Enumsarefantasticandstructsareagood
fitforawiderangeofproblems.
Valuetypesandreferencetypeseachhavetheirplaceandweneed
referencestypestobuildCocoaapplications.Thenexttimeyoudefinea
class,though,considercreatingastructorenum.Wouldthatalsowork?
Laterinthebook,Igointomoredetailaboutthedifferencesandthe
benefitsofvaluetypesandreferencetypes.Usevaluetypeswhenever
youcanandusereferencetypeswhenitfeelsyouneedthem.Youdon’t
needtochooseoneortheother.Theycomplementoneanotherquite
well.
TheSwiftlanguageiscomposedofasmallnumberofcorevaluesor
coreingredients.Onceyoudiscoverwhattheyare,youbetterunderstand
howthelanguageworksbestandshouldbeused.Ialreadymentioned
valuetypesandoptionals.Laterinthebook,Ialsotalkaboutprotocols
andprotocol-orientedprogramming.
BeCritical
Beingcriticalisaskilleverydeveloperneedstocultivate.Learnfrom
othersandexperiment,butremaincriticalaboutthelessonsyoutake
awayandadopt.Icannotemphasizethisenough.
5Security
Securityisafundamentalaspectofsoftwaredevelopmentandit’s
importanttoknowaboutbestpracticesandcommonpatternsthatcan
helpstrengthenthesecurityoftheprojectsyouworkon.Iwantto
emphasizethatI’mnotasecurityexpert.TherecommendationsIprovide
inthischapterarebasedonmyexperienceandwhatI’velearnedfrom
fellowdevelopers.
MakeItHard
Ioncereadthat,ifsomeonewantstoaccessyourdata,thentheywill
succeed.Howbadlytheywanttoaccessyourdatadetermineswhether
they’llsucceed.Idon’tknowwhetherthisistrue,butItendtoerronthe
sideofsafety.
Whyisthisimportant?Itchangedmyperspectiveonsecurity.It’snaiveto
thinkthatyoucanoutsmartpeoplethataretrainedtofindandextractthe
informationtheyneed.Thatdoesn’tmeanyouneedtobecomplacentor
ignoretheadviceyouread.Itsimplymeansthatyouractionsand
motivationchangeslightly.
Aneffectiveapproachtosecurityistohavethemindsettomakeithard
fortheotherpartytoaccessthedatayou’retryingtoprotect.Inother
words,youaddseverallayersofsecuritytoprotectthedataoftheuser.
Let’sstartwiththebasics.
PlainText
Ifyouhavesomeexperiencedevelopingsoftware,youmostlikelyknow
thatyoushouldn’tstoresensitiveinformationinplaintext.Ever.Don’t
storetheuser’susernameandpasswordintheuserdefaultsdatabase,
forexample.Usethekeychaintoprotectthistypeofsensitive
information.
Thesameappliestonetworking.AppleandGoogleareactivelyforcing
developerstomoveawayfromHTTPanduseSSLbydefault.Apple’s
AppTransportSecurityencouragesdeveloperstobeawareofthe
securityrisksoftheirapplications.Makesurethatyourapplication
communicateswithremoteservicesoverasecureconnection.Thisisn’t
alwayspossibleifyouaren’tincontroloftheremoteservice.Insucha
scenario,it’suptoyoutodecidewhatthenextbestoptionis.
ButSSLmaynotalwaysbesufficient.Yourapplicationisstillsusceptible
to,forexample,man-in-the-middleattacks.Youcanremedythisby
adoptingcertificatepinning,addinganextralayerofsecurity.
ObfuscatingInformation
AcommonquestionIreceiveishowtobesthideorobfuscatesensitive
informationthat’sbundledwithyourapplication.That’sagoodquestion.
Theanswermaydisappointyou,though.AsImentionedearlierinthis
chapter,there’salwaysawayforpeoplewithbadintentionstogetahold
oftheinformationtheyneed.Youneedtoconsiderthesensitivityofthe
informationyou’retryingtoprotect.
Thesameadviceapplies,though.Makeitashardaspossible.But,atthe
sametime,considerthesensitivityoftheinformationyou’reprotecting.
Don’tstoresensitiveinformation,suchasAPIkeys,inyourapplication’s
Info.plist.It’seasytodissectanapplicationyoudownloadedfromthe
AppStoreandinspectthecontentsoftheInfo.plist.
Iusuallystoresensitiveinformationasprivateconstantsina
configurationfile,whichmeansit’scompiledalongsidetheapplication.
Thisdoesn’tmakeitimpossibletoextractthesensitiveinformation,butit
makesitlesstrivial.
FetchingSensitiveInformation
Youcangoonestepfurtherandavoidstoringkeysorcredentialsinthe
applicationitself.Instead,yourapplicationcontactsaremoteserviceand
asksforcredentialseverytimeitneedstocommunicatewiththatservice.
Thisrequiresadedicatedinfrastructureandalotmoreworkupfront,but
itaddsapowerfullayerofsecurity.
Encryption
Encryptionisaneffectivesolutiontoprotecttheuser’sdata.Realm,for
example,hasbuilt-insupportforencryptingthedatastoredinits
database.ForCoreData,however,thisislesstrivial.IhopeApplewill
makethislesscumbersomeinafuturereleaseoftheframework.
Thedatatheuserstoresontheirdeviceisautomaticallyencryptedifthe
deviceisprotectedwithapasswordorTouchID.Onlyyou,theuser,can
unlockthedatastoredonyourdevicebecauseyouholdthekeyto
decryptit,notApple.It’sgreattoseethatApplecontinuestoinvestinthe
privacyandsecurityofitscustomers.Apple’smotivationisabitmore
nuanced,though.
Privacy
Alothasbeenwrittenaboutprivacyandprotectingtheuser’sprivacy.
Unfortunately,manydevelopersdon’trealizethatthisalsomeans
protectingtheuser’sprivacyfromcompaniesthatofferservicestheyuse
dayindayout.Ifyourapplicationusesanalyticsordisplaysads,then
you’reexposingtheuser’spersonalinformationtothecompaniesbehind
theseservices.
IusedtouseFabricforcrashreportingandanalytics,butInolongerdo
forpersonalprojects.Asadeveloper,it’smyresponsibilitytoprotectthe
user’sprivacyandtheyexpectthatfromme.Iunderstandthatmany
developersdon’thavethisluxury,butIstillbelievethatyoushould,ata
minimum,considertheoptionandbeawareoftheinformationyoumay
beexposingtothirdparties.
IfyouincludeathirdpartySDKinyourapplicationandyoudon’thave
accesstothesource,thenhowdoyouknowwhatinformationyou’re
sharingwiththisthirdparty?Youdon’t.That’simportanttokeepinmind.
LoggingandDebugging
Logginginformationtotheconsoleismyfavoritetechniquetodebug
issuesbecauseit’ssimpleandtothepoint.It’satechniquemanyofus
use,butit’salsoapotentialsecurityproblem.Manydevelopersforget
thatprintorlogstatementsalsologinformationtotheconsolein
production.Thiscanbeusefulandintentional,butitcanalsobea
securityissue.
Ihopeyou’renotloggingcredentialsorothersensitiveinformation.Even
fragmentsoftheuser’sdatashouldn’tbeloggedinproduction.Ifyou
needtogeneratelogs,thenIrecommendlookingintoremoteloggingin
combinationwithdataencryption.Avoidthatathirdparty,anythirdparty,
canaccessthelogsyougenerate.
EducatingYourClient
Theroleofadeveloperisoftenreducedtowritingcodeandsolvinga
problem.Notonlyisthisincorrect,Istronglybelieveanydeveloper,
regardlessoftheirexperience,shouldalsoprovideatechnicalserviceto
thepartiestheyworkwith.Whatdoesthatmean?Ifyou’retoldto
implementasolution,thenit’syourresponsibilitytoinformyourclientor
projectmanageraboutanysecurityrisksorproblems.
Ibelieveit’sthetaskofthedevelopertoeducatetheclient.Theclientstill
decideswhathappensandwhatneedstobeimplemented,butthey
shouldataminimumbeawareoftherisksinvolved.I’veimplemented
severalsolutionsIdidn’tagreewith,butItriedtoeducatetheclientabout
alternativesolutionsthatweresafer.
AtonepointIinheritedaprojectinwhichtheuser’scredentialswere
storedintheuserdefaultsdatabase.Eventhoughtherewasnoroomto
refactorthisglaringsecurityhole,Iinformedtheclientabouttheproblem.
Foradeveloper,itcanbefrustratingnothavingfinalsayinsuch
arguments,butthat’showitis.Thisisverydifferentifyoubuildaproduct
businessinwhichyoumakethecalls.
6Don’tIgnoreYourFoundation
It’scommonforcompaniestobuildanin-houseframeworkthatlieson
topofApple’sframeworks.Someframeworksfixbugsandadd
conveniencestoApple’sAPIswhileothersabstractawaylargeportions
ofthenativeframeworks.
It’sclearwhythisisacommonpracticeinlargecompanies,especially
agencies.Youdon’twanttoreinventthewheeleverytimeyouneed,well,
awheel.Butthereareinherentriskinvolvedthatareoftenignoredornot
spokenabout.
UndertheHood
Oneofthemostimportantpiecesofadviceinthisbookissimplebutso
important,investinyourfoundation.Onceyouhaveasolidfoundation,
you’llnoticethatpickingupanewframeworkorsolvingachallenging
problemispossible.It’snolongercomplex,it’ssimplychallenging.
Butifyoulandajobatacompanythatkindlyforcesyoutousethein-
houseframeworkthenyourfoundationiscompromised.I’msureyoucan
buildbeautifulapplicationsthatworkverywell.ButIwonderifyouknow
andunderstandwhat’shappeningunderthehood?Whathappensifyou
movetoanewcompany?Anin-houseframeworkisalmostalwaysthe
company’sintellectualproperty.Doyouknowhowtobuildapplications
withoutit?
Dependencies
Thisbringsustodependencies,atopicIcoverinmoredetaillaterinthe
book.IalwaystrytominimizethenumberofdependenciesIincludeina
project.Everydependencyneedstoearnitswayontotheproject.The
realityisthatmostdon’tmakeitintotheproject’sPodfileorCartfile,
whichisagoodthing.
I’mabigfanoflightweightabstractionsorwrappersaroundframeworks.
CoreDataisafineexample.Idon’tusealibrarytoworkwithCoreData,
butIcreateahandfuloffilesthatincludeconveniencemethodsto
interactwiththeframework.Theseareusuallyspecifictotheproject.
Don’tIgnoretheFundamentals
Investinginthefundamentalsisthebestinvestmentyoucanmakeasa
developer,regardlessofyourexperience.Evenifthecompanyyouwork
forusesanin-houseframework,Iencourageyoutocontinueinvestingin
thefundamentalsoftheplatformyoubuildsoftwarefor.
7RespecttheSDK
Whenyou’renewtoalanguageorframework,itoccasionallyhappens
thatyoufindyourselffightingthelanguageorframework.Wheneveryou
feelthatyou’recodingyourselfinacorner,youshouldstopandtakea
stepback.
TaketheCocoaSDKasanexample.TheengineersatApplearen’t
stupidandtheycarefullycrafttheAPIsofthevariouslibrariesand
frameworks.Ifyoufindyourselfjumpingthroughalotofhoopsto
accomplishasimpletask,thenit’sverylikelythatthere’sabettersolution
you’renotawareof.
KnowYourLimitations
Atthesametime,youshouldbeawareofthelimitationsoftheAPIyou’re
using.Thisisdifficultwhenyou’restartingout.Taketheuserdefaults
systemasanexample.Theuserdefaultsdatabaseismeantforstoring
smallchunksofdata.Thesearestoredaskey-valuepairs.
Whileyoucanstorecomplexobjectgraphsintheuserdefaultsdatabase
(aslongasyousticktothesupportedtypes)don’tbenaiveandstore
megabytesofdataintheuserdefaultsdatabase.It’llprobablywork,butit
won’tbeaperformantorscalablesolution.
RespecttheSDK
AverycommontypeofquestiononStackOverflowis“HowdoI
customize…?”Fillintheblank.MostofthecomponentsoftheUIKit
frameworkareverycustomizable,buttherearetimeswhenyouruninto
limitations.Appledoesitsbesttokeeptheuserinterfaceofapplications
onitsplatformsconsistentandbylimitingthecustomizationofuser
interfacecomponentsittriestodiscouragetoomuchcustomization.
Afewweeksago,Iwaslookingforasolutiontoatrivialproblem.I
wantedtomodifythecoloroftheclearbuttonofatextfield,aninstance
oftheUITextFieldclass.SeveralStackOverflowentriessuggestedto
lookfortheclearbuttonintheviewhierarchyandsettingitstintcolor
propertytothedesiredcolor.Thisisabadideaandacommonexample
ofrunningintothelimitationofanAPI.
TheUITextFieldclasscurrentlydoesn’tsupportmodifyingthetintcolorof
theclearbutton.That’safact.TheonlyoptionIhadwasfilingabugand
moveon.Iendedupimplementingacustomsolutionthatsolvedthe
problem.
I’mstillnotsureiftheinabilitytocustomizethetintcoloroftheclear
buttonisadeliberatechoicemadebyApple,butthetruthisthattheAPI
oftheUITextFieldclassdoesn’tsupportit.ThatmeansthatI’mnotable
tousethedefaultimplementationofUITextFieldifIneedtocustomize
theclearbutton.Youdecideifyouwanttopushthelimits,butyoudoso
atyourownrisk.
Diggingintotheviewhierarchyofthetextfieldmayresolvetheissue
today,anditdidformanydevelopersjudgedbythenumberofupvotes,
butyou’rebuildingahouseonquicksand.ThemomentApplemakes
changestotheinternalsoftheUITextFieldclass,yoursolutionstops
working.Ifyou’relucky,theuserwillseethedefaultclearbutton.Ifyou’re
notsolucky,yourapplicationcrashesorisrejectedbyApple.
9DesignPatterns
Inthischapter,IdiscusssomeofthedesignpatternsIusedayindayout.
They’remybreadandbutter.Ifyou’reaCocoacastsreaderorstudent,
thenyoumayalreadybefamiliarwithsomeofthem.
Model-View-Controller
Ibetyou’realreadyfamiliarwithModel-View-Controller,orMVCfor
short.TheModel-View-Controllerpatternisawidelyuseddesignpattern
forarchitectingsoftwareapplications.It’sbeenaroundforseveral
decadesandmadeitswaytomanylanguages,frameworks,and
libraries.
CocoaapplicationsarecenteredaroundtheModel-View-Controller
pattern,andmanyofApple’sframeworksmakeheavyuseofMVC.It’s
thereforeimportantthatyouknowwhatitis,whyit’sapopularchoiceto
architectsoftwareapplications,and,let’sbehonest,whereitfallsshort.
WhatIsMVC
Asthenamesuggests,theModel-View-Controllerpatternbreaksan
applicationupintothreecomponentsorlayers,Model,View,and
Controller.
Model
Themodellayerisresponsibleforthebusinesslogicoftheapplication.It
managestheapplicationstate,whichalsoincludesreadingandwriting
data,persistingapplicationstate,anditmayevenincludetasksrelatedto
datamanagement,suchasnetworkinganddatavalidation.
TheMInMVC
View
Theviewlayerhastwoimportanttasks,presentingdatatotheuserand
handlinguserinteraction.AcoreprincipleoftheMVCpatternistheview
layer’signorancewithrespecttothemodellayer.Viewsaredumb
objects.Theyonlyknowhowtopresentdatatotheuserandtheydon’t
knoworunderstandwhatthey’representing.Thismakesthemflexible
andeasytoreuse.
TheVInMVC
Controller
Theviewlayerandthemodellayeraregluedtogetherbyoneormore
controllers.InaniOSapplication,thatglueisaviewcontroller,an
instanceoftheUIViewControllerclassorasubclassthereof.InamacOS
application,thatglueisawindowcontroller,aninstanceofthe
NSWindowControllerclassorasubclassthereof.
TheCInMVC
Acontrollerknowsabouttheviewlayeraswellasthemodellayer.This
oftenresultsintightcoupling,makingcontrollerstheleastreusable
componentsofanapplicationbasedontheModel-View-Controller
pattern.Theviewandmodellayersdon’tknowaboutthecontroller.The
controllerownstheviewsandthemodelsitinteractswith.
Model-View-ControllerinaNutshell
Advantages
TheModel-View-Controllerpatternhasearneditsstripesoverseveral
decadesandthereareseveralreasonswhyit’ssuchapopulardesign
pattern.
SeparationofConcerns
ThemostobviousadvantageoftheModel-View-Controllerpatternisa
clearseparationofconcerns.EachlayeroftheModel-View-Controller
patternisresponsibleforaclearlydefinedaspectoftheapplication.In
mostapplications,there’snoconfusionaboutwhatbelongsintheview
layerandwhatbelongsinthemodellayer.
Whatgoesintocontrollersisoftenlessclear.Theresultisthatcontrollers
arefrequentlyusedforeverythingthatdoesn’tclearlybelongtotheview
layerorthemodellayer.
Reusability
Whilecontrollersareoftennotreusable,viewandmodelobjectsare
mostlyeasytoreuse.IftheModel-View-Controllerpatterniscorrectly
implemented,theviewlayerandthemodellayershouldbecomposedof
reusablecomponents.
Problems
Ifyou’vespentanyamountoftimereadingbooksortutorialsaboutiOS
ormacOSdevelopment,thenyou’veprobablycomeacrosspeople
complainingabouttheModel-View-Controllerpattern.Whyisthat?
What’swrongwiththeModel-View-Controllerpattern?
Aclearseparationofconcernsisgreat.Itmakesyourlifeasadeveloper
easier.Projectsareeasiertoarchitectandstructure.That’sonlypartof
thestory,though.Muchofthecodeyouwritedoesn’tbelongtotheview
layerorthemodellayer.Noproblem.Dumpitinthecontroller.Problem
solved?Notreally.
AnExample
Dataformattingisacommontask.Imaginethatyou’redevelopingan
invoicingapplication.Eachinvoicehasacreationdate.Dependingonthe
localeoftheuser,thedateofaninvoiceneedstobeformatteddifferently.
AnExample
Thecreationdateofaninvoiceisstoredinthemodellayerandtheview
displaystheformatteddate.That’sobvious.Butwho’sresponsiblefor
formattingthedate?Themodel?Maybe.Theview?Rememberthatthe
viewshouldn’tneedtounderstandwhatit’spresentingtotheuser.But
whyshouldthemodelberesponsibleforataskrelatedtotheuser
interface?
Waitaminute.Whataboutourgoodoldcontroller?Sure.Dumpitinthe
controller.Afterthousandsoflinesofcode,youendupwithabunchof
overweightcontrollers,readytoburstandimpossibletotest.Isn’tMVC
thebestthingever?
HowCanWeSolveThis?
Inrecentyears,anotherpatternhasbeengainingtractionintheCocoa
community.It’scommonlyreferredtoastheModel-View-ViewModel
pattern,MVVMforshort.TheoriginsoftheMVVMpatternleadbackto
Microsoft’s.NETframeworkanditcontinuestobeusedinmodern
Windowsdevelopment.Inthenextsectionofthischapter,wetakea
closerlookattheModel-View-ViewModelpatternandtheadvantagesit
hasovertheModel-View-Controllerpattern.
Model-View-ViewModel
HowdoestheModel-View-ViewModelpatternsolvetheproblemswe
describedearlier?TheModel-View-ViewModelpatternintroducesa
fourthcomponent,theviewmodel.Theviewmodelisresponsiblefor
managingthemodelandfunnelingthemodel’sdatatotheviewviathe
controller.Thisiswhatthatlookslike.
Model-View-ViewModelinaNutshell
Despiteitsname,theMVVMpatternincludesfourcomponentsorlayers,
theModel,theView,theViewModel,andthecontroller.
Theimplementationofaviewmodelcansometimesbestraightforward,
translatingdatafromthemodeltovaluestheviewlayercandisplay.The
controllerisnolongerresponsibleforthisungratefultask.Becauseview
modelshaveacloserelationshipwiththemodelstheyconsume,they’re
oftenconsideredmoremodelthanview.
Let’stakealookattheadvantagesMVVMhasoverMVC.Whywould
youevenconsidertradingtheModel-View-Controllerpatternforthe
Model-View-ViewModelpattern?
AdvantagesofMVVM
WealreadyknowthattheModel-View-Controllerpatternhasafewflaws.
Withthatinmind,whataretheadvantagesMVVMhasoverMVC?
BetterSeparationofConcerns
Letmestartbyaskingyouasimplequestion.Whatdoyoudowithcode
thatdoesn’tfitorbelongintheviewormodellayer?Doyouputitinthe
controllerlayer?Don’tfeelguilty,though.Thisiswhatmostdevelopers
do.Theproblemisthatitinevitablyleadstomassivecontrollersthatare
difficulttotestandmanage.
TheModel-View-ViewModelpatternpresentsabetterseparationof
concernsbyaddingviewmodelstothemix.Theviewmodeltranslates
thedataofthemodellayerintosomethingtheviewlayercanuse.The
controllerlayerisnolongerresponsibleforthistask.
ImprovedTestability
View(iOS)andwindow(macOS)controllersarenotoriouslyhardtotest
becauseoftheircloserelationtotheviewlayer.Bymigratingsome
responsibilities,suchasdatamanipulation,totheviewmodel,testing
becomesmucheasier.Testingviewmodelsissurprisinglyeasy.Testing?
Easy?Absolutely.
Becauseaviewmodeldoesn’thaveareferencetotheviewcontroller
thatownsit,it’seasytowriteunittestsforaviewmodel.Anotherbenefit
ofMVVMisimprovedtestabilityofviewandwindowcontrollers.The
controllernolongerdependsonthemodellayer,whichmakesthem
easiertotest.
TransparentCommunication
Theresponsibilitiesofthecontrollerarereducedtocontrollingthe
interactionbetweentheviewandmodellayer.Theviewmodelprovidesa
transparentinterfacetotheviewcontroller,whichitusestopopulatethe
viewlayerandinteractwiththemodellayer.Thisresultsinatransparent
communicationbetweenthefourcomponentsorlayersofyour
application.
BasicRules
TherearesixkeyelementsthatdefinetheModel-View-ViewModel
pattern.Isometimesrefertotheseasrules.However,onceyou
understandhowtheModel-View-ViewModelpatterndoesitsmagic,it’s
finetobendorbreaksomeoftheserules.
Rule#1
First,theviewdoesn’tknowabouttheviewcontrollerit’sownedby.
Rememberthatviewsaresupposedtobedumb.Theyonlyknowhowto
presentwhatthey’regivenbytheviewcontrollertotheuser.Thisisarule
youshouldn’tbreak.Ever.
Theviewdoesn’tknowabouttheviewcontrollerit’s
ownedby.
Rule#2
Second,thevieworwindowcontrollerdoesn’tknowaboutthemodel.
ThisissomethingthatseparatesMVCfromMVVM.
Theviewcontrollerdoesn’tknowaboutthemodel.
Rule#3
Themodeldoesn’tknowabouttheviewmodelit’sownedby.Thisis
anotherrulethatyoushouldn’tbreak.Themodelshouldhavenoclue
whoit’sownedby.
Themodeldoesn’tknowabouttheviewmodelit’s
ownedby.
Rule#4
Theviewmodelownsthemodel.InaModel-View-Controllerapplication,
themodelisusuallyownedbythevieworwindowcontroller.
Theviewmodelownsthemodel.
Rule#5
Thevieworwindowcontrollerownsthevieworwindow.Thisrelationship
remainsunchanged.
Theviewcontrollerownstheview.
Rule#6
Andfinally,thecontrollerownstheviewmodel.Itinteractswiththemodel
layerthroughoneormoreviewmodels.
Thecontrollerownstheviewmodel.
GiveItaTry
Ifyou’renewtoCocoaandSwiftdevelopment,thenIrecommend
stickingwiththeModel-View-Controllerpattern.It’saprovenpatternthat
manyofushaveusedforyearstobuildsoftware.Butifyounoticethat
you’restartingtohitthelimitsoftheModel-View-Controllerpattern,then
itmaybetimetolookforanalternative.
TheModel-View-ViewModelpatternhaschangedhowIwriteandthink
aboutsoftware.Eventhoughthechangesitintroducesaremodest,the
resultsaresubstantial.CombinetheModel-View-ViewModelpatternwith
reactiveprogramming,whichIdiscusslaterinthischapter,andyouhave
apotentrecipetobuildsoftware.
Singletons
Thesingletonpatternisapatterndevelopersquicklybecomefamiliar
with.WhenIfirststarteddabblingwithCocoadevelopment,Ialmost
immediatelycameintocontactwiththesingletonpattern.ManyCocoa
frameworks,includingUIKitandFoundation,usethesingletonpattern.
BecausetheCocoaSDKmakesuseofthesingletonpattern,developers
thinkthatit’sfinetousesingletons.Itisfinetousesingletons,butit’s
morenuancedthanthis.
WhatIstheSingletonPattern
Theconceptisverysimple.Thesingletonpatternensuresonlyone
instanceofaclassisinstantiatedforthelifetimeoftheroutineor
application.TheCocoaframeworksoftenrefertoasharedobjectora
sharedinstance.Takealookattheseexamples.URLSessionand
UserDefaultsarebothdefinedintheFoundationframework.
1//SharedSessionObject
2letsession=URLSession.shared
3
4//SharedDefaultsObject
5letuserDefaults=UserDefaults.standard
Withtheabovedefinitioninmind,thesingletonpatternappearstobea
usefuldesignpattern.Unfortunately,manydevelopersmisusethe
singletonpatternanduseittoconvenientlyaccessanobjectfrom
anywhereinaproject.Havingglobalaccesstoasingletonisnothingbut
asideeffectofthesingletonpattern.It’snotwhatthesingletonpatternis
about.
SingletonsEverywhere
WheneverItalkaboutsingletons,IliketobringupMaslow’shammer
analogy.
Isupposeitistempting,iftheonlytoolyouhaveisahammer,to
treateverythingasifitwereanail.—AbrahamMaslow
Asurprisingnumberofdevelopersstrugglewiththisproblem.The
singletonpatternappearstobesolvingacommonproblem,accessingan
objectinvariousplacesofaproject.Asingleton,nothingmorethana
fancyglobal,looksliketheperfectfitfortheproblem.Anditistheperfect
fitifallyouwanttodoissolvethatproblem.There’smoretothestory,
though.
Haveyoueverwonderedwhysomeexperienceddevelopersconsiderthe
singletonpatternananti-pattern?Whyisitthatsuchausefulpatternis
oftenavoidedbymoreseniordevelopers?
SacrificingTransparencyforConvenience
Byusingsingletons,youalmostalwayssacrificetransparencyfor
convenience.ThisisaproblemIbringupfrequentlyinthisbook.The
questionis,“Howmuchareyouwillingtosacrificeforthatlittlebitof
convenience?”Convenienceshouldn’trankhighonyourprioritylistif
you’reworkingonasoftwareproject.Letmeshowyouwithanexample
whattheproblemis.
Byusingsingletons,youalmostalwayssacrificetransparencyfor
convenience.
Acommonprobleminsoftwareprojectsisusermanagement.This
meansthatausermodelobjectneedstobecreatedandmanaged.
Therearemanysolutionstothisproblem.Ifyou’reafanofthesingleton
pattern,thenyoumightcreateasingletonuserobjectoramanagerclass
thatmanagesthecurrentlysignedinuser.Onlyasingleusercanbe
signedinatatime.Right?
Problemsolved?It’struethatyoucannowaccessthecurrentlysignedin
userfromanywhereinyourproject.Whilethismayseemlikethebest
thingsinceslicedbread,itintroducesseveralproblems.
Considerthefollowingquestion.Whichobjectisallowedtomodifythe
usermodelobject?Easy.Themanagerobjectmanagingtheuser.Hmm
…butisn’tthemanagerobjectaccessiblefromanywhereinyourproject?
Thismeansthattheusermodelobjectcanbemodifiedfromanywherein
yourproject.Ifyou’restillwithme,thenIhopeyoucanseethatthisis
startingtosoundlessandlesslikethegreatideaitinitiallyappearedto
be.
Howareyougoingtomakesurethattheobjectsthatdependonthe
currentlysignedinuserarenotifiedwhentheuserismodified?Easy.
Notifications.AnotherpopularoptionistouseapatternsimilartoJava’s
observerpattern.Youcouldusekey-valueobserving,butdoyoureally
wanttoobservethepropertiesofanobjectthat’smanagedbya
singleton?Thatsoundslikeaskingfortrouble.
LosingTrackofEverything
Iagreethatthesingletonpatternseemsconvenientanditmay
occasionallybewarrantedtouseit,butthedrawbacksalmostalways
outweighthebenefits.Unfortunately,thedrawbacksareverysubtleat
firstandthat’swhatmisleadsmanydevelopers.
Unfortunately,thedrawbacksareverysubtleatfirstandthat’swhat
misleadsmanydevelopers.
Themostimportantdrawbackofthesingletonpatternissacrificing
transparencyforconvenience.Considertheearlierexample.Overtime,
youlosetrackoftheobjectsthataccesstheusermodelobjectand,more
importantly,theobjectsthatmodifyitsproperties.
Theinitialadvantageofusingasingleton,convenience,becomesthe
mostimportantproblem.Ironic.Isn’tit.Byusingsingletonsinyour
project,youstarttocreatetechnicaldebt.Singletonstendtospreadlikea
virusbecauseit’ssoeasytoaccessthem.It’sdifficulttokeeptrackof
wherethey’reusedandgettingridofasingletoncanbearefactoring
nightmareinlargeorcomplexprojects.
Oncethesingletonpatternbecomesanacceptedpracticeinaproject,it’s
difficulttomovetheprojectforwardwithoutusingevenmoresingletons.
Thestructureoftheprojectmayseemflexibleandlooselycoupled,but
it’sanythingbutthat.
SubstitutingSingletonsWithDependencyInjection
AsImentionedearlier,singletonshavethetendencytospreadlikea
virus.Thecuretosolvesingletondiseaseisdependencyinjection.I
coverdependencyinjectioninmoredetailabitlaterinthischapter.
Whileakeyadvantageofthesingletonpatternisconvenience,themost
importantadvantageofdependencyinjectionistransparency.Ilike
transparency.
Ifanobjectrequiresavalidusermodelobjecttodoitsjob,thenthatuser
modelobjectshouldbeinjectedasadependency.It’seasytotranslate
thisrequirementintocode.Takealookatthefollowingexample.
1classUser{
2varfirstName=""
3varlastName=""
4}
5
6classNetworkController{
7
8letuser:User
9
10init(user:User){
11self.user=user
12}
13
14}
ThissnippetshowsanydeveloperworkingwiththeNetworkController
classthatitdependsonavalidUserinstance.Thisisalsoknownas
passinganobjectbyreference.It’slessconvenientthanusinga
singleton,butitpaysdividendsinthelongrun.Itaddsclaritytothe
codebase,unambiguouslyshowingwhichobjectsdependonwhich
objects.
It’sanadvantagethatpassinganobjectbyreferenceislessconvenient.
Huh?Itforcesyoutoconsideryourdecision.DoestheNetworkController
classneedaccesstotheusermodelobject?Woulditsufficetopassthe
user’susernameandpasswordinstead?Dependencyinjectioncanbea
usefultooltodefinetherequirementsofanobject.
Dependencyinjectioncanbeausefultooltodefinetherequirements
ofanobject.
MovingAwayFromSingletons
Afewyearsago,Istartedworkingonaclientprojectthatwaslitteredwith
singletons.Somesingletonsevenreferencedothersingletons,addingto
theproblem.Afterseveralroundsofrefactoring,Imanagedtoeliminate
mostofthesingletonsfromtheproject,whichdrasticallyincreased
transparencyandrobustness.
Haveyoueverworkedonaprojectnobodyinyourteamwantedto
touch?Modifyingahandfuloflinesinoneclasscouldcausemayhemin
adistant,unrelatedcomponentoftheproject?Thisisnotuncommonfor
projectsthatmakeheavyuseofsingletons.
Anotherbenefitofriddingaprojectofsingletonsrelatestotesting.Writing
unittestswithouthavingtoworryaboutsingletonsisfantastic.Itreallyis.
Combinethiswithdependencyinjectionandyouhaveagreat
combinationtoworkwith.
AreSingletonsBad
Mystanceonsingletonsvariesfromdaytoday.IfIhadaroughday
battlingsingletonitis,Idislikethemwithapassion.Thetruthisthat
singletonsaren’tinherentlybadifthey’reusedcorrectly.Thegoalofthe
singletonpatternistoensureonlyoneinstanceofaclassisaliveatany
onetime.That,however,isnotthegoalmanydevelopershaveinmind
whenusingsingletons.
Singletonsareverymuchlikethegoodthingsinlife;they’renotbadif
usedinmoderation.Thenexttimeyou’reabouttocreateasingleton,
consideryourmotivationforcreatingit.Isitconvenience?Thenyou
shouldnotcreatethatsingleton.Period.That’sthesimpleruleIapply.
DependencyInjection
MyfavoritequoteaboutdependencyinjectionisaquotebyJamesShore.
Itsummarizesmuchoftheconfusionthatsurroundsdependency
injection.
“DependencyInjection”isa25-dollartermfora5-centconcept.—
JamesShore
WhenIfirstheardaboutdependencyinjection,Ifigureditwasa
techniquetooadvancedformyneedsatthattime.Icoulddowithout
dependencyinjection,whateveritwas.
WhatIsIt
Ilaterlearnedthat,ifboileddowntoitsbareessentials,dependency
injectionisasimpleconcept.JamesShoreoffersasuccinctand
straightforwarddefinitionofdependencyinjection.
Dependencyinjectionmeansgivinganobjectitsinstancevariables.
Really.That’sit.—JamesShore
Fordevelopersnewtodependencyinjection,it’simportanttolearnthe
basicsbeforerelyingonaframeworkorlibrary.Startsimple.Chancesare
thatyoualreadyusedependencyinjectionwithoutrealizingit.
Dependencyinjectionisnothingmorethaninjectingdependenciesinto
anobjectinsteadoftaskingtheobjectwiththeresponsibilityofcreating
itsdependencies.Or,asJamesShoreputsit,yougiveanobjectits
instancevariablesinsteadofcreatingthemintheobject.
AnExample
Intheexamplebelow,wedefineaUIViewControllersubclassthat
declaresaproperty,requestManager,oftypeRequestManager?.
1importUIKit
2
3classViewController:UIViewController{
4
5varrequestManager:RequestManager?
6
7}
WecansetthevalueoftherequestManagerpropertyoneoftwoways.
WithoutDependencyInjection
ThefirstoptionistotasktheViewControllerclasswiththeinstantiationof
theRequestManagerinstance.Wecanmakethepropertylazyorinitialize
therequestmanagerintheviewcontroller’sinitializer.That’snotthe
point,though.Thepointisthattheviewcontrollerisinchargeofcreating
theRequestManagerinstance.
1importUIKit
2
3classViewController:UIViewController{
4
5varrequestManager:RequestManager?=RequestManager()
6
7}
ThismeansthattheViewControllerclassnotonlyknowsaboutthe
behavioroftheRequestManagerclass.Italsoknowsaboutitsinstantiation.
That’sasubtlebutimportantdetail.
WithDependencyInjection
Inthesecondoption,weinjecttheRequestManagerinstanceintothe
ViewControllerinstance.Eventhoughtheresultmayappearidentical,it
isn’t.Byinjectingtherequestmanager,theviewcontrollerdoesn’tknow
howtoinstantiatetherequestmanager.
1//InitializeViewController
2letviewController=ViewController()
3
4//ConfigureViewController
5viewController.requestManager=RequestManager()
Manydevelopersimmediatelydiscardthesecondoptionbecauseitis
cumbersomeandunnecessarilycomplex.Butifyouconsiderthe
benefits,dependencyinjectionbecomesmoreappealing.
AnotherExample
LetmeshowyouanotherexampletoemphasizethepointImadeinthe
previoussection.Takealookatthefollowingexample.
1protocolSerializer{
2
3funcserialize(data:AnyObject)->NSData?
4
5}
1classRequestSerializer:Serializer{
2
3funcserialize(data:AnyObject)->NSData?{
4...
5}
6
7}
1classDataManager{
2
3varserializer:Serializer?=RequestSerializer()
4
5}
TheDataManagerclasshasaproperty,serializer,oftypeSerializer?.In
thisexample,Serializerisaprotocol.TheDataManagerclassisincharge
ofinstantiatinganinstanceofatypethatconformstotheSerializer
protocol,theRequestSerializerclassinthisexample.
ShouldtheDataManagerclassknowhowtoinstantiateanobjectoftype
Serializer?Takealookatthefollowingexampletoshowthepowerof
protocolsanddependencyinjection.
1//InitializeDataManager
2letdataManager=DataManager()
3
4//ConfigureDataManager
5dataManager.serializer=RequestSerializer()
TheDataManagerclassisnolongerinchargeofinstantiatingthe
RequestSerializerclass.Itnolongerassignsavaluetoitsserializer
property.Infact,wecanreplaceRequestSerializerwithanothertypeas
longasitconformstotheSerializerprotocol.TheDataManangerno
longerknowsorcaresaboutthesedetails.
WhatYouGain
Ihopetheaboveexampleshaveatleastcapturedyourattention.Letme
listafewadditionalbenefitsofdependencyinjection.
Transparency
Byinjectingthedependenciesofanobject,theresponsibilitiesand
requirementsofaclassorstructurebecomemoreclearandmore
transparent.Byinjectingarequestmanagerintoaviewcontroller,we
understandthattheviewcontrollerdependsontherequestmanagerand
wecanassumetheviewcontrollerisresponsibleforrequestmanaging
and/orhandling.
Testing
Unittestingissomucheasierwithdependencyinjection.Dependency
injectionallowsdeveloperstosubstituteanobject’sdependencieswith
mockobjects,makingunittestseasiertosetupandisolatebehavior.
1classMockSerializer:Serializer{
2
3funcserialize(data:AnyObject)->NSData?{
4...
5}
6
7}
1//InitializeDataManager
2letdataManager=DataManager()
3
4//ConfigureDataManager
5dataManager.serializer=MockSerializer()
SeparationofConcerns
AsImentionedandillustratedearlier,anothersubtlebenefitof
dependencyinjectionisastricterseparationofconcerns.The
DataManagerclassintheaboveexampleisn’tresponsibleforinstantiating
theRequestSerializerinstance.Itdoesn’tneedtoknowhowtodothis.
EventhoughtheDataManagerclassisconcernedwiththebehaviorofits
serializer,itisn’t,andshouldn’tbe,concernedwithitsinstantiation.What
iftheRequestManagerofthefirstexamplealsohasanumberof
dependencies.ShouldtheViewControllerbeawareofthose
dependenciestoo?
Coupling
TheexamplewiththeDataManagerclassillustratedhowtheuseof
protocolsanddependencyinjectioncanreducecouplinginaproject.
ProtocolsareincrediblyusefulandversatileinSwift.Thisisonescenario
inwhichprotocolsreallyshine.Laterinthischapter,Iwritemoreabout
protocolsandprotocol-orientedprogramming.
Types
Mostdevelopersconsiderthreeformsortypesofdependencyinjection:
dependencyinjectionthroughaninitializer
dependencyinjectionusingproperties
dependencyinjectioninmethods
Thesetypesshouldn’tbeconsideredequal,though.Letmelistthepros
andconsofeachtype.
Initializer
Ipersonallyprefertopassdependenciesduringtheinitializationofan
objectbecausethishasseveralkeybenefits.Themostimportantbenefit
isthatdependenciespassedinduringinitializationcanbemade
immutable.ThisisveryeasytodoinSwiftbydeclaringthepropertiesfor
thedependenciesasconstants.Takealookatthebelowexample.
1classDataManager{
2
3privateletserializer:Serializer!
4
5init(serializer:Serializer){
6self.serializer=serializer
7}
8
9}
1//InitializeRequestSerializer
2letserializer=RequestSerializer()
3
4//InitializeDataManager
5letdataManager=DataManager(serializer:serializer)
Theonlywaytosettheserializerpropertyisbypassingitasan
argumentduringinitialization.Theinit(serializer:)methodisthe
designatedinitializerandguaranteesthattheDataManagerinstanceis
correctlyconfigured.Anotherbenefitisthattheserializerproperty
cannotbemutated.
Becausewe’rerequiredtopasstheserializerasanargumentduring
initialization,thedesignatedinitializerclearlyshowswhatthe
dependenciesoftheDataManagerclassare.
InternalorPublicProperties
Dependenciescanalsobeinjectedbydeclaringaninternalorpublic
propertyontheclassorstructurethatrequiresthedependency.Thismay
seemconvenient,butitaddsaloopholeinthatthedependencycanbe
modifiedorreplaced.Inotherwords,thedependencyisn’timmutable.
1importUIKit
2
3classViewController:UIViewController{
4
5varrequestManager:RequestManager?
6
7}
1//InitializeViewController
2letviewController=ViewController()
3
4//ConfigureViewController
5viewController.requestManager=RequestManager()
Methods
Dependenciescanalsobeinjectedwheneverthey’reneeded.Thisis
easytodobydeclaringamethodthatacceptsthedependencyasa
parameter.Intheexamplebelow,theserializerisn’tapropertyonthe
DataManagerclass.Instead,theserializerisinjectedasanargumentof
theserializeRequest(_:withSerializer:)method.
1classDataManager{
2
3funcserializeRequest(request:Request,withSerializerserialize\
4r:Serializer)->NSData?{
5...
6}
7
8}
EventhoughtheDataManagerclasslosessomecontroloverthe
dependency,theserializer,thistypeofdependencyinjectionintroduces
flexibility.Dependingontheusecase,wecanchoosewhattypeof
serializertopassintoserializeRequest(_:withSerializer:).
Singletons
Earlierinthischapter,Ishowedyouhowdependencyinjectioncanbe
usedtoeliminatetheneedforsingletonsinaproject.I’mnotafanofthe
singletonpatternandIavoiditwheneverpossible.EventhoughIdon’t
considerthesingletonpatternananti-pattern,Ibelievetheyshouldbe
usedvery,verysparingly.Thesingletonpatternincreasescoupling
whereasdependencyinjectionreducescoupling.
Toooften,developersusethesingletonpatternbecauseit’saneasy
solutiontoa,oftentrivial,problem.Dependencyinjection,however,adds
claritytoaproject.Byinjectingdependenciesduringtheinitializationof
anobject,itbecomesclearwhatdependenciesthetargetclassor
structurehasanditalsorevealssomeoftheobject’sresponsibilities.
Dependencyinjectionisoneofmyfavoritepatternsbecauseithelpsme
stayontopofcomplexprojects.Thispatternhassomanybenefits.The
onlydrawbackIcanthinkofistheneedforafewmorelinesofcode,but
that’sadrawbackI’mhappytoaccept.
References,Delegation,andNotifications
AtypicalCocoaapplicationiscomposedofdozensanddozensof
objects,workingtogethertomakeyourapplicationtick.Togetthejob
done,theseobjectsneedtheabilitytotalktoeachother.Inthissection,
wetakealookatthreecommonpatternsthatenableobjectsto
communicatewithoneanother.Wealsodiscusswhentousewhich
patternand,moreimportantly,whentoavoidaparticularpattern.
References
OniOS,aviewistypicallyownedandmanagedbyaviewcontroller.This
istextbookModel-View-Controller.Theviewcontrollerkeepsareference
totheviewitmanagesandtalkstoitdirectly.
Eventhoughthere’snothingwrongwiththisapproach,it’simportantto
understandthatitintroducestightcoupling.Theimplementationofthe
viewcontrolleristightlycoupledtothatoftheview.Theoppositeisn’t
true,though.Theviewisunawareoftheviewcontrollerand,asaresult,
itsimplementationisn’tcoupledanddoesn’tdependonthatoftheview
controller.
Keepingareferencetoanobjectisthemostdirectwayof
communication.Becauseitintroducescouplingbetweenobjects,it
cannot,orshouldnot,beusedineverycontext.
Delegation
Atfirstglance,delegationappearstobesimilartothefirstapproach.The
keydifferenceisthattheobjectsarelooselycoupled.The
UITableViewDelegateprotocolisagoodexampleofdelegation.
Likeanyotherview,atableviewisinchargeofrespondingtouser
interaction.Eventhoughatableviewcandetectuserinteraction,it
doesn’tknowhowtointerpretthetouchevents.Thisseeming
disadvantageiswhatmakestableviewsreusablecomponents.
Atableviewinformsitsdelegateaboutthetoucheventsitdetects.It’sthe
responsibilityofthetableview’sdelegate,aviewcontroller,forexample,
tohandletableviewinteractions.Atableviewislooselycoupledtoits
delegatethroughtheUITableViewDelegateprotocol.Thedelegateobject
isalsolooselycoupledtothetableview.Allitneedstodoisconformto
theUITableViewDelegateprotocolbyimplementingthemethodsdefined
bytheprotocol.
AnyclassinstanceconformingtotheUITableViewDelegateprotocolcan
actasthetableview’sdelegate.Thetableviewdoesn’tcareanddoesn’t
needtoknowwhichobjectactsasthetableview’sdelegateaslongasit
conformstotheUITableViewDelegateprotocol.
Thisisanexampleofprotocol-orientedprogramming,whichwecover
laterinthischapter.Asthenameimplies,thetableviewdelegatestasks
tothedelegateobject.Delegationisaverycommondesignpatternin
Cocoaapplicationsandframeworks.
Notifications
Ideally,delegationisusedtoenableunidirectionalcommunication
betweentwoobjects.Whatifanobjecthasamessagethat’sofinterest
totwo,three,ordozensofobjects?ForCocoaapplications,the
recommendedapproachispostinganotificationthroughanotification
center.
TheNotificationCenterclass,definedintheFoundationframework,
providesaninterfaceforbroadcastingmessageswithinaCocoa
application.Tomakethispossible,twoelementsneedtobeinplace:
anobjectpostingthenotification
oneormoreobjectsinterestedinthenotification
Anobjectneedstotellanotificationcenterthatit’sinterestedinreceiving
notificationswithaparticularname.Itcanoptionallyspecifywhichobjects
they’dliketoreceivenotificationsfrom.Whatdoesthatlooklikeincode?
1letdefaultCenter=NotificationCenter.default
2defaultCenter.addObserver(self,selector:#selector(synchronizationD\
3idFinish(_:)),name:Notification.Name.SynchronizationDidFinish,obj\
4ect:nil)
Theobjectthatbroadcaststhenotificationusesthesamenotification
centertopostanotificationwithaparticularname.Itcanoptionally
includeadditionalinformationintheformofadictionary.
1letdefaultCenter=NotificationCenter.default
2defaultCenter.post(name:Notification.Name.SynchronizationDidFinish,\
3object:self,userInfo:["success":true])
Ifanobjectisnolongerinterestedinreceivingnotificationswitha
particularname,itsimplyremovesitselfasanobserver.
1NotificationCenter.default.removeObserver(self)
BeCareful
NotificationsareanessentialaspectofCocoadevelopment.Apple’s
frameworksdefinedozensanddozensofnotificationsforvarious
purposes.Thismaygiveyoutheimpressionthatnotificationsarea
proven,reliable,androbustsolutiontosendmessagesfromoneobjectto
another.Whilethat’strue,there’sacatch.
Coupling
Welikeloosecoupling.Right?Tightcouplingisbad.Thisistrue,buthow
looselycoupledisthenotificationpattern.Ifyouhaveanobjectthat
subscribestotheUIApplicationDidEnterBackgroundnotification,you
implicitlytieitsimplementationtotheUIKitframework.There’snothing
wrongwiththis,butit’simportanttoconsiderthis.You’reimplicitlyadding
adependencytotheUIKitframework.
Debugging
InmyearlydaysdevelopingCocoaapplications,Imadeampleuseof
twopatterns,singletonsandnotifications.Lookingbackitseemsonly
natural.IwastryingtosolvecommonproblemsandIfoundtwosolutions
thatwereeasytoimplement.
Notificationsaren’tbadandthey’reveryusefulattimes,butit’simportant
tounderstandthatyoupayforthemintransparency.
ThefirstprojectIstartedandsuccessfullyfinishedmadeheavyuseof
notifications.Debuggingthisprojectwasanightmareattimes.Xcode’s
debuggercanmakeiteasytodebugcommonproblems,butnotifications
canmakedebuggingmuchmorecomplexandtedious.
Anotificationsentbyoneobjectcantriggeraresponseinadistantobject
inyourproject.Theonlylinkbetweentheseobjectsisthenotification.
IfYouDecidetoUseNotifications
Ifyoudecidethatnotificationsaretherightsolutiontoaproblem,then,by
allmeans,usethem.However,Iencourageyoutoadoptahandfulof
goodpracticesifyoudo.Don’tusestringliteralstonameyour
notifications.Ever.Doyourselfafavorandcreateanextensionfor
NotificationandfollowApple’slead.Youcanuseyourownnaming
scheme,butIadviseyoutouseconstantsfornotificationnames.
1importFoundation
2
3extensionNotification.Name{
4
5staticletDidResetStatistics=Notification.Name(rawValue:"Did\
6ResetStatistics")
7
8}
Usenotificationssparinglyandonlyifthere’snootheralternativethat’s
straightforwardtoimplement.Forexample,don’tusenotificationsinstead
ofdelegation.Ifyouonlyintendtonotifyoneobject,thendelegationis
usuallytherightchoice,notnotifications.
Askyourselfwhethernotificationsaretherightsolutiontosolvethe
problem.Behonestwithyourself.Doyouusenotificationsbecauseit’s
convenientorbecauseit’stherightsolutiontotheproblemyou’re
solving?
That’swhatItrulyenjoyaboutsoftwaredevelopment.Therearerecipes
andtherearetools,butit’suptoyou,thedeveloper,tousetheright
combination.Thereareusuallymultiplesolutions,butnotwosolutions
arethesame.Onesolutionisoftenpreferredoveranother.
WhatAboutKey-ValueObserving?
Key-ValueObserving,orKVOforshort,isasolutionthatenablesobjects
toobservepropertiesofotherobjects.Key-ValueObservingandKey-
ValueCodingareimportantaspectsofCocoaprogramming.They’re
heavilyusedbybindingsonmacOS,forexample.Thatsaid,it’s
importanttounderstandthatKVOisapassiveformofcommunication
betweenobjects.
WhenToUseWhat
References
Objectreferencesmakesenseifbothobjectshaveaclearorlogical
relationshipwithoneanother.Aviewcontroller,forexample,keepsa
referencetotheviewitmanages.It’simportanttounderstandthatthe
ownertakesresponsibilityforthelifetimeoftheobjectitowns.Thisisn’t
truefordelegation.
Delegation
DevelopersnewtoCocoaareoftenconfusedbydelegationand
notifications.There’snoneedtobeconfused,though.Delegationshould
onlybeusedifoneobjectneedstotalktoanotherobject.It’saone-to-
onerelationshipandthecommunicationisoftenunidirectional,fromthe
delegatingobjecttoitsdelegate.
Delegationworksbestwithprotocols.Adelegateobject,theobjectbeing
talkedto,canbeanyobjectaslongasitconformstothedelegate
protocol.Rememberhowatableviewtalkstoitsdelegate.Itdoesn’t
knowwhichobjectitdelegatestasksto.Itonlyknowsthatitconformsto
theUITableViewDelegateprotocol.Asaresult,delegationpromotesa
looselycoupledobjectgraph.
Notifications
Notificationsareusedifanobjectwantstonotifyotherobjectsofan
event.Thesenderofthenotificationdoesn’tcarewhichobjectssubscribe
tothenotificationorhowtheyhandlethebroadcast.Eventhoughthis
mayseemthebestsolutionsinceobjectsareseeminglyuncoupled,it
introducesasubtleformofcouplingasImentionedearlierinthischapter.
OneSolutiontoRuleThemAll
Great.I’mgoingtostickwithnotifications.Foreverything.Itoffersthe
mostflexibility,well,notexactly.It’struethatnotificationsaregreatfor
communicationbetweenobjectsthatareunawareofeachother.
AsIwroteearlier,anapplicationthatreliesheavilyonnotificationsquickly
becomesanightmaretomaintainanddebug.Remembertoonlyuse
notificationsifyouhavenootheroption.Notificationsaren’tbad,butthey
shouldn’tbeoverusedeither.They’renocure-all.
ClosuresasanAlternativetoDelegation
EventhoughIlikeusingdelegationinCocoaapplications,itcan
sometimesbecomeabitoverwhelming.Largeapplicationscanendup
withdozensofdelegateprotocols,withsomeofthemdefiningonlya
singlemethod.
Analternativeapproachistouseclosures(orblocksinObjective-C).I
onlyrecommendthisalternativeasasubstituteforcompactdelegate
protocols.Let’slookatanexampletobetterunderstandhowthisworks.
Imagineanapplicationthatmanagesalistofitems.Theusercanadd
itemstothelistbytappingabuttoninthenavigationbar.Eachitemisan
instanceoftheItemstructure.
1structItem{
2
3vartitle:String
4varcontent:String
5
6}
Toaddanitem,theusertapsabuttoninthenavigationbar.Thisaction
instantiatesaninstanceoftheAddItemViewControllerclass.Theclass
declaresadidAddItempropertyoftypeDidAddItemHandler?,atypealias
foraclosurethatacceptsanIteminstanceasanargument.Thisclosure
isinvokedwhentheusercreatesandsavesanewitem.
1classAddItemViewController:UIViewController{
2
3typealiasDidAddItemHandler=(Item)->()
4
5vardidAddItem:DidAddItemHandler?
6
7privatevaritem:Item?
8
9@IBActionfuncsave(_sender:AnyObject){
10ifletitem=item,letdidAddItem=didAddItem{
11didAddItem(item)
12}
13}
14
15}
ThelistofitemsismanagedbyaninstanceoftheItemsViewController
class.ThisclassimplementstheaddItem(_:)action,whichislinkedto
thebuttoninthenavigationbar.Tappingthebuttoninstantiatesthe
AddItemViewControllerinstance.
1classItemsViewController:UIViewController{
2
3varitems=[Item]()
4
5@IBActionfuncaddItem(_sender:AnyObject){
6//InitializeViewController
7letviewController=AddItemViewController()
8
9//ConfigureViewController
10viewController.didAddItem={(item)in
11//AddItemtoList
12self.items.append(item)
13}
14
15present(viewController,animated:true)
16}
17
18}
Beforepresentingtheadditemviewcontroller,wesetitsdidAddItem
property.TheclosureacceptsanIteminstanceasitsonlyargumentand
thatenablestheitemsviewcontrollertoaddthenewitemtothearrayof
itemsitmanages.Notonlyremovesthispatterntheoverheadofcreating
andimplementingadelegateprotocol,italsokeepsrelatedcode
together.
SingletonsandObjectReferences
There’snothingwrongwithobjectreferences,butit’simportanttokeep
trackwhichobjectsknowaboutwhichobjects.Whenobjectreferences
arecombinedwithsingletons,youneedtobeextracarefultoavoid
gettingyourselfontoaslipperyslope.
Fromthemomentsingletonskeepreferencestoothersingletons,well,I
hopebynowthatyouknowwherethatends.Singletonsaren’tbad,but
youneedtobecarefulwhenyouusethesingletonpattern.Iavoiditby
defaultandonlyuseitwhenthere’snootheroption.
ReactiveProgramming
Laterinthischapter,Italkaboutreactiveprogramming.Ifyoufeel
comfortableusingtheCocoaSDKandtheSwiftlanguage,thenitmaybe
timetolookintoreactiveprogramming.Itmayseemdauntingatfirst,but
it’sgoingtochangehowyouthinkaboutcodeandsoftwaredevelopment.
MasterThesePatterns
Objectreferences,delegation,andnotificationsareverycommondesign
patternsoniOS,tvOS,macOS,andwatchOS.TheCocoaframeworks
makeheavyuseofthesepatternsandit’simportanttounderstandhow
theyworkandwhentousethem.Evenifyouneverdefineadelegate
protocolyourself,youinevitablyneedtousethemifyoubuildCocoa
applications.Andthesameappliestonotifications.Andremember,thisis
norocketscience.
6Protocol-OrientedProgramming
Object-orientedprogramming,orOOP,isawidespreadparadigmmost
developersarefamiliarwith.Theparadigmhasbeenaroundfordecades
andit’sprovenitsvalueinsoftwaredevelopment.
Becauseobject-orientedprogrammingisbakedintotheCocoaSDK,it’s
impossibletocreateaCocoaapplicationwithoutit.Itshouldcometono
surprisethenthatit’sthedefaultchoiceformostdevelopers.
NotlongaftertheintroductionoftheSwiftlanguage,aseeminglynew
paradigmmadeitswayintotheSwiftcommunity,protocol-oriented
programming,orPOP.Whatisitandshouldyoucare?Spoiler.You
should.
ButFirstThis
BeforeIcontinue,IneedtotellyouaboutDaveAbrahams.Daveworks
atAppleandisamemberoftheSwiftCoreTeam.Afewyearsago,at
WWDC2015,Davegaveanamazingpresentationthatmadewavesin
theSwiftcommunity.Inhispresentation,Protocol-OrientedProgramming
inSwift,Davechallenges,withadashofhumor,thedefaultsmostofus
areusedto.
IstronglyencourageyoutotakesometimetowatchDave’spresentation
aboutprotocol-orientedprogramming.Hedoesamuchbetterjob
explainingwhatprotocol-orientedprogrammingisandhowyoucan
benefitfromit.Davealsozoomsinonsomeofthekeydrivingforcesof
theSwiftlanguage.LikeDaveemphasizesinhistalk“Swiftisaprotocol-
orientedprogramminglanguage.”and“Atitsheart,Swiftisprotocol-
oriented.”
WhatIsIt
Letmestartwithabitofcontext.Theideaisn’tasdifficulttograspasyou
mightthink.Mostofusareusedtotheobviousbenefitsofobject-oriented
programming,suchasencapsulation,accesscontrol,andinheritance.
Thesearefeaturesweloveandusuallytakeforgranted.
Thetruthisthatobject-orientedprogrammingcomesatacost.Wepaya
pricefortheconveniencesitoffers.Object-orientedprogramminghasits
downsidesand,withoutrealizingit,wefightthemonanalmostdaily
basis.
Whataresomeofthosedownsides?Inheritanceisgreat,butyouneedto
carefullychoosethesuperclassyourclassinheritsfrom.It’snotalways
clearwhichmethodsasubclasscanoverrideandwhichonesitshould
override.
Inheritancealsomeansthatsubclassesinheritstoredpropertiesfrom
theirsuperclass.That’sagoodthing.No?Complexclasshierarchiescan
addalotofcrufttoyourclasses,and,becauseSwiftrequiresyouto
provideaninitialvalueforeverystoredproperty,initializationcanbe
messy.
Classesarereferencetypesand,whilethisisoftenexactlywhatyou
want,itcanleadtocomplexproblemsthatarehardtodebug.Shared
mutablestateoftenleadstocomplexitiesthatbiteyouatsomepoint.
IsProtocol-OrientedProgrammingAnyBetter
Protocol-orientedprogrammingisn’tnecessarilysolvingtheshortcomings
ofobject-orientedprogramming,butit’sabetteralternativeinmany
scenarios.Davepresentsadetailedexampleinhispresentation,
highlightingthebenefitofprotocol-orientedprogramminginSwift.
Protocol-orientedprogrammingstartswithadifferentmindset.Insteadof
creatingclasshierarchies,youcreatetypesthatconformtoprotocols.A
protocolisnothingmorethananinterface,definingablueprintof
propertiesandmethods.Atypecanconformtoaprotocolby
implementingitsinterface.
Flexibility
Usingprotocolsinsteadofinheritancehasitsprosandcons.You
probablyknowtheadvantagesofinheritance.Whatdoesprotocol-
orientedprogramminggainus?
InSwift,aclasshasonlyonesuperclasswhileatypecanconformto
multipleprotocols.Whilevaluetypesdon’tsupportinheritance,structs
andenumscanconformtoprotocols.
TransparencyandAbstraction
Becauseaprotocoldefinesaninterface,it’simmediatelyobvioustoa
typeconformingtoaprotocolwhichpropertiesandmethodsitshould
implement.Thisisn’talwaystrueifyou’resubclassingaclass.
AsDavepointsoutinhispresentation,protocol-orientedprogrammingis
oftenabettersolutionforabstraction.Youcanfindanexampleofthisin
MasteringMVVMWithSwift.Weuseprotocol-orientedprogrammingto
addalayerofabstractionbetweentheviewmodelandthetableviewcell
itconfigures.Theviewmodelconformstoaprotocolandthatallowsthe
tableviewcelltoconfigureitselfwiththeviewmodelwithouttheneedfor
thetableviewcelltoknowabouttheviewmodel’sexistence,definition,
orinterface.
BeCareful
Whileprotocolsmayseemconvenientandflexible,theycanalso
complicateyourcodebase.I’veworkedonprojectsthatweredifficultto
understandbecauseoftheoveruseofprotocols.
ChrisEidhofwroteaboutthisproblemafewmonthsago.Heillustrates
theversatilityofaprotocol-orienteddesign,buthealsoemphasizesthat
itshouldn’tbeyourdefaultchoice.
[P]rotocolscanbeveryuseful.Butdon’tstartwithaprotocoljustfor
thesakeofprotocol-orientedprogramming.Startbylookingatyour
problem,andtrytosolveitinthesimplestwaypossible.Letthe
problemdrivethesolution,nottheotherwayaround.Protocol-
orientedprogrammingisn’tinherentlygoodorbad.Justlikeany
othertechnique(functionalprogramming,OO,dependencyinjection,
subclassing)itcanbeusedtosolveaproblem,andweshouldtryto
picktherighttoolforthejob.Sometimesthat’saprotocol,butoften,
there’sasimplerway.
RememberwhatIwroteinthechapteronrefactoring.Yousolvea
complexproblembyimplementingthesimplestpossiblesolutionyoucan
comeupwith.Withtheproblemsolved,it’stimetooptimizeyoursolution.
WatchDave’sPresentation
Don’tforgettowatchDave’spresentation.I’vewatcheditseveraltimes
andyoushouldtoo.It’safunpresentationthatteachesyoualotabout
theSwiftlanguage,includingprotocol-orientedprogramming.
7ReactiveProgramming
Asadeveloper,you’llhaveseveralahamomentsinyourcareer.The
discoveryofreactiveprogrammingwasoneofthosemomentsforme.
WhenIfirstheardaboutreactiveprogramming,Iwasskeptical.Itlooked
exoticandmagical,andIdiscardeditalmostimmediately.Afewyears
later,RxSwiftcrossedmypathanditclicked.
It’struethatthere’salearningcurve,especiallyifyoureadrandom
tutorialsontheweb.Butonceitclicks,youseethebenefitsandwhat
reactiveprogrammingbringstothetable.
WhatIsIt
Tryingtofindadefinitionofreactiveprogrammingthatmakessenseis
thefirstchallengeyou’llface.Let’skeepitverysimpleandstickwith
AndréStaltz’sdefinition.
Reactiveprogrammingisprogrammingwithasynchronousdata
streams.—AndréStaltz
Andréhasacomprehensiveguideonreactiveprogrammingthatyou
shouldreadifyou’reinterestedinadoptingreactiveprogramming.As
Andréwrites,reactiveprogrammingisnothingmorethaninteractingwith
streamsofdata.Thesearecommonlyreferredtoasobservable
sequences,orobservablesforshort.
Reactiveprogrammingisn’tbuiltintoSwift.Asaresult,several
frameworksandlibrarieshaveemergedforSwiftandCocoaoverthe
years.ThemostpopularsolutionsareReactiveCocoaandRxSwift.I’ve
chosenforRxSwiftbecauseit’stheofficialextensionforSwiftofthe
ReactiveXAPI.It’suptoyoutodecidewhichimplementationyouprefer.
Why,Why,Why
AsImentionedearlier,IwasskepticalwhenIfirstheardandreadabout
reactiveprogramming.Ididn’tseewhyIshouldinvesttimeinyetanother
technology.Objective-CandSwifthadservedmewellformanyyears.It
didn’tclickformeatthetime.Yetreactiveprogramminghasbecomean
integralpartofmyworkflow.Whyisthat?Whatchangedmymind?
Simplification
Applicationsthatrespondtoevents,suchasuserinteraction,tendto
becomecomplexratherquickly.Let’sfaceit,asynchronousprogramming
isn’teasy.ArequestissenttoaremoteAPI,atsomepointyoureceivea
response,andthatresponseisusedinadistantunrelatedsectionofyour
application.Itcanbeachallengetoimplementeventhesimplesttasks.
Reactiveprogrammingaimstomakethiseasier.Younolongerdrownin
callbacks.Yousimplyworkwithstreamsofdatathatyoumonitor,
compose,andrespondto.Youshiftfromimperativeprogrammingto
reactiveprogramming.
RemovingState
Whileit’sthissimplificationthatdrawsmostdeveloperstoreactive
programming,youreceiveanotherimportantbenefitifyoudecideto
adoptreactiveprogramming.Becauseyou’reobservingandresponding
tostreamsofvalues,younolongermaintainstate.Whyisthat
important?Whyisthisabigdeal?
Almosteveryapplicationmanagesstateinsomeformorshape.Ifyou’re
developingamobileapplication,thenyouneedtoreflectsomeofthat
stateintheuserinterface.Whilethismayseemeasyonpaper,it’smuch
harderthanitlooks.I’msureyouknowwhatImeanifyou’reworkingon
projectsthathaveabitofcomplexitytothem.
Reactiveprogrammingmakesthismucheasier.Forthepastfewmonths,
I’vebeenworkingonanapplicationwithacomplextimerengine.This
wouldhavebeenanightmarewithoutreactiveprogramming.Insteadof
keepingtrackofthestateofthetimer,thetime,thecurrentsegment,and
onandon,theapplicationobservesandrespondstothevaluesof
severalobservablesequences.It’samazing.
Coupling
Reactiveprogrammingpromotesloosecouplingofobjects.Anyobject
canobserveanobservablesequenceanditonlyneedstokeepa
referencetothatstreamofvalues.That’stheonlyaspectit’sinterested
in.
Thedelegationpatternisveryeasytoreplacewithreactiveprogramming.
Insteadofkeepingareferencetoadelegateobject,thedelegatingobject
managesanobservablesequence,emittingvalueswhenappropriate.
Anyotherobjectthat’sinterestedinthevaluesemittedbythatobservable
sequencecansubscribetoit.
AllorNothing
Developersunfamiliarwithreactiveprogrammingwronglybelievethat
reactiveprogrammingrequiresanall-or-nothingapproach.Thatisn’ttrue,
though.Onceyou’veincludedRxSwiftandRxCocoainoneofyour
projects,it’suptoyoutodecidewhere,how,andwhyyouwanttouseit.
TheapplicationwebuildinMasteringMVVMWithSwiftisagood
example.Weonlyusereactiveprogramminginahandfulofclasses.The
restoftheprojectisunawareofRxSwiftandRxCocoa.
IsThisForYou
Iencourageeverydevelopertohavealookatreactiveprogramming.
However,ifyou’renewtosoftwaredevelopment,thenmyadviceisto
focusonyourfoundationfirst.RememberwhatIwroteearlierinthis
book.Reactiveprogrammingcanwait.
Model-View-ViewModel
InMasteringMVVMWithSwift,Iillustratethepowerfulcombinationofthe
Model-View-ViewModelpatternandreactiveprogramming.TheModel-
View-ViewModelpatternworksbestwithabindingssolution,andreactive
programmingoffersjustthat.
Rememberthatitdoesn’tneedtobeRxSwiftandRxCocoa.Youcanuse
thesolutionthatbestfitsyourstyleandpreferences.
PART2:SWIFT
1LearnSwiftWithanOpenMind
DevelopersmakingtheswitchfromObjective-CtoSwifttendtotranslate
Objective-CintoSwift.TheytakewhattheyknowaboutCocoa
developmentandapplyittoSwift.Unfortunately,thisoftenresultsin
frustrationandsometimesevenanaversiontowardstheSwiftlanguage.
It’seasyenoughtounderstandwhydeveloperstakethisapproach.
Peoplelearninganewspokenlanguagetendtolookforthepatternsand
constructsthey’realreadyfamiliarwith.Whilethisisacommonphasein
thelearningprocess,itemphasizestheimportanceofacarefullychosen
learningtrajectory.Thesameappliestopickingupanewprogramming
language.
DevelopersnewtoSwiftoftentakethesecommonalitiestothinkthat
SwiftandObjective-Careverysimilarwhilethey’renot.
BecauseSwiftissodifferentfromObjective-C,youneedtotakeastep
backward.YouneedtounlearnwhatyouknowaboutObjective-Cand
startwithacleanslateandanopenmind.SwiftandObjective-Cdiffer
morethanthey’realike.It’struethataSwiftapplicationrunsinthe
Objective-Cruntimeandthatthelanguagesareinteroperable,they
understandoneanother.ButdevelopersnewtoSwiftoftentakethese
commonalitiestothinkthatSwiftandObjective-Careverysimilarwhile
they’renot.
ReferenceTypesandValueTypes
Whilethere’snothinginherentlywrongwithclassesandinheritance,Swift
implicitlyencouragestheuseofvaluetypes(tuples,structures,and
enumerations)insteadofreferencetypes(classes).Severalmonthsago,
IcameacrossatalkfromAndyMatuschakaboutthistopic.It’sagreat
introductiontotheadvantagesvaluetypeshaveoverreferencetypes.
TheSwiftStandardLibraryalsoembracesvaluetypes.Strings,arrays,
dictionaries,andsets,forexample,arevaluetypesinSwift.Thisisvery
differentfromtheirFoundationcounterparts,NSString,NSArray,
NSDictionary,andNSSet.
Protocol-OrientedProgramming
EventhoughstructuresandenumerationsinSwiftaremorepowerful
thantheirObjective-Ccounterparts,theydon’tsupportinheritance.This
isoftenseenasamissingfeatureandscaresmanydevelopersaway
fromvaluetypes.DevelopersnewtoSwiftandaccustomedtoobject-
orientedprogramminglookforinheritanceandfinditinclasses,thatis,
referencetypes.
Earlierinthebook,Iemphasizethatthelackofinheritanceisn’ta
problem.Protocolsandvaluetypesareapotentcombination,maybe
evenmoresothanreferencetypesandinheritance.
Appleemphasizesthatprotocol-orientedprogrammingisapattern
developersshouldembraceinSwift.IencourageyoutowatchProtocol-
OrientedProgramminginSwifttounderstandwhatitisandhowyoucan
applyitinSwift.DaveAbrahamsdoesatremendousjobexplainingwhy
protocol-orientedprogrammingisanaturalfitforSwift.
ClassesandinheritanceremainimportantinSwift.They’renotthe
enemy.TheCocoaframeworksareforthemostpartpoweredby
Objective-Candthatmeansclassesandinheritanceareheretostay,at
leastfortheforeseeablefuture.
AsaCocoadeveloper,youcontinuetouseclassesandcreate
subclasses.Butit’sequallyimportanttounderstandtheideasthatpower
Swiftandhowyoucanusetheminyourprojects.Inhispresentation,
DaverepeatedlydrawsattentiontoSwiftbeingaprotocol-oriented
language.
TypeSafety
TypesafetyisacornerstoneoftheSwiftprogramminglanguage.Asa
developer,Swiftexpectsyoutobeclearaboutthetypesofthevariables
andconstantsyouuse.Theadvantageisthatcommonmistakes,suchas
passingavalueofthewrongtypetoamethod,canbecaughtbythe
compiler.
DeveloperscomingfromObjective-CoftenstrugglewithSwift’sstricttype
safetyrules.ThistiesinwithanotherconceptofSwift,optionals.
Optionalsareseenasanobstacle,anunavoidablesideeffectofSwift’s
typesafety.WhathappenedtosendingmessagestonilinObjective-C?
What’swrongwiththat?
Optionalsmayindeedfeelasobstacleswhenyoufirststart
experimentingwithSwift.Astimepassesandyoubecomemorefamiliar
withthelanguageinitsentirety,thepiecesofthepuzzlestarttocome
togetherandyoucometoappreciateoptionalsforwhattheyrepresent
andtheproblemtheysolve.Incombinationwithoptionalbindingand
optionalchaining,optionalsstarttofitintothatproverbialpuzzle.
Iagreethatoptionalscanfeelclunkyifyou’reinteractingwithan
Objective-CAPIthatwasn’tbuiltwithSwiftoroptionalsinmind.ButI
wouldn’twanttouseSwiftwithoutthem.Optionalsaresuchanice
featureofSwiftandI’vecometoappreciatethem.Infact,everytimeI
takeatripdownmemorylanewhenIneedtofixabuginObjective-C,I
missthem.Optionalsclearlyexpresswhat’shappening.
Ifyou’restillnotsureaboutoptionals,thenIsuggestyoureadthechapter
aboutoptionalsinthisbook.Givethemthebenefitofthedoubtfornow.
Usethemforafewweeks,avoidtheexclamationmark,andseehowyou
feelabouttheminamonth.
BestPractices
ThemoreyoureadaboutSwiftandthelongeryouspendtimeinthe
Swiftcommunity,themoreyourealizethatSwiftisstillaveryyoung
language,especiallyifyoucomparethelanguagewithCandObjective-
C.Acommonproblemdevelopersfaceisthelackofbestpractices.They
lookforstrategiestosolvecommonproblemsandstruggletofindthem.
Bestpracticesareslowlytakingformasmorepeopleusethelanguagein
real-worldscenarios.
Thisisn’tsurprising.TheSwiftcommunityisstillexploringthelanguage,
findingoutwhat’spossibleandhowthingscanorshouldbedone.The
languageisstilldevelopingatarapidpaceandtheopensourcingofthe
languageisanothercomponentthatdrivesthisswiftevolution.
Severalbestpracticesareslowlytakingshape,suchastheadoptionof
protocol-orientedprogramming,thevalueofimmutability,andtheuseof
valuetypesoverreferencetypes.
ForgetWhatYouKnow
MyadviceistoapproachSwiftwithanopenmind.Trytoforgetwhatyou
know.Whatyouknowhasvalue,butitmayslowyoudownoritmaylead
tofrustration.Explorethelanguage,becomefamiliarwiththefoundations
it’sbuilton,andlearnfromothers.
2BeCritical
TheprimarygoalofCocoacastsistohelpdevelopersbecomebetterat
theircraft.Itcanbechallengingtoputthatintowords.Butthere’sone
traitIfeeleverygooddevelopershouldhave,beingcritical.Thismeans
beingcriticalofyourownwork,butalsoofthatofothers.
Ifyouspendtimereadingblogs,watchingvideos,orbrowsingsocial
media,youinevitablypickupnewtechniques,tips,andtricksthatcan
helpyouinyourwork.It’softentemptingtoabsorbthisinformationas
gospelifthesourceisarespecteddeveloperoranauthorityintheirfield.
Eventhoughthisisanaturalresponse,itsometimeshintsatalackof
confidence.Myadviceistoalwaysbecritical.TheresponsesIgetonmy
tutorialsandvideosaremostoftenquestions.Butthere’sanumberof
developersthatsendmetheirthoughtsonthesubjectortheychallenge
mewithanalternative.That’sahealthyattitude.Thereasoncanbe
arrogance,but,moreoften,it’sjustsomeonebeingcritical.
StackOverflowisablessingforthedevelopercommunity.Idon’tthink
there’sadeveloperthatdoesn’toccasionallyvisitStackOverflowfor
answers.Butit’simportanttobecriticalofwhatyouread.StackOverflow
hasareliablevotingsystemformakingsureanswersarecorrectand
tested,butthatdoesn’tmeanyoushouldtakewhatyoureadonStack
Overflowasthetruth.
Wheneveryoureadasolutiontoaproblemyou’rehavingit’simportantto
takeacloserlookatthatsolutionbeforeembracingit.Makesureyou
understandthesolution.Doesthesolutionmakesense?Howcouldyou
improvethesolution?
ThetipsandpracticesIdescribeinthisparthavebecomeanintegralpart
ofmyworkflow.Someofthemareopinionatedwhileothersare
consideredgoodpracticesforSwiftdevelopment.Ileaveituptoyouto
decidewhetherthey’reworthadopting.Remembertoalwaysbecritical.
3EmbracingOptionals
TypesafetyisafundamentalconceptoftheSwiftprogramminglanguage
andoptionalsneatlytieintoSwift’sstricttypesafetyrules.Theconcept
underlyingoptionalsissimple,anoptionalhasavalueoritdoesn’t.
Developersnewtothisconceptoftenstrugglewithoptionals.Theysee
optionalsasanobstacleandadirectconsequenceofthestricttype
safetyrulesimposedbythelanguage.Thisstruggleusuallydissipates
afterspendingsometimewiththelanguageandafterdiscoveringSwift’s
constructsforsafelyinteractingwithoptionals,suchasoptionalbinding
andoptionalchaining.
WarningSign
Beforethestruggleends,though,bruteforceisusedtoattackthe
problemthatoptionalsappeartobe.Afterdiscoveringtheexclamation
mark,everyoptionalisconsideredanailthatneedstobehitwiththe
proverbialhammer.Forcedunwrappingandimplicitlyunwrapped
optionalsaretemporarilyseenasthesolutiontotheproblem.
TheexclamationmarkisinSwiftwhatyoumayintuitivelyexpectittobe,
awarningsign.Ifyouusetheexclamationmark,you’reabouttoperform
anoperationthatmaybackfire.Forcedunwrappinganoptionalthat
doesn’tcontainavaluethrowsaruntimeerror,crashingyourapplication.
Theexclamationmarkwarnedyouthiscouldhappen,though.
Irecentlyreceivedanemailfromareaderabouttheuseofthe
exclamationmark.Thecompanysheworksforhasasimplepolicy,
“Don’tusetheexclamationmark.”Thismayattimesresultincodethat’s
abitverbose,butthebenefitsareobvious.Thecodetheywriteissafe
andit’sconsistent.
EleganceandBeauty
Thebeautyofoptionalsiseasilyoverlookedifnotpaidattentionto.
Optionalsembodyaconceptthat’seasytograspandthat’swhatmakes
itpowerful.Ifyou’regivenanon-optional,you’regiventhepromisethatit
hasavalue,it’sanythingbutnil.Incomputing,that’saboldpromise.
Ifyouknowthataconstantorvariableisguaranteedtohaveavalue,
you’realsogivenfreedom.
Ifyouknowthataconstantorvariableisguaranteedtohaveavalue,
you’realsogivenfreedom.ApointerinObjective-C,forexample,isn’t
guaranteedtonotbenil.Whileitmaybepointingtoavalidobjectnow,
thatmaychangelater.Noproblem.Youcansafelysendmessagestonil
inObjective-C.That’swonderful,buthowoftenhasthisbeenan
advantage?Thinkaboutit.
Ifyou’resendingamessagetonil,itprobablymeansthatyouwere
expectingsomethingtohappenthatdidn’thappen.Isthatabetter
solutionthanoptionals?
Ifyou’resendingamessagetonil,itprobablymeansthatyouwere
expectingsomethingtohappenthatdidn’thappen.
SwifttotheRescue
Swiftdoesn’tleavedevelopersoutinthecold.Thelanguageoffersa
numberofconstructsforworkingwithoptionals,suchasoptionalbinding
andoptionalchaining.
Optionalbindingisusedtosafelyunwrapthevaluethat’sstoredinan
optional.Iftheoptionalhasavalue,thenthatvalueisboundtoa
constantthat’savailableintheifclause.
1ifletmessage=message{
2print(message)
3}else{
4print("novalue")
5}
Thissolutionismoreelegantthanverifyingwhethermessagehasavalue
andthenforcedunwraptheoptionalusingtheexclamationmark.
1ifmessage!=nil{
2print(message!)
3}else{
4print("novalue")
5}
Optionalbindingisflexibleandpowerful.Takealookatthefollowing
example.
1ifletpayload=payload,
2letmessage=payload["message"]{
3print(message)
4}
Optionalchainingisanelegantalternativetoforcedunwrapping
optionals.Insteadofforcedunwrappinganoptional,youuseoptional
chainingtoaccessapropertyorinvokeamethodonthevaluestoredin
theoptional.
1label?.textColor=UIColor.blackColor()
ThetextColorpropertyisonlysetiflabel,anoptional,hasavalue.The
questionmarkisusedtosafelysetthetextColorpropertythrough
optionalchaining.
Attimes,IuseSwift’snil-coalescingoperatorwhenI’mfacedwithan
optional.Thiscanbeusefultoelegantlyaccessthevalueofanoptional
orprovideadefaultvalue.
1funcdate(forprofile:Profile)->Date{
2returnprofile.createdAt??Date()
3}
ThecreatedAtpropertyoftheProfileinstanceisoftypeDate?.The
date(for:)functionalwaysreturnsaDateinstancebydefaultingtothe
currentdateandtime.
EmbraceOptionals
Eventhoughitmayseemasifoptionalsareasolutiontoworkaround
Swift’sstricttypesafetyrules,they’recomplementingthoserules.
Optionalsgetridofunsafepointersandofferguaranteesthatmakeyour
codesaferandeasiertodebug.
Optionalsgetridofunsafepointersandofferguaranteesthatmake
yourcodesaferandeasiertodebug.
WhileitmayseemgreatthatyoucansendmessagestonilinObjective-
C,it’sanemptypromise.Ifyouconsideryourapplicationnotcrashing
whenyousendamessagetoanilpointer,thenthinkagain.Also,
considerthatoptionalscanbeusedforanytypewhilenilonlyappliesto
pointersinObjective-C.
Afewdaysago,Ihadtoopenupanoldprojectthatwasprimarilywritten
inObjective-C.Theabsenceoftypesafetyandoptionalswas
immediatelyobvious.Itmaysoundodd,butImissoptionalseverytimeI
needtoworkwithObjective-C.
Ifyou’reseriousaboutSwift,thenit’simportantthatyoubecomefamiliar
withoptionals,whichproblemstheysolve,andembracetheminthecode
youwrite.
4MindtheExclamationMark
I’msuretheexclamationmarkisanecessaryaspectoftheSwift
language,butIwouldn’tblinkaneyeifitwereremovedfromthe
languagetomorrow.Theexclamationmarkisawarningsign,buttoo
manydevelopersignorethisanduseitbecauseit’smoreconvenient.
NotethatI’mnotreferringtothelogicalNOToperator.That’saperfectly
validuseoftheexclamationmark.
AsImentionlaterinthebook,theuseoftheexclamationmarkisoftena
codesmell.Becauseyou’retradingsafetyforconvenience,itshouldbe
usedsparingly.
UseCases
Theexclamationmarkisusedinseveralsituations.Themostcommon
useisforcedunwrappingthevaluestoredinanoptional.Asyouknow,a
runtimeerroristhrownifthatoptionaldoesn’tholdavalue.
Youalsousetheexclamationmarktodeclareanimplicitlyunwrapped
optionalorwhenyouwanttodisableerrorpropagation.Thesamerule
applies.Ifyouaccessthevalueofanimplicitlyunwrappedoptionalthat
doesn’tcontainavalueorathrowingfunctionthrowsanerrorwhenerror
propagationisdisabled,aruntimeerroristhrown.
ConvenienceandLaziness
DevelopersnewtoSwiftoftenresorttotheexclamationmarkbecause
they’reunfamiliarwithorconfusedbyoptionals.Mostdevelopersgo
throughthisphase,butIalwaysrecommendtogetusedtooptionals
soonerratherthanlater.
ThoseofuswithabackgroundinObjective-Cusuallyhaveahardertime
becomingfamiliarwithoptionals.We’reusedtothefactthatsending
messagestonildoesn’tcausehavocinObjective-C.ItdoesinSwiftand
that’sanunwelcomechange.
Don’tBeLazy
Youprobablyheardthephrase“Alazydeveloperisagooddeveloper.”
Thissayingistrue,butitdependsonwhat’sunderstoodbylazy.Many,
manydevelopersusetheexclamationmarkbecauseit’sconvenient.In
otherwords,they’rebeinglazy.I’dliketosaythatlazinessor
convenienceisneveravalidreasonforusingtheexclamationmark.
Unfortunately,it’sdifficulttoarguewiththatexplanation.
WhenIUsetheExclamationMark
Iusetheexclamationmarkinthreesituations,outlets,required
properties,andresources.
Outlets
Outletsthatshouldalwayshaveavaluearedeclaredasimplicitly
unwrappedoptionals.Aswitheveryuseoftheexclamationmark,Ionly
declareanoutletasanimplicitlyunwrappedoptionaltoconveniently
accessitsvalue.That’stheonlyreason.Youcandeclareoutletsas
optionals.That’sperfectlyfinetoo.
Ifanoutletisdeclaredasanimplicitlyunwrappedoptionalanditdoesn’t
haveavaluewhenit’saccessed,thenImadeamistakeIneedtofix.
Bearinmindthatit’spossibletohaveoptionaloutlets.Insomeprojects,I
createaUIViewControllerclassthatservesasthebaseclassforother
viewcontrollersoftheproject.Thisclassdeclaresanoptionaltableview
outlet.Becausenoteveryviewcontrollerhasatableview,it’swiseand
necessarytodeclaretheoutletasanoptional.
RequiredProperties
SwiftworksfinewiththeCocoaSDK,buttherearesomeroughedges.
Youprobablyknowthateverystoredpropertyofaclassorstructure
needstohaveavalidinitialvaluebythetimeaninstanceofthetypeis
created.Thisisfine,butitpresentssomeproblemsifyou’reworkingwith
storyboards.Ifyou’reusingstoryboards,thenyou’renotinchargeof
instantiatingtheviewcontrollersofyourapplication.Thismeansthatyou
can’timplementacustominitializerthatacceptsvaluesforeverystored
property.
Anapproachthat’softenusedisthatyouconfigurethedestinationview
controllerintheprepare(for:sender:)methodofthesourceview
controller.Atthattime,thedestinationviewcontrollerisalreadyinitialized
andeverystoredpropertyhasaninitialvalue.Ifyouwanttopassa
modelobjecttotheviewcontroller,youneedtodeclarethepropertyfor
thatmodelobjectasanoptionalor,youguessedit,asanimplicitly
unwrappedoptional.
AsImentionedearlier,themotivationfordeclaringapropertyasan
implicitlyunwrappedoptionalisalwaysconvenience.Thereasoning
behindthischoice,however,ismorenuanced.Let’sassumeyou’re
implementingaviewcontrollerthatdisplaysthedetailsofanote.You
passthenotetothedetailviewcontroller.Thedetailviewcontrolleris
uselessifitdoesn’thaveavalidnotetoworkwith.Inotherwords,the
notepropertyofthedetailviewcontrollershouldalwayshaveavalue.No
exceptions.
Laterinthisbook,Idiscussfatalerrors.Inthissituation,Iprefertothrow
afatalerrorifthenotepropertydoesn’thaveavaluebecausethatshould
neverhappeninproduction.Unfortunately,Ihaven’tfoundanelegant
solutiontoimplementthis,whichiswhyIuseimplicitlyunwrapped
optionalsinstead.
Resources
There’soneotherusecaseinwhichIusetheexclamationmark.Ifthe
applicationneedstoaccessaresourcefromitsbundle,Idon’twantto
dealwithoptionals.Whyisthat?
Theresource,animageorastoryboard,shouldbepresentinthe
applicationbundle.Ifitisn’t,thenthatmeansIhavebiggerproblemsto
worryabout.TakealookatthiscodesnippettobetterunderstandhowI
usethistechnique.
1extensionUIImage{
2
3enumIcons{
4
5enumProfile{
6
7staticletSegments=UIImage(named:"icon-profile-segme\
8nts")
9staticletConfiguration=UIImage(named:"icon-profile-\
10configuration")
11
12}
13
14}
15
16}
IalsoapplythistechniquetoURLsthatarehard-codedintheproject.
1enumAudio{
2
3staticletSilence=Bundle.main.url(forResource:"rocknroll",w\
4ithExtension:"mp3")!
5
6}
7
8enumAPI{
9
10staticletBaseUrl=URL(string:"https://api.myawesomeapplicati\
11on.co")!
12
13}
APersonalChoice
Whileit’sapersonalchoicewhenyouusetheexclamationmarkand
whatyourmotivationis,it’simportantthatunderstandwhyyou’reusing
theexclamationmarkandwhattheconsequencesare.Thenexttimeyou
appendanexclamationmarktoavariable,consideryourmotivationand
therisk.Choosewiselyanddon’tbelazy.
5ExclamationMarksandFatalErrors
Fatalerrorshaveanegativeconnotationandwithreason.Youshould
usethemsparinglyifyouwanttoavoidhavingyourapplicationcrashand
burnattheslightesthiccup.Despitetheirnegativeundertone,fatalerrors
areanintegralpartofmyworkflowasIwriteelsewhereinthisbook.
WheneverIwriteorspeakaboutmyuseoffatalerrors,Iusuallyseetwo
typesofresponses.Developersunfamiliarwithfatalerrorsandhowthey
canbeusedsafelyaresurprisedandexcited.Theyspotthebenefitsfatal
errorscanbringtoaproject.Canyouguesswhatthesecondtypeof
responsesoundslike?
Whydon’tyouuseanexclamationmarkinstead?
Thesuggestiontouseanexclamationmarkinsteadofthrowingafatal
errorisunderstandable.Fromauser’sperspective,theresultisidentical.
ButI’mnotusingfatalerrorswiththeuserinmind.Idon’tthrowafatal
errortocrashtheapplicationwhentheuserisusingit.Inanideal
scenario,afatalerrorshouldonlybethrownindevelopmentorwhenthe
applicationisbeingtested.
Iagreethattheuserwon’tappreciatemyuseoffatalerrorsifthe
applicationcrashesthemomentthey’reabouttobesttheirprevioushigh
score.ThethingisthatI’madeveloperandIlookatcodemostofmy
workinghours.Andthat’sexactlythereasonIchooseforfatalerrors
morefrequentlythanIchoosefortheexclamationmark.Letmeexplain
whatImeanbythat.
ClarityOverSubtleness
Mybiggestcomplaintwiththeexclamationmarkisitssubtleness.
Ironically,plentyofdevelopersusetheexclamationmarkforexactlythat
reason.It’ssoeasytoappendanexclamationmarktoavariableora
constant.It’salmosttooeasy.IunderstandwhytheSwiftteamhas
chosentosupportforcedunwrappingandforcedconversionusingthe
as!operator,butIwouldn’tshedatearifbothwereremovedfromthe
Swiftlanguagetomorrow.
IagreethatitcanbefrustratingtointeractwithanancientObjective-C
APIthatdoesn’tcareaboutnilandoptionals.Interactingwiththefile
system,forexample,canoftenleadyoudownarabbitholeofoptionals,
indentation,andconditionals.Butthat’swhatittakesifyoudecideto
writesoftwareinSwift.
Don’tbelazybyappendinganexclamationmarktoavariableora
constantyou’reprettysurewillalwayscontainavalue.Itwillcontaina
value…mostofthetime…almostalways.Asthedocumentation
explains,youshouldonlyforceunwrapanoptionalifyou’recertainthatit
containsavalue.IturnitaroundwhenIusefatalerrors.Afatalerror
shouldbethrowniftheapplicationentersastateitdidn’tanticipate.
ChoosingforClarity
Acommontraitamongdevelopersisanobsessionwithsimplicityand
minimalism.Cleancodeisbutonemanifestationofthistrait.Byusing
fatalerrorsIchooseforclarity.Iftheapplicationthrowsafatalerror,I
wanttoknowaboutit.It’struethattheexclamationmarkwillalsodothat
forme.ButIalsowanttoknowaboutitwhenI’msimplyreadingthrough
mycode.
Anexclamationmarkdoesn’tjumpout,butaguardstatementwitha
fatalError()calldoes.Itimmediatelyshowsyouthatyouknowthata
certainscenarioshouldneverhappenandyouguardagainstthat.
Takealookatthefollowingimplementationoftheprepare(for:sender:)
method.ThisisacommonpatternIuse.Iftheusertriggersthe
Segue.SelectProfilesegue,theapplicationexpectsthedestinationview
controllertobeoftypeSelectProfileViewController.Itsimplydoesn’t
knowhowtorespondifthatisn’ttruehencethefatalerrorintheelse
clauseoftheguardstatement.Whileitmaylookabitverbose,it’sclear
andexplicit.
1//MARK:-Navigation
2
3overridefuncprepare(forsegue:UIStoryboardSegue,sender:Any?){
4guardletidentifier=segue.identifierelse{return}
5
6switchidentifier{
7caseSegue.SelectProfile:
8guardletdestination=segue.destinationas?SelectProfileV\
9iewControllerelse{
10fatalError("UnexpectedDestinationViewControllerforS\
11egue")
12}
13
14...
15default:break
16}
17}
Thealternativeistousetheas!operatortoforcefullyconvertthe
destinationviewcontrollertothetypetheapplicationexpects.
1//MARK:-Navigation
2
3overridefuncprepare(forsegue:UIStoryboardSegue,sender:Any?){
4guardletidentifier=segue.identifierelse{return}
5
6switchidentifier{
7caseSegue.SelectProfile:
8letdestination=segue.destinationas!SelectProfileViewCon\
9troller
10
11...
12default:break
13}
14}
Iunderstandthatthispracticeisabitcontroversial,butI’veseenits
effectiveness.It’swhyI’mabigfanofthispattern.AsImentionedearlier
inthischapter,theissueIhavewiththeexclamationmarkisthatitisn’t
explicitenough,it’stoosubtle.It’seasytooverlookitwhilebrowsinga
codebase.
Thedifferencebetweentheuseoffatalerrorsandtheuseofthe
exclamationmarkissubtle.Youcouldalsosaythatthedifferenceiseasy
tomiss,whichisexactlywhyIbringitup.Giveitatryandletmeknow
whatyouthink.
6SmellyCode
PixelsyncwasthefirstiOSapplicationIpublishedontheAppStore.For
afirstproject,itwasquitecomplexandfarmorechallengingthanIhad
anticipated.TheprojectgrewquicklyasIaddedmorefeaturesand
maintainabilityquicklybecameanissueIcouldn’tignore.
Lookingback,theprojectwaslitteredwithanti-patterns,badpractices,
andcodesmells.Addingfeaturestoalarge,complexcodebaseis
challengingifitlacksdirectionandstructure.
Manydevelopersstartoutthiswayandlearnastheygo.It’sfinetomake
mistakesaslongasyoulearnfromyourmistakesandfindsolutionsthat
workbetter.Inthischapter,Iwanttofocusoncommonsignsofcode
smellinSwift.
ForcedUnwrappingandConversion
Onceyougetusedtooptionals,youcometoappreciatetheirvalue.Not
onlyareoptionalsmakingyourcodesafer,theyalsomakeyourcode
morereadable.Anoptionalcarriesamessagethatsays“Imaynothave
avalue.Becareful.”
DevelopersnewtoSwiftoftenseeoptionalsasahurdle,forcingthemto
jumpthroughabunchofunnecessaryhoops.Optionalsneedtobe
unwrappedandthatrequiresmorecode.There’sashortcut,though.It’s
possibletoforcedunwrapoptionals.Takealookatthefollowing
example.
1privatefuncprofileData(forlaunchOptions:[UIApplicationLaunchOpti\
2onsKey:Any]?)->[ProfileData]?{
3letfileUrl=launchOptions![UIApplicationLaunchOptionsKey.url]\
4as!URL
5returnprofileData(at:fileUrl)
6}
Thislooksfine.Right?We’recertainthatthedictionaryoflaunch
optionalsisn’tequaltonil,thattheUIApplicationLaunchOptionsKey.url
ispresent,andthatitsvalueisoftypeURL.
Itdoesn’tmatterhowcertainyouare,anoptionalshouldbetreatedwith
caution.Forcedunwrappingorforcedconversionisaskingfortrouble.As
Idiscussedinanearlierchapter,therearesituationsinwhichyoucan
usethe!operator,butdonotforcedunwrapanoptionaltoavoidaguard
oranifstatementorafewextralinesofcode.
Theupdatedexampleshowsyouhowtheguardstatementcanelegantly
andsafelyhandleoptionals.Theguardstatementtellsuswhatwe
expect,but,atthesametime,ithintsthatwemaynotgetwhatwe
expected.
1privatefuncprofileData(forlaunchOptions:[UIApplicationLaunchOpti\
2onsKey:Any]?)->[ProfileData]?{
3guardletlaunchOptions=launchOptionselse{
4returnnil
5}
6
7guardletfileUrl=launchOptions[UIApplicationLaunchOptionsKey.\
8url]as?URLelse{
9returnnil
10}
11
12returnprofileData(at:fileUrl)
13}
Ifyoufindyourselfusinga!insteadofan?,thenstopforamoment
andaskyourselfwhetherthere’sasaferalternative.
MonsterClasses
AndyMatuschakisagreatspeakerandaverygoodteacher.Heonce
gaveawonderfultalkattheRealmofficesaboutrefactoringview
controllers.Inthetalk,Andyillustratesthatviewcontrollersareoften
takingonfartoomanyresponsibilities.
SomeofusapplytheModel-View-Controllerpatternabittoostrictly.Did
youknowthatit’sfinetocreateclassesthatarenotmodels,views,or
controllers?
Somedevelopersevenarguethatyoushouldcreatefatmodelsand
skinnycontrollers.Whilethatmaybeabittoomuchresponsibilityforthe
modellayer,Iagreethatcontrollersshouldbeleanandlightweight.Of
course,it’seasytostuffbusinesslogicincontrollersandittakesabitof
extraworktorefactorcodethatcanbelonginaseparateclass.Butit’s
oftentherightchoice.
Byisolatingfunctionality,youputtheviewcontrollersofyourprojectona
dietandmakecodeeasiertoreuse.Whynotextractapieceof
functionalityinanObjective-CcategoryoraSwiftextension.
Iftheimplementationofaclassexceeds1000linesofcode,Iknowit’s
timeforaseriousroundofrefactoring.Canyouload1000linesofcodein
yourworkingmemory?That’swhatittakestoworkwithaclass.Ifyou
makechangestoaclass,youneedtoknowhowotherpartsareaffected
andthat’sonlypossibleifyouknowwhatthevariouspartsoftheclass
do.
MassiveMethods
Monsterclassesveryoftenharbormassivemethods.Fewthingsina
developer’slifeareasfrustratingasunittestingamethodthatspans
dozensanddozensoflines.AsImentionelsewhereinthebook,
functionsandmethodsshouldbefocusedandtothepoint.Afunctionor
methodshouldideallyhaveasingularfocus.
HelperMethods
Mostofmyviewcontrollershaveahandfultoadozenhelpermethods.
Thesehelpermethodsarefocusedandhelpothermethodsbethesame.
DotheviewDidLoad()methodsofyourviewcontrollersspandozensand
dozensoflines?That’sacodesmell.
Idiligentlytrytokeepmethodsshortandsuccinct.EveryviewcontrollerI
implementthathasanycomplexitytoithasasetupView()anda
updateView()method.Iusethesemethodstofactoranyview
configurationoutoftheviewDidLoad()methodintothesehelpermethods.
1//MARK:-ViewLifeCycle
2
3overridefuncviewDidLoad(){
4super.viewDidLoad()
5
6//SetTitle
7title=NSLocalizedString("root_view_title",comment:"RootView\
8Title")
9
10//SetupView
11setupView()
12
13//SetupNotificationHandling
14setupNotificationHandling()
15}
PropertyObservers
Configuringviewsisn’tmyfavoritepastime.Toremedythis,Ioftenadda
didSetpropertyobservertoanoutlettoconfigureitwhenit’sset.There
areseveralbenefits,oneofthembeingthatitkeepstheconfiguration
closetotheoutlet’sdeclaration.
1@IBOutletvarmessageLabel:UILabel!{
2didSet{
3messageLabel.numberOfLines=0
4messageLabel.font=UIFont.Namaste.lightRegular
5messageLabel.textColor=UIColor.Namaste.lightGray
6messageLabel.text=NSLocalizedString("root_message_no_profi\
7les",comment:"")
8}
9}
I’msureseveraldevelopersfrownwhentheyseethispatterninthewild.
WhileI’mnotsure,IbelieveIlearnedthistrickfromNatashaMurashev.
Creditwherecreditisdue.
AmbiguousMethodNames
Massivemethodsaren’tonlyhardtounittest,theyalmostalwayshave
namesthatmakelittleornosense.Becausemassivemethodsperforma
slewoftasks,it’sdifficulttonamethem.
Massivemethodsusuallyhavelongnamesthatdon’treflectthe
implementationortheyhaveavaguenamethatcouldmeananything.
Breakthemethodupintosmaller,focusedmethodsandgiveeacha
descriptivename.Thissmallchangeimmediatelyimprovesthetestability
ofmassivemethods.
IgnoringErrors
It’sgreattoseethaterrorhandlingistightlyintegratedintotheSwift
language.InObjective-C,it’seasytoignoreerrors,abittooeasyifyou
askme.Haveyoueverseensomethinglikethis?
1[managedObjectContextsave:nil];
Idon’tknowanydeveloperwhoenjoyserrorhandling,butifyouwantto
writecodethatworksandapplicationsthatcanrecoverwhenthingsgo
haywire,thenyouneedtoacceptthaterrorhandlingispartofthejob.
Ignoringerrorsalsomakesdebuggingmoredifficult.Puttingyourheadin
thesandisn’tthesolutionwhenthingsgowrong.Don’tworry,though.
Laterinthisbook,weexploreerrorhandlinginabitmoredetail.
Singletons
Singletonsaregreat.They’resousefulthatlessexperienceddevelopers
tendtooverusethem.Beenthere,donethat.I’mnotjokingwhenIsay
thatsingletonsaregreat.EventhoughIdon’tconsiderthesingleton
patternananti-pattern,sometimesitseemsasifdevelopershave
forgottenhowtopassanobjectbyreference.
Oneofthenegativesideeffectsofsingletonsistightcoupling.Overthe
years,Ihavecomeacrossprojectsthatwerelitteredwithsingletons,
singletonsreferencingothersingletons.Thiscanmakerefactoringa
nightmare.
Afterremovingthesingletonsfromaproject,it’snolongerintimidating,
anditlosessomeofitscomplexity.Bypassingobjectsbyreference,
evenifonlyoneinstanceisaliveatanyonetime,itbecomesmuch
clearerwheretheobjectisusedandwhatroleitplays.
Anotherbenefitofkeepingsingletonstoaminimumistesting.Singletons
maketestingmoredifficult.
There’snothingwrongwithpassingobjectsbyreference.Whenever
you’reabouttocreateasingleton,askyourselfwhetherpassingthe
objectbyreferenceisanoption.Thatshouldbeyourfirstchoice.Always.
StringLiterals
Stringliteralsaresmellybydefault.They’regreatinplaygrounds,buthow
oftendoyou,orshouldyou,usestringliteralsinaproject?Theonlyvalid
usecasesIcanthinkofarelocalization,constants,andlogging.
Iagreethatcreatingconstantsorenumsistedious,butitpaysoffinthe
longrun.Youavoidtypos,autocompletionkicksin,anditsignificantly
improvesmaintainability.
Thiscertainlyisn’tahardrulethatIapplytotheprojectsIworkon,butI
trytosticktoitasmuchaspossible.Ifthevalueofanobjectliteralis
usedinmorethanoneplace,it’sdefinedasaconstantorenumeration,
or,evenbetter,putinaconfigurationfile.
MyXcodecolorschemehighlightsstringliteralsinbrightred.WhenI’m
browsingthroughlinesandlinesofcode,thestringliteralsstandout
immediately.IfIseetoomuchred,it’stimeforaclean-up.
Stringliteralsarehighlightedinbrightred.
IsYourCodeSmelly
AsImentionedearlier,thegoalofthischapteristoreviewthecodeyou
write.HowcanIimprovethis?Whatsideeffectsdoesthis
implementationhave?ShouldIforcedunwrapthisoptional?Itrarelypays
offtotakeashortcut.
7ValueTypesandReferenceTypes
Whentalkingaboutobject-orientedprogramming,mostofusintuitively
thinkaboutclasses.InSwift,however,thingsareabitdifferent.While
youcancontinuetouseclasses,Swifthasafewothertricksupitssleeve
thatcanchangethewayyouthinkaboutsoftwaredevelopment.Thisis
probablythemostimportantshiftinmindsetwhenworkingwithSwift,
especiallyifyou’recomingfromamoretraditionalobject-oriented
programminglanguagelikeRubyorObjective-C.
What’stheFuss
Theconceptwetackleinthischapteristhedifferencesbetweenvalue
typesandreferencetypesor,putdifferently,passingbyvalueand
passingbyreference.
InSwift,instancesofclassesarepassedbyreference.Thisissimilarto
howclassesareimplementedinRubyandObjective-C.Itimpliesthatan
instanceofaclasscanhaveseveralownersthatshareacopy.
Instancesofstructuresandenumerationsarepassedbyvalue.Every
instanceofastructorenumhasitsownuniquecopyofdata.Andthe
sameappliestotuples.
Intheremainderofthischapter,Irefertoinstancesofclassesasobjects
andinstancesofstructsandenumsasvalues.Thisavoidsunnecessary
complexity.
AnExample
It’simportantthatyouunderstandtheaboveconceptsoletmeexplain
thiswithanexample.
1classEmployee{
2
3varname=""
4
5}
6
7varemployee1=Employee()
8employee1.name="Tom"
9
10varemployee2=employee1
11employee2.name="Fred"
12
13print(employee1.name)//Fred
14print(employee2.name)//Fred
Wedeclareaclass,Employee,andcreateaninstance,employee1.Weset
thenamepropertyofemployee1toTom.Wethendeclareanothervariable,
employee2,andassignemployee1toit.Wesetthenamepropertyof
employee2toFredandprintthenamesofbothEmployeeinstances.
Becauseinstancesofclassesarepassedbyreference,thevalueofthe
namepropertyofbothinstancesisequaltoFred.Doesthatmakesenseor
doestheresultsurpriseyou?
1structEmployee{
2
3varname=""
4
5}
6
7varemployee1=Employee()
8employee1.name="Tom"
9
10varemployee2=employee1
11employee2.name="Fred"
12
13print(employee1.name)//Tom
14print(employee2.name)//Fred
Inthesecondexample,wedeclareastructure,Employee,andrepeatthe
stepsofthefirstexample.Theoutputoftheprintstatementsisdifferent,
though.
Byreplacingclasswithstruct,theoutcomeoftheexamplechangesina
significantway.Aninstanceofaclass,anobject,canhavemultiple
owners.Aninstanceofastructhasoneowner.Whenaninstanceofa
structisassignedorpassedtoafunction,itsvalueiscopied.Aunique
instanceofthestructispassedinsteadofareferencetotheinstanceof
thestruct.
Themomentemployee1isassignedtotheemployee2variable,acopyof
employee1ismadeandassignedtoemployee2.Thevaluesofemployee1
andemployee2havenorelationtooneanotherapartfromthefactthat
theyarecopies.
BenefitsofValueTypes
Swiftusesvaluetypesextensively.Strings,arrays,dictionaries,sets,and
numbersarevaluetypesinSwift.That’snocoincidence.Ifyou
understandthebenefitsofvaluetypes,youautomaticallyunderstandwhy
thesetypesaredefinedasvaluetypesinSwift’sstandardlibrary.What
aresomeofthebenefitsofvaluetypes?
StoringImmutableData
Valuetypesaregreatforstoringdata.Andtheyareevenbettersuitedfor
storingimmutabledata.Assumeyouhaveastructthatstoresthe
balanceoftheuser’sbankaccount.Ifyoupassthebalancetoafunction,
thatfunctiondoesn’texpectthebalancetochangewhileit’susingit.By
passingthebalanceasavaluetype,itreceivesauniquecopyofthe
balance,regardlessofwhereitcamefrom.
Knowingthatavaluewon’tchangeisapowerfulconceptinsoftware
development.It’saboldpromiseand,ifusedcorrectly,onethatvalue
typescankeep.
ManipulatingData
Valuetypesusuallydon’tmanipulatethedatatheystore.Whileitisfine
andusefultoprovideaninterfaceforperformingcomputationsonthe
data,it’stheownerofthevaluethatmanipulatesthedatastoredbythe
value.
Thisresultsinacontrolflowthatistransparentandpredictable.Value
typesareeasytoworkwithand,anothergreatbenefit,theybehave
admirablyinmultithreadedenvironments.
Whyisthat?IfyoufetchdatafromaremoteAPIonabackgroundthread
andpassthedata,asavalue,fromthebackgroundthreadtothemain
thread,acopyismadeandsentofftothemainthread.Modifyingthe
originalvalueonthebackgroundthreadwon’taffectthevaluethat’s
beingusedonthemainthread.Clean,simple,andtransparent.
WhentoUseValueTypes
WhileIhopeI’veconvincedyoutostartusingvaluetypesmoreoften,
they’renotagoodfitforeveryscenario.Valuetypesaregreatforstoring
data.Ifyoupassaroundthebalanceofsomeone’saccountinyour
application,youshouldn’tbeusingaclassinstance.Whatyouaredoing
ispassingaroundacopyofthecurrentbalanceoftheaccount.
Butifyouneedtopassaroundtheaccountitself,thenyouwanttomake
suretheobjectsthathaveareferencetotheaccountareworkingwiththe
sameaccount,thesameinstance.Ifthenameoftheaccountholder
changes,youwanttheotherobjectsthathaveareferencetotheaccount
toknowaboutit.
Valuetypesandreferencetypeseachhavetheirvalueanduse.Itwould
beunwisetochooseoneovertheother.AndyMatuschakhasaclear
stanceonthebenefitsofvaluetypesandreferencetypesinsoftware
developmentandhasgivenseveralpresentationsonthetopic.Andy
describestheobjectsofanapplicationasalayerthatoperatesonthe
valuelayer.That’sagreatwaytoputit.
Thinkofobjectsasathin,imperativelayerabovethepredictable,
purevaluelayer.—AndyMatuschak
8CatchingErrors
IwasthrilledtofindoutthaterrorhandlingisbuiltintotheSwiftlanguage.
AsIwroteearlier,it’stooeasytoignoreerrorsinObjective-C.Youcan
stillignoreerrorsinSwiftifyouchoosetogothatroute,butyouneedto
beexplicitaboutit.
Thischapterwon’trepeatwhatTheSwiftProgrammingLanguagehasto
sayabouterrorhandlinginSwift.Instead,I’dliketotaketheopportunity
togiveyousometipsabouterrorhandling.Whenshouldyouhandle
errors?Shouldyoualwaysnotifytheuserifsomethinggoeshaywire?
Whereshouldyouhandleerrors?
WhenShouldYouHandleErrors
Theshortanswerissimple.Always.Theanswerismorenuanced,
though.Theremainderofthischapterzoomsinonthewhen,thehow,
andthewhy.
WhereShouldYouHandleErrors
ErrorhandlinginSwiftisintuitiveandflexible.Youcanpropagateerrors
andhandlethemwhereitfeelsappropriate.Thequestionisthen,“Where
isitappropriatetohandleerrors?”TheruleIapplyinmostscenariosis
simpleandeasytoadopt.Wheneveranobjectperformsanoperation
andanerroristhrown,theerrorishandledbytheobjectthatstill
understandswhattheerrorisabout.LetmeexplainwhatImeanbythis
withanexample.
Afewdaysago,Iwasimplementingreceiptvalidationinoneofmy
applications.Iwon’tgointothefinerdetails,butsufficetosaythatthe
applicationsendsthereceipttoaremoteserver,whichvalidatesthe
receipt,andreturnsaresponsetotheapplication.Theresponseisa
JSONobjectthatisdeserializedusingJohnSundell’sfantasticUnbox
library.
Asyoucanimagine,thingscangowronginseveralphasesofthe
operation.Whichobjectsshouldhandlewhicherrors?Theobjectthat
deserializestheJSONresponseshouldhandleanyerrorsthatarethrown
bythedeserializationoperation.Itisn’tusefultopropagatetheseerrors
sincetheobjectsupstreamwon’tunderstandtheerrorsand,more
importantly,don’tneedtoknowaboutthem.
Ifyoudowanttonotifytheobjectsupstream,thenIsuggestdefiningand
throwingacustomerror.Thiscanbeveryusefultosummarizearangeof
errorsthatanupstreamobjectcanunderstandandrespondto.
AnotherexampleinvolvesCoreData.Ialwaysuseadedicatedobjectto
managetheapplication’sCoreDatastack.Thisobjecthandlesanyerrors
thatarethrownbyasaveoperation.Ifotherobjectsneedtoknowabout
afailedsaveoperation,acustomerroristhrownbytheCoreData
manager.
Objectsthatareunawareofthepersistencelayer,CoreDatainthis
example,won’tknowhowtohandletheerrorsthatamanagedobject
contextcanthrow.Theycanatbestcheckifanyerrorsarethrownbya
managedobjectcontext.Itusuallydoesn’tmakesensetomakeanobject
handleerrorsitdoesn’tunderstandordoesn’tknowhowtorespondto.
NotifyingtheUser
DevelopersnewtoprogrammingorSwiftdevelopmentusuallychoose
oneoftwostrategieswhenhandlingerrors.Theeitherignoreerrors
altogetherortheyprintanyerrorsthatpopuptotheconsole.Neither
approachisideal,butthelattergroupisatleastinformedwhen
somethinggoeswrong.
UserAction
Manyoperationscangowrongorbackfire.Whenshouldyounotifythe
user?Let’sstartwiththemostobviousscenario.Whentheuserperforms
anactionthatbackfires,sheshouldbenotifiedthatheractionwas
unsuccessful.
Isthisahardrule?No.IftheuserlikesapostonFacebookandtheAPI
requestwasunsuccessful,youmayonlywanttonotifyherifshe’sstillon
thepagesheliked.IfthefailedAPIrequestistheresultofapoornetwork
connection,thenthatwouldmeantheuserisnotifiedafterthenetwork
requesttimedout.Thatmaybetoolatefortheusertomakesenseofthe
error.
BackgroundOperations
Mostapplicationsperformbackgroundoperationstheuserisn’t,and
shouldn’tbe,awareof.Examplesincludedatasynchronizationand
receiptvalidation.Shouldyounotifytheuserifyourapplicationisunable
tosynchronizetheuser’sdatabase?Theanswerisalmostalwaysno.
Thisdoesn’tmeantheusershouldn’tbeinformed,though.
WhatIlikeabout1Password’smobileapplication,forexample,isthe
currentstateofthesynchronizationprocessaswellasthelasttimethe
applicationsynchronized.
1Password
Ifsomethinggoesfunky,theusercanreadaboutitinthesettingsofthe
application.
AvoidCrypticMessages
I’msureyou’veseenerrormessageswithacrypticmessageorerror
code.Youshouldavoidthisatanycost.Itdoesn’thelptheusertoseean
alertwithanHTTPstatuscode.Infact,itmayconcernandannoythe
user.
MonitoringApplicationHealth
Thedownsideofmobileapplicationsisthatyoucan’teasilymonitoryour
application’sperformanceorhealthinrealtime.Thisisverydifferentfor
webapplications.
Howareyougoingtostayinformedaboutyourapplication’sperformance
andhealththemomentit’sinthehandsofyourcustomers?Areyou
goingtowaituntilyourcustomersemailyou?Wecoverthisinmore
detaillaterinthebook.Fornow,Iwanttoemphasizethatyouneedeyes
onyourapplicationfromthemomentyourapplicationisinproduction.
Howoftendoesyourapplicationcrash?Whicherrorsoccurmostoften?
Whatisthecauseoftheseerrors?
Don’tIgnoreThem
Ithinkthatknowinghow,when,andwheretohandleerrorsiswhatstops
manyinexperienceddevelopersfromhandlingerrorsproperly.Thereis
noclear-cutrecipeforerrorhandlingandthatcanbefrustrating.The
guidelinesIpresentinthischaptershouldgiveyouabetterideawhereto
startandIhopeit’sclearthatyoushouldn’tignoreerrors.
9UsingFatalErrorstoWriteElegantSwift
Speakingoferrors,afewmonthsagoIstumbledonadiscussioninthe
thoughtbotguidesabouttheuseoffatalerrorsinSwift.Itseemsevery
developerhasanopinionaboutfatalerrorsandaconsensushasn’tbeen
reachedyetintheSwiftcommunity.TheonlymentioninTheSwift
ProgrammingLanguageisinthesectionthatdiscussestheguard
statementandearlyexit.
WhenIfirstencounteredthefatalError(_:file:line:)function,it
remindedmeoftheabort()function.Eventhoughbothfunctionscause
theimmediateterminationofyourapplication,the
fatalError(_:file:line:)functionisdifferentand,inthecontextofSwift,
it’smoreuseful.
WhattoDoWhenYouDon’tKnowWhattoDo
EversinceIstartedworkingwithSwift,I’vebeenstrugglingwiththe
implementationofthetableView(_:cellForRowAt:)method.Ifyouthink
thatsoundssilly,thentakealookatthefollowingexample.
1overridefunctableView(_tableView:UITableView,cellForRowAtindex\
2Path:IndexPath)->UITableViewCell{
3ifletcell=tableView.dequeueReusableCell(withIdentifier:Sett\
4ingsTableViewCell.reuseIdentifier,for:indexPath)as?SettingsTable\
5ViewCell{
6//ConfigureCell
7cell.textLabel?.text="SomeSetting"
8
9returncell
10
11}else{
12returnUITableViewCell()
13}
14}
ThereareseveralvariationsoftheaboveimplementationandI’vetriedall
ofthem.Theideaissimple.Weexpectaninstanceofthe
SettingsTableViewCellclassifweaskthetableviewforacellwiththe
reuseidentifieroftheSettingsTableViewCellclass.Becausethe
dequeueReusableCell(withIdentifier:for:)methodreturnsa
UITableViewCellinstance,weneedtocasttheresulttoaninstanceofthe
SettingsTableViewCellclass.
Thisisinconvenientsincewealwaysexpecttoreceivea
SettingsTableViewCellinstanceifweaskthetableviewforacellwiththe
reuseidentifieroftheSettingsTableViewCellclass.Wecouldusetheas!
operatorinsteadoftheas?operator,butthatisn’tasolutionIfeel
comfortablewith.RememberthatIavoidtheexclamationmarkwhenever
Ican.
Ifforsomereason,somethinggoeswrong,wereturnaUITableViewCell
instancefromthetableView(_:cellForRowAt:)method.Butthatshould
neverhappen.Right?
Whilethisisfineandnecessarytomakesurewereturna
UITableViewCellinstancefromthetableView(_:cellForRowAt:)method,I
hopeyoucanseethatwe’reimplementingaworkaroundforascenario
wedon’texpect,ascenariothatshouldneveroccur.
GuardingAgainstUnexpectedEvents
EverytimeIimplementtableView(_:cellForRowAt:)Iwonderifthere’sa
betterapproach.Andthereis.Weneedtoguardagainsttheeventthat
thetableviewhandsusaUITableViewCellinstancewedon’texpectand,
ifthathappens,wethrowafatalerror.
1overridefunctableView(_tableView:UITableView,cellForRowAtindex\
2Path:IndexPath)->UITableViewCell{
3guardletcell=tableView.dequeueReusableCell(withIdentifier:S\
4ettingsTableViewCell.reuseIdentifier,for:indexPath)as?SettingsTa\
5bleViewCellelse{
6fatalError("UnabletoDequeueReusableCell")
7}
8
9//ConfigureCell
10...
11
12returncell
13}
Theapplicationcrashesifafatalerroristhrown.Whyisthisbetter?This
isabettersolutionfortworeasons.
UnexpectedState
Iftheapplicationrunsintoascenarioinwhichafatalerroristhrown,we
communicatetotheruntimethattheapplicationisinastateitdoesn’t
knowhowtohandle.
Inthefirstexample,thesolutionwastoreturnaUITableViewCell
instance.Doesthatsolvetheproblem?No.Theapplicationignoresthe
situationandavoidscausinghavocbyreturningaUITableViewCell
instance.Theapplicationavoidsdealingwiththeunexpectedstateit’s
gottenitselfinto.
FindingandFixingtheBug
Iftheapplicationrunsintoastatewedidn’tanticipate,itmeansabughas
slippedintothecodebase.Iftheapplicationisterminatedduetoafatal
errorbeingthrown,wehaveworktodo.Itmeansthatweneedtofindthe
bugandfixit.
Theabovesolution,usingaguardstatementandthrowingafatalerror,is
asolutionI’mveryhappywith.Itavoidstheobsoleteifstatementofthe
firstimplementationofthetableView(_:cellForRowAt:)methodandit
correctlyhandlesthesituation.Theresultisamuchmoreelegant
implementationofthetableView(_:cellForRowAt:)method.Anditadds
claritytotheimplementationofthetableView(_:cellForRowAt:)method.
UseFatalErrorsSparingly
Thisdoesn’tmeanthatyouneedtousefatalerrorswheneveryouwant
toavoiderrorhandlingortheapplicationentersastatethat’shardto
recoverfrom.Iusefatalerrorsonlywhentheapplicationcanenterina
stateitwasn’tdesignedfor.Takealookatthefollowingexample.
1importFoundation
2
3enumSection:Int{
4
5casenews
6caseprofile
7casesettings
8
9vartitle:String{
10switchself{
11case.news:returnNSLocalizedString("section_news",comment\
12:"news")
13case.profile:returnNSLocalizedString("section_profile",c\
14omment:"profile")
15case.settings:returnNSLocalizedString("section_settings",\
16comment:"settings")
17}
18}
19
20}
21
22structSettingsViewViewModel{
23
24functitle(forsection:Int)->String{
25guardletsection=Section(rawValue:section)else{
26fatalError("UnexpectedSection")
27}
28returnsection.title
29}
30
31}
Thetitle(for:)methodoftheSettingsViewViewModelstructdoesn’t
expectavalueitcan’tusetoinstantiateavalidSectioninstancewith.If
thevalueofthesectionparameterisinvalid,itwouldn’tknowwhattodo.
Inthatscenario,afatalerroristhrown.
Iftheapplicationdoesenterthatscenario,itmeansyoumadealogical
mistakeandit’syourtasktofindoutwhyandhowitcanberesolved.
ClarityandElegance
TheuseofthefatalError(_:file:line:)functionhasmademycode
morereadablewithoutcompromisingtheinherentsafetyoftheSwift
language.ItaddsclaritytothecodeIwriteandSwiftregainsits
elegance.Giveitatryandletmeknowifyoulikeit.
PART3:PROJECTS
1ABrandNewProject
TherearemanytutorialsandcoursesavailabletogetstartedwithSwift
development.Theissuewithmostofthemisthatthey’refocusedona
specifictopic,ignoringotheressentialaspectsofSwiftdevelopment.
Whatteachersoftenforgetisthatdevelopersnewtoalanguage,a
framework,oratechnology,arevery,veryreceptivetonewinformation.
Thisincludesbestpractices,but,unfortunately,italsomeanslessgood
practicesorevenbadhabits.
Inthischapter,I’dliketowalkyouthroughthestepsItakewhensetting
upabrandnewprojectinXcode9.Byfollowingthestepslaidoutinthis
chapter,yousetyourselfupforasuccessfulproject.Letitsinkinand
tweakittoyourownpreferences.
Step1:SettingUptheProject
Iunderstandthatitcanbeusefultoexperimentfromtimetotime,butI
alwaysusetheSingleViewApptemplatefornewprojects.Itgivesme
anapplicationdelegate,aviewcontroller,andastoryboard.Idon’tneed
anythingelsewhenI’mstartinganewproject.
ChoosingaTemplate
GivetheprojectasensiblenameandcheckIncludeUnitTestsand
IncludeUITests.InevercheckUseCoreDataforproductionprojects.
ConfiguringtheProject
WhileitmayseemconvenienttocheckCreateGitrepositoryonmy
Mac,Idon’trecommendthis.Whyisthat?Theprojectfirstneedsabitof
housekeepingbeforeI’mreadyformyfirstcommit,Xcodedoesn’t
automaticallyadda.gitignorefile,andIdon’tlikeXcode’sfirstcommit
message.Thelatterisobviouslyanitpickydetail.
ChoosingaLocationfortheProject
Step2:OrganizingtheProject
Ialwaysstartbycleaninguptheproject.Thissimplymeansputtingthe
applicationdelegateinaseparategroup,organizingtheviewcontrollers,
andmakingsurenofilesliveattherootoftheproject.Smallprojects
don’thavetheproblemofbecomingcluttered,butlargeprojectsdo,and
veryquicklyatthat.
Theideaissimple.ThisistheprojectXcodehascreatedforus.
BeforeOrganizingtheProject
Andthisistheprojectafteraddingsomestructure.Laterinthisbook,I
takeacloserlookatorganizingaprojectinXcodeandhowtousegroups
andfolderstokeepeverythingniceandtidy.
AfterOrganizingtheProject
Step3:AddingaREADME.md
Evenifyou’reworkinginateamofone,itcanbeveryhelpfulto
documentyourprojectandit’ssomethingIstronglyrecommend.Ifyou’ve
everbrowsedGitHub,thenyouprobablyknowthatputtingafilenamed
README.mdattherootoftheprojectisagoodfirststep.Markdownisa
wonderfulmarkuplanguageandit’sidealforthispurpose.Thisisthe
README.mdfileIusuallystartwith.
1#ProjectName
2##Author:BartJacobs
3###Description:Loremipsumdolorsitamet,consecteturadipiscing\
4elit.Curabituracdolorjusto,actempusleo.Etiampulvinarerosa\
5tlectussollicitudinscelerisque.Aliquameratvolutpat.Suspendiss\
6eeuerosnonelitblanditsuscipit.Morbiscelerisqueeuismodtempu\
7s.
8
9###Dependencies:
10-Unbox
11-RxSwift
12-RxCocoa
13-Reveal
Ifyou’reworkinginateam,thenIrecommendputtingmoretimeand
effortintodocumentingtheproject.Idiscussthisinmoredetailelsewhere
inthebook.
Step4:BuildandRun
BeforeIputtheprojectundersourcecontrol,Imakesureitbuildsand
runswithoutwarningsanderrors.Afterupdatingtheproject’sstructure,it
sometimeshappensthatXcodecannolongerfindsomeofthefilesyou
moved.Weneedtofixthisbeforeweputtheprojectundersource
control.AsImentioninthechapteronsourcecontrol,youshouldonly
makeacommitiftheprojectbuildssuccessfully,withoutwarningand
errors.
Step5:Addinga.gitignore
Beforeweputtheprojectundersourcecontrol,weneedtoadda
.gitignorefile.Ifyou’reunfamiliarwithGitandthepurposeofa
.gitignorefile,thenIrecommendreadingmoreaboutthisfantastic
versioncontrolsystem.
The.gitignorefileattherootoftheprojectdefineswhichfilesneedtobe
keptundersourcecontrolandwhichfilescanbeignoredhencethename
ofthefile.Thisiswhatthe.gitignorefileofmostofmyprojectslooks
like.
1#########################
2#**.gitignore**fileforXcode4/OSXSourceprojects
3#
4#NB:ifyouarestoring"built"products,thisWILLNOTWORK,
5#andyoushoulduseadifferent**.gitignore**(ornoneatall)
6#ThisfileisforSOURCEprojects,wheretherearemanyextra
7#filesthatwewanttoexclude
8#
9#Forupdates,see:http://stackoverflow.com/questions/49478/git-ign\
10ore-file-for-xcode-projects
11#########################
12
13#####
14#OSXtemporaryfilesthatshouldneverbecommitted
15
16.DS_Store
17*.swp
18profile
19
20
21####
22#Xcodetemporaryfilesthatshouldneverbecommitted
23#
24#NB:NIB/XIBfilesstillexistevenonStoryboardprojects,sowew\
25antthis...
26
27*~.nib
28
29
30####
31#Xcodebuildfiles-
32#
33#NB:slashontheend,soweonlyremovetheFOLDER,notanyfiles\
34thatwerebadlynamed"DerivedData"
35
36DerivedData/
37
38#NB:slashontheend,soweonlyremovetheFOLDER,notanyfiles\
39thatwerebadlynamed"build"
40
41build/
42
43
44#####
45#Xcodeprivatesettings(windowsizes,bookmarks,breakpoints,cust\
46omexecutables,smartgroups)
47#
48#Thisiscomplicated:
49#
50#SOMETIMESyouneedtoputthisfileinversioncontrol.
51#Appledesigneditpoorly-ifyouuse"customexecutables",theya\
52re
53#savedinthisfile.
54#99%ofprojectsdoNOTusethose,sotheydoNOTwanttoversionc\
55ontrolthisfile.
56#..butifyou'reinthe1%,commentouttheline"*.pbxuser"
57
58*.pbxuser
59*.mode1v3
60*.mode2v3
61*.perspectivev3
62#NB:also,whitelistthedefaultones,someprojectsneedtouse\
63these
64!default.pbxuser
65!default.mode1v3
66!default.mode2v3
67!default.perspectivev3
68
69
70####
71#Xcode4-semi-personalsettings,oftenincludedinworkspaces
72#
73#Youcansafelyignorethexcuserdatafiles-butdoNOTignorethe\
74filesnexttothem
75#
76
77xcuserdata
78
79####
80#XCode4workspaces-moredetailed
81#
82#Workspacesareimportant!TheyareacorefeatureofXcode-don't\
83excludethem:)
84#
85#Workspacelayoutisquitespammy.Forreference:
86#
87#(root)/
88#(project-name).xcodeproj/
89#project.pbxproj
90#project.xcworkspace/
91#contents.xcworkspacedata
92#xcuserdata/
93#(yourname)/xcuserdatad/
94#xcuserdata/
95#(yourname)/xcuserdatad/
96#
97#
98#
99#Xcode4workspaces-SHARED
100#
101#ThisisUNDOCUMENTED(google:"developer.apple.comxcshareddata"-\
1020results
103#Butifyou'regoingtokillpersonalworkspaces,atleastkeepthe\
104sharedones...
105#
106#
107!xcshareddata
108
109####
110#XCode4build-schemes
111#
112#PRIVATEonesarestoredinsidexcuserdata
113!xcschemes
114
115####
116#Xcode4-Deprecatedclasses
117#
118#Allegedly,ifyoumanually"deprecate"yourclasses,theygetmove\
119dhere.
120#
121#We'reusingsource-control,sothisisa"feature"thatwedonot\
122want!
123
124*.moved-aside
125
126#CocoaPods
127/Pods
AsyoucanseeitincludesreferencestoXcode4,whichshowsyouhow
longI’vebeenusingthis.gitignorefile.Itworkswellforme.Whilemost
ofthecontentsareeasytounderstand,thereareafewdetailsthatare
worthpointingout.
Atthebottom,youcanseeareferencetoCocoaPods,thedependency
managerofmychoice.The/PodsentrymeansthatIignoretheentire
Podsdirectory.Thisisapersonalchoiceandithasitsprosandcons.
I’veneverrunintothecons,whichiswhyI’vestuckwiththisoption.
WhileignoringthePodsdirectoryisfineanduptoyoutodecide,you
shouldneverignorePodfile.lockor,ifyou’reusingCarthage,
Cartfile.lock.Astheextensionofthefileimplies,alockfilelocksthe
currentconfiguration.Aproject’sPodfileorCartfiledescribesthe
project’sdependencies,optionallyspecifyingtheversionthatshouldbe
used.Theproject’sPodfile.lockorCartfile.locklocksthecurrent
configuration,includingtheversionthatisusedbytheproject.
Puttinglockfilesundersourcecontrolisespeciallyimportantifyou’re
workinginateam.Whenateammemberchecksouttherepositoryand
installstheproject’sdependenciesbyrunningpodinstallorcarthage
bootstrap,youwanttomakesurethey’reincludingthecorrectversionof
eachdependency.
The.gitignorefilealsodefinesthatIignoreanypersonalpreferences
andsettings.Thisisrecommendedforteams.Youdon’twanttoclutter
therepositorywiththepreferencesofeveryteammemberthatworkedon
theproject.
Tobeclear,Ididn’tcreatethis.gitignorefilefromscratch.Idon’trecall
whereIpickeditup,butit’simportanttobecriticalofthingsyoupickup
fromelsewhere.Makesureyouunderstandeverylineofthe.gitignore
fileyouuseinyourprojects.
Step6:PuttingtheProjectUnderSourceControl
ThemostpopularversioncontrolsystemintheCocoaandSwift
communitiesisGit.It’sawonderfulpieceofsoftwarewithmanyfeatures
andit’seasytogetstartedwith.Thisbookwon’tcoverthedetailsofGit,
butthereareplentyofresourcestogetuptospeedquickly.Ireferencea
fewoftheminthechapteronsourcecontrol.
WhenIwrotemyfirstlinesofcodemanymoonsago,Ididn’tknowabout
sourcecontrolanddiscoveringGitwasatruerevelation.Itwasoneof
thoseahamoments.Itfeltincredible.
It’ssurprisingtoseethattherearestilldevelopersthatdon’tuseanytype
ofsourcecontrol.Ifthat’syou,don’tbeembarrassed.Buttakeamoment
tolearnthebasicsofGit(oranyotherversioncontrolsystem)andtake
yourworkseriously.Youdon’twanttoloseanyworkbynotusingsource
control.
ThestepsItaketoputtheprojectundersourcecontrolarealwaysthe
same.Takealookatthefollowingcommands.That’sallittakestoget
startedwithGit.
1gitinit
2gitadd.
3gitcommit-m"Projectsetup"
Step7:PushingtheProjecttoGitHub
IverymuchenjoyusingGitHuband,tomakesuremyworkissafe,I
createaprivaterepositoryandpushtheprojecttoGitHub.Youcanuse
othersolutionsaswell,suchasBitbucketorGitLab.Onceyou’vecreated
therepositoryonGitHub,youonlyneedtoadditasaremoteandpush
therepository.
1gitremoteaddorigin<URL>
2gitpushoriginmaster
Step8:OptionalSteps
Youcantakeitafewstepsfurtherand,ifyou’reworkinginacompany,
thatmaybenecessary.ThesestepsusuallyincludeaddingaGemfile,
settingupcontinuousintegrationorcreatingaprojectinamanagement
tool.Thesestepsareoptional,though.
2ProjectStructure
TheapplicationtemplatesthatshipwithXcodearen’tthebestexamples
fordevelopersnewtoCocoadevelopment.AnewprojectinXcodeisn’t
structuredinanywayandtheprojectfolderondiskisn’teither.Thisisn’t
anapproachthatscalesandit’snotsomethingIcanrecommend.
Oneofthesubtledetailsstudentsappreciateaboutmybooksand
coursesisthattheyseewhataproductionprojectcanlooklike.Cannot
should.Ibelieveit’simportanttosticktoasetofguidelinestomakesure
youintroduceconsistencyandstructureintoyourprojects.
That’sprobablywhatIappreciatedmostwhenIcreatedmyfirstRubyon
Railsapplication.DavidHeinemeierHanssonemphasizesthatRubyon
Railsisanopinionatedframeworkprovidingsensibledefaults.Suchan
approachhasitsprosandcons.AdefiniteupsideisthataRubyonRails
applicationexpectsaparticularprojectstructure.Developersnewto
RubyonRailslikethis,butIcanimaginethatmoreexperienced
programmersdeveloptheirownopinionsovertime.
I’msureyouagreethatanystructureisbetterthannostructure.The
approachIusehasevolvedovertheyears.Forexample,whenIstarted
toadopttheModel-View-ViewModelpatterninmyprojects,Imadeafew
tweakstomyprojects’structure.That’sfine.Thecoreideaistobe
consistentandtohaveaprojectstructurethatworksforyouandyour
team.
AnExample
TheprojectsIincludeinmycoursesandbooksarerelativelybasic
comparedtotheproductionprojectsIworkon.Forthatreason,I’dliketo
giveyouapeekbehindthescenesofoneofmyrecentprojects.Every
projectIcreateandworkonadoptsthisprojectstructure.Itworksforme,
butIunderstandthatothersolutionsworkequallywell.Rememberthat
consistencyiskey.
Aprojectstructurethatworks.
AsIwroteinthepreviouschapter,thefirstthingIdowhenIcreateanew
projectinXcodeisrefactortheproject’sstructure.Iputtheapplication
delegateinitsowngroupandIcreateagroupnamed,ViewControllers,
forthemodulesoftheapplication.Forme,amoduleisnothingmorethan
ascreenfulofcontentorareusableuserinterface.
ViewControllers
I’mafanofstoryboardsandIputthestoryboardsoftheprojectina
separatefolder.IaggressivelyusestoryboardreferencestomakesureI
don’tendupwithonelargestoryboardthat’sslowtoloadanddifficultto
manage.
Storyboards
EverythingrelatedtoCoreDataisthrowninaseparategroup.This
includesthedatamodelandtheextensionsfortheNSManagedObject
subclasses.
CoreData
Ialsocreateaseparategroupforextensions,protocols,genericmodels,
andmanagers.Itrytoavoidhavinggroupsthatarenamed
MiscellaneousorGeneral.Thisdoesn’thelpmeorganizemyprojects
anditmakesfindingfilesinefficient.
AgroupnamedResourcescontainstheproject’sresources,suchas
assets,audiofiles,andlocalizationfiles.NoticethatIcreatesubgroupsto
keepeverythingniceandtidy.
Resources
ThegroupnamedUIKitcontainssubclassesofUIKitcomponents.
Everythinghasitsplaceinmyprojects.
UIKitSubclasses
ThisprojectalsousestheModel-View-ViewModelpatternandIhavea
separategroupforgenericviewmodels,viewmodelsthatareused
throughouttheproject.Theprojectalsomakesheavyuseofoperations.
TheOperationsubclassesarelocatedinagroupnamedOperations.
Thetarget’sInfo.plistfileislocatedinagroupnamedSupportingFiles.
ViewControllers
TheViewControllersgroupissplitupintoseveralsubgroups,onefor
eachmoduleoftheapplication.Thissplitisalmostalwaysspecifictothe
project.Useyourcommonsenseandseewhatworksbestforyour
project.
Everymodulecontainssubgroupsfortheviewcontrollersofthatmodule
andsuchasubgroupusuallycontainsseveralsubgroups,suchas
protocols,viewmodels,tableviewcells,andcollectionviewcells.Thisis
veryoftenspecifictotheproject.
TestTarget
Thetesttargetisorganizedabitdifferentlyforobviousreasons.Agroup
namedSupportingFilescontainsthetarget’sInfo.plist.Icreate
separategroupsforthetestcases,theextensionsIuseonlyintheunit
tests,andIalsocreateagroupforstubs.
UIKitSubclasses
ItfrequentlyhappensthatIcreatemockandotherhelpertypes.These
arealsolumpedtogetherinseparategroups,MocksandHelpers
respectively.
OnDisk
PriortoXcode9,agroupinXcode’sProjectNavigatordidn’tcorrespond
withafolderondisk.Thishasfinallychanged.InXcode9,agroupby
defaultcorrespondstoafolderondisk.Thismeansthattheproject
structureyoucreateinXcodemoreorlesscorrespondstoafolder
structureondisk.
Ifyou’reusinganearlierversionofXcode,Istronglyrecommendthatyou
manuallycreateafolderforeverygroupyoucreateinXcode’sProject
Navigator.Thisistedious,butit’swellworththeinvestment.Anditisn’t
difficult.
YoucreateagroupintheProjectNavigatorandcopythenameofthe
group.OpentheFileInspectorontheright,clickthefoldericoninthe
Locationsection,andcreateanewfolderwiththesamenameasthe
groupintheFinderwindowthatappears.Choosethenewlycreated
folderandclickChoosetolinkthegrouptothefolder.Anyfilesorother
groupsthatyouaddtothegroupinXcodeareautomaticallyaddedtothe
folderthat’slinkedtothegroup.
WhatDoIGain
StickingtoaprojectstructuremakesiteasiertofindwhatI’mlookingfor,
butitalsoallowsmetofocusonwhatmatters,thatis,thecodethatI
write.FocusisatopicImentionalotinthisbookbecauseit’sessentialif
youwanttogetmeaningfulworkdone.Anorganizedprojectthatsticksto
astructurethatmakessenseisonelessdistractiontoworryabout.
Tools
Thereareseveraltoolsandscriptsthathelpyouwithorganizingyour
projects.Thebestknowntoolisliftoff,createdbythefolksatthoughtbot.
It’sacommandlinetoolthatallowsdeveloperstoquicklycreateanew
Xcodeprojectthatstickstoapredefinedprojectstructure.
Thiscanbeusefulifyou’reworkinginateamandeveryprojectneedsto,
andshould,usethesameprojectstructure.
Caveats
Thisprojectstructureworksformanyprojects,butthereareafew
caveats.Whathappensifyourprojectmanagerorthedesigner
introducesmajorchanges?Insuchasituation,youneedtomake
changestothestructureofyourproject.That’sthedownside.The
questioniswhetherthisisnecessaryandwarranted.Shouldn’tthe
developerstartdevelopingoncethedesignandfeaturesetisagreedon?
3ProjectHygiene
Inthepreviouschapter,Iwroteaboutstructuringtheprojectsyouwork
on.Thisappliestoeverysoftwareproject.WhatIdidn’tdiscussinthe
previouschapterisprojecthygiene.Whatshouldbekeptundersource
control?Whatdoyoudowitholdfilesandassets?
ProjectsEvolve
Asaprojectgrowsandages,morestuffmakesitswayintothe
repository.Thatisn’taproblembecauseit’sinevitable.Fortunately,the
projectisundersourcecontrol.You’reusingsourcecontrol.Right?
WheneverIinheritanexistingproject,Istartbyexploringtheproject’s
repositoryanditshistory.You’dbesurprisedbywhatIsometimes
discoverinprojects.Twothingsthatstandout,though,obsoletefilesand
filesthatshouldn’tbekeptinarepository.
ObsoleteFiles
Fromthemomentyounolongerneedoruseafile,deleteit.It’sthat
simple.Somedevelopersarereluctanttodeletestuffandcleanupa
project.Theyusuallyhaveaclearmotivation.It’seitherlazinessorthe
fearthattheymightneeditlater.Someday.
Goodprogrammersarelazy,butthisisn’tthetypeoflazinessthatthe
adageisreferringto.Thisissloppinessthatyoushouldavoid.Ifyou’rea
teamlead,makesureyouavoidthistypeofbehaviorinyourteam.
Projecthygieneisjustasimportantastakingyourcartotheshopevery
sooften.
Thefearsomedevelopershavewhentheyneedtodeleteafileis
unwarrantedifyou’reembracingsourcecontrol.Theideaunderlying
sourcecontrolisexactlywhyyoudon’tneedtobeafraidtoexperimentor
deletestuff.Trustyourversioncontrolsystem,makesureyouhave
backupsofyourrepository,andhitthedeletebuttonwhensomething’s
nolongerneeded.
Comments
Thesameappliestocomments.Commentsaregreat.Ilovecomments,a
bittoomuchaccordingtosomepeople.Butcommentsshouldn’tbeused
tocommentsomethingout,commitit,andsaveitforlater.Ifachunkof
codeisnolongerused,thendeleteit.Shouldyouneeditlater,then
sourcecontrolisthereforyou.
WheneverIseeapieceofcodecommentedout,awarningbellgoesoff
inmyhead.Cleanitupandcommitittotherepository.Seriously.
Embracesourcecontrolandlearntotrustit.
Documentation
Keepingdocumentationuptodatecanbechallenging.I’mnotawareofa
infalliblesolutiontothisproblem.Thatsaid,makesureyouregularly
updatethedocumentationofyourprojects.Takealookatthe
documentationandmakesurerecentchangesarereflectedinthe
documentation.
DidyouswitchfromCocoaPodstoCarthage?Thatmeansyouprobably
needtoupdatetheproject’sREADME.IstherestillaPodfileatthe
project’sroot?AndwhataboutthePodsproject?Obsoleteconfiguration
filesaremorecommonthanyouthink.Didsomeoneexperimentwitha
commandlinetoolthatgeneratedaconfigurationfileanddidn’tbotherto
removingitwhentheynolongerneededit?Ithappens.
ThebeststrategythatIknowoftokeepdocumentationuptodateis
surprisinglysimple.Itworksbestifit’smadeexplicitbyturningitintoa
policyorguideline.Wheneveryoumakeachangethatcontradictsthe
documentation,it’syourtasktoupdatethedocumentation.Ifit’spossible,
updatethedocumentationinthesamecommitthatincludesthecode
changes.
It’sahealthystrategyforseveralreasons.First,itplacesthe
responsibilitywiththedeveloperthatmadethechange.Thatpersonisin
thebestpositiontoupdatethedocumentation.Second,itminimizesthe
riskthatyouforgettoupdatethedocumentation.
Don’tCommitEverything
Keepingaproject’s.gitignorefileuptodateisessentialifyouwantto
avoidclutteringyourproject’srepository.Filesthataregeneratedare
generallyignored,suchasbuildsanddocumentation.That’salsowhyI
prefertoleavethePodsdirectoryoutoftherepository.Theproject’s
Podfile.lockandCartfile.lockdefinetheproject’sdependencies,which
ssufficienttoinstallthedependenciesandbuildtheproject.
Anythingthat’srelatedtothedeveloperortheIDEyou’reusingshouldbe
ignored.Xcodekeepsyourpreferencesintheprojectfolderand
AppCodealsostoresabunchofpreferencesattheproject’sroot.That’s
fine,butyoudon’tneedtocommitthosetotheproject.Oneofthe
reasonsisthatyoudon’twanttohaveconflictswithotherteammembers.
Sensitiveinformationshouldalmostalwaysbeignored.Ionceworkedon
aprojectthatcontainedprivatekeys.Thisisn’tsomethingIrecommend.
Privatekeysshouldbestoredinasecurelocation,notintherepository.
GuidelinesandExceptions
Thischaptermerelydescribesasetofguidelines.Atsomepoint,youwill
runintoanexception.Youneedtodiscussthiswithyourteamandwhat
youdecidemaydifferfromprojecttoproject.
AsImentionedelsewhereinthisbook,becritical.It’snotbecauseBart
Jacobssaidthatyoushouldn’tkeepthePodsdirectoryundersource
controlthatthatiswhatyoushoulddo.Thereareplentyofdevelopers
whodisagreewiththisstance.
4DocumentEverything
Liketesting,documentationisoftenconsideredaluxuryor“Something
wecandolater.”Thisisacommonmisconceptionand,especiallyin
teams,itcomesbacktobiteyou.
Therearevarioustypesofdocumentation.Theoneyou’reprobablymost
familiarwithisthedocumentationorcommentsintheprojectsyouwork
on.Whileit’struethataddingtoomanycommentsisn’tagoodidea,I
hopeyouagreethatnocommentsisworse.
StartWiththeBasics
Asabasicrule,everyprojectshouldhaveaREADMEattherootofthe
project,regardlessoftheproject.Evenifyou’recreatingatinylibrarythat
addsroundedcornerstoabutton,thenyoushouldaddaREADME.
EverytimeIcomeacrossaprojectonGitHubthatdoesn’thavea
properlyformattedREADMEthatsaysafewthingsabouttheprojectI’m
lookingat,Iclosethebrowsertabandmoveon.
Youdon’tneedtospenddayswritingdocumentation.Thebasicsarefine
togetyourfeetwet.Startwithabriefdescriptionoftheproject,its
authors,itsdependencies,andhowsomeoneunfamiliarwiththeproject
canquicklygetuptospeed.Thelatterisoftenoverlooked.Ithappensall
toooftenthatIneedtofigureoutwhichtoolstoinstall,whichversionof
RubyIneedtohave,andonandononlytocompiletheproject.That
shouldn’tbenecessaryanditcanbeavoidedwithminimaleffort.
Projectownership,atopicIdiscusselsewhereinthebook,isoften
undervaluedorignored.Theprojectownerisinchargeofcreatingastep
bystepguidetohelpnewdevelopersgetuptospeedasquicklyas
possible.Ifyouowntheproject,thenit’syourresponsibilitytomakesure
suchaguideexistsandthatit’suptodate.Didanewteammemberrun
intoanissue?Noproblem.DebugtheproblemandupdatetheREADME
tomakesurethisdoesn’thappeninthefuture.That’snotunreasonable.
Isit?
MakeItEasy
Documentationisonlyusefulifpeopleuseit.Ifyouhidethestyleguideof
yourteaminahardtofindfolderstructurethat’ssharedonGoogleDrive
orBitbucket,thenthechancesarethatnobody’sgoingtomakeaneffort
tolookforit,letaloneuseit.Itdoesn’tmatterwhatsolutionyouuse,as
longasyoumakesureyourteamcanaccessitwithafewclicksorkey
strokes.
Thereareseveralopensourcesolutionsthatmakeiteasyto
automaticallygeneratedocumentationforlibrariesorprojects.This
meansthatthedocumentationisautomaticallyupdatedwhenyoupusha
commit.Lookingintoanautomatedsolutionmaybewellworthyourtime.
Youcanevenintegrateyourdocumentationwithdocumentationbrowsers
ormakethemavailableonline.CocoaDocsisaniceexampleofthis
strategy.Ibelieveit’snolongermaintained,butthetoolsthatpower
CocoaDocsareopensourceandavailableforyoutouse.
WhattoDocument
Theshortanswerissimple.Everything.ThereasonIrecommendto
documenteverythingissimple.It’salwaysapaintofiguresomethingout
andmostofthetimeyoudon’thavethetimetomessaround.
Irememberthat,yearsandyearsago,Icreatedastepbystepguideto
setupaLAMPstackonmacOS.Thischangedwitheveryrelease,and
everytimeIinstalledafreshcopyofmacOSorpurchasedanew
computer,IhadtofigureouthowtosetupaLAMPstack.Havingthis
stepbystepguidewasalifesaver.Every.Single.Time.
UptoDate
Keepingdocumentationuptodateischallenging,especiallyifyouwork
inanenvironmentthatevolvesquickly.However,morefrustratingthan
nothavingdocumentationishavingincorrectdocumentation.Ican’ttell
youhowoftenIhitawallbecauseofincorrectoroutdated
documentation.Youknowitshouldworkbecauseit’sdocumented.Butit
isn’tworking.
Keepingdocumentationuptodaterequirestwoelements.Thefirstisthe
mostimportantone,amindsetandcommitmenttodoso.Again,
ownershipiskey.Everypageofdocumentationshouldhaveanowner.
Thatpersonisresponsibleforkeepingthedocumentationuptodate.
Avoidthatonepersonisresponsibleforeverything.Thisdoesn’twork.
Thesecondelementishavingarobustsystem.Thistiesinneatlywith
discoverability.I’veencounteredsituationsinwhichanAPIwas
documentedinseveralplaces.Thedatewasmyonlyindicationwhich
documentwasmostuptodate.That’swhatIassumed.
SomepeopleswearbytoolslikeJIRAandConfluence.That’sfineand
I’mnotgoingtorecommendatool.I’veneverlikedthesetools.
Confluenceandmehaveneverbeenbestfriends.Useatoolthatyouor
yourteamenjoyusing.Itshouldn’ttaketenclicksandfivebrowser
windowstoaddanewentrytothedocumentation.
MakeItaCoreTool
Documentationisoftenanafterthought.“Oh.Westillneedasystemto
managethedocumentation.Confluence?Sure.GoogleDocs.That
shouldwork.”
Don’tmakethismistake.Investinasystem,freeorpaid,thatworksfor
youandyourteam.Ifyoufindafreesolutionthatworksforyou,then
that’sfantastic.Ifit’sapaidsolution,thenthat’sfinetoo.Aslongasyour
teamusesitonadailybasis,you’resetandaheadofthecurve.
I’maTeamofOne
Whatdoyoudoifyouareateamofone?You’reafreelanceroryourun
asmallproductbusiness.Thesamerulesapply.Itsimplymeansthatyou
needtotakecareofeverythingyourself.Therulesaresimpler.You’rethe
owner,whichmeansthatyou’reinchargeofkeepingeverythingupto
date.
Don’tmakethemistakethatyou’llrememberhowtosetupJenkinssix
monthsfromnow.Youwon’t.Writeitdownanddocumentit.You’llbe
gladyoudidsixmonthsfromnow.
Somepeoplegotheextramileandwriteablogpost.Theydocument
theirfrustrationsbyprovidingastep-by-stepguideto,forexample,setup
abuildserver.Thousandsofpeoplewillthankyouforit.
MakeItaHabit
Ifyou’reateamleaderoramanager,thenmakesureyourteammakes
documentingahabit.Thiscanbechallenging,butit’snecessary.Every
developershouldlearnthatnoteveryaspectofsoftwaredevelopmentis
funorenjoyable.
Adeveloperwhomakesdocumentingahabitunderstandswhatsoftware
developmentisabout.It’smorethanwritingcodeandmakingbeautiful
userinterfaces.Softwaredevelopmentiscreatingsomethingthatlasts.It
shouldworktodayandayearfromnow.Documentationisatinygearin
themachinethatmakesthatpossible.
TimeIsMoney
Icanseewhypeoplesometimesseedocumentingasawasteoftime
sinceithasnotmeasurablereturnoninvestment.Isthattrue?Arethese
thesamepeoplethatclaimthattestingisamisuseoftime?
Isn’titalsotruethatnocompanymeasureshowmuchtimeislostfiguring
outthingsthatshouldhavebeendocumented?Thinkaboutthatandthen
considerthereturnoninvestmentofproperdocumentation.
PART4:WORKFLOW
1Testing
DevelopersoftenfeelguiltywhenIstarttalkingabouttesting.They
sheepishlyturntheirheadormumblethatthey’vebeenplanningtowrite
testsbuthaven’tfoundthetime.Youshouldn’tfeelashamedifyou’ve
neverwrittenatest.Thatsaid,youshouldconsiderstartingtoday.
WheretoStart
Ifyou’reunfamiliarwithtesting,thenthesubjectfeelsabstractand
complex.That’sthefeelingIhadbeforeIstartedwritingunittests.The
truthisthattestingisn’tthatdifficultifyoubreakitdown.Like
documentation,it’satopicmanydevelopersdon’tgivemuch
consideration.
StartSimple
Theeasiestteststowriteareusuallythosethattestthemodellayerof
yourapplication.Ifyou’renewtounittesting,thenit’sagoodideatostart
there.Don’tstartwithtestingviewcontrollersorCoreDatamodels.If
you’renewtounittesting,thenthatwillonlyconfuseyou.
Chooseatinyclassorstruct,createatesttarget,andwriteyourfirstunit
test.Runtheunittestandbesurprisedbyhoweasythatwas.
CodeCoverage
Whileyoucantestaprojectwithoutit,codecoveragegivesyouanidea
ofhowwellyourprojectiscoveredbyyourtestsuite.Therearevarious
toolsandtechniquesforcalculatingcodecoverage.Appleaddednative
supportforcodecoverageinXcode7.
Toenablecodecoverage,youcheckacheckboxintheconfigurationof
yourschemeandrunthetestsuite.Xcodeautomaticallycollects
coveragedata,createsareportforyou,andevendisplayscode
coveragemetricsinthesourceeditor.
Codecoverageismerelyanestimate.TheimplementationofXcode,for
example,inspectsthecodepathsthataretriggeredwhenthetestsuiteis
run.BecauseXcodespinsupaninstanceofyourapplicationwhenitruns
theproject’stestsuite,codepathsthatarenotunittestedarealso
triggered.Someoftheapplicationlifecycleeventsintheapplication
delegate,forexample,aretriggeredwhenyourtestsuiteisrun.Ibelieve
thatXcodetakestheseintoaccountwhencalculatingtheproject’scode
coverage.YoucanverifythisinthetestreportXcodegeneratesforyou.
RevealingWeaknesses
There’samoreimportantreasonwhyIwasexcitedwhenAppleadded
supportforcodecoveragetoitsIDE.Codecoveragerevealsweakspots
intheunitteststhatIwrite.Xcodeshowsyouwhichcodepathsare
triggeredwhenthetestsuiteisrun.Greenmeansthatacodepathis
triggeredbythetestsuiteandredmeansacodepathisn’ttriggeredby
thetestsuite.Inotherwords,redmeansthatIneedtowritemoreunit
tests.
Thisoccasionallyhappenswhenedgecasesareinplay.Wehavethe
tendencytotestthehappypathsandoverlookorignoretheedgecases.
Whathappensifthebackendreturnsanemptyresultortheformatofthe
fileyou’reloadingisn’twhattheapplicationexpects?
WritingBetterCode
Eventhoughwritingunittestsisn’tmyfavoriteaspectofsoftware
development,overtheyears,I’vecometoenjoyandappreciateit.Not
onlyisarobusttestsuiteinvaluableforanysoftwareproject,italso
makesyouabetterprogrammer.Whyisthat?
Whenyouwriteatestforafunctionormethod,you’reforcedtothink
abouttheimplementationofthatfunctionormethod.Youapproachthe
implementationfromadifferentperspective.
BreakItDown
Lengthymethodsandmassiveviewcontrollersarealmostalways
symptomsofcodesmell,subtlytellingyouthatit’stimeforaroundof
refactoring.Animportantbenefitofwritingtestsisthatitpushesyouto
keepmethodsshortandfocused.
Asageneralrule,amethodshouldfocusononethingandonething
only.Ifyouadoptthatstrategy,methodsnolongerspandozensor,
heavenforbid,hundredsoflines.Massivemethodsareveryhardtotest.
Notonlyisitdifficulttounderstandwhatyou’retesting,toomany
variablesareinplay,eachaffectingtheimplementationandthe
correspondingtests.Thenumberofcodepathsyouneedtotest
becomesunwieldyandtheresultisoftenthatnounittestsarewrittenor
themethodisn’tproperlycoveredbyunittests.
KeepItSimple
It’sbettertohaveahandfulofshortandfocusedmethodsthanone
monstrousone.Whyisthat?Themostobviousbenefitisthatconcise
methodsareeasiertounderstand.It’seasiertowrapyourheadaround
themethod’simplementation.Youhaveabetterunderstandingofwhat’s
goingonandwhatthepossibleoutcomesare.
Anotherimportantbenefitisthenamingofmethods.Ifyoucreatea
methodthatspansdozensoflinesandisresponsibleforhalfadozen
tasks,thenwhatareyougoingtonamethatmethod?Ifyoubreakthat
methoddownintosmallermethods,eachwithaparticularfocusortask,
namingthesemethodswillbeeasyandstraightforward.
Bykeepingitsimple,yougainclarity.Bycreatingmassivemethodsor
classes,youcreatechaosandlosefocus.
DependencyInjection
FromthemomentIbecameseriousaboutunittesting,Ilostmyfondness
forsingletonsandcametolikedependencyinjection.ItfeltasifI
graduatedasaprogrammerandnolongerneededthesingletonpattern
togluethepiecesofaprojecttogether.
Dependencyinjectionisawonderfulconceptthat’softenignoredor
discardedinfavorofthesingletonpattern.EventhoughIdon’tdislike
singletons,Ialwaysaskmyselfwhetherthere’sabettersolutiontosolve
theproblemthatdoesn’tinvolveasingleton.Hint.Thereoftenis.
Dependencyinjection,mocking,andtestingisapowerfulandflexible
combination.Mockingandstubbingalsobecomemucheasierwith
dependencyinjection.
XcodeandTesting
Xcode’ssupportfortestinghasgraduallyimprovedovertime.Withits
supportforcodecoverage,younowgetanicetestreportandthesource
editorshowsyouifaparticularcodepathwastriggeredbytheproject’s
testsuite.
CodeCoverageinXcode
AsImentionedearlier,codecoverageisn’tmagicalandithasitsflaws.
Youshouldn’tsolelyrelyoncodecoveragewhenwritingunittests.That
said,itmakesitmucheasiertospotholesinyourproject’stestsuite.
MyCurrentTestSetup
EventhoughXCTesthasimprovedovertheyears,Iusuallyuseafew
additionallibrariesformakingtestingeasierandmorepowerful.For
Objective-Cprojects,IhavecometoloveandrelyonOCMock,a
mockinglibraryforObjective-C.BecauseOCMockhooksintothe
Objective-Cruntime,therecurrentlyisn’tanequivalentforSwiftprojects.
OCMockallowsyoutotestmoreaspectsofyourcode.It’seasytomock
objectsandstubmethods,enablingyoutotestpartsofyourcodebase
youwouldn’tbeabletotestwithonlyXCTestinyourtoolbox.
Anotherlibrarythat’sgreatfortestingisOHHTTPStubs.Asthename
implies,thislibrarymakesstubbingnetworkrequestseffortlessly.With
OHHTTPStubs,younolongerhaveanexcusetoignorenetworkinglogic
inyourproject’stestsuite.
WhatAreYouTesting
Notwritingunittestsdoesn’tmakeyouabadprogrammer.Butyou
shouldaskyourselfwhyyou’renotwritingunittests.Moststudiesshow
thatyousavetimeinthelongrunbecausebreakingchangesareeasier
tofindandbugsarelesslikelytocreepintoyourproject’scodebase.It
alsogivesyoumoreconfidenceinthecodeyouwrite.
Earlierinthischapter,Ibrieflytouchedonatopicthat’sveryoften
overlookedbydevelopers,especiallythosethatarenewtounittesting.
Whatareyoutesting?
ImplementationVersusSpecification
Fromadeveloper’sperspective,unittestinganentitymeanswriting
unittestsforeverymethodandpropertyoftheentity.Inotherwords,
you’rewritingunitteststotesttheimplementationoftheentity.
What’softenoverlookedormisunderstoodisthatunittestingfallsinthe
categoryofblack-boxtesting.Thismeansthatyoudon’tcarehowthe
entityundertestdoeswhatitdoes.Fromthemomentyoustartwriting
unittests,youneedtostopbeingadeveloperandtakeonthemindsetof
atester.
Asatester,you’renotinterestedinhowsomethingworks.Youcarefully
inspectthepublicinterfaceoftheentityandmakesuretheentity
behavesasspecified.Youcancomparethiswithsomeonetestingacar.
Ifthetesterstartsthecar,she’snotinterestedinwhathappensunderthe
hood.Thespecificationsaysthatturningthekeyshouldstartthecar
withinapredefinedperiodoftime.Thetesterteststhebehaviorand
functionalityoftheentityundertest.
PublicOnly
Byembracingblack-boxtesting,unittestingbecomesmucheasier.You
don’tcareabouttheprivatemethodsandpropertiestheentity
defines.Asatester,youonlyfocusonthepublicinterfaceoftheentity.
Byunittestingthepublicinterfaceoftheentity,youautomaticallyunittest
theprivateinterface.That’stheunderlyingidea.
CodeCoverageCanHelp
Thereisonecaveatyouneedtobeawareof.Asatester,you’renot
interestedintheprivatemethodsandpropertiesoftheentityyou’re
testing.That’sfinebecausethat’swhatblack-boxtestingisabout.Butit
alsomeansthatyouneedtocarefullycrafttheunittestsyouwrite.Itcan
oftenmeanthatyouneedtowritemultipleunittestsforonepublic
methodorproperty.Whyisthat?
Ifyouwanttohavecompletecodecoveragefortheentityyou’reunit
testing,youneedtomakesureeverycodepathoftheentityundertestis
executed,includingthoseofprivatemethodsandproperties.
AsIdiscussedearlierinthischapter,Xcodecanhelpyouwiththis.Ifyou
enablecodecoverage,Xcodetocollectcodecoveragedataforyou.It
visualizescodecoverageforanentityinthegutterontherightofthe
sourceeditor.Thenumberindicateshowmanytimestheunittests
enteredaparticularcodepath.Thisishelpfultofindoutwhereyourunit
testsfallshort.
ItTakesTime
WhenIfirststartedunittestingCocoaapplications,Itriedtoreach
completecodecoveragebyunittestingpublicandprivatemethods.In
Objective-C,thisispossiblewithafewtricks.Unittestingprivate
methodsandpropertiesisn’tpossibleinSwift.Andthatmaybeagood
thingasIexplainedearlier.
Fromthemomentyoustarttowriteunittestsforaproject,youneedto
stepoutofyourroleasadeveloperandtakeonthemindsetofatester.
Youneedtoviewtheentityyou’reunittestingasablackboxthatneeds
toconformtoaspecification.It’sthespecificationyouneedtotest,not
theimplementation.
2ContinuousIntegration
Whilecontinuousintegrationisespeciallyusefulforteams,Ibelieveit
alsohasbenefitsfordevelopersthatworksolo.ThepracticesIdescribe
inthischapterapplytoanyonedevelopingsoftware,largeofsmall.
WhatIsIt
Thenamecontinuousintegrationmaysounddauntingorscary,butit
reallyshouldn’t.Theideaissimple.Oneormoredevelopersworkona
projectandpushtheirchangestoasharedrepository.Wheneverapush
isdetected,aseriesofautomatedstepsissetintomotion.Thisusually
involvescreatingabuild,executingatestsuite,andperforminganumber
ofqualityassurancesteps.
Thereareseveralbenefitstousingcontinuousintegration.Oneofthe
benefitsIappreciatemostisthatnohumaninteractswiththefinal
productaftercodeiscommittedtotherepository.Otherbenefitsinclude
testautomation,codeanalysis,andbuildoptimization.
WhyIsThisUseful
Continuousintegrationisusefulformosttypesofsoftwaredevelopment.
Therearemanyflavorsofcontinuousintegrationavailable.Thebenefits
ofcontinuousintegrationaremostapparentinteamswithmultiple
developersworkingonthesamecodebaseandcommittingmultipletimes
aday.
Insteadofworkingonafeatureinisolationfordaysorweeks,you
frequentlycommitandpushyourchangestoasharedrepository.That’s
whenthebuildserverjumpsintoaction,buildingyourapplication.
ThereasonIwanttoincludeachapteroncontinuousintegrationinthis
bookistoillustrateacommonsetofproblemsthatIhaveseeninsome
ofthecompaniesIworkedfor.Iwon’tbecoveringcontinuousintegration
itselfingreatdetailbecausetherearemanysolutionsavailable,each
withtheirownbenefits,paid,hosted,andopensource.
LongHangingFruit
Forsmall,personalprojects,Idon’trecommendusingacontinuous
integrationsolutionbecauseitcomeswithabitofoverheadandcost.For
criticalprojects,though,continuousintegrationbringsclearbenefitsto
thetable.Whatyoudefineascriticalisuptoyou.Forme,anyprojectfor
athirdpartyiscritical,largeorsmall.
Ifyouoryourteamarenewtocontinuousintegration,thenIsuggestto
startwithasimplesetuptotakeadvantageoftheimmediatebenefits
continuousintegrationhastooffer.Youmaywanttostartwithahosted
solutionifyou’renewtocontinuousintegration.Thereareopensource
solutions,butitcantakesometimetosetupabuildserver,configureit,
andintegrateitwithservices,suchasApple’sTestFlightorGoogle’s
Fabric.
Togetyourfeetwetwithcontinuousintegration,tryoutahostedsolution
first.Ifyoulikethebenefitsitbrings,thenconsiderabettersolution,with
bettermeaningmorerobust,scalable,andcost-effective.
TheminimumsetupIrecommendissurprisinglybasic.Itincludes
automatedunittestswitheverypush,updatingoftranslations,and
creatingabuildfortesting.Isthatenough?Isthatworthit?Ibelieveitis.
It’stooeasytoforgettorununittestsbeforecreatingatestbuild.Right?
It’scertainlytooeasytoupdatetheproject’stranslationsbeforecreating
abuild,productionorstaging.Andmessingwithtestbuildsissomething
youwanttoavoidaltogether.
Giveitatry.Spendafewhoursoradaysettingupcontinuousintegration
foraprojectandevaluatethebenefitsyouandyourteamgetfromit.
AvoidHumanTinkering
Inanidealscenario,youwanttomakesurethatnohumantouchesthe
productfromthemomentthelastcommitispushedtotheshared
repository.Thismaysoundobvioustosomepeople,butitcertainlyisn’t
whathappenswhenthingshitthefan.Manuallyimportingtranslations,
tweakingbuildflagsandsettings,updatingversionandbuildnumbers,…
Thesearestepsthatshouldbeavoidedatanycost.Ifyou’rescaredto
pushabuildtoproduction,thenyouhaveworktodo.Continuous
integrationcanhelpyouwiththis.
LetmerepeatwhatIwroteearlier,youneedtopreventthatahuman
interactswiththefinalproductaftertheteamcommittedtheirlast
changestotherepository.Thelastthingthedeveloperdoesispushing
theirchangestothesharedrepository.
TestFlight
IusedtouseFabricfordistributingtestbuildstotesters.Apple’s
acquisitionofTestFlighthaschangedthisforme.Thereasonissimple.I
onlyneedtosendonebinarytoApple’sservers.Thesamebinaryisused
byAppletocreateatestbuildandabuildfortheAppStore.Myjobis
limitedtoselectingthebuildIwanttodeploytotheAppStore.Whatyour
testersaretestingiswhatyourcustomersaregoingtodownloadand
use.Fantastic.
Thisisthegoalyouneedtotrytoreachregardlessofthesolutionyou’re
using.Thebuildthatyourtestersaretestingshouldbeidenticalfroma
functionalperspectivetotheoneyousendtoApple.Thisimpliesthat
bothbuildsreferencethesamecommitintherepository.TestFlight
makesthisveryeasy.Othersolutions,suchasFabricandHockeyApp,
mayrequireyoutodoabitofadditionalworksincethesesolutionsdon’t
neatlyintegratewithiTunesConnectasfarasIknow.
ChooseacontinuousintegrationsolutionthatintegrateswithTestFlight,if
youoptforTestFlight,andthat’sabletosendbuildstoiTunesConnect.
Youdon’twanttodothismanually.Rememberthatchoosingthecorrect
buildorarchivetouploadtoiTunesConnectisanothermanualstepyou
needtoavoid.Youdon’twanttobetheonethatuploadedthewrong
buildtoiTunesConnect.
PainlessReleases
Youneedtoavoidthatreleasesarestressfulandchaotic.Anautomated
workflowcanandshouldhelpyouwiththis.Irealizethatnotevery
developerhasthefortunetoworkinacompanythatembraces
automationandtesting.Whydon’tyoumakeastartbywritingabuild
scriptthatautomaticallyupdatesthebuildnumber?
Youcanevenleverageexistingopensourcetoolsforthat,suchas
fastlane,apowerfulsuiteofcommandlinetoolsthatautomatecommon
tasks,suchasbuilding,testing,generatingscreenshots,andsending
buildstoiTunesConnect.
MakeItRobust
Inthechapteronautomation,Italkmoreaboutthebenefitsof
automation.It’simportantthatyoumakeyourautomationrobust.Make
sureit’stestedanddoesn’tbreakseveraltimesaday.Thisisn’tonly
frustratingtoanyoneinvolved,italsomakesthatpeopledon’tputalotof
trustintothesolution.Whenpeopledon’ttrustasystemorasolution,
theytendtoavoidit.That’ssomethingyouneedtoprevent.
Ifyou’reworkinginacompanythathastheresources,thenitpaysoffto
putsomeoneinchargeofcontinuousintegration,makingsureit’s
monitoredandkeptincheck.Inasmallteam,it’susuallyadeveloper
that’sinchargeofautomationandcontinuousintegration.Thisis
unavoidableifyou’resmall,butitcanleadtofrustrationandasystem
thatsimplydoesn’twork.Don’tconsiderautomationandcontinuous
integrationanafterthought.Itcansaveyoutimeandmoney.In
professionalenvironments,it’sacoreelementoftheworkflowand
releasecycle.
Transparency
Transparencyisanimportantaspectofworkinginateam.Itmeansthat
peopleareallowedtomakemistakes,butitalsomeansthateveryone
involvedisnotifiedwhensomethinggoeswrong.
Notifications
Ifabuildfailsorunittestsdon’tpass,theneverypersonworkingonthe
project,includingtheprojectmanager,shouldbenotifiedofthisevent.It
shouldalwaysbeobviouswhoneedstotakeactiontofixtheproblem.
Iftheteam’sworkflowissloppyandnotrespectedbythepeopleworking
ontheproject,thennotificationspileupandthey’reignored.Thisisvery
similartowarningsinXcode.Fromthemomentyouignoreonewarning,
it’sveryeasytoignorethesecondandthirdwarning.Afterawhile,you
nolongerpayattentiontowarnings,whichisacritical,andoftenpainful,
mistake.
Notificationitis
AsIalreadymentioned,carefullytweakthenotificationsyousendand
receive.Fromthemomentpeoplereceivetoomanynotifications,they
starttoignorethem.That’soneofthereasonsI’mabigproponentof
InboxZero.Ifyourinboxisempty,you’relesslikelytoignoreormiss
importantnotifications.
LearningCurve
Thereisacosttoeverycontinuousintegrationsolution.There’sa
financialcostandthere’salearningcurve.Youcanoptforanopen
sourcesolution,suchasJenkins,butthatmeansyou’reresponsiblefor
settinguptheinstallationaswellasitsmaintenance.Hostedsolutions
areeasiertogetstartedwithbutyoupayapriceforthem.Thisshouldn’t
beaproblemformediumtolargecompanies,butitcanbeforfreelancers
orindependentdevelopers.
Icanassureyou,though,thattheinvestmentyoumakepaysitselfback
inthelongrun.Thedevelopmentteamcanfocusonwhattheydobest,
qualityimproves,andreleasesarelessstressful.
3Refactoring
RefactoringisawordIfrequentlyuseinmycommitmessagesbecause
it’ssomethingIdoveryoften.It’safancywordforwritingorimplementing
somethingdifferently.Youdon’toftenhearorreadaboutrefactoring.
Especiallyifyouworkinacompanyororganizationthatputsan
emphasisonoutputorvaluesquantityoverquality,there’slittleroomor
understandingforrefactoring.
Ihaveadifferentopiniononrefactoring.Refactoringisanintegralpartof
myworkflowandthereareseveralreasonswhythatis.
TechnicalDebt
WheneverIimplementasolutiontoacomplexproblem,theprimarygoal
istogetthesolutiontowork.Ineedtoknowthatthebasic
implementationI’veputintoplaceworksasexpected.This
implementationisrarelytheoneIwanttokeep,though.Thereare
severalreasonsforthat.
Idon’tknowaboutyou,butIknowmyselfwellenoughthatIneedseveral
shotsatacomplexproblembeforeIcomeupwithasolutionI’mhappy
with.It’snotsomuchamatteroflikingasitisavoidingtechnicaldebt.
Refactoringisanoftenoverlookedcuretotechnicaldebt.Tobehonest,
it’snotacure,it’savaccine.
Yourfirstshotatanimplementationisn’tgoingtobeyourbest.Ifyou
thinkaboutit,it’soddthatotherphasesofaprojectgetmultiple
opportunitiestocomeupwithasolution.Designersareoftengiventhe
freedomtotryoutseveraldesigns.Adeveloperisrarelygiventhisluxury.
Oneofthereasonsisthattheclientorprojectmanagercanseethe
design.Yourimplementationisusuallynotputunderalotofscrutinyifit
worksasexpected.But,ifyouhaveabitofexperiencedeveloping
software,youknowthatthere’sworkingandworking.Ifadevelopertells
me“Itworks.”andheshrugshisshoulders,thenIknowit’stimefora
codereview.
CoreDataisafineexample.Ifyou’veworkedwithCoreData,thenyou
knowthatgettingthedatamodelrightisacrucialaspect.It’snotunusual
thatadatamodelchangesovertimeastheapplicationgainsfeatures
andcomplexity.Thosechanges,however,areevolutionary.Theybuildon
whatyoualreadyhave.Gettingthedatamodelwronginafundamental
way,however,isapain.Youdon’twanttogothroughseverallightweight
orheavyweightmigrationstofixsomethingyoucouldhavefixedfromthe
start.
I’mcurrentlyworkingonaprojectwithacomplextimerengine.Ithas
takenmeseveralroundsofrefactoringbeforeIendedupwithasolution
I’mhappywith.Whyisthat?Implementingasolutiontoacomplex
problemoftenfeelslikeputtingtogetherapuzzleinthedark.Ittakestime
beforeyouseethebiggerpicture.Ittakestimebeforeyoucanseeevery
componentthat’sinvolvedandthevariousedgecases.
BuildingfortheFuture
Whilerefactoringisausefultooltoreducetechnicaldebt,thereare
severalotherbenefits.Insteadoftacklingtheproblemsyou’recurrently
facing,youcanthinkahead.What’sthedirectiontheproductisgoingin?
Whatproblemsdoestheproductsolvethreeorsixmonthsfromnow?
Canwe,withminimaleffort,laythegroundworkforasolutionthatsolves
theseproblems?
There’sasubtledifferencebetweenprematureoptimizationandsimply
optimizingforgrowthornewfeatures.Let’stakeCoreDataasan
example.Ialreadymentionedthatgettingthedatamodelrightisvery
important.Youwanttotouchthedatamodelaslittleaspossible.The
cardinalityofarelationship,however,issomethingyoucanbeflexible
withearlyon.It’spossiblethatanaccountonlyhasoneuseratthe
moment,butisitplausiblethattheproductsupportsmultipleusersper
accountinthenotsodistantfuture?Yes?
Thinkaheadanddefineinthedatamodelthatanaccountcanhave
multipleusers.Andtomakeyourcurrentworkeasier,defineacomputed
property,user,thatfetchesthefirstuser.Inotherwords,you’recurrently
workingincodeasifanaccounthasoneuser,butthedatamodel
alreadyhassupportformultipleusers.
Thelinebetweenprematureoptimizationandanticipatinggrowthisfine,
butitreallypaysofftospendsometimeconsideringthesedecisions.
Codereviewsandanalysiscanreallyhelpwiththis.Letyourselfbe
challengedbyanotherteammember.Listentotheirarguments,
questions,andinput.
TheFallacyofSunkCost
It’spossiblethatyou’veinvestedhours,days,orevenweeksintothe
implementationofasolutiontoachallengingproblemyou’refacedwith.
You’vepouredhoursandhoursintothissolution.Itworks,well,mostof
thetime.Thelongeryouspendontheproblemandimplementinga
solution,themoreyourealizethatyoursolutionisflawed.Thatcanbea
hardpilltoswallow.
Someofusaretooproudtothrowtheirworkintothetrashandstart
anew.Sometimesyoudon’tevenhavethatluxury.Itcanbeparticularly
frustratingifyou’reworkingforyourselfandyou’veinvestedtimeand
moneyintoasolutionthatyou’renothappywith.
Ittakescourageandconfidencetotakeresponsibilityandadmitto
yourselfthatyouneedtocomeupwithanewsolution.Manyofusare
blindedbythefallacyofsunkcost.You’veinvestedtimeandmoneyinto
aproblemandthatmeansitneedstomakeitsmoneyback.Thetruthis
thatyouwon’tevergetthattimeormoneyback.However,youcansave
yourselftimeandmoneyinthefuturebytakinganotherlookatthe
problem,learningfromyourmistakes,andcomingupwithabetter
solution.
Ifyouthinkthisonlyhappenstorookiedevelopers,thenyou’dbe
mistaken.It’stheexperienceddeveloperthathastheaudacitytostart
afreshwithacleanslateandthatknowsandseesthesolutionwon’tcut
it,forwhateverreason.But,again,there’safinelinebetweenknowing
whenthesolutionisn’tgoodenoughandstrivingforaperfectsolution
thatdoesn’texist.Behonestwithyourselfand,asalways,askadvice
fromteammembersorfellowdevelopers.
StartingAnew
Startingwithacleanslateisalmostalwaysahardselliftheclientmakes
thedecisions.Unfortunately,I’veworkedonprojectsthatwouldhavecost
lessiftheclienthadhadthecouragetostartanew.That’sthefallacyof
sunkcost.Truthbetold,it’sdifficulttopredictthefutureandit’seasyto
writethisinhindsight.
Whilerefactoringisanintegralaspectofsoftwaredevelopment,you
sometimesneedtohavetheaudacitytostartfromscratch.Learnfrom
themistakesthatweremadeandcreatesomethingthatisreadyforthe
future.Whileit’srarethatyou’regiventhisopportunity,youcanerase
monthsoryearsoftechnicaldebtthatslowtheproduct’sevolutiondown
bystartingfromsquareone.That’saverytemptingofferforadeveloper.
Isitnot?
4SourceControl
ThedayIdiscoveredsourcecontrolwasoneofthoseahamoments.I’m
aself-taughtprogrammerandthatwasclearlyvisibleintheearlydaysof
mycareer.I’msureyoucanguesswhattypeofsourcecontrolstrategyI
usedbeforeIfoundoutaboutGit.Letmegiveyouahint.Itinvolved
copyingfolders.Ignoranceisbliss,butnotifyou’readeveloper.
WheneverI’mhookedbyanewtoolortechnique,Itrytolearneverything
thereistoknowaboutit.Gitwasnodifferent.Inthischapter,Ishowyou
whatyouabsolutelyneedtoknowaboutsourcecontrol,thebasics.Itake
itonestepfurtherbyintroducingyoutotheworkflowthatI’vebeenusing
forthepastfewyears,aworkflowthat’sbeenworkingverywellforme.
TheBasics
ThemostpopularsourcecontrolsolutionintheCocoaandSwift
communitiesisGit.Thatdoesn’tmeanit’sthebestsolution,butit’sthe
oneIhavethemostexperiencewith.Iloveit.Ifyou’renewtosource
control,thenIurgeyoutoputdownthebookandlearnmoreaboutGit.
Seriously.Putthebookdown.I’llbeherewhenyoucomeback.Thefolks
atFournovahaveabunchofgreatresourcestolearnthebasics.
It’snicetoseethatXcodehasimprovedsupportforGitovertheyears.
Xcode9takesitupanotchanditsurelookspromising.Iusea
combinationofthecommandlineandadedicatedGitclient,Tower.
Don’tBreakTheseRules
Elsewhereinthebook,Iwritethatonceyouknowtherulesandwhat
theystandfor,it’sfinetobreakthem.Thatruledoesnotapplytosource
control.ThereareafewsimplerulesIsticktoreligiously.Letmegiveyou
anoverview.
MasterandDevelop
Aprojectshouldalwayshaveaminimumoftwobranches,masterand
develop.WhenyoucreateanewGitrepository,yougetmasterforfree.
Doyourselfafavor,createadevelopbranch,andcheckitoutbeforeyou
startdevelopment.
MasterIstheTruth
Deploymentstoproductionalwayshappenfrommaster.Thereshouldbe
noexceptionstothisrule.Plainandsimple.
DeveloponDevelop
Developmentshouldalwayshappenondeveloporafeaturebranchthat
branchesoffofdevelop.There’soneexceptiontothisrule,hotfixes.
Wheneveryouneedtofixanurgentprobleminproduction,youcreatea
hotfixbranchthatbranchesoffofmaster.Youimplementthesolutionon
thehotfixbranchandmergethechangesbacktomaster,readytobe
deployed.
Technicallyspeaking,youdon’tdeveloponahotfixbranch.Youonlyfix
theproblemathand.
Commits
Commitsandcommitmessagesareyourwindowintotheproject’s
history.Thismeansthatit’simportanttocarefullycraftyourcommitsand
commitmessages.That’soneofthereasonsIuseaGitclientbecauseit
allowsmetopickandchoosewhichcodechangesmakeitintothenext
commit.Youcandothesamefromthecommandline,butit’sless
convenient.HowyouinteractwithGitisapersonalchoice.
Thereareseveralmethodsforcreatingacommitmessage.Itdoesn’t
matterwhichoneyouchoose,butmakesureyou’reconsistentand,if
youworkonateam,adoptthesamemethodologyacrosstheteam.
Avoidlargecommits.It’struethatthiscansometimesbeaproblemif
you’remodifyingtheprojectfileofanXcodeproject.Notonlyisthis
importantforclarityandcommunication,butit’salsoimportantfor
practicalreasons.Ifyouwanttocherrypickacommit,thenyouwantto
makesurethecommityou’recherrypickingonlyincludeswhatyouthink
itincludes.Thesameistrueforrollingbackcommits.
Stashing
I’malwayssurprisedbythenumberofdevelopersthatarenewtothegit
stashcommand.Theconceptissurprisinglysimple.Imaginethatyou’re
workingonanewfeatureonafeaturebranch.Yourprojectmanagertaps
youontheshoulderandasksyoutohotfixaproblemonmaster.Your
workspaceislitteredwithchanges.Whatdoyoudo?Doyoucommit
whatyou’reworkingonjusttomakesureyoudon’tloseyourwork?No.
Don’tdothat.
Thegitstashcommandstashesthechangesintheworkingdirectory
andthestagingareaforlateruse,leavingyouwithacleanworking
directoryandstagingarea.Thestashedchangesarepushedontoa
stackandyoucancreateasmanystashesasyouneed.
Tostashthechangesintheworkingdirectoryandthestagingarea,you
executethegitstashcommand.Thechangesintheworkingdirectory
andthestagingareaaresafelystoredforlateruse.Youswitchtothe
releasebranch,createabuild,returntothebranchyouwereworkingon,
andapplythestashyoucreatedearlier.It’sthatsimple.Toapplyastash,
youpopitfromthestackofstasheswiththegitstashpopcommand.
Ifyoufrequentlyusestashes,Irecommendnamingthestashesyou
create.Thismakesiteasytofindstashesandapplyorremoveastash
byname.
Patching
Inaway,patchingissimilartostashing.Bothcommandsgroupanumber
ofchangesthatyoucanapplylater.Apatchcombinesseveralcommits
orthechangesintheworkingdirectory.Thechangesarestoredinafile
witha.diffextension.
Patchesareusefulforseveralreasons.It’seasytostorepatchestodisk
orsharethemwithotherdevelopers.Youcanapplypatchestobranches
nomatterwhatthebranchingmodellookslike.They’realsoagood
alternativetocherrypicking.
AsImentionedearlier,IinteractwithGitusingacombinationofthe
commandlineandFournova’sTower.Creatingapatchisveryeasyin
Tower.Selectthecommitsyouwanttoincludeinthepatch,right-click,
andchooseSavePatchforXRevisions…fromthecontextualmenu.
Patchescanbeusedinawiderangeofscenarios.Imagineyou’re
workingwithateammateonabig,complexfeature.You’rebothworking
onthesamebranchandfiringonallcylinders,committingasifyourlife
dependedonit.You’reabouttopushyourchangestoGitHubwhenyou
noticethatyourteammatealreadypushedherchanges.It’stimetopull
andperformanastymerge.Idon’tknowaboutyou,butIdon’tlikethese
kindsofmerges.
Thesolutionissurprisinglysimple.Youcreateapatch,includethe
commitsyou’reaheadoftheremotebranch,andresetyourbranchto
HEADoftheremotebranch.Youthenpullthechangesofyourteammate
andapplythepatchyoucreatedearlier.Ifyou’rebothworkingonthe
samebranchandmodifyingthesamefiles,thenit’sstillpossiblethatyou
stillneedtoperformamanualmerge.
Keepinmindthataresetisapotentiallydangerousoperationthatcan
leadtodataloss.Alwaysbearthisinmindwhenusingthereset
command.
GitFlow
Aprojectwithanydegreeofcomplexityneedsarobustbranchingmodel.
ThebranchingmodelIhavecometoappreciateistheoneoutlinedby
VincentDriessen.Vincent’smodelmaylookdauntingatfirst,butit’seasy
toadoptinmostsoftwareprojects.
Theideaissimple.AprojectadoptingVincent’sbranchingmodelhasa
masterandadevelopbranch.Wecoveredthatearlierinthischapter.If
youdecidetoworkonafeature,youcreateafeaturebranchthat
branchesoffofdevelop.Whenafeatureisreadytobereleased,the
featurebranchismergedbackintodevelop.
Whenthetimecomestoschedulearelease,areleasebranchiscreated
thatbranchesoffofdevelop.Thegoalofthereleasebranchistoprepare
thereleaseandfixcriticalbugs.Areleasebranchisneverusedto
implementfeatures.Afterasuccessfulrelease,thereleasebranchis
mergedintomaster,mergedintodevelop,andmergedintodownstream
releasebranches.
Mergingintodevelopanddownstreamreleasebranchesisimportantto
guaranteethatanyworkdoneonthereleasebranch,suchasbugfixes,
isalsoincludedinfeatureanddownstreamreleasebranches.
Earlierinthischapter,Idiscussedhotfixbranches.Ifyouneedtopusha
hotfixtoproduction,youcreateahotfixbranchthatbranchesoffof
master.Afterreleasingthehotfix,thesamemergestrategyisappliedas
forreleasebranches.
ThisbranchingmodelworksreallywellformeandtheprojectsIworkon.
Irecommendprefixingbranchnameswithfeature/,release/,andhotfix/
toavoidconfusion.Ifyouapplythisnamingconvention,thenmostGit
clientsautomaticallygroupeverybranchtypeinafolder.
SomeTips
I’dliketoendthischapterwithafewtipsthatIpickedupovertheyears.
DoesItBuild
Youshouldonlymakeacommitiftheprojectbuildssuccessfully,without
warninganderrors.Thisisn’talwayseasy,especiallyifyou’rerefactoring
asectionofaproject.
IgnoreWhatYouDon’tNeed
Makesureyouuseanuptodate.gitignorefile.Elsewhereinthisbook,I
sharethe.gitignorefileIuseinCocoaprojects.Regardlessofwhich
.gitignorefileyouuse,makesureyouunderstandwhatitincludes.Don’t
includeoneyoufoundonthewebifyoudon’tunderstandwhatitignores.
Configuration
It’simportanttoknowandunderstandwhichfilestokeepundersource
control.Adevelopercheckingouttheprojectshouldbeabletobuildand
runtheprojectwithminimaleffort.Thismeansthatyoudon’tneedto
includethePodsdirectoryifyou’reusingCocoaPods,butyouneedto
includethePodfileandPodfile.lockfiles.
SensitiveInformation
Sensitiveinformation,suchasprivatekeys,shouldnotbekeptunder
sourcecontrol.Makesureyoudon’tcompromisesecuritybydumping
everythingintheproject’srepository.
5Dependencies
Thenumberofopensourceprojectsgrowseverydayandit’spretty
amazingwhatyoucanbuildwiththehelpofopensourcesoftware.Swift,
forexample,isanopensourceprojectthatgainedalotofmomentumthe
momentitwasopensourced.
Butopensourceprojectsalsohaveadownsideandsodoeseverythird
partyprojectyourelyon.DoyourememberParse,thecompany
Facebookacquiredseveralyearsago.Afewyearsaftertheacquisition,
Facebookannounceditwasgoingtoshutdownthecompany,leaving
tensofthousandsofdevelopers,companies,andprojectsinthecold.
Thewinnersofthisdecisionwerefreelancersandconsultants.Ialsohad
tomigrateaprojectawayfromParse.
WhyamItellingyouthis?It’struethatopensourceprojectsandthird
partysolutionscansignificantlyspeedupthedevelopmentofaproject.In
verylittletime,youcancreateaproofofconceptoraminimumviable
product.Thisspeedcomesatacost,though.AsImentionedearlierin
thisbook,thereareveryfewshortcutsinsoftwaredevelopment.Every
shortcutyouencounterhasanotherside,arisk.
MinimizeDependencies
Asafreelancer,Ihavetheopportunitytobrowsemanycodebases.Some
ofthemaregreat.Manyofthemaren’t.Oneofthemostcommon
problemsisthatprojectsincludetoomanydependencies.There’s
nothingwrongwithhavingdependencies.Everymodernsoftwareproject
hasdependencies.Theproblemisthatthey’reoftenusedasashortcut
orbecausethey’reconsideredindispensable.
WheneverIcreateaprojectinXcode,Istartoutwithoutadependency
manager.Thatusedtobedifferent,though.Severalyearsago,after
discoveringCocoaPods,IimmediatelyinstalledthisRubygemonmy
machine.Don’tgetmewrong.CocoaPodsandCarthagearefantastic
projectsthathavehelpedmetremendously.Butthatdoesn’tmeanthat
youcan’twriteaproperCocoaapplicationwithoutthem.
WhatIsaDependency
Dependenciescomeinmanyformsandshapes.Themostobvious
dependenciesareopensourcesolutionsyoumanagewithadependency
managerlikeCarthage,CocoaPods,ortheSwiftPackageManager.
Managingdependencieswitharobustdependencymanageristrivial.It’s
almosttooeasy.
Inexperienceddevelopersmakethemistakeofincludingtoomany
dependencies.Afterawhile,theprojectfeelslikeacarheldtogetherwith
tapeandglue,readytocrashandburnattheslightestbumpintheroad.
It’struethatdependenciescansignificantlyspeedupthedevelopmentof
aproject,but,again,shortcutscomeataprice.
RememberthatParseoffereddevelopersatemptingsolution,amobile
backendwithsupportfordatastorage,pushnotifications,andmore.Most
oftheprojectsthatreliedonParsewereforcedtopayaheftypricewhen
theplatformwasshutdown.
AsImentionedearlier,dependenciescomeinmanyformsandshapes.
Swiftisadependencyofeveryprojectyouworkon.Ifyou’reaSwift
developer,thenyouhavenootheroption.Somedependenciesare
unavoidable.Xcodeisprobablyanotherdependencyofyourprojects.
ThattooisoutofyourcontrolunlessyouswitchtoJetBrain’sAppCode.
RxSwiftmayalsobeadependencyofyourproject.Youcouldrollyour
ownlibraryforreactiveprogramming.Shouldyou?Ianswerthatquestion
inamoment.
Anddon’tforgetthehiddendependenciesofaproject.Ifyourproject
dependsonMoya,thenitautomaticallyhasadependencyonAlamofire.
FewerDependencies
Theideaissimple.Thefewerdependenciesyourprojecthasthebetter.I
hopewecanagreeonthat.EverytimeIaddadependencytoaproject,I
carefullyanalyzewhetheritdeservestobepartoftheproject.Whatare
thealternatives?Howlongwouldittakemetoimplementacustom
solution?Howhealthyisthedependency?Isitaliabilityfortheproject?
EveryauditIsetupwithadeveloperoracompanystartswithasession
that,amongotherthings,analyzesthedependenciesoftheproject.The
leaddeveloperoftheprojectmustbeabletojustifywhytheproject
dependsonaparticularlibrary,platform,ortechnology.Iftheprojectuses
CocoaPodstomanagedependencies,forexample,weinspectthe
contentsoftheproject’sPodfile.
Iunderstandthatdependenciescansavetimeand,intheshortterm,
money.Butwhathappensifyouneedtoreplaceadependencythat’s
usedthroughouttheproject?Whatifyouneedtoswitchoutavital
componentoftheprojectandreplaceitwithanalternative?
MappingtheLiabilitiesofaProject
Everydependencyisaliability.Plainandsimple.EventheSwift
programminglanguageisaliability.Don’tbelieveme?Askthetensof
thousandsofdevelopersthatadoptedSwiftinitsearlydays.Migrating
projectstothelatestSwiftsyntaxwasnoeasytask.Icanassureyou.
Everyprojecthaspointsoffailure.That’sunavoidable.You,asa
developer,havetheresponsibilitytoknowaboutthepointsoffailuresof
theprojectsyouworkonand,equallyimportant,tominimizetheir
number.
Don’tMakeYourLifeTooEasy
IhaveafewrulesIreligiouslysticktowhenitcomestodependencies.
EverydependencyIaddneedstoearnitswayontotheproject.Thefirst
ruleIneverbreakissimple.Idirectlyinteractwithfirstpartylibrariesand
frameworks.Whatdoesthatmean?
CoreDataistheexampleIusuallybringupinthiscontext.Ineverusea
CoreDatalibrarytointeractwiththeframework.CoreData’sAPIhas
improvedsubstantiallyovertheyearsandit’seasytouseand
understand.Whywouldyouuseathirdpartylibrarytointeractwiththe
framework?Isitbecauseyoudon’tquiteunderstandhowtheframework
works?Convenience?Laziness?Behonestwithyourself.
MostofApple’sframeworksareverywelldesigned.Thecompanyhas
decadesofexperiencedesigningAPIs.It’struethatsomeoftheolder
APIsaren’tprettyandabitverbose,butdon’tletthatbeareasontoadd
anotherdependencytoaproject.Writeyourownlightweightwrapperif
youwantconvenienceandelegance.Iguaranteeyouthatit’sworththe
investment.
RollingYourOwn
Projectswithdozensofdependenciesveryoftenhaveseveral
dependenciesfortrivialtasks,suchasahelperlibraryforAutoLayout,a
CoreDatalibrary,aconveniencelibraryforanimations,andonandon.
Wheneveryou’reabouttoaddadependencytoaproject,considerhow
longitwouldtakeyoutorollyourownimplementation.Woulditbea
matterofhoursorweeks?Ifitonlyrequiresafewhoursofwork,thenit
maybebettertorollyourown.Youprobablydon’tneedeveryfeatureof
thedependencyanyway.Isitfeasibletocreatealightweightsolutionthat
doesthejobequallywell?
Thisdoesn’tmeanthatyoualwaysneedtoreinventthewheel,butyour
firstreactionshouldnotbelookingforadependencytosolveanissue.
You’readeveloper.Right?
ChooseWisely
Ialreadywrotethatatypicalsoftwareprojecthasmanyhidden
dependencies,suchastheprogramminglanguageandthedeveloper
toolsweuse.Someofthesedependenciesareeasilyoverlooked.How
doyoucollectcrashreportsoranalyzeuserengagement?Ibetyoudon’t
useApple’sanalytics.DoyourelyonFabric,Firebase,orMixpanel?
Thesearematureplatforms,butthey’redependenciestoo.
BecomingaBetterDeveloper
Relyingondependencieswon’tmakeyouabetterdeveloper.Infact,you
riskbecominglazyandcomplacent.Haveyouheardthatagood
developerisalazydeveloper?Thisisnotthetypeoflazinessthat’s
meantbythis.
I’mabigfanofopensourcesoftware.Unfortunately,thepopularityof
opensourcesoftwarehasadarkside.ProjectslikeAlamofireandMoya
arefantastic.Acommittedgroupofdevelopershasmadeittheirgoalto
createabeautifulpieceofsoftwareforeveryoneelsetouse.Projectslike
Alamofireareincrediblypopular.Theymakeyourlifeasadeveloper
easier.
ThedownsideisthatmanydevelopershavecometorelyonAlamofire
withoutlearningthebasicsfirst.Asurprisingnumberofdevelopers
doesn’tknowhowtouseURLSessiontoperformanetworkrequest.Isthat
aproblem?Ibelieveitis.IfIweretointerviewadeveloperforaposition
andheorshedoesn’tknowhowtoperformanetworkrequest,Iwouldn’t
hirethatdeveloper.
SamsaraisanapplicationIhavebeendevelopingforseveralyears.It
makesahandfulofnetworkrequests.Insuchascenario,anetworking
librarylikeAlamofireorMoyaisoverkill.It’struethatNSURLConnection,the
predecessorofURLSession,hadanAPIthatwasn’tterriblyelegant.The
introductionofURLSessionseveralyearsagohaschangedthis.TheAPI
isn’tassophisticatedasAlamofire’sorMoya’s,butitdoesitsjobwell.
Thatshouldbeyourfirstchoice.
WatchOutfortheDefaults
Thereareseveraldependenciesthathavebecomealmostdefault
dependencies.Theseincludelibrariesandframeworksforanalytics,
crashreporting,andlogging.Iconsideritadangerouspracticetomakea
dependencyadefaultdependency.Iunderstandthatyourapplication
needscrashreportingandanalytics,butdoesthatmeanthatyouneedto
optforFabricorFirebase?DidyouknowthatApplealsohascrash
reporting?YoucaneveninspectthecrashreportsfromwithinXcode,
pointingyoutothelinethatcausedthecrash.
I’mnotpleadingthatyoushouldavoidFabricandFirebase,butdon’t
makethemdefaultoptions.Everydependencyneedstoearnitsplace
ontotheproject.ThesameistrueforthemanySDKsthatareavailable,
suchastheTwitterandFacebookSDKs.
ChallengeYourself
I’dliketochallengeyou.ThenexttimeyoucreateaCocoaapplication,a
sideprojectmaybe,avoidrelyingonanythirdpartydependencies.See
howfaryoucangowithoutincludingthirdpartylibrariesorframeworks.
Impossible?Thinkagain.Atitscore,adeveloperissomeonethatsolves
problems.Thisisaproblemyoucansolve.Believeme.
6Automation
“Agooddeveloperisalazydeveloper.”It’saphraseIuseseveraltimes
inthisbook.Ibelievetheterm“lazyprogrammer”wasfirstcoinedby
PhilippLenssen.Theideaisthataprogrammerwantstoavoidbeing
repetitivewheneverpossible.Butthat’snottheonlyreasonautomationis
important.
Automationcanalsominimizehumanerror.Continuousintegration,
whichwediscussedearlierinthisbook,isanexampleofthis.By
automatingasequenceofsteps,wereduceoreliminatethenumberof
manualstepsateamneedstotaketodeployabuildtoproduction.
Automationdoesn’tneedtoberocketscience,though.TheCocoacasts
websiteisbackedupautomatically.Thisisatrivialexampleof
automation,buttheresultisthatIhavepeaceofmindand,whenthings
hitthefan,Iwon’tloseanydata.
Let’sstartwiththebasicsofautomation,scripting.
Scripting
Manyofusinstinctivelyautomatetasksweneedtoperformfrequently.If
you’reusinganapplicationlauncher,suchasLaunchBarorAlfred,ora
snippetmanager,suchasTextExpanderorDash,thenyou’realready
embracingautomation.
WiththereleaseofSwift,however,youcantakescriptingtothenext
levelwithprojectslikeMarathon,Swiftline,andCommander.Several
frameworks,libraries,andtoolshaveemergedthatallowustouseSwift
tocreatescriptsandautomateaslewofcommontasks.
BeforetheintroductionofSwift,IusedRubytowritesmallscriptsthat
helpedmeautomateacollectionofmundanetasks.I’mslowlyporting
someofthosescriptstoSwift.Youcanusefromawiderangeof
languages,includingJavaScript,Python,andPerl.
BuildPhases
Xcodebuildphasesareidealforautomatingtasksyoutendtoskipor
forget.Forpersonalprojects,IuseRealm’sSwiftLinttomakesurethe
codeIwriteisconsistentandstickstoasetofguidelines.SwiftLintis
easytosetupandintegratewithXcodeinabuildphase.Youcaneven
triggerSwiftLineusingfastlane.
AutomatedTesting
It’snosecretthatI’mafanofautomatedtesting.Itisn’thardtosetup
anditbuildsconfidence.Everycommityoupushtoasharedrepository
triggersthetestsuite,immediatelyshowingyouifyou’vebroken
anything.Thisfeedbackloopallowsyoutoconfidentlybuildarobust,
stableproduct.Nothavingtothinkaboutrunningyourtestsisessential.
Documentation
Ifyouoryourteammaintainaframeworkorlibrary,thenyouneedto
makesureitsdocumentationisuptodate.AsImentionedelsewherein
thebook,it’sfrustratingtoworkwithoutdatedorincorrectdocumentation.
Thegoodnewsisthatthisisanothertaskthatcanbeautomated.Ifyou
properlydocumentthecodeyouwrite,toolslikeRealm’sJazzycan
automaticallygeneratedocumentationforyou.Makeitaccessibletoyour
teamandyouhaveaccesstouptodatedocumentationwithevery
commityoupushtothelibrary’sorframework’srepository.
ContinuousIntegration
Earlierinthisbook,Iwroteaboutcontinuousintegrationanditsbenefits.
It’samoresophisticatedformofautomationthatcanhelpyouandyour
teamstayontopoflarger,complexprojectswithmanymovingparts.
Rememberthatoneofthegoalsofautomationisreducingthenumberof
manualstepsyouneedtotaketodeployyourproducttoproduction.
Fromthemomentadeveloperpushesthelastcommittotheshared
repository,nohumanshouldtinkerwiththebuildthat’sdeployed.
Ifyouworkatanagencyoradevelopmentshopthatmanagesdozensof
products,thenhavingarobustcontinuousintegrationsolutionisn’ta
luxury.It’sessential.Notwoprojectsarethesameandeveryprojecthas
itsownrequirements,dependencies,andconfiguration.Youdon’twantto
rememberthoseandyoudon’twanttomanuallytweakbuildsettings
momentsbeforeyoutriggeraproductionbuild.Takeyourworkandthat
ofyourclientsseriousandinvestinacontinuousintegrationsolution.
fastlane
Afewyearsago,FelixKrausestarteddevelopingasuiteoftoolsfor
automatingcommontasksrelatedtoCocoadevelopment.Thissuiteof
toolsisfastlane.Atthetimeofwriting,fastlaneisapartofFabricand
GoogleacquiredFabricnottoolongago.
Thetoolsareopensourceandunderactivedevelopment.Felixisstill
verymuchinvolvedinthisamazingsuiteofcommandlinetoolsandI
recommendthatyoutakealookatfastlaneifit’snewtoyou.My
workflowdoesn’trelyonfastlane,butIdouseitforgenerating
screenshots,building,testing,andpushingbuildstoiTunesConnect.
Felix’suiteoftoolsisanessentialcomponentinmanycompanies
becauseitalsosolvescommonproblemsdevelopersface,suchas
creatingandrenewingprovisioningprofiles,creatingcodesigning
identities,andkeepingthemsynchronizedthroughGit.It’sanamazing
collectionoftools.
KeepItSimple
Automationisgreat,butitneedstoworkreliably.Forexample,ifyour
continuousintegrationsetupisn’treliable,yourteamwillstarttolose
confidenceinitandmoretimeisspentworkingongettingittorunthan
benefittingfromit.
7Privacy
Privacyandsecurityarehottopicsandrightfullyso.Whatdevelopers
oftendon’trealizeistheirroleinprotectingtheuser’sprivacy.Inthe
chapteraboutsecurity,Ialreadywroteaboutprivacyandwhatyoucan
dotomakesurethedataofyourusersiskeptfromthepryinghandsof
peopleandcompanieswithquestionableethics.
Manypartiesareinterestedinthedataofyourusers,forvariousreasons.
Fromadeveloper’sperspective,it’slessimportantwho’safterthis
information.What’simportantisthattheusersofyourapplicationtrust
youwiththeirinformationandtheyexpectyoutokeepitprivateand
secure.
ProtectingtheUser’sPrivacy
Eventhoughprivacyisn’tafancytopicanditisn’ttopofmindformost
developers,Ihopeyou’reatleastkeepingprivacyinmindwhenyou’re
buildingsoftware.Yousometimeshavenootheroption,forexample,if
you’redevelopinganapplicationforabank.Butthereisarangeofless
obviousapplicationtypesthatprivacyisimportantfor,forexample,
applicationsthathavealinktotheuser’shealth.
WhoDoYouWorkWith
Ialreadywroteaboutdependenciesandhowimportantitistoproperly
vetanydependencyofasoftwareproject.Thisalsoimpactsprivacy.AsI
wroteearlierinthisbook,thirdpartyservices,suchasanalyticsand
advertising,usuallyoffertheirservicesforfree.Whyisthat?
You’veprobablyheardthephrase“Ifyou’renotpayingfortheproduct,
thenyouaretheproduct.”Somecompaniescollectandsellinformation.
Theycollectuserinformation,suchasbrowsingbehaviorandlocation
data,andsellittoadvertisers.Whiletheservicestheyofferarefree,
there’sacatch.
It’snotalwayseasytodiscoverwhichcompaniesarelegitandwhich
onestoavoid,butifyou,thedeveloper,includeathirdparty’sservicein
yourapplication,thenit’syourresponsibilitytomakesureitdoesn’t
violatetheuser’sprivacy.You’reonthehookifsomethinghappenswith
theuser’sdata.
Youcanremedythisbypublishingaprivacypolicyforyourapplicationin
whichyouexplainwhathappens,ordoesn’thappen,withtheuser’s
information.Thisalsomeansthatyouneedtoknowhowthethirdparties
youworkwithuseyourapplicationtocollectinformation.Thiscanbe
tedious.It’sironicthatit’susuallyeasiertoincludeathirdpartySDKthan
tofindouthowthethirdpartyusesyourapplicationfortheirowngain.
AsImentionedearlier,Inolongerincludethirdpartyservices,suchas
analyticsandadvertisingintheprojectsIworkon.That’saconscious
decisionandIhavetheluxurytodothis.Unfortunately,thisisn’tpossible
foreveryone.Infact,itmayberare.
GivingtheUserControl
OneofthereasonsforchoosingforApple’secosystem,bothasa
consumerandasadeveloper,arethevaluesthecompanyholds.Privacy
isimportanttoAppleandthereareveryfewcompaniesthatfollowits
exampleinthetechnologyindustry.
AppReviewisafineexample.WhileAppReviewhasreceivedafair
amountofflakovertheyearsandisoftenseenasanobstaclefor
developers,IapplaudAppleforputtingthisbarrierinplace.Aftermore
thannineyears,thecompanystickswithitsambitiontokeeptheApp
Storesafeandhealthy.
WheneverIinstallanapplicationfromApple’sAppStore,IknowthatI
won’tbeinstallingapieceofmalwarethatsendsthecontentsofmy
addressbooktoaremoteserver.AppReviewisn’tperfectorbulletproof,
butit’sdemonstratedthatitdoesaprettygoodjobatprotectingyouand
mefrompeopleandcompanieswithdubiouspractices.
Youneedtogiveanapplicationyourexplicitpermissionforittoaccess
youraddressbook,photos,andlocation.Thisisagoodthingbecauseit
putsyou,theuser,inchargeofmanagingyourprivacy.Whilethis
solutionisn’tperfect,itatleastgivesyoutheopportunitytobeconscious
ofyourprivacyifthat’swhatyouwant.Somepeopledon’tcareabout
theirprivacyandthat’sfine.Theuserisincharge.
ThirdPartySDKs
Whileyoucan’talwayschoosewhichcompaniesyouworkwith,you,the
developer,areresponsiblefortheuser’sdata,howit’sused,andwho
canaccessit.Overtheyears,manyscandalshavesurfacedof
companiesthatuseddevioustacticstogetaholdoftheuser’spersonal
information,suchastheircontactsandlocation.
IfyouincludeathirdpartySDKinyourapplication,thenyoushould
realizethatyouhavenoideahowthecompanyprovidingtheSDKis
usingyourapplication’sdata.Thisissomethingweoftenforget.
Thisiscloselytiedtothediscussionaboutdependenciesearlierinthis
book.NotonlyisathirdpartySDKadependencythatcancausehavoc
inyourapplication,italsohasunlimitedaccesstoyourapplication’sdata.
ChooseWisely
Considerthecompaniesyouimplicitly,orexplicitly,workwith.Idon’twant
toimplythatyoushouldn’ttrustApple,Google,andFacebook,butyou
needtobemindfuloftheservicesyourapplicationandyourbusiness
uses.
8WhattoDoWhenYouInheritaSoftware
Project
Asanemployee,freelancer,orconsultant,youinevitablyendupwitha
foreigncodebaseonyourplateatsomepointinyourcareer.Inaway,
inheritingasoftwareprojectismuchlikereceivingthekeystoahouseor
caryoudon’tknowanythingabout.Youholdyourbreath,afraidforwhat’s
abouttocome.Butyou’realsoalittleexcited,curioustofindoutwhat
you’llbeworkingonforthenextweeks,months,orlonger.
Anewprojectcanbeoverwhelming.Dependingonitssizeandstate,
openingaprojectforthefirsttimecanbedownrightshocking.Don’tlet
thisintimidateyou,though.Somethingsarehard,butthatdoesn’tmean
they’reimpossible.
FirstThingsFirst
Takeyourtimetoexplorethecodebaseandlearnmoreabouttheproject
asyougo.Thefirstfewdayscanbedisorientinganditmayfeelasif
you’renotmakinganyprogress.Andthat’sfine.
TalktothePreviousOwner
Ifthepreviousowneroftheprojectisstillaroundandabletodoaformal
handover,thenyou’reinluck.Thisisamajoradvantage.Preparealistof
questionsandfireawayduringthehandover.Don’tbeshy.You’renewto
theproject,whichmeanstherearenosillyordumbquestions.
Isthepreviousownernotaround,thentrytogetaholdofsomeonewho
workedonorisfamiliarwiththeproject.That’sthenextbestthing.
SourceControl
Wheneveraprojectisthrowninmylap,thefirstthingIdoisclonethe
repository.Istheprojectnotundersourcecontrolor,evenworse,
someonetamperedwiththerepository’shistory,thenthat’sthefirstred
flag.It’spossiblethepreviousownersaretryingtohidesomething.In
thatcase,yourfirsttaskistocreatearepositoryfortheproject.Ifthings
gohaywire,it’seasytoretraceyoursteps.
Ifyou’reinluckandtheproject’sundersourcecontrol,thentakeaclose
lookatthecommithistory.Fornow,themostimportantquestionsare
“Whomadethefirstcommitandwhenwasitmade?”and“Whomadethe
lastcommitandwhenwasitmade?”
Thetimeofthefirstandlastcommitstellyoualotaboutthestateofthe
project.Youmayevenbeabletocontactsomeofthepeoplethatworked
ontheproject.Sourcecontrolisinvaluableforanysoftwareproject.
Compatibility
Dependingonthesoftwareproject,youneedtomakesureyour
developmentenvironmentiscompatiblewiththeproject’stechnology
stack.ACocoaapplication,forexample,requiresamachinerunning
macOSwithacopyofXcodeinstalled.
ItmayevenbenecessarythatyouneedaspecificversionofmacOSor
Xcodetobringtheprojecttolife.AsImentionedearlier,ifyoucantalkto
someonethatusedtoworkontheproject,thenyou’resavingyourselfa
lotoftimeandfrustration.
BuildandRun
Themomentoftrutharriveswhenyoucompiletheprojectforthevery
firsttime.Giveitatry.Buildandruntheapplicationonadeviceorinthe
simulator.Thisstepiscriticalbecauseitrevealssomeoftheproject’s
dependencies,suchasthirdpartyframeworksandlibraries,anditcan
alsoexposesomeearlyproblems.
Iftheprojectusesadependencymanager,suchasCocoaPodsor
Carthage,thenyoumayneedtoinstallthedependenciesfirstbefore
you’reabletocompiletheproject.
Onceyou’vesuccessfullybuiltandruntheproject,you’vereachedyour
firstimportantmilestone.Youcannowstarttoexploretheprojectand
collectinformation.
CollectData
Withtheprojectupandrunningonyourdevelopmentmachine,it’stime
togettoknowyournewbestfriend.It’simportanttounderstandhowthe
projectworksand,moreimportantlyatthisstage,findoutwhatits
requirementsare.
ForaCocoaapplication,forexample,thedeploymenttargetisan
importantpieceofinformation.IttellsyouwhatAPIsyoucanuseand
whichdevicestheapplicationiscompatiblewith.Areyoudealingwitha
universalapplicationordoesitonlysupportiPhoneandiPodTouch?Has
theprojectbeenupdatedforretinadisplays?Doyouthinkthat’sasilly
question?Thinkagain.
Someprojectshavebeencollectingdustforyears.Thiscansometimes
meanthatyouneedtomakesignificantchangesbeforeyoucansubmita
buildtoApple’sAppStore.AsofJune2015,forexample,Applerequires
newapplicationsandupdatestoexistingapplicationstoinclude64-bit
support.Iftheprojectdependsonathirdpartyframeworkorlibrarythat
hasn’tbeenupdatedinyears,thismaybeaproblem.
Dependencies
Speakingofdependencies,you’reprobablystartingtogetaprettygood
pictureoftheproject’sdependencies.It’stimetotakeacloserlook.Are
thedependenciesmanagedbyadependencymanagerorarethey
includedinthemainproject?
Withabitofluck,thepreviousownerusedadependencymanagerto
separatethedependenciesfromthemainproject.Inthatcase,it’s
straightforwardtoverifythecurrentversionofeachdependencyand,ata
laterstage,updatethem.
Insomecases,dependenciesareincludedinsubmodulesor,ifyouare
lessfortunate,they’remixedinwiththeproject.Thelattermakes
updatingdependenciesapain.Migratingthirdpartydependencies
outsidethemainprojectwiththehelpofadependencymanagerisa
worthwhileinvestment.It’llsaveyoumanyhoursandheadaches.
WorkingontheProject
Howyouapproachaprojectlargelydependsonthetimeyou’reallowed
tospendworkingonit.Ifyouonlyneedtostepintofixahandfulofbugs,
thenitisn’tworthspendingdaysorweeksfamiliarizingyourselfwiththe
codebase.
Areyoutaskedtoimplementamajorfeature,thenit’skeythatyouknow
howtheapplicationisarchitectedandhowitoperates.Ifyou’rethenew
owneroftheprojectandinchargeofmaintainingtheprojectforthe
foreseeablefuture,thenyouhavetheluxuryofinvestingtimeandenergy
tocleanupthecodebase,refactoringneglectedparts,andmakingthe
projectyours.
DocumentEverything
Nomatterwhatprojectyouworkon,it’simportanttodocumentasmuch
aspossible.TheREADMEoftheprojectisagoodstartingpoint.For
larger,morecomplexprojects,itcanalsobeusefultodocumentfeatures
orincludeanoverviewoftheapplication’scorearchitecture.Ithelps
otherdevelopersbecomefamiliarwiththeprojectanditalsobenefits
you,themaintainer,inthelongrun.
Bycommentingyourcode,documentingtheproject,writingsensible
commitmessages,andmaintainingalistofbugreports,youhavemost
ofthetoolsyouneedtostayontopofyourproject.
AndBeyond
What’snext?That’sagoodquestion.Inthischapter,weonlyscratched
thesurface.Startingworkonaforeignorlegacysoftwareprojectcanbe
messy.Itmaypushyououtofyourcomfortzone,butthat’sagoodthing.
Leavingyourcomfortzonefromtimetotimekeepsyousharp,forcesyou
tobecreative,andpreventsyoufrombecomingcomplacent.
9Speed,Quality,andTechnicalDebt
Thefirstversionofaproductcanneverbereleasedsoonenough.That
makessense.Aslongasdesignersanddevelopersareworkingona
productthatisn’tmakingmoney,it’scostingmoney.
Butspeedcancomeatacost.Togainspeed,youneedtomake
sacrifices.Andveryoftenspeedistradedforquality,resultingintechnical
debt.
SpeedandQuality
Inproductdevelopment,speedandqualityarealmostalways
irreconcilable.Increasingthevelocityofaprojectmeanscompromising
onquality.Fromadevelopmentperspective,thisusuallyresultsinthe
creationoraccumulationoftechnicaldebt.
Assumeforamomentthatyou’retheproductownerofasoftware
project.Thefirstversionoftheproductneedstoincludefivemajor
features.Eachofthesefeaturestakesaweektodevelop.Theproblemis
thattheclientwantstoshipthefirstversionoftheproductinthreeweeks.
Whatdoyoudo?
Youhaveseveraloptions.Themostobviousoneisdroppingtwo
features.Unfortunately,that’srarelysomethingtheclientagreesto.
Anotheroptioniscuttingdowndevelopmenttimeofeachfeaturebyone
ortwodays.Thisusuallytranslatestoremovinganythingthatdoesn’t
involvetheimplementationofthefeature,suchascodereviews,quality
assurance,andtesting.
TechnicalDebt
Technicaldebtcancreepintoaprojectwithouttheproductowner
knowingaboutit.Thedevelopmentteamusuallyknows,though.Ifthe
teamisledbyaseniordeveloperandcodereviewsarebakedintothe
company’sculture,technicaldebtiseasytospot.
Afastapproachingdeadlinecancauseeventhebesttoignoretechnical
debt.Thesymptomsstarttoappearwhennewfeaturestakelongerto
buildthanexpectedandregressionsmaketheirwayintotheproduct.
Thesearetheearlysymptomsoftechnicaldebt.
Inadvancedstages,technicaldebttakesaprojecthostage.Nobody
wantstotouchtheprojectanymore.Featurestakeagestocompleteand
areoftencompromisedbytechnicallimitationscausedbytechnicaldebt.
Days,weeks,ormonthsofbugfixingareneededtostabilizetheproject.
I’mnotexaggerating.
Inthemeantime,theproductitselfevolvesatasnail’space.Thespeedy
startthatwasoncesoimportantfortheproject’ssuccesshaslongbeen
forgottenand,lookingback,wasn’tthatimportantafterall.Itrarelyis.
Focus
Iftheclientwantstoshipinthreeweeks,thecorrectanswerisremoving
features.Forprojectswithalongshelflife,youwanttoavoidtechnical
debtatanycost.Technicaldebtisverymuchlikeavirus.It’shardto
eradicateand,ifitisn’ttreatedinitsearlystages,itspreadsoutrapidly
acrosstheproject’scodebase.
Focusisessentialtoavoidtechnicaldebt.Insteadofrushingouta
feature,youtakethetimetocraftsomethingthatstandsout.Thisdoesn’t
onlyrelatetothefinalproduct;italsoinvolvesthedevelopmentaspectof
thefeature.
Youdon’tneedtooverengineerthesolution,butyouneedtomakesure
thefeaturecangrowbeyonditscurrentscope.Youplanandanticipate
howitcanorcouldevolve.
HowtoGetRidofTechnicalDebt
There’snomiraclecuretoridaprojectoftechnicaldebt.Youneedto
takeaction,though,ifyouwanttoavoidworse.
Refactoring
Theleastradicalapproachisrefactoringtheproject,focusingonone
problematatime.Ifyou’reinluck,oneroundofrefactoringissufficient.
However,mostprojectssufferingfromtechnicaldebthavemany
problemsthatneedfixing.
AsImentionedearlier,technicaldebtspreadslikeavirusandthatmeans
manyareasofthecodebaseareinfected.Istronglyadviseagainsta
singleroundofrefactoring.Maptheproblemsyouplantoattackand
spreadtherefactoringoverseveralreleases.Thisensurestherelease
cycleisn’tblockedaslongastherefactoringisongoing.
Inthemeantime,makesureyoudon’tintroducenewproblems.Holdoff
onnewfeaturesifpossible.Don’tmakethesamemistaketwice.
Ifyou’reworkingonalargeprojectwithyearsofhistory,bepreparedto
spendweeksormonthsrefactoring.That’sthepriceyoupayfortechnical
debt.
CleanSlate
Themostradicalapproachisstartinganew.Thismeansyoudon’tneed
tospendmonthsrefactoring.Thisisn’tanoptionforeveryproject.Ifyou
havetheopportunitytostartwithacleanslate,though,you’reinluck.
Whileitmeansthatyouneedtoimplementeveryfeaturefromscratch,
it’sanopportunitymanydeveloperswouldgrabwithbothhands.Learn
fromyourmistakes,orthoseofyourcolleagues,andcreateanamazing
product.
I’veworkedonseveralprojectsthatwouldhavecostlessiftheproject
wasrebooted.Butthat’softenaveryhardsell.Theclientdoesn’tseethe
problemsthedevelopersees.Theyonlystarttoseethesymptomsof
technicaldebtwhendeadlinesaremissedorfeaturesbecomevery
expensive.
TakingShortcuts
Takingshortcutsrarelypaysoffinsoftwaredevelopmentandmost
developersknowthis.Butdeadlinesareoftenmoreimportantand
developersrarelyhavetheauthoritytomakedecisionsaboutthefeature
setoftheproduct.
PART5:TEAM
1CodeReviews
Likeunittesting,codereviewsareoftenseenasanicefeatureifthere’s
sometimeleftonaproject.Thismisconceptionstemsfrominexperience.
Onceyoustartschedulingregularcodereviews,youstarttoappreciate
thevalueforanyoneinvolved.Ifyouworkinateam,you’dbecrazynot
totakeadvantageoftheknowledge,experience,andinputfromyour
colleagues.
JustStart
Codereviewsdon’tnecessarilyneedtohaveagoal.Pickatimeanddate
tosittogetherwithoneofyourcolleagues,orasateam,andhavehimor
herscrutinizeyourcode.Thesimplestquestionsareoftenthemost
powerfulones.Acommonmisconceptionisthatcodereviewsareonly
usefultodebuganissueorfindproblemsinaproject.
Codereviewsarefirstandforemostatooltoimproveyourself.I’lltalk
moreaboutthatlaterinthischapter.
CalendarandAgenda
It’simportantthatacodereviewisfocusedandproductive.That’swhyI
alwaysrecommendtoschedulecodereviewsinthecalendarsof
everyoneinvolvedandtohaveanagendabeforethecodereviewstarts.
Everyparticipantshouldbeabletoaccessandmodifytheagenda.
Oneoftheparticipantsneedstotakethelead.Thatdoesn’tmeanthat
onlyheorshecanaskquestions.Itsimplymeansthatsomeoneneedsto
makesurethecodereviewrespectstheagendaandkeepsthesession
productive.
MakeThemActionable
Codereviewscanbeveryusefulifthey’rescheduledatregulartime
intervals.Ifthat’sanoption,Irecommendcompilingalistofactionsatthe
endofeachcodereviewandevaluatingtheactionsatthestartofthe
nextsession.
Thisalsomeansthattheparticipantsofthecodereviewsneedtokeep
eachotheraccountable.Ifyoucommityourselftorefactoringa
problematicviewcontrollerinaproject,thenyouneedtomakesureit
getsdonebythenextcodereview.Ifyouignoreaccountability,yourisk
turningthecodereviewsintoarequiredmeetingnobodyenjoysortakes
anythingawayfrom.
Thegoalofacodereviewisn’tfindingbugs.Thebenefitsaremuch
broader.Youcriticallyinspectsomeone’scodeanddiscussitwithan
openmind.Thegoalistolearnandtoimprovethequalityofthecode.
Findingandfixingbugsisawelcomesideeffect.
KeepThemSmall
Whenaseniordevelopersitsdownwithajuniordeveloper,themistake
that’softenmadeisbitingofftoomuchatatime.Ifthejuniordeveloper
madedozensofcommitssincethelastcodereview,addinghundredsor
thousandsoflinesofcode,thenthecodereviewisgoingtofeel
overwhelming.Youneedfocusanddirection.
Keepacodereviewsmallandfocused,especiallyifyou’retraining
someone.Thegoalisn’ttocoverasmuchgroundorcodeaspossible.
Thegoalistogothroughachunkofcode,askquestions,andbrainstorm
ideasandalternativesolutions.Evenseniordeveloperscanlearnfrom
developerswithmuchlessexperience.
BePrepared
Ialreadymentionedthatanagendaisindispensableforproductivecode
reviews.Ittakesmoretobepreparedforacodereview,though.Areyou
unfamiliarwiththeproject?Makesureyoutakesometimetodiveinto
thecodebasetoensureyouknowwhattheprojectentailsandhowit’s
organized.Askacolleagueforhelpifyouhavelittletime.
Ifyouhavenoideahowthecodeyou’rereviewingfitsintotheproject,
thenyoumightaswellreviewarandomblockofcodeyoufoundonthe
web.Thisdoesn’tmeanthatyouneedtospendhoursbrowsingthe
codebase.Familiarizeyourselfwiththeprojectandzoominonthecode
you’replanningtoreview.That’sagoodstartifyou’reshortontime.
Tools
Therearemany,manytoolsavailablefororganizingandstructuringcode
reviews.I’mnotgoingtomentionanyofthesetoolsbecauseIfeelthat
they’resecondary.Mostofthesetoolshavetheoptiontosendsomeone
acodereview.WhileIunderstandwhythisfeatureexists,thecode
reviewsI’mtalkingaboutinthischapterarelivecodereviews,twoor
morepeoplehavingadiscussionaboutaparticularpieceofcode.
Youcanstilluseatooltokeepcodereviewsorganizedandstructured,
andIrecommendyoudo,butmakesureyoudon’toverlooktheessence
ofcodereviews.That’sthemaintakeawayofthischapter.
ThatHurts
Findingoutduringacodereviewthatyouintroducedabugcanbepainful
anditcanhurtyourego.Tobehonest,thisisafacetofcodereviewsthat
Ilike.Whyisthat?Nobodylikestomakemistakesand,frommy
experience,developersinparticularhatetobepointedoutthatthey
madeone.Afellowdeveloperpointingoutthatyoumadeamistakecan
behardtoswallow.
It’sthereforeessentialthatcodereviewsareorganizedinsuchawaythat
thefingerisn’tpointedatsomeone.Everybodymakesmistakes.No
exceptions.Ifyoudon’tbelieveme,thenhavealookatthecrashreports
oftheprojectsyouworkedoninthepastmonthoryear.
It’sagoodsignifitstingsalittlewhensomeoneuncoversabugyou
made.Itshowsthatyoucare.Don’tbearrogantandtrytoprovethem
wrongifyouknowthey’reright.Youcanonlygrowasadeveloperif
you’rewillingtogrowandlearnfromyourpeers.Learningfromsmart
developersisoneofthefewshortcutstospeedupyourcareer.Take
advantageofthisshortcutwheneveryoucan.
ConvincingManagement
It’softendifficulttoconvincemanagementofthevalueofcodereviews.
Aswithtesting,itdoesn’tseemtoresultinadirectreturnoninvestment.
Eventhoughtheresultsaren’tdirectlymeasurable,thereturnon
investmentcomesinmanyformsandshapes.
Themostobviousbenefitisanimprovementofthecodequality.Aless
obviousresultisthatdevelopersfeelmoreconfidentinthecodethey
ship,andthatisn’tonlytrueforjuniordevelopers.Havingasecondpair
ofeyeslookatacomplexpieceofcodecandowonders.
Ifeveryoneentersacodereviewwithmutualrespect,itcanalso
strengthentheteam.Thisisabenefitthatisn’timmediatelyvisibleand
easilyoverlooked.
Frequency
Howoftenshouldyouschedulecodereviews?Thatdepends.Ifyou
schedulecodereviewsonlyonceamonth,thenyoumayoverwhelm
developerswiththeamountofcodethatneedstobereviewed.
Rememberthatsmallcodereviewsaremosteffective.Toreducethe
numberofissuesyoufindduringasession,it’sagoodideatoschedulea
codereviewafterthecodeyou’rereviewingiscoveredbyautomated
tests.Thisisagoodstrategyfortworeasons.
First,youcaninspectthecodeaswellasthetestsduringthecode
review.Second,trivialissuesthatarecaughtbyautomatedtestsshould
alreadyberesolvedbeforethecodereviewtakesplace.
Thereareseveralotherfactorsyouneedtotakeintoaccount,suchas
thesizeofyourteamandthetypeofsoftwareyou’redeveloping.
ButIt’sJustMe
Whatdoyoudoifyou’reateamofone?Thatmakesitmoredifficult,but
thereareseveralsolutions.Eventhoughyouworkaloneasafreelancer
orindependentdeveloper,orjustasahobbyist,youcanalwaysaska
fellowdevelopertotakealookatyourcode.Youcanschedulecode
reviewsandexploreeachother’scodebasefromtimetotime.
Thiscanbeevenmorepowerfulthanhavingcodereviewsinateam.
Whyisthat?Eachdeveloperhasitsownstyleandthisisusuallyeven
morethecasefordevelopersthatworkontheirown.Itcanbeeye-
openingtoseesomeoneelse’scodeorhavesomeonecritiqueyour
project.
OneoftheservicesIofferiscodereviewsandprojectaudits.Itcanbe
usefultohaveathirdpartytakealookatyourcode,askquestions,
suggestalternatives,and,fromtimetotime,findbugs.
GiveItaTry
Codereviewshavemanybenefits.Ifyou’renewtocodereviews,thenI
encourageyoutogiveitashot.Irecommendrunningatrialforatleasta
fewweeksormonths.Giveyourteamthechancetobecomefamiliarwith
theprocessandtweakitasyougo.Youwon’tgetitrightfromthestart.
2AdoptaStyleGuide
Evenifyou’reworkingonyourown,inateamofone,adoptingastyle
guidecanbeveryhelpfulanduseful.Itensuresthatyousticktoasetof
guidelinesyoudefine.Theresultisthatyourcodeisconsistentandeasy
toread.
WhyHaveOne
Themostobviousbenefitofhavingastyleguideispromoting
consistency.Itensuresthatthecodeyouandyourteamproducesis
consistent.Thisbenefitaloneisenoughtoconsideradoptingastyle
guide.Butit’sonlythetipoftheiceberg.
Anotherimmediatebenefitofhavingastyleguideisimproving
readability.WhenIbrowseaforeigncodebase,itusuallytakessometime
tobecomefamiliarwiththeauthor’sstyle.Thisincludesnaming
conventions,comments,spacing,andeventheuseofcurlybraces.A
styleguidenormalizesthis,makingiteasierfordevelopersofthesame
teamtoreadeachother’scode.
Athirdsubtlebenefitisreducingfrictionwithintheteam.There’sno
internaldiscussionbetweenteammembersabouttheuseofcurlybraces
anditensuresdevelopersdon’tneedtothinkabouttheirstyle.They
simplysticktotheconventionsdefinedinthestyleguide.
Automation
I’veworkedinteamswithaformalstyleguidethatwasn’tenforcedinany
way.Teammembersweresimplyexpectedtosticktothestyleguide.If
youdecidethatastyleguidecanbenefityourteam,thenIrecommend
youalsoinvestinautomationtoenforcetherulesdefinedinthestyle
guide.
Thisisveryeasytosetupifyou’reusingXcode.Addingabuildphaseto
theprojectthattriggersashellscriptoracommandlinetoolshoulddo
thetrick.Becarefulthatthestyleguideyouenforcelocallyisuptodate.
Ifyouopenanoldproject,makesureitusesthemostrecentversionof
thestyleguide.
RoughTransition
Makingthetransitionfromnostyleguidetoaclearlydefinedspecification
canberoughforsometeammembers.Iadviceenforcingthestyleguide
fornewprojectsonlyunlessyourcompanyrunsaproductbusiness.
Youneedtoavoidthatdevelopersarespendinghoursordaysupdating
projectsbecauseofstyleviolations.Notonlyisthistime-consuming,it
almostalwaysintroducesbugsifthere’salargenumberofchangesthat
needtobemade.
Adoptingastyleguideisabigchangeformanydevelopers.Trytoease
thepainbygraduallyenforcingthestyleguide.
3WorkingInaTeam
Thewholeisgreaterthanthesumofitsparts.—Aristotle
Workinginateamcanbeajoywithmanybenefits,butitcanalsobea
challenge.Everyteammemberhasaresponsibilitytowardstheteam,
andthisdeterminesinasignificantwayhoweffectivetheteamis.
HiretheRightPeople
Growingacompanyischallengingforawiderangeofreasons,hiringis
oneofthem.Youngcompaniesareoftenstilldiscoveringthemselves,
anditmaynotalwaysbeclearwhoyouwanttohire.Youknowwhattheir
resumeshouldlooklike,buthowdoyouknowwhethertheyfitthe
company?
Ifyouaimtobuildareliable,efficientteam,youneedtohirepeoplethat
excelinateam.Youneedpeoplethatareambitiousandeagertoworkin
ateam.Thosequalitiesdon’talwaysgotogether,though.
What’smostimportantisthatthepersonyouhirefitsthecompany
culture.Findingsomeonethattickseveryboxishard,andittakestime,
especiallyinthetechnologyindustry.
Leadership
Ateamneedsaleader,evensmallones.Onepersonneedstomake
decisionsandhavethelastwordwhenpushcomestoshove.Aleader
oftenhasasignificantimpactontheteamandtheteam’sethos.
Havingahealthymixofjuniorandmoreseniordevelopersisagood
strategy.Attractingsomeonewhohasexperienceworkinginandbuilding
ateamisabigplus.
Communication
Elsewhereinthebook,Iwriteaboutfocusandproductivity.Attimes,it’s
necessarytoputonyourheadphonesandfocus.That’sunavoidableif
youwanttogetworkdone.
WhatI’vealsonoticedisthatthiscultureofheadphonescansometimes
resultinalackofcommunication.Talkingtoyourteammatesisas
importantasgettingworkdone,especiallyifyou’reworkingtowardsthe
samegoal.
Youcansolvethisseemingconflictbyorganizingteammeetingsthat
focusonteambuilding.Taketheafternoonoffforateameventthat
doesn’thaveanythingtodowithwork.Ororganizeaweeklylunchtotalk
aboutatechnicaltopic.Startadiscussionandleaveroomforeveryoneto
sharetheiropinions.
GiveItTime
Ittakestimetoturnagroupofpeopleintoateam.Itisn’tnecessarilya
naturalprocessanddon’texpectittobe.Asolidteamisn’tbuiltovernight
nordoesithappenbyaccident.
Agoodteamstrengthenswhenitgetstough.Whensomethinggoes
wrong,there’susuallyonepersontoblame,butyoutakethehitasa
team.It’sateameffort,andyouneedtoavoidthatsomeoneissingled
out,takingtheblame.You’reinthistogether.Peopleshouldbeallowedto
makemistakes.
Respect
Noteveryoneiscutouttoworkinateamandyoucan’talwayschoose
theothermembersofyourteam,whichcancausefriction.That’swhy
hiringissuchanimportantaspectofagrowingcompanyandsomething
manystrugglewith.I’msureyoucanthinkofafewexamples.
Respectisakeyingredientofahealthyteamorcompany.Thismay
seemobvious,butit’snotalwayseasy.Youcan’tchoosethepeopleyou
workwith.Thelargertheteam,themorelikelyitisthatyou’regoingto
meetsomeoneyoudon’tseeeyetoeyewith.Thisdoesn’tneedtobean
issue,though,aslongasyourespectoneanother.
WhenThingsHittheFan
Thingswillgowrongifyou’resolvingcomplexorambitiousproblems.
Acceptthatthisisinevitable.But,asImentionedearlier,theteamtakes
thehit.
Youobviouslyneedtoinvestigatetheissueandfindoutwhomadea
mistake,butrememberthatit’sateameffort.You’reinthistogether.
Someteamleadersormanagerstrytocoverproblemsup.Irecommend
takingtheoppositeapproach.Analyzetheproblemandinvestigate,asa
team,whatwentwrong.It’sinthetoughtimesthatteamsarebuiltorfall
apart.That’swhenyoudiscoverhowmuchyoucanrelyonyourteam
andyourfellowteammembers.
OwnershipandResponsibility
Takingownershipandresponsibilityareaspectsofworkinginateamthat
aren’ttalkedaboutveryoften.However,themostperformantteamsand
companiesIworkedwitharetheonesthatembracethesevalues.
Therearedozensanddozensofsmalltasksinacompany.Havinga
committedteammakeshandlingthesetasksmucheasier.Knowingthat
someonetakescareofaparticulartaskyoudon’tneedtoworryaboutis
oneofthemostenjoyableaspectsofworkinginateam.
That’salsooneoftheaspectsIenjoyedmostwhenIwasworkingasa
subcontractor.WhileI’veworkedwithmanyprojectmanagersoverthe
years,Ihadmyfavorites.Anexperiencedprojectmanageriscoretoan
effectiveandefficientteam.They’rethegluethatbindsclients,designers,
developers,andtesterstogether.Anexperiencedprojectmanagerowns
theprojectandtakesthefinalresponsibilityforeveryaspectofthe
project.
Anddevelopersneedtodothesame.Ifsomethinggoesamiss,thenthe
personresponsibleforthataspectneedstostepupandtakecareofthe
problem.
Whensomethinggoeshaywireandpeoplestartpointingfingersateach
other,thenthere’saproblemthatneedstobeaddressed.Itshouldbe
obviouswho’sresponsibleandwhoneedstotakeaction.Thatperson
shouldn’tbeblamedforwhatwentwrong,though.Itmerelyeliminates
thediscussionwhoneedstostepinandfixtheproblem.
ShareandAsk
I’msureit’sobviousthatyoushouldsharewhatyouknowwiththeteam
andlearnfromyourteammates.It’soneoftheshortcutsinsoftware
developmentthatyoushouldtakeadvantageof.StackOverflowisgreat,
butnothingreplacesahealthydiscussionwithyourteammatesabouta
technicaltopicoraproblemyou’retryingtosolve.
Anddon’tforgettoincludedesignersandmanagers.I’vehadmany
interestingdiscussionswithteammembersthatweren’ttechnical.
There’smoretosoftwaredevelopmentthanwritingcode.
4BeingaLeader
Asafreelancer,Idon’thavemuchexperienceleadingteams,butI’ve
beenpartofseveralteamsasasubcontractor.Leadingateamand
actingasaleadercanbechallengingfordevelopersbecausethey’renot
alwaysaskingforthistypeofpromotion.Asacompanygrows,teamsare
formed,andateamneedsaleader.
ListenandBeOpen
Agoodleaderlistenstothepeopleheorsheworkswith.Itcanbe
frustratingtobepartofateaminwhichyourvoiceisn’theard.Itdoesn’t
meanthatyouneedtotakeactionbasedonwhatyouhear,butyouneed
tomakesureeverymemberoftheteamknowsthatheorshecan
approachyou,talktoyou,andknowthatyouunderstandthem.
It’sequallyimportanttobeopeninyourcommunication.Alwaysmake
surethattherearenounresolvedissuesinyourteamthatcreatetension.
Talktoyourteammembers,asateam,andinone-to-onemeetings.
Everyoneneedstobeuptodateaboutwhat’sgoingonintheteamand
thecompany.Ifateammemberoremployeeisunawareofanimportant
eventorannouncement,thenthatpersonmayfeelleftoutornotpartof
theteam.
Modesty,Humility,andRespect
ThemostmemorableleadersIworkedwitharemodestandhumble.
Theycanbringthebestoutofyou,takingadvantageofthestrengthsof
eachmemberoftheteam.
Developersthatdon’tfeelcomfortableleadingateamsometimeshave
thetendencytopleasetheteamtheyleadinanattempttoearntheir
respect.Ifyouclimbtheranksinacompanyandarepromotedfromteam
membertoteamleader,thenearningthatpositioncanbechallenging.
Butyoudon’tearntherespectofyourteambyattemptingtoplease
them.
WorkasaTeam
MostoftheteamorprojectleadsI’veworkedwithhadtoomuchontheir
plate.That’savery,verycommonproblemforpeopleleadingateamora
company.Theirworkloadisn’talwaysthecauseoftheproblem,though.
Twocausesareverycommon.
Thefirstcauseiswantingtodoeverythingyourself.Inexperienced
leaders,especiallythosewithahealthydoseofpride,findithardtoask
themembersoftheirteamforhelp.Youwon’tbeabletodoeverything
yourselfandyouneedtolearntodelegatetaskstothemembersofyour
team.
Thiscanhaveadramaticimpactonyourworkload.Atfirst,itcanfeelas
ifyou’reaskingsomeoneelsetodoyourjob,butthatfeelingquickly
disappearsonceyoudiscoverthatyouhavemoretimeforothertasks,
suchasorganizingyourteamandsettingupone-to-onemeetingswith
thepeopleofyourteam.
Delegatingissomethingyouneedtolearnanditalsomeansyouneedto
knowthepeopleonyourteamverywell.Eachmemberhastheir
strengthsandweaknesses.It’suptoyoutoleveragethisdiversityand
usethestrengthsofyourteamtoyouradvantage.
Thesecondcauseiscloselyrelatedtothefirst.Handingcontroloverto
otherpeoplecanbescary,veryscary.You’retheleaderofyourteamand
thatmeansthatyoucarrythefinalresponsibility.Asaresult,
inexperiencedleadershavetheurgetomakesureeverythingisexactly
astheywantittobe,asiftheydiditthemselves.
Thisapproachisn’thealthy.First,theresultisthatyouincreaseyour
workloadfornogoodreason.Second,youmaygiveotherteam
membersafeelingofinadequacy,notbeinggoodenough.Itcan
sometimesbegoodtoletthingshitthefan.Everyonelearnsfromsuch
anexperience.
Ifyoustillstrugglewiththis,thenyoumaywanttoembracecodereviews
orroundtables.Thesecanbeveryeffectivestrategiestobuildyourteam,
showthemhowthingsshouldbedone,andmakesureeveryoneison
thesamepage.
WorkingWithPeople
Asadeveloper,you’reusedtofindingandimplementingsolutionsto
problems.It’snotthatstraightforwardifyou’reworkingwithpeople.
Developersshareapassionforsolvingproblems,butthey’rehuman
beingsandeachofusisdifferent.Thismeansthatyouneedtoapproach
everymemberofyourteamorcompanyalittledifferently.
Thiscanbeoneofthemostchallengingaspectsofbeingaleader
becauseitmeansyouneedtorelyonyourintuition.Youneedtobeable
toreadthepeopleonyourteamandrelyonyourpeopleskills.
Someofyourteammatesareextrovertsandyoualwaysknowwhat’son
theirmind.Othersarequiet,shy,ornoteagertosharetheiropinionswith
others.Ittakesleadershiptoensurethevoiceofthequietisalsoheard
bytheextrovert.
FollowYourGut
Evenifyousignupforacrashcourseinleadership,ittakestimeformost
peopletobecomealeaderandbeseenasone.Youwon’talwaysknow
whattodoincertainsituations.Howdoyouhandleaconflictwithinyour
team?There’snooneorrightanswer.
Astheleaderofyourteamorcompany,you’reinthebestpositionto
assessthesituationandmakeadecisionthatfeelsrighttoyou.It’s
possiblethatyoutakethewrongdecision,butthat’showitis.Youwin
someandyoulosesome.Learnfromyourmistakes,betransparent
aboutthem,andmoveon.
Lead
Listeningtothepeopleyouworkwithandaskingfortheirinputis
essentialtobuildingahealthyteamorcompany.Butalwaysremember
thatyou’retheleaderandyouhavefinalsaywhendecisionsneedtobe
made.Andthat’swhatateammemberexpectsfromitsleader.When
pushcomestoshove,youneedtoshowthatyou’retheleaderandthe
manorwomantakingthedecisions.
Thiswon’talwaysbeeasy,butit’snecessary.It’sassimpleasthat.You
won’talwaysknowwhetherthatdecisionistherightone,butthat’showit
is.That’swhatsetsaleaderapartfromateammemberoranemployee.
PART6:CAREER
1OpenSource
Theconceptofopensourcehasbeenaroundfordecades,butplatforms
likeGitHubhaveacceleratedthegrowthofopensourceinitiatives.Most
ofuscan’timagineaworldwithoutopensourcesoftware.
Opensourcesoftwarecanbeapowerfulinstrumenttopromoteyourself
asadeveloper.ManyrespecteddevelopersintheCocoaandSwift
communitieshavegainednameandfamethroughtheiropensource
projects,thinkEloyDurn,MatttThompson,andOleBegemann.
StartSmall
Ifyou’renewtoopensource,thenIdon’trecommenddivinginheadfirst.
Startsmall.I’msurethereareseveralopensourceprojectsyoumake
useofinyourownprojects.Agoodplacetostartistoexplorethe
documentationoftheseprojects.That’sright.Thedocumentation.
You’dbesurprisedbythenumberofopensourceprojectsthathave
outdateddocumentation.Thisisn’tsurprisingsinceitrequiresalotof
worktomaintainanopensourceproject.Becauseyou’realreadyfamiliar
withtheproject,youcanbrowsethedocumentationandfixanyissues
youfindonyourpath,includingtyposandgrammaticalissues.Whilethis
mayseemnitpicky,theauthoroftheprojectwillthankyouforit.
Clonetheproject,makethechanges,andsubmitapullrequest.Make
sureyoureadtheguidelinesforcontributingtotheprojectfirst.Many
projectshaveacodeofconducttomakecontributionseasierandreduce
friction.
TakingthePlunge
Youmayalreadyhavealibraryorprojectyouwanttosharewiththe
community.Sharingsomethingwiththeworldcanbescary,though.
Makesureyou’vecleaneduptheprojectanddon’tshareanypersonalor
confidentialinformation.Whenyousharearepositorywiththeworld,you
giveeveryoneaccesstoitshistory.
Forexample,ifyoucommittedaprivatekeyortokenatsomepointand
removeditlater,thenanyonewithaccesstotherepositorycanretrace
yourstepsandaccessthatinformation.Removetheprojecthistoryifyou
wanttoplayitsafe.Oncetheinformationispublic,there’snowayback.
Documentation
Mostofusdon’tspendmuchtimedocumentingpersonalorinternal
projects.That’sadecisioneveryoneneedstomakeforthemselves.An
opensourceprojectwithoutdocumentation,however,won’tgetmuch
traction.Notonlyisitdifficultforanyoneinterestedinyourprojecttoget
uptospeed,it’snotahealthysign.
EverytimeIlookforathirdpartylibrarytoincludeinaproject,I
immediatelydiscardrepositorieswithoutaproperREADME.Itonlytakes
afewminutestocreateaREADMEandanadditionalhourtocreatean
installationandgettingstartedguide.Notonlydoesyourprojectlook
moreappealing,youhelpanyoneinterestedinyourproject.
Youcantakeitonestepfurtherandaddasampleapplicationthatshows
developershowtouseyourlibrary.Anyonenewtoyourlibrarycanplay
withthebundledapplicationandseeforthemselveshowtouseyour
libraryandintegrateitintoaproject.
TakingItSeriously
Thecommitmentofsomedevelopersisadmirable.Theycovertheir
projectwithunittests,setupcontinuousintegration,andwritepagesand
pagesofdocumentation.Thisisusuallyacommunityeffortandthat’s
what’swonderfulaboutopensourcesoftware.Onceyourprojectgains
traction,developersautomaticallystartgivingbackwithsmall,orlarge,
contributions.
Thesecontributionsareverywelcome,especiallyifyouhavelimitedtime
tospendonyouropensourceproject.Ifyou’reafreelanceroran
independentdeveloper,thenitcanbeabreathoffreshairtocollaborate
withotherdevelopersonaproject.That’sabonusyougetforfree.
GivingUpControl
Forsomedevelopers,thehardestpartofopensourcingaprojectis
givingupsomeofthecontroltheyhaveovertheproject.Youcandecide
tomanageeverythingyourself,butthatisn’tfeasibleifyourproject
becomespopular.Italsogoesagainstthespiritofopensourcesoftware.
Toavoidthatyourprojectbecomesmessyandanoddcollectionof
codingstyles,youshouldadoptandenforceastyleguide.Thisisn’t
difficulttoimplement.WhenIsubmittedmyfirstpullrequesttothe
CocoaPodsproject,Iimmediatelyreceivedautomatedfeedbackabout
thecodingstyleIwasusing.Itookalookattheproject’sstyleguide,
madeafewchanges,andsubmittedanupdate.Havingastyleguide
that’sautomaticallyenforcedhelpstokeepyourprojectconsistentandit
keepsthemaintainer(s)sane.
TakingResponsibility
Oneofthemostchallengingaspectsofanopensourceprojectiskeeping
ituptodate.Ittakestimeandefforttokeepyourprojectsuptodate.
Automationcanmakethismucheasier.Knowthatseveralhosted
continuousintegrationsolutionsofferafreetierforopensourceprojects.
Ifyou’reseriousaboutyourproject,thenthatmaybeworthlookingat.
Andrememberthatyoudon’tneedtodoeverythingyourself.For
Cocoacasts,Icreatemany,manyprojectsforthetutorialsIwriteand
record.It’schallengingtokeepthemuptodate.Ifareadernotifiesme
thataprojecthasn’tbeenupdatedforthelatestversionofSwiftorXcode,
thenIsuggestthattheysubmitapullrequest.That’snotunreasonable.Is
it?
Opensourceisacommunityeffortandeveryoneinvolvedinaproject
shouldtakeresponsibility.
2YouAretheConstantinYourCareer
Oneofthereasonsforwritingthisbookisthatitallowsmetotalkabout
subjectsthatarerelatedtoprogramming,software,andthelifeofa
developer.Eventhoughthey’rerelated,they’reoftenoverlookedor
ignored.Thisisespeciallytrueforyoungdevelopers.Don’tfeelbad,
though.It’snaturalandmaybeevenanecessarypartofyourevolutionas
adeveloper.
PuttingYourselfFirst
Mostofyourtimeisspentworkingforsomeoneelse,aboss,amanager,
oraclient.Thetechnologyindustryisknownforlongdaysandweeks
andsacrificingtimewithfriendsandfamily.Butdon’tletthatdistractyou
fromwhat’simportant.What’simportantisn’ttheprojectyou’reworking
onortheclientyou’rebuildingamobilesolutionfor.What’simportantis
you.Whyisthat?
Manydeveloperschangejobseveryfewyears.Therearemanyreasons
fordoingso.That’snotthepoint,though.Nomatterwhereyouendup
next,there’sonlyonethingyoutakewithyou.You.You’retheconstantin
yourcareer.Thismaysoundlikeasimpleplatitude,butitisn’t.
TherehavebeentimesthatIworkedforthesameclientforseveral
years.Itwasgoodmoney,butIdidn’tfeelIwasreachingthegoalsIset
formyself.IfeltthatIwasstagnatingasadeveloper,andthat’snota
goodthingforafreelancer.Thespaceisevolvingatbreakneckspeed
andyoucan’taffordtostagnate.
SettingGoals
Everynowandthen,Isetgoalsformyselftokeepmemotivated,
accountable,andtomakesureIcanobjectivelyvalidatethatI’mevolving
asadeveloper.I’msureyouhaveafewthingsonyourlistthatyouwant
tolearn,someday.Who’skeepingyouaccountable?Howlonghave
theseitemsbeenonyourlist?
LearningRequiresanInvestment
Ifyou’reinluck,thenyouhavethetimetolearnnewthings.Youmay
evenhaveabossormanagerthatexplicitlyasksyoutoinvestigatea
newtechnologytopickup.
Learningsomethingnewrequiresyoutoinvesttimeandenergy.You
needtoallocatetimetoseriouslylookintoandexperimentwiththe
technologyyou’relearning.
TakeCareofYourself
EarlierImentionedthatlongdaysandweeksarenotuncommoninthe
technologyspace.That’sfineaslongasyoudon’tpushyourselftoo
hard.Everyonehaslimits.Iknowwhatit’sliketofeelinvinciblewhen
you’reinyourtwenties.Thatfeelingofinvincibilitydisappearsgradually
asyouapproachyourthirtiesandforties.Burningthemidnightoilisn’t
somethingI’vedoneinalongtime.I’mtoooldforthat.
I’vebeenarounddevelopersforlongenoughtoknowandunderstand
howtemptingitcanbetoonlyfocusonthejob.Weliveintimeswhere
workisavalidexcuseforignoringotherimportantaspectsofourlives.
Workingoutorgoingforasimplewalkisoftenmoreimportantand
sacrificedasaresult.
Itshouldcomeasnosurprisethatmanyofussufferfromaslewof
illnessesandsubtlehealthproblems,fromobesity,diabetes,andback
problemstochronicfatigueandbadsleep.Theunderlyingproblemis
surprisinglyoftenrelatedtowork,directlyorindirectly.
Ifyou’reinyourtwenties,thenyouprobablythinkthatI’mtalkingrubbish.
Ifyou’reinyourthirties,thenyoumightalreadythinkabitdifferently.If
you’reinyourforties,thenyou’reprobablynoddingyourhead.
LookingBack
I’dliketoendthischapterwithasimpleassignment.InDecember,I
alwaystakethetimetolookbackatthepastyear.Thelastweeksof
Decemberareidealforthisexercise.Workisslowingdownandmany
peoplearetakingsometimeofftospendwithfriendsandfamily.Butyou
candothisexercisewheneveryoulike.
Takeapieceofpaperandwritedownwhatyou’veaccomplishedthis
year.Don’tuseacomputeroranotherelectronicdevice.Useapenor
pencilandapieceofpaper.Whichgoalshaveyouaccomplishedthat
movedtheneedleforyou?Notforyourboss.Notforyourclients.For
you.
Whathaveyoulearned?Whohaveyoumetorspokenwiththatimpacted
yourwayofthinking?Whatbookshavemadeanimpactonthewayyou
thinkaboutyourworkasadeveloper?Giveyourselftentofifteen
minutes.Don’tstoptoosoon.Thebeststuffcomesoutafteralittlewhile.
Areyouhappywiththelistyou’vecompiled?
3BuildThatApplication
Doyouhaveafolderonyourmachinethat’sfilledwithunfinished
projects?Behonest.Iknowyoudo.Ihavedozensofunfinishedprojects.
Eachoftheseprojectsstarteditslifeasanexcitingidea,anideaI
absolutelyneededtoexecuteon.
Whenafresh,excitingideaentersthemindofasoftwaredeveloper,it’s
hardtoresistthemadness.Theseprojectsoftenstartwithafewdaysor
weeksofhardwork,verylittleplanning,nobusinessplan,andonlya
vagueideaofwhatthefinalresultwilllooklike.
Theseunplannedprojectsaregreat.Iloveworkingonthem.Thesadpart
isthattheyalmostalwaysendupcollectingdigitaldust,joiningdozensof
otherunfinishedprojects.Buildingiseasy.Shippingishard.
BuildandShip
Realartistsship.—SteveJobs
SteveJobsfamouslysaidthatrealartistsshiptheircreations.You’llfind
thisquotemorethanonceinthisbook.It’seasytocomeupwitha
compellingidea,spendafewdaysorweeksbuildingtheproduct,and
shelveit,elegantlywrappingitinapromisetofinishitwhenyouhave
moretime.
It’seasy,but,moreimportantly,it’ssafe.It’ssaferbecausefewpeople
arewillingtoshowtheworldwhattheycreated.Theyfeartheopinionsof
others.Theyfearpeoplearegoingtojudgetheirproductand,even
worse,itscreator.
ShowWhatYouCan
Whenyou’reapplyingforajob,showingthatyouhaverelevant
experienceisoftenessential.Nottoolongago,severalyearsof
experienceweremandatoryforajobasasoftwaredeveloper.
Nowadays,employersarelookingmoreandmoreattheportfolioof
potentialcandidates.Thisisespeciallytrueinsoftwaredevelopment.
Peoplenewtosoftwaredevelopmentorgraduateslookingfortheirfirst
jobmayfinditchallengingtoprovethattheyhaveexperiencedeveloping
software.Thetruthisthattheyoftendon’thavethenecessary
experience.
Howdoyousolvethisproblem?Howdoyoubreakthisviciouscircle?
Don’twaitforthatfirstjoborprojecttostartgainingexperience.Show
potentialclientsoryourfutureemployerthatyouhaveexperience
buildingsoftware.It’sneverbeeneasiertogetstartedwithsoftware
development.What’sstoppingyoufromcreating?
StayAhead
Whileit’sfinetolearnasyougo,it’llcertainlyhelpyouifyouknowthe
basicsofthemostcommontasksofsoftwaredevelopment.Buildingand
launchingasoftwareproductisquiteaninvolvedprocess.Itdoesn’tstop
themomentyouhavesuccessfullybuiltanddeployedyourfirstiOS
applicationonyouriPhoneoriPad.
Haveyouthoughtaboutbetatesting,launchimages,applicationicons,
andlocalization?Ifyoucanshowyourfutureemployerthatyouhave
thoughtof,built,andshippedasoftwareprojectthat’spolishedand
carefullymaintained,you’realmostcertainlywhatthey’relookingfor.An
interviewisalmostguaranteed.
RinseandRepeat
Apple’sAppStoreisfilledwithabandonedapplications.Frequent
applicationupdatesareasigntoyourcustomersthatyou’rebuilding
somethingyoucareaboutandcustomerswillautomaticallyfeelthatyou
alsocareaboutthem.
Itisn’tnecessarytoincludeamajorfeatureineveryupdateyouship.
Improvingyourapplication’sstabilitybyfixingbugsisjustasimportantas
focusingonfeatures.
Localizationisanotheraspectthat’seasilyoverlooked.Didyouknowthat
Japanisoneofthemostprofitablemarketsformobileapplications?
Considerworkingwithatranslatortotranslateyourapplicationto
Japanese.Itwon’tcostyoumuchandyou’lllearnalotfromthe
experience.YourJapanesecustomerswillthankyouforit.
BuildThatApplication
Iencourageyoutostartbuildingand,moreimportantly,tostartshipping.
Yourfirstapplicationdoesn’tneedtobeperfect.What’simportantisto
getitinthehandsofyourcustomers.Createsomethingusefulforothers.
Refinewhatyou’vecreatedandlistentoyourcustomers.What’sstopping
you?Whatareyouwaitingfor?Gainexperiencebybuildingand
shipping.
4ProtectYourProductivity
Howproductiveyouareasadeveloperisn’tonlytheresultofyourhabits,
yourtalents,andyourexperience.Yourenvironmentplaysakeyrole,
especiallyifyouworkinateam,acompany,orasharedworkspace.
Somedevelopersthriveinanoisyorbusyenvironment,butthoseare
usuallyexceptionstotherule.Thatruleissimple“Don’tinterruptthe
developer.”
WorkingFromHome
Workingfromhomeisaluxuryifyouhavethedisciplinetosetclear
boundariesforyourself.Unfortunately,it’savery,verycommontrap
manypeoplefallinto,notonlydevelopers.Whenyoumaketheswitch
fromworkingasanemployeeinalargeofficetoworkingfromhomeina
smallhomeoffice,ifyou’reluckytohaveone,youmaynaivelythinkyour
productivityisabouttoskyrocket.Theoppositeisalmostalwaystrue,
especiallyinthefirstfewdaysorweeks.
Makingadrasticchange,suchasmovingintoahomeoffice,meansthat
youneedtocreatenewhabits.Mostofusbelieveithaseverythingtodo
withdiscipline,butthat’sonlypartoftheequation.Takethetimetocreate
aschedulethatworksforyouandthepeopleyouworkandlivewith.That
maymeanthatyoustartearlyorputinafewextrahoursintheevening
whenthekidsareasleep.
Youneedtodefineboundaries,notonlyforyourself,alsoforthepeople
youlivewith.Workingfromhomeisstillwork.
WorkingInanOffice
Workinginanofficehasitsprosandcons.Theadvantageisthat
everyoneknowsandunderstandsthatyou’reatworkto,well,work.Make
itclearthatyoudon’twanttobedisturbed.Protectyourproductivity.This
maysoundharsh,butit’sessentialifyouwanttogetmeaningfulwork
done.
Asadeveloper,yourmostimportantassetisyourattention.Ifyou’re
workingonacomplextask,ittakestimetogainmomentumandbe
productive.Everytimeyou’reinterrupted,youneedtostartfromsquare
one.Notonlyisthisfrustrating,itcanbementallytaxing.
Ionceworkedinanofficethathadasimplerulethatsaidthata
developerwithitsheadphonesonshouldn’tbeinterrupted.Aroomfilled
withpeoplewearingheadphonesisn’tuncommoninthetechnology
industrywhereopenofficesarethenorm.You’dbesurprisedbythe
numberofdevelopersthatwearheadphoneswithoutactuallylisteningto
music.It’satrickI’veusedmany,manytimes.Thisisespeciallyeffective
ifyourheadphoneshavenoisecancellation.
Whilethisrulelooksgreatonpaper,itdoesn’tholdupinmostsituations.
Everyoneisinterrupteddozensoftimesaday.Thenumberofproductive
hoursweputinismuchlowerthanyou’dthink.That’stherealitywelive
in.
MinimizingInterruptions
Slackandemailhavebecomeindispensableinmostcompanies,large
andsmall.They’regreattoolsforcommunicationifthey’reusedwisely.
They’renotmostofthetime.They’resurprisinglyoftenusedas
distractionsinsteadofproductivitytools.
Makesureyou’renotdistractedbyaslewof,oftenunimportant,
notifications.Ifyou’reconstantlyinterruptedbynotifications,thenit’s
clearyouhavenointentionofgettingworkdone.Don’tlookfor
productivityhacksifyou’renotseriousaboutthemostfundamental
elements.
FindaQuietPlace
Ifyouhaveadeadlinetomeetoryouabsolutelyneedfocus,thenlooking
foraquietspotintheofficemaybeyourlastresort.Thisisn’tasolution
longterm,butit’ssometimesyouronlyoption.Ifyou’reinluck,youmay
findanemptymeetingroom,butacouchorthekitchenisfinetoo.Don’t
forgettobringyourheadphones.
DealWithIt
Distractionsandinterruptionsarepartoftheworldwelivein.Workingin
thetechnologyindustrymeansthatyou’reintheeyeofthestorm.
There’snoperfectsolutionunlessyouworkfromahomeofficewhere
youdictatetherules.
5BuildingYourPortfolio
Aportfolioisoneofthemostimportantassetsofanydeveloperwith
ambition.Mobileapplications,forexample,aresocommonplacethat
potentialemployersorclientswillwanttoseewhatprojectsyou’ve
workedoninthepast.Aspiringdevelopersoftenaskwhattheyshould
showiftheyhaven’tcreatedanyapplicationsyet.Theanswerissimple.
Startcreating.
Ifyou’relearningtheropesofsoftwaredevelopmentandyoudon’thave
anyclientsyet,thenwhatareyoudoingallday?Youdon’tneedtolearn
everythingthereistoknowaboutsoftwaredevelopmenttostartyourfirst
project.
ScratchanItch
Whilenoteveryideawillbearunawaysuccess,theitchesyouhaveare
perfectforyourfirstprojects.Ifyou’rejustgettingstarted,thenit’s
importanttochoosearelativelyeasyproblemtosolve.
ThefirstapplicationIshippedwasaniPadapplicationthatallowedusers
toimportandtagimagesfromanApertureoriPhotolibrary.WhileIdid
eventuallypublishtheapplication,itwasabittoocomplexforafirst
project.
Startsmallandbuildlarger,moreambitiousprojectsasyougrowasa
developer.Bybitingoffmorethanyoucanchew,youmaylosemotivation
orbecomediscouraged.
SettingGoals
Theprimarygoalofyourfirstprojectshouldbesimple,creatingand
publishinganapplicationthatprovidesvaluetopeople.Youcanset
secondarygoals,suchastryingtomonetizeyourapplicationorclimbing
thechartsoftheAppStore.Thosegoalsarelessimportant,though.
Monetizingyourapplicationisonlypossibleifyoushareitwiththeworld,
whichmeansyoufirstneedtobuildandshipanapplication.
Iloverunning.EverytimeIgoforarun,Ihavethreegoals.Thefirstand
mostimportantgoalistoenjoytherun.Thesecondgoalistofinishthe
run.Andthethirdgoalistobeatmybesttime.
Intheearlystagesofyourcareer,it’simportanttoapproachsoftware
developmentwiththesamemindset.Makesureyouenjoywhatyou’re
doing.Ifyoudon’t,youwon’tstaycommittedtolearningyourcraft.It
shouldn’tfeelasastruggle.Idaresaythatitshouldn’tevenfeellike
work.
Itshouldn’tfeelasastruggle.
Thesecondgoalshouldbetocompletetheprojectyou’reworkingon.
Onceyoucommittoaprojectoridea,it’simportantthatyoustickwithit.
SteveJobsfamouslysaid“Realartistsship.”Asadeveloper,you’re
creating.Thatalsomeansthatyouneedtoshipyourcreations.
Realartistsship.—SteveJobs
Thethirdgoalistheproverbialcherryonthecake.Thatgoalmaybe
hittingthetopchartsinyourapplication’scategoryorreachingacertain
numberofdownloads.That’suptoyou.
WhyamIgivingyouthisadvice?Andwhatgivesmetheauthoritytogive
youadviceinthefirstplace?Askanydeveloperhowmanyprojectsthey
startedbutneverfinished.Startingprojectsisfine.Butsometimesyou
needtoship.Doyouwanttobetakenseriouslyasadeveloper,thenyou
needtobeabletoshowthatyoucanstartandfinishsomething.
Doyouwanttobetakenseriouslyasadeveloper,thenyouneedto
beabletoshowthatyoucanstartandfinishsomething.
WheneverIinterviewadeveloperforaproject,Iaskthemabouttheir
previousprojects.Yourfutureemployerorclientswilldoexactlythat.
Evenifyouplantostartasajuniordeveloperoraninternatacompany
oragency,itplaystoyouradvantagetoshowoneormoreprojectsyou
startedandfinishedsuccessfully.Itmakesaworldofdifference.Why?
Becausefinishingsomethingisharderthanitseems.
IfsoftwaredevelopmentispartofyourDNA,thenyou’llbeabletostart
andcompleteyourfirstsoftwareproject.Mostdevelopershaveahard
timestoppingthemselvesfromcreatingcoolsoftwareorusingthelatest,
fancylibraries.Despitethisdrivetocreate,it’sequallyimportanttofinish
andship.Icannotemphasizethisenough.
LearntheBasics
Aquestionthatcomesupofteniswhetheryoushoulddiveinheadfirstor
learnthebasics.Theansweris,“Both.”It’skeythatyouknowthe
foundationofthelanguageyou’reusing,butit’salsoimportantthatyou
startcreatingassoonaspossible.Iexplainthisinmoredetailinthefirst
chaptersofthisbook.
Apple’splatformsaresoaccessiblethatIguaranteeyouthatyoucan
createabasicCocoaapplicationthedayyoustartlearningCocoa
development.There’snoneedtoreadTheSwiftProgrammingLanguage
fromcovertocover.It’lldiscourageyousinceyoustartedwithCocoa
developmenttocreatecoolthings.Mysuggestionistochooseaguide
thatteachesyouSwiftasyoulearntheropesofsoftwaredevelopment.
Thesooneryouseethebiggerpicture,thesooneryou’llfeelcomfortable
onthepathyou’retaking.
Thereisonebigbut,though.Ifyouonlyfocusoncreatingthingsand
don’ttakethetimetolearnthemoreintricateaspectsoftheplatform,
you’llendupcreatingbugs,missingbestpractices,and,intheend,being
frustratedwhysomethingisn’tworking.RememberwhatIwroteearlier,
“Don’tignoreyourfoundation.”
Learningahumanlanguageiseasyatfirstifyouonlyfocuson
memorizingwordsandsentences.Yourmemoryisonlyabletotakeinso
much,though,andwhatareyougoingtodoifyourunintoasituationyou
don’tknowanythingabout?
Mostlanguagecoursesstartwithsimplesentencestogivestudentsthe
feelingthatthey’remakingprogress.Soonerratherthanlater,theteacher
teachesthemaboutspellingandgrammar,explainingthesentencesthey
learnedfromagrammaticalpointofview.
Thegististhatyouneedtobecomefamiliarwiththebasics,the
foundation,ifyouwanttogrowasadeveloper.Itisn’talwaysas
interestingaslearningthecoolthings,butit’sjustasimportant.
ButStartCreating
Nomatterwhatpathyouchooseorwhatlanguageyoulearn,it’s
importanttostartcreating.Setagoal,pickaproblemyouwanttosolve,
andbuildasolution.That’swhatsoftwaredevelopmentisabout.
6HowBadlyDoYouWantIt
Itisn’teasyforinexperienceddeveloperstofindanattractivejobwithout
yearsofexperienceoranimpressiveportfolio.Thatshouldn’tbean
excuse,though.It’sneverbeeneasierfordeveloperstobuildaportfolio,
gainingexperiencealongtheway.Inthischapter,Ishowafewexamples
ofhowyoucanbuildaportfolioandgainexperiencetohelpyoufind
clientsorimpressyourfutureemployer.
Contribute
WheneverIvetadeveloper,Itakealookattheirpastwork.Opensource
contributionsareidealforthis.Itisn’tnecessarytobuildanopensource
projectfromthegroundup,though.Engagementandtakingresponsibility
inexistingopensourceprojectsisagoodfirststep.
Manywellknowndevelopershavegainednameandfamebycreating
andmaintainingopensourceprojects.EloyDurán,forexample,had
yearsofexperienceasaRubydeveloperandmissedareliable
dependencymanagerforCocoa.Insteadofcomplainingaboutit,he
createdCocoaPodsandturneditintothemostpopulardependency
managerforCocoadevelopment.
Opensourceprojectsoftendieaquietdeathduetothelackof
contributors.Butanothercommonreasonistheabsenceofgood
documentation.Nothingstopsyoufromcreatingapullrequesttoupdate
theREADMEofanopensourceprojecttopolishitsdocumentation.
Developersnewtotheprojectwillthankyouforitandsowillthe
maintainersoftheproject.
Build
It’sneverbeeneasiertocreatesoftware.Gettingstartedwithsoftware
developmentisn’tthathard.What’sstoppingyoufromcreatingyourfirst
mobileapplication?Ifyou’relookingforajob,thenyourfutureemployer
willaskyouaboutyourportfolio.
Findingclientsishardwithoutaportfolio.Wouldyouhireanarchitect
whohasneverbuiltahousebefore?Thefactthatyou’relookingforyour
firstjobasasoftwaredeveloperorfreelancerisn’tanexcusefornot
havingaportfoliowithoneortwoapplications.Buildthatapplication.
Maintain
Beingasoftwaredeveloperalsomeansthatyou’reresponsiblefor
maintainingwhatyoucreate.Itisn’tnecessarytoshipanewfeature
everymonth.What’smoreimportantismakingsureexistingusersare
happyandstayhappy.
Takealookatthecrashreportsofyourapplication.Arethereanyissues
youcanfix?Whatarepeoplecomplainingabout?Couldyouimprovethe
onboardingexperience?
Beingabletoshowthatyouhavetheskillstobuildandmaintaina
softwareprojectgoesalongway.Notonlywillyourfutureemployerlook
fortheseskills,youalsoneedthemtoexcelasasoftwaredeveloper.
PlanandManage
Ifyouwanttotakeitupanotch,thenschedulingreleasesandadding
featuresisthenextstep.Theideaistostartsimple,buildamodestuser
base,andimprovetheapplicationovertime.Listentotheusersofyour
application,siftthroughthefeaturerequests,anddecidewhichfeatures
makethecut.Rememberthatyoumanagetheproject,nottheusersof
yourapplication.
Testanewfeaturebeforereleasingittothepublic.Involveyourexisting
usersbydistributingabetabuildoftheapplicationthroughFabric,
Hockey,orApple’sTestFlight.
Addingsupportformultiplelanguagesisanothergreatimprovementthat
underlinesyourcommitmenttotheproject.Thismayinvolvehiringa
translator.
GainExperience
Gettingstartedwithsoftwaredevelopmentiseasy.Startingfromzeroand
publishinganapplicationonApple’sAppStorerequireseffortand
perseverance,though.Itmeansthatyoucannotquithalfwaywhenyou
don’tfeellikefinishingtheproject.Everydeveloperhasaslewofprojects
theystartedworkingonandneverfinished.
Finishingishard,butthat’sexactlywhatyourfutureemployerorpotential
clientswanttosee.There’snothingmoreenjoyablethanstartinganew
project,butittakesgritandtenacitytofinishaprojectandclickthe
submitbuttontopublishyourcreationontheAppStore.
It’stofinishaprojectandshipsomethingpeoplecanuse.Itcanbescary
toshareyourworkwithyourpeers,butthat’swhatittakestosucceed.
BeYourself
There’snoneedtocompetewithyourpeers.Ifyoucontinuetodowhat
youloveandwhatyou’regoodat,youwillgetwhereyouwanttobe.But
rememberthatyouonlygetwhatyouworkfor.Ifyouaimformediocracy,
thenthat’swhatyou’llget.Ifyouaimforthebest…
HowBadlyDoYouWantIt
Whetheryousucceeddependsonthequestion“Howbadlydoyouwant
it?”Areyouwillingtoworknightsandweekends?Tomakeadent,you
willneedtogobeyondshowingup.
Showingupisoverrated.Necessarybutnotnearlysufficient.—Seth
Godin
It’simportanttobehonestwithyourselfanddefinewhatyouexpectfrom
yourcareerasasoftwaredeveloper.GaryVaynerchuckisspotonwhen
hesays“Ifyouliveforweekendsorvacations,yourshitisbroken.”Isthat
youorareyouaiminghigher?
Ifyouliveforweekendsorvacations,yourshitisbroken.—Gary
Vaynerchuk
WhatAboutYou
Areyoumotivatedtogetoffyourbuttandmakeawesomestuff?What
areyourgoalsanddreams?Youdon’tknow?Thenthat’sthefirstthing
youneedtosortout.
7FreelancingandSubcontracting
Makingalivingasanindependentfreelancedeveloperisgreat,butitcan
beatoughjobattimes.WhatIenjoymostaboutfreelancingaretheskills
youlearntomaster,orbetter,areforcedtomaster.Ateamofonehasits
upsidesanditsdownsides.
FreelancingandSubcontracting
Asanindependentfreelancedeveloper,youspendasignificantchunkof
yourtimedoingtasksthatdon’tinvolveprogramming.Ifprogrammingis
whatyouwanttofocusonandyouhavetheambitiontorunyourown
business,thenyoumaywanttoconsidersubcontracting?
WhatIsSubcontracting
Asubcontractorisanindividualorinmanycasesabusinessthat
signsacontracttoperformpartoralloftheobligationsofanother’s
contract.—Wikipedia
Theabovedefinitionsumsitupnicely.Asasubcontractor,youarehired
byanothercompanytocarryoutworkforoneoftheirclients.Whywould
acompanydothat?Thereareanumberofreasons.Themostcommon
onesareatemporaryshortageofmanpowerandalackofexpertiseina
particularfield.
WhyConsiderSubcontracting
It’struethat,attimes,itfeelsasifyou’reanemployeeofthecompany
youworkfor.Subcontractingisn’tforyouifthat’sacompromiseyou’re
notwillingtotake.Icanseewhyyoudon’twanttogothatrouteasan
independentfreelancer.Asasubcontractor,yourunabusinesswhile,at
thesametime,you’reworkingforanothercompany.Thereareseveral
notablebenefits,though.
ChangeofEnvironments
Oneoftheadvantagesofsubcontractingisthechangeofenvironments.I
don’tmeanachangeofscenery,butachangeofdevelopment
environments.Byworkingatdifferentcompanies,youcomeincontact
withawiderangeofpeopleandcompanycultures.Youlearnthepros
andconsofthetoolstheyuse,theworkflowstheyapply,andthebest
practicestheyliveby.
Evenifyou’vebeenprogrammingforyearsandyears,youlearn
somethingfromeverycompanyyouworkfor.There’salwayssomeone
who’ssmarterthanyouandwhoyoucanlearnfrom.Thisisabenefitof
subcontractingthat’softenoverlooked.Asadeveloper,it’soneofthe
mostimportantbenefitsifyouaskme.
Ifyouenteracontractwiththemindsetofknowingeverythingyouneed
toknow,thenthisfreebenefitisn’tforyou.Thatsaid,ifyouevercomeat
apointwhereyouthinkyouknoweverythingthereistoknowaboutyour
craft,thenitmaybetimetoevaluateyourcurrentsituation.Ihaveyetto
meetsomeonewhoknowseverythingabouttheircraft.Themoreyou
learn,themoreyourealizehowlittleyouknow.
FocusonWhatYouLove
AsImentionedearlier,anindependentfreelancedeveloperneedsto
masterawiderangeofskillstorunasuccessfulbusiness.Findingleads,
talkingtocustomers,andwritingproposalsandspecificationsarebuta
smallsubsetofthethingsyoudoasafreelancedeveloperandbusiness
owner.Somepeoplelovethatmixofresponsibilities.Ifthat’syou,then
subcontractingmaytakesomegettingusedto.
Butifyoustartedfreelancingbecauseyouenjoyprogrammingmorethan
anythingelse,thenyoumaynotlikethoseresponsibilitiesallthatmuch.
Inthatcase,subcontractingcouldbeagreatfitforyou.
Inlargercompanies,developerscanfocusonwhattheydobest,
programming.Aprojectmanagertakescareofclientrelationships,the
salesteammakessurenewprojectsarelinedupforyou,andthe
operationsteamhandlestheinfrastructure.
ChooseYourClients
Thecompanyyouworkforasasubcontractorisyourclient.The
company’sclientsarenotyourclients.Beforeyoudecidetosubcontract
foracompany,takealookatthecompany’sportfolio.It’sfinetobepicky,
especiallyifyouhaveaportfolioyoucanbeproudof.
SubcontractingorEmployment
Thelinebetweensubcontractingandemploymentmayseemthinat
times.Thisisespeciallytrueifyou’vebeenworkingforthesame
companyformonthsoryears.There’snothingwrongwiththat,butit’s
importantthatyoufeelcomfortableinthatsituation.
Ifsubcontractingbeginstofeellikeemploymentwithoutthebenefitsof
beinganemployee,thenitmaybetimetofindanotherprojectata
differentcompanyorchooseadifferentpathaltogether.
Ifthisreallybothersyou,thenbeinganindependentfreelancermaybea
betterfit.Nothingstopsyoufrommixingsubcontractingwithworkingas
anindependentfreelancer.Manyfreelancersdo.Thelinebetween
subcontractingandfreelancingissometimesprettythin.
Bothpathswillteachyoumorethanyoucanimagine.Butmakesureyou
don’tbecomecomplacent.That’smyoneadvice.Ifyouchoosea
particularpathbecauseitmakesyourbankaccounthappy,thenit’stime
toreconsideryourchoicesandpriorities.
BeingPicky
Elsewhereinthisbook,Iexplainwhichstepsyouneedtotakewhenyou
inheritasoftwareproject.Ifyou’reworkingasanemployeeatanagency
andyourcompanyacquiresaclientfromacompetingagency,thisoften
meansthatyoualsoacquireoneormoreexistingprojects.Thisisusually
partofthedeal.Asanemployee,youhaveverylittlesayinthematter.
Inheritingasoftwareprojectisrarelyagift.
Thingsareabitdifferentasafreelancer.Youhavetheluxuryand
freedomtochoosewhoyouworkwith.Forexample,Inolongertakeon
existingprojectsbecauseitusuallymeansseveraldays,weeks,or
monthsfixingbugs,makingminorimprovements,andspendingalotof
timefixingissues.Iunderstandthatnoteveryonehasthisfreedom,but
it’simportanttoknowthatyoucanbepickyifyouchoosetobe.
Beingpickydoesn’tonlyapplytoprojects.Youcanalsobepickywhenit
comestotheclientsyouworkwith.Workingwithindividualswithasmall
budgetisrarelyworthyourtime.Notbecausethesepeoplearen’tfunto
workwith,butbecausetheyhavenoexperienceinthespaceandhavea
limitedbudgettospend.Theirfocusisalmostalwaysonlimitingcosts
andunderstandablyso.Thequalityoftheproductissecondary.This
meansthatthedeveloperneedstoworkfast,cutcorners,andalmost
alwaysdefendtheirdecisions.
TakingaPeek
Ifyoudodecidetoworkonanexistingproject,Istronglyrecommendthat
youtakealookattheprojectfirst.Thisusuallyisn’taproblem.Ifitis,
thenthatmaybearedflagforyou.
Takingalookattheprojectusuallymeanssigninganon-disclosure
agreement.That’sfine,butmakesureyoucarefullyreadtheagreement.
You’reonlyvettingtheclientandtheirproject.Don’ttakeanyrisksand
don’tcommittoanythingyoudon’tfeelcomfortablewith.
IsItWorthIt
Insteadoftakingontheproject,haveaconversationwiththeclienttoget
anideaoftheamountofworktheycanbringinoverthenextmonths.Be
careful,though.Ihavespokenwithmanypotentialclientsthatpromised
moreworkinthefutureandneverdelivered.That’swhyIneverstarta
relationshipwithaclientbasedonaprojectthatonlyinvolvesbugfixing
andminorimprovements.Iunderstandthatsuchanassignmentisideal
fortheclienttotestthewaters.Iseethatabitdifferently.
Ifaclientapproachesmeforacollaboration,Iexpectthemtotrustme.
TheycontactmeformyexpertiseandIhavenointentionofconvincing
themthatI’magoodfitforthejob.IftheyfeelI’mnot,thentheyshouldn’t
havecontactedmeinthefirstplace.Doesthisseemarrogantor
complacenttoyou?Thinkagain.Iconsideritaformoftrustandrespect.
FiringClients
Mostfreelancershavethefeelingthataclientchoosesthemtoworkona
project.Thisisusuallytrueifyoudon’thavemanyprojectslineduporif
you’rejuststartingout.EarlierIwroteaboutbeingpickyandthatalso
appliestoclients.
Asafreelancer,it’simportanttorememberthatyou’reonyourown.No
matterhowgoodyourrelationshipiswithyourclient,theywillletyougoif
theyfeelthat’sthebestdecisionfortheircompany.Thismeansthatyou
shouldalwaysputyourselffirst,notyourclient.Thisappliestoyour
health,yourworkload,andyourmentalsanity.
I’vealwaysbeenconfusedbytheuseof“freelancer”and“consultant”.
Whilethereisadifference,agoodfreelancerisalsoaconsultant.An
experiencedfreelancerisworthitsweightingoldandaclientshouldbe
luckytohaveyou.Withthatattitude,yourrelationshipwiththeclient
changesdramatically.Younolongerfeelthatyoushouldonlydowhat
you’retold.Youshouldalsoadvisetheclient.
Ifyoufeelthatyourinputandyouradviceareignoredbytheclient,then
youmaybestartingtowonderwhyyouchosetobecomeafreelancer.
Whenthere’sanissuewithmycar,Itrustmymechanictodecidewhat
needstobedone.Aprofessionallistenstotheclientandthendecides
whatshouldbedone.Iftheclientdoesn’trespectyouradviceandinsists
thatyoudowhattheythinkisbest,thenyoumaywanttofiretheclient.
Wait.What?Firetheclient?
FiretheClient
Firingaclientisanewconceptformanyfreelancersandsubcontractors.
Itcanbeascarythingtodo,butifyoufeelthatyou’rehavingan
unhealthyrelationshipwithyourclient,thenconsidertakingactionto
changethesituation.Havingaconversationisobviouslyyourfirststep,
but,ifthatdoesn’tbringsignificantchange,thenyoushouldconsider
movingon.
PART7:PRODUCTS
1Ship,Ship,Ship
SteveJobsfamouslysaid“Realartistsship.”Hemeantthatputtingyour
workoutintheworldisanessentialaspectofeverycreative,andthat
includesdevelopers.Creativesthatonlyworkinisolationandnevership
anythingmaynotbethatrealafterall.
Earlierthisyear,IsentasurveytoCocoacastsreaderstolearnmore
aboutwhattheydo,whattheirgoalsare,andwherethey’recurrentlyat.I
alsoaskedthemaboutanyapplicationstheyhaveintheAppStore.
Manyofushavepublishedsomepersonalprojects,butthemost
commonanswertothequestionwasthegoalorambitiontohavean
applicationintheAppStore.It’scommontostartsomethingwithoutever
finishingit.
It’sHard
I’vewrittenaboutthismany,manytimesbecauseit’ssomethingthat
fascinatesme.Developersarecreativepeople,andwehaveanurgeto
create.Unfortunately,mostofusstopwhenweloseinterest.Motivation
isn’twhat’sgoingtogetyoufromideatoAppStore.It’sgrit,tenacity,and
persistence.
Solvingaproblemiswhatweliketodo.Writingreleasenotes,
implementingin-apppurchases,orlocalizinganapplicationisn’twhatwe
enjoymost.Butit’sanessentialaspectofsoftwaredevelopment.
Unfortunately,it’swhatstopsmostofusfromshipping.
HowtoShipConsistently
Overtheyears,I’vebuiltmany,manyapplicationsandsomeofthem
madetheirwaytotheAppStore,notall.Ithastaughtmeseveraluseful
lessonsthatguaranteethatIshipstuffconsistently.
MakeItTiny
It’sfinetodreamandtobeaudacious.ButRomewasn’tbuiltinaday.
Whatstopsmanyofusfromshippingourcreationsisaimingtoohigh.I
don’tmeantosaythatyoushouldn’taimhigh.WhatIamsayingisthat
youshouldaimforconsistency.
Mylatestapplicationisfocusedandtothepoint.Ihavebiggoals,and
evendreams,forthisapplication,butthefirstreleasefocusesonthe
essentials.Iinterviewedpeoplethatareinterestedintheproductand
askedthemwhichfeatureswereessentialforthemtousetheapplication.
Ianalyzedtheresults,wenttowork,andplantoshipthefirstversionof
theapplicationlaterthismonth.
It’sfinethatyourapplicationislimitedinscope.That’smuchbetterthan
noapplicationatall.Right?I’mconvincedthattherearethousandsof
applicationscollectingdustonpeople’scomputersbecausetheyaimed
toohighforthefirstrelease.Keepitsmallandfocused.
ShipFrequently
OnceyouhavesomethingintheAppStore,it’ssurprisinglyeasyto
iterateonwhatyoualreadyhave.Definethescopeforthenextrelease,
keepitfocusedandsmall,andship.Rinseandrepeat.Listentofeedback
andimprovetheapplicationasyougo.
It’sanapproachthathasworkedvery,verywellforme.Italsoshowsmy
customersthatI’mcontinuingtoinvestintheproduct.Itbuildstrustand
confidence.TheAppStoreislitteredwithabandonedapplicationsthatno
longerreceiveupdates.Oneofmyfavoriteutilitiesstoppedworkingafter
IupdatedmyphonetoiOS11.
KeeptheBiggerPictureinMind
Shippingfrequent,focusedupdatesisveryeffective,butmakesureyou
keepthebiggerpictureinmindalongtheway.Avoidendingupwitha
productthatpacksdozensoffeaturesbutlacksacleardirection.You’re
theproductownerandit’syourtask,notyourcustomers’,togive
direction.
InternalDeadlines
Isometimesmakethemistakeofpubliclycommittingtoadeadline.This
strategyworksfordrawingattention,butit’sdetrimentalforyoursanity.
Whatworksmuchbetterissettinginternaldeadlines,whichIdiscussin
thechapteronsourcecontrol.Itworkswellinteams,butit’salsoan
effectivestrategyforpersonalprojects.
Theideaissimple.Schedulereleasesonaregularbasisandshipwhat’s
ready.That’sthegist.IfyouadoptthebranchingstrategyIdescribe
elsewhereinthisbook,thenthat’ssimpletoimplement.Combinethis
withadashofautomation,andyouhaveyourselfashippingmachine.
Suchaworkflowletsyoufocusonwhatyouenjoydoingmost,building
amazingsoftware.
RemoveFrictionandClutter
Therearenumeroustasksyouneedtohandleifyou’rebuildingand
shippingproducts.Itcanbeachoretopreparearelease.Tomakethis
easier,Iautomatemostofthetrivialaspectsofarelease,suchas
translationmanagementandcreatinganduploadingscreenshots.
Manuallycreatinganduploadingscreenshotsisvirtuallyimpossibleifyou
wanttosupporteverydeviceyourapplicationcanrunon.You’rea
developerandyoushouldbeautomatingrepetitivetasks.
Itpaysofftosetasideafewhoursfromtimetotimeandautomateyour
workflows.Iwritemoreaboutthisaspectofsoftwaredevelopmentinthe
chapteronautomation.
2TalktoYourCustomers
Asdevelopers,wehavetheitchortheneedtoanalyzeproblemsand
craftsolutionsforthem.That’swhatdrivesmostdevelopers.Ifyouboilit
downtoitsessentials,thenadevelopersolvesproblems,largeand
small.
Someofushavebiggerambitions,though.Whathasalwaysappealedto
memostisthepossibilityofcreatingaproductandsellingittohundreds
orthousandsofpeople.Applegetsalotofflakfortakingasignificantcut
fromyourearnings,but,creditwherecreditisdue,Applehasmade
creatinganddistributingsoftwareeasierthanever.It’snocoincidence
thattheAppStorecatalogpacksmillionsofapplications.Whetherthat’s
agoodthingisadifferentdiscussion.
SolveaProblem
TherearemanyreasonsforpublishinganapplicationonApple’sApp
Store.Somedeveloperswanttotestthewaters,createaportfolioto
showfutureemployers,andsomeofuswanttohelpothersforfree.
Someofushavetheambitiontoturnourpassionintoabusiness.Tobe
honest,I’malwayssuspiciouswhenIsee“passion”and“business”inthe
samesentence.Ibelievethatyoucanbepassionateaboutthethingthat
makesyoumoney,butpassionandbusinesscanbeadangerousor
misleadingcombination.
Everybusinessstartswithanidea.Butasuccessfulbusinessstartswith
aproblem.IgnoreFacebookandTwitterfornow.Ihopeyoudon’thave
theambitiontocreatethenextFacebookorTwitter.
AsImentionedearlier,adeveloperiswiredtosolveproblems.Someof
usalsohaveagifttospotproblems,whichcanbebothacurseanda
blessing.Butthefirstmistakedevelopersmakeistryingtocomeupwith
anidea.AndmanypeopleI’vetalkedtogetfrustratedinthisphase.
Thesolutionissurprisinglysimple.Turnitaround.Insteadoflookingfor
anidea,lookforproblemsandtrytocomeupwithasolution.That’sthe
seedforasuccessfulbusiness.Whyisthat?
Asdevelopers,we’refocusedonthetechnicalaspectsoftheproduct.
We’resoimmersedintheprocessofsolvingtheproblemthatweforget
toaskthemostimportantquestion.Doesanyonewantwhatwe’re
building?Andthisleadstoawaterfallofotherequallyimportant
questions.Whoisthepersonwe’rehelping?Whatisthepaintheyhave?
Andhowarewetryingtomakethatpaingoaway?
GroundZero
Yourfirsttaskistovalidateyouridea.Itdetermineswhetheryouwill
spendthenextdays,weeks,ormonthscreatingabusinessorafantasy.
EverydeveloperI’vetalkedtoaboutcreatingaproductbusinesshas
madethismistake.Every.Single.One.I’vemadethismistakeseveral
times,evenafterIknewIhadtovalidatetheideafirst.It’sjustincredibly
temptingtofireupacodeeditorandstartcoding.
IsThisforYou
Ifyourpassioniswritingcode,thenbuildingaproductbusinessmaynot
beforyou.Youhavetobehonestwithyourselfaboutthis.Buildinga
businessalsoincludesmarketing,customersupport,writingrelease
notes,andmuchmore.Youdon’tneedtobepassionateaboutthese
responsibilities,butyouneedtotakecareofthem.Idon’tlikemarketing,
butIknowit’sessentialformybusiness.
Thesameappliestofreelancingandworkingasanemployee.
Freelancinglooksamazingonpaper,butafreelancerneedstofind
clients,writeproposals,andalotofadministration.That’swhymost
developersworkasemployeesatacompanywheretheycanfocuson
whattheyenjoydoingmost.Andthat’sfine.
ButIt’sFantastic
Eventhoughrunningaproductbusinessishardwork,andalotofit,the
feelingofcreatingsomethingpeoplearewillingtopayforisamazing.
Youhavethefeelingthatyou’remakingadentintheuniverse,atinyone,
butit’sstilladent.You’redoingsomethingthatmattersandthathelps
peopleintheirlives.
Andthattoocanturnintoapassion.Beingpassionateaboutyour
businesssoundsmuchhealthierthantryingtoturnyourpassionintoa
business.
ARecipeforSuccess
Whilebuildingasuccessfulbusinessishardwork,thereisaneasy
blueprintyoucanuse.Itdoesn’trequireventurecapital,andyoudon’t
needtohavethousandsoffollowersonTwitter.Therecipeissimple.
Step1:Findaburningproblempeoplehave.
Step2:Solvethatproblem.
Step3:Askformoney.
Thisroadmapisn’trocketscience.Unfortunately,thepathmost
developersthatturnentrepreneurtakeisthefollowing.
Step1:Comeupwithanidea,notaproblem.
Step2:Buildaproduct,notasolution.
Step3:Releaseit.
Step4:Franticallylookforpotentialcustomers.
Step5:…
Likemostfreelancers,peopleoccasionallycontactmetotalkaboutan
ideatheyhaveforanapplication.They’repreparedtospendthousands
ofdollarsoftheirsavingsintoaproductthathasn’tevenbeenvalidated
yet.Theyhaven’ttalkedtoasinglepotentialcustomer.Thisisarecipefor
disaster.
Asarule,Idon’ttakeonprojectsIdon’tbelievein.Itisn’tfuntosee
someonepourtheirsavingsintoaprojectthatisn’tgoinganywhere.Don’t
makethismistakeyourself.Talktoyourcustomers.
3WhatIsStoppingYouFromShipping
Earlierinthebook,Iwroteaboutbuildingandshippingsomething,putting
somethingintopeople’shands.Iunderstandthatlifegetsinthewayfrom
timetotime,butI’mgenuinelywonderingifyou’recreatingsomething.
I’mnotreferringtotheworkyoudoforyouremployeroryourclients.
WhatI’mspeakingaboutisthecreativeprocessoffindinganitch,
comingupwithasolution,andcreatingaproductthatscratchesthatitch.
Yourproductdoesn’tneedtochangetheworld.Youcanstartsmall.But
youhavetostart.Whatareyouworkingon?Whatitchareyou
scratching?
WhyIsThisImportant
BuildingandshippingaproductissomethingIwriteandtalkabout
frequentlybecauseIbelieveit’simportantforeveryCocoaorSwift
developertobefamiliarwiththelifecycleofaproduct,fromstartto
finish.It’struethatyou’readeveloper,butthatdoesn’tmeanyoushould
ignoreotheraspectsofproductdevelopment.
Inmediumtolargecompanies,peopleoftenhavetheluxurytofocuson
whattheydobestandenjoydoingmost.ButIdon’tseethisasaluxury.I
firmlybelievethatakeystrengthofmostfreelancersandindependent
developersistheirdeepunderstandingofwhatitmeanstoshipa
product,fromideatoAppStore.
Ifirmlybelievethatakeystrengthofmostfreelancersand
independentdevelopersistheirdeepunderstandingofwhatit
meanstoshipaproduct,fromideatoAppStore.
Itcanbetoughandfrustratingtohavetomanageeveryaspectofthe
product’slifecycle,butit’salsointeresting.Itteachesyoualotabout
yourcraft,andyoudevelopskillsthatmakeyouanattractivehire.Ifyou
don’thavetheopportunitytobemoreinvolvedinproductdevelopmentat
thecompanyyouwork,thenyoucan,andshould,createaproductof
yourown.
StartSmall
Havingbigdreamsisgreat.It’sadmirable.Weneedpeoplewithvision
andambition.Buteverythingstartssmall.Thinkingbigisn’taproblemas
longasitdoesn’tdistractyoufromtheworkthatneedstobedonetoday.
Biggoalsalwaysstartsmall.
Biggoalsalwaysstartsmall.
Startsmallbyfocusingonthatonefeaturethatsetsyourapplication
apartfromeveryotherapplication.Howcanyoumakeitstandout?What
canyoudotobringvaluetotheuserofyourapplicationwiththatone
feature?Nottwo.Notthree.Onlythatonefeature.
Byintenselyfocusingononepieceoffunctionality,youforceyourselfto
makethatonefeaturegreat,tomakeitmagical.It’sfinetoaddbellsand
whistles,buttheyshouldn’tdistracttheuserfromcenterstage.
Apple’soriginaliPodputthecompanybackonthemap.Itwasa
revolutionaryproduct.It’struethatitlookedamazingandthatitwaseasy
touse.But,atitscore,itdidonethingvery,verywell.Playingmusic.The
productwasfocused.Appleremovedeverybitofclutterthatcould
potentiallydistracttheuser.FocusiswhatmadetheiPodstandoutfrom
therestofthemarket.
RemoveClutter
Manyprojectshavealistoffeaturesthatgoesonandon.Andthat’sfine.
Butisthefeaturelistofyourprojectstoppingyoufromshipping?Areyou
delayingthelaunchofyourprojectbecauseofoneortwofeaturesthat
yourapplicationcanprobablydowithout?
Ifyourprojectneedsadozenormorefeaturestoaddvalue,itmaybe
timetogobacktothedrawingboard.Ifyouneedthebellsandwhistles
tocoverupthatcenterstageisn’tthatgreat,youhavemissedthepoint.
Toomanyfeaturesisalltoooftenthecauseofmisseddeadlinesanda
productthatisn’tbeingshipped.I’mcurrentlywrappingupabrandnew
application.Someofthepeopletestingtheapplicationareaskingforan
AppleWatchapplication.IplantosupportAppleWatch,butthefirst
versionwon’tincludethisfeature.Iknowitwilltakemeseveralweeksor
monthstoaddthisfeatureandthat’snotwhatIhaveinmind.Iwantto
havethisapplicationintheAppStorebeforetheendofthismonth.
BypostponingsupportforAppleWatchImakesureIcanshipthe
applicationsooner,butitalsoallowsmetofocus.Focusisawordyou
findveryofteninthisbook.Ithasbecomeanessentialingredientto
successintoday’sdayandage.Iknowithasforme.
Whatisstoppingyoufromshipping?
4MotivationWillGetYouOnlyHalfway
Ibetthatyoustartedmoreprojectsthanyoucanremember.Howmany
ofthoseprojectshaveyoufinished?Howmanyapplicationsdidendupin
thehandsofcustomers?
You’veprobablyheardthephrase“Followyourpassion.”or“Dowhatyou
enjoydoing.”Iagreethatyoushoulddowhatyouenjoydoing,butyou
alsoneedtoknowthatpassionoftenisn’tenoughtogofromideato
product,aproductpeoplecanuseandfindvaluein.
MotivationWon’tCutIt
Asdevelopers,wetendtolaunchacodeeditorwheneverwehavea
brilliantidea,codingawaytosolvetheproblemathand.Thisimpulse
usuallylastsforafewdaysorweeks.Ifyou’relucky,youcanmotivate
yourselfuntilyouhaveaworkingprototypeyoucansharewithfriendsor
family.
Aprototypeisn’tenough,though.Buildingaproductpeoplecanuse
requiresmuchmorethanarudimentaryversionthatsolvesaproblem.
RunningaMarathon
Perseverance,tenacity,andgritarequalitiesthatareoftenundervalued
oroverlooked.Yourbossorclientsdon’tpayyoubecauseyou’re
passionateormotivated.Theypayyoubecauseyouconvincedthemthat
youcangetthejobdone.
Buildingaproduct,shippingittocustomers,addingfeatures,andfixing
bugsareessentialcomponentsofcreatingasuccessfulproduct.Few
developersgetexcitedbybugorcrashreports.Thetruthisthatyour
codecontainsbugsandyourapplicationcrashesifithasanycomplexity
toit.Eventhoughfixingbugsandinvestigatingcrashreportsareless
enjoyabletasks,they’reintegralaspectsofsoftwaredevelopment.
Creatingaproductisn’tasprint.It’samarathonwithmanyupsand
downs.
Ifyou’rewaitingformotivationtokickinbeforeyoustartworkingonthose
bugreports,you’reprobablywaitinginvain.Itrequiresperseveranceto
takeaprojectfromideatoshippableproduct.Ittakestenacitytoiterate
onaproduct,tofixbugs,andaddfeatures.
Creatingaproductisn’tasprint.It’samarathonwithmanyupsand
downs.It’sfinetostartwithasprint,butyouneedtorememberthat
you’reinitforthelongrun.
PullingthePlug
Noteveryproductisgoingtobeasuccess.TheAppStoreislitteredwith
failedandabandonedprojects.Nottoolongago,AppleandGoogleused
thenumberofapplicationsintheirmobilestorestomarkettheir
platforms.Sadly,thisisnolongersomethingtobragabout.Appleis
activelyremovingapplicationsthatnolongercomplywiththeAppStore
guidelines.Applehasrealizedit’stimetofocusonqualityinsteadof
quantity.
EventhoughApple’sAppStorecontainsmillionsofapplications,finding
whatyou’relookingforisdifficult.Findinganapplicationthat’sfrequently
updatedandfitsyourneedsisevenmorechallenging.
It’sfinetopulltheplugonaproductifyoubelieveit’snolongerworth
pursuingaslongasitisn’tanexcusetoworkonthenextbrilliantidea
thatentersyourmind.Thisiscommonlyreferredtoastheshinyobject
syndrome.
StartandPersevere
I’vewrittenaboutbuildingandshippingproductsquiteafewtimesinthis
bookbecauseit’ssomethingIfrequentlystrugglewith.Addingfeaturesis
nice,butupdatingtranslations,makingscreenshots,trackingbugs,and
respondingtocustomerfeedbackismuchlessglamourous.
Buildingandmaintainingaproductismorethanworthit,though.
Samsara,forexample,hasbeenaroundforseveralyearsandpeoplestill
emailtotellmehowmuchtheyenjoyusingitfortheiryogaand
meditationpractice.Theseemailsgetmeexcitedtocontinueimproving
Samsarawitheveryrelease.Itgetsyouthroughthetoughtimeswhen
motivationislow.
ChallengeYourself
Mostdevelopersthrivewhenthey’refacedwithaproblemtheyneedto
solve.Continuetochallengeyourself.Pickupanewlanguageorexplore
anewlibrarytokeepyousharp.Solvingproblemsisexactlywhat
softwaredevelopmentisabout.Isitnot?
5HowtoMakeaLivingasaMobileDeveloper
DevelopersoftenrefertotheearlydaysofApple’sAppStoreasthegold
rushoftheAppStore.Paidapplicationswerethenormandpriceswere
muchhigherthantheyarenow.Whatoptionsdoyouhaveasa
developerorentrepreneurintoday’sAppStore?Isitpossibletomakea
livingasanindependentdeveloper?Inthischapter,Ilisttheoptionsyou
havetomakemoneyfromyourapplicationsinApple’sAppStore.
PaidUpFront
ThemostcommonapproachtomakemoneyonApple’sAppStoreused
tobeaskingusersformoney.Really.Itsoundstoocrazytobetrue.
Askingformoneyinexchangeforaproductiscrazy.Jokingaside,froma
businessperspective,thismakesperfectsense,anditcomeswith
virtuallynooverheadfromthedeveloper’sperspective.
TomakemoneyinApple’sAppStore,paidapplicationswerethenormfor
thefirstfewyears.Thisperiodendedwithwhat’snowknownastherace
tothebottom,developerscompetingwitheachotherbycuttingthe
pricesoftheirapplications.Theracetothebottomforceddevelopersand
businessestofindotherwaystomakemoney.
WhileI’veplayedwithSamsara’spricing,ithasalwaysbeenpaid,andit
hasdoneprettywellcomparedtothemajorityofapplicationsoutthere.
Whilepaidapplicationsstillhaveafuture,it’salesspopularoptionthese
days.
Freemium
Thefreemiummodelpredatesthemobileera.Desktopandweb
applicationsusedthefreemiummodellongbeforetheiPhonewas
introduced.Theideaissimple.Youofferaproductforfree,gettingitin
thehandsofasmanypeopleaspossible.Togeneraterevenue,youdo
yourbesttoconvinceasubsetofyouruserstopayforapremium
experience.
Offeringtheproductforfreehastwoimportantbenefits.Yourproduct
spreadsfasterandmoreeasily,andyouhaveafootholdinthe
customer’slife.
Howyoudefineapremiumexperiencedependsontheproduct.
Evernoteisafineexampleofacompanythathassuccessfullyapplied
thefreemiummodel.Thecompanyhastensofmillionsofcustomers.A
fractionofthosecustomerspaysforEvernote’spremiumservices.The
companywouldhavehadahardertimegainingmarketshareifithad
offereditssuiteofproductspaidupfrontorwithamonthlysubscription.
Freemiumisn’twithoutrisk,though.Foryears,RobWallinghasbeen
warningdevelopersandentrepreneursthatfreemiumisdifficulttopulloff,
especiallyforsmall,bootstrappedcompanies.
Ifyourproducthasabackend,forexample,thenkeepinmindthat
customersthatdon’tpayforyourproductalsomakeuseofthatbackend.
Hostingcostscanskyrocketifyourproductgainstraction.Inthatcase,
theconversionrateoffreetopaidcustomerswilldeterminewhetheryour
businessisviableinthelongrun.
Advertising
Anotherwidespreadbusinessstrategyisadvertising.Youofferyour
applicationforfreeanddisplayadstoyourcustomers.Thisbusiness
modelonlyworksifyourapplicationhaslotsandlotsofusersandifyour
usersfrequentlyuseyourapplication.
Gamesareagoodfitforads.FlappyBirdshowedthatdeveloperscan
potentiallymakemillionsofdollarsthroughadvertisingaslongasthe
applicationhasenoughusersthatfrequentlyplaythegame.FlappyBird
wasincrediblyaddictive,andthatwasthekeytoitsshortsuccess.
DavidSmithisasuccessful,independentdeveloperandhepublisheda
veryinterestingarticleabouthowhisbusinesshasevolvedoverthe
years.IntheearlydaysoftheAppStore,themajorityofDavid’srevenue
camefrompaidapplications.Nowadays,advertisingbringsinmostofthe
revenue.
Themarkethasbeenpullingmealongtowardsadvertisingbased
apps,andI’vefoundthatthelessIfightbackwithanachronistic
ideasabouthowsoftware“should”besold,themoresustainablea
businessIhave.—DavidSmith
ForOvercast,MarcoArmenthasexperimentedwithseveralbusiness
models,includingadvertising.Atthetimeofwriting,Overcastdisplays
ads,whichyoucanremovebysubscribingtoOvercastPremium.The
adsshowninOvercastaremanagedbyMarcohimselfandareprimarily
targetedatpodcasts.HerecentlymentionedonATPthatthisisworking
verywellforhim.It’sinterestingtoseethischangeanditshowsthatyou
canmakechangestothebusinessmodelofyourproductsasthespace
you’reinevolves.
In-AppPurchases
Sellingvirtualitemsisaverycommonmonetizationstrategyinmobile
games.MostofthegamesthattopthechartsoftheAppStoremake
moneythroughin-apppurchases.It’sabitironictoseeafreegameat
thetopoftheTopGrossingchart,butthat’sthereality.
Youcanusein-apppurchasesformanypurposes.Someapplicationsare
freetodownloadandofferpremiumfeaturesthroughin-apppurchases.
Thisapproachisverysimilartothefreemiummodelwediscussedearlier.
Otherapplicationsdisplayadvertising,offeringtheoptiontoremoveads
throughanin-apppurchase.
Whetherin-apppurchasesworkforyourproductdependsonyourvalue
propositionanditrequiresabitofexperimentation.Ifyouonlyshowa
tinyadinthesettingsviewofyourapplicationandyouofferanin-app
purchasetoremoveit,thenthechancesarethatpeoplearefineseeing
theadeverynowandthen.Don’tdiscardin-apppurchasesifyoufeelit
isn’tworking.Itmaytakeafewtriestogetitright.
Subscriptions
Fewmobileapplicationsmakemoneythroughsubscriptions.Ifyour
applicationoffersaservicethatcontinuestobeofvaluetothecustomer,
thenofferingasubscriptionmakessense.
Subscriptionsaretheholygrailinmyopinion.Theyaregreatforbuilding
asustainablebusiness.Insteadofstartingfromzeroatthestartofevery
month,youbuildupMRRormonthlyrecurringrevenue.Witha
predictable,recurringrevenuestream,buildingabusinessbecomesabit
lessrisky.
Ifthat’strue,whyaren’tsubscriptionsmorecommonintheAppStore?
Netflixofferssubscriptionsbecauseitscustomerswatchmoviesand
showsonadailyorweeklybasis.Thecompanyaddsnewmoviesand
showsalmostdaily.
Mostmobileapplicationscan’tofferasimilarvalueproposition.Acamera
application,forexample,isn’tagoodfitforasubscriptionmodel.
Customersexpecttobuyacameraapplicationonceanduseitasoften
astheywant.
Thelandscapeischanging,though.Lastyear,Appleannouncedthat
auto-renewablesubscriptionsarenowavailableformostapplicationsin
theAppStore.Also,afterthefirstyear,thedeveloper’scutincreases
fromtheusual70%to85%.ItseemsAppleisencouragingdevelopersto
experimentwithnewbusinessmodels,includingsubscriptions.Itshows
thatAppleunderstandsthatthemarketischangingandevolving.
Donations
Asmallgroupofapplicationsgeneratesrevenuethroughdonations.With
thereleaseofOvercast2,MarcoArmentmadeitspopularpodcastclient
free.HeintroducedapatronagemodelinOvercast2togeneraterevenue
fromhisproduct.Tothesurpriseofmanyskeptics,patronageseemedto
workforOvercast.ButMarcowasn’tentirelyhappywiththelow
conversionrateandhestartedexperimentingwithadvertisingandauto-
renewablesubscriptions.
Marco’sreasoningmakesperfectsense.Hewantstoofferthebestuser
experiencetoeveryonethatchoosesforOvercast.Hedoesn’twantto
offeraninferioruserexperiencetopeoplethatdon’tpayforthepremium
featuresor,moreimportantly,tothosethathaven’tdecidedyetwhether
Overcastisrightforthem.Itmakessense,butIwonderhowviable
patronageordonationsarefornicheapplicationsorapplicationswitha
smalleraudience.
I’veconsideredthisapproachinthepastforSamsara.Apatronage
modelwouldbeagoodfit,offeringthebestpossibleuserexperienceto
everyuser.Fromadeveloper’sperspective,it’sacompellingidea.
FindingtheRightBusinessModel
Everyapplicationisdifferent.Noteverybusinessmodelisagoodfitfor
anapplication.Ifyou’recreatingacameraapplication,thenofferinga
subscriptionisprobablynotgoingtowork.Usingin-apppurchasesto
unlockpremiumfiltersisamoreviablebusinessstrategy.
It’sworthspendingtimeconsideringyouroptionsandexperimentingwith
differentbusinessmodels.It’sfineandpossibletomakeyourapplication
paidupfrontandswitchtofreemiumdowntheroad.
Itfelthopeless,butmyinitialthinkingwasrestrictedbytryingto
wedgetraditionalsoftwarebusinessmodelsintotherealitiesof
today’sAppStore.It’shardtomakeolderrevenuemodelswork
todaybecausethemarketiscompletelydifferent.—MarcoArment
Experimentingisfine,butmakesureyoudon’tburnthegoodwillof
existingcustomers.Ifyouswitchfrompaidtofreemiumandforceyour
loyalcustomerstounlockpremiumfeaturestheyalreadypaidfor,then
prepareyourselfforafloodofangrycomplaints.
ExperimentButBeSmart
Alwayskeepyourcustomersinmind.Don’tswitchbusinessmodelswith
everymajorrelease.Doesthatmeanyoucan’tmakechangestothe
businessmodelofyourproduct?Absolutelynot.Letmegiveyouan
example.
Let’sassumeyoureleasethefirstversionofyourapplicationasapaid
application.Afterafewmonths,yourealizeitisn’tdoingaswellasit
could.Youwanttomaketheapplicationfreewithanin-apppurchaseto
unlockpremiumcontent.
Youcouldsimplyimplementthein-apppurchase,butthiswouldanger
customersthatpurchasedyourapplicationwhenitwaspaidupfront.The
solutionissimple,butitrequiressomework.TheAppStorereceipt
includestheoriginalpurchasedate.Yourapplicationcaninspectthe
receiptandonlyofferthein-apppurchasetocustomersthatdownloaded
theapplicationafteryoumadetheswitchfrompaidtofreewithanin-app
purchase.
Evolution
Themobilespacecontinuestoevolveandthatalsomeansthatyouand
yourbusinessneedtoevolve.Thisdoesn’tneedtobescary,butyou
needtobevigilant.Keepaneyeontheindustry.Whichtrendsare
emerging?What’sworkingforotherdevelopers?Talktoyourcustomers?
Whataretheirexpectations?Youmaybesurprisedbytheirresponses.
PART8:YOU
1BeingandStayingProductive
ProductivityisatopicthatmanypeoplehavewrittenaboutandI’m
certainlynotaguruwhenitcomestoproductivity.Throughtrialanderror,
I’velearnedwhatworksandwhatdoesn’t.
Productivityisaverypersonalsubject.Whatworksformemaynotwork
foryou.Forthatreason,Iwon’tbebombardingyouwithtipsandtricksin
thischapter.Instead,Icoverafewkeyelementsthatdirectlyand
indirectlyimpactyourproductivity.
MaintainingFocus
Oneofthebiggestchallengeswe’refacedwithasdevelopersis
maintainingfocusthroughouttheday.Thepeopleweworkwithoften
expectustobeavailableatalltimes.Ifyoucannotcopewiththatfeeling,
itcanaddasubstantialamountstresstoyourlife.
That’swhyit’svitaltosetboundaries.Thisisevenmoretruefor
freelancersandconsultants.Ifyourunabusiness,peopleseemto
expectyou’reworkingeverywakingmoment.Youarethebusinessand
youshouldalwaysbeavailable.
Don’tmakethatmistake.Setboundariesforyourselfandforthepeople
youworkwith.Believeme.Peoplewillrespectyouforit.Andthosethat
don’tmaynotbethepeopleyoushouldbeworkingwith.
ProtectYourProductivity
Openofficesareverypopularinthetechnologyindustry.WhileI
understandtheirappeal,I’mnotafan.It’struethattheypromote
communicationandcollaboration,butthey’realmostalwaysdestroyersof
productivity.Becauseyourdeskisn’tsurroundedbyfourwalls,people
tendtothinkthattheycanstepintoyourimaginaryofficewheneverthey
feellike.
Asadeveloper,youneedfocusandyouneedtoknowthatpeoplewon’t
disturbyouwhenyou’rewritingcode.Mostofusknowthis,whichiswhy
openofficesareusuallyfilledwithpeoplewearingheadphones.The
headphonesareasilentprotestagainstthelackofanofficeoraspace
thatallowspeopletofocusonwhatthey’resupposedtodo.
Makeitcleartothepeopleyouworkwiththattheycan’torshouldn’t
disturbyouwhenevertheylike.Isn’tthatwhatthedailyscrummeetings
arefor?
DistractionIsAddictive
Asifopenofficesaren’tenough,instantmessaging,likeSlack,areused
inalmosteverytechnologycompany.They’reincrediblyusefuland,atthe
sametime,amajordistractionformostdevelopers.Thesameistruefor
instantmessagingofallformsandshapes.
Beingdistractedhasbecomeanaddictionforsomeofus.Wegetakick
everytimeweseeanemailcomein,amessageonSlack,oranewtweet
onTwitter.
Formanyofus,it’saproblem,arealone.We’rebeingdistractedand
we’recravingfordistraction.Idon’thavetheperfectcuretobattle
distraction,butIhaveapieceofpapertapedtothewalloppositemy
deskwiththreelinesoftext.
HaveFocus,RemoveNoise,SetBoundaries
HaveFocus
Thisisaveryeffectivestrategyifyousticktoit.Thefirstlineissimple.
Makesurethatyouknowwhatyou’redoing.Yourfocusshouldbe
singular.Thismaysoundobvious,butmanyofusstarttoprocrastinate
andlookforadistractionwhenwedon’thaveaclearfocus.EverytimeI
don’thaveaclearfocusIaskmyselfasimplequestion.
What’sthenextactionIneedtotaketomoveforward?
IbelieveIreadthisinabookbyDavidAllenyearsago.It’sapowerful
techniquetogetunstuckandmoveon.Itworksvery,verywellifyou’re
battlingacomplexprogrammingproblem,because,let’sbehonest,even
complexproblemsandsolutionscanbebrokendownintosimple,
manageablepieces.
Ifyou’rehavingaroughday,Irecommendtakingtinysteps.Launch
Xcode.Opentheprojectyou’reworkingon.
RemoveNoise
Focusisonlypossibleifyouremoveanythingthatcandistractyou.Seta
timerfor30to60minutesandremoveeverypossiblesourceof
distraction.I’mwritingthisonalaptopwithoutaninternetconnectionina
dimmedroomonanimprovisedstandingdesk.Ihavenotifications
disabled,closedbrowserwindows,andIcanonlybedisturbedby
emergencies.
Isthisoverkill?Idon’tthinkso.Howdoyouthinkprogrammersgotwork
donetwentyorthirtyyearsago?Theyweren’tdistractedbySlack,mobile
phones,andaconstantinfluxofnews,tweets,andmessages.We
haven’tevolvedsincethosedays,whichmeanswearenotimmuneto
thedistractionsoftoday’sworld.
Ihaveoneprotipforyou.Ifyou’reworkingonaniOSapplication,make
sureyouuseatestdevice,notyourpersonaldevice.Itmakesiteasierto
blockoutmessages,phonecalls,andotherdistractionsthatyourphone
receives.
SetBoundaries
Thisisabigone.Afewmonthsago,Ireadanarticleonproductivityby
RamitSethi.Inthecommentsofthearticle,areaderaskedRamitabout
beingoverwhelmedbyworkandthefeelingthateverythingwasgetting
toomuch.Ramitrespondedtothisperson’scommentandpointedout
thatoverwhelmisalmostalwayscausedbyalackofboundaries.
Iwroteaboutsettingboundariesearlierinthischapter.Notsetting
boundariescanmentallyandphysicallyexhaustyou.Howdoyouset
boundaries?Turnoffyourcomputerat6PMandmakeitahabitthatyou
don’tcheckemailormessagesfromworkafterthattime.That’sagood
start.
Thiscanbechallengingifyou’renotusedtodothis,butafterafewdays
youshouldfeelmorerelaxedandmoreenergizedthenextday.Aspring
that’sconstantlystressedlosesitsflexibilityandthesamehappensto
people.Theresultcanbeburnoutordepression,bothofwhichare
difficulttorecoverfrom.Thisbringsmetothelastsectionofthischapter.
TakeCareofYourself
Arunnerrunningamarathondoesn’trunalloutfortheentirerace.She
keepssomethinginthetankforthefinaleoftherace.Workingasa
developerissimilar.Makesureyoudon’tpushyourselftoyourlimitsday
indayout.Makesureyouhaveahealthyreserveforwhenitgetstough
orwhenthingshitthefan.
You’reinitforthelongrunandthatmeansthatyouneedtotakecareof
yourself,includingyourbody.I’minmythirtiesandburningthemidnight
oilissomethingIcannolongerpulloffwithoutsufferingthe
consequences.Iseeyoungpeopledrinkingenergydrinksand
bucketloadsofcoffee.Thisisn’thealthyandyouwillpaythepriceat
somepoint.Youprobablywon’tbelievemeifyou’reinyourtwenties.
2StopLookingfortheSilverBullet
Mostframeworksandlibrarieshaveguidelinesandbestpractices.
Apple’sSDKsarenodifferent.Whilethere’sroomforexperimentation
andexploration,atypicaliOSapplication,forexample,usesoneormore
viewcontrollersandtheusercannavigatebetweenthoseview
controllers.That’sarecipeyou’reprobablyfamiliarwith.
Noteveryproblemyoufaceduringdevelopmenthasonesolution,
though.ThisisacommonissuedevelopersfacewhentheyuseCore
Data,forexample.Theyrunintoanissueandtheytrytoresolveitby
lookingfortherecipethatfixestheirproblem.
AnExample
Afewyearsago,FlorianKuglerwroteanexcellentarticleinwhichhe
comparesthreeCoreDatastackconfigurations.Inhisarticle,Florian
testshoweachCoreDatastackperformswhentheapplicationimportsa
largedatasetinthebackground.Theresultsweresurprising,tosaythe
least.
TheCoreDatastackAppleandseveralknownexpertsrecommend
performedterribly.IwassurprisedbytheresultsandsowasFlorian.He
investigatesthetestresultsandunravelswhyaCoreDatastackwitha
parent-childconfigurationdoesn’thandlelargebackgroundimportsvery
well.It’saverygoodreadifyou’reinterestedinCoreDataperformance.
Toresolvetheissue,Floriandidn’tgolookingforthesilverbulletinthe
CoreDataprogrammingguidebecausethereisnosilverbullet.There
arebestpracticesandguidelines,butnoteveryproblemcanbesolved
withaclear-cutrecipe.
InvestigateandTest
Afewmonthsago,IcameacrossanarticlebySamSoffesabout
improvingapplicationperformancewiththehelpofInstruments,oneof
themostunderuseddevelopertoolsforCocoadevelopment.Inhis
article,Samdescribeshowhespentanafternooninvestigatingthree
performanceissuesinanapplicationhewasworkingon.
Aswithmanyperformanceissues,thebottleneckswereunexpected.
Oneissue,forexample,wascausedbyadateparserthatparsedISO
8601dates.Heonlydiscoveredthisissuebyprofilingtheapplication’s
performance.
Samtested,investigated,andimprovedtheapplication’scodebase.He
didn’tfollowarecipeandhecertainlydidn’tsearchforasilverbulletto
solvehisperformanceproblems.
StopLookingfortheSilverBullet
Ifyou’renewtoaframeworkorlibrary,itcanbefrustratingorevenscary
toknowthatyou’reonyourowntofixperformanceissuesorotherissues
thatarespecifictoyourapplication.Butthat’stherealityofsoftware
development.
It’struethatyoumaybeusingtheframeworkorlibraryincorrectly.That’s
actuallyacommoncauseofbugsandperformanceproblems.The
momentyourprojectgainsincomplexity,you’reoftenonyourown.You
canlearnfromotherdevelopersthathavefacedsimilarissues,butit’s
importanttostoplookingforthesilverbulletthatyoumaythinkyoucan
findsomewhere.
Instead,profileyourapplication,investigatetheresults,andtryto
improveperformanceproblemsorfixthathardtofindmemoryleak.
That’showyougrowasadeveloper.Beingafraidofexploringuncharted
watersisunderstandable,butthatdoesn’tmeanyoushouldn’tgiveita
try.
3YouAreNotanImposter
Haveyoueverheardofimpostersyndrome?LikePaulineRoseClance,I
preferimposterexperienceasitbetterdescribestheproblem.
Asurprisingnumberofpeoplesufferfromimposterexperience.And
developersarenoexception.Whatisimposterexperience?Andwhyam
Iwritingaboutitinthisbook?
WhatIsIt
Peoplesufferingfromimposterexperiencearegenerallyverygoodat
whattheydo.They’reoftenperfectionists,givingtheirverybest.Yetthey
feelinsecureand,attimes,theythinkofthemselvesasfraudsor
imposters.Theyfeelasifthey’retrickingtheworldintobelievingthat
they’rebetterthantheyactuallyare.Doesthatsoundfamiliar?
Ifyouwanttolearnmoreaboutimposterexperience,Irecommend
readingtheWikipediaentryonthetopic.Itdoesagreatjobatexplaining
thedetails.
WhyDoIBringThisUp
RegularreadersofCocoacastsknowthatIoccasionallywriteaboutthe
psychologicalaspectsofbeingadeveloper,workingasafreelancer,or
runningabusiness.ThesearetopicsIhaveaspecialinterestinsince
they’reanintegralpartofbeingadeveloper.
Topicslikeimpostersyndromeorexperienceareoftenignored,discarded
withalaugh,ortrivialized.Butifyou’readeveloperandyouwanttolivea
happylife,enjoyingtheworkyoudoisn’tenough.It’sequallyimportantto
feelcomfortablearoundthepeopleyouworkwithandtheenvironment
youspendagoodchunkofyourtimein.
CuringImposterExperience
It’simportanttoemphasizethatI’mnotapsychologistandhaveno
medicaltrainingwhatsoever.TheadviceIofferisbasedonmyown
experienceandconversationswithdeveloperslikeyourself.
Honesty
Imposterexperienceisprettycommonamongfreelancedevelopers,
especiallyifyou’reworkinginateamofone.Whywouldanyonepayyou
moneyforthecodeyouwrite?Andwhatifpeoplefindoutthatyou’renot
asgoodastheythoughtyouwere?
Oneofthebestcuresforimposterexperienceishonestyandopenness.
WhenSwiftwasintroducedin2014,apartfromahandfulofdevelopersat
Apple,nobodyknewwhatSwiftwas.Bestpracticeswerestillwaitingto
bediscoveredandeveryoneplayedwithandexploredthelanguage.
NatashaMurashevhasbeenatrueinspirationformanydevelopers.
Fromthestart,Natashahasopenlydocumentedherexplorationofthe
language,sharingherdiscoveriesalongtheway.Eventhoughshe’sa
fantasticdeveloper,shedoesn’tproclaimtobeanexpert.Especiallyin
theearlydaysofSwift,herblogreadlikeadiaryofhowsheexploredthe
language.ShestudiedSwifthonestlyandopenly,theperfectremedyto
cureandevenpreventimposterexperience.ItmakesNatasha’sblogfun
toreadanditimmediatelycreatesahumanconnection.
Don’tMakePromisesYouCan’tKeep
Yearsandyearsago,ItaughtstudentsatauniversityinBelgium.Oneof
thekeylessonsIlearnedfromoneofmymentorswastobeupfrontwith
yourstudentsaboutwhatyouknowand,moreimportantly,whatyou
don’tknow.Ifastudentasksyouaquestionyoudon’tknowtheanswer
to,tellthem.
Admittingthatyoudon’tknowsomethingmakesyouhuman.You’renota
robotandyourbrainisn’tpluggedintoGoogle—notyetanyway.But
there’smore.Mostpeopleshowrespectifyoucanadmitthatyoudon’t
knoworcannotdosomething.Whatcanseemlikeasignofweaknessis
actuallyasignofstrengthandconfidence.
ItAutomaticallyDisappears
Idon’tfeelit’simportanttounderstandtherootcauseofimposter
experiencetoridyourselfofit.Afterawhile,itdisappearsautomatically.
WheneverIdiscussaprojectwithaclient,I’mopenandhonestabout
what’spossibleandwhatisn’t.IfI’mnotfamiliarwithaspecific
technology,Itellthemandprovideanalternative.
Beingopenincreasesyourcredibilityanditstrengthenstherelationship
withtheclient.It’sapowerfulantidoteforimposterexperience.
TalkAboutIt
I’vebeenwantingtowritethispostforquiteawhile.Whatinspiredmeto
takeactionwasarecentepisodeoftheTropicalMBApodcast,
TMBA384:AreYouanImposter?.Oneofthekeytakeawaysfromthe
episodeissimple,surroundyourselfwithlike-mindedpeopleandtalk
aboutit.
Youonlyfeellikeanimposterifyoucompareyourselfwithothers.—
LuisMiguelGil
Daninterviewsseveralpeoplethatopenlytalkaboutimposter
experience.LuisMiguelGilopensupabouthowheexperiencedimposter
experience.Healsozoomsinonwhatcausesimposterexperienceand
howtodefuseit.ThisiswhatLuishastosayaboutfeelinglikean
imposter.
WhenIcomparemyselfwithLuisfromthreeyearsagoIseehuge
growth,hugesuccess.Amazing.I’mveryhappyandveryproudof
whatI’veaccomplished.ButwhenIcomparemyselfwithpeoplelike
youguys(DanandIan,thehostsofthepodcast)orother
entrepreneursthathavehadmanyamazingsuccesses,IfeelI’mfar
awayfromreachingthat.I’msofaraway.—LuisMiguelGil
Itcansometimesbeeasytobecomeoverwhelmedorintimidatedbywhat
othersaredoingandhaveachieved,especiallyifyouwatchtoomany
talksorreadtoomanyblogposts.It’simportanttoappreciateyourself
anddon’tundervaluewhatyou’vealreadyachieved.
It’sCommon
Imposterexperienceisn’tuncommon.Manypeoplesufferfromimposter
experience,includingpeoplethatareconsideredtopperformersintheir
field.TomHanks,oneofmyfavoriteactors,madeasurprisingcomment
severalyearsago.
IstillfeelsometimesthatI’dliketobeasgoodasso-and-soactor.I
seesomeotheractors’work,andIthinkI’llnevergetthere.IwishI
could.—TheNewYorkTimes
Thismayseemoddforsomeonewho’swontwoacademyawards.It
showsthatitisn’tuncommon.Itmakeshimhumanandapproachable.
Don’tBelieveEverythingYouRead
Imposterexperiencecanalsobefueledbybelievingeverythingyouread.
Somepeoplemayclaimthattheybuiltasuccessfulbusinessintwo
monthsbyworkingfivehoursaweek.Thatmaybepossible,butthey’re
theexceptiontotherule.
Don’tcompareyourselfwithexceptions.Ifyouwanttoachievesomething
thatyou’reproudof,youneedtoputinthework.Ifyouwanttobecomea
greatdeveloper,you’llneedtowritecode,andlotsofit.Andspending
yourdaysreadingtutorialsorbrowsingStackOverflowwon’thelpmuch.
Don’tLetItAffectYou
Mostdeveloperssufferfromimposterexperienceatsomepointintheir
life.Andthat’sfine.Itwon’tkillyou.ButDanAndrewsemphasizesthat
impostorexperiencecangrowintoaproblemif,howyourunyour
businessoryourcareer,isaffectedbyimposterexperience.
ThisisaproblemIseemanyfreelancersstrugglewith.Theyundervalue
whattheyhavetooffer.Somethingthatseemseasyoreventrivialtoyou
canbeofgreatvaluetoothers.Thatdoesn’tmeanyouneedto
undervalueyourselfor,heavenforbid,doitforfree.Thereasonyoufindit
easyisbecauseyou’reanexpertatwhatyoudo.Andthat’swhypeople
wanttopayyouforyourservicesandexpertise.
Acarpentergetsbetterthelongerhedoeshisjob.Thismeanshegets
bettertheolderhegets.Doyouthinkhedropshishourlyrateashegets
betterandgrowsolder?Theoppositeistrue.Don’tthinkforasecond
thatyou’reanydifferent.
SuccessThroughFailure
Failurecontinuestobeatouchysubjectinmanypartsoftheworld.Ifeel
it’smuchlessofataboointheUnitedStates.Let’sbehonest,ifyou
succeedwithoutfailure,thenyouhaven’taimedhighenough.
Everysinglepersonthathasreachedsuccesshasexperiencedfailure.
It’snotsomethingtobeembarrassedabout.Youcanonlysucceedby
trying,failing,tryingharder,failingagain,andpersistinguntilyou
succeed.
Rememberthis,ifyousucceedwithoutfailing,you’renotaiminghigh
enough.Berealistic,butmakesureyou’renotunderestimatingwhatyou
canachieve.Somethingsarehard,butthatdoesn’tmeanthey’re
impossible.
PART9:LEARNING
1ChooseYourTeacherWisely
Thevastnumberoftutorialsandcoursesaboutsoftwaredevelopmentis
ablessingforanyoneinterestedinbuildingsoftware.Andthisisnoless
trueforanyoneinterestedinSwiftdevelopment.GettingstartedwithSwift
developmentiseasyanditdoesn’tneedtocostyouafortune.But,as
you’veprobablydiscovered,there’sadownsidetothiswealthof
information.Inthischapter,I’dliketohighlightthreeproblemsthatI
frequentlyfaceandhearaboutfrommystudentsandreaders.
InformationOverload
WhenIstartedlearningCocoadevelopmentin2006,therewereonlya
handfulofbooksavailable.AaronHillegass’bookCocoaProgramming
for(Mac)OSXwastheunofficialgoldenstandard.
CocoaProgrammingfor(Mac)OSX
But,withtheintroductionoftheiPhonein2007andthereleaseofthe
officialSDKin2008,thatnumberincreasedsubstantially.Thereare
manybooksavailablefromtraditionalpublishers,suchasApressand
O’Reilly,butmanydevelopers,includingyourstruly,havechosenthe
pathofself-publishing,bypassingtraditionalpublishers.
Ithasneverbeeneasiertopublishabookorcourse.Booksandcourses
areavailableatanypricepoint,includingfree.Unfortunately,thishas
madeitmorechallengingfordeveloperstodecidewhichpathtochoose
tolearnthetopicthey’reinterestedin.Eachdaynewtutorials,videos,
andcoursesarepublished.It’schallenging.That’sforsure.
Theblessingofhavingsomuchfreeinformationatyourfingertipsismore
oftenthannotacursefordevelopersthatwanttolearnCocoaandSwift
development.Notonlyistheamountofinformationoverwhelming,there
doesn’tseemtobeaclearpathtofollow.It’sdifficulttoseetheforestfor
thetrees.Don’tstophere,though.There’shope.
WhotoTrust
EverydeveloperthatwritesaboutCocoaandSwiftdevelopmentdoes
thiswiththebestofintentions.Theywanttohelppeoplelearnsomething
neworsolveaproblemthey’rehaving.It’sfantastictoseehowmanyof
ustakethetimetowriteatutorialorproduceavideotohelpothers.It’s
oneofthekeyingredientsofthethrivingCocoaandSwiftcommunities.
Despitetheauthor’sgoodintentions,though,whatthey’reteachingmay
beincorrectorignoregoodpractices.Ifyou’renewtoasubject,thenyou
maynotbeabletospotthesemistakes.Thetitleofthischapterisvery
telling.It’sbecomemoreimportantthanevertochooseyourteacher
wisely.WhileIdon’tbelievethatpeopleareintentionallyputtingoutbad
contentorincorrectinformation,it’suptoyou,thestudent,tofilterthe
goodfromthebad.
Afewweeksago,Iwaslookingforasolutiontocustomizethecolorof
theclearbuttonofaUITextFieldinstance.Itturnsoutthatthetintcolorof
aUITextFielddoesn’taffecttheclearbutton.Bummer.Iwashavingan
issuewheretheclearbuttonwasnearlyinvisibleagainstadark
background.
Duringmysearchforananswer,IstumbledonseveralStackOverflow
entriesthatrecommendeddiggingintotheviewhierarchyofthetextfield,
lookingfortheclearbutton,andmodifyingitstintcolor.AsImention
elsewhereinthisbook,thisisabadpractice.IftheAPIdoesn’tallowfor
thistypeofcustomization,youfileabugwithAppleandimplementa
customsolution.That’stheonlycorrectsolution.Yourcleverworkaround
willinevitablybreakwhenApplemakeschangestotheinternalsofthe
UITextFieldclass.RespecttheSDK.Always.
Theanswersthatsuggesteddiggingintotheviewhierarchyofthetext
fieldwereupvotedbecause,atthattime,itsolvedtheproblem.
Unfortunately,thiscreatesabiggerproblem.Everyinexperienced
developerthatreadsoneoftheseanswersismadetobelievethatthisis
aviablesolution,thatthisisfine.Insteadofspottingtheriskofthe
solution,theywronglybelievethatthey’vepickedupagoodpracticethey
canadoptinother,similarsituations.
IfIneedtopickupanewframeworkorAPI,IrelyonthepeopleIhave
cometotrustovertime.Theseareveryoftenpeoplethathavebuiltup
authorityinthecommunityoverseveralyearsorpeoplelikeAaron
Hillegass,MarcusZarra,andJeffLaMarchethathavebeenaroundsince
theveryearlydaysoftheplatform.
Focus,Focus,Focus
Iusedtofollowaslewofdevelopersonsocialmedia.Iwantedtoknow
whattheywerelearning,whattheyhadtoshare,andwhichtechniques
andlessonsIcouldadoptinmyownprojects.Aboutayearago,I
stoppeddoingthisbecauseitwastoooverwhelming.There’ssomuchto
learn.TheplatformsandtheSwiftlanguageevolvesoquicklythatit’s
hardtokeepyourfocusifyoudon’tprotectitferociously.
Therearecountlesstalksaboutalmostanytopicyoucanimagine,butit
canleaveyouwithmorequestionsthanyoustartedwith.Idon’tknow
aboutyou,butfocushasbeenthecureforme.Attentionhasbecomeso
importantintoday’sbusyworldthathavingtheskilltofocusobsessively
isaskilleverydevelopershouldlearntomaster.
Idon’tbelieveintheconceptofagenius.It’struethatsomepeopleare
moregiftedthanothers,but,intheend,developersthatexcelinwhat
theydoarethosewhocanfocusandcommittosomething.Youdon’t
masterSwiftbyreadingafewchaptersinApple’slanguageguide.That’s
agoodstart,butit’saprocessthatcontinuesandneverstops.That’sthe
beautyofit.No?Didn’tyoubecomeadeveloperbecausethesky’sthe
limit?
That’salsowhyIoftenaskdeveloperswhatgoalstheyhaveforthe
comingmonthsoryears.WhatI’mactuallyaskingthemiswhattheir
focusis.Whataretheytryingtoaccomplish?Ambitiouspeoplehavea
clearfocus,veryoftenasingularone.Letmeaskyouthen,“Whatisyour
focus?”
NeverStopLearning
Themobilespaceisstillveryyoung,relativelyspeaking,anditevolvesat
anincrediblepace.WithAppleandGoogleheavilyinvestingintheir
platforms,thespeedwithwhichmobileplatformsevolverequires
developerstofocusandlearnnon-stop.
In2015,Appleintroducednolessthantwonewplatforms,tvOSand
watchOS.WhiledevelopersfamiliarwithiOSwon’thaveahardtime
gettinguptospeedwithApple’sbrandnewSDKs,therearemany,many
APIsandparadigmstobecomefamiliarwith.It’sunderstandableifyou
feelalittleoverwhelmedasamobiledeveloper.That’sfineandit’sfineto
admitthat.
Ifyoudecidetobecomeadeveloper,regardlessoftheplatformyouwrite
softwarefor,youneedtoacceptandbecomecomfortablewiththefact
thatlearningonadailybasisispartofthejob.
Forthepastfewyears,Applehasreleasedanewversionofitsoperating
systemseveryyear,introducingnewtechnologiesweneedtobecome
familiarwith.TheSwiftprojectcontinuestoevolveatafastpace.Atthe
timeofwriting,Swift4isjustaroundthecornerandwithitcomenew
features,bugfixes,andnumerousimprovements.
Areyoureadytodiveinheadfirst?IfAppleannouncesaslewofnew
APIsnextyear,willthatscareyouorwillitexciteyou?Doyouhavethe
motivationtonotonlycontinuelearningbutalsopushtheenvelope.
UsinganAPIisonething,pushingittoitsboundariesandbeyondis
whereit’sat.
Ifyoulikeprogramming,butprefertostickwithwhatyouknow,then
mobiledevelopmentmaynotbethebestchoice.Iflearningisinyour
bloodandthemerethoughtofWWDCorGoogleI/Ogivesyou
goosebumps,thenbeingamobiledeveloperisthebestjobintheworld.
2TakingaShortcut
WhatIlikeaboutprogrammingandsoftwaredevelopmentisthat
everyoneistreatedthesame.Thismeansthattherearenoshortcutsyou
cantake.ThisissomethingIbringupseveraltimesinthisbookbecause
Istronglybelievethatyouneedtoputintheworkifyouwanttoevolve
intoaproficientSwiftdeveloper.
Ifyourgoalistobecomeoneoftheworld’stopviolinists,thenyousimply
needtoputinthehours.Thesameappliestoprogrammingandsoftware
development.Whywoulditbeanydifferent?
Eventhoughtherearenoshortcuts,thereareseveralpathsyoucantake
tospeedupyourcareer.TheshortcutsImentioninthischapterare
legitimaterecipestoaccelerateyourgrowthasadeveloper.
Internship
Aninternshipattherightcompanycanspeedupyourcareer
dramatically.Whyisthat?Ajuniordeveloperhasalottolearnandthat’s
somethingmany,manydevelopersareoverwhelmedby.WhatdoIneed
tolearnnext?WhatdoIneedtoknowtobuildmyfirstapplication?
There’salottolearnandalotthatyoucouldlearn.Whichtopicisthe
nextstepyouneedtotake.Havingamentororaseniordeveloperby
yoursidecanmakeaworldofdifference.Forthistowork,though,it’s
importantthatyoucarefullychoosetheplaceyouapplyforaninternship.
It’sfinetobepicky.It’snotbecauseyouhavelittleexperiencethatyou
havetoacceptwhatyoucanget.Doyourresearch,askaround,and
contactthecompaniesthatyouthinkareagoodfitforyouandwhatyou
wanttoachieve.
FreelancingandSubcontracting
Thelifeofafreelancermayseemliketheperfectlifetomanydevelopers.
It’struethatitcomeswithseveralperks.Youcanstartworkwhenever
youlikeandyoucanchooseyourworkplace.Butit’satoughlifeattimes,
especiallyifyou’rejuststartingout.
Forthatexactreason,however,freelancingcanbeashortcutinyour
career.You’reforcedtolearnalotofstuffandfigurethingsoutonyour
own.Youneedtotakecareofamillionthingstokeepyourbusiness
afloat.Youneedtodevelopskillsyoudidn’tknowyoueverneeded,such
aswritingproposals,talkingtoclients,andworkingwithsubcontractors.
Thisisn’tforeveryone,butifthissoundslikeachallengetoyou,then
freelancingcansignificantlyspeedupyourcareer.
Subcontractingissimilartofreelancing.Thedifferenceisthatyouusually
workatyourclient’scompany.Itcansometimesfeelasifyou’rean
employeeifyou’resubcontracting.ThereasonIconsidersubcontracting
ashortcutisforexactlythatreason.
Asasubcontractor,youusuallybecomeamemberoftheteamatthe
companyyouworkfor.Youlearnaboutthecompany’sculture,thetools
theyuse,theirworkflow,andtheirautomation.Theresultisthatyoulearn
alotinashortamountoftime.Youseewhatworksandwhatdoesn’t.
Iworkedasasubcontractorforseveralyearsandithastaughtmealot
aboutthevariousaspectsofrunningabusiness,projectmanagement,
programing,automation,andtesting.Thebiggerthecompany,themore
effectivethisshortcutis.
Asasubcontractor,youswitchcompaniesfromtimetotimeandthatonly
increasestheamountyoulearn.Everycompanydoesthingsdifferently
andthat’swhatyou’relookingfor.Youcanpickandchoosewhatworks
andapplythat.It’sonethingreadingaboutsomething,butit’ssomething
completelydifferenttobeimmersedinit.
Ifyou’reafreelancerandfreedomisimportanttoyou,then
subcontractingmaynotbewhatyou’relookingfor.Keepthatinmind
whenyou’regiventhisopportunity.
Learn,Learn,Learn
Ifyou’rereadingthisbook,thenitprobablymeansthatyou’vechosenfor
acareerinthemobilespaceoryouwanttobuildfantasticproductsthat
helpthousandsormillionsofpeople.Thetechnologyindustryisevolving
atabreakneckpaceandyouneedtostayuptodate.Youneedtolearn
everysingleday.
Thatdoesn’tnecessarilymeanthatyouneedtospendanhouradaywith
yournoseinabook.It’senoughtohaveanopenmind.Whatdoesthat
mean?Overtheyears,I’vedevelopedaslewofhabitsandstrategiesto
solvecommonprogrammingproblems.ButItrytodothingsabit
differentlyeverytimeIworkonaproject.That’showIdiscoveredthe
Model-View-ViewModelpattern.Theviewcontrollersinmyprojectswere
gettingtooheavyanditwastimeforsomethingdifferent.
Istudiedthepatternforseveralweeks,triedafewimplementations,and
settledwithasolutionIsatisfiedmyneedsandrequirements.That’show
Iusuallypickupnewframeworksandlibraries.Haveanopenmindand
trytodothinsabitdifferentlyeverytimeyouencounterafamiliar
problem.
Build,Build,Build
OneofthemainreasonsIcontinuetoinvesttimeandenergyinside
projectsistolearnandexperiment.Ifyou’reworkingforalargeagency
oraproductcompany,youdon’tnecessarilyhavetheluxuryofworking
withthelatestandgreatest.Manycompaniespostponedthetransitionto
SwiftforthefirstfewyearsbecauseObjective-Cwasmuchmorereliable
andithadaproventrackrecord.Butwhat’sstoppingyoufromlearning
Swifttoday?What’sstoppingyoufromplayingwithCoreDataorRealm
inyoursparetime?
Ifyou’relucky,thenyouworkatacompanythatgivesyouthefreedomto
learnnewthingsonthejob.Whilethismayseemlikeagenerous
gesture,youremployerknowsandunderstandsthattheyneedtoinvest
intheiremployeesandtheireducation.Thetechnologyindustryisa
competitivearenaandwhatworkedyesterdaymaynolongerworktoday
ortomorrow.
ChooseWisely
IstartedthisbookwithastrongfocusonyourfoundationandIwantto
brieflyrevisitthistopic.It’stemptingtofocusontheshinystuffcompanies
likeAppleandGooglespoiluswith.Butrememberthatyoumakealiving
buildingapplicationsthatarepoweredbytechnologiesthathavebeen
aroundfordecades.Makesureyoudon’tneglectyourfoundation.
Withasolidfoundationit’seasiertopickupnewtechnologies.Onceyou
understandhowthepuzzlefitstogether,it’seasiertopickupnew
languages,frameworks,andlibraries.Investinginyourfoundationshould
alwaysbeyourmainconcern.Ithelpsyoubuildconfidenceandit
ensuresthatyoucanmakealivingdoingwhatyoulovedoing,building
software.
3SomeThingsAreHard
BeforetheiPhonewasintroducedin2007,CocoaProgrammingforMac
OSXbyAaronHillegasswasthebookifyouwereinterestedinCocoa
development.ItwasAaron’sbookthatintroducedmetoCocoa
programming.
OneofthemostimportantlessonsAarontaughtmehadnothingtodo
withprogramming.Inthefirstchapterofhisbook,Aaronwritesabout
Rock,aformerbosshehadworkedwith.
IusedtohaveabossnamedRock.Rockhadearnedadegreein
astrophysicsfromCallTechandhadneverhadajobinwhichhe
usedhisknowledgeoftheheavens.OnceIaskedhimwhetherhe
regrettedgettingthedegree.“Actually,mydegreeinastrophysics
hasprovedtobeveryvaluable,”hesaid.“Somethingsinthisworld
arejusthard.WhenIamstrugglingwithsomething,Isometimes
think‘Damn,thisishardforme.IwonderifIamstupid,’andthenI
rememberthatIhaveadegreeinastrophysicsfromCalTech;Imust
notbestupid.”-AaronHillegass
Somethingsarehard.Unfortunately,admittingthatsomethingsarehard
issomesortoftabooamongprogrammers.Youlosecredibilityasa
programmerifyouadmitthatyou’restrugglingunderstandingsomething.
CutYourselfSomeSlack
Ifyou’rejuststartingoutasaprogrammeroryou’vebeendevelopingfor
yearsandarenowtestingthewaterswithanewlanguageortechnology,
thencutyourselfsomeslackifyou’renotmakingasmuchprogressas
you’dhoped.Somethingsarehardandthat’sfine.
Generics,forexample,aremischievouscreaturesifyou’recomingfrom
CorObjective-C.It’sfineifyouneedabitmoretimetoletthisparadigm
sinkin.Curryingisaconceptevensomeexperienceddevelopersavoid
becauseitisn’teasytograspifyou’renotusedtofunctional
programmingconcepts.
That’sfine.Unlessyou’reagenius,youwillstruggleattimes.That’swhat
makesprogrammingfun.Right?Whatwouldthechallengebeifevery
daywasawalkinthepark.Whywouldyouinvesttimeandenergyin
learningsomethingifitwaseasy.
It’snotthatI’msosmart,it’sjustthatIstaywithproblemslonger.—
AlbertEinstein
Programmingisaboutsolvingproblemsandthatincludeslearninganew
language,framework,ortechnology.Challengingyourselfisimportant,
butit’sequallyimportanttogiveyourselfabreakfromtimetotime.
Somethingsarehardandthat’sfine.
4LearntheRules,ThenBreakThem
Whenyou’restartingoutasadeveloperoryou’relearninganew
language,framework,orlibrary,you’reoftenwonderingwhatthebest
practicesareandwhichrulesyouneedtostickto.Mostofushavegone
throughthisphasewhenwelearnedtheSwiftlanguage.
IoftenbringupCoreDatabecauseit’ssuchagoodexample.Developers
areveryoftenfrustratedwiththeframeworkandthat’sinpartwhythe
frameworkdoesn’thaveagreatreputation.Icanassureyouthatthevast
majorityofproblemsiscausedbynotknowingaboutorignoringtherules
oftheframework.
Examples
Viewsaresupposedbedumb.Aviewshouldonlyknowhowtopresent
thedatait’sgiven.Thisisaruleyoushouldn’tbreak.ButIdon’tagree
withthat.Onceyouunderstandwhythisruleisimportant,it’sfineto
breakitaslongasyouunderstandwhattheconsequencesare.
IsometimesbreakthisrulewhenIcreateacomplextableorcollection
view.Ifyounoticethatyou’remakingitveryhardonyourselftokeepthe
viewdumbandignorant,thenitmaybebettertolookforanalternative.
Insuchascenario,Ipromotethetableorcollectionviewcelltoa
controller.Iseeeachtableorcollectionviewcellasaviewcontrollerand
itscontentviewastheviewcontroller’sview.Thiscanoftenreducethe
complexityintheviewcontrollerthatdrivesthetableorcollectionview.
IknowthatI’mbreakingaruleandIunderstandtheimpactofthat
decision.ThatunderstandinggivesmetheconfidenceIneedto
implementasolutionIknowworksbetter.
AnothercommonexampleinvolvestheModel-View-ViewModelpattern.
YoumayhavereadthatimportingUIKitintheviewmodelisacode
smell.Iagreewiththisstatementandunderstandwhythatis.Theview
modelshouldn’tknowabouttheviewitpowersthroughtheview
controller.IfyouimporttheUIKitframework,itindicatesthatyou’redoing
somethingintheviewmodelthatrelatestotheviewlayerhencethecode
smell.
Thisisclear.ButIsometimesbreakthisruleforobviousreasons.Whatif
IwanttoreturnaUIImageinstancefromtheviewmodelorIwantto
specifytheaccessorytypeofatableviewcell?Thesecondexampleis
hardertojustify,butreturningaUIImageinstanceisafineexample.The
UIImageclassisdefinedintheUIKitframeworkandifyouwanttoreturna
UIImageinstance,youhavenootheroptionbuttoimporttheUIKit
framework.Youcouldsticktotherulesbyjustreturningthenameforthe
image,butisthatreallyabettersolution?Isn’tthatsimplyaworkaround
toabidebyarule?
GrowingasaDeveloper
There’sasubtlebutimportantdifferencebetweenviolatingaruleand
breakingarule.Breakingaruleimpliesthatyouknowabouttheruleand
youshouldknowabouttheconsequences.Thatsaid,breakrules
sparingly.There’sareasonwhydesignpatternsandbestpracticesexist.
Itcansometimeshelptoplaybytherulestounderstandhowtobreak
them.
There’sasubtlebutimportantdifferencebetweenviolatingarule
andbreakingarule.Breakingaruleimpliesthatyouknowaboutthe
ruleandyoushouldknowabouttheconsequences.
Ifyou’renewtoalanguageorframework,thenIrecommendplayingby
therules.Thisisessentialtounderstandthelanguageorframework,
learnabouttheAPI,andhowthevariouspiecesofthepuzzlefittogether.
Youcannotsafelybreakaruleifyoudon’tknowwhattheconsequences
are.Juniordevelopersdothisfrequentlywithoutrealizingit.Andthat’s
fine.Youalwayslearnsomethingifyoumakeamistake.Justmakesure
youdon’tmakethesamemistaketwice.
CreatingSomethingBetter
Theconceptofbreakingrulesisquitecommonindesign.Revolutionary
designsdon’temergebystickingtotherules.Eventhoughthisisless
obviousinsoftwaredevelopment,breakingrulescanleadtobetter
designpatternsorpractices.Butitrequiresadeepunderstandingof
thoserulestopullitoff.