Skip to content

Clean code is the art of writing code that humans can understand. Learn how to write C# in a style that's easy to write, read, and maintain. This course is filled with clear comparisons between "dirty" C# code to avoid, and the "clean" C# equivalent. Check out the course at https://www.pluralsight.com/courses/csharp-clean-coding-principles

License

Notifications You must be signed in to change notification settings

learnasyougo/CleanCodingPrinciplesInCSharp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 

Repository files navigation

About

Clean code is the art of writing code that humans can understand. Learn how to write C# in a style that's easy to write, read, and maintain. This course is filled with clear comparisons between "dirty" C# code to avoid, and the "clean" C# equivalent. Check out the course at https://www.pluralsight.com/courses/csharp-clean-coding-principles

Table of contents

  1. Intro
    1. Code is communication
    2. Reasons to care
    3. We are ahtors
  2. Clean Coding Principles
    1. Three Core Clean Coding Principles
  3. Naming
    1. Why naming matters
      1. Classes
      2. Methods
      3. Abbreviations
      4. Booleans

Intro

Code is Communication

Code is like humor, if you have to explain it, it's bad. ~ Cory House

Programming is the art of telling another human what one wants the computer to do. ~ Donald Knuth

Any fool can write code that a computer can understand. Good programmers write code that humans can understand. ~ Martin Fowler

Reasons to Care

  1. Reading is harder than writing
  2. Technical debt is despressing
  3. Laziness (extra care in code up front, so it's easier to adapt/read)
  4. Sloppiness equals slowing us down
  5. Don't be a verb (aka this code has been Jimmified)...

We are authors

Each line of code is likely to be read 10 times by another human, so we have to strive to be proper authors, as in fact we are. Authors are writers of a book, article or text and:

  • one who practices writing as a profession (writing code)
  • one who writes or constructs an electronic document or system (_yes, we make systems)
  • an originator or creator of a theory or plan (we do fall under this category as well)

An author strive to tell a compelling, clear, story. We have to take this in mind when doing so. The tools and conventions of clean code principles help us to achieve this.

Clean Coding Principles

Three Core Clean Coding Principles

  1. Right tool for the job. Sometimes the hardest part is selecting the right technology for the job.
  2. High signal to noise ratio. Remove noise so the reader can easily extract the intent, intstead of dabbing through the noise.
  3. Self-documenting. Comments aren't the key, but expressive code is.

Picking the right tool for the job

Let's use lunatic's favorite tool for everything. Not every technology is a good fit for the readibility, the security, the performance, etc... Creatively using the wrong tool isn't something to brag about

Example: using regex to validate an e-mail address of standard RFC822. This is simple not readible, referring to http://ex-parrot.com/~pwd/Mail-RFC822-Address.html.

Watch for boundaries

Each technology has a specific purpose, html is for content, css seperates style for the content markup, etc... Some things to look out for.

  • storing html in sql
  • html in a js string, or js in html
  • inline css styles
  • dynamic sql to generate your own sql
  • dynamic js made at c#

Example:

  • bad practice var string = @"<script type=""text/javascript"">...</script>"; this.Header.Controls.Add(new LiteralControl("\r\n" + script));
  • good practice
    • put the js inside a seperate js file
    • use C# to load up or inject dynmaic data in the header in a http call.

One language per file; avoid using one language to write another language/format via strings. Search, use and leverage libraries that do this for you, in stead of doing it yourself.

Each technology is potentially evil

  • linq-2-sql could be potentially evil when it's used for massive queries or outer joins
  • sql is great but should embed display logic
  • c# is great but should never be used to write JS or HTML in strings, leverage a library for that

Maximing signal to noise

  • TED rules
    • Terse: your code should not be excessively wordy
    • Expresive: clear what the code is trying to do
    • Does one thing: clear responsibily, and does this one thing well
  • When we read code our brain is the compiler. Humans can hold around 7 items in short term memory. This implies that it has an effect on
    • number of parameters per method
    • number of methods in a class
    • number of varibales currently in scope
  • Refactor regurarely, as noise (or mess) builds over time. It builds quietly and slowly.

DRY Don't repeat yourself

  • It's same as DB normalization
  • Copy and paste is often a design problem (aka duplication). Avoid this as it creates a maintenance problem.
    • Try to refactor.
    • But be careful, not all code that looks the same has the same intent.

Self-documenting code

Understanding the original programmer's intent is the most difficult problem. ~ Fjelstad & Hamlen (1979)

  • Express intent clearly
  • Use layers of abstraction, so the reader can walk through the different levels of detail
  • Format for readibility
  • Favor code over comments, comments are noise, if the code can tell the story

Naming

Why naming matters

Consider the following code snipper

var p = new List<decimal>() { 5.50m, 1.48m };
decimal t = 0;
foreach(var i in p)
   t += i;
return t;
  • Intent is a problem, what did the programmer meant to do here?

Consider the cleaned up version, the only changes being done here are

  • using different variable names that describe intent
  • using spaces (breaklines), as in a book we use paragrapgs, to seperate different blocks and make it easier for the reader to understand the different parts of
    • setting up
    • executing logic
    • return a value
var prices = new List<decimal>() { 5.50m, 1.48m };
decimal total = 0;

foreach(var price in prices)
   total += price;

return total;

Classes

Consider following class names: WebsiteBO, Utility, Common, MyFunctions, JimmysUtils, x*Manager*, x*Processor*, x*Info*. Poorly named classes are magnets to throw code in this spot in stead of making a new class with a good name that shows the purpose of the class name.

A well designed class should have a single responsibility, and the name should reflect that. Some guidelines:

  • It's a noun, not a verb.
  • Be as specific as possible (SRP).
  • Name should lead to SRP.
  • Avoid generic prefixes of suffixes such as Manager.

Methods

Abbreviations

Booleans

About

Clean code is the art of writing code that humans can understand. Learn how to write C# in a style that's easy to write, read, and maintain. This course is filled with clear comparisons between "dirty" C# code to avoid, and the "clean" C# equivalent. Check out the course at https://www.pluralsight.com/courses/csharp-clean-coding-principles

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published