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

Post on 31-Dec-2020

2 views 1 download

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

PracticalCourse:WebDevelopment

GoodPracticeWinterSemester2016/17

TobiasSeitz

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

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

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

“Anyfoolcanwritecodethatacomputercanunderstand.Goodprogrammerswritecodethathumanscanunderstand.”

MartinFowler,“Refactoring”

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

Conventions&Style

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

Conventions:CodeFormatting

function getDivs() {

}

// versus

function getDivs (){

}

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

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

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

Example.jscsrc

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

}

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

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

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

Break-Out:Prettifyugly-code.html

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

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

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

Language

• German/NativeLanguage:– easiertofindvariablenames– fewertypos– badEnglishcannegativelyinfluencethereadabilityofyourcode

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

world.à askingforhelpiseasierwithcodesnippets.

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

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)

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

ProblematicComments/Heuristics

• Ifyouneedmorethan3-4sentencestodescribewhatafunctiondoes,thiscouldmeanitdoestoomuch

• Commentsrefertoparameters/variablesthatwererenamed.

• Commentincludesnon-standardabbreviations• Commentshouldactuallybethecommitmessage(orvice

versa)• Commentdoesnotaddressthereadership

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

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) {}

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

TruckFactor

Howmanyofyourteamwouldhavetoberunoverbyatruck tomaketheprojectstandstill?

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

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

SolutionstoIncreasetheTruckFactor

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

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

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

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

Debugging

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

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

ChecklistforwhentogetHelp

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

environment?• Didyouchecktheofficialdocumentationforwhatyouare

tryingtoachieve?• Didyoulookonstackoverflow.com?

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

?

Stackoverflow Debugging

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

Ifyoucanhonestlyanswerthesefivequestionsandhavenotfoundtheanswerduringthisprocess,goandaskthequestiononstackoverflow.

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

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

BadCode

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

BadCodeHeuristics– Part1

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

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

BadCodeHeuristics– Part2

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

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

BreakOut:PastBehavior

• Step1:Fromthethingsyouhaveheardabouttoday,whathaveyoudone”wrong”inthepast?

• Step2:Useastyleguideandspotthingsthatyouhavedonewronginthepast.

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

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

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

Youdon'tlearntowalkbyfollowingrules.Youlearnbydoing,andbyfallingover.

(RichardBranson)

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