SlideShare ist ein Scribd-Unternehmen logo
1 von 74
Downloaden Sie, um offline zu lesen
Writing code for people
Alexey Ivanov, Evil Martians
Evil Martians
Evil Martians
Let's talk about
writing
—  Know how to write letters?
—  Know how to write words?
—  Know how to write sentences?
—  Do you write emails, Line messages, or tweets every day?
—  Published articles in magazines or books?
Do you know how to write?
7
Writing code is the
same
—  You open your code from one year ago and can't remember how it works.
—  You spend half of the day adding debug and console.log to functions
to see what they are doing.
—  You tried to read another person's code and can't understand it.
—  ^ Another person probably thought the same about your code too.
Have you been in these situations?
9
Most of programming tutorials and books teach how to write code that can
be understood by the computer and do some stuff with it.
Very few books and tutorials teach how to write code that other people can
read and understand.
This is a common situation
10
You write code once. But you and other people will be reading and modifying
it tens or even hundreds of times after that.
So it's crucial to write code that is readable, reusable, and refactorable.
But it's not a good situation
11
Writing code for
people
As with any other skill, if you will be mindful of what you are writing and spend
enough time training, you will become better at this.
It's a skill that can be learned
14
1.  Writing the code — principles, rules, style guides, and linters.
2.  Reading the code — how to train yourself to become a better writer.
Talk structure
15
Writing the code
1.  Clean code.
2.  Easy to understand code.
3.  Code that shares context.
Writing the code
17
Clean code
—  Select one code style.
—  Automate it.
—  Forget about it.
Clean code
19
There are tons of existing style guides:
—  https://standardjs.com/
—  https://github.com/airbnb/javascript
—  https://google.github.io/styleguide/jsguide.html
—  Standard Prettier settings
Choose any of them. It's not important which one. Don't spend time on that.
Select a code style
CLEAN CODE
20
—  eslint for Javascript or TypeScript.
—  stylelint for CSS.
—  rubocop for Ruby.
—  prettier — tool that can automatically fix style for multiple languages.
Linters usually have excellent documentation about when and why to use
each rule.
Add linters
CLEAN CODE
21
—  eslint-config-airbnb
—  eslint-config-standard
—  stylelint-config-standard
The good thing about using a popular style guide is the fact that it is already
automated.
Add standard config for linters
CLEAN CODE
22
—  Add prettier and linter plugins to your editor.
—  Enable automatic fixing in prettier .
—  Add precommit hook that automatically format/lint your code.
—  Run your checks in CI (CircleCI or TravisCI will do).
Enable automatic linting and fixing
CLEAN CODE
23
Demo
Again, it's not important what style you choose. Toss a coin if you like. You
can always automatically reformat it later.
Forget about it
CLEAN CODE
25
Easy to
understand code
1.  Readability.
2.  Complexity.
3.  Reading flow.
Easy to understand code
27
Bad:
const yyyymmdstr = moment().format("YYYY/MM/DD");
Good:
const currentDate = moment().format("YYYY/MM/DD");
Use meaningful and pronounceable
variable names
READABILITY
28
Bad:
setTimeout(blastOff, 86400000);
Good:
const MILLISECONDS_IN_A_DAY = 86_400_000;
setTimeout(blastOff, MILLISECONDS_IN_A_DAY);
Use searchable names
READABILITY
29
Bad:
function createMenu(title, body, buttonText, cancellable) {
// ...
}
createMenu("Foo", "Bar", "Baz", true);
Function arguments (2 or fewer ideally)
READABILITY
30
Good:
function createMenu({ title, body, buttonText, cancellable })
// ...
}
createMenu({
title: "Foo", body: "Bar",
buttonText: "Baz", cancellable: true
});
Function arguments (2 or fewer ideally)
READABILITY
31
Bad:
function createFile(name, temp) {
if (temp) {
fs.create(`./temp/${name}`);
} else {
fs.create(name);
}
}
Don't use flags as function parameters
READABILITY
32
Good:
function createFile(name) {
fs.create(name);
}
function createTempFile(name) {
createFile(`./temp/${name}`);
}
Don't use flags as function parameters
READABILITY
33
—  Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin
⽇本語
—  https://github.com/ryanmcdermott/clean-code-javascript   ⽇本語 —
examples was from there.
—  https://github.com/ryanmcdermott/3rs-of-software-architecture
—  JS UX: Writing code for Humans by Lea Verou
Further reading
READABILITY
34
One of the sighs of the bad code is complexity:
—  Large functions that do multiple things at once.
—  Too many arguments for the function.
—  Multiple nested IFs or callbacks.
Complexity
35
You can automate detection of such things. For example with Eslint:
—   complexity  — Cyclomatic Complexity
—   max-depth
—   max-statements
—   max-nested-callbacks
Be careful. Following these rules blindly can produce harder to read code.
Automation
COMPLEXITY
36
—  How often do you go back and forth between functions and methods in the
file?
—  How many files do you need to open to understand how something works?
—  Are the files that you are switching between are close to each other or do you
need to go to different nested folders?
Sometimes it is better to break complexity rules to make the reading
flow easier.
Reading flow
37
dropdown/
locale/
en.json
jp.json
index.js
index.test.js
readme.md
styles.css
Place things close to each other
READING FLOW
38
Code that shares
context
Old code:
window.ga("send", {
hitType: "event",
eventCategory: "Videos",
eventAction: "play",
eventLabel: "Fall Campaign",
eventValue: 10
});
Replacing GA with GTM
EXAMPLE
40
New code:
window.dataLayer.push({
category: "Videos",
action: "play",
label: "Fall Campaign",
value: 10
});
Replacing GA with GTM
EXAMPLE
41
Solution:
const event = { /* ... */ }
const eventPlaceholder = {
label: undefined, value: underfined
};
window.dataLayer.push({ ...eventPlaceholder, ...event });
Replacing GA with GTM
EXAMPLE
42
1.  You can't just leave the code" as is" – next developer can delete it while
refactoring, and they spend eight more hours debugging it.
2.  You can't ask other people to review this code without telling them what it is
doing and why.
3.  Other people can't update and maintain this code.
But how do you share this knowledge?
43
/*
GTM sets all event fields as global variables inside itself,
so until we rewrite them, they will have old values. Because
label and value are optional fields, we need to unset them
for the next events explicitly. Relevant docs:
- https://developers.google.com/tag-manager/devguide
- https://support.google.com/tagmanager/answer/6164391?hl=en
*/
Use comments
44
Code can't explain why the program is being written, and the rationale for
choosing this or that method. Code cannot discuss the reasons certain
alternative approaches were taken.
Jeff Raskin
What is context?
“
45
For example:
/* A binary search turned out to be slower than the
Boyer-Moore algorithm for the data sets of interest,
thus we have used the more complex, but faster method
even though this problem does not at first seem
amenable to a string search technique. */
Jeff Raskin
What is context?
46
@media (--sm-scr) {
.input {
font-size: 16px; /* prevents iOS auto-scale on focus */
}
}
CSS example
47
React Source
GIT Source
—  The reader needs a context that can't be expressed using other means.
—  The code exists because of the environment issues. Browser bugs, for
example.
—  The ugly solution is chosen because of speed optimization reasons.
When to comment
50
—  Code Tells You How, Comments Tell You Why by Jeff Artwood
—  The Art of Comments by Sarah Drasner
Links
52
1.  Clean code.
2.  Easy to understand code.
1.  Readability.
2.  Complexity.
3.  Reading flow.
3.  Code that shares context.
Summary of the first part
53
Reading the code
1.  Code reading.
2.  Code reviews.
3.  Pair Programming.
Reading the code
55
Code reading
Douglas Crockford — Goto There and Back Again starting from 27:15
Code reading
57
Crockford's method:
1.  Do it every day.
2.  Discuss approaches, patterns, and possible solutions.
3.  Don't judge. Don't use results as metrics.
Code reading
58
Who should read:
1.  Reading by the author — faster to do, better at describing context, but
fewer chances to find problems.
2.  Reading by the other person — slower, requires more steps, more useful
feedback on writing.
Code reading
59
You can use methodology from usability testings for the additional effect:
—  Think aloud. Make assumptions about what variables and functions will do.
—  Check if these assumptions were correct.
—  See how much time you spend on each block.
—  See how often you switch between files and sections inside the file.
Read more: Thinking Aloud: The #1 Usability Tool
Code reading
60
Read the code from open-source projects that you use together in the same
way:
—  You will have a better understanding of how they work.
—  You will see which approaches to writing code works and which don't.
Code reading
61
—  https://github.com/reduxjs/redux
—  https://github.com/mobxjs/mobx
—  webpack loaders
Some projects to start from
62
Code review
Principles of the clean code apply to commits and PRs as well:
—  Short, <200LOC PRs.
—  Do only one thing.
—  Describe the context.
Code review
64
If you have large PR — split them to the smaller parts:
1.  Refactoring filenames? Create PR.
2.  Changing the React component that is used in multiple places? Create PR.
3.  Making new utility for everyone to use? Create PR.
Split to many small PRs
CODE REVIEW
65
You can (and should) use commit messages and PR description to describe
the task's context:
1.  What was the task?
2.  Why did you choose to solve it in this way and not another?
Describe context
CODE REVIEW
66
Things that should be done before code review:
—  Discuss the PR process and decide who and how fast should review them.
—  Chose style guide and enable linters.
—  Discuss the new APIs before starting writing code for them.
Advance preparation
CODE REVIEW
67
1.  Split large PRs that need to be merged all at once in the separate commits
that only do one thing.
2.  Give each commit a meaningful name.
3.  Before pushing to upstream, make your commit history beautiful: Squash,
rename, and clean up your commits.
Can't split to different PRs?
CODE REVIEW
68
Links:
—  http://ohshitgit.com/
—  https://chris.beams.io/posts/git-commit/
—  https://sethrobertson.github.io/GitBestPractices/
Code review
70
Pair programing
How to use to become a better writer:
—  Discuss the plan and make a basic structure.
—  Split tasks so both sides can program and not only listen.
—  Comment what you are trying to do now.
—  Give real-time feedback and ask questions.
Pair programing
72
Writing:
1.  Clean code.
2.  Easy to understand code.
1.  Readability.
2.  Complexity.
3.  Reading flow.
3.  Code that shares context.
Reading:
1.  Code reading.
2.  Code reviews.
3.  Pair Programming.
Summary of the talk
73
Alexey Ivanov, Evil Martians
Twitter: @iadramelk
Writing code for people
74

Weitere ähnliche Inhalte

Was ist angesagt?

Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best PracticesTheo Jungeblut
 
API workshop: Deep dive into Java
API workshop: Deep dive into JavaAPI workshop: Deep dive into Java
API workshop: Deep dive into JavaTom Johnson
 
Thinking of Documentation as Code [YUIConf 2013]
Thinking of Documentation as Code [YUIConf 2013]Thinking of Documentation as Code [YUIConf 2013]
Thinking of Documentation as Code [YUIConf 2013]evangoer
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summaryJan de Vries
 
DEF CON 23 - Saif el-sherei and etienne stalmans - fuzzing
DEF CON 23 - Saif el-sherei and etienne stalmans - fuzzingDEF CON 23 - Saif el-sherei and etienne stalmans - fuzzing
DEF CON 23 - Saif el-sherei and etienne stalmans - fuzzingFelipe Prado
 
Software Analysis using Natural Language Queries
Software Analysis using Natural Language QueriesSoftware Analysis using Natural Language Queries
Software Analysis using Natural Language QueriesPooja Rani
 
Improving Code Quality In Medical Software Through Code Reviews - Vincit Teat...
Improving Code Quality In Medical Software Through Code Reviews - Vincit Teat...Improving Code Quality In Medical Software Through Code Reviews - Vincit Teat...
Improving Code Quality In Medical Software Through Code Reviews - Vincit Teat...VincitOy
 
GPT-2: Language Models are Unsupervised Multitask Learners
GPT-2: Language Models are Unsupervised Multitask LearnersGPT-2: Language Models are Unsupervised Multitask Learners
GPT-2: Language Models are Unsupervised Multitask LearnersYoung Seok Kim
 
Prefer Code to Comments
Prefer Code to CommentsPrefer Code to Comments
Prefer Code to CommentsKevlin Henney
 
Object Oriented Apologetics
Object Oriented ApologeticsObject Oriented Apologetics
Object Oriented ApologeticsVance Lucas
 
Writing High Quality Code in C#
Writing High Quality Code in C#Writing High Quality Code in C#
Writing High Quality Code in C#Svetlin Nakov
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency InjectionTheo Jungeblut
 
How to write maintainable code - Peter Hilton - Codemotion Amsterdam 2017
How to write maintainable code - Peter Hilton - Codemotion Amsterdam 2017How to write maintainable code - Peter Hilton - Codemotion Amsterdam 2017
How to write maintainable code - Peter Hilton - Codemotion Amsterdam 2017Codemotion
 
API Documentation -- Presentation to East Bay STC Chapter
API Documentation -- Presentation to East Bay STC ChapterAPI Documentation -- Presentation to East Bay STC Chapter
API Documentation -- Presentation to East Bay STC ChapterTom Johnson
 

Was ist angesagt? (19)

Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
 
API workshop: Deep dive into Java
API workshop: Deep dive into JavaAPI workshop: Deep dive into Java
API workshop: Deep dive into Java
 
Thinking of Documentation as Code [YUIConf 2013]
Thinking of Documentation as Code [YUIConf 2013]Thinking of Documentation as Code [YUIConf 2013]
Thinking of Documentation as Code [YUIConf 2013]
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summary
 
DEF CON 23 - Saif el-sherei and etienne stalmans - fuzzing
DEF CON 23 - Saif el-sherei and etienne stalmans - fuzzingDEF CON 23 - Saif el-sherei and etienne stalmans - fuzzing
DEF CON 23 - Saif el-sherei and etienne stalmans - fuzzing
 
RajeshK
RajeshKRajeshK
RajeshK
 
Software Analysis using Natural Language Queries
Software Analysis using Natural Language QueriesSoftware Analysis using Natural Language Queries
Software Analysis using Natural Language Queries
 
Improving Code Quality In Medical Software Through Code Reviews - Vincit Teat...
Improving Code Quality In Medical Software Through Code Reviews - Vincit Teat...Improving Code Quality In Medical Software Through Code Reviews - Vincit Teat...
Improving Code Quality In Medical Software Through Code Reviews - Vincit Teat...
 
GPT-2: Language Models are Unsupervised Multitask Learners
GPT-2: Language Models are Unsupervised Multitask LearnersGPT-2: Language Models are Unsupervised Multitask Learners
GPT-2: Language Models are Unsupervised Multitask Learners
 
code documentation
code documentationcode documentation
code documentation
 
Prefer Code to Comments
Prefer Code to CommentsPrefer Code to Comments
Prefer Code to Comments
 
Object Oriented Apologetics
Object Oriented ApologeticsObject Oriented Apologetics
Object Oriented Apologetics
 
Writing High Quality Code in C#
Writing High Quality Code in C#Writing High Quality Code in C#
Writing High Quality Code in C#
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency Injection
 
Clean code
Clean codeClean code
Clean code
 
How to write maintainable code - Peter Hilton - Codemotion Amsterdam 2017
How to write maintainable code - Peter Hilton - Codemotion Amsterdam 2017How to write maintainable code - Peter Hilton - Codemotion Amsterdam 2017
How to write maintainable code - Peter Hilton - Codemotion Amsterdam 2017
 
Inside Requirements
Inside RequirementsInside Requirements
Inside Requirements
 
Sorted
SortedSorted
Sorted
 
API Documentation -- Presentation to East Bay STC Chapter
API Documentation -- Presentation to East Bay STC ChapterAPI Documentation -- Presentation to East Bay STC Chapter
API Documentation -- Presentation to East Bay STC Chapter
 

Ähnlich wie Writing code for people

Introducing systems analysis, design & development Concepts
Introducing systems analysis, design & development ConceptsIntroducing systems analysis, design & development Concepts
Introducing systems analysis, design & development ConceptsShafiul Azam Chowdhury
 
Introducing Systems Analysis Design Development
Introducing Systems Analysis Design DevelopmentIntroducing Systems Analysis Design Development
Introducing Systems Analysis Design Developmentbsadd
 
Clean code, Feb 2012
Clean code, Feb 2012Clean code, Feb 2012
Clean code, Feb 2012cobyst
 
Introduction to the intermediate Python - v1.1
Introduction to the intermediate Python - v1.1Introduction to the intermediate Python - v1.1
Introduction to the intermediate Python - v1.1Andrei KUCHARAVY
 
Commit Hooks: the Subtle Hammer
Commit Hooks: the Subtle HammerCommit Hooks: the Subtle Hammer
Commit Hooks: the Subtle HammerBen McGraw
 
Half-automatic Compilable Source Code Recovery
Half-automatic Compilable Source Code RecoveryHalf-automatic Compilable Source Code Recovery
Half-automatic Compilable Source Code RecoveryJoxean Koret
 
How to do code review and use analysis tool in software development
How to do code review and use analysis tool in software developmentHow to do code review and use analysis tool in software development
How to do code review and use analysis tool in software developmentMitosis Technology
 
Writing code for others
Writing code for othersWriting code for others
Writing code for othersAmol Pujari
 
WordCamp Nashville: Clean Code for WordPress
WordCamp Nashville: Clean Code for WordPressWordCamp Nashville: Clean Code for WordPress
WordCamp Nashville: Clean Code for WordPressmtoppa
 
Lunch and learn as3_frameworks
Lunch and learn as3_frameworksLunch and learn as3_frameworks
Lunch and learn as3_frameworksYuri Visser
 
Clean Code - Part 2
Clean Code - Part 2Clean Code - Part 2
Clean Code - Part 2Knoldus Inc.
 
Cs121 Unit Test
Cs121 Unit TestCs121 Unit Test
Cs121 Unit TestJill Bell
 
YAGNI Principle and Clean Code
YAGNI Principle and Clean CodeYAGNI Principle and Clean Code
YAGNI Principle and Clean CodeLuan Reffatti
 
Refactoring, 2nd Edition
Refactoring, 2nd EditionRefactoring, 2nd Edition
Refactoring, 2nd Editionjexp
 
Hire a Machine to Code - Michael Arthur Bucko & Aurélien Nicolas
Hire a Machine to Code - Michael Arthur Bucko & Aurélien NicolasHire a Machine to Code - Michael Arthur Bucko & Aurélien Nicolas
Hire a Machine to Code - Michael Arthur Bucko & Aurélien NicolasWithTheBest
 
C++ Restrictions for Game Programming.
C++ Restrictions for Game Programming.C++ Restrictions for Game Programming.
C++ Restrictions for Game Programming.Richard Taylor
 
Code Review
Code ReviewCode Review
Code ReviewRavi Raj
 
An Introduction To Software Development - Implementation
An Introduction To Software Development - ImplementationAn Introduction To Software Development - Implementation
An Introduction To Software Development - ImplementationBlue Elephant Consulting
 
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...Antonio de la Torre Fernández
 

Ähnlich wie Writing code for people (20)

Introducing systems analysis, design & development Concepts
Introducing systems analysis, design & development ConceptsIntroducing systems analysis, design & development Concepts
Introducing systems analysis, design & development Concepts
 
Introducing Systems Analysis Design Development
Introducing Systems Analysis Design DevelopmentIntroducing Systems Analysis Design Development
Introducing Systems Analysis Design Development
 
Clean code, Feb 2012
Clean code, Feb 2012Clean code, Feb 2012
Clean code, Feb 2012
 
Introduction to the intermediate Python - v1.1
Introduction to the intermediate Python - v1.1Introduction to the intermediate Python - v1.1
Introduction to the intermediate Python - v1.1
 
Commit Hooks: the Subtle Hammer
Commit Hooks: the Subtle HammerCommit Hooks: the Subtle Hammer
Commit Hooks: the Subtle Hammer
 
Half-automatic Compilable Source Code Recovery
Half-automatic Compilable Source Code RecoveryHalf-automatic Compilable Source Code Recovery
Half-automatic Compilable Source Code Recovery
 
How to do code review and use analysis tool in software development
How to do code review and use analysis tool in software developmentHow to do code review and use analysis tool in software development
How to do code review and use analysis tool in software development
 
Writing code for others
Writing code for othersWriting code for others
Writing code for others
 
Code quality
Code quality Code quality
Code quality
 
WordCamp Nashville: Clean Code for WordPress
WordCamp Nashville: Clean Code for WordPressWordCamp Nashville: Clean Code for WordPress
WordCamp Nashville: Clean Code for WordPress
 
Lunch and learn as3_frameworks
Lunch and learn as3_frameworksLunch and learn as3_frameworks
Lunch and learn as3_frameworks
 
Clean Code - Part 2
Clean Code - Part 2Clean Code - Part 2
Clean Code - Part 2
 
Cs121 Unit Test
Cs121 Unit TestCs121 Unit Test
Cs121 Unit Test
 
YAGNI Principle and Clean Code
YAGNI Principle and Clean CodeYAGNI Principle and Clean Code
YAGNI Principle and Clean Code
 
Refactoring, 2nd Edition
Refactoring, 2nd EditionRefactoring, 2nd Edition
Refactoring, 2nd Edition
 
Hire a Machine to Code - Michael Arthur Bucko & Aurélien Nicolas
Hire a Machine to Code - Michael Arthur Bucko & Aurélien NicolasHire a Machine to Code - Michael Arthur Bucko & Aurélien Nicolas
Hire a Machine to Code - Michael Arthur Bucko & Aurélien Nicolas
 
C++ Restrictions for Game Programming.
C++ Restrictions for Game Programming.C++ Restrictions for Game Programming.
C++ Restrictions for Game Programming.
 
Code Review
Code ReviewCode Review
Code Review
 
An Introduction To Software Development - Implementation
An Introduction To Software Development - ImplementationAn Introduction To Software Development - Implementation
An Introduction To Software Development - Implementation
 
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
20191116 DevFest 2019 The Legacy Code came to stay (El legacy vino para queda...
 

Mehr von Alexey Ivanov

REST to GraphQL migration: Pros, cons and gotchas
REST to GraphQL migration: Pros, cons and gotchasREST to GraphQL migration: Pros, cons and gotchas
REST to GraphQL migration: Pros, cons and gotchasAlexey Ivanov
 
Внутреннее устройство и оптимизация бандла webpack
Внутреннее устройство и оптимизация бандла webpackВнутреннее устройство и оптимизация бандла webpack
Внутреннее устройство и оптимизация бандла webpackAlexey Ivanov
 
CSS-в-JS, HTML-в-JS, ВСЁ-в-JS. Все гораздо проще, когда всё вокруг JavaScript
CSS-в-JS, HTML-в-JS, ВСЁ-в-JS. Все гораздо проще, когда всё вокруг JavaScriptCSS-в-JS, HTML-в-JS, ВСЁ-в-JS. Все гораздо проще, когда всё вокруг JavaScript
CSS-в-JS, HTML-в-JS, ВСЁ-в-JS. Все гораздо проще, когда всё вокруг JavaScriptAlexey Ivanov
 
Будущее шаблонизаторов
Будущее шаблонизаторовБудущее шаблонизаторов
Будущее шаблонизаторовAlexey Ivanov
 
ДАМП 2015 Екатеринбург
ДАМП 2015 ЕкатеринбургДАМП 2015 Екатеринбург
ДАМП 2015 ЕкатеринбургAlexey Ivanov
 

Mehr von Alexey Ivanov (6)

REST to GraphQL migration: Pros, cons and gotchas
REST to GraphQL migration: Pros, cons and gotchasREST to GraphQL migration: Pros, cons and gotchas
REST to GraphQL migration: Pros, cons and gotchas
 
Внутреннее устройство и оптимизация бандла webpack
Внутреннее устройство и оптимизация бандла webpackВнутреннее устройство и оптимизация бандла webpack
Внутреннее устройство и оптимизация бандла webpack
 
CSS-в-JS, HTML-в-JS, ВСЁ-в-JS. Все гораздо проще, когда всё вокруг JavaScript
CSS-в-JS, HTML-в-JS, ВСЁ-в-JS. Все гораздо проще, когда всё вокруг JavaScriptCSS-в-JS, HTML-в-JS, ВСЁ-в-JS. Все гораздо проще, когда всё вокруг JavaScript
CSS-в-JS, HTML-в-JS, ВСЁ-в-JS. Все гораздо проще, когда всё вокруг JavaScript
 
Будущее шаблонизаторов
Будущее шаблонизаторовБудущее шаблонизаторов
Будущее шаблонизаторов
 
ДАМП 2015 Екатеринбург
ДАМП 2015 ЕкатеринбургДАМП 2015 Екатеринбург
ДАМП 2015 Екатеринбург
 
Gipp
GippGipp
Gipp
 

Kürzlich hochgeladen

%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsBert Jan Schrijver
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 

Kürzlich hochgeladen (20)

%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

Writing code for people

  • 1. Writing code for people Alexey Ivanov, Evil Martians
  • 2.
  • 5.
  • 7. —  Know how to write letters? —  Know how to write words? —  Know how to write sentences? —  Do you write emails, Line messages, or tweets every day? —  Published articles in magazines or books? Do you know how to write? 7
  • 8. Writing code is the same
  • 9. —  You open your code from one year ago and can't remember how it works. —  You spend half of the day adding debug and console.log to functions to see what they are doing. —  You tried to read another person's code and can't understand it. —  ^ Another person probably thought the same about your code too. Have you been in these situations? 9
  • 10. Most of programming tutorials and books teach how to write code that can be understood by the computer and do some stuff with it. Very few books and tutorials teach how to write code that other people can read and understand. This is a common situation 10
  • 11. You write code once. But you and other people will be reading and modifying it tens or even hundreds of times after that. So it's crucial to write code that is readable, reusable, and refactorable. But it's not a good situation 11
  • 12.
  • 14. As with any other skill, if you will be mindful of what you are writing and spend enough time training, you will become better at this. It's a skill that can be learned 14
  • 15. 1.  Writing the code — principles, rules, style guides, and linters. 2.  Reading the code — how to train yourself to become a better writer. Talk structure 15
  • 17. 1.  Clean code. 2.  Easy to understand code. 3.  Code that shares context. Writing the code 17
  • 19. —  Select one code style. —  Automate it. —  Forget about it. Clean code 19
  • 20. There are tons of existing style guides: —  https://standardjs.com/ —  https://github.com/airbnb/javascript —  https://google.github.io/styleguide/jsguide.html —  Standard Prettier settings Choose any of them. It's not important which one. Don't spend time on that. Select a code style CLEAN CODE 20
  • 21. —  eslint for Javascript or TypeScript. —  stylelint for CSS. —  rubocop for Ruby. —  prettier — tool that can automatically fix style for multiple languages. Linters usually have excellent documentation about when and why to use each rule. Add linters CLEAN CODE 21
  • 22. —  eslint-config-airbnb —  eslint-config-standard —  stylelint-config-standard The good thing about using a popular style guide is the fact that it is already automated. Add standard config for linters CLEAN CODE 22
  • 23. —  Add prettier and linter plugins to your editor. —  Enable automatic fixing in prettier . —  Add precommit hook that automatically format/lint your code. —  Run your checks in CI (CircleCI or TravisCI will do). Enable automatic linting and fixing CLEAN CODE 23
  • 24. Demo
  • 25. Again, it's not important what style you choose. Toss a coin if you like. You can always automatically reformat it later. Forget about it CLEAN CODE 25
  • 28. Bad: const yyyymmdstr = moment().format("YYYY/MM/DD"); Good: const currentDate = moment().format("YYYY/MM/DD"); Use meaningful and pronounceable variable names READABILITY 28
  • 29. Bad: setTimeout(blastOff, 86400000); Good: const MILLISECONDS_IN_A_DAY = 86_400_000; setTimeout(blastOff, MILLISECONDS_IN_A_DAY); Use searchable names READABILITY 29
  • 30. Bad: function createMenu(title, body, buttonText, cancellable) { // ... } createMenu("Foo", "Bar", "Baz", true); Function arguments (2 or fewer ideally) READABILITY 30
  • 31. Good: function createMenu({ title, body, buttonText, cancellable }) // ... } createMenu({ title: "Foo", body: "Bar", buttonText: "Baz", cancellable: true }); Function arguments (2 or fewer ideally) READABILITY 31
  • 32. Bad: function createFile(name, temp) { if (temp) { fs.create(`./temp/${name}`); } else { fs.create(name); } } Don't use flags as function parameters READABILITY 32
  • 33. Good: function createFile(name) { fs.create(name); } function createTempFile(name) { createFile(`./temp/${name}`); } Don't use flags as function parameters READABILITY 33
  • 34. —  Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin ⽇本語 —  https://github.com/ryanmcdermott/clean-code-javascript   ⽇本語 — examples was from there. —  https://github.com/ryanmcdermott/3rs-of-software-architecture —  JS UX: Writing code for Humans by Lea Verou Further reading READABILITY 34
  • 35. One of the sighs of the bad code is complexity: —  Large functions that do multiple things at once. —  Too many arguments for the function. —  Multiple nested IFs or callbacks. Complexity 35
  • 36. You can automate detection of such things. For example with Eslint: —   complexity  — Cyclomatic Complexity —   max-depth —   max-statements —   max-nested-callbacks Be careful. Following these rules blindly can produce harder to read code. Automation COMPLEXITY 36
  • 37. —  How often do you go back and forth between functions and methods in the file? —  How many files do you need to open to understand how something works? —  Are the files that you are switching between are close to each other or do you need to go to different nested folders? Sometimes it is better to break complexity rules to make the reading flow easier. Reading flow 37
  • 40. Old code: window.ga("send", { hitType: "event", eventCategory: "Videos", eventAction: "play", eventLabel: "Fall Campaign", eventValue: 10 }); Replacing GA with GTM EXAMPLE 40
  • 41. New code: window.dataLayer.push({ category: "Videos", action: "play", label: "Fall Campaign", value: 10 }); Replacing GA with GTM EXAMPLE 41
  • 42. Solution: const event = { /* ... */ } const eventPlaceholder = { label: undefined, value: underfined }; window.dataLayer.push({ ...eventPlaceholder, ...event }); Replacing GA with GTM EXAMPLE 42
  • 43. 1.  You can't just leave the code" as is" – next developer can delete it while refactoring, and they spend eight more hours debugging it. 2.  You can't ask other people to review this code without telling them what it is doing and why. 3.  Other people can't update and maintain this code. But how do you share this knowledge? 43
  • 44. /* GTM sets all event fields as global variables inside itself, so until we rewrite them, they will have old values. Because label and value are optional fields, we need to unset them for the next events explicitly. Relevant docs: - https://developers.google.com/tag-manager/devguide - https://support.google.com/tagmanager/answer/6164391?hl=en */ Use comments 44
  • 45. Code can't explain why the program is being written, and the rationale for choosing this or that method. Code cannot discuss the reasons certain alternative approaches were taken. Jeff Raskin What is context? “ 45
  • 46. For example: /* A binary search turned out to be slower than the Boyer-Moore algorithm for the data sets of interest, thus we have used the more complex, but faster method even though this problem does not at first seem amenable to a string search technique. */ Jeff Raskin What is context? 46
  • 47. @media (--sm-scr) { .input { font-size: 16px; /* prevents iOS auto-scale on focus */ } } CSS example 47
  • 50. —  The reader needs a context that can't be expressed using other means. —  The code exists because of the environment issues. Browser bugs, for example. —  The ugly solution is chosen because of speed optimization reasons. When to comment 50
  • 51.
  • 52. —  Code Tells You How, Comments Tell You Why by Jeff Artwood —  The Art of Comments by Sarah Drasner Links 52
  • 53. 1.  Clean code. 2.  Easy to understand code. 1.  Readability. 2.  Complexity. 3.  Reading flow. 3.  Code that shares context. Summary of the first part 53
  • 55. 1.  Code reading. 2.  Code reviews. 3.  Pair Programming. Reading the code 55
  • 57. Douglas Crockford — Goto There and Back Again starting from 27:15 Code reading 57
  • 58. Crockford's method: 1.  Do it every day. 2.  Discuss approaches, patterns, and possible solutions. 3.  Don't judge. Don't use results as metrics. Code reading 58
  • 59. Who should read: 1.  Reading by the author — faster to do, better at describing context, but fewer chances to find problems. 2.  Reading by the other person — slower, requires more steps, more useful feedback on writing. Code reading 59
  • 60. You can use methodology from usability testings for the additional effect: —  Think aloud. Make assumptions about what variables and functions will do. —  Check if these assumptions were correct. —  See how much time you spend on each block. —  See how often you switch between files and sections inside the file. Read more: Thinking Aloud: The #1 Usability Tool Code reading 60
  • 61. Read the code from open-source projects that you use together in the same way: —  You will have a better understanding of how they work. —  You will see which approaches to writing code works and which don't. Code reading 61
  • 64. Principles of the clean code apply to commits and PRs as well: —  Short, <200LOC PRs. —  Do only one thing. —  Describe the context. Code review 64
  • 65. If you have large PR — split them to the smaller parts: 1.  Refactoring filenames? Create PR. 2.  Changing the React component that is used in multiple places? Create PR. 3.  Making new utility for everyone to use? Create PR. Split to many small PRs CODE REVIEW 65
  • 66. You can (and should) use commit messages and PR description to describe the task's context: 1.  What was the task? 2.  Why did you choose to solve it in this way and not another? Describe context CODE REVIEW 66
  • 67. Things that should be done before code review: —  Discuss the PR process and decide who and how fast should review them. —  Chose style guide and enable linters. —  Discuss the new APIs before starting writing code for them. Advance preparation CODE REVIEW 67
  • 68. 1.  Split large PRs that need to be merged all at once in the separate commits that only do one thing. 2.  Give each commit a meaningful name. 3.  Before pushing to upstream, make your commit history beautiful: Squash, rename, and clean up your commits. Can't split to different PRs? CODE REVIEW 68
  • 69.
  • 72. How to use to become a better writer: —  Discuss the plan and make a basic structure. —  Split tasks so both sides can program and not only listen. —  Comment what you are trying to do now. —  Give real-time feedback and ask questions. Pair programing 72
  • 73. Writing: 1.  Clean code. 2.  Easy to understand code. 1.  Readability. 2.  Complexity. 3.  Reading flow. 3.  Code that shares context. Reading: 1.  Code reading. 2.  Code reviews. 3.  Pair Programming. Summary of the talk 73
  • 74. Alexey Ivanov, Evil Martians Twitter: @iadramelk Writing code for people 74