Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
C

clean-code-dotnet

> DevOps
Open source

:bathtub: Clean Code concepts and tools adapted for .NET

7.7K stars0 likes1 views
WebsiteGitHub

About

:bathtub: Clean Code concepts and tools adapted for .NET

Clean Code concepts adapted for .NET/.NET Core

If you liked clean-code-dotnet project or if it helped you, please give a star :star: for this repository. That will not only help strengthen our .NET community but also improve skills about the clean code for .NET developers in around the world. Thank you very much :+1:

Check out my blog or say hi on Twitter!

Table of Contents

  • Clean Code concepts adapted for .NET/.NET Core
  • Table of Contents
  • Introduction
  • Clean Code .NET
    • Naming
    • Variables
    • Functions
    • Objects and Data Structures
    • Classes
    • SOLID
    • Testing
    • Concurrency
    • Error Handling
    • Formatting
    • Comments
  • Other Clean Code Resources
    • Other Clean Code Lists
    • Style Guides
    • Tools
    • Cheatsheets
  • Contributors
  • Backers
  • Sponsors
  • License

Introduction

Software engineering principles, from Robert C. Martin's book Clean Code, adapted for .NET/.NET Core. This is not a style guide. It's a guide to producing readable, reusable, and refactorable software in .NET/.NET Core.

Not every principle herein has to be strictly followed, and even fewer will be universally agreed upon. These are guidelines and nothing more, but they are ones codified over many years of collective experience by the authors of Clean Code.

Inspired from clean-code-javascript and clean-code-php lists.

Clean Code .NET

Naming

Avoid using bad names A good name allows the code to be used by many developers. The name should reflect what it does and give context.

Bad:

csharp
int d;

Good:

csharp
int daySinceModification;

⬆ Back to top

Avoid Misleading Names

Name the variable to reflect what it is used for.

Bad:

csharp
var dataFromDb = db.GetFromService().ToList();

Good:

csharp
var listOfEmployee = _employeeService.GetEmployees().ToList();

⬆ Back to top

Avoid Hungarian notation

Hungarian Notation restates the type which is already present in the declaration. This is pointless since modern IDEs will identify the type.

Bad:

csharp
int iCounter;
string strFullName;
DateTime dModifiedDate;

Good:

csharp
int counter;
string fullName;
DateTime modifiedDate;

Hungarian Notation should also not be used in paramaters.

Bad:

csharp
public bool IsShopOpen(string pDay, int pAmount)
{
    // some logic
}

Good:

csharp
public bool IsShopOpen(string day, int amount)
{
    // some logic
}

⬆ Back to top

Use consistent capitalization

Capitalization tells you a lot about your variables, functions, etc. These rules are subjective, so your team can choose whatever they want. The point is, no matter what you all choose, just be consistent.

Bad:

csharp
const int DAYS_IN_WEEK = 7;
const int daysInMonth = 30;

var songs = new List<string> { 'Back In Black', 'Stairway to Heaven', 'Hey Jude' };
var Artists = new List<string> { 'ACDC', 'Led Zeppelin', 'The Beatles' };

bool EraseDatabase() {}
bool Restore_database() {}

class animal {}
class Alpaca {}

Good:

csharp
const int DaysInWeek = 7;
const int DaysInMonth = 30;

var songs = new List<string> { 'Back In Black', 'Stairway to Heaven', 'Hey Jude' };
var artists = new List<string> { 'ACDC', 'Led Zeppelin', 'The Beatles' };

bool EraseDatabase() {}
bool RestoreDatabase() {}

class Animal {}
class Alpaca {}

⬆ back to top

Use pronounceable names

It will take time to investigate the meaning of the variables and functions when they are not pronounceable.

Bad:

csharp
public class Employee
{
    public Datetime sWorkDate { get; set; } // what the heck is this
    public Datetime modTime { get; set; } // same here
}

Good:

csharp
public class Employee
{
    public Datetime StartWorkingDate { get; set; }
    public Datetime ModificationTime { get; set; }
}

⬆ Back to top

Use Camelcase notation

Use Camelcase Notation for variable and method paramaters.

Bad:

csharp
var employeephone;

public double CalculateSalary(int workingdays, int workinghours)
{
    // some logic
}

Good:

csharp
var employeePhone;

public double CalculateSalary(int workingDays, int workingHours)
{
    // some logic
}

⬆ Back to top

Use domain name

People who read your code are also programmers. Naming things right will help everyone be on the same page. We don't want to take time to explain to everyone what a variable or function is for.

Good

…

⬆ Back to top

Variables

Avoid nesting too deeply and return early

Too many if else statements can make the code hard to follow. Explicit is better than implicit.

Bad:

csharp
public bool IsShopOpen(string day)
{
    if (!string.IsNullOrEmpty(day))
    {
        day = day.ToLower();
        if (day == "friday")
        {
            return true;
        }
        else if (day == "saturday")
        {
            return true;
        }
        else if (day == "sunday")
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }

}

Good:

csharp
public bool IsShopOpen(string day)
{
    if (string.IsNullOrEmpty(day))
    {
        return false;
    }

    string[] openingDays = ["friday", "saturday", "sunday"];
    return openingDays.Any(d => d == day.ToLower());
}

Bad:

csharp
public long Fibonacci(int n)
{
    if (n < 50)
    {
        if (n != 0)
        {
            if (n != 1)
            {
                return Fibonacci(n - 1) + Fibonacci(n - 2);
            }
            else
            {
                return 1;
            }
        }
        else
        {
            return 0;
        }
    }
    else
    {
        throw new System.Exception("Not supported");
    }
}

Good:

csharp
public long Fibonacci(int n)
{
    if (n == 0)
    {
        return 0;
    }

    if (n == 1)
    {
        return 1;
    }

    if (n > 50)
    {
        throw new System.Exception("Not supported");
    }

    return Fibonacci(n - 1) + Fibonacci(n - 2);
}

⬆ back to top

Avoid mental mapping

Don’t force the reader of your code to translate what the variable means. Explicit is better than implicit.

Bad:

csharp
var l = new[] { "Austin", "New York", "San Francisco" };

for (var i = 0; i < l.Count(); i++)
{
    var li = l[i];
    DoStuff();
    DoSomeOtherStuff();

    // ...
    // ...
    // ...
    // Wait, what is `li` for again?
    Dispatch(li);
}

Good:

csharp
var locations = ["Austin", "New York", "San Francisco"];

foreach (var location in locations)
{
    DoStuff();
    DoSomeOtherStuff();

    // ...
    // ...
    // ...
    Dispatch(location);
}

⬆ back to top

Avoid magic string

Magic strings are string values that are specified directly within application code that have an impact on the application’s behavior. Frequently, such strings will end up being duplicated within the system, and since they cannot automatically be updated using refactoring tools, they become a common source of bugs when changes are made to some strings but not others.

Bad

csharp
if (userRole == "Admin")
{
    // logic in here
}

Good

csharp
const string ADMIN_ROLE = "Admin"
if (userRole == ADMIN_ROLE)
{
    // logic in here
}

Using this we only have to change in centralize place and others will adapt it.

⬆ back to top

Don't add unneeded context

If your class/object name tells you something, don't repeat that in your variable name.

Bad:

csharp
public class Car
{
    public string CarMake { get; set; }
    public string CarModel { get; set; }
    public string CarColor { get; set; }

    //...
}

Good:

csharp
public class Car
{
    public string Make { get; set; }
    public string Model { get; set; }
    public string Color { get; set; }

    //...
}

⬆ back to top

Use meaningful and pronounceable variable names

Bad:

csharp
var ymdstr = DateTime.UtcNow.ToString("MMMM dd, yyyy");

Good:

csharp
var currentDate = DateTime.UtcNow.ToString("MMMM dd, yyyy");

⬆ Back to top

Use the same vocabulary for the same type of variable

Bad:

csharp
GetUserInfo();
GetUserData();
GetUserRecord();
GetUserProfile();

Good:

csharp
GetUser();

⬆ Back to top

Use searchable names (part 1)

We will read more code than we will ever write. It's important that the code we do write is readable and searchable. By not naming variables that end up being meaningful for understanding our program, we hurt our readers. Make your names searchable.

Bad:

csharp
// What the heck is data for?
var data = new { Name = "John", Age = 42 };

var stream1 = new MemoryStream();
var ser1 = new DataContractJsonSerializer(typeof(object));
ser1.WriteObject(stream1, data);

stream1.Position = 0;
var sr1 = new StreamReader(stream1);
Console.Write("JSON form of Data object: ");
Console.WriteLine(sr1.ReadToEnd());

Good:

csharp
var person = new Person
{
    Name = "John",
    Age = 42
};

var stream2 = new MemoryStream();
var ser2 = new DataContractJsonSerializer(typeof(Person));
ser2.WriteObject(stream2, data);

stream2.Position = 0;
var sr2 = new StreamReader(stream2);
Console.Write("JSON form of Data object: ");
Console.WriteLine(sr2.ReadToEnd());

⬆ Back to top

Use searchable names (part 2)

Bad:

csharp
var data = new { Name = "John", Age = 42, PersonAccess = 4};

// What the heck is 4 for?
if (data.PersonAccess == 4)
{
    // do edit ...
}

Good:

csharp
public enum PersonAccess : int
{
    ACCESS_READ = 1,
    ACCESS_CREATE = 2,
    ACCESS_UPDATE = 4,
    ACCESS_DELETE = 8
}

var person = new Person
{
    Name = "John",
    Age = 42,
    PersonAccess= PersonAccess.ACCESS_CREATE
};

if (person.PersonAccess == PersonAccess.ACCESS_UPDATE)
{
    // do edit ...
}

⬆ Back to top

Use explanatory variables

Bad:

csharp
const string Address = "One Infinite Loop, Cupertino 95014";
var cityZipCodeRegex = @"/^[^,\]+[,\\s]+(.+?)\s*(\d{5})?$/";
var matches = Regex.Matches(Address, cityZipCodeRegex);
i

Issues· 47 open

View all issuesOpen on GitHub
  • #125

    Searchable Names Part1 in Good code section incorrect variable is used

    Updated Feb 13, 2024
  • #115

    Typo in section "Functions" paragraph "Functions should only be one level of abstraction"

    Updated Jul 11, 2022
  • #113

    ShowList funtion in DRY section does not return a list

    Updated Apr 12, 2022
  • #111

    Add ids to <details> elements, in order to share URLs to specific rules

    Updated Mar 17, 2022
  • #96

    SOLID. Liskov Substitution Principle (LSP). Example incorrect.

    Updated Feb 8, 2022
  • #98

    Add some of the sections from https://csharpcodingguidelines.com/

    Updated Jun 9, 2021
  • #97

    Please, add vs project with cs examples in this repo

    Updated Dec 23, 2020
  • #94

    Objects and Data Structures. Make objects have private/protected members

    Updated Dec 22, 2020
  • #93

    Avoid conditionals

    Updated Dec 22, 2020
  • #90

    CleanCodeDotnet

    Updated Nov 17, 2020

> Tags

C#aspnetawesomeazurebest-practices

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedOct 1, 2026
CategoryDevOps
PricingOpen source

> Related tools

D
Docker
容器化平台,标准化应用交付
G
GitHub Actions
GitHub 原生 CI/CD 工作流
N
Nginx
高性能 Web 服务器与反向代理