Maintainable + Extensible = Clean ... yes, Code!
-
Upload
antonio-peric-mazar -
Category
Education
-
view
272 -
download
2
Transcript of Maintainable + Extensible = Clean ... yes, Code!
AntonioPerić-Mažar
29.10.2016-#sfcampua
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
• t:@antonioperic
@antonioperic
Locastic
• Wehelpclientscreateamazingwebandmobileapps(since2011)
• designanddevelopmentagency
• mobiledevelopment
• webdevelopment
• UX/UI
• TrainingandConsulting
• ShiftConference,SymfonyCroatia
• www.locastic.com
• t:@locastic
@antonioperic
Locastic
@antonioperic
Questions?
• Whothinksheisproducinggoodcode?
• Whatisbadcode?
• Whatisgoodcode?
• Doyouknowhowtomeasurecodequality?
@antonioperic
@antonioperic
Note:whenweaskedforthiscodewegotitinzipfile!!!NoVCSatall!
@antonioperic
@antonioperic
@antonioperic
@antonioperic
@antonioperic
@antonioperic
ThiswasonehugeWTFnproject!
@antonioperic
@antonioperic
CodeSmell!!!(BadCode)
• Useglobals
• Anythinghardcoded(url,ip,etc)
• Longclassesormethods
• Deepstructures
• Longandbadnames
• Lackofformatting
• Lackofstandard
@antonioperic
CodeSmell!!!(BadCode)
• Overuseofpublicstatic
• Toomanyparameters
• Weirdorderofparameters
• GODObject(hecandoeverythingandheknowseverything)
• Noinputvalidation
• Nocomments
@antonioperic
CodeSmell!!!(BadCode)
• Takes1-2sentencestoexplain
• Copy-pasted-repetitivecode
• Neverusedinheritance,interfaceorcomposition
• notreadable
• nottestable
@antonioperic
CodeSmell!!!(BadCode)
• hardtounderstand
• hardtomaintain
• givesaheadache
• youdon’twon’ttoworkon/withit
@antonioperic
@antonioperic
AvoidbeingSTUPID
Singleton
Tightcoupling
Untestability
Prematureoptimization
Indescriptivenaming
Duplication
@antonioperic
AvoidbeingSTUPID
Singleton
Tightcoupling
Untestability
Prematureoptimization
Indescriptivenaming
Duplication
@antonioperic
@antonioperic
Butwhywestilldoingit…
• Wearelazy
• Shortdeadlines
• Baddecisions
• Fast-good-cheap
• Wearealwaysthebestdeveloperever:)
@antonioperic
Codehasexpirationdate!
@antonioperic
Yesterday!
@antonioperic
Gooddevelopersareshipping!balance shipping vs good code
@antonioperic
Developersareevolving!
@antonioperic
@antonioperic
Languageisevolving
• Frameworks(Symfony<3)
• Packagemanagers(composer)
• Standards
• PHP7
@antonioperic
“Anyfoolcanwritecodethatacomputercanunderstand.Goodprogrammerswritecodethathumanscanunderstand.“
Martin Fowler
@antonioperic
CODE
@antonioperic
@antonioperic
Cleancode
• Codethatdoesn’texist
• KISS
• DRY
• SOLID
• Don’treinventthewheel
• DesignPatterns
• Testable->Tested
@antonioperic
Cleancode
• Flexible
• Maintainable
• Easytorefactor
• Readable
@antonioperic
Cleancodeiseasytounderstand,easytochangeandreusable.
@antonioperic
@antonioperic
Whyweshouldcare…
• Someoneelsewillusethatcode
• Youwillusethatcode
• Badcodedoesalotofthingsbutnonewell
• Youdon’twritecodejusttobethere
• Maintainingshouldbeeasy
• Goodcodesavemoneyandtime
@antonioperic
@antonioperic
Iftechnicaldebtisnotrepaid,itcanaccumulate'interest',makingithardertoimplementchangeslateron.
@antonioperic
@antonioperic
Guidanceforbetter(clean)code
@antonioperic
#1Namingmatters
• Don’tabbreviate
• $string->b=false;
• $string->bold=false;
• Makecodereadable
• Meaningfulnames
• Improvesreadability
• Goodcodeshouldbetalkingtoyou
• Youshouldreaditlikeabook,whitespaceisimportant
@antonioperic
#1Namingmatters
• Twoworldwordsvariablename
• $data,$data2
• $total,$total2,$total3
@antonioperic
#1Namingmatters
@antonioperic
#1Namingmatters
• Don’tbesilly!
@antonioperic
#1Namingmatters
• Goodnameshouldexplain
• whyitexist
• whatitdoes
• howtouseit
• Ifyouneedcommentforexplainit,itisbadname
• Classshoulduseanoun,methodaverb
@antonioperic
#2Codestandard
• Don’tmixstylesinproject,usewhitespace
• Easiertonavigateinsideproject
• Lesstimeforboardingnewdeveloper
• PHP-FIG
• StickwithPSR
• PSR-0autoloading
• PSR-1basingcodestyle
• PSR-2detailedcodingstyle
@antonioperic
#2Codestandard
• SymfonyfollowsthestandardsdefinedinthePSR-0,PSR-1,PSR-2andPSR-4documents.
• http://symfony.com/doc/current/contributing/code/standards.html
@antonioperic
#3Useonlyonelevelofindentationpermethod• {{{}}}trytoavoidthis
• forcesingleresponsibility
• small,simple,easiertounderstand
• ourmindmodelisimportant
• separatelogicblocksandcomplexlevelofindentationintomethods
@antonioperic
#4Don’tuseelse
• reducecodecomplexity
• earlyreturns
• useExceptions
• itreducecomplexofourmindmodel
• methodshouldnotdomorethenonething
• don’tuseintermediatevariable
• usepolymorphism,switchissignalforpolymorphism
• don’tabusepolymorphism
@antonioperic
#4Don’tuseelse
@antonioperic
#5Keepyourclasses/methodssmall• easiertotest
• doonething,anddoonethingwell
• allfunctionsshouldreturnsomethingandavoidreturningNULL
• keepmethodssmall(max.20linesofcode)
• avoidside-effects
• avoidglobalstate
@antonioperic
#6UseExceptions
• Usethem
• Makesuretocatchthem
• Specifythenatureoftheerror
• thrownewInvalidArgumentException();
• Don’tusespecialerrorcodes
@antonioperic
#7Designpatterns
• usethem,theygiveyousolutionforsomewellknownproblems
@antonioperic
#8UseSPL
• TheStandardPHPLibrary(SPL)isacollectionofinterfacesandclassesthataremeanttosolvecommonproblems.
• SPLprovidesasetofstandarddatastructure,asetofiteratorstotraverseoverobjects,asetofinterfaces,asetofstandardExceptions,anumberofclassestoworkwithfilesanditprovidesasetoffunctionslikespl_autoload_register()
@antonioperic
#8UseSPL
• Datastructures
• SplDoublyLinkedList—TheSplDoublyLinkedListclass
• SplStack—TheSplStackclass
• SplQueue—TheSplQueueclass
• SplHeap—TheSplHeapclass
• SplMaxHeap—TheSplMaxHeapclass
• SplMinHeap—TheSplMinHeapclass
• SplPriorityQueue—TheSplPriorityQueueclass
• SplFixedArray—TheSplFixedArrayclass
• SplObjectStorage—TheSplObjectStorageclass
@antonioperic
#8UseSPL
• Iterators
• AppendIterator—TheAppendIteratorclass
• ArrayIterator—TheArrayIteratorclass
• CachingIterator—TheCachingIteratorclass
• CallbackFilterIterator—TheCallbackFilterIteratorclass
• DirectoryIterator—TheDirectoryIteratorclass
• EmptyIterator—TheEmptyIteratorclass
• FilesystemIterator—TheFilesystemIteratorclass
• FilterIterator—TheFilterIteratorclass
• GlobIterator—TheGlobIteratorclass
• InfiniteIterator—TheInfiniteIteratorclass
• …
@antonioperic
#8UseSPL
• Interfaces• Countable—TheCountableinterface
• OuterIterator—TheOuterIteratorinterface• RecursiveIterator—TheRecursiveIteratorinterface
• SeekableIterator—TheSeekableIterator
@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
@antonioperic
#9Lawofdemeter(LoD)
• Eachunitshouldhaveonlylimitedknowledgeaboutotherunits:onlyunits"closely"relatedtothecurrentunit.
• Eachunitshouldonlytalktoitsfriends;don'ttalktostrangers.
• Onlytalktoyourimmediatefriends
• Helpyoubuildcodethatiseasiertotest
@antonioperic
#9Lawofdemeter
@antonioperic
#9LawofDemeter
@antonioperic
#9Lawofdemeter(LoD)
• Benefits:
• Keepobjectinstantionsimple
• Easiertomockobjects
• Simplifydependencygraph
@antonioperic
#10Comments
• Goodcomments
• Badcomments
• PHPDoc
• Don’tusecommentsfortrackinghistoryofchanges
@antonioperic
#11Usetools
• PHPCS
• PHP-CS-Fixer
• pDepend(performsstaticcodeanalysis)
• PHPLOC(AtoolforquicklymeasuringthesizeofaPHPproject)
• SensioLabsInsight
• phpmd(messdetector)
• PHPCPD(copypastedetector)
• PHPDCP(deadcodedetector)
• learnmoreaboutyourIDE(PHPStormisamazingtool)
@antonioperic
#12improveyourself
• readalotofcode
• http://www.livecoding.tv/
• workinpairs• doopensource-youwillgetalotoffreereviews
fromamazingdevelopers
• showyourcodetootherdevelopers
• gotoconferences
• beresponsiveforyourcode
@antonioperic
“Iliveandbreathemycodeandmycodeismostlythefunstuff.Youknowthelogic,thestuffthatmakescoolapplications,right?.“
Misko Havery
@antonioperic
#11Boy-scoutrule
@antonioperic
#12Boyscoutrule
• Alwayscheckamoduleincleanerthanwhenyoucheckeditout.
• Alwaysleavecodeinbettershapethenyoufoundit
@antonioperic
Conclusion
• Cleancodeis:
• structured
• simple
• consistent
• Useboyscoutrule
• Dosmallsteps
• Thereisnosilverbulletonlyhardwork
@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