Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

🛁 Clean Code concepts and tools adapted for .NET

License

NotificationsYou must be signed in to change notification settings

thangchung/clean-code-dotnet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

If you likedclean-code-dotnet project or if it helped you, please give a 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 👍

Check out myblog or say hi onTwitter!

Table of Contents

Introduction

Humorous image of software quality estimation as a count of how many expletives you shout when reading code

Software engineering principles, from Robert C. Martin's bookClean 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 ofClean Code.

Inspired fromclean-code-javascript andclean-code-php lists.

Clean Code .NET

Naming

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

Bad:

intd;

Good:

intdaySinceModification;

⬆ Back to top

Avoid Misleading Names

Name the variable to reflect what it is used for.

Bad:

vardataFromDb=db.GetFromService().ToList();

Good:

varlistOfEmployee=_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:

intiCounter;stringstrFullName;DateTimedModifiedDate;

Good:

intcounter;stringfullName;DateTimemodifiedDate;

Hungarian Notation should also not be used in paramaters.

Bad:

publicboolIsShopOpen(stringpDay,intpAmount){// some logic}

Good:

publicboolIsShopOpen(stringday,intamount){// 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 whateverthey want. The point is, no matter what you all choose, just be consistent.

Bad:

constintDAYS_IN_WEEK=7;constintdaysInMonth=30;varsongs=newList<string>{'Back In Black','Stairway to Heaven','Hey Jude'};varArtists=newList<string>{'ACDC','Led Zeppelin','The Beatles'};boolEraseDatabase(){}boolRestore_database(){}classanimal{}classAlpaca{}

Good:

constintDaysInWeek=7;constintDaysInMonth=30;varsongs=newList<string>{'Back In Black','Stairway to Heaven','Hey Jude'};varartists=newList<string>{'ACDC','Led Zeppelin','The Beatles'};boolEraseDatabase(){}boolRestoreDatabase(){}classAnimal{}classAlpaca{}

⬆ 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:

publicclassEmployee{publicDatetimesWorkDate{get;set;}// what the heck is thispublicDatetimemodTime{get;set;}// same here}

Good:

publicclassEmployee{publicDatetimeStartWorkingDate{get;set;}publicDatetimeModificationTime{get;set;}}

⬆ Back to top

Use Camelcase notation

UseCamelcase Notation for variable and method paramaters.

Bad:

varemployeephone;publicdoubleCalculateSalary(intworkingdays,intworkinghours){// some logic}

Good:

varemployeePhone;publicdoubleCalculateSalary(intworkingDays,intworkingHours){// 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

publicclassSingleObject{// create an object of SingleObjectprivatestaticSingleObject_instance=newSingleObject();// make the constructor private so that this class cannot be instantiatedprivateSingleObject(){}// get the only object availablepublicstaticSingleObjectGetInstance(){return_instance;}publicstringShowMessage(){return"Hello World!";}}publicstaticvoidmain(String[]args){// illegal construct// var object = new SingleObject();// Get the only object availablevarsingletonObject=SingleObject.GetInstance();// show the messagesingletonObject.ShowMessage();}

⬆ 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:

publicboolIsShopOpen(stringday){if(!string.IsNullOrEmpty(day)){day=day.ToLower();if(day=="friday"){returntrue;}elseif(day=="saturday"){returntrue;}elseif(day=="sunday"){returntrue;}else{returnfalse;}}else{returnfalse;}}

Good:

publicboolIsShopOpen(stringday){if(string.IsNullOrEmpty(day)){returnfalse;}varopeningDays=new[]{"friday","saturday","sunday"};returnopeningDays.Any(d=>d==day.ToLower());}

Bad:

publiclongFibonacci(intn){if(n<50){if(n!=0){if(n!=1){returnFibonacci(n-1)+Fibonacci(n-2);}else{return1;}}else{return0;}}else{thrownewSystem.Exception("Not supported");}}

Good:

publiclongFibonacci(intn){if(n==0){return0;}if(n==1){return1;}if(n>50){thrownewSystem.Exception("Not supported");}returnFibonacci(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:

varl=new[]{"Austin","New York","San Francisco"};for(vari=0;i<l.Count();i++){varli=l[i];DoStuff();DoSomeOtherStuff();// ...// ...// ...// Wait, what is `li` for again?Dispatch(li);}

Good:

varlocations=new[]{"Austin","New York","San Francisco"};foreach(varlocationinlocations){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

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

Good

conststringADMIN_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:

publicclassCar{publicstringCarMake{get;set;}publicstringCarModel{get;set;}publicstringCarColor{get;set;}//...}

Good:

publicclassCar{publicstringMake{get;set;}publicstringModel{get;set;}publicstringColor{get;set;}//...}

⬆ back to top

Use meaningful and pronounceable variable names

Bad:

varymdstr=DateTime.UtcNow.ToString("MMMM dd, yyyy");

Good:

varcurrentDate=DateTime.UtcNow.ToString("MMMM dd, yyyy");

⬆ Back to top

Use the same vocabulary for the same type of variable

Bad:

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

Good:

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. Bynot naming variables that end up being meaningful for understanding our program, we hurt our readers. Make your names searchable.

Bad:

// What the heck is data for?vardata=new{Name="John",Age=42};varstream1=newMemoryStream();varser1=newDataContractJsonSerializer(typeof(object));ser1.WriteObject(stream1,data);stream1.Position=0;varsr1=newStreamReader(stream1);Console.Write("JSON form of Data object: ");Console.WriteLine(sr1.ReadToEnd());

Good:

varperson=newPerson{Name="John",Age=42};varstream2=newMemoryStream();varser2=newDataContractJsonSerializer(typeof(Person));ser2.WriteObject(stream2,data);stream2.Position=0;varsr2=newStreamReader(stream2);Console.Write("JSON form of Data object: ");Console.WriteLine(sr2.ReadToEnd());

⬆ Back to top

Use searchable names (part 2)

Bad:

vardata=new{Name="John",Age=42,PersonAccess=4};// What the heck is 4 for?if(data.PersonAccess==4){// do edit ...}

Good:

publicenumPersonAccess:int{ACCESS_READ=1,ACCESS_CREATE=2,ACCESS_UPDATE=4,ACCESS_DELETE=8}varperson=newPerson{Name="John",Age=42,PersonAccess=PersonAccess.ACCESS_CREATE};if(person.PersonAccess==PersonAccess.ACCESS_UPDATE){// do edit ...}

⬆ Back to top

Use explanatory variables

Bad:

conststringAddress="One Infinite Loop, Cupertino 95014";varcityZipCodeRegex=@"/^[^,\]+[,\\s]+(.+?)\s*(\d{5})?$/";varmatches=Regex.Matches(Address,cityZipCodeRegex);if(matches[0].Success==true&&matches[1].Success==true){SaveCityZipCode(matches[0].Value,matches[1].Value);}

Good:

Decrease dependence on regex by naming subpatterns.

conststringAddress="One Infinite Loop, Cupertino 95014";varcityZipCodeWithGroupRegex=@"/^[^,\]+[,\\s]+(?<city>.+?)\s*(?<zipCode>\d{5})?$/";varmatchesWithGroup=Regex.Match(Address,cityZipCodeWithGroupRegex);varcityGroup=matchesWithGroup.Groups["city"];varzipCodeGroup=matchesWithGroup.Groups["zipCode"];if(cityGroup.Success==true&&zipCodeGroup.Success==true){SaveCityZipCode(cityGroup.Value,zipCodeGroup.Value);}

⬆ back to top

Use default arguments instead of short circuiting or conditionals

Not good:

This is not good becausebreweryName can beNULL.

This opinion is more understandable than the previous version, but it better controls the value of the variable.

publicvoidCreateMicrobrewery(stringname=null){varbreweryName=!string.IsNullOrEmpty(name)?name:"Hipster Brew Co.";// ...}

Good:

publicvoidCreateMicrobrewery(stringbreweryName="Hipster Brew Co."){// ...}

⬆ back to top

Functions

Avoid side effects

A function produces a side effect if it does anything other than take a value in and return another value or values. A side effect could be writing to a file, modifying some global variable, or accidentally wiring all your money to a stranger.

Now, you do need to have side effects in a program on occasion. Like the previous example, you might need to write to a file. What you want to do is to centralize where you are doing this. Don't have several functions and classes that write to a particular file. Have one service that does it. One and only one.

The main point is to avoid common pitfalls like sharing state between objects without any structure, using mutable data types that can be written to by anything, and not centralizing where your side effects occur. If you can do this, you will be happierthan the vast majority of other programmers.

Bad:

// Global variable referenced by following function.// If we had another function that used this name, now it'd be an array and it could break it.varname="Ryan McDermott";publicvoidSplitAndEnrichFullName(){vartemp=name.Split(" ");name=$"His first name is{temp[0]}, and his last name is{temp[1]}";// side effect}SplitAndEnrichFullName();Console.WriteLine(name);// His first name is Ryan, and his last name is McDermott

Good:

publicstringSplitAndEnrichFullName(stringname){vartemp=name.Split(" ");return$"His first name is{temp[0]}, and his last name is{temp[1]}";}varname="Ryan McDermott";varfullName=SplitAndEnrichFullName(name);Console.WriteLine(name);// Ryan McDermottConsole.WriteLine(fullName);// His first name is Ryan, and his last name is McDermott

⬆ back to top

Avoid negative conditionals

Bad:

publicboolIsDOMNodeNotPresent(stringnode){// ...}if(!IsDOMNodeNotPresent(node)){// ...}

Good:

publicboolIsDOMNodePresent(stringnode){// ...}if(IsDOMNodePresent(node)){// ...}

⬆ back to top

Avoid conditionals

This seems like an impossible task. Upon first hearing this, most people say, "how am I supposed to do anything without anif statement?" The answer is that you can use polymorphism to achieve the same task in many cases. The second question is usually, "well that's great but why would I want to do that?" The answer is a previous clean code concept we learned: a function should only doone thing. When you have classes and functions that haveif statements, you are telling your user that your function does more than one thing. Remember, just do one thing.

Bad:

classAirplane{// ...publicdoubleGetCruisingAltitude(){switch(_type){case'777':returnGetMaxAltitude()-GetPassengerCount();case'Air Force One':returnGetMaxAltitude();case'Cessna':returnGetMaxAltitude()-GetFuelExpenditure();}}}

Good:

interfaceIAirplane{// ...doubleGetCruisingAltitude();}classBoeing777:IAirplane{// ...publicdoubleGetCruisingAltitude(){returnGetMaxAltitude()-GetPassengerCount();}}classAirForceOne:IAirplane{// ...publicdoubleGetCruisingAltitude(){returnGetMaxAltitude();}}classCessna:IAirplane{// ...publicdoubleGetCruisingAltitude(){returnGetMaxAltitude()-GetFuelExpenditure();}}

⬆ back to top

Avoid type-checking (part 1)

Bad:

publicPathTravelToTexas(objectvehicle){if(vehicle.GetType()==typeof(Bicycle)){(vehicleasBicycle).PeddleTo(newLocation("texas"));}elseif(vehicle.GetType()==typeof(Car)){(vehicleasCar).DriveTo(newLocation("texas"));}}

Good:

publicPathTravelToTexas(Travelervehicle){vehicle.TravelTo(newLocation("texas"));}

or

// pattern matchingpublicPathTravelToTexas(objectvehicle){if(vehicleisBicyclebicycle){bicycle.PeddleTo(newLocation("texas"));}elseif(vehicleisCarcar){car.DriveTo(newLocation("texas"));}}

⬆ back to top

Avoid type-checking (part 2)

Bad:

publicintCombine(dynamicval1,dynamicval2){intvalue;if(!int.TryParse(val1,outvalue)||!int.TryParse(val2,outvalue)){thrownewException('Must be of type Number');}returnval1+val2;}

Good:

publicintCombine(intval1,intval2){returnval1+val2;}

⬆ back to top

Avoid flags in method parameters

A flag indicates that the method has more than one responsibility. It is best if the method only has a single responsibility. Split the method into two if a boolean parameter adds multiple responsibilities to the method.

Bad:

publicvoidCreateFile(stringname,booltemp=false){if(temp){Touch("./temp/"+name);}else{Touch(name);}}

Good:

publicvoidCreateFile(stringname){Touch(name);}publicvoidCreateTempFile(stringname){Touch("./temp/"+name);}

⬆ back to top

Don't write to global functions

Polluting globals is a bad practice in many languages because you could clash with another library and the user of your API would be none-the-wiser until they get an exception in production. Let's think about an example: what if you wanted to have configuration array.You could write global function likeConfig(), but it could clash with another library that tried to do the same thing.

Bad:

publicDictionary<string,string>Config(){returnnewDictionary<string,string>(){["foo"]="bar"};}

Good:

classConfiguration{privateDictionary<string,string>_configuration;publicConfiguration(Dictionary<string,string>configuration){_configuration=configuration;}publicstring[]Get(stringkey){return_configuration.ContainsKey(key)?_configuration[key]:null;}}

Load configuration and create instance ofConfiguration class

varconfiguration=newConfiguration(newDictionary<string,string>(){["foo"]="bar"});

And now you must use instance ofConfiguration in your application.

⬆ back to top

Don't use a Singleton pattern

Singleton is ananti-pattern. Paraphrased from Brian Button:

  1. They are generally used as aglobal instance, why is that so bad? Becauseyou hide the dependencies of your application in your code, instead of exposing them through the interfaces. Making something global to avoid passing it around is acode smell.
  2. They violate thesingle responsibility principle: by virtue of the fact thatthey control their own creation and lifecycle.
  3. They inherently cause code to be tightlycoupled. This makes faking them out undertest rather difficult in many cases.
  4. They carry state around for the lifetime of the application. Another hit to testing sinceyou can end up with a situation where tests need to be ordered which is a big no for unit tests. Why? Because each unit test should be independent from the other.

There is also very good thoughts byMisko Hevery about theroot of problem.

Bad:

classDBConnection{privatestaticDBConnection_instance;privateDBConnection(){// ...}publicstaticGetInstance(){if(_instance==null){_instance=newDBConnection();}return_instance;}// ...}varsingleton=DBConnection.GetInstance();

Good:

classDBConnection{publicDBConnection(IOptions<DbConnectionOption>options){// ...}// ...}

Create instance ofDBConnection class and configure it withOption pattern.

varoptions=<resolvefrom IOC>;varconnection=newDBConnection(options);

And now you must use instance ofDBConnection in your application.

⬆ back to top

Function arguments (2 or fewer ideally)

Limiting the amount of function parameters is incredibly important because it makes testing your function easier. Having more than three leads to a combinatorial explosion where you have to test tons of different cases with each separate argument.

Zero arguments is the ideal case. One or two arguments is ok, and three should be avoided. Anything more than that should be consolidated. Usually, if you have more than two arguments then your function is trying to do too much. In cases where it's not, most of the time a higher-level object will suffice as an argument.

Bad:

publicvoidCreateMenu(stringtitle,stringbody,stringbuttonText,boolcancellable){// ...}

Good:

publicclassMenuConfig{publicstringTitle{get;set;}publicstringBody{get;set;}publicstringButtonText{get;set;}publicboolCancellable{get;set;}}varconfig=newMenuConfig{Title="Foo",Body="Bar",ButtonText="Baz",Cancellable=true};publicvoidCreateMenu(MenuConfigconfig){// ...}

⬆ back to top

Functions should do one thing

This is by far the most important rule in software engineering. When functions do more than one thing, they are harder to compose, test, and reason about. When you can isolate a function to just one action, they can be refactored easily and your code will read muchcleaner. If you take nothing else away from this guide other than this, you'll be ahead of many developers.

Bad:

publicvoidSendEmailToListOfClients(string[]clients){foreach(varclientinclients){varclientRecord=db.Find(client);if(clientRecord.IsActive()){Email(client);}}}

Good:

publicvoidSendEmailToListOfClients(string[]clients){varactiveClients=GetActiveClients(clients);// Do some logic}publicList<Client>GetActiveClients(string[]clients){returndb.Find(clients).Where(s=>s.Status=="Active");}

⬆ back to top

Function names should say what they do

Bad:

publicclassEmail{//...publicvoidHandle(){SendMail(this._to,this._subject,this._body);}}varmessage=newEmail(...);// What is this? A handle for the message? Are we writing to a file now?message.Handle();

Good:

publicclassEmail{//...publicvoidSend(){SendMail(this._to,this._subject,this._body);}}varmessage=newEmail(...);// Clear and obviousmessage.Send();

⬆ back to top

Functions should only be one level of abstraction

Not finished yet

When you have more than one level of abstraction your function is usually doing too much. Splitting up functions leads to reusability and easier testing.

Bad:

publicstringParseBetterJSAlternative(stringcode){varregexes=[// ...];varstatements=explode(" ",code);vartokens=newstring[]{};foreach(varregexinregexes){foreach(varstatementinstatements){// ...}}varast=newstring[]{};foreach(vartokenintokens){// lex...}foreach(varnodeinast){// parse...}}

Bad too:

We have carried out some of the functionality, but theParseBetterJSAlternative() function is still very complex and not testable.

publicstringTokenize(stringcode){varregexes=newstring[]{// ...};varstatements=explode(" ",code);vartokens=newstring[]{};foreach(varregexinregexes){foreach(varstatementinstatements){tokens[]=/* ... */;}}returntokens;}publicstringLexer(string[]tokens){varast=newstring[]{};foreach(vartokenintokens){ast[]=/* ... */;}returnast;}publicstringParseBetterJSAlternative(stringcode){vartokens=Tokenize(code);varast=Lexer(tokens);foreach(varnodeinast){// parse...}}

Good:

The best solution is move out the dependencies ofParseBetterJSAlternative() function.

classTokenizer{publicstringTokenize(stringcode){varregexes=newstring[]{// ...};varstatements=explode(" ",code);vartokens=newstring[]{};foreach(varregexinregexes){foreach(varstatementinstatements){tokens[]=/* ... */;}}returntokens;}}classLexer{publicstringLexify(string[]tokens){varast=new[]{};foreach(vartokenintokens){ast[]=/* ... */;}returnast;}}classBetterJSAlternative{privatestring_tokenizer;privatestring_lexer;publicBetterJSAlternative(Tokenizer tokenizer,Lexer lexer){_tokenizer=tokenizer;_lexer=lexer;}publicstringParse(stringcode){vartokens=_tokenizer.Tokenize(code);varast=_lexer.Lexify(tokens);foreach(varnodeinast){// parse...}}}

⬆ back to top

Function callers and callees should be close

If a function calls another, keep those functions vertically close in the source file. Ideally, keep the caller right above the callee. We tend to read code from top-to-bottom, like a newspaper. Because of this, make your code read that way.

Bad:

classPerformanceReview{privatereadonlyEmployee_employee;publicPerformanceReview(Employeeemployee){_employee=employee;}privateIEnumerable<PeersData>LookupPeers(){returndb.lookup(_employee,'peers');}privateManagerDataLookupManager(){returndb.lookup(_employee,'manager');}privateIEnumerable<PeerReviews>GetPeerReviews(){varpeers=LookupPeers();// ...}publicPerfReviewDataPerfReview(){GetPeerReviews();GetManagerReview();GetSelfReview();}publicManagerDataGetManagerReview(){varmanager=LookupManager();}publicEmployeeDataGetSelfReview(){// ...}}varreview=newPerformanceReview(employee);review.PerfReview();

Good:

classPerformanceReview{privatereadonlyEmployee_employee;publicPerformanceReview(Employeeemployee){_employee=employee;}publicPerfReviewDataPerfReview(){GetPeerReviews();GetManagerReview();GetSelfReview();}privateIEnumerable<PeerReviews>GetPeerReviews(){varpeers=LookupPeers();// ...}privateIEnumerable<PeersData>LookupPeers(){returndb.lookup(_employee,'peers');}privateManagerDataGetManagerReview(){varmanager=LookupManager();returnmanager;}privateManagerDataLookupManager(){returndb.lookup(_employee,'manager');}privateEmployeeDataGetSelfReview(){// ...}}varreview=newPerformanceReview(employee);review.PerfReview();

⬆ back to top

Encapsulate conditionals

Bad:

if(article.state=="published"){// ...}

Good:

if(article.IsPublished()){// ...}

⬆ back to top

Remove dead code

Dead code is just as bad as duplicate code. There's no reason to keep it in your codebase. If it's not being called, get rid of it! It will still be safe in your version history if you still need it.

Bad:

publicvoidOldRequestModule(stringurl){// ...}publicvoidNewRequestModule(stringurl){// ...}varrequest=NewRequestModule(requestUrl);InventoryTracker("apples",request,"www.inventory-awesome.io");

Good:

publicvoidRequestModule(stringurl){// ...}varrequest=RequestModule(requestUrl);InventoryTracker("apples",request,"www.inventory-awesome.io");

⬆ back to top

Objects and Data Structures

Use getters and setters

In C# / VB.NET you can setpublic,protected andprivate keywords for methods.Using it, you can control properties modification on an object.

  • When you want to do more beyond getting an object property, you don't have to look up and change every accessor in your codebase.
  • Makes adding validation simple when doing aset.
  • Encapsulates the internal representation.
  • Easy to add logging and error handling when getting and setting.
  • Inheriting this class, you can override default functionality.
  • You can lazy load your object's properties, let's say getting it from a server.

Additionally, this is part of Open/Closed principle, from object-oriented design principles.

Bad:

classBankAccount{publicdoubleBalance=1000;}varbankAccount=newBankAccount();// Fake buy shoes...bankAccount.Balance-=100;

Good:

classBankAccount{privatedouble_balance=0.0D;pubicdouble Balance{get{return_balance;}}publicBankAccount(balance=1000){_balance=balance;}publicvoidWithdrawBalance(intamount){if(amount>_balance){thrownewException('Amount greater than available balance.');}_balance-=amount;}publicvoidDepositBalance(intamount){_balance+=amount;}}varbankAccount=newBankAccount();// Buy shoes...bankAccount.WithdrawBalance(price);// Get balancebalance=bankAccount.Balance;

⬆ back to top

Make objects have private/protected members

Bad:

classEmployee{publicstringName{get;set;}publicEmployee(stringname){Name=name;}}varemployee=newEmployee("John Doe");Console.WriteLine(employee.Name);// Employee name: John Doe

Good:

classEmployee{publicstringName{get;}publicEmployee(stringname){Name=name;}}varemployee=newEmployee("John Doe");Console.WriteLine(employee.Name);// Employee name: John Doe

⬆ back to top

Classes

Use method chaining

This pattern is very useful and commonly used in many libraries. It allows your code to be expressive, and less verbose.For that reason, use method chaining and take a look at how clean your code will be.

Good:

publicstaticclassListExtensions{publicstaticList<T>FluentAdd<T>(thisList<T>list,Titem){list.Add(item);returnlist;}publicstaticList<T>FluentClear<T>(thisList<T>list){list.Clear();returnlist;}publicstaticList<T>FluentForEach<T>(thisList<T>list,Action<T>action){list.ForEach(action);returnlist;}publicstaticList<T>FluentInsert<T>(thisList<T>list,intindex,Titem){list.Insert(index,item);returnlist;}publicstaticList<T>FluentRemoveAt<T>(thisList<T>list,intindex){list.RemoveAt(index);returnlist;}publicstaticList<T>FluentReverse<T>(thisList<T>list){list.Reverse();returnlist;}}internalstaticvoidListFluentExtensions(){varlist=newList<int>(){1,2,3,4,5}.FluentAdd(1).FluentInsert(0,0).FluentRemoveAt(1).FluentReverse().FluentForEach(value=>value.WriteLine()).FluentClear();}

⬆ back to top

Prefer composition over inheritance

As stated famously inDesign Patterns by the Gang of Four,you should prefer composition over inheritance where you can. There are lots of good reasons to use inheritance and lots of good reasons to use composition.

The main point for this maxim is that if your mind instinctively goes for inheritance, try to think if composition could model your problem better. In some cases it can.

You might be wondering then, "when should I use inheritance?" Itdepends on your problem at hand, but this is a decent list of when inheritance makes more sense than composition:

  1. Your inheritance represents an "is-a" relationship and not a "has-a" relationship (Human->Animal vs. User->UserDetails).
  2. You can reuse code from the base classes (Humans can move like all animals).
  3. You want to make global changes to derived classes by changing a base class (Change the caloric expenditure of all animals when they move).

Bad:

classEmployee{privatestringName{get;set;}privatestringEmail{get;set;}publicEmployee(stringname,stringemail){Name=name;Email=email;}// ...}// Bad because Employees "have" tax data.// EmployeeTaxData is not a type of EmployeeclassEmployeeTaxData:Employee{privatestringName{get;}privatestringEmail{get;}publicEmployeeTaxData(stringname,stringemail,stringssn,stringsalary){// ...}// ...}

Good:

classEmployeeTaxData{publicstringSsn{get;}publicstringSalary{get;}publicEmployeeTaxData(stringssn,stringsalary){Ssn=ssn;Salary=salary;}// ...}classEmployee{publicstringName{get;}publicstringEmail{get;}publicEmployeeTaxDataTaxData{get;}publicEmployee(stringname,stringemail){Name=name;Email=email;}publicvoidSetTax(stringssn,doublesalary){TaxData=newEmployeeTaxData(ssn,salary);}// ...}

⬆ back to top

SOLID

What is SOLID?

SOLID is the mnemonic acronym introduced by Michael Feathers for the first five principles named by Robert Martin, which meant five basic principles of object-oriented programming and design.

Single Responsibility Principle (SRP)

As stated in Clean Code, "There should never be more than one reason for a class to change". It's tempting to jam-pack a class with a lot of functionality, like when you can only take one suitcase on your flight. The issue with this is that your class won't be conceptually cohesive and it will give it many reasons to change. Minimizing the amount of times you need to change a class is important.

It's important because if too much functionality is in one class and you modify a piece of it, it can be difficult to understand how that will affect other dependent modules in your codebase.

Bad:

classUserSettings{privateUserUser;publicUserSettings(Useruser){User=user;}publicvoidChangeSettings(Settingssettings){if(verifyCredentials()){// ...}}privateboolVerifyCredentials(){// ...}}

Good:

classUserAuth{privateUserUser;publicUserAuth(Useruser){User=user;}publicboolVerifyCredentials(){// ...}}classUserSettings{privateUserUser;privateUserAuthAuth;publicUserSettings(Useruser){User=user;Auth=newUserAuth(user);}publicvoidChangeSettings(Settingssettings){if(Auth.VerifyCredentials()){// ...}}}

⬆ back to top

Open/Closed Principle (OCP)

As stated by Bertrand Meyer, "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification." What does that mean though? This principle basically states that you should allow users to add new functionalities without changing existing code.

Bad:

abstractclassAdapterBase{protectedstringName;publicstringGetName(){returnName;}}classAjaxAdapter:AdapterBase{publicAjaxAdapter(){Name="ajaxAdapter";}}classNodeAdapter:AdapterBase{publicNodeAdapter(){Name="nodeAdapter";}}classHttpRequester:AdapterBase{privatereadonlyAdapterBaseAdapter;publicHttpRequester(AdapterBaseadapter){Adapter=adapter;}publicboolFetch(stringurl){varadapterName=Adapter.GetName();if(adapterName=="ajaxAdapter"){returnMakeAjaxCall(url);}elseif(adapterName=="httpNodeAdapter"){returnMakeHttpCall(url);}}privateboolMakeAjaxCall(stringurl){// request and return promise}privateboolMakeHttpCall(stringurl){// request and return promise}}

Good:

interfaceIAdapter{boolRequest(stringurl);}classAjaxAdapter:IAdapter{publicboolRequest(stringurl){// request and return promise}}classNodeAdapter:IAdapter{publicboolRequest(stringurl){// request and return promise}}classHttpRequester{privatereadonlyIAdapterAdapter;publicHttpRequester(IAdapteradapter){Adapter=adapter;}publicboolFetch(stringurl){returnAdapter.Request(url);}}

⬆ back to top

Liskov Substitution Principle (LSP)

This is a scary term for a very simple concept. It's formally defined as "If S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed,etc.)." That's an even scarier definition.

The best explanation for this is if you have a parent class and a child class, then the base class and child class can be used interchangeably without getting incorrect results. This might still be confusing, so let's take a look at the classic Square-Rectangle example. Mathematically, a square is a rectangle, but if you model it using the "is-a" relationship via inheritance, you quicklyget into trouble.

Bad:

classRectangle{protecteddoubleWidth=0;protecteddoubleHeight=0;publicDrawableRender(doublearea){// ...}publicvoidSetWidth(doublewidth){Width=width;}publicvoidSetHeight(doubleheight){Height=height;}publicdoubleGetArea(){returnWidth*Height;}}classSquare:Rectangle{publicdoubleSetWidth(doublewidth){Width=Height=width;}publicdoubleSetHeight(doubleheight){Width=Height=height;}}DrawableRenderLargeRectangles(Rectanglerectangles){foreach(rectangleinrectangles){rectangle.SetWidth(4);rectangle.SetHeight(5);vararea=rectangle.GetArea();// BAD: Will return 25 for Square. Should be 20.rectangle.Render(area);}}varrectangles=new[]{newRectangle(),newRectangle(),newSquare()};RenderLargeRectangles(rectangles);

Good:

abstractclassShapeBase{protecteddoubleWidth=0;protecteddoubleHeight=0;abstractpublicdoubleGetArea();publicDrawableRender(doublearea){// ...}}classRectangle:ShapeBase{publicvoidSetWidth(doublewidth){Width=width;}publicvoidSetHeight(doubleheight){Height=height;}publicdoubleGetArea(){returnWidth*Height;}}classSquare:ShapeBase{privatedoubleLength=0;publicdoubleSetLength(doublelength){Length=length;}publicdoubleGetArea(){returnMath.Pow(Length,2);}}DrawableRenderLargeRectangles(Rectanglerectangles){foreach(rectangleinrectangles){if(rectangleisSquare){rectangle.SetLength(5);}elseif(rectangleisRectangle){rectangle.SetWidth(4);rectangle.SetHeight(5);}vararea=rectangle.GetArea();rectangle.Render(area);}}varshapes=new[]{newRectangle(),newRectangle(),newSquare()};RenderLargeRectangles(shapes);

⬆ back to top

Interface Segregation Principle (ISP)

ISP states that "Clients should not be forced to depend upon interfaces that they do not use."

A good example to look at that demonstrates this principle is forclasses that require large settings objects. Not requiring clients to setup huge amounts of options is beneficial, because most of the time they won't need all of the settings. Making them optional helps prevent having a "fat interface".

Bad:

publicinterfaceIEmployee{voidWork();voidEat();}publicclassHuman:IEmployee{publicvoidWork(){// ....working}publicvoidEat(){// ...... eating in lunch break}}publicclassRobot:IEmployee{publicvoidWork(){//.... working much more}publicvoidEat(){//.... robot can't eat, but it must implement this method}}

Good:

Not every worker is an employee, but every employee is an worker.

publicinterfaceIWorkable{voidWork();}publicinterfaceIFeedable{voidEat();}publicinterfaceIEmployee:IFeedable,IWorkable{}publicclassHuman:IEmployee{publicvoidWork(){// ....working}publicvoidEat(){//.... eating in lunch break}}// robot can only workpublicclassRobot:IWorkable{publicvoidWork(){// ....working}}

⬆ back to top

Dependency Inversion Principle (DIP)

This principle states two essential things:

  1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
  2. Abstractions should not depend upon details. Details should depend on abstractions.

This can be hard to understand at first, but if you've worked with .NET/.NET Core framework, you've seen an implementation of this principle in the form ofDependency Injection (DI). While they are not identical concepts, DIP keeps high-level modules from knowing the details of its low-level modules and setting them up.It can accomplish this through DI. A huge benefit of this is that it reduces the coupling between modules. Coupling is a very bad development pattern because it makes your code hard to refactor.

Bad:

publicabstractclassEmployeeBase{protectedvirtualvoidWork(){// ....working}}publicclassHuman:EmployeeBase{publicoverridevoidWork(){//.... working much more}}publicclassRobot:EmployeeBase{publicoverridevoidWork(){//.... working much, much more}}publicclassManager{privatereadonlyRobot_robot;privatereadonlyHuman_human;publicManager(Robotrobot,Humanhuman){_robot=robot;_human=human;}publicvoidManage(){_robot.Work();_human.Work();}}

Good:

publicinterfaceIEmployee{voidWork();}publicclassHuman:IEmployee{publicvoidWork(){// ....working}}publicclassRobot:IEmployee{publicvoidWork(){//.... working much more}}publicclassManager{privatereadonlyIEnumerable<IEmployee>_employees;publicManager(IEnumerable<IEmployee>employees){_employees=employees;}publicvoidManage(){foreach(varemployeein_employees){_employee.Work();}}}

⬆ back to top

Don’t repeat yourself (DRY)

Try to observe theDRY principle.

Do your absolute best to avoid duplicate code. Duplicate code is bad because it means that there's more than one place to alter something if you need to change some logic.

Imagine if you run a restaurant and you keep track of your inventory: all your tomatoes, onions, garlic, spices, etc. If you have multiple lists that you keep this on, then all have to be updated when you serve a dish with tomatoes in them. If you only have one list, there's only one place to update!

Oftentimes you have duplicate code because you have two or more slightly different things, that share a lot in common, but their differences force you to have two or more separate functions that do much of the same things. Removing duplicate code means creating an abstraction that can handle this set of different things with just one function/module/class.

Getting the abstraction right is critical, that's why you should follow the SOLID principles laid out in theClasses section. Bad abstractions can be worse than duplicate code, so be careful! Having said this, if you can make a good abstraction, do it! Don't repeat yourself, otherwise you'll find yourself updating multiple places anytime you want to change one thing.

Bad:

publicList<EmployeeData>ShowDeveloperList(Developersdevelopers){foreach(vardevelopersindeveloper){varexpectedSalary=developer.CalculateExpectedSalary();varexperience=developer.GetExperience();vargithubLink=developer.GetGithubLink();vardata=new[]{expectedSalary,experience,githubLink};Render(data);}}publicList<ManagerData>ShowManagerList(Managermanagers){foreach(varmanagerinmanagers){varexpectedSalary=manager.CalculateExpectedSalary();varexperience=manager.GetExperience();vargithubLink=manager.GetGithubLink();vardata=new[]{expectedSalary,experience,githubLink};render(data);}}

Good:

publicList<EmployeeData>ShowList(Employeeemployees){foreach(varemployeeinemployees){varexpectedSalary=employees.CalculateExpectedSalary();varexperience=employees.GetExperience();vargithubLink=employees.GetGithubLink();vardata=new[]{expectedSalary,experience,githubLink};render(data);}}

Very good:

It is better to use a compact version of the code.

publicList<EmployeeData>ShowList(Employeeemployees){foreach(varemployeeinemployees){render(new[]{employee.CalculateExpectedSalary(),employee.GetExperience(),employee.GetGithubLink()});}}

⬆ back to top

Testing

Basic concept of testing

Testing is more important than shipping. If you have no tests or aninadequate amount, then every time you ship code you won't be sure that you didn't break anything. Deciding on what constitutes an adequate amount is up to your team, but having 100% coverage (all statements and branches) is how you achieve very high confidence and developer peace of mind. This means that in addition to having a great testing framework, you also need to use agood coverage tool.

There's no excuse to not write tests. There'splenty of good .NET test frameworks, so find one that your team prefers. When you find one that works for your team, then aim to always write tests for every new feature/module you introduce. If your preferred method is Test Driven Development (TDD), that is great, but the main point is to just make sure you are reaching your coverage goals before launching any feature, or refactoring an existing one.

Single concept per test

Ensures that your tests are laser focused and not testing miscellaenous (non-related) things, forcesAAA patern used to make your codes more clean and readable.

Bad:

publicclassMakeDotNetGreatAgainTests{[Fact]publicvoidHandleDateBoundaries(){vardate=newMyDateTime("1/1/2015");date.AddDays(30);Assert.Equal("1/31/2015",date);date=newMyDateTime("2/1/2016");date.AddDays(28);Assert.Equal("02/29/2016",date);date=newMyDateTime("2/1/2015");date.AddDays(28);Assert.Equal("03/01/2015",date);}}

Good:

publicclassMakeDotNetGreatAgainTests{[Fact]publicvoidHandle30DayMonths(){// Arrangevardate=newMyDateTime("1/1/2015");// Actdate.AddDays(30);// AssertAssert.Equal("1/31/2015",date);}[Fact]publicvoidHandleLeapYear(){// Arrangevardate=newMyDateTime("2/1/2016");// Actdate.AddDays(28);// AssertAssert.Equal("02/29/2016",date);}[Fact]publicvoidHandleNonLeapYear(){// Arrangevardate=newMyDateTime("2/1/2015");// Actdate.AddDays(28);// AssertAssert.Equal("03/01/2015",date);}}

Sourehttps://www.codingblocks.net/podcast/how-to-write-amazing-unit-tests

⬆ back to top

Concurrency

Use Async/Await

Summary of Asynchronous Programming Guidelines

NameDescriptionExceptions
Avoid async voidPrefer async Task methods over async void methodsEvent handlers
Async all the wayDon't mix blocking and async codeConsole main method (C# <= 7.0)
Configure contextUseConfigureAwait(false) when you canMethods that require con­text

The Async Way of Doing Things

To Do This ...Instead of This ...Use This
Retrieve the result of a background taskTask.Wait or Task.Resultawait
Wait for any task to completeTask.WaitAnyawait Task.WhenAny
Retrieve the results of multiple tasksTask.WaitAllawait Task.WhenAll
Wait a period of timeThread.Sleepawait Task.Delay

Best practice

The async/await is the best for IO bound tasks (networking communication, database communication, http request, etc.) but it is not good to apply on computational bound tasks (traverse on the huge list, render a hugge image, etc.). Because it will release the holding thread to the thread pool and CPU/cores available will not involve to process those tasks. Therefore, we should avoid using Async/Await for computional bound tasks.

For dealing with computational bound tasks, prefer to useTask.Factory.CreateNew withTaskCreationOptions isLongRunning. It will start a new background thread to process a heavy computational bound task without release it back to the thread pool until the task being completed.

Know Your Tools

There's a lot to learn about async and await, and it's natural to get a little disoriented. Here's a quick reference of solutions to common problems.

Solutions to Common Async Problems

ProblemSolution
Create a task to execute codeTask.Run orTaskFactory.StartNew (not theTask constructor orTask.Start)
Create a task wrapper for an operation or eventTaskFactory.FromAsync orTaskCompletionSource<T>
Support cancellationCancellationTokenSource andCancellationToken
Report progressIProgress<T> andProgress<T>
Handle streams of dataTPL Dataflow or Reactive Extensions
Synchronize access to a shared resourceSemaphoreSlim
Asynchronously initialize a resourceAsyncLazy<T>
Async-ready producer/consumer structuresTPL Dataflow orAsyncCollection<T>

Read theTask-based Asynchronous Pattern (TAP) document.It is extremely well-written, and includes guidance on API design and the proper use of async/await (including cancellation and progress reporting).

There are many new await-friendly techniques that should be used instead of the old blocking techniques. If you have any of these Old examples in your new async code, you're Doing It Wrong(TM):

OldNewDescription
task.Waitawait taskWait/await for a task to complete
task.Resultawait taskGet the result of a completed task
Task.WaitAnyawait Task.WhenAnyWait/await for one of a collection of tasks to complete
Task.WaitAllawait Task.WhenAllWait/await for every one of a collection of tasks to complete
Thread.Sleepawait Task.DelayWait/await for a period of time
Task constructorTask.Run orTaskFactory.StartNewCreate a code-based task

Sourcehttps://gist.github.com/jonlabelle/841146854b23b305b50fa5542f84b20c

⬆ back to top

Error Handling

Basic concept of error handling

Thrown errors are a good thing! They mean the runtime has successfully identified when something in your program has gone wrong and it's letting you know by stopping function execution on the current stack, killing the process (in .NET/.NET Core), and notifying you in the console with a stack trace.

Don't use 'throw ex' in catch block

If you need to re-throw an exception after catching it, use just 'throw'By using this, you will save the stack trace. But in the bad option below,you will lost the stack trace.

Bad:

try{// Do something..}catch(Exceptionex){// Any action something like roll-back or logging etc.throwex;}

Good:

try{// Do something..}catch(Exceptionex){// Any action something like roll-back or logging etc.throw;}

⬆ back to top

Don't ignore caught errors

Doing nothing with a caught error doesn't give you the ability to ever fix or react to said error. Throwing the error isn't much better as often times it can get lost in a sea of things printed to the console. If you wrap any bit of code in atry/catch it means you think an error may occur there and therefore you should have a plan, or create a code path, for when it occurs.

Bad:

try{FunctionThatMightThrow();}catch(Exceptionex){// silent exception}

Good:

try{FunctionThatMightThrow();}catch(Exceptionerror){NotifyUserOfError(error);// Another optionReportErrorToService(error);}

⬆ back to top

Use multiple catch block instead of if conditions.

If you need to take action according to type of the exception,you better use multiple catch block for exception handling.

Bad:

try{// Do something..}catch(Exceptionex){if(exisTaskCanceledException){// Take action for TaskCanceledException}elseif(exisTaskSchedulerException){// Take action for TaskSchedulerException}}

Good:

try{// Do something..}catch(TaskCanceledExceptionex){// Take action for TaskCanceledException}catch(TaskSchedulerExceptionex){// Take action for TaskSchedulerException}

⬆ back to top

Keep exception stack trace when rethrowing exceptions

C# allows the exception to be rethrown in a catch block using thethrow keyword. It is a bad practice to throw a caught exception usingthrow e;. This statement resets the stack trace. Instead usethrow;. This will keep the stack trace and provide a deeper insight about the exception.Another option is to use a custom exception. Simply instantiate a new exception and set its inner exception property to the caught exception with thrownew CustomException("some info", e);. Adding information to an exception is a good practice as it will help with debugging. However, if the objective is to log an exception then usethrow; to pass the buck to the caller.

Bad:

try{FunctionThatMightThrow();}catch(Exceptionex){logger.LogInfo(ex);throwex;}

Good:

try{FunctionThatMightThrow();}catch(Exceptionerror){logger.LogInfo(error);throw;}

Good:

try{FunctionThatMightThrow();}catch(Exceptionerror){logger.LogInfo(error);thrownewCustomException(error);}

⬆ back to top

Formatting

Uses.editorconfig file

Bad:

Has many code formatting styles in the project. For example, indent style isspace andtab mixed in the project.

Good:

Define and maintain consistent code style in your codebase with the use of an.editorconfig file

root=true[*]indent_style=spaceindent_size=2end_of_line= lfcharset= utf-8trim_trailing_whitespace= trueinsert_final_newline= true# C# files[*.cs]indent_size=4# New line preferencescsharp_new_line_before_open_brace= allcsharp_new_line_before_else= truecsharp_new_line_before_catch= truecsharp_new_line_before_finally= truecsharp_new_line_before_members_in_object_initializers= truecsharp_new_line_before_members_in_anonymous_types= truecsharp_new_line_within_query_expression_clauses= true#Code files[*.{cs,csx,vb,vbx}]indent_size=4#Indentation preferencescsharp_indent_block_contents= truecsharp_indent_braces= falsecsharp_indent_case_contents= truecsharp_indent_switch_labels= truecsharp_indent_labels=one_less_than_current# avoidthis. unless absolutely necessarydotnet_style_qualification_for_field= false:suggestiondotnet_style_qualification_for_property= false:suggestiondotnet_style_qualification_for_method= false:suggestiondotnet_style_qualification_for_event= false:suggestion# only use varwhen it's obvious what the variable typeis# csharp_style_var_for_built_in_types= false:none# csharp_style_var_when_type_is_apparent= false:none# csharp_style_var_elsewhere= false:suggestion# use language keywords instead of BCL typesdotnet_style_predefined_type_for_locals_parameters_members= true:suggestiondotnet_style_predefined_type_for_member_access= true:suggestion# name all constant fieldsusingPascalCasedotnet_naming_rule.constant_fields_should_be_pascal_case.severity=suggestiondotnet_naming_rule.constant_fields_should_be_pascal_case.symbols=constant_fieldsdotnet_naming_rule.constant_fields_should_be_pascal_case.style=pascal_case_styledotnet_naming_symbols.constant_fields.applicable_kinds=fielddotnet_naming_symbols.constant_fields.required_modifiers=constdotnet_naming_style.pascal_case_style.capitalization= pascal_case#staticfields should have s_ prefixdotnet_naming_rule.static_fields_should_have_prefix.severity=suggestiondotnet_naming_rule.static_fields_should_have_prefix.symbols=static_fieldsdotnet_naming_rule.static_fields_should_have_prefix.style=static_prefix_styledotnet_naming_symbols.static_fields.applicable_kinds=fielddotnet_naming_symbols.static_fields.required_modifiers=staticdotnet_naming_style.static_prefix_style.required_prefix=s_dotnet_naming_style.static_prefix_style.capitalization=camel_case# internal and privatefields shouldbe _camelCasedotnet_naming_rule.camel_case_for_private_internal_fields.severity=suggestiondotnet_naming_rule.camel_case_for_private_internal_fields.symbols=private_internal_fieldsdotnet_naming_rule.camel_case_for_private_internal_fields.style=camel_case_underscore_styledotnet_naming_symbols.private_internal_fields.applicable_kinds=fielddotnet_naming_symbols.private_internal_fields.applicable_accessibilities=private,internaldotnet_naming_style.camel_case_underscore_style.required_prefix=_dotnet_naming_style.camel_case_underscore_style.capitalization=camel_case#Code styledefaultsdotnet_sort_system_directives_first= truecsharp_preserve_single_line_blocks= truecsharp_preserve_single_line_statements= false#Expression-level preferencesdotnet_style_object_initializer= true:suggestiondotnet_style_collection_initializer= true:suggestiondotnet_style_explicit_tuple_names= true:suggestiondotnet_style_coalesce_expression= true:suggestiondotnet_style_null_propagation= true:suggestion# Expression-bodied memberscsharp_style_expression_bodied_methods= false:nonecsharp_style_expression_bodied_constructors= false:nonecsharp_style_expression_bodied_operators= false:nonecsharp_style_expression_bodied_properties= true:nonecsharp_style_expression_bodied_indexers= true:nonecsharp_style_expression_bodied_accessors= true:none# Pattern matchingcsharp_style_pattern_matching_over_is_with_cast_check= true:suggestioncsharp_style_pattern_matching_over_as_with_null_check= true:suggestioncsharp_style_inlined_variable_declaration= true:suggestion# Null checking preferencescsharp_style_throw_expression= true:suggestioncsharp_style_conditional_delegate_call= true:suggestion# Space preferencescsharp_space_after_cast= falsecsharp_space_after_colon_in_inheritance_clause= truecsharp_space_after_comma= truecsharp_space_after_dot= falsecsharp_space_after_keywords_in_control_flow_statements= truecsharp_space_after_semicolon_in_for_statement= truecsharp_space_around_binary_operators= before_and_aftercsharp_space_around_declaration_statements= do_not_ignorecsharp_space_before_colon_in_inheritance_clause= truecsharp_space_before_comma= falsecsharp_space_before_dot= falsecsharp_space_before_open_square_brackets= falsecsharp_space_before_semicolon_in_for_statement= falsecsharp_space_between_empty_square_brackets= falsecsharp_space_between_method_call_empty_parameter_list_parentheses= falsecsharp_space_between_method_call_name_and_opening_parenthesis= falsecsharp_space_between_method_call_parameter_list_parentheses= falsecsharp_space_between_method_declaration_empty_parameter_list_parentheses= falsecsharp_space_between_method_declaration_name_and_open_parenthesis= falsecsharp_space_between_method_declaration_parameter_list_parentheses= falsecsharp_space_between_parentheses= falsecsharp_space_between_square_brackets= false[*.{asm,inc}]indent_size=8#Xml projectfiles[*.{csproj,vcxproj,vcxproj.filters,proj,nativeproj,locproj}]indent_size=2#Xml configfiles[*.{props,targets,config,nuspec}]indent_size=2[CMakeLists.txt]indent_size=2[*.cmd]indent_size=2

⬆ back to top

Comments

Avoid positional markers

They usually just add noise. Let the functions and variable names along with the proper indentation and formatting give the visual structure to your code.

Bad:

////////////////////////////////////////////////////////////////////////////////// Scope Model Instantiation////////////////////////////////////////////////////////////////////////////////varmodel=new[]{menu:'foo',nav:'bar'};////////////////////////////////////////////////////////////////////////////////// Action setup////////////////////////////////////////////////////////////////////////////////voidActions(){// ...};

Bad:

#region Scope Model Instantiationvarmodel={menu:'foo',nav:'bar'};#endregion#region Action setupvoidActions(){// ...};#endregion

Good:

varmodel=new[]{menu:'foo',nav:'bar'};voidActions(){// ...};

⬆ back to top

Don't leave commented out code in your codebase

Version control exists for a reason. Leave old code in your history.

Bad:

doStuff();// doOtherStuff();// doSomeMoreStuff();// doSoMuchStuff();

Good:

doStuff();

⬆ back to top

Don't have journal comments

Remember, use version control! There's no need for dead code, commented code, and especially journal comments. Usegit log to get history!

Bad:

/** * 2018-12-20: Removed monads, didn't understand them (RM) * 2017-10-01: Improved using special monads (JP) * 2016-02-03: Removed type-checking (LI) * 2015-03-14: Added combine with type-checking (JR) */publicintCombine(inta,intb){returna+b;}

Good:

publicintCombine(inta,intb){returna+b;}

⬆ back to top

Only comment things that have business logic complexity

Comments are an apology, not a requirement. Good codemostly documents itself.

Bad:

publicintHashIt(stringdata){// The hashvarhash=0;// Length of stringvarlength=data.length;// Loop through every character in datafor(vari=0;i<length;i++){// Get character code.constchar=data.charCodeAt(i);// Make the hashhash=((hash<<5)-hash)+char;// Convert to 32-bit integerhash&=hash;}}

Better but still Bad:

publicintHashIt(stringdata){varhash=0;varlength=data.length;for(vari=0;i<length;i++){constchar=data.charCodeAt(i);hash=((hash<<5)-hash)+char;// Convert to 32-bit integerhash&=hash;}}

If a comment explains WHAT the code is doing, it is probably a useless comment and can be implemented with a well named variable or function. The comment in the previous code could be replaced with a function namedConvertTo32bitInt so this comment is still useless.However it would be hard to express by code WHY the developer chose djb2 hash algorithm instead of sha-1 or another hash function. In that case a comment is acceptable.

Good:

publicintHash(stringdata){varhash=0;varlength=data.length;for(vari=0;i<length;i++){varcharacter=data[i];// use of djb2 hash algorithm as it has a good compromise// between speed and low collision with a very simple implementationhash=((hash<<5)-hash)+character;hash=ConvertTo32BitInt(hash);}returnhash;}privateintConvertTo32BitInt(intvalue){returnvalue&value;}

⬆ back to top

Other Clean Code Resources

Other Clean Code Lists

Style Guides

  • Google Styleguides - This project holds the C++ Style Guide, Swift Style Guide, Objective-C Style Guide, Java Style Guide, Python Style Guide, R Style Guide, Shell Style Guide, HTML/CSS Style Guide, JavaScript Style Guide, AngularJS Style Guide, Common Lisp Style Guide, and Vimscript Style Guide
  • Django Styleguide - Django styleguide used in HackSoft projects
  • nodebestpractices - The Node.js best practices list

Tools

  • codemaid - open source Visual Studio extension to cleanup and simplify our C#, C++, F#, VB, PHP, PowerShell, JSON, XAML, XML, ASP, HTML, CSS, LESS, SCSS, JavaScript and TypeScript coding
  • Sharpen - Visual Studio extension that intelligently introduces new C# features into your existing code base
  • tslint-clean-code - TSLint rules for enforcing Clean Code

Cheatsheets


Contributors

Thank you to all the people who have already contributed toclean-code-dotnet project

contributors

Backers

Love our work and help us continue our activities? [Become a backer]

Sponsors

Become a sponsor and get your logo in our README on Github with a link to your site. [Become a sponsor]

License

CC0

To the extent possible under law,thangchung has waived all copyright and related or neighboring rights to this work.


[8]ページ先頭

©2009-2025 Movatter.jp