29
Code Formatting Correctly Formatting the Source Code Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training http://www.nakov.com http://codecourse.telerik.com/

9. Code Formatting - Correctly Formatting the Source Code

Embed Size (px)

DESCRIPTION

High-Quality Code @ Telerik AcademyTelerik Software Academy: http://codecourse.telerik.com/The website and all video materials are in Bulgarian Content:Why Do We Need Code Formatting?Formatting MethodsFormatting TypesCommon MistakesAlignmentsRecommended Practices

Citation preview

Page 1: 9. Code Formatting - Correctly Formatting the Source Code

Code FormattingCorrectly Formatting the Source Code

Svetlin Nakov

Telerik Software Academyacademy.telerik.com

Manager Technical Traininghttp://www.nakov.com

http://codecourse.telerik.com/

Page 2: 9. Code Formatting - Correctly Formatting the Source Code

Table of Contents

1. Why Do We Need Code Formatting?

2. Formatting Methods

3. Formatting Types

4. Common Mistakes

5. Alignments

6. Recommended Practices

2

Page 3: 9. Code Formatting - Correctly Formatting the Source Code

Code Formatting

Why Do We Need It?

Page 4: 9. Code Formatting - Correctly Formatting the Source Code

Why Code Needs Formatting?

4

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 ( ) ; }

Page 5: 9. Code Formatting - Correctly Formatting the Source Code

Code Formatting Fundamentals

Good formatting goals To improve code readability

To improve code maintainability

Fundamental principle of code formatting:

Any formatting style that follows the above principle is good

Any other formatting is not good 5

The formating of the source code should disclose its logical structure.

Page 6: 9. Code Formatting - Correctly Formatting the Source Code

Formatting Blocks in C# Put { and } alone on a line under the corresponding parent block

Indent the block contents by a single [Tab] Don't indent with spaces

Example:

6

if (some condition){ // Block contents indented by a single [Tab] // Don't use spaces for indentation}

Page 7: 9. Code Formatting - Correctly Formatting the Source Code

Formatting Blocks in Java

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] Don't indent with spaces

Example:

7

if (some condition) { // Block contents indented by a single [Tab] // Don't use spaces for indentation}

Page 8: 9. Code Formatting - Correctly Formatting the Source Code

Empty Lines between Methods

Use empty line for separation between methods:

8

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

(there is no space to do it here)

Page 9: 9. Code Formatting - Correctly Formatting the Source Code

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

9

public class IndentationExample{ private int Zero() { return 0; }}

The entire method is indented with a

single [Tab]

Method body is also indented

Page 10: 9. Code Formatting - Correctly Formatting the Source Code

Brackets in Methods Declaration

Brackets in the method declaration should be formatted as follows:

Don't use spaces between the brackets:

The same applies for if-conditions and for-loops:

10

private static ulong CalcFactorial(uint num)

private static ulong CalcFactorial ( uint num )

private static ulong CalcFactorial (uint num)

if (condition) { … }

Page 11: 9. Code Formatting - Correctly Formatting the Source Code

Separating Parameters Separate method parameters by comma followed by a space Don't put comma before the space Examples:

Incorrect examples:

11

private void RegisterUser(string username, string password)

private void RegisterUser(string username,string password)private void RegisterUser(string username ,string password)private void RegisterUser(string username , string password)

RegisterUser("nakov", "s3cr3t!p@ssw0rd");

Page 12: 9. Code Formatting - Correctly Formatting the Source Code

Empty Lines in Method Body

Use an empty line to separate logically related sequences of lines:

12

private List<Report> PrepareReports() { List<Report> reports = new List<Report>();

// Create incomes reports Report incomesSalesReport = PrepareIncomesSalesReport(); reports.Add(incomesSalesReport); Report incomesSupportReport = PrepareIncomesSupportReport(); reports.Add(incomesSupportReport);

// Create expenses reports Report expensesPayrollReport = PrepareExpensesPayrollReport(); reports.Add(expensesPayrollReport); Report expensesMarketingReport = PrepareExpensesMarketingReport(); reports.Add(expensesMarketingReport);

return reports;}

Empty line

Empty line

Empty line

Page 13: 9. Code Formatting - Correctly Formatting the Source Code

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

13

Page 14: 9. Code Formatting - Correctly Formatting the Source Code

Formatting Types – Example in C#

14

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; }

(continues on the next slide)

Page 15: 9. Code Formatting - Correctly Formatting the Source Code

Formatting Types – Example in C# (2)

15

// Properties

public string Name { get; set; }

// Methods

public void Breath() { // TODO: breathing process }

public void Bark() { Console.WriteLine("wow-wow"); }

}

Page 16: 9. Code Formatting - Correctly Formatting the Source Code

Formatting Types – Example in Java

16

public class Dog {

// Static variables

public static final string SPECIES = "Canis Lupus Familiaris";

// Instance variables

private int age;

// Constructors

public Dog(String name, int age) { this.setName(name); this.setAge(age); }

// Properties

public String getName() { return this.name }

Page 17: 9. Code Formatting - Correctly Formatting the Source Code

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

Never put the block after if / for / while on the same line!

Always put the { on the next line (in C#)

Always put the { on the same line (in Java)

Never indent with more than one [Tab]

17

Page 18: 9. Code Formatting - Correctly Formatting the Source Code

Conditional Statements and

Loops Formatting – C# Examples Example:

Incorrect examples:

18

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; i++) Console.WriteLine("i={0}", i);

for (int i=0; i<10; i++) { Console.WriteLine("i={0}", i);}

The { and } are

missingNever put multiple

stetements on the same

line!

In C# the { should be on the next line

Page 19: 9. Code Formatting - Correctly Formatting the Source Code

Using Empty Lines Empty lines are used to separate

logically unrelated parts of the source code

Don't put empty lines when not needed!

19

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

Page 20: 9. Code Formatting - Correctly Formatting the Source Code

Misplaced Empty Lines – Example

20

public static void PrintList(List<int> ints) { Console.Write("{ "); foreach (int item in ints) { Console.Write(item);

Console.Write(" ");

} Console.WriteLine("}");}static void Main(){ // ...}

What do these empty lines server for?

Page 21: 9. Code Formatting - Correctly Formatting the Source Code

Breaking Long Lines Break long lines after punctuation Indent the second line by single [Tab] Do not additionally indent the third

line Examples:

21

DictionaryEntry<K, V> newEntry = new DictionaryEntry<K, V>( oldEntry.Key, oldEntry.Value);

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){ …

Page 22: 9. Code Formatting - Correctly Formatting the Source Code

Incorrect Ways ToBreak Long Lines (in

C#)

22

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);

Page 23: 9. Code Formatting - Correctly Formatting the Source Code

In C# use single [Tab] after breaking a long line:

In Java use double [Tab] in the carried long lines:

Breaking Long Linesin C# and Java

23

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;}

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;}

Page 24: 9. Code Formatting - Correctly Formatting the Source Code

Alignments All types of alignments are considered harmful Alignments are hard-to-maintain!

Incorrect examples:

24

int count = 0;DateTime date = DateTine.Now.Date;Student student = new Student();List<Student> students = new List<Student>();

matrix[x, y] == 0;matrix[x + 1, y + 1] == 0;matrix[2 * x + y, 2 * y + x] == 0;matrix[x * y, x * y] == 0;

Think about renaming Student to

SchoolStudent

Page 25: 9. Code Formatting - Correctly Formatting the Source Code

Recommended Practices

Break long lines after punctuation Indent the second line by single [Tab] Do not additionally indent the third

line Examples:

25

DictionaryEntry<K, V> newEntry = new DictionaryEntry<K, V>( oldEntry.Key, oldEntry.Value);

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){ …

Page 26: 9. Code Formatting - Correctly Formatting the Source Code

Automated Tools

Take advantage of your IDE to help formatting the code [Shift+Ctrl+F] Automatic alignment Indentation

Style Code analysis Visual Studio – StyleCop

http://code.msdn.microsoft.com/sourceanalysis

Eclipse – CheckStyle

http://sourceforge.net/projects/eclipse-cs/

26

Page 27: 9. Code Formatting - Correctly Formatting the Source Code

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезания

ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NETкурсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGap

free C# book, безплатна книга C#, книга Java, книга C#Дончо Минков - сайт за програмиранеНиколай Костов - блог за програмиранеC# курс, програмиране, безплатно

?

? ? ??

?? ?

?

?

?

??

?

?

? ?

Questions?

?

Code Formatting

http://academy.telerik.com

Page 28: 9. Code Formatting - Correctly Formatting the Source Code

Homework

1. Format correctly the following source code:

C# code given in the file events.cs.

Java code given in the file BASE64.java.

PHP code given in the file utils.php.

Use the official code conventions for C# / Java / PHP:

Official C# Coding Conventions (MSDN)

Official Java Code Conventions (by Oracle)

Zend code convention for PHP28

Page 29: 9. Code Formatting - Correctly Formatting the Source Code

Free Trainings @ Telerik Academy

“High-Quality Programming Code" course @ Telerik Academy codecourse.telerik.com

Telerik Software Academy academy.telerik.com

Telerik Academy @ Facebook facebook.com/TelerikAcademy

Telerik Software Academy Forums forums.academy.telerik.com