Summary

This document discusses clean code principles, including naming conventions, function design, and exception handling. It also touches on topics like garbage collection and version control, providing examples of good and bad coding practices.

Full Transcript

CLASS#9 Clean code principals + JIRA REFACTOR? - What does it mean to refactor? - Why do we need to refactor/clean up? - How to write a clean code? WHAT IS CLEAN CODE? Elegant & efficient - It does one thing well Care - It looks like it was written by someone who cared (about the reader!)...

CLASS#9 Clean code principals + JIRA REFACTOR? - What does it mean to refactor? - Why do we need to refactor/clean up? - How to write a clean code? WHAT IS CLEAN CODE? Elegant & efficient - It does one thing well Care - It looks like it was written by someone who cared (about the reader!) Expected – you get what you expect when you read it. It is more important that your peers can get your code to work, than to make the computer get your code to work! CLEAN FUNCTIONS  Write small functions – a function should do 1 thing (i.e you can’t extract another function from it)  Limit function arguments to zero to three; use objects to pass cohesive data instead of long comma-separated lists.  Avoid switch statements and if-else statements with boolean arguments; separate code into two functions for true and false cases BAD EXAMPLE - FUNCTIONS GOOD EXAMPLE BAD EXAMPLE BAD EXAMPLE – FUNCTION PARAMS Takes six parameters, which makes it hard to use, test, and maintain. The caller needs to know too much about the order creation process. GOOD EXAMPLE Refactoring function params to be a class BAD EXAMPLE BAD EXAMPLE – NESTED IFS Issues in the Code: 1.Nested Complexity: The logic is difficult to read and maintain. 2.Single Responsibility Violation: The method is responsible for both input validation and discount calculation. 3.Hard to Extend: Adding a new customer type requires modifying existing logic. GOOD EXAMPLE EXCEPTION HANDLING BAD EXAMPLE – EXCEPTION HANDLING Throws a generic Exception for all types of errors, making it hard to identify the root cause. The error messages are unclear and not specific to the problem. The catch block only logs the issue without appropriate handling. NAMING CONVENTIONS Descriptive and Meaningful: Names should clearly Consistent Case: Follow language conventions: indicate their purpose. CamelCase for variables and methods (e.g., Example: numberOfStudents instead of n. calculateTotal). Avoid Abbreviations: Use full words to improve PascalCase for classes (e.g., PaymentProcessor). clarity. UPPERCASE_WITH_UNDERSCORES for Example: calculatedAmount instead of calcAmt. constants (e.g., MAX_BUFFER_SIZE). Boolean Names: Start with verbs like is, has, can. Example: isActive, hasPermission. NAMING CONVENTIONS Reflect Scope: Use shorter names for small scopes; Positive Logic: Avoid negative logic in variable names. descriptive names for larger scopes. Example: isReady instead of isNotReady. Example: msg for a local variable; errorMessage for a broader scope. Include Units: Specify units in variable names when relevant. Consistent Terminology: Use the same term for the same concept. Example: timeoutInSeconds instead of timeout. Example: Always use user instead of alternating with Plural for Collections: Use plural names for arrays and client or customer. lists. Example: students instead of student. NAMING CONVENTIONS Short and Clear: Keep names concise but Avoid Generic Names: Avoid vague terms meaningful. like doSomething or temp. Example: getStudentCount instead of Example: customerFullName instead of getTheNumberOfRegisteredStudents. temp. Meaningful Exception Names: Exception Domain-Specific: Use names relevant to names should indicate the issue. the application context. Example: InvalidUserInputException Example: calculateDiscount in an e- instead of CustomException. commerce domain. NAMING CONVENTIONS Action-Oriented Functions: Use No Magic Numbers: Use named verbs for function names. constants. Example: processData instead of Example: if (age > dataProcessing. LEGAL_ADULT_AGE). Nouns for Classes: Class names Avoid Noise Words: Skip should represent objects or entities. unnecessary terms like data or variable. Example: PaymentProcessor instead of ProcessPayment. Example: customer instead of customerDataObject. GARBAGE COLLECTION Bad Example: String concatenation creates multiple intermediate objects, wasting memory. Clean Example: Use StringBuilder to optimize memory usage. GARBAGE COLLECTION Bad Example: Allocating a large initial capacity unnecessarily Allocates just Clean Example: enough memory CLEAN CODE PRINCIPALS General Principles Readability First: Write code that is easy to read and understand, even for someone new to the project. Keep It Simple (KISS): Avoid over-complicating the design; solve the problem with the simplest solution. Don't Repeat Yourself (DRY): Eliminate duplicate code by reusing functions, methods, or modules. Single Responsibility Principle (SRP): Each class, method, or function should have one and only one responsibility. Open-Closed Principle (OCP): Code should be open for extension but closed for modification. Separation of Concerns: Divide the code into distinct sections, each addressing a specific concern. Minimize Dependencies: Keep modules loosely coupled and avoid unnecessary dependencies. CLEAN CODE PRINCIPALS Functions and Methods Functions should do one thing and one thing only. Keep functions small (ideally 5–20 lines). Limit the number of function parameters (prefer 3 or fewer). Avoid side effects (a function should not change the state of something unexpected). Return early to avoid deep nesting. CLEAN CODE PRINCIPALS Error Handling Handle errors gracefully using exceptions or validation. Avoid swallowing exceptions without meaningful handling or logging. Prefer specific exceptions over generic ones. CLEAN CODE PRINCIPALS Memory Management Avoid unnecessary object creation; reuse existing ones where possible. Close resources (e.g., streams, sockets) properly using try-with-resources or explicit cleanup. Use weak references or caching mechanisms when appropriate to prevent memory leaks. Version Control Commit code frequently with meaningful commit messages. Follow branching strategies that suit your team (e.g., Gitflow, trunk-based development). CLEAN CODE PRINCIPALS Comments Use comments to explain why the code exists, not what it does (the code should explain itself). Avoid redundant comments; refactor code if comments are required to clarify logic. Use TODO comments sparingly and ensure they are actionable. Don’t comment code! Just delete it, you can get it back from version control. CLEAN CODE CHECKLIST 1. Are names clear and meaningful? 2. Do methods perform only one task? 3. Is code free of duplication? 4. Are error-handling mechanisms implemented? 5. Is formatting consistent? 6. Are comments helpful and concise? 7. Are there tests for critical parts of the code? JIRA HANDS ON CREATE EPICS CREATE NEW BACKLOG ITEM BACKLOG SIZED & PRIORITIZED CREATE SPRINT BACKLOG START SPRINT WITH SPRINT GOALS MODIFY WORKFLOW DASHBOARDS JQL (JIRA QUERY LANGUAGE) Using JIRA’s filters to retrieve issues and set filters

Use Quizgecko on...
Browser
Browser