Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical...

35
Practical Course: Web Development Good Practice Winter Semester 2016/17 Tobias Seitz Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 1

Transcript of Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical...

Page 1: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

PracticalCourse:WebDevelopment

GoodPracticeWinterSemester2016/17

TobiasSeitz

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 1

Page 2: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Thecontentofthissessionmostlyoriginatesfromthisbook:

Weniger SchlechtProgrammieren

KathrinPassig &JohannesJander

https://www.oreilly.de/buecher/120174/9783897215672-weniger-schlecht-programmieren.html

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 2

Page 3: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 3

“Anyfoolcanwritecodethatacomputercanunderstand.Goodprogrammerswritecodethathumanscanunderstand.”

MartinFowler,“Refactoring”

Page 4: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 4

Conventions&Style

Page 5: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Conventions

• Stickingtocode-conventionshelpsmaintainingagoodatmosphereamongteammembers

• Followtheconventionsof– yourchosenlanguage:Informyourselfaboutcommonlyusedcoding

styleandtrytoadaptit.– yourexistingteam:Seewhattheothersaredoing,thendothesame.

• Languageconventions,e.g.JSstyleguides– AirBnB:https://github.com/airbnb/javascript– Google:http://google.github.io/styleguide/jsguide.html– @felixge NodeJS:https://github.com/felixge/node-style-guide

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 5

Page 6: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Conventions:CodeFormatting

function getDivs() {

}

// versus

function getDivs (){

}

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 6

Page 7: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Conventions:“Enforcement”

• UseaLinter(e.g.ESLint,JSHint)• ConfigureyourIDE/editortoautomatically lintyourcode• Configureshort-cuts toreformatyourcode• ShareLint-stylewithyourteammembers,intherootofyour

repository.

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 7

Page 8: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Example.editorconfig

# EditorConfig helps developers define and maintain consistent# coding styles between different editors and IDEs# editorconfig.org

root = true

[*]

# Change these settings to your own preferenceindent_style = spaceindent_size = 2

# We recommend you to keep these unchangedend_of_line = lfcharset = utf-8trim_trailing_whitespace = trueinsert_final_newline = true

[*.md]trim_trailing_whitespace = false

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 8

Page 9: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Example.jscsrc

{"preset": "google","disallowSpacesInAnonymousFunctionExpression": null,"disallowTrailingWhitespace": null,"disallowMultipleVarDecl": false,"maximumLineLength": false,"excludeFiles": ["node_modules/**"]

}

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 9

Page 10: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Example.jshintrc

{"node": true,"browser": true,"camelcase": true,"curly": true,"eqeqeq": true,"immed": true,"indent": 2,"latedef": true,"noarg": true,"quotmark": "single","undef": true,"unused": true,"newcap": false,"globals": {"wrap": true,"unwrap": true,"app": true,"google": true,"zxcvbn": true,"HeatmapOverlay": true

}}

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 10

Page 11: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

AddingaLintertoaTaskRunner(Gulp)

var gulp = require('gulp');var $ = require('gulp-load-plugins')();

// Lint JavaScriptgulp.task('lint', [], function() {

return gulp.src(['*.js','*.html'

]) .pipe($.if('*.html', $.htmlExtract({strip: true}))).pipe($.jshint()).pipe($.jscs()).pipe($.jscsStylish.combineWithHintResults()).pipe($.jshint.reporter('jshint-stylish'))

});

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 11

Page 12: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Break-Out:Prettifyugly-code.html

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 12

Page 13: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Break-Out:Prettifyugly-code.html

• Openyourfavoritecodeeditor• LookfortheKeyboardshort-cutthatallowsyouto

automagicallyreformatcode• Openthefileugly-code.html fromthecoursematerial

repository(github /gitlab)• Makethecodepretty!

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 13

Page 14: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Naming

DOs• functionnamesshoulddescribe

whatthefunctiondoes,nothowitdoesitvalidatePassword()

• Privatevariablesareusuallyprefixedwithanunderscore_untouchableThing

• Includeunits:delaySeconds

• FunctionnamingstructureverbAdjectiveNounDatatype

DONTs• don’tuseanyother

abbreviationsthannum,post,len,max,min,temp,val.

• don’tbefunnyanduseincomprehensiblenamessuperCat =1

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 14

Page 15: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Language

• German/NativeLanguage:– easiertofindvariablenames– fewertypos– badEnglishcannegativelyinfluencethereadabilityofyourcode

• ..but:DoyourselfandanyoneelseafavoranduseEnglish!– statementsandothersyntaxinEnglishà otherwiseweirdmix– thecommunityinyourcountrymightnotbeasbigasthewhole

world.à askingforhelpiseasierwithcodesnippets.

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 15

Page 16: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 16

Comments&Documentation“Always code as if the guy who ends up maintaining your code is a violent

psychopath who knows where you live.” (origin unclear, probably one of: John Woods / Martin Golding / Rick Osborne)

Page 17: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Comments

• “Mangelhafter,gründlich kommentierter Codeistmangelhaftem unkommentiertem Codeklar vorzuziehen(Passig &Jander)

• “Don’tdocumentbadcode– rewriteit”(Kernigham &Pike)• Whentocomment:

– Ifthere’sunexpectedbehavior– ifyou“temporarily”commentoutcode– ifyoufailedwithasolution:sayinthecommenthowyoufailedand

why– ifyoufoundagoodsolutionthatlooksscary/complicated– ifyouassumethingsmightbreak– ifyoupastecodefromothersources

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 17

Page 18: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

ProblematicComments/Heuristics

• Ifyouneedmorethan3-4sentencestodescribewhatafunctiondoes,thiscouldmeanitdoestoomuch

• Commentsrefertoparameters/variablesthatwererenamed.

• Commentincludesnon-standardabbreviations• Commentshouldactuallybethecommitmessage(orvice

versa)• Commentdoesnotaddressthereadership

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 18

Page 19: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

JSDoc - http://usejsdoc.org/

• SimilartoJavaDoc.Addressesacentral“problem”ofJavaScript:dynamictyping.

• ProperJSDoc allowseditorstodisplaylive-helpwhenyoutrytousethefunction.

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 19

/*** generates a div that displays a movie poster (or placeholder)* a title, type and the year.* @param {String} title of the movie* @param {String} type of the move (movie/series/episode)* @param {Number} year* @param {String} posterURL* @return {jQuery|HTMLElement} with class "movie flexChild card"*/function generateMovieDiv(title, type, year, posterURL) {}

Page 20: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

TODO

• Ifyouneedtopostponeatask,markitwithaTODO• Example// TODO reformat this code

• Usually,codeeditorsallowyoutoscanandfindTODOs,orevenhighlightthem

• Beforeyoucommit:resolveTODOs(notalwayspossible,butatleasttry)

• Important:SticktoTODO/FIXME/CHANGEBACK/XXX/!!!!!!

• Don’t:TODOFixthis.

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 20

Page 21: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

TruckFactor

Howmanyofyourteamwouldhavetoberunoverbyatruck tomaketheprojectstandstill?

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 21

https://commons.wikimedia.org/wiki/File:Kenworth_W900_semi_in_red.jpg

Page 22: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

SolutionstoIncreasetheTruckFactor

• IssueTracker(builtintoGitLab)• Responsibilities:Whoisresponsibleforwhat?• AgileProcess:everybodyatleasthasahigh-level

understandingofwhat’sgoingoninother“departments”• GoodDocumentation• CodeReviews/ExtremeProgramming• Decideupfrontwhoyourreplacementis.

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 22

Page 23: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 23

Debugging

Page 24: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

DebuggingApproaches(Sample)

• Usuallyuseful:– Debuggertopauseprogramduringexecution– Rubber-DuckDebugginghttp://www.developerduck.com/– Otherinspectiontools(HTML,CSS)

• Sometimesuseful:– Console.log Debugging(Printline Debugging)– Stackoverflow-Debugging(nextslides)– Sophisticatedlogging(multiplelevels)– Codereviews/pairprogramming/Thinkaloud

• Afterall:Takeabreak.Getsomesleep.

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 24

Page 25: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

CommonStupidities(we’veallbeenthere)

• ThefilethatIedit,isnotthefileIexecute/view.• Iuseafeaturethatisunsupportedbyolderbrowsers

(http://caniuse.com/)• Iaccidentlyuseavariablenameforalocalvariablethat

collideswithhigher-scopevariable.• Itreatundefined,‘undefined’,nullandfalseasthesamething

(hint:theyarenot)• Off-By-OneErrors.

“Therearetwohardproblemsincomputerscience:cacheinvalidation,namingthings,andoff-by-oneerrors”(LeonBambrick)

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 25

Page 26: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

ChecklistforwhentogetHelp

• Didyoucopypastetheerror-messageintoasearchengine?• DidyouusetheEnglishversionoftheerrormessage?• Didyoulintyourcode?• Didyouenableerrormessagesinyourprogramming

environment?• Didyouchecktheofficialdocumentationforwhatyouare

tryingtoachieve?• Didyoulookonstackoverflow.com?

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 26

?

Page 27: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Stackoverflow Debugging

1. Whatisyourgoal?2. Whathaveyoudone?3. Whathaveyoutried?4. Whatweretheresults?5. Whatdidyouexpect?

Ifyoucanhonestlyanswerthesefivequestionsandhavenotfoundtheanswerduringthisprocess,goandaskthequestiononstackoverflow.

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 27

Page 28: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 28

BadCode

Page 29: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

ABadProgrammer’s7Arguments

1. Nobodyelseisgoingtoseemycode2. Thesoftwareisn‘tgoingtobeusedbyanyoneelsebutme.3. I‘llredoitproperlylater.4. It‘sacomplexproblem.Icanonlysolveitwith8stacked

loops.5. Isimplyremembernottoenterthat.6. I‘mgoingtouncommentthatagain.7. It‘sjustasmallproject.

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 29

Page 30: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

BadCodeHeuristics– Part1

• Filestoobig• Functionbodiestoolong• Highindentationlevel• Controlstatementswithmorethan5checks• MagicNumbers• complexarithmeticwithoutacomment• Globalvariables• Codethatintroducesa„hack“tomakethingswork.

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 30

Page 31: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

BadCodeHeuristics– Part2

• Thirdpartyfunctionsareimplementedagain• Inconsistentcodestyle• Functionswithmorethan5parameters• Codeduplication/Redundancy• Suspiciousfilenames• Readinglabyrinth(insteadoftoptobottom)• Manymethodsandmembervariables• Old,commentedoutcodeblocks• Suspiciouskeyboardsounds.

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 31

Page 32: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

BreakOut:PastBehavior

• Step1:Fromthethingsyouhaveheardabouttoday,whathaveyoudone”wrong”inthepast?

• Step2:Useastyleguideandspotthingsthatyouhavedonewronginthepast.

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 32

Page 33: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Hands-On:RefactorForeignCode

• Clone/Forkthisrepository:https://github.com/MIMUC-MMN/assignments-16-17

• pickoneofthefolders,e.g.04- jquery basicsor06- jquery ajax

• Takealookofthecodeinthereandtryto– understandit– writedownthingsthatyoudon’tunderstand– improveit– documentwhatyouimproved.

• Timeframe:15minutes,discussionafterwards.

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 33

Page 34: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 34

Youdon'tlearntowalkbyfollowingrules.Youlearnbydoing,andbyfallingover.

(RichardBranson)

Page 35: Practical Course: Web Development Good Practice...Ludwig-Maximilians-Universität München Practical Course Web Development WS 16/17 - 07 - 3 “Any fool can write code that a computer

Links‘n’Stuff

• http://jscs.info/overview• http://jshint.com/docs/• http://eslint.org/• http://editorconfig.org/• https://blog.codinghorror.com/new-programming-jargon/• http://www.journaldev.com/240/my-25-favorite-

programming-quotes-that-are-funny-too

Ludwig-Maximilians-UniversitätMünchen PracticalCourseWebDevelopmentWS16/17- 07- 35