Class 24 - Clean Code

JavaScript Clean Code

Writing Code for Humans

CSCI 3403 - Web Programming

Day 24

Great code comes from experience. Experience comes from not-so-great code.

Today's Schedule 📅

Clean Code Lecture (40-50 min)

  • What is clean code and why it matters
  • Naming conventions and best practices
  • Code organization and consistency
  • Writing meaningful comments

Rock Paper Scissors Project

Individual work session with instructor support

The Reality of Programming 📖

What do developers actually do?

Writing code: ~20%

Reading code: ~80%

Quick Quiz: Which is Better? 🤔

Example A

const x= function (z){ const w = "Hello "; return w + z } x("John");

Example B

const generateUserGreeting = function (name) { const greeting = "Hello "; return greeting + name; }; generateUserGreeting("John");

Both do the EXACT same thing! 🤯

What Makes Code "Clean"?

Clean code is...

Remember: You're writing for humans, not just computers!

Important Mindset 🧠

⚠️ Don't Stress About Perfection!

Everyone writes messy code sometimes - even professionals!

Our Goal Today:

  • Learn guidelines to improve readability
  • Develop good habits gradually
  • Focus on improvement, not perfection

"Clean code is a journey, not a destination"

Historical Insight 📜

Donald Knuth on Premature Optimization

"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."

— Donald Knuth, 1974

Context:

  • Written in his landmark paper "Structured Programming with go to Statements"
  • One of the most cited principles in software engineering
  • Knuth himself is considered the "father of algorithm analysis"

Why This Matters Today 💡

Readable Code > Clever Code

❌ "Optimized" but Unreadable

// Clever one-liner! const r = a.reduce((p,c)=>p+c,0)/a.length;

Hard to understand, hard to debug, hard to maintain

✅ Clear and Maintainable

// Calculate average of array const sum = array.reduce((total, num) => total + num, 0); const average = sum / array.length;

Easy to understand, easy to debug, easy to maintain

Reflection Question: When have you written "clever" code that you later couldn't understand? How could you have made it clearer?

Naming Variables & Functions 🏷️

A good name is descriptive

❌ Bad

const d = new Date(); const u = users.filter(x => x.a > 18); const calc = (a, b) => a * 0.1 + b;

✅ Good

const currentDate = new Date(); const adultUsers = users.filter(user => user.age > 18); const calculateTotalWithTax = (price, tax) => price * 0.1 + tax;
Rule: If you need a comment to explain a variable name, the name needs improvement!

JavaScript Naming Convention: camelCase 🐫

How camelCase Works:

  • First word: all lowercase
  • Following words: capitalize first letter
  • No spaces or underscores
// Variables (nouns/adjectives) const userName = "Alice"; const isLoggedIn = true; const shoppingCartItems = []; // Functions (verbs) function calculateTotal() { } function getUserProfile() { } function validateEmailAddress() { }

Use Consistent Vocabulary 📚

❌ Inconsistent

function getUserScore() { } function fetchPlayerName() { } function retrievePlayer1Tag() { } // Wait... User? Player? Player1? // Get? Fetch? Retrieve?

✅ Consistent

function getPlayerScore() { } function getPlayerName() { } function getPlayerTag() { } // Same pattern throughout!
Tip: Pick one word for one concept and stick with it!

Historical Insight 📜

The Hungarian Notation Debate

Microsoft's Variable Naming Convention

In the 1980s, Charles Simonyi invented Hungarian notation at Microsoft, where variable names included type information.

// Hungarian Notation Examples var strUserName = "Alice"; // str = string var intAge = 25; // int = integer var bIsActive = true; // b = boolean var arrScores = [95, 87, 92]; // arr = array

Popular in the 1990s-2000s • Used in Windows API development

Why Hungarian Notation Fell Out of Favor 📉

❌ Hungarian Notation (Old Style)

var strFirstName = "Alice"; var strLastName = "Johnson"; var intUserAge = 25; var bIsLoggedIn = true;

Problems: Redundant with modern IDEs, clutters code, maintenance burden

✅ Semantic Naming (Modern Style)

const firstName = "Alice"; const lastName = "Johnson"; const userAge = 25; const isLoggedIn = true;

Benefits: Cleaner, focuses on meaning not type, easier to read

Why the change? As IDEs improved (hover to see type) and languages became more strongly typed, encoding type information in names became unnecessary.

Reflection Question: How does your IDE help you understand variable types without needing prefixes?

Variables vs Functions Naming 📝

Variables = Things (Nouns/Adjectives)

const numberOfItems = 10; const userName = "Thor"; const isSelected = true; const shoppingCart = [];

Functions = Actions (Verbs)

function calculateTotal() { } function validateInput() { } function sendEmail() { } function updateScore() { }

Avoid "Magic Numbers" 🎩

What does 3600000 mean?

❌ Unclear

setTimeout(stopTimer, 3600000); if (score > 75) { showBadge(); }

✅ Clear

const ONE_HOUR = 60 * 60 * 1000; setTimeout(stopTimer, ONE_HOUR); const PASSING_SCORE = 75; if (score > PASSING_SCORE) { showBadge(); }
Convention: Use ALL_CAPS for true constants that never change

Indentation & Line Length 📏

Consistency is KEY!

Pick ONE and stick with it:

  • 2 spaces OR 4 spaces OR tabs
  • Same bracket style throughout
  • ~80 characters per line maximum
// Breaking long lines let reallyLongLine = something + somethingElse + anotherThing + howManyTacos + oneMoreThing; // Consistent indentation if (condition) { doSomething(); if (anotherCondition) { doSomethingElse(); } }

The Semicolon Debate ;

To use or not to use?

JavaScript can automatically insert semicolons...

BUT this can cause bugs!

// Recommended: Use semicolons const name = "Alice"; const age = 25; console.log(name); // Can work without, but risky const name = "Alice" const age = 25 console.log(name)
Our recommendation: Use semicolons consistently to avoid surprises

Bad Comments 💬❌

What NOT to do

1. Don't use comments for version control

/** * 2023-01-10: Fixed bug (RM) * 2023-03-05: Simplified code (JP) * 2023-05-15: Removed old function (LI) */ // That's what Git is for!

2. Don't leave commented-out code

theFunctionInUse(); // oldFunction(); // evenOlderFunction(); // whyAmIEvenHere();

Good Comments: Tell WHY, Not HOW 💡

❌ Redundant

// Increment counter by 1 counter++; // Check if user age is over 18 if (user.age > 18) { // Set adult to true adult = true; }

✅ Helpful

// Track failed login attempts for security counter++; // Legal requirement in some regions if (user.age > 18) { adult = true; }

When Comments Are Valuable 💎

Good Example:

function calculateBMI(height, weight) { // BMI formula: weight(kg) / height(m)² // We receive height in cm, so convert first const heightInMeters = height / 100; const bmi = weight / (heightInMeters * heightInMeters); return bmi; }

Comments are great for:

  • Explaining complex algorithms
  • Clarifying business logic
  • Warning about edge cases
  • Documenting WHY decisions were made

Self-Documenting Code 📖

Let the code speak for itself!

Needs Comments

// Extract text between brackets function extract(s) { // Find [ and get position after it // Find ] and get text between return s.substring(s.indexOf("[") + 1, s.indexOf("]")); }

Self-Explanatory

function extractTextWithinBrackets(text) { const bracketStart = text.indexOf("[") + 1; const bracketEnd = text.indexOf("]"); return text.substring(bracketStart, bracketEnd); }

Project Time! ✂️📄🪨

Rock Paper Scissors

Today's Focus: Console-Based Game

Build the game logic entirely in JavaScript

Play through the browser console

Key Requirements:

  • Random computer choice
  • Get human choice (prompt)
  • Play 5 rounds
  • Track scores
  • Declare final winner

Apply Clean Code to Rock Paper Scissors

Good Function Names:

// Clear, descriptive names function getComputerChoice() { } function getHumanChoice() { } function playRound(humanChoice, computerChoice) { } function playGame() { }

Good Variable Names:

let humanScore = 0; let computerScore = 0; const choices = ["rock", "paper", "scissors"];
Remember: Write code as if the person maintaining it is a violent psychopath who knows where you live! 😅

Recommended Project Workflow 🔄

Step 1: Plan

Pseudocode your solution first

Step 2: Write

Code one function at a time

Step 3: Test

Use console.log() to verify each step

Step 4: Commit

Make meaningful commits often!

Important: NO GUI yet - that comes in a later lesson!

Common Pitfalls to Avoid ⚠️

In Your Code:

  • ❌ Single-letter variable names (except in loops)
  • ❌ Inconsistent indentation
  • ❌ No spacing between code blocks
  • ❌ Massive functions that do everything
  • ❌ Copy-pasting without understanding

Quick Fixes:

  • ✅ Use descriptive names
  • ✅ Keep functions small and focused
  • ✅ Test frequently
  • ✅ Ask "Would I understand this in 2 weeks?"

Historical Insight 📜

The Zen of Python

19 Aphorisms for Writing Great Code

In 1999, Tim Peters wrote PEP 20 - The Zen of Python, a collection of guiding principles for Python developers.

Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Readability counts.

Fun fact: You can see all 19 principles in Python by typing import this

Universal Principles of Clean Code 🌍

Not Just for Python!

The Zen of Python Applies to ALL Languages:

Python

# Simple is better average = sum(numbers) / len(numbers)

JavaScript

// Simple is better const average = numbers.reduce((a,b) => a+b) / numbers.length;

Key Takeaways for Your Code:

  • 📖 Readability counts - Others will read your code
  • Simple is better - Don't overcomplicate solutions
  • 🎯 Explicit is better - Make your intentions clear
Reflection Question: Which of the Zen principles resonates most with you? How can you apply it to your Rock Paper Scissors project?

Clean Code Summary 📋

Remember These Principles:

  • 📖 Code is read more than it's written
  • 🏷️ Names should be self-explanatory
  • 📏 Consistency > Personal preference
  • 💬 Comments explain WHY, not WHAT
  • 🔄 Refactor as you learn

"Any fool can write code that a computer can understand.
Good programmers write code that humans can understand."
- Martin Fowler

Work Session Time! 💻

Rock Paper Scissors Project

Your Tasks:

  1. Set up project structure
  2. Create getComputerChoice()
  3. Create getHumanChoice()
  4. Build playRound() function
  5. Implement playGame() for 5 rounds
  6. Test thoroughly!
I'll be walking around to help! Raise your hand if you get stuck.

Let's Build Clean Code! 🚀

Remember:

Perfect is the enemy of good

Focus on gradual improvement

Clean code is a skill that develops over time

Start your Rock Paper Scissors project!

Apply the clean code principles we learned today

Goal: Working game in the console by end of class