Your SlideShare is downloading. ×
0
Code Formatting                      Correctly Formatting the Source CodeSvetlin NakovManager Technical Traininghttp://www...
Table of Contents1.   Why Do We Need Code Formatting?2.   Formatting Methods3.   Formatting Types4.   Common Mistakes5.   ...
Code Formatting Why Do We Need It?
Why Code Needs Formatting?public   const     string                    FILE_NAME="example.bin" ; static void Main      (  ...
Code Formatting Fundamentals Good formatting goals  To improve code readability  To improve code maintainability Funda...
Formatting Blocks in C# Put {and } alone on a line under the corresponding parent block Indent the block contents by a s...
Formatting Blocks in Java Put {at the end of the block and } alone on a line under the corresponding parent block Indent...
Empty Lines between Methods   Use empty line for separation between methods:    public class Factorial    {      private ...
Methods Indentation Methods should be indented with a single [Tab] from the class body Methods body should         be in...
Brackets in Methods Declaration Brackets in the method declaration              should be formatted as follows:  private ...
Separating Parameters Separate method parameters by comma followed by a space  Dont put comma before the space  Example...
Empty Lines in Method Body   Use an empty line to separate logically related    sequences of lines:private List<Report> P...
Formatting Types Formatting classes / structures    / interfaces / enumerations   Indent the class body with a single [T...
Formatting Types –                             Example in C#public class Dog{  // Static variables public const string SPE...
Formatting Types –                             Example in C# (2)    // Properties    public string Name { get; set; }    /...
Formatting Types –                                Example in Javapublic class Dog {  // Static variables  public static fi...
Formatting Conditional                     Statements and Loops Formatting conditional   statements and loops  Always us...
Conditional Statements and              Loops Formatting – C# Examples Example:  for (int i=0; i<10; i++)  {    Console.W...
Using Empty Lines   Empty lines are used to separate logically    unrelated parts of the source code    public static voi...
Misplaced Empty Lines – Examplepublic static void PrintList(List<int> ints){  Console.Write("{ ");  foreach (int item in i...
Breaking Long Lines   Break long lines after punctuation   Indent the second line by single [Tab]   Do not additionally...
Incorrect Ways To                   Break Long Lines (in C#)if (matrix[x, y] == 0 || matrix[x-1, y] ==  0 || matrix[x+1, y...
Breaking Long Lines                                    in C# and Java   In C# use single [Tab] after breaking a long line...
Alignments All types of alignments are considered harmful   Alignments are hard-to-maintain! Incorrect examples:  int  ...
Recommended Practices   Break long lines after punctuation   Indent the second line by single [Tab]   Do not additional...
Automated Tools Take advantage of your IDE to help formatting the code [Shift+Ctrl+F]   Automatic alignment   Indentati...
Code Formatting    курсове и уроци по програмиране, уеб дизайн – безплатно     BG Coder - онлайн състезателна система - on...
Homework1.   Format correctly the following source code:      C# code given in the file events.cs.      Java code given ...
Free Trainings @ Telerik Academy “High-Quality   Programming Code"    course @ Telerik Academy       codecourse.telerik....
Upcoming SlideShare
Loading in...5
×

9. Code Formatting - Correctly Formatting the Source Code

611

Published on

High-Quality Code @ Telerik Academy
Telerik Software Academy: http://codecourse.telerik.com/
The website and all video materials are in Bulgarian
Content:
Why Do We Need Code Formatting?
Formatting Methods
Formatting Types
Common Mistakes
Alignments
Recommended Practices

Published in: Education, Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
611
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
66
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Transcript of "9. Code Formatting - Correctly Formatting the Source Code"

  1. 1. Code Formatting Correctly Formatting the Source CodeSvetlin NakovManager Technical Traininghttp://www.nakov.comTelerik Software Academyacademy.telerik.com
  2. 2. Table of Contents1. Why Do We Need Code Formatting?2. Formatting Methods3. Formatting Types4. Common Mistakes5. Alignments6. Recommended Practices 2
  3. 3. Code Formatting Why Do We Need It?
  4. 4. Why Code Needs Formatting?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 ( ) ; } 4
  5. 5. Code Formatting Fundamentals Good formatting goals  To improve code readability  To improve code maintainability Fundamental principle of code formatting: The formating of the source code should disclose its logical structure.  Any formatting style that follows the above principle is good  Any other formatting is not good 5
  6. 6. Formatting Blocks in C# Put {and } alone on a line under the corresponding parent block Indent the block contents by a single [Tab]  Dont indent with spaces Example: if (some condition) { // Block contents indented by a single [Tab] // Dont use spaces for indentation } 6
  7. 7. 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]  Dont indent with spaces Example: if (some condition) { // Block contents indented by a single [Tab] // Dont use spaces for indentation } 7
  8. 8. Empty Lines between Methods Use empty line for separation between methods: public class Factorial { private static ulong CalcFactorial(uint num) { if (num == 0) Always use { and } after if return 1; (there is no space to do it here) else return num * CalcFactorial(num - 1); } Leave empty line static void Main() between methods { ulong factorial = CalcFactorial(5); Console.WriteLine(factorial); } } 8
  9. 9. 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 IndentationExample { private int Zero() The entire method is { indented with a single [Tab] return 0; } } Method body is also indented 9
  10. 10. Brackets in Methods Declaration Brackets in the method declaration should be formatted as follows: private static ulong CalcFactorial(uint num) Dont 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) { … } 10
  11. 11. Separating Parameters Separate method parameters by comma followed by a space  Dont put comma before the space  Examples: private void RegisterUser(string username, string password) RegisterUser("nakov", "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) 11
  12. 12. Empty Lines in Method Body Use an empty line to separate logically related sequences of lines:private List<Report> PrepareReports() { List<Report> reports = new List<Report>(); Empty line // Create incomes reports Report incomesSalesReport = PrepareIncomesSalesReport(); reports.Add(incomesSalesReport); Report incomesSupportReport = PrepareIncomesSupportReport(); reports.Add(incomesSupportReport); Empty line // Create expenses reports Report expensesPayrollReport = PrepareExpensesPayrollReport(); reports.Add(expensesPayrollReport); Report expensesMarketingReport = PrepareExpensesMarketingReport(); reports.Add(expensesMarketingReport); return reports;} Empty line 12
  13. 13. 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
  14. 14. 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; } (continues on the next slide) 14
  15. 15. Formatting Types – Example in C# (2) // Properties public string Name { get; set; } // Methods public void Breath() { // TODO: breathing process } public void Bark() { Console.WriteLine("wow-wow"); }} 15
  16. 16. Formatting Types – Example in Javapublic 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 } … 16
  17. 17. 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
  18. 18. Conditional Statements and Loops Formatting – C# Examples Example: for (int i=0; i<10; i++) { Console.WriteLine("i={0}", i); The { and } } are missing Incorrect examples: Never put multiple for (int i=0; i<10; i++) stetements on the Console.WriteLine("i={0}", i); same line! for (int i=0; i<10; i++) Console.WriteLine("i={0}", i); for (int i=0; i<10; i++) { Console.WriteLine("i={0}", i); In C# the { should } be on the next line 18
  19. 19. Using Empty Lines Empty lines are used to separate logically unrelated parts of the source code public static void PrintList(List<int> ints) { Console.Write("{ "); foreach (int item in ints) { Console.Write(item); Console.Write(" "); } Console.WriteLine("}"); An empty line } separates the static void Main() methods { // …  Dont put empty lines when not needed! 19
  20. 20. Misplaced Empty Lines – Examplepublic static void PrintList(List<int> ints){ Console.Write("{ "); foreach (int item in ints) { Console.Write(item); Console.Write(" "); What do these empty lines server for? } Console.WriteLine("}");}static void Main(){ // ...} 20
  21. 21. 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) { … DictionaryEntry<K, V> newEntry = new DictionaryEntry<K, V>( oldEntry.Key, oldEntry.Value); 21
  22. 22. 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); 22
  23. 23. Breaking Long Lines in C# and Java 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 Java 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; } 23
  24. 24. Alignments All types of alignments are considered harmful  Alignments are hard-to-maintain! Incorrect examples: int count = 0; DateTime date = DateTine.Now.Date; Student student = new Student(); List<Student> students = new List<Student>(); matrix[x, y] == 0; Think about matrix[x + 1, y + 1] == 0; renaming Student matrix[2 * x + y, 2 * y + x] == 0; to SchoolStudent matrix[x * y, x * y] == 0; 24
  25. 25. Recommended Practices 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) { … DictionaryEntry<K, V> newEntry = new DictionaryEntry<K, V>( oldEntry.Key, oldEntry.Value); 25
  26. 26. 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
  27. 27. Code Formatting курсове и уроци по програмиране, уеб дизайн – безплатно BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране – Телерик академия форум програмиране, форум уеб дизайн уроци по програмиране и уеб дизайн за ученици ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET http://academy.telerik.com програмиране за деца – безплатни курсове и уроци ASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC безплатен SEO курс - оптимизация за търсачки алго академия – състезателно програмиране, състезаниякурсове и уроци по програмиране, книги – безплатно от Наков курс мобилни приложения с iPhone, Android, WP7, PhoneGap уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop Дончо Минков - сайт за програмиране free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране безплатен курс "Качествен програмен код" безплатен курс "Разработка на софтуер в cloud среда" C# курс, програмиране, безплатно
  28. 28. Homework1. 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 PHP 28
  29. 29. 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
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×