Podcast
Questions and Answers
Which of the following best describes the primary goal of writing clean code?
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?
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?
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?
What is the PRIMARY benefit of minimizing code duplication?
Why is it important for functions to have a single, well-defined responsibility?
Why is it important for functions to have a single, well-defined responsibility?
In the context of clean code, when should comments be used?
In the context of clean code, when should comments be used?
How does proper error handling contribute to clean code?
How does proper error handling contribute to clean code?
What is the primary purpose of refactoring code?
What is the primary purpose of refactoring code?
Which of the following is a characteristic of a "code smell"?
Which of the following is a characteristic of a "code smell"?
According to Fowler's Rule of Three, when should you consider refactoring duplicated code?
According to Fowler's Rule of Three, when should you consider refactoring duplicated code?
What is "Feature Envy" considered to be, in the context of code smells?
What is "Feature Envy" considered to be, in the context of code smells?
What does the code smell 'Shotgun Surgery' indicate?
What does the code smell 'Shotgun Surgery' indicate?
Which of these approaches is MOST aligned with the principle of keeping methods short and focused?
Which of these approaches is MOST aligned with the principle of keeping methods short and focused?
What’s the main reason for using meaningful names for variables, methods, and classes?
What’s the main reason for using meaningful names for variables, methods, and classes?
What is the term 'magic number' in the context of clean code?
What is the term 'magic number' in the context of clean code?
How should 'magic numbers' be avoided?
How should 'magic numbers' be avoided?
What is the PRIMARY problem with redundant comments?
What is the PRIMARY problem with redundant comments?
What characteristic defines a 'good' comment?
What characteristic defines a 'good' comment?
Why is consistent source code formatting important for clean code?
Why is consistent source code formatting important for clean code?
What is one strategy for limiting the use of global variables?
What is one strategy for limiting the use of global variables?
Why is having a small number of parameters in a function considered good practice?
Why is having a small number of parameters in a function considered good practice?
What is the main issue with output parameters?
What is the main issue with output parameters?
What does the principle of 'vertical separation' refer to in clean code practices?
What does the principle of 'vertical separation' refer to in clean code practices?
According to the slide on 'suggested order', what is something that it is good practice to put at the top of a class?
According to the slide on 'suggested order', what is something that it is good practice to put at the top of a class?
According to the slides, what is the first thing to do regarding Exceptions?
According to the slides, what is the first thing to do regarding Exceptions?
What is the primary reason for encapsulating code?
What is the primary reason for encapsulating code?
How does encapsulation support clean code principles??
How does encapsulation support clean code principles??
What characterizes 'programming defensively'?
What characterizes 'programming defensively'?
What is the suggested way to handle errors gracefully?
What is the suggested way to handle errors gracefully?
Why should exceptions, and not error codes, be used?
Why should exceptions, and not error codes, be used?
When handling exceptions, what does the 'Catch the most specific exception type' principle suggest??
When handling exceptions, what does the 'Catch the most specific exception type' principle suggest??
What is the 'null object pattern'?
What is the 'null object pattern'?
According to the slides, which should you be doing to improve code?
According to the slides, which should you be doing to improve code?
When should you focus on code performance? What do the slides recommend?
When should you focus on code performance? What do the slides recommend?
When is it best to handle the exception in code?
When is it best to handle the exception in code?
What will always be the result of choosing better algorithms?
What will always be the result of choosing better algorithms?
Why would restructuring data make things better?
Why would restructuring data make things better?
Flashcards
Clean Code
Clean Code
Code that is easy to read, understand, and modify due to its clarity, simplicity, and organization.
Descriptive Naming
Descriptive Naming
Using names for variables, functions, and classes that clearly indicate their purpose and content.
Explanatory Variables
Explanatory Variables
Applying descriptive variable names to clarify complex logic in conditional statements.
Refactoring
Refactoring
Signup and view all the flashcards
Code Smell
Code Smell
Signup and view all the flashcards
Feature Envy
Feature Envy
Signup and view all the flashcards
Inappropriate Intimacy
Inappropriate Intimacy
Signup and view all the flashcards
Shotgun Surgery
Shotgun Surgery
Signup and view all the flashcards
Small Functions
Small Functions
Signup and view all the flashcards
Avoid Magic Numbers
Avoid Magic Numbers
Signup and view all the flashcards
Bad Comments
Bad Comments
Signup and view all the flashcards
Good Comments
Good Comments
Signup and view all the flashcards
Consistent Formatting
Consistent Formatting
Signup and view all the flashcards
Limited Global Variables
Limited Global Variables
Signup and view all the flashcards
Small Number of Parameters
Small Number of Parameters
Signup and view all the flashcards
Output Parameters
Output Parameters
Signup and view all the flashcards
Vertical Separation
Vertical Separation
Signup and view all the flashcards
Be Consistent
Be Consistent
Signup and view all the flashcards
Don't Over-engineer
Don't Over-engineer
Signup and view all the flashcards
Encapsulate and Modularize
Encapsulate and Modularize
Signup and view all the flashcards
Handle Errors Gracefully
Handle Errors Gracefully
Signup and view all the flashcards
Exceptions
Exceptions
Signup and view all the flashcards
Standard Exceptions
Standard Exceptions
Signup and view all the flashcards
Propagation
Propagation
Signup and view all the flashcards
Exceptions, not error codes
Exceptions, not error codes
Signup and view all the flashcards
First, write Try Catch
First, write Try Catch
Signup and view all the flashcards
Catch the most specific exception type
Catch the most specific exception type
Signup and view all the flashcards
Don't return null
Don't return null
Signup and view all the flashcards
Avoid returning nullptr
Avoid returning nullptr
Signup and view all the flashcards
Where to handle exceptions.
Where to handle exceptions.
Signup and view all the flashcards
How to Handle Exceptions
How to Handle Exceptions
Signup and view all the flashcards
Program Defensively
Program Defensively
Signup and view all the flashcards
Choose the best algorithm for the context
Choose the best algorithm for the context
Signup and view all the flashcards
Data Structures Choice
Data Structures Choice
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.