Home Programming Clean Code with C# - Second Edition

Clean Code with C# - Second Edition

By Jason Alls
ai-assist-svg-icon Book + AI Assistant
eBook + AI Assistant $39.99 $27.98
Print $49.99
Subscription $15.99 $10 p/m for three months
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime! ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Along with your eBook purchase, enjoy AI Assistant (beta) access in our online reader for a personalized, interactive reading experience.
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime! ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
eBook + AI Assistant $39.99 $27.98
Print $49.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Along with your eBook purchase, enjoy AI Assistant (beta) access in our online reader for a personalized, interactive reading experience.
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 2: Code Review – Process and Importance
About this book
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.
Publication date:
December 2023
Publisher
Packt
Pages
492
ISBN
9781837635191

 

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:

About the Author
  • Jason Alls

    Jason Alls has been programming for over 23 using Microsoft technologies. During his career, he has developed several different desktop, web, and mobile applications in VB.NET, C#, and SQL Server. He is the author of the successful books Clean Code in C# and High-Performance Programming in C#. Currently employed as a software developer with a software housel, he develops warehouse software for media distribution companies.

    Browse publications by this author
Latest Reviews (2 reviews total)
Clean Code with C#  - Second Edition
Unlock this book and the full library FREE for 7 days
Start now