Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Clean Code with C#
Clean Code with C#

Clean Code with C# : Refactor your legacy C# code base and improve application performance using best practices , Second Edition

eBook
₹799 ₹2978.99
Paperback
₹3723.99
Subscription
Free Trial
Renews at ₹800p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Clean Code with C#

Code Review – Process and Importance

The primary motivation behind any code review is to improve the overall quality of the code. Code quality is very important. This almost goes without saying, especially if your code is part of a team project or is accessible to others, such as open-source developers and customers through escrow agreements.

If every developer were free to code as they pleased, you would end up with the same kind of code written in so many ways, and ultimately, the code would become an unwieldy mess. That is why it is important to have a coding standards policy that outlines the company’s coding practices and code review procedures that are to be followed.

When code reviews are carried out, colleagues will review the code of other colleagues. Colleagues will understand that it is only human to make mistakes. They will check the code for mistakes, such as code that breaks the company’s code of coding conduct, and any code that, while syntactically correct, can be improved upon to make it more readable, more maintainable, or more performant.

Therefore, in this chapter, we will cover the following topics to understand the code review process in detail:

  • A brief introduction to GitHub
  • The code review process
  • Preparing code for review
  • Leading a code review
  • Knowing what to review
  • Knowing when to send for code review
  • Providing and responding to review feedback

Note

For the Preparing code for review and Knowing when to send code for review sections, we will be talking from the point of view of the programmer. For the Leading a code review and Knowing what to review sections, we will be talking from the point of view of the code reviewer. However, concerning the Providing and responding to review feedback section, we will cover the viewpoints of both the programmer and the code reviewer.

The learning objectives for this chapter are for you to be able to do the following:

  • Understand GitHub and its potential use in the code review process
  • Understand code reviews and why they are good
  • Partake in code reviews
  • Provide constructive criticism
  • Respond positively to constructive criticism

Before we dive deep into these topics, let’s understand the general code review process.

A brief introduction to GitHub

This section covers a brief introduction to programmers and developers who are new to GitHub and never used it since this chapter focuses on the use of GitHub for performing code reviews.

GitHub is a powerful platform that revolutionizes the way developers collaborate on projects. Whether you’re a seasoned programmer or just starting your coding journey, GitHub provides a centralized hub for version control, collaboration, and code sharing. This introduction aims to guide beginners through the fundamentals of GitHub and provide resources to help you embark on your journey to becoming a proficient GitHub user.

What is GitHub?

GitHub is a web-based platform built around Git, a distributed version control system. In simpler terms, it helps you manage and track changes to your code. GitHub extends Git’s functionality by providing a user-friendly interface and collaborative features, making it an essential tool for individual developers and large-scale teams alike.

Here are its key concepts:

  • Repositories: These are containers for your project. A repository, or “repo,” holds all the files, history, and documentation related to your project.
  • Commits: Each change you make to your project is captured in a commit. Commits help you track the progress of your project and can be accompanied by messages to describe the changes.
  • Branches: Branches allow you to work on different versions of your project simultaneously. You can experiment with new features or fix bugs without affecting the main project until you’re ready to merge your changes.
  • Pull Requests: When you’ve made changes in a branch and are ready to merge them into the main project, you create a pull request. This allows others to review your changes before they are incorporated.

GitHub’s use within the code review process

GitHub plays a crucial role in the code review process, facilitating collaboration and maintaining code quality within a development team. Here’s an overview of how GitHub is used in the code review process:

  1. Pull requests (PRs):
    • Developers typically create a branch for a new feature or bug fix. Once the changes have been implemented, they initiate a pull request.
    • A pull request is a proposal to merge the changes from one branch into another (often from a feature branch into the main branch).
    • PRs encapsulate the changes made, providing an overview of the additions, modifications, and deletions.
  2. Reviewers:
    • In a collaborative environment, code reviews involve one or more reviewers who examine the changes proposed in a pull request.
    • Reviewers may include peers, team leads, or anyone with expertise in the code base. Their role is to ensure code quality, adherence to coding standards, and the correctness of the implementation.
  3. Discussion and feedback:
    • GitHub’s interface allows reviewers to comment on specific lines of code. This feature facilitates detailed discussions about the proposed changes.
    • Reviewers can suggest improvements, request clarifications, or point out potential issues directly within the context of the code.
  4. Continuous integration (CI):
    • Many development teams integrate CI tools (such as Jenkins, Travis CI, or GitHub Actions) with GitHub.
    • CI automatically builds and tests code changes whenever a pull request is opened or updated. This ensures that proposed changes don’t break existing functionality and helps maintain a stable code base.
  5. Status checks:
    • GitHub allows integration with various status checks, including automated tests, code style checks, and other custom checks defined by the development team.
    • Pull requests can only be merged if all defined status checks pass. This ensures that the proposed changes meet the project’s quality standards.
  6. Iterative improvements:
    • Code reviews often involve multiple iterations. Developers can make additional commits to the same branch in response to feedback and then update the pull request.
    • The iterative process continues until the changes are approved and meet the team’s standards.
  7. Merge and deployment:
    • Once the code review process is complete, and the changes are approved, the pull request can be merged into the target branch (for example, main or master)
    • Merging triggers further actions, such as deployment to staging or production environments, depending on the team’s release process
  8. History and documentation:
    • GitHub maintains a detailed history of all changes made through pull requests. This historical record is invaluable for understanding the evolution of the code base and tracking who contributed to specific features or fixes.

By leveraging GitHub’s features for pull requests, code review, and integrations with CI tools, development teams can streamline their workflows, catch potential issues early in the development process, and maintain high-quality code bases. This collaborative approach promotes knowledge sharing, code consistency, and overall team efficiency.

Resources for learning

To learn more about using GitHub, coding best practices, and using software methodologies to manage your projects, you can use the following resources:

  • GitHub Learning Lab: GitHub provides an interactive learning experience through Learning Lab (https://github.com/apps/github-learning-lab). This platform offers hands-on courses on Git, GitHub, and other related topics.
  • GitHub Guides: GitHub Guides (https://guides.github.com/) covers a wide range of topics, from the basics of GitHub to more advanced workflows. The guides are well-structured and easy to follow.
  • YouTube tutorials: Numerous tutorials on YouTube cater to GitHub beginners. Channels such as The Net Ninja and Traversy Media provide step-by-step guides for using GitHub.
  • Documentation: GitHub’s official documentation (https://docs.github.com/en) is a valuable resource. It covers everything from the basics to advanced topics, providing in-depth explanations and examples.
  • Interactive Git tutorial: If you’re new to Git, try the tryGit (https://try.github.io/) interactive tutorial. It’s a hands-on way to learn the basics of Git right in your browser.
  • C# coding standards and best practices: Dofactory has a good web page (https://dofactory.com/csharp-coding-standards) that provides C# coding standards and best practices with C# code.
  • C# design patterns: Dofactory provides an excellent online resource (https://dofactory.com/net/design-patterns) that covers the gang-of-four (GoF) software design patterns with detailed explanations, UML diagrams, and source code.
  • Agile software development methodologies and how to apply them: The Code Project article at https://www.codeproject.com/articles/604417/agile-software-development-methodologies-and-how-t takes you on a journey from the Waterfall method through to the modern Scrum methodology and is an interesting article on choosing the right project management methodology for managing your software projects.
  • Code Project: Code Project (https://www.codeproject.com/) is a good place to search for articles, tutorials, and code examples, as well as search for software implementation guidance on topics such as YAGNI, DRY, SOLID, and the software development life cycle (SDLC).

GitHub is an indispensable tool for modern software development, fostering collaboration, version control, and efficient project management. By familiarizing yourself with its key concepts and exploring the recommended resources, you’ll be well on your way to mastering GitHub and enhancing your development workflow.

The code review process

The normal procedure for carrying out a code review is to make sure your code compiles and meets the requirements set. It should also pass all unit tests and end-to-end tests. Once you are confident that you can compile, test, and run your code successfully, it is checked into the current working branch. Once checked in, you must issue a pull request.

A peer reviewer will then review your code and share comments and feedback. If your code passes the code review, your code review is completed, and you can merge your working branch into the main trunk. Otherwise, the peer review will be rejected, and you will be required to review your work and address the issues raised in the comments provided by your reviewer.

The following diagram shows the peer code review process:

Figure 2.1: The code review process

Figure 2.1: The code review process

In the following sections, you are going to read about the code review process in detail. We’ll start by looking at preparing code for review.

Preparing code for review

Preparing for a code review can be a royal pain at times, but it does work for better overall code that is easy to read and maintain. It is a worthwhile practice that teams of developers should carry out as a standard coding procedure. This is an important step in the code review process as perfecting this step can save you considerable time and energy in performing the review.

Note

When working on a piece of code, you can create a draft PR. Your colleagues can then review the code without having to approve it. This is a good way to receive early feedback as you progress through the development or maintenance of the code. If your coding practices are in the process of being adopted, it is a good way to ensure those new practices are being followed. Once your work is ready for final submission and approval, you can publish your draft pull request. You can learn more about draft PRs on the GitHub website: https://github.blog/2019-02-14-introducing-draft-pull-requests/.

Here are some standard points to keep in mind when preparing your code for review:

  • Always keep the code review in mind: When beginning any programming, you should have the code review in mind. So, keep your code small. If possible, limit your code to one feature, and always follow the coding standards.
  • Remember YAGNI: As you code, make sure to only add code that is necessary to meet the requirement or feature you are working on. If you don’t need it yet, then don’t code it. Only add code when it is needed and not before.
  • Check for duplicate code: If your code must be object-oriented and be DRY and SOLID, then review your code to see whether it contains any procedural or duplicate code. Should it do so, take the time to refactor it so that it is object-oriented, DRY, and SOLID.
  • Use static analyzers: Static code analyzers that have been configured to enforce your company’s best practices will check your code and highlight any issues that are encountered. Make sure that you do not ignore information and warnings. These could cause you issues further down the line.
  • Make sure that all your tests pass, even if your code builds: If your code builds but you have failing tests, then deal immediately with what’s causing those tests to fail. Then, when the tests pass as expected, you can move on. It is important to make sure that all unit tests pass and that end-to-end testing passes all tests. It is important that all testing is complete and gets the green light since releasing code that works but was a test fail could result in some very unhappy customers when the code goes to production.

Note

Most importantly, only check your code when you are confident that your code satisfies business requirements, adheres to coding standards, and passes all tests. If you check your code as part of a CI pipeline, and your code fails the build, then you will need to address the areas of concern raised by the CI pipeline. When you can check in your code and the CI pipeline gives the green light, then you can issue a pull request.

If you’re new to software development and may not know what CI/CD pipelines are, we will briefly describe them before we go any further.

CI, continuous delivery (CD), and continuous deployment (CD) are three software development practices that focus on improving the speed, quality, and reliability of software development processes. While these terms are sometimes used interchangeably, they represent different stages of a software delivery pipeline:

  • Continuous integration (CI): CI is the practice of frequently merging code changes from developers into a shared repository, followed by building and testing the code automatically. The goal of CI is to identify and fix issues as early as possible in the development process to prevent the accumulation of bugs and technical debt. With CI, developers can integrate their code changes into a shared repository multiple times a day, ensuring that the code is always in a releasable state.
  • Continuous delivery (CD): Continuous delivery is an extension of CI that focuses on automating the release of software to production. It is the practice of always keeping the code base in a releasable state and deploying it to production frequently, usually via an automated pipeline. With continuous delivery, developers can continuously deliver new features, bug fixes, and improvements to users in a fast and efficient manner.
  • Continuous deployment (CD): Continuous deployment is the most advanced stage of the software delivery pipeline and is where every change that passes through CI/CD is automatically deployed to production without any manual intervention. This process is only suitable for organizations that have a high degree of automation, test coverage, and confidence in their code base. Continuous deployment enables organizations to release features and updates to users in real-time, with little to no downtime.

In summary, CI ensures that the code base is always working, continuous delivery automates the release process, and continuous deployment takes automation one step further by deploying code changes to production automatically.

Leading a code review

When leading code reviews, it is important to have the right people present. The people who will attend the peer code review will be agreed upon with the project manager. The programmer(s) responsible for submitting the code for review will be present at the code review unless they work remotely. In the case of remote working, the reviewer will review the code and either accept the pull request, decline the pull request, or send the developer some questions to be answered before taking any further action.

A suitable lead for a code review should possess the following skills and knowledge:

  • Be a technical authority: The person leading the code review should be a technical authority who understands the company’s coding guidelines and software development methodologies. It is also important that they have a good overall understanding of the software under review. The person doing the code review should also be a master in the technology in which the code is written.
  • Have good soft skills: As the leader of the code review, the person must be a warm and encouraging individual who can provide constructive feedback and not be overly critical. The person reviewing the programmer’s code must have good soft skills so that there is no conflict between the reviewer and the person whose code is being reviewed.

In my experience, peer code reviews are always carried out on pull requests in the source control tool being used by the team. A programmer will submit the code to source control and then issue a pull request. The peer code reviewer will then review the code in the pull request. Constructive feedback will be provided in the form of comments that will be attached to the pull request. If there are problems with the pull request, then the reviewer will reject the change request and comment on specific issues that need to be addressed by the programmer. If the code review is successful, then the reviewer may add a comment providing positive feedback, merge the pull request, and close it.

Programmers will need to note any comments made by the reviewer and take them on board. If the code needs to be resubmitted, then the programmer will need to ensure that all the reviewer’s comments have been addressed before resubmitting.

It is a good idea to keep code reviews short and not review too many lines at any one time.

Since a code review normally starts with a pull request, we will look at issuing a pull request, followed by responding to a pull request.

Issuing a pull request

In source control, a pull request is a mechanism for submitting proposed changes to the code base to the main branch or repository. It is a request to merge changes made in one branch of a repository into another branch, usually the main branch.

The process typically involves a developer creating a new branch from the main branch, making changes to the code in the new branch, and then submitting a pull request to merge the changes into the main branch. The pull request includes information about the changes made, the reasons for making them, and any related issues or tickets.

Once the pull request has been submitted, other developers can review the proposed changes, suggest modifications, or approve the changes for merging into the main branch. The code changes are typically reviewed for quality, compatibility, and compliance with any coding standards or best practices before they are merged into the main branch.

To issue a pull request, all you must do (once you’ve checked your code in or pushed it) is click on the Pull requests tab of your source control. There will then be a button you can click on – New pull request. This will add your pull request to a queue, where it will be picked up by the relevant reviewers.

Information

We will be focusing on using GitHub for version control. If you have never used GitHub before or are new to version control with GitHub, you can learn more about GitHub at GitHub Skills: https://skills.github.com/.

GitHub is a web-based platform that provides a collaborative environment for developers to store, manage, and share their code repositories. It is a cloud-based source control system that enables teams to work together on projects and manage the changes that are made to the code base over time.

GitHub allows developers to create and manage their own Git repositories, which can be either public or private. Developers can then use Git commands to push code changes to their repositories and track the history of changes made to the code base over time. Other developers can then clone or fork the repository to access the code and contribute to the project.

GitHub provides a range of features and tools to support collaboration, including issue tracking, pull requests, code reviews, and project management tools. These features enable teams to work together more efficiently, resolve issues quickly, and maintain high standards of code quality.

In addition to its core functionality as a version control system, GitHub has become a hub for open-source software development, with millions of open-source projects hosted on the platform. It also provides a marketplace for third-party integrations and tools, making it a valuable resource for developers looking to streamline their development workflows.

The following screenshots show the process of requesting and fulfilling a pull request via GitHub.

On your GitHub project page, click on the Pull requests tab:

Figure 2.2: The Pull requests tab

Figure 2.2: The Pull requests tab

Then, click on the New pull request button. This will display the Comparing changes page:

Figure 2.3: The Comparing changes page

Figure 2.3: The Comparing changes page

If you are happy, then click on the Create pull request button to start the pull request. You will be presented with the Open a pull request screen:

Figure 2.4: The Open a pull request page

Figure 2.4: The Open a pull request page

Write your comment regarding the pull request. Provide all the necessary information for the code reviewer, but keep it brief and to the point. Useful comments include those that identify what changes have been made. Modify the Reviewers, Assignees, Labels, Projects, and Milestones fields as necessary. Then, once you are happy with the pull request details, click on the Create pull request button to create the pull request. Your code will now be ready to be reviewed by your peers.

Code conflict

In GitHub, code conflict resolution refers to the process of resolving conflicts that arise when two or more developers make changes to the same code file or lines of code in a Git repository. Code conflicts can occur when two or more developers modify the same piece of code in different ways, or when one developer modifies a code file while another deletes it.

When a code conflict occurs, GitHub will highlight the conflicting lines of code in the code file and notify the developers who made the conflicting changes. The developers can then use the GitHub web interface or a Git client to review the changes and resolve the conflict.

There are several ways to resolve code conflicts in GitHub:

  • Merge: Developers can merge their changes if they have made non-conflicting changes to different parts of the code. This involves reviewing the changes and manually merging the code changes.
  • Rebase: Developers can use the git rebase command to apply their changes on top of the changes made by another developer. This involves rebasing their changes on top of the changes made by the other developer and resolving any conflicts that arise.
  • Manual resolution: If the changes made by the developers conflict with each other, developers may need to manually resolve the conflicts by reviewing the changes and deciding which changes to keep and which to discard.

GitHub provides a range of tools to help developers resolve code conflicts, including visual diff tools, merge tools, and conflict resolution workflows. Code conflict resolution in GitHub aims to ensure that the code base is kept up to date, that conflicts are resolved efficiently, and that code quality is maintained.

Responding to a pull request

Figure 2.5: Responding to a pull request

Figure 2.5: Responding to a pull request

Since the reviewer is responsible for reviewing pull requests before merging branches, we would do well to look at responding to pull requests:

  1. Start by cloning a copy of the code under review.
  2. Review the comments and changes in the pull request.
  3. Check that there are no conflicts with the base branch. If there are, then you will have to reject the pull request with the necessary comments.

    Otherwise, you can review the changes, make sure the code builds without errors, and make sure there are no compilation warnings. At this stage, you will also look out for code smells and any potential bugs. Code smell is a term that’s used in software development to describe common signs of poor code design or implementation that can lead to code that is difficult to understand, maintain, or extend.

    They are not necessarily errors, but rather indicators that the code could be improved. You will also check that the tests build, run, are correct, and provide good test coverage of the feature to be merged. Make any comments necessary and reject the pull request unless you are satisfied. When satisfied, you can add your comments and merge the pull request by clicking on the Merge pull request button, as shown here:

Figure 2.6: Merging pull requests

Figure 2.6: Merging pull requests

  1. Now, confirm the merge by entering a comment and clicking on the Confirm merge button:
Figure 2.7: Confirming the merge

Figure 2.7: Confirming the merge

  1. Once the pull request has been merged and the pull request has been closed, the branch can be deleted by clicking on the Delete branch button, as can be seen in the following screenshot:
Figure 2.8: The Delete branch button

Figure 2.8: The Delete branch button

In the previous section, you saw how the reviewee raises a pull request to have their code peer-reviewed before it is merged. In this section, you saw how to review a pull request and complete it as part of a code review. Now, we will look at the negative and positive feedback that affects reviewees.

Effects of feedback on reviewees

When performing a code review of your peer’s code, you must also consider the fact that feedback can be positive or negative. Negative feedback does not provide specific details about the problem. The reviewer focuses on the reviewee and not on the problem. Suggestions for improving the code are not offered to the reviewee by the reviewer, and the reviewer’s feedback is aimed at hurting the reviewee.

Such negative feedback received by the reviewee offends them. This has a negative impact and can cause them to start doubting themselves. A lack of motivation then develops within the reviewee, and this can negatively impact the team, as work is not done on time or to the required level. The bad feelings between the reviewer and the reviewee will also be felt by the team, and an oppressive atmosphere that negatively impacts everyone on the team can ensue. This can lead to other colleagues becoming demotivated, and the overall project can end up suffering as a result.

In the end, it gets to the point where the reviewee has had enough and leaves for a new position somewhere else to get away from it all. The project then suffers time-wise and even financially, as time and money will need to be spent on finding a replacement. Whoever is found to fill the position must be trained in the system and the working procedures and guidelines. The following diagram shows negative feedback from the reviewer toward the reviewee:

Figure 2.9: The negative feedback process

Figure 2.9: The negative feedback process

Conversely, positive feedback from the reviewer to the reviewee has the opposite effect. When the reviewer provides positive feedback to the reviewee, they focus on the problem and not on the person. They explain why the code they’ve submitted is not good, along with the problems it can cause. The reviewer will then suggest to the reviewee ways in which the code can be improved. The feedback provided by the reviewer is only given to improve the quality of the code submitted by the reviewee.

When the reviewee receives the positive (constructive) feedback, they respond positively. They take on board the reviewer’s comments and respond appropriately by answering any questions and asking any relevant questions themselves. After this, the code is then updated based on the reviewer’s feedback. The amended code is then resubmitted for review and acceptance. This has a positive impact on the team as the atmosphere remains a positive one, and work is done on time and to the required quality. The following diagram shows the results of positive feedback on the reviewee from the reviewer:

Figure 2.10: Positive feedback process

Figure 2.10: Positive feedback process

The point to remember is that your feedback can be constructive or destructive. Your aim as a reviewer is to be constructive and not destructive. A happy team is a productive team. A demoralized team is not productive and is damaging to the project. So, always strive to maintain a happy team through positive feedback.

A technique for positive criticism is the feedback sandwich technique. You start with praise on the good points, then you provide constructive criticism, and then you finish with further praise. This technique can be very useful if you have members on the team who don’t react well to any form of criticism. Your soft skills in dealing with people are just as important as your software skills in delivering quality code. Don’t forget that!

We will now move on and look at what we should review.

Knowing what to review

Different aspects of code must be considered when you’re reviewing it. Primarily, the code being reviewed should only be the code that was modified by the programmer and submitted for review. That’s why you should aim to make small submissions often. Small amounts of code are much easier to review and comment on.

Let’s look at the different aspects a code reviewer should assess for a complete and thorough review.

The company’s coding guidelines and business requirement(s)

All code being reviewed should be checked against the company’s coding guidelines and the business requirement(s) the code is addressing. All new code should adhere to the latest coding standards and best practices employed by the company.

There are different types of business requirements. These requirements include those of the business and the user/stakeholder as well as functional and implementation requirements. Regardless of the type of requirement the code is addressing, it must be fully checked for correctness in meeting requirements.

For example, if the user/stakeholder requirement states that as a user, I want to add a new customer account, does the code under review meet all the conditions set out in this requirement? If the company’s coding guidelines stipulate that all code must include unit tests that test the normal flow and exceptional cases, then have all the required tests been implemented? If the answer to any of these questions is no, then the new code added by the developer fails and is sent back to be corrected.

Naming conventions

The code should be checked to see whether the naming conventions have been followed for the various code constructs, such as classes, interfaces, member variables, local variables, enumerations, and methods. Nobody likes cryptic names that are hard to decipher, especially if the code base is large.

Here are a couple of questions that a reviewer should ask:

  • Are the names long enough to be human-readable and understandable?
  • Are they meaningful concerning the intent of the code, but short enough to not irritate other programmers?

As the reviewer, you must be able to read the code and understand it. If the code is difficult to read and understand, then it needs to be refactored before being merged.

Formatting

Formatting goes a long way to making code easy to understand. Namespaces, braces, and indentation should be employed according to the guidelines, and the start and end of code blocks should be easily identifiable.

Again, here is a set of questions a reviewer should consider asking in their review:

  • Is code to be indented using spaces or tabs?
  • Has the correct amount of white space been employed?
  • Are there any lines of code that are too long that should be spread over multiple lines?
  • What about line breaks? Do the line breaks adhere to the rules laid out in the coding standards?
  • Following the style guidelines, is there only one statement per line? Is there only one declaration per line?
  • Are continuation lines correctly indented using one tab stop?
  • Are methods separated by one line?
  • Are multiple clauses that make up a single expression separated by parentheses?
  • Are classes and methods clean and small, and do they only do the work they are meant to do?
  • Do you see anything that stands out that, even if it compiles and works in isolation, could cause bugs when integrated into the system?

Testing

Tests must be understandable and cover a good subset of use cases. They must cover the normal paths of execution and exceptional use cases. When it comes to testing the code, the reviewer should check for the following:

  • Has the programmer provided tests for all the code?
  • Is there any untested code?
  • Do all the tests work?
  • Do any of the tests fail?

Let’s see how the process works:

Figure 2.11: Test plan process flow

Figure 2.11: Test plan process flow

Untested code has the potential to raise unexpected exceptions during testing and production. But just as bad as code that is not tested are tests that are not correct. This can lead to bugs that are hard to diagnose, can be annoying for the customer, and make more work for you further down the line. Bugs are technical debt and are looked upon negatively by the business. And so, as part of the process of developing code, you need to ensure you have proper unit and end-to-end tests, and that the inputs and outputs of those tests are correct.

Moreover, you may have written the code, but others may have to read it as they maintain and extend the project. It is always a good idea to provide some documentation for your colleagues.

Now, concerning the customer, how are they going to know where your features are and how to use them? Good documentation that is user-friendly is a good idea. And remember, not all your users may be technically savvy. So, cater to the less technical person who may need handholding, but do it without being patronizing.

As a technical authority reviewing the code, do you detect any code smells that may become a problem? If so, then you must flag, comment, and reject the pull request and get the programmer to resubmit their work.

As a reviewer, you should check that those exceptions are not used to control the program flow and that any errors that are raised have meaningful messages that are helpful to developers and to the customers who will receive them.

Documentation

Documentation is vital to the success of a software project. You need enough documentation to enable a full understanding of the system so that it makes extending and maintaining the existing software easier and less error-prone. Good documentation makes it easier to on-board new software developers and help them get up and running faster. Here are some things to ask when reviewing the documentation for a project:

  • Is there adequate documentation of the code, including comments, documentation comments, tests, and customer product documentation?
  • Is the code well documented to aid with maintenance and support as well as adding new product extensions?

Architectural guidelines and design patterns

When performing an architectural review of a C# project, you should be looking at the overall structure of the application and ensuring that it adheres to best practices and is scalable, maintainable, and has good performance. You should also ensure that the architecture supports the current and future requirements of the project.

Here are some questions you should ask yourself during the review:

  1. Is the application using a layered architecture, such as the Model-View-Controller (MVC) pattern or the Model-View-ViewModel (MVVM) pattern?
  2. Are the layers of the application properly separated, and are there clear boundaries between them?
  3. Are there any circular dependencies between components or modules in the application?
  4. Are the interfaces between components or modules well-defined and easy to understand?
  5. Are there any potential performance bottlenecks, such as slow database queries or inefficient algorithms?
  6. Are there any security vulnerabilities in the application, such as injection attacks or cross-site scripting (XSS) attacks?
  7. Is the code organized and structured in a way that makes it easy to maintain and understand?
  8. Are there any anti-patterns or bad coding practices in the application?
  9. Are there any unnecessary dependencies or components that could be removed to simplify the architecture?
  10. Does the architecture allow for easy testing and debugging of the application?
  11. Is the code adhering to SOLID principles and other design patterns to ensure code quality and extensibility?
  12. Are there any performance issues or bottlenecks that could be improved, such as network latency, database connection pooling, or caching?
  13. Is the application following a consistent naming convention and code style to ensure that it’s easy to read and maintain by other developers?
  14. Are there any dependencies or third-party libraries that are being used, and are they being properly managed and updated?
  15. Is the architecture taking advantage of modern C# features, such as async/await and LINQ, to improve code readability and performance?
  16. Is the application following any industry standards or best practices, such as OWASP guidelines for web security or Microsoft’s .NET Core design guidelines?
  17. Are there any opportunities to improve the code’s organization and structure, such as grouping related code into namespaces or creating separate projects for different components of the application?
  18. Are there any potential issues with deploying and scaling the application, such as difficulties with load balancing or scaling horizontally?
  19. Are there any opportunities to introduce design patterns or architectural improvements to reduce complexity and improve maintainability?
  20. Is there a clear separation of concerns between the different components and layers of the application, such as separating data access logic from business logic and presentation logic?

By addressing these questions during an architectural review, you can ensure that the C# application is well-designed, easy to maintain, and meets the requirements of its intended use case. This can lead to a more efficient development process, fewer bugs and issues, and improved user satisfaction.

Performance and security

Other things that may need to be considered include performance and security:

  • How well does the code perform?
  • Are there any bottlenecks that need to be addressed?
  • Is the code programmed in such a way that it protects against SQL injection attacks and denial-of-service (DoS) attacks?
  • Is code properly validated to keep the data clean so that only valid data gets stored in the database?
  • Have you checked the user interface, documentation, and error messages for spelling mistakes?
  • Have you encountered any magic numbers or hard-coded values?
  • Is the configuration data correct?
  • Have any secrets accidentally been checked in?

A comprehensive code review will encompass all the preceding aspects and their respective review parameters. But let’s find out when it is the right time to even be performing a code review.

Knowing when to send code for review

In general, it’s a good idea to send code for a code review whenever you have made significant changes or additions to the code base. This can help ensure that the code is well-designed, adheres to coding standards, and is free of bugs or other issues.

Here are some specific situations where you might want to send code for a code review:

  1. When you have completed a new feature or functionality: If you have added a new feature or made a significant change to an existing feature, it’s a good idea to send the code for review. This can help ensure that the feature works as intended and meets the requirements of the project.
  2. When you have made changes to core functionality: If you have made changes to the core functionality of the application, such as the database or authentication system, it’s important to get the code reviewed to ensure that the changes are well-designed and don’t introduce any security vulnerabilities or other issues.
  3. When you have refactored or optimized code: If you have made changes to the code to improve performance or make it more maintainable, it’s a good idea to send the code for review to ensure that the changes are well-designed and don’t introduce any new bugs or issues.
  4. When you are unsure about a particular piece of code: If you are unsure about the best way to implement a particular piece of functionality or if you are not sure if a particular piece of code adheres to best practices or coding standards, it’s a good idea to get the code reviewed by a more experienced developer.
  5. When there is a requirement for code review in your development process: If your team or organization requires code review as part of the development process, you should send the code for review whenever you have made changes to the code base.

In general, it’s a good idea to send code for review early and often, to catch issues early in the development process. Code review can help ensure that the code is well-designed, easy to maintain, and meets the requirements of the project.

Providing and responding to review feedback

It is worth remembering that code reviews are aimed at the overall quality of code in keeping with the company’s guidelines. Therefore, feedback should be constructive and not used as an excuse to put down or embarrass a colleague. Similarly, reviewer feedback should not be taken personally and responses to the reviewer should focus on suitable action and explanation.

The following diagram shows the process of issuing a PR, performing a code review, and either accepting or rejecting the PR:

Figure 2.12: The peer code review process

Figure 2.12: The peer code review process

Providing feedback as a reviewer

As the peer code reviewer, you will be responsible for understanding the requirements and making sure the code meets them. So, look for the answers to these questions:

  • Are you able to read and understand the code?
  • Can you see any potential bugs?
  • Have any trade-offs been made?
  • If so, why were the trade-offs made?
  • Do the trade-offs incur any technical debt that will need to be factored into the project further down the line?

Once your review is complete, you will have three categories of feedback to choose from: positive, optional, and critical. With positive feedback, you can provide commendations on what the programmer has done well. This is a good way to bolster morale. Optional feedback can be very useful in helping computer programmers hone their programming skills in line with the company guidelines, and they can work to improve the overall well-being of the software being developed.

Finally, we have critical feedback. This is necessary for any problems that have been identified and must be addressed before the code can be accepted and passed on to the QA department. Your critical comments must address the specific issue being raised with valid reasons to support the feedback.

Responding to feedback as a reviewee

As the reviewee programmer, you must effectively communicate the background of your code to your reviewer. While you are waiting for your code to be reviewed, you must not make any further changes to it.

As you can guess, you will receive either positive, optional, or critical feedback from the reviewer. The positive feedback works to boost your confidence in the project as well as your morale. Build upon it and continue with your good practices. You may choose to act upon optional feedback, but it’s always a good idea to talk it through with your reviewer.

For critical feedback, you must take it seriously and act upon it as this feedback is imperative for the very success of the project. You must handle critical feedback politely and professionally. Don’t allow yourself to be offended by any comments from your reviewer; they are not meant to be personal.

As soon as you receive your reviewer’s feedback, act upon it, and make sure that you discuss it with them as necessary.

Summary

In this chapter, we discussed the importance of performing code reviews and the complete process of getting code ready for review and responding to reviewer comments as the programmer, along with how to lead a code review and what to look for when performing a review as the code reviewer. There are two roles in a peer code review. These are the reviewer and the reviewee. The reviewer is the person performing the code review, and the reviewee is the person whose code is being reviewed.

You have also seen how you, as a reviewer, can categorize your feedback and why soft skills are important when providing feedback to fellow programmers. And as a reviewee whose code is being scrutinized, you have seen how important it is to build upon positive and optional feedback and how important it is to act upon critical feedback.

By now, you should have a good understanding of why it is important to conduct regular code reviews, and why they should be done before the code is passed on to the QA department. Peer code reviews do take time and can be uncomfortable for both the reviewer and reviewee. But in the long run, they work toward a high-quality product that is easy to extend and maintain, and they lead to better code reuse as well.

In the next chapter, we will look at how to write clean classes, objects, and data structures. We will discuss how to organize our classes effectively and ensure they only have one responsibility. We will also cover commenting on classes to help with documentation. Additionally, we’ll look at designing for change, the Law of Demeter, cohesion, and coupling. We’ll also cover concepts such as immutable objects, hiding data, and exposing methods in objects. Finally, we’ll explore data structures.

Questions

Answer the following questions to test your knowledge of this chapter:

  1. What are the two roles involved in a peer code review?
  2. Who agrees on the people who will be involved in the peer code review?
  3. How can you save your reviewer time and effort before requesting a peer code review?
  4. When reviewing code, what kinds of things must you look out for?
  5. What are the three categories of feedback?
  6. As a developer, what are the things you should consider while developing a software application?

Further reading

To learn more about the topics that were covered in this chapter, take a look at the following resources:

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Write code that seamlessly integrates with other systems while maintaining well-defined software boundaries
  • Understand how coding principles and standards elevate software quality
  • Learn how to avoid common errors while implementing concurrency or threading
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

Traditionally associated with Windows desktop applications and game development, C# has expanded into web, cloud, and mobile development. However, despite its extensive coding features, professionals often encounter issues with efficiency, scalability, and maintainability due to poor code. Clean Code in C# guides you in identifying and resolving these problems using coding best practices. This book starts by comparing good and bad code to emphasize the importance of coding standards, principles, and methodologies. It then covers code reviews, unit testing, and test-driven development, and addresses cross-cutting concerns. As you advance through the chapters, you’ll discover programming best practices for objects, data structures, exception handling, and other aspects of writing C# computer programs. You’ll also explore API design and code quality enhancement tools, while studying examples of poor coding practices to understand what to avoid. By the end of this clean code book, you’ll have the developed the skills needed to apply industry-approved coding practices to write clean, readable, extendable, and maintainable C# code.

Who is this book for?

This coding book is for proficient C# developers, team leads, senior software engineers, and software architects who want to improve the efficiency of their legacy systems. A strong understanding of C# programming is assumed.

What you will learn

  • Master the art of writing evolvable and adaptable code
  • Implement the fail-pass-refactor methodology using a sample C# console application
  • Develop custom C# exceptions that provide meaningful information
  • Identify low-quality C# code in need of refactoring
  • Improve code performance using profiling and refactoring tools
  • Create efficient and bug-free code using functional programming techniques
  • Write cross-platform code using MAUI
  • Develop cloud-deployable microservices for versatile applications

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 22, 2023
Length: 492 pages
Edition : 2nd
Language : English
ISBN-13 : 9781837632992
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Dec 22, 2023
Length: 492 pages
Edition : 2nd
Language : English
ISBN-13 : 9781837632992
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
₹4500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts
₹5000 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 11,916.97
Clean Code with C#
₹3723.99
Apps and Services with .NET 8
₹3723.99
C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals
₹4468.99
Total 11,916.97 Stars icon
Banner background image

Table of Contents

17 Chapters
Chapter 1: Coding Standards and Principles in C# Chevron down icon Chevron up icon
Chapter 2: Code Review – Process and Importance Chevron down icon Chevron up icon
Chapter 3: Classes, Objects, and Data Structures Chevron down icon Chevron up icon
Chapter 4: Writing Clean Functions Chevron down icon Chevron up icon
Chapter 5: Exception Handling Chevron down icon Chevron up icon
Chapter 6: Unit Testing Chevron down icon Chevron up icon
Chapter 7: Designing and Developing APIs Chevron down icon Chevron up icon
Chapter 8: Addressing Cross-Cutting Concerns Chevron down icon Chevron up icon
Chapter 9: AOP with PostSharp Chevron down icon Chevron up icon
Chapter 10: Using Tools to Improve Code Quality Chevron down icon Chevron up icon
Chapter 11: Refactoring C# Code Chevron down icon Chevron up icon
Chapter 12: Functional Programming Chevron down icon Chevron up icon
Chapter 13: Cross-Platform Application Development with MAUI Chevron down icon Chevron up icon
Chapter 14: Microservices Chevron down icon Chevron up icon
Assessments Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5
(2 Ratings)
5 star 50%
4 star 50%
3 star 0%
2 star 0%
1 star 0%
N/A Apr 04, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Feefo Verified review Feefo
Michael Börner Feb 20, 2024
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Feefo Verified review Feefo
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.