Maintainable + Extensible = Clean ... yes, Code!

72
Antonio Perić-Mažar 29.10.2016 - #sfcampua Maintainable + Extensible = Clean ... yes, Code!

Transcript of Maintainable + Extensible = Clean ... yes, Code!

Page 1: Maintainable + Extensible = Clean ... yes, Code!

AntonioPerić-Mažar

29.10.2016-#sfcampua

Maintainable+Extensible=Clean...yes,Code!

Page 2: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Aboutme

• AntonioPerić-Mažar,mag.ing.comp.

• CEO,Co-Founder@Locastic

• Co-Founder@ShiftConference

• Softwaredeveloper,Symfony2

• OpenSourceContributor

• SFUGCRO

• w:www.locastic.com

• m:[email protected]

• t:@antonioperic

Page 3: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Locastic

• Wehelpclientscreateamazingwebandmobileapps(since2011)

• designanddevelopmentagency

• mobiledevelopment

• webdevelopment

• UX/UI

• TrainingandConsulting

• ShiftConference,SymfonyCroatia

• www.locastic.com

• t:@locastic

Page 4: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Locastic

Page 5: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Questions?

• Whothinksheisproducinggoodcode?

• Whatisbadcode?

• Whatisgoodcode?

• Doyouknowhowtomeasurecodequality?

Page 6: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Page 7: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Note:whenweaskedforthiscodewegotitinzipfile!!!NoVCSatall!

Page 8: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Page 9: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Page 10: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Page 11: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Page 12: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Page 13: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

ThiswasonehugeWTFnproject!

Page 14: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Page 15: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

CodeSmell!!!(BadCode)

• Useglobals

• Anythinghardcoded(url,ip,etc)

• Longclassesormethods

• Deepstructures

• Longandbadnames

• Lackofformatting

• Lackofstandard

Page 16: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

CodeSmell!!!(BadCode)

• Overuseofpublicstatic

• Toomanyparameters

• Weirdorderofparameters

• GODObject(hecandoeverythingandheknowseverything)

• Noinputvalidation

• Nocomments

Page 17: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

CodeSmell!!!(BadCode)

• Takes1-2sentencestoexplain

• Copy-pasted-repetitivecode

• Neverusedinheritance,interfaceorcomposition

• notreadable

• nottestable

Page 18: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

CodeSmell!!!(BadCode)

• hardtounderstand

• hardtomaintain

• givesaheadache

• youdon’twon’ttoworkon/withit

Page 19: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Page 20: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

AvoidbeingSTUPID

Singleton

Tightcoupling

Untestability

Prematureoptimization

Indescriptivenaming

Duplication

Page 21: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

AvoidbeingSTUPID

Singleton

Tightcoupling

Untestability

Prematureoptimization

Indescriptivenaming

Duplication

Page 22: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Page 23: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Butwhywestilldoingit…

• Wearelazy

• Shortdeadlines

• Baddecisions

• Fast-good-cheap

• Wearealwaysthebestdeveloperever:)

Page 24: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Codehasexpirationdate!

Page 25: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Yesterday!

Page 26: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Gooddevelopersareshipping!balance shipping vs good code

Page 27: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Developersareevolving!

Page 28: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Page 29: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Languageisevolving

• Frameworks(Symfony<3)

• Packagemanagers(composer)

• Standards

• PHP7

Page 30: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

“Anyfoolcanwritecodethatacomputercanunderstand.Goodprogrammerswritecodethathumanscanunderstand.“

Martin Fowler

Page 31: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

CODE

Page 32: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Page 33: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Cleancode

• Codethatdoesn’texist

• KISS

• DRY

• SOLID

• Don’treinventthewheel

• DesignPatterns

• Testable->Tested

Page 34: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Cleancode

• Flexible

• Maintainable

• Easytorefactor

• Readable

Page 35: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Cleancodeiseasytounderstand,easytochangeandreusable.

Page 36: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Page 37: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Whyweshouldcare…

• Someoneelsewillusethatcode

• Youwillusethatcode

• Badcodedoesalotofthingsbutnonewell

• Youdon’twritecodejusttobethere

• Maintainingshouldbeeasy

• Goodcodesavemoneyandtime

Page 38: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Page 39: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Iftechnicaldebtisnotrepaid,itcanaccumulate'interest',makingithardertoimplementchangeslateron.

Page 40: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Page 41: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Guidanceforbetter(clean)code

Page 42: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#1Namingmatters

• Don’tabbreviate

• $string->b=false;

• $string->bold=false;

• Makecodereadable

• Meaningfulnames

• Improvesreadability

• Goodcodeshouldbetalkingtoyou

• Youshouldreaditlikeabook,whitespaceisimportant

Page 43: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#1Namingmatters

• Twoworldwordsvariablename

• $data,$data2

• $total,$total2,$total3

Page 44: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#1Namingmatters

Page 45: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#1Namingmatters

• Don’tbesilly!

Page 46: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#1Namingmatters

• Goodnameshouldexplain

• whyitexist

• whatitdoes

• howtouseit

• Ifyouneedcommentforexplainit,itisbadname

• Classshoulduseanoun,methodaverb

Page 47: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#2Codestandard

• Don’tmixstylesinproject,usewhitespace

• Easiertonavigateinsideproject

• Lesstimeforboardingnewdeveloper

• PHP-FIG

• StickwithPSR

• PSR-0autoloading

• PSR-1basingcodestyle

• PSR-2detailedcodingstyle

Page 48: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#2Codestandard

• SymfonyfollowsthestandardsdefinedinthePSR-0,PSR-1,PSR-2andPSR-4documents.

• http://symfony.com/doc/current/contributing/code/standards.html

Page 49: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#3Useonlyonelevelofindentationpermethod• {{{}}}trytoavoidthis

• forcesingleresponsibility

• small,simple,easiertounderstand

• ourmindmodelisimportant

• separatelogicblocksandcomplexlevelofindentationintomethods

Page 50: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#4Don’tuseelse

• reducecodecomplexity

• earlyreturns

• useExceptions

• itreducecomplexofourmindmodel

• methodshouldnotdomorethenonething

• don’tuseintermediatevariable

• usepolymorphism,switchissignalforpolymorphism

• don’tabusepolymorphism

Page 51: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#4Don’tuseelse

Page 52: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#5Keepyourclasses/methodssmall• easiertotest

• doonething,anddoonethingwell

• allfunctionsshouldreturnsomethingandavoidreturningNULL

• keepmethodssmall(max.20linesofcode)

• avoidside-effects

• avoidglobalstate

Page 53: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#6UseExceptions

• Usethem

• Makesuretocatchthem

• Specifythenatureoftheerror

• thrownewInvalidArgumentException();

• Don’tusespecialerrorcodes

Page 54: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#7Designpatterns

• usethem,theygiveyousolutionforsomewellknownproblems

Page 55: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#8UseSPL

• TheStandardPHPLibrary(SPL)isacollectionofinterfacesandclassesthataremeanttosolvecommonproblems.

• SPLprovidesasetofstandarddatastructure,asetofiteratorstotraverseoverobjects,asetofinterfaces,asetofstandardExceptions,anumberofclassestoworkwithfilesanditprovidesasetoffunctionslikespl_autoload_register()

Page 56: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#8UseSPL

• Datastructures

• SplDoublyLinkedList—TheSplDoublyLinkedListclass

• SplStack—TheSplStackclass

• SplQueue—TheSplQueueclass

• SplHeap—TheSplHeapclass

• SplMaxHeap—TheSplMaxHeapclass

• SplMinHeap—TheSplMinHeapclass

• SplPriorityQueue—TheSplPriorityQueueclass

• SplFixedArray—TheSplFixedArrayclass

• SplObjectStorage—TheSplObjectStorageclass

Page 57: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#8UseSPL

• Iterators

• AppendIterator—TheAppendIteratorclass

• ArrayIterator—TheArrayIteratorclass

• CachingIterator—TheCachingIteratorclass

• CallbackFilterIterator—TheCallbackFilterIteratorclass

• DirectoryIterator—TheDirectoryIteratorclass

• EmptyIterator—TheEmptyIteratorclass

• FilesystemIterator—TheFilesystemIteratorclass

• FilterIterator—TheFilterIteratorclass

• GlobIterator—TheGlobIteratorclass

• InfiniteIterator—TheInfiniteIteratorclass

• …

Page 58: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#8UseSPL

• Interfaces• Countable—TheCountableinterface

• OuterIterator—TheOuterIteratorinterface• RecursiveIterator—TheRecursiveIteratorinterface

• SeekableIterator—TheSeekableIterator

Page 59: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#8UseSPL

• Exceptions

• BadFunctionCallException—TheBadFunctionCallExceptionclass

• BadMethodCallException—TheBadMethodCallExceptionclass

• DomainException—TheDomainExceptionclass

• InvalidArgumentException—TheInvalidArgumentExceptionclass

• LengthException—TheLengthExceptionclass

• LogicException—TheLogicExceptionclass

• OutOfBoundsException—TheOutOfBoundsException

• OutOfRangeException—TheOutOfRangeException

• OverflowException—TheOverflowException

• RangeException—TheRangeException

• RuntimeException—TheRuntimeException

• UnderflowException—TheUnderflowException

• UnexpectedValueException—TheUnexpectedValueExceptionclass

Page 60: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#9Lawofdemeter(LoD)

• Eachunitshouldhaveonlylimitedknowledgeaboutotherunits:onlyunits"closely"relatedtothecurrentunit.

• Eachunitshouldonlytalktoitsfriends;don'ttalktostrangers.

• Onlytalktoyourimmediatefriends

• Helpyoubuildcodethatiseasiertotest

Page 61: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#9Lawofdemeter

Page 62: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#9LawofDemeter

Page 63: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#9Lawofdemeter(LoD)

• Benefits:

• Keepobjectinstantionsimple

• Easiertomockobjects

• Simplifydependencygraph

Page 64: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#10Comments

• Goodcomments

• Badcomments

• PHPDoc

• Don’tusecommentsfortrackinghistoryofchanges

Page 65: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#11Usetools

• PHPCS

• PHP-CS-Fixer

• pDepend(performsstaticcodeanalysis)

• PHPLOC(AtoolforquicklymeasuringthesizeofaPHPproject)

• SensioLabsInsight

• phpmd(messdetector)

• PHPCPD(copypastedetector)

• PHPDCP(deadcodedetector)

• learnmoreaboutyourIDE(PHPStormisamazingtool)

Page 66: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#12improveyourself

• readalotofcode

• http://www.livecoding.tv/

• workinpairs• doopensource-youwillgetalotoffreereviews

fromamazingdevelopers

• showyourcodetootherdevelopers

• gotoconferences

• beresponsiveforyourcode

Page 67: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

“Iliveandbreathemycodeandmycodeismostlythefunstuff.Youknowthelogic,thestuffthatmakescoolapplications,right?.“

Misko Havery

Page 68: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#11Boy-scoutrule

Page 69: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

#12Boyscoutrule

• Alwayscheckamoduleincleanerthanwhenyoucheckeditout.

• Alwaysleavecodeinbettershapethenyoufoundit

Page 70: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Conclusion

• Cleancodeis:

• structured

• simple

• consistent

• Useboyscoutrule

• Dosmallsteps

• Thereisnosilverbulletonlyhardwork

Page 71: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

References

• https://cleancoders.com/• CleanCode:AHandbookofAgileSoftwareCraftsmanship,RobertC.

Martin

• DottingYourI’sandCrossingYourT7s,JulietteReindersFolmer,IPCSprint2015

• Yourcodesucks,let'sfixit-ByRafaelDohms

• CleanCode,TobiasSchlitt,WebSummerCamp2016

• GoogleTechTalks,CleanCode• https://www.youtube.com/watch?v=HZJxjlvBbVA,CleanCode,

DavidDonahue

• PlentyofothertalksatYoutube

Page 72: Maintainable + Extensible = Clean ... yes, Code!

@antonioperic

Thankyou!

www.locastic.com [email protected]

@antonioperic