Slide 1

Slide 1 text

WRITING CLEAN CODE FOR HUMANS Women Coding The Future - Online, April 2022

Slide 2

Slide 2 text

Gift Egwuenu @LAURAGIFT_ DEVELOPER ADVOCATE, CLOUDFLARE

Slide 3

Slide 3 text

WHY DOES CLEAN CODE MATTER?

Slide 4

Slide 4 text

✅ A good way to keep your code maintainable?

Slide 5

Slide 5 text

✅ Its a good practice when you work with a large team?

Slide 6

Slide 6 text

HOW DO YOU CLASSIFY BAD CODE?

Slide 7

Slide 7 text

Shh... Code Review In Progress!

Slide 8

Slide 8 text

WHAT'S WRONG WITH THIS CODE? // sending get request to Shopify Admin API const x = await Shopify.Utils.loadCurrentSession(req, res); const y = new Shopify.Clients.Rest(x.shop, x.accessToken); const products = await y.get({ path: 'products', });

Slide 9

Slide 9 text

WHAT'S WRONG WITH THIS CODE? // sending get request to Shopify Admin API const x = await Shopify.Utils.loadCurrentSession(req, res); const y = new Shopify.Clients.Rest(x.shop, x.accessToken); const products = await y.get({ path: 'products', });

Slide 10

Slide 10 text

WHAT'S WRONG WITH THIS CODE? // sending get request to Shopify Admin API const x = await Shopify.Utils.loadCurrentSession(req, res); const y = new Shopify.Clients.Rest(x.shop, x.accessToken); const products = await y.get({ path: 'products', });

Slide 11

Slide 11 text

WHAT'S WRONG WITH THIS CODE? // sending get request to Shopify Admin API const x = await Shopify.Utils.loadCurrentSession(req, res); const y = new Shopify.Clients.Rest(x.shop, x.accessToken); const products = await y.get({ path: 'products', });

Slide 12

Slide 12 text

BETTER EXAMPLE // sending get request to Shopify Admin API const session = await Shopify.Utils.loadCurrentSession(req, res); const client = new Shopify.Clients.Rest(session.shop, session.accessToken); const products = await client.get({ path: 'products', });

Slide 13

Slide 13 text

BAD CODE IS CODE THAT IS DIFFICULT TO UNDERSTAND AND CREATES TECHNICAL DEBT.

Slide 14

Slide 14 text

NO ONE UNDERSTANDS IT EXCEPT THE PERSON WHO WROTE IT.

Slide 15

Slide 15 text

What bad code looks like.

Slide 16

Slide 16 text

LATER = NEVER ⭐ Learn more about the LeBlanc's Law.

Slide 17

Slide 17 text

Messy code in a long term causes technical debt!

Slide 18

Slide 18 text

BEST PRACTICES FOR WRITING CLEAN CODE

Slide 19

Slide 19 text

WHAT IS CLEAN CODE?

Slide 20

Slide 20 text

CLEAN CODE IS CODE THAT IS COMPREHENSIVE AND EASY TO UNDERSTAND.

Slide 21

Slide 21 text

Clean code always looks like it was written by someone who cares! -- Michael Feathers

Slide 22

Slide 22 text

USE MEANINGFUL NAMING CONVENTIONS

Slide 23

Slide 23 text

There are only two hard things in Computer Science: cache invalidation and naming things. — Phil Karlton

Slide 24

Slide 24 text

Who else is guilty?

Slide 25

Slide 25 text

USE INTENTIONAL- REVEALING NAMES // ❌ this is a bad example import { Order } from '@shopify/shopify-api/dist/rest-resources/2022-04/index.js'; const x = await Shopify.Utils.loadCurrentSession(request, response); const y = new Order({session: x }); y.id = 450789469; await y.cancel({});

Slide 26

Slide 26 text

USE INTENTIONAL- REVEALING NAMES // ✅ this is a good example import {Order} from '@shopify/shopify-api/dist/rest-resources/2022-04/index.js'; const current_session = await Shopify.Utils.loadCurrentSession(request, response); const order = new Order({session: current_session}); order.id = 450789469; await order.cancel({});

Slide 27

Slide 27 text

USE PRONOUCABLE NAMES // ❌ this is a bad example const yyyy = new Date('August 19, 1975 23:15:30'); const date1 = yyyy.getDate();

Slide 28

Slide 28 text

USE PRONOUCABLE NAMES // ✅ this is a good example const birthday = new Date('August 19, 1975 23:15:30'); const date = birthday.getDate();

Slide 29

Slide 29 text

WRITE CLEAN FUNCTIONS

Slide 30

Slide 30 text

FUNCTIONS SHOULD DO ONE THING. THEY SHOULD DO IT WELL. THEY SHOULD DO IT ONLY.

Slide 31

Slide 31 text

FUNCTION SHOULD DO JUST ONE THING // ❌ this is a bad example function getCustomer(customer) { const customerName = prompt("What is your name?"); console.log(`Hello ${customerName}! How are you?`); const customerAddress = prompt("What is your address?"); console.log(`My address is: ${customerAddress}.`); } return getCustomer();

Slide 32

Slide 32 text

FUNCTION SHOULD DO JUST ONE THING // ❌ this is a bad example function getCustomer(customer) { const customerName = prompt("What is your name?"); console.log(`Hello ${customerName}! How are you?`); const customerAddress = prompt("What is your address?"); console.log(`My address is: ${customerAddress}.`); } return getCustomer();

Slide 33

Slide 33 text

FUNCTION SHOULD DO JUST ONE THING // ✅ this is a good example function getCustomerName(customer) { const customerName = prompt("What is your name?"); console.log(`Hello ${customerName}! How are you?`); } function getCustomerAddress(customer) { const customerAddress = prompt("What is your address?"); console.log(`My address is: ${customerAddress}.`); }

Slide 34

Slide 34 text

GOOD CODE COMMENTS

Slide 35

Slide 35 text

No content

Slide 36

Slide 36 text

❌ BAD COMMENT EXAMPLES

Slide 37

Slide 37 text

NEVER EXPLAIN WHAT THE CODE IS DOING // Load the current session to get the `accessToken`. const session = await Shopify.Utils.loadCurrentSession(req, res); // Create a new client for the specified shop. const client = new Shopify.Clients.Rest(session.shop, session.accessToken); // Use `client.get` to request the specified Shopify REST API endpoint, in this case `products`. const products = await client.get({ path: 'products', });

Slide 38

Slide 38 text

REMOVE COMMENTED CODE const adminApiClient = new Shopify.Clients.Rest( session.shop, session.accessToken, ); // const storefrontTokenResponse = await adminApiClient.post({ // path: 'storefront_access_tokens', // type: DataType.JSON, // data: { // storefront_access_token: { // title: 'This is my test access token', // }, // }, // });

Slide 39

Slide 39 text

AVOID JOURNAL COMMENTS /** * 2022-04-20: Removed call to GraphQL Endpoint, will do that later (GE) * 2022-04-01: Improved Code Quality (JP) */ const storefrontAccessToken: string; const session = await Shopify.Utils.loadCurrentSession(req, res); // StorefrontClient takes in the shop url and the Storefront Access Token for that shop. const client = new Shopify.Clients.Storefront( session.shop, storefrontAccessToken, ); });

Slide 40

Slide 40 text

✅ GOOD COMMENT EXAMPLES

Slide 41

Slide 41 text

LEGAL COMMENTS /* @licstart Copyright (©) 2022 CompanyName Available under the terms of the GNU/LGPL-3.0 See LICENSE file for more informations. @licend */ const storefrontAccessToken: string; const session = await Shopify.Utils.loadCurrentSession(req, res); const client = new Shopify.Clients.Storefront( session.shop, storefrontAccessToken, ); });

Slide 42

Slide 42 text

JSDOC COMMENTS /** * Storefront POST API * @constructor * @param {object} req - The request object * @param {object} res - The response object */ const storefrontAccessToken: string; const session = await Shopify.Utils.loadCurrentSession(req, res); const client = new Shopify.Clients.Storefront( session.shop, storefrontAccessToken, ); });

Slide 43

Slide 43 text

TODO COMMENTS // TODO: Implement request to GraphQL endpoint const storefrontAccessToken: string; const session = await Shopify.Utils.loadCurrentSession(req, res); const client = new Shopify.Clients.Storefront( session.shop, storefrontAccessToken, ); });

Slide 44

Slide 44 text

FORMATTING / STYLE GUIDE

Slide 45

Slide 45 text

JS Standard Style, Airbnb Style Guide etc..

Slide 46

Slide 46 text

FOLLOW CONSISTENT STYLE // ❌ this is a bad example const DAYS_IN_WEEK = 7; const daysInMonth = 30; function getUserData() {} function delete_user_data() {} class user {} class Account {}

Slide 47

Slide 47 text

FOLLOW CONSISTENT STYLE // ✅ this is a good example const DAYS_IN_WEEK = 7; const DAYS_IN_MONTH = 30; function getUserData() {} function deleteUserData() {} class User {} class Account {}

Slide 48

Slide 48 text

FOLLOW CONSISTENT STYLE // ✅ this is a good example const DAYS_IN_WEEK = 7; const DAYS_IN_MONTH = 30; function getUserData() {} function deleteUserData() {} class User {} class Account {}

Slide 49

Slide 49 text

FOLLOW CONSISTENT STYLE // ✅ this is a good example const DAYS_IN_WEEK = 7; const DAYS_IN_MONTH = 30; function getUserData() {} function deleteUserData() {} class User {} class Account {}

Slide 50

Slide 50 text

TESTING

Slide 51

Slide 51 text

LAWS OF TDD

Slide 52

Slide 52 text

LAWS OF TDD ▸ Write production code only to pass a failing unit test.

Slide 53

Slide 53 text

LAWS OF TDD ▸ Write production code only to pass a failing unit test. ▸ Write no more of a unit test than sufficient to fail (compilation failures are failures).

Slide 54

Slide 54 text

LAWS OF TDD ▸ Write production code only to pass a failing unit test. ▸ Write no more of a unit test than sufficient to fail (compilation failures are failures). ▸ Write no more production code than necessary to pass the one failing unit test.

Slide 55

Slide 55 text

Good tests should follow the FIRST principle: F = Fast i = Isolated R = Repeatable S = Self Validating T = Timely

Slide 56

Slide 56 text

The FIRST Principle

Slide 57

Slide 57 text

ERROR HANDLING

Slide 58

Slide 58 text

BAD CODE: ERROR HANDLING WITH TRY, CATCH EXPECTIONS app.post('/webhooks', async (req, res) => { try { await Shopify.Webhooks.Registry.process(req, res); } catch (error) { // ❌ this is not sufficient console.log(error); } });

Slide 59

Slide 59 text

GOOD CODE: ERROR HANDLING WITH TRY, CATCH EXPECTIONS app.post('/webhooks', async (req, res) => { try { await Shopify.Webhooks.Registry.process(req, res); } catch (error) { // ✅ this is better console.log(error); notifyUserOfError(error); reportErrortoService(error); } });

Slide 60

Slide 60 text

CLEAN CODE PRINCIPLES

Slide 61

Slide 61 text

K.I.S.S KEEP IT SIMPLE, STUPID

Slide 62

Slide 62 text

D.R.Y DON'T REPEAT YOURSELF

Slide 63

Slide 63 text

W.E.T ( We enjoy typing!)

Slide 64

Slide 64 text

Y.A.G.N.I YOU AIN'T GONNA NEED IT

Slide 65

Slide 65 text

YAGNI PRINCIPLE

Slide 66

Slide 66 text

BOY'S SCOUT RULE

Slide 67

Slide 67 text

”ALWAYS LEAVE THE CODE CLEANER THAN YOU FOUND IT”

Slide 68

Slide 68 text

HOW YOU CAN TELL YOUR CODE IS CLEAN?

Slide 69

Slide 69 text

HOW YOU CAN TELL YOUR CODE IS CLEAN? ▸ Can someone else read this and understand what I wrote?

Slide 70

Slide 70 text

HOW YOU CAN TELL YOUR CODE IS CLEAN? ▸ Can someone else read this and understand what I wrote? ▸ How easy is it going to be to add new features further down the line?

Slide 71

Slide 71 text

HOW YOU CAN TELL YOUR CODE IS CLEAN? ▸ Can someone else read this and understand what I wrote? ▸ How easy is it going to be to add new features further down the line? ▸ Do you constantly break existing functionality when making changes?

Slide 72

Slide 72 text

RECAP

Slide 73

Slide 73 text

BEST PRACTICES FOR WRITING CLEAN CODE

Slide 74

Slide 74 text

BEST PRACTICES FOR WRITING CLEAN CODE ▸ Use meaningful naming conventions

Slide 75

Slide 75 text

BEST PRACTICES FOR WRITING CLEAN CODE ▸ Use meaningful naming conventions ▸ Write clean functions

Slide 76

Slide 76 text

BEST PRACTICES FOR WRITING CLEAN CODE ▸ Use meaningful naming conventions ▸ Write clean functions ▸ Good code comments

Slide 77

Slide 77 text

BEST PRACTICES FOR WRITING CLEAN CODE ▸ Use meaningful naming conventions ▸ Write clean functions ▸ Good code comments ▸ Format and use a style guide

Slide 78

Slide 78 text

BEST PRACTICES FOR WRITING CLEAN CODE ▸ Use meaningful naming conventions ▸ Write clean functions ▸ Good code comments ▸ Format and use a style guide ▸ Follow TDD principles

Slide 79

Slide 79 text

BEST PRACTICES FOR WRITING CLEAN CODE ▸ Use meaningful naming conventions ▸ Write clean functions ▸ Good code comments ▸ Format and use a style guide ▸ Follow TDD principles ▸ Handle errors correctly

Slide 80

Slide 80 text

CLEAN CODE PRINCIPLES

Slide 81

Slide 81 text

CLEAN CODE PRINCIPLES ▸ K.I.S.S

Slide 82

Slide 82 text

CLEAN CODE PRINCIPLES ▸ K.I.S.S ▸ D.R.Y

Slide 83

Slide 83 text

CLEAN CODE PRINCIPLES ▸ K.I.S.S ▸ D.R.Y ▸ Y.A.G.N.I

Slide 84

Slide 84 text

CLEAN CODE PRINCIPLES ▸ K.I.S.S ▸ D.R.Y ▸ Y.A.G.N.I ▸ Boy's Scout Rule

Slide 85

Slide 85 text

REMEMBER: "ALWAYS LEAVE THE CODE CLEANER THAN YOU FOUND IT"

Slide 86

Slide 86 text

WHAT TO DO NEXT?

Slide 87

Slide 87 text

RESOURCES

Slide 88

Slide 88 text

RESOURCES ▸ Clean Code Book - Robert Martin

Slide 89

Slide 89 text

RESOURCES ▸ Clean Code Book - Robert Martin ▸ Code Complete - Steve McConnell

Slide 90

Slide 90 text

RESOURCES ▸ Clean Code Book - Robert Martin ▸ Code Complete - Steve McConnell ▸ Introduction to Clean Code and Software Design Principles

Slide 91

Slide 91 text

RESOURCES ▸ Clean Code Book - Robert Martin ▸ Code Complete - Steve McConnell ▸ Introduction to Clean Code and Software Design Principles ▸ Writing Clean Code for Humans - Cory House

Slide 92

Slide 92 text

Thank you! @LAURAGIFT_