百科.dev
全部条目AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
C

clean-code-dotnet

> DevOps
开源

:bathtub: 适用于 .NET 的清晰代码概念和工具

7.7K stars0 点赞0 次浏览
访问官网GitHub

工具介绍

:bathtub: 适用于 .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 开放

查看全部 Issues在 GitHub 打开
  • #125

    搜索可用名字 Part1 在良好代码部分使用了不正确的变量

    更新于 2024年2月13日
  • #115

    "功能"部分"功能只应具有一个抽象层次"段中的拼写错误

    更新于 2022年7月11日
  • #113

    DRY 部分的 ShowList 函数没有返回列表

    更新于 2022年4月12日
  • #111

    为 <details> 元素添加 id,以便共享指定规则的 URL

    更新于 2022年3月17日
  • #96

    SOLID. Liskov 替换原则 (LSP)。示例不正确。

    更新于 2022年2月8日
  • #98

    从 https://csharpcodingguidelines.com 添加一些部分

    更新于 2021年6月9日
  • #97

    请在本仓中添加包含 cs 示例的 vs 项目

    更新于 2020年12月23日
  • #94

    对象和数据结构。使对象具有私有/受保护的成员

    更新于 2020年12月22日
  • #93

    避免条件语句

    更新于 2020年12月22日
  • #90

    CleanCodeDotnet

    更新于 2020年11月17日

> 标签

C#aspnetawesomeazurebest-practices

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月21日
分类DevOps
定价开源

> 相关工具

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