Clean Code Principles

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

Which of the following best describes the primary goal of writing clean code?

  • To make code easy to read and understand. (correct)
  • To use the latest programming language features.
  • To optimize code for the fastest execution.
  • To minimize the number of lines of code.

In the context of clean code, what is the significance of using descriptive variable names?

  • They help prevent naming conflicts in large projects.
  • They automatically document the code, reducing the need for comments.
  • They make the code easier to understand by clarifying the purpose of the data. (correct)
  • They allow for faster code execution by the compiler.

Why is it generally recommended to avoid negative conditionals (e.g., !isValid) in if statements?

  • Negative conditionals are not supported in all programming languages.
  • Negative conditionals require more memory to store.
  • Negative conditionals can make code harder to understand and mentally process. (correct)
  • Negative conditionals can lead to slower program execution.

What is the PRIMARY benefit of minimizing code duplication?

<p>It makes the code easier to modify and maintain because changes only need to be made in one place. (C)</p> Signup and view all the answers

Why is it important for functions to have a single, well-defined responsibility?

<p>It increases the reusability and testability of the function. (A)</p> Signup and view all the answers

In the context of clean code, when should comments be used?

<p>Comments should only be used when the code is not self-explanatory. (D)</p> Signup and view all the answers

How does proper error handling contribute to clean code?

<p>It makes the code more resilient and easier to debug by anticipating and gracefully handling errors. (B)</p> Signup and view all the answers

What is the primary purpose of refactoring code?

<p>To improve the internal structure and readability of the code without changing its external behavior. (B)</p> Signup and view all the answers

Which of the following is a characteristic of a "code smell"?

<p>A pattern in the code that indicates a potential deeper problem or design flaw. (C)</p> Signup and view all the answers

According to Fowler's Rule of Three, when should you consider refactoring duplicated code?

<p>After the third time you encounter the need for similar code. (B)</p> Signup and view all the answers

What is "Feature Envy" considered to be, in the context of code smells?

<p>A method in one class excessively using methods or data of another class. (C)</p> Signup and view all the answers

What does the code smell 'Shotgun Surgery' indicate?

<p>A situation where a single change requires small modifications to many different classes. (D)</p> Signup and view all the answers

Which of these approaches is MOST aligned with the principle of keeping methods short and focused?

<p>Breaking down a large method into smaller methods, each with a specific responsibility. (B)</p> Signup and view all the answers

What’s the main reason for using meaningful names for variables, methods, and classes?

<p>To improve code readability by clearly indicating the purpose and function of the code elements. (B)</p> Signup and view all the answers

What is the term 'magic number' in the context of clean code?

<p>A literal numerical value used directly in code without explanation. (B)</p> Signup and view all the answers

How should 'magic numbers' be avoided?

<p>By replacing them with named constants that explain their meaning. (C)</p> Signup and view all the answers

What is the PRIMARY problem with redundant comments?

<p>They can become outdated and inaccurate without being maintained. (A)</p> Signup and view all the answers

What characteristic defines a 'good' comment?

<p>Clarifying the purpose or intent of complex code. (D)</p> Signup and view all the answers

Why is consistent source code formatting important for clean code?

<p>It makes the code easier to read and understand, improving maintainability. (D)</p> Signup and view all the answers

What is one strategy for limiting the use of global variables?

<p>Using encapsulation within classes to control access. (C)</p> Signup and view all the answers

Why is having a small number of parameters in a function considered good practice?

<p>It makes the function easier to understand and less prone to errors. (D)</p> Signup and view all the answers

What is the main issue with output parameters?

<p>They make the function's behavior less predictable and harder to understand. (D)</p> Signup and view all the answers

What does the principle of 'vertical separation' refer to in clean code practices?

<p>The logical arrangement of code, with important items at the top and details further down. (C)</p> Signup and view all the answers

According to the slide on 'suggested order', what is something that it is good practice to put at the top of a class?

<p>Public Constants (C)</p> Signup and view all the answers

According to the slides, what is the first thing to do regarding Exceptions?

<p>Log the exceptions (B)</p> Signup and view all the answers

What is the primary reason for encapsulating code?

<p>Hiding details (B)</p> Signup and view all the answers

How does encapsulation support clean code principles??

<p>By preventing data corruption through restricted access. (A)</p> Signup and view all the answers

What characterizes 'programming defensively'?

<p>Using assertions to check conditions that should always be true, assuming you'll be getting bad 'garbage' data. (D)</p> Signup and view all the answers

What is the suggested way to handle errors gracefully?

<p>By using a fallback mechanism if possible. (C)</p> Signup and view all the answers

Why should exceptions, and not error codes, be used?

<p>Errors codes are not descriptive (A)</p> Signup and view all the answers

When handling exceptions, what does the 'Catch the most specific exception type' principle suggest??

<p>Use the most precise exception class to handle specific error cases effectively. (B)</p> Signup and view all the answers

What is the 'null object pattern'?

<p>A design pattern employing a default object to avoid returning <code>null</code>. (B)</p> Signup and view all the answers

According to the slides, which should you be doing to improve code?

<p>Avoid premature optimization (D)</p> Signup and view all the answers

When should you focus on code performance? What do the slides recommend?

<p>Prove the benefits and the need before putting in the work (B)</p> Signup and view all the answers

When is it best to handle the exception in code?

<p>Handle the exception where it makes the most sense (A)</p> Signup and view all the answers

What will always be the result of choosing better algorithms?

<p>None of these (A)</p> Signup and view all the answers

Why would restructuring data make things better?

<p>For better performance (B)</p> Signup and view all the answers

Flashcards

Clean Code

Code that is easy to read, understand, and modify due to its clarity, simplicity, and organization.

Descriptive Naming

Using names for variables, functions, and classes that clearly indicate their purpose and content.

Explanatory Variables

Applying descriptive variable names to clarify complex logic in conditional statements.

Refactoring

Restructuring existing computer code—changing its internal structure—without changing its external behavior.

Signup and view all the flashcards

Code Smell

An indication in the source code of a program that possibly indicates a deeper problem.

Signup and view all the flashcards

Feature Envy

A method uses more methods of another class than of its own class.

Signup and view all the flashcards

Inappropriate Intimacy

High semantic coupling between two classes. One class uses the internals of another.

Signup and view all the flashcards

Shotgun Surgery

Making one change requires many small changes in many different classes.

Signup and view all the flashcards

Small Functions

The practice of ensuring code functions are short, focused, and perform a single responsibility. Prevents the need to enforce the order of operations.

Signup and view all the flashcards

Avoid Magic Numbers

Replacing "magic numbers" with named constants that have a clear meaning. Increases code readability.

Signup and view all the flashcards

Bad Comments

Comments that are unnecessary, redundant, misleading, or poorly written, which detract from code clarity.

Signup and view all the flashcards

Good Comments

Comments which explain the intent behind the code, provide context, and clarify complex logic.

Signup and view all the flashcards

Consistent Formatting

Adhering to the same style throughout a codebase, including indentation, spacing, and naming conventions.

Signup and view all the flashcards

Limited Global Variables

Restricting the scope of variables to minimize unintended side effects and improve code maintainability.

Signup and view all the flashcards

Small Number of Parameters

Functions should have a small number of parameters for increased readability and maintainability.

Signup and view all the flashcards

Output Parameters

Variables passed into a function that are modified by that function, making the code harder to reason about.

Signup and view all the flashcards

Vertical Separation

Organizing code files so that high-level concepts appear near the top and lower-level details appear further down.

Signup and view all the flashcards

Be Consistent

Applying a consistent coding style throughout a project, ensuring uniformity and readability.

Signup and view all the flashcards

Don't Over-engineer

Avoiding unnecessary complexity by implementing the simplest solution that meets the current requirements.

Signup and view all the flashcards

Encapsulate and Modularize

Hiding internal details and exposing only what is needed through a well-defined interface.

Signup and view all the flashcards

Handle Errors Gracefully

Anticipating and managing errors gracefully to prevent crashes and provide informative feedback.

Signup and view all the flashcards

Exceptions

Problems that occur during the execution of a program which disrupts the normal flow.

Signup and view all the flashcards

Standard Exceptions

Standard exceptions in C++ are organized as a hierarchy.

Signup and view all the flashcards

Propagation

If an exception is not caught in the current scope, it travels up the call stack until a suitable handler is found.

Signup and view all the flashcards

Exceptions, not error codes

Use exceptions, but not error codes. Error codes force the programmer to check for problems at all method calls.

Signup and view all the flashcards

First, write Try Catch

Code for which the first operation is write the try catch block before writing other code.

Signup and view all the flashcards

Catch the most specific exception type

Masking can be a problem, instead catch the specific error type.

Signup and view all the flashcards

Don't return null

Instead of returning null, it is better to return a default object that does nothing. Then the programmer does not have to check for != null.

Signup and view all the flashcards

Avoid returning nullptr

A solution where, instead of returning null, a default object that does nothing is returned. This increases code stability.

Signup and view all the flashcards

Where to handle exceptions.

Handle the exception where it makes the most sense. Often this is in main.

Signup and view all the flashcards

How to Handle Exceptions

When you catch the error, you must first log it, provide useful feedback, and either recover or exit.

Signup and view all the flashcards

Program Defensively

Assume that you will be given garbage in the parameters, and decide what to do.

Signup and view all the flashcards

Choose the best algorithm for the context

You must usually choose the best algorithm depending on the context. Quicksort is O(n log n), while Insertion sort is ON2.

Signup and view all the flashcards

Data Structures Choice

Review the data structures or data choices to maximize the data throughputs.

Signup and view all the flashcards

Study Notes

  • Clean code enhances readability, making it easier to read and understand, allowing one to grasp the code's purpose and logic without extensive explanation
  • Clean code is simple and concise, avoiding unnecessary complexity, achieved through simple, direct solutions
  • Clean code is consistent by using Naming conventions, Indentation, and consistent Function usage
  • Clean code is Well-organized by using Logical groups of functionality making it Easy to navigate and know where to find code

Descriptive Naming

  • Names provide context for data and actions
  • Variable names make what data they hold clear
  • Method names make what they do clear
  • Class names makes clear their abstraction level and what they model
  • Avoid generic names like foo, temp, data, manager, or controller

Conditional Statements

  • Explanatory variables make complex logic clear
  • Avoid negative conditionals

General Code Principles

  • Minimize duplication by using good OOAD principles like SOLID
  • Small functions are focused on a single responsibility and Makes it easier to test and debug
  • Code should be testable and easy to write unit tests (e.g. using TDD)
  • Code should have minimal comments, being self-explanatory, except when it is not
  • Error handling anticipates and handles errors gracefully avoiding cluttering the main logic with lots of try…catch blocks and Error-checking logic

Refactoring

  • Refactoring is restructuring or improving code without changing the external behavior or functionality
  • Refactoring should be done in small, incremental steps to avoid introducing bugs, and requires passing tests
  • Refactoring simplifies the code, improves readability, and prevents "design decay" which are also know as “code smells”
  • Code smells are structures in code that indicate a deeper problem or design flaw that will lead to maintenance problems or future bugs, but are not the same as bugs

Why Refactor?

  • Refactoring reduces coding time by helping to meet deadlines easier, avoid errors and reduce debugging time
  • Refactoring helps find bugs
  • Refactoring builds learning about the application as we code
  • Redoing things during refactoring is fundamental to any creative programming process

Refactoring Workflow

  • Ensure all tests pass
  • Find code that smells
  • Determine simplification
  • Make Simplification
  • Ensure all tests still pass

Before Starting to Refactor

  • Use Collective code ownership, and consistent coding standards
  • Enforce standards using code review and static analysis
  • Use Continuous integration with Automated testing
  • Use rested programmers

Fowler's Rule of Three

  • The first time code is written, just code it
  • The second time code is similar, tolerate the duplication
  • The third time code is similar, refactor to remove duplication

Other Code Smells

  • Feature Envy: A method in a class uses more methods of another class than its own
  • Inappropriate Intimacy: High semantic coupling between two classes
  • Shotgun Surgery: Making a change results in small changes across a lot of the source code

Coding Practices: Methods

  • Keep methods short and focused
  • In functions ensure there are multiple responsibilities
  • Use meaningful names for variables, methods, and classes

Use Meaningful Names

  • Variable names should clearly say what data they hold
  • Method names should clearly say what they do
  • Class names make clear their abstraction level and what they model

Avoid Magic Numbers

  • Do not use hard coded constants
  • Instead use named constants and variables to denote a value and its use

Bad Comments

  • Dead methods
  • Commented out code
  • Obsolete comments
  • Misleading comments
  • Redundant Comments
  • Incorrect grammar
  • Poor spelling
  • Incomplete comments
  • Comments that longer than the code
  • Use comments should be an abstraction level higher than the code

Good Comments

  • Explain why not what
  • Give Context
  • Clarify Complex Logic

Consistent Formatting

  • Apply Consistent Formatting when coding
  • Inconsistent formatting makes code less readable

Global Variables

  • Limit the Use of Global Variables _ Makes code more difficult to understand

Small Number of Parameters

  • The more parameters, the harder to understand how to use and test it.
  • Avoid flag arguments, as they indicate SRP violation
  • 2+ parameters should have a high cohesion

Output paramters

  • Best avoided
  • Makes method use harder to understand

Vertical Separation

  • Think of code like a newspaper
  • Most important items at the top
  • Details further down
  • High-level methods (public) first
  • Low-level details (private) after that
  • Variables declared close to use
  • Implement private methods just after they are first called in public method
  • Blank lines between "concepts"

Suggested Order

  • Instance Variables (Java, C#, etc.)
  • Public Constants
  • Private Constants (Java, C#, etc.)
  • Constructors / Destructors
  • Class methods
  • Public
  • Private
  • Instance Methods
  • Public
  • Private
  • Private Constants (C++)
  • Instance Variable (C++)

Coding Style

  • Choose a coding style and stick with it
  • If something is done a particular way, do similar things the same way

Don't Over-engineer

  • Avoid adding unnecessary complexity or features to code
  • Implement the simplest solution that meets the current requirements
  • YAGNI (You Aren't Gonna Need It): If you don't need it now, don't build it
  • KISS (Keep It Simple, Stupid): Only add abstraction, inheritance and design patterns when needed
  • Refactor Later: If more functionality is needed, refactor
  • Avoid Premature Optimization: Prove it is needed before putting in the work

Encapsulate and Modularize

  • Encapsulate: Hide the details (private), Expose only what is needed (public/protected)
  • Modularize: Divide the program into meaningful units, Each module has a specific responsibility, Use well-defined interfaces

Handle Errors Gracefully

  • Catch Errors, Don't Ignore Them: Failing to do so leads to hard bugs
  • Provide meaningful messages: Don't confuse the user/developers
  • Fail Safely: Either the program recovers (preferred) or shuts down, Avoid data corruption
  • Fallback Mechanism: Switch to an alternative to complete the task

Exceptions

  • Runtime errors
  • Interrupts the normal program flow
  • Standard exception is defined by stdexcept>

Standard Exceptions

  • Includes logic errors such as length or domain errors where as the runtime error can only be detected at RunTime with range or system failures
  • All exceptions take a string argument to supply the appropriate error message
  • Key exception concepts include a thrown function when errors occur, the use of the try...catch statement to handle exceptions gracefully, and lastly, the multiple “catch” blocks for diverse exception types

Catch Block Parameters

  • There catch parameter include exception T exactly catch statement as well as for “T” or other related derived type and class
  • Always handle catches as if that exception must the last resort

Standard Exceptions Propagation

  • If an exception is not caught within the statement its propagated out
  • If the error is never caught then the program exits

Throwing Exceptions

  • Use exceptions to not error codes because it is easier to forget what to check for after a method call
  • Error codes need to be able to descriptive

How to Throw Exceptions

  • Code to pass the test for specific errors that may be unknown

Catching Thrown Exceptions

  • The most specific catch statements are to take a specific exception in type or value
  • “Try” statements must be included in front of statements that are supposed to throw and receive the exception

Handling Exceptions

  • Catch the most specific exception type, and don't mask problems
  • Rethrow if needed, writing a log message and passing through
  • “Final” statements need to always be called after try/catch statements whether exceptions are caught or not
  • Do not return nullptr code to avoid issues
  • Instead use a default do nothing object to show code instead of showing “null object patterns”

Best alternative for no null pointer

  • User can create a more reliable object such as optional interfaces along with optional error messages

Handling Exceptions Where Problems can Occur

  • Create a custom exception to propagate certain areas of the code

Handling Exceptions

  • After an error consider either to: Log the error, provide meaningful feedback, recover, fail gracefully, and clean up.

Additional Considerations

  • Code defensively: Checking Input for garbage code and validating through “Assert Statements”
  • Choose the best algorithms based off size and performance over code lines
  • Implement data structure management through documentation
  • Use only well designed code comments along with well designed documentation

Summary

  • Keep it simple and clear by refactoring consistenly, and testing often

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Clean Coding Principles Quiz
8 questions

Clean Coding Principles Quiz

AstoundingDandelion6783 avatar
AstoundingDandelion6783
Clean Code Principles and Practices
24 questions
Improve Code Readability
10 questions

Improve Code Readability

ManageableWilliamsite1879 avatar
ManageableWilliamsite1879
Use Quizgecko on...
Browser
Browser