Topics covered:
- Why Do We Need Code Formatting?
- Formatting Methods
- Formatting Types
- Common Mistakes
- Alignments
- Automated Tools
Video (in Bulgarian)
Presentation Content
Code Formatting
Why do we need it? How can white spaces and parenthesis help us?
Any fool can write code that a computer can understand. Good programmers write code that humans can understand.
public const string FILE_NAME
="example.bin" ; static void Main ( ){
FileStream fs= new FileStream(FILE_NAME,FileMode
. CreateNew) // Create the writer for data .
;BinaryWriter w=new BinaryWriter ( fs );
// Write data to Test.data.
for( int i=0;i<11;i++){w.Write((int)i);}w .Close();
fs . Close ( ) // Create the reader for data.
;fs=new FileStream(FILE_NAME,FileMode. Open
, FileAccess.Read) ;BinaryReader r
= new BinaryReader(fs); // Read data from Test.data.
for (int i = 0; i < 11; i++){ Console .WriteLine
(r.ReadInt32 ())
;}r . Close ( ); fs . Close ( ) ; }
- Good formatting goals
- To improve code readability
- To improve code maintainability
- Fundamental principle of code formatting:
- Any (consistent) formatting style that follows the above principle is good
- Good formatting don’t affect speed, memory use or other aspects of the program
Formatting Blocks in C#
- Put { and } alone on a line under the corresponding parent block
- Indent the block contents by a single [Tab]
- Visual Studio will replace the [Tab] with 4 spaces
- Example:
if (some condition)
{
// Block contents indented by a single [Tab]
// VS will replace the [Tab] with 4 spaces
}
Formatting Blocks in JS
- Put { at the end of the block and } alone on a line under the corresponding parent block
- Indent the block contents by a single [Tab]
- [tab] or spaces depends on the team style
- Example:
if (some condition) {
// Block contents indented by a single [Tab]
// Choosing between [tab] and spaces depends
// on project formatting style
}
Why are Brackets Obligatory?
// swap left and right elements for whole array
for (var i = 0; i < MaxElements; i++)
{
leftElement = left[i];
left[i] = right[i];
right[i] = leftElement;
}
// swap left and right elements for whole array
for ( var i=0; i<MaxElements; i++ )
leftElement = left[i];
left[i] = right[i];
right[i] = leftElement;
Why are Brackets Obligatory?
x = 3+4 * 2+7;
x = (3 + 4) * (2 + 7);
Empty Lines between methods
- Use empty line for separation between methods:
public class Factorial
{
private static ulong CalcFactorial(uint num)
{
if (num == 0)
{
return 1;
}
else
{
return num * CalcFactorial(num - 1);
}
}
static void Main()
{
ulong factorial = CalcFactorial(5);
Console.WriteLine(factorial);
}
}
- Leave empty line between methods
- Always use { and } after if
Methods Indentation
- Methods should be indented with a single [Tab] from the class body
- Methods body should be indented with a single [Tab] as well
public class Indentation_Example_
{
private int Zero()
{
return 0;
}
}
- The entire method is indented with a single [Tab]
- Method body is also indented
Brackets in Methods Declaration
- Brackets in the method declaration should be formatted as follows:
private static ulong CalcFactorial(uint num)
- Don’t use spaces between the brackets:
private static ulong CalcFactorial ( uint num )
private static ulong CalcFactorial (uint num)
- The same applies for if-conditions and for-loops:
if (condition) { … }
for (int i = 0; i < 10; i++) { … }
Separating Parameters
- Separate method parameters by comma followed by a space
- Don’t put space before the comma
- Correct examples:
private void RegisterUser(string username, string password);
RegisterUser("academy", "s3cr3t!p@ssw0rd");
- Incorrect examples:
private void RegisterUser(string username,string password)
private void RegisterUser(string username ,string password)
private void RegisterUser(string username , string password)
Empty Lines
- Use an empty line to separate logically related sequences of lines:
private List<Report> PrepareReports()
{
List<Report> reports = new List<Report>();
// Create incomes reports
Report incomesSalesReport = PrepareIncomesSalesReport();
Report incomesSupportReport = PrepareIncomesSupportReport();
reports.Add(incomesSalesReport, incomesSupportReport);
// Create expenses reports
Report expensesPayrollReport = PrepareExpensesPayrollReport();
Report expensesMarketingReport = PrepareExpensesMarketingReport();
reports.Add(expensesPayrollReport, expensesMarketingReport);
return reports;
}
Formatting Types
- Formatting classes / structures / interfaces / enumerations
- Indent the class body with a single [Tab]
- Use the following order of definitions:
- Constants, delegates, inner types, fields, constructors, properties, methods
- Static members, public members, protected members, internal members, private members
- The above order of definitions is not the only possible correct one
Formatting Types – Example in C#
public class Dog
{
// Static variables
public const string SPECIES = "Canis Lupus Familiaris";
// Instance variables
private int age;
// Constructors
public Dog(string name, int age)
{
this.Name = name;
this.Age = age;
}
// Properties
public string Name { get; set; }
// Methods
public void Breath()
{
// TODO: breathing process
}
public void Bark()
{
Console.WriteLine("wow-wow");
}
}
Formatting Conditional Statements and Loops
- Formatting conditional statements and loops
- Always use { } block after if / for / while, even when a single operator follows
- Indent the block body after if / for / while
- Always put a new line after a if / for / while block!
- Always put the { on the next line (in C#)
- Always put the { on the same line (in JavaScript)
- Never indent with more than one [Tab]
Conditional Statements and Loops Formatting – Examples in C#
- Correct examples:
for (int i = 0; i < 10; i++)
{
Console.WriteLine("i={0}", i);
}
- Incorrect examples:
for (int i = 0; i < 10; i++)
Console.WriteLine("i={0}", i);
for (int i = 0; i < 10; i++) Console.WriteLine("i={0}", i);
for (int i = 0; i < 10;) {
Console.WriteLine("i={0}", i); i++; Console.WriteLine();
}
- The { and } are missing
- Never put multiple statements on the same line!
- In C# the { should be on the next line
Using Empty Lines
- Empty lines are used to separate logically unrelated parts of the source code
- Don’t put empty lines when not needed!
public static void PrintList(List<int> ints)
{
Console.Write("{ ");
foreach (int item in ints)
{
Console.Write(item);
Console.Write(" ");
}
Console.WriteLine("}");
}
static void Main()
{
// …
- An empty line separates the methods
- An empty line after the foreach block
Misplaced Empty Lines – Example
for (int i = 0; i < 10;)
{
Console.WriteLine("i={0}", i);
i++;
Console.WriteLine();
}
- What do these empty lines serve for?
Breaking Long Lines
- Break long lines after punctuation
- Indent the second line by single [Tab]
- Do not additionally indent the third line
- Examples:
if (matrix[x, y] == 0 || matrix[x-1, y] == 0 ||
matrix[x+1, y] == 0 || matrix[x, y-1] == 0 ||
matrix[x, y+1] == 0)
{ …
public void GetAllAbstractPaintings()
{
var paintings = this.Database.Paintings.All()
.Where(x => x.PaintingStyle == PaintingStyleType.Abstract)
.OrderBy(x => x.Price)
.ThenBy(x => x.DateCreated)
.Select(x => x.OriginalPaintingPath)
.ToList();
}
Incorrect ways to break long lines (in C#)
if (matrix[x, y] == 0 || matrix[x-1, y] ==
0 || matrix[x+1, y] == 0 || matrix[x,
y-1] == 0 || matrix[x, y+1] == 0)
{ …
if (matrix[x, y] == 0 || matrix[x-1, y] == 0 ||
matrix[x+1, y] == 0 || matrix[x, y-1] == 0 ||
matrix[x, y+1] == 0)
{ …
DictionaryEntry<K, V> newEntry
= new DictionaryEntry<K, V>(oldEntry
.Key, oldEntry.Value);
Breaking Long Lines in C# and JavaScript
- In C# use single [Tab] after breaking a long line:
if (matrix[x, y] == 0 || matrix[x-1, y] == 0 ||
matrix[x+1, y] == 0 || matrix[x, y-1] == 0 ||
matrix[x, y+1] == 0)
{
matrix[x, y] == 1;
}
- In JavaScript use double [Tab] in the carried long lines:
if (matrix[x, y] == 0 || matrix[x-1, y] == 0 ||
matrix[x+1, y] == 0 || matrix[x, y-1] == 0 ||
matrix[x, y+1] == 0) {
matrix[x, y] == 1;
}
Alignments
- All types of alignments are considered harmful
- Alignments are hard-to-maintain!
- Modifying one line of code shouldn’t require modifying several others
- Incorrect examples:
public void NotCool()
{
var student = new Student("Ivan", "Kolev", 21);
var studentGrades = new List<int>() { 2, 3, 4, 5, 6 };
var school = new SMG("Kopernik");
var studenstInSchool = new List<Student>();
}
Automated Tools
- Take advantage of your IDE to help formatting the code [Ctrl+K+D]
- Automatic alignment
- Indentation
- Style Code analysis
- Visual Studio – StyleCop
- Eclipse – CheckStyle
- JSHint, JSLint – JavaScript code analysis (all IDEs)