Correctly Formatting the Source Code Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer

Slides:



Advertisements
Similar presentations
Windows Basic and Dynamic Disk Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator Marian Marinov CEO of 1H Ltd.
Advertisements

HTML Forms, GET, POST Methods Tran Anh Tuan Edit from Telerik Academy
Make swiftly iOS development Telerik Academy Telerik Academy Plus.
Amazon S 3, App Engine Blobstore, Google Cloud Storage, Azure Blobs Svetlin Nakov Telerik Software Academy academy.telerik.com.
RPN and Shunting-yard algorithm Ivaylo Kenov Telerik Software Academy academy.telerik.com Technical Assistant
Shortest paths in edge-weighted digraph Krasin Georgiev Technical University of Sofia g.krasin at gmail com Assistant Professor.
Telerik Software Academy Telerik School Academy.
Asynchronous Programming with C# and WinRT
Character sequences, C-strings and the C++ String class, Working with Strings Learning & Development Team Telerik Software Academy.
Correctly Formatting the Source Code Svetlin Nakov Telerik Software Academy academy.telerik.com.
Hybrid or Native?! Doncho Minkov Telerik Software Academy Senior Technical Trainer
Done already for your convenience! Telerik School Academy Unity 2D Game Development.
Processing Sequences of Elements Telerik School Academy C# Fundamentals – Part 1.
C# Fundamentals – Part I
The Business Plan and the Business Model Margarita Antonova Volunteer Telerik Academy academy.telerik.com Business System Analyst Telerik Corporation.
What are ADTs, STL Intro, vector, list, queue, stack Learning & Development Team Telerik Software Academy.
Making JavaScript code by template! Learning & Development Team Telerik Software Academy.
Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training Who, What, Why?
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Accessing SQL Server and MySQL – Live Demo Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Processing Matrices and Multidimensional Tables Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Learning & Development Telerik Software Academy.
Reading and Writing Text Files Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Telerik Software Academy ASP.NET Web Forms.
Classical OOP in JavaScript Classes and stuff Telerik Software Academy
Using Selenium for Mobile Web Testing Powered by KendoUI Telerik QA Academy Atanas Georgiev Senior QA Engineer KendoUI Team.
New features: classes, generators, iterators, etc. Telerik Academy Plus JavaScript.Next.
Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy
Loops, Conditional Statements, Functions Tran Anh Tuan Edit from Telerik Academy
Private/Public fields, Module, Revealing Module Learning & Development Team Telerik Software Academy.
Building Data-Driven ASP.NET Web Forms Apps Telerik Software Academy ASP.NET Web Forms.
Course Introduction Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Telerik Software Academy End-to-end JavaScript Applications.
General and reusable solutions to common problems in software design Vasil Dininski Telerik Software Academy academy.telerik.com Intern at Telerik Academy.
Planning and Tracking Software Quality Yordan Dimitrov Telerik Corporation Team Leader, Team Pulse, Team Leader, Team Pulse, Telerik Corporation,
What you need to know Ivaylo Kenov Telerik Corporation Telerik Academy Student.
Data binding concepts, Bindings in WinJS George Georgiev Telerik Software Academy academy.telerik.com Technical Trainer itgeorge.net.
Pavel Kolev Telerik Software Academy Senior.Net Developer and Trainer
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Doing the Canvas the "easy way"! Learning & Development Telerik Software Academy.
Creating and Running Your First C# Program Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Course Overview Doncho Minkov Telerik Software Academy Technical Trainer
Subroutines in Computer Programming Telerik School Academy C# Fundamentals – Part 1.
Revealing the Secrets of Self-Documenting Code Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer.
Code Formatting Correctly Formatting the Source Code Svetlin Nakov Technical Trainer Software University
Data Types, Primitive Types in C++, Variables – Declaration, Initialization, Scope Telerik Software Academy academy.telerik.com Learning and Development.
The past, the present, the future Learning & Development Team Telerik Software Academy.
Using the Standard.NET Framework Classes Telerik Software Academy C# Fundamentals – Part 2.
Learn to Design Error Steady Code Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
Processing Sequences of Elements Telerik Software Academy C# Fundamentals – Part 2.
Telerik JavaScript Framework Telerik Software Academy Hybrid Mobile Applications.
Building Rock-Solid Software Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Telerik Software Academy Databases.
Things start to get serious Telerik Software Academy JavaScript OOP.
Learning & Development Mobile apps for iPhone & iPad.
Processing Matrices and Multidimensional Tables Telerik Software Academy C# Fundamentals – Part 2.
Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
Code Formatting Formatting the Source Code Correctly SoftUni Team Technical Trainers Software University
Implementing Control Logic in C# Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical trainer
Inheritance, Abstraction, Encapsulation, Polymorphism Telerik Software Academy Mobile apps for iPhone & iPad.
Mocking tools for easier unit testing Telerik Software Academy High Quality Code.
What why and how? Telerik School Academy Unity 2D Game Development.
Windows Security Model Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator
Definition, Constructors, Methods, Access Modifiers, Static/Instance members, Learning & Development Team Telerik Software Academy.
Presentation transcript:

Correctly Formatting the Source Code Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer

1. Why Do We Need Code Formatting? 2. Formatting Methods 3. Formatting Types 4. Common Mistakes 5. Alignments 6. Automated Tools 2

Why Do We Need It?

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 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 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.

 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: 6 if (some condition) { // Block contents indented by a single [Tab] // Block contents indented by a single [Tab] // VS will replace the [Tab] with 4 spaces // VS will replace the [Tab] with 4 spaces}

 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] // Block contents indented by a single [Tab] // Don't use spaces for indentation // Don't use spaces for indentation}

 Use empty line for separation between methods: 8 public class Factorial { private static ulong CalcFactorial(uint num) private static ulong CalcFactorial(uint num) { if (num == 0) if (num == 0) return 1; return 1; else else return num * CalcFactorial(num - 1); return num * CalcFactorial(num - 1); } static void Main() static void Main() { ulong factorial = CalcFactorial(5); ulong factorial = CalcFactorial(5); Console.WriteLine(factorial); Console.WriteLine(factorial); }} Leave empty line between methods Always use { and } after if (there is no space to do it here)

 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() private int Zero() { return 0; return 0; }} The entire method is indented with a single [Tab] Method body is also indented

 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) if (condition) { … }

 Separate method parameters by comma followed by a space  Don't put space before the comma  Examples:  Incorrect examples: 11 private void RegisterUser(string username, string password) RegisterUser("nakov",

 Use an empty line to separate logically related sequences of lines: 12 private List PrepareReports() { List reports = new List (); List reports = new List (); // Create incomes reports // Create incomes reports Report incomesSalesReport = PrepareIncomesSalesReport(); Report incomesSalesReport = PrepareIncomesSalesReport(); reports.Add(incomesSalesReport); reports.Add(incomesSalesReport); Report incomesSupportReport = PrepareIncomesSupportReport(); Report incomesSupportReport = PrepareIncomesSupportReport(); reports.Add(incomesSupportReport); reports.Add(incomesSupportReport); // Create expenses reports // Create expenses reports Report expensesPayrollReport = PrepareExpensesPayrollReport(); Report expensesPayrollReport = PrepareExpensesPayrollReport(); reports.Add(expensesPayrollReport); reports.Add(expensesPayrollReport); Report expensesMarketingReport = PrepareExpensesMarketingReport(); Report expensesMarketingReport = PrepareExpensesMarketingReport(); reports.Add(expensesMarketingReport); reports.Add(expensesMarketingReport); return reports; return reports;} Empty line

 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 public class Dog { // Static variables // Static variables public const string SPECIES = public const string SPECIES = "Canis Lupus Familiaris"; "Canis Lupus Familiaris"; // Instance variables // Instance variables private int age; private int age; // Constructors // Constructors public Dog(string name, int age) public Dog(string name, int age) { this.Name = name; this.Name = name; this.age = age; this.age = age; } (continues on the next slide)

15 // Properties // Properties public string Name { get; set; } public string Name { get; set; } // Methods // Methods public void Breath() public void Breath() { // TODO: breathing process // TODO: breathing process } public void Bark() public void Bark() { Console.WriteLine("wow-wow"); Console.WriteLine("wow-wow"); }}

 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] 16

 Example:  Incorrect examples: 17 for (int i=0; i<10; i++) { Console.WriteLine("i={0}", i); Console.WriteLine("i={0}", i);} for (int i=0; i<10; i++) Console.WriteLine("i={0}", 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); Console.WriteLine("i={0}", i);} The { and } are missing Never put multiple stetements on the same line! In C# the { should be on the next line

 Empty lines are used to separate logically unrelated parts of the source code  Don't put empty lines when not needed! 18 public static void PrintList(List ints) { Console.Write("{ "); Console.Write("{ "); foreach (int item in ints) foreach (int item in ints) { Console.Write(item); Console.Write(item); Console.Write(" "); Console.Write(" "); } Console.WriteLine("}"); Console.WriteLine("}");} static void Main() { // … // … An empty line separates the methods An empty line after the foreach block

19 public static void PrintList(List ints) { Console.Write("{ "); Console.Write("{ "); foreach (int item in ints) foreach (int item in ints) { Console.Write(item); Console.Write(item); Console.Write(" "); Console.Write(" "); } Console.WriteLine("}"); Console.WriteLine("}");} static void Main() { //... //...} What do these empty lines server for?

 Break long lines after punctuation  Indent the second line by single [Tab]  Do not additionally indent the third line  Examples: 20 DictionaryEntry newEntry = new DictionaryEntry (oldEntry.Key, oldEntry.Value); new DictionaryEntry (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+1, y] == 0 || matrix[x, y-1] == 0 || matrix[x, y+1] == 0) matrix[x, y+1] == 0) { …

21 if (matrix[x, y] == 0 || matrix[x-1, y] == 0 || matrix[x+1, y] == 0 || matrix[x, 0 || matrix[x+1, y] == 0 || matrix[x, y-1] == 0 || matrix[x, y+1] == 0) 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+1, y] == 0 || matrix[x, y-1] == 0 || matrix[x, y+1] == 0) matrix[x, y+1] == 0) { … DictionaryEntry newEntry = new DictionaryEntry (oldEntry = new DictionaryEntry (oldEntry.Key, oldEntry.Value);.Key, oldEntry.Value);

 In C# use single [Tab] after breaking a long line:  In JavaScript use double [Tab] in the carried long lines: 22 if (matrix[x, y] == 0 || matrix[x-1, y] == 0 || matrix[x+1, y] == 0 || matrix[x, y-1] == 0 || matrix[x+1, y] == 0 || matrix[x, y-1] == 0 || matrix[x, y+1] == 0) matrix[x, y+1] == 0){ matrix[x, y] == 1; 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+1, y] == 0 || matrix[x, y-1] == 0 || matrix[x, y+1] == 0) { matrix[x, y+1] == 0) { matrix[x, y] == 1; matrix[x, y] == 1;}

 All types of alignments are considered harmful  Alignments are hard-to-maintain!  Incorrect examples: 23 int count = 0; DateTime date = DateTine.Now.Date; Student student = new Student(); List students = new List (); 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

 Take advantage of your IDE to help formatting the code [Ctrl+K+D]  Automatic alignment  Indentation  Style Code analysis  Visual Studio – StyleCop   Eclipse – CheckStyle 

форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен 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# Николай Костов - блог за програмиране

1. Format correctly the following source code (given in Code-Formatting-Homework.zip):  C# code given in the file events.cs.  JavaScript code given in the file code.js.  Use the official code conventions for C# / JavaScript / Java / PHP:  Official C# Coding Conventions (MSDN) Official C# Coding Conventions (MSDN) Official C# Coding Conventions (MSDN)  Google JavaScript Style Guide Google JavaScript Style Guide Google JavaScript Style Guide  Official Java Code Conventions (by Oracle) Official Java Code Conventions (by Oracle) Official Java Code Conventions (by Oracle)  Zend code convention for PHP Zend code convention for PHP Zend code convention for PHP 26

 C# Telerik Academy  csharpfundamentals.telerik.com csharpfundamentals.telerik.com  Telerik Software Academy  academy.telerik.com academy.telerik.com  Telerik Facebook  facebook.com/TelerikAcademy facebook.com/TelerikAcademy  Telerik Software Academy Forums  forums.academy.telerik.com forums.academy.telerik.com