Code Formatting Formatting the Source Code Correctly SoftUni Team Technical Trainers Software University

Slides:



Advertisements
Similar presentations
Correctly Formatting the Source Code Svetlin Nakov Telerik Software Academy academy.telerik.com.
Advertisements

Software Quality Assurance QA Engineering, Testing, Bug Tracking, Test Automation Software University Technical Trainers SoftUni Team.
Other Types in OOP Enumerations, Structures, Generic Classes, Attributes Svetlin Nakov Technical Trainer Software University
 Dimitar Ivanov Introduction to programming with microcontrollers.
C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC SoftUni Team Technical Trainers Software University
Programming Basics Course Introduction SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Teamwork and Personal Skills Course Introduction Software University SoftUni Team Technical Trainers.
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
JavaScript Design Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers SoftUni.
Conditional Statements Implementing Control-Flow Logic in C# SoftUni Team Technical Trainers Software University
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
Database APIs and Wrappers
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Delegates and Events Callback Functionality and Event-Driven Programming Svetlin Nakov Technical Trainer Software University
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC Angel Georgiev Part-time Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Static Members and Namespaces Static Members, Indexers, Operators, Namespaces SoftUni Team Technical Trainers Software University
Arrays, Lists, Stacks, Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
C# Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Technical Trainer Software University
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Code Formatting Correctly Formatting the Source Code Svetlin Nakov Technical Trainer Software University
Correctly Formatting the Source Code Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
JavaScript Modules and Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers.
Web Development Tools Tools for Front-End Developers Writing HTML and CSS Code SoftUni Team Technical Trainers Software University
Exam Preparation Algorithms Course: Sample Exam SoftUni Team Technical Trainers Software University
Tables, Rows, Columns, Cells, Header, Footer, Colspan, Rowspan
High-Quality Programming Code Code Correctness, Readability, Maintainability Svetlin Nakov Technical Trainer Software University
High-Quality Code: Course Introduction Course Introduction SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Advanced C# Course Introduction SoftUni Team Technical Trainers Software University
Object-Oriented Programming Course Introduction Svetlin Nakov Technical Trainer Software University
Reflection Programming under the hood SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Operators and Expressions
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Programming for Beginners Course Introduction SoftUni Team Technical Trainers Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
High-Quality Code: Course Introduction Course Introduction SoftUni Team Technical Trainers Software University
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Programming Fundamentals Course Introduction SoftUni Team Technical Trainers Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Static Members Static Variables & Methods SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
C# OOP Advanced Course Introduction SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
Static Members and Namespaces
C# Basic Syntax, Visual Studio, Console Input / Output
Repeating Code Multiple Times
Presentation transcript:

Code Formatting Formatting the Source Code Correctly SoftUni Team Technical Trainers Software University

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

Code Formatting Why Do We Need It?

4 Why Does Code Need 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 for (int i = 0; i < 11; i++){ Console.WriteLine (r.ReadInt32 ()) ;}r. Close ( ); fs. Close ( ) ; }

5  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 Code Formatting Fundamentals The formatting of the source code should disclose its logical structure.

6  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: Formatting Blocks 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}

7  Use empty line for separation between methods: Empty Lines between Methods 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 an empty line between methods Always use { and } after if (there is no space to do it here)

Indentation of Methods  Methods should be indented with a single [Tab] from the class body  Methods body should be indented with a single [Tab] as well 8 public class IndentationExample { private int Zero() private int Zero() { return 0; return 0; }} The entire method is indented with a single [Tab] The method body is also indented

Brackets in Method Declarations  Brackets in the method declarations should be formatted as follows:  Don't use spaces between the brackets:  The same applies for if -conditions and for -loops: 9 private static ulong CalculateFactorial(uint num) if (condition) { … } The brackets should be on their own line

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

11  Use an empty line to separate logically related sequences of lines: Empty Lines in Method Body 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

12  Formatting classes / structures / interfaces / enumerations  Indent the class body with a single [Tab]  Use the following order of definitions:  By member type: constants, delegates, inner types, fields, constructors, properties, methods  By visibility: static members, public members, protected members, internal members, private members  The order of definitions stated above may not be the only correct order  May depend on company-level code conventions Formatting Types

13 Formatting Types – Example public class Dog { // Static variables // Static variables public const string Species = "Canis Lupus Familiaris"; public const string Species = "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)

14 Formatting Types – Example (2) // Properties // Properties public string Name { get; set; } public string Name { get; set; } // Methods // Methods public void Breathe() public void Breathe() { // TODO: breathing process // TODO: breathing process } public void Bark() public void Bark() { Console.WriteLine("wuf-wuf"); Console.WriteLine("wuf-wuf"); }}

15  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  Never indent with more than one [Tab] Formatting Conditional Statements and Loops

16  Example:  Incorrect examples: Conditional Statements and Loops Formatting 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! The { should be on the next line

17  Empty lines are used to separate logically unrelated parts of the source code  Don't put empty lines when not needed! Using Empty Lines 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

18 Misplaced Empty Lines – Example 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 serve for?

19  Break long lines after punctuation  Indent the second line by single [Tab]  Do not indent the next lines further  Examples: Breaking Long Lines DictionaryEntry newEntry = new DictionaryEntry ( 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) { …

20 Incorrect Ways To Break Long Lines 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);

21  All types of alignments are considered harmful  Alignments are hard-to-maintain!  Incorrect examples: Alignments 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

22  Take advantage of your IDE to help formatting the code  [Ctrl] + K + D in Visual Studio  Automatic alignment  Code style analysis  StyleCop   JetBrains ReSharper  Automated Tools

Code Formatting Exercises in Class

24 1.Formatting Guidelines  Make sure the formatting clearly shows the purpose of the code 2.Formatting Conventions  Blocks, types, method parameters  Separating logically related blocks of code 3.Automated Code Analysis and Refactoring Tools Summary

? ? ? ? ? ? ? ? ? Code Formatting

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 26  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA licenseFundamentals of Computer Programming with C#CC-BY-SA  "C# Part I" course by Telerik Academy under CC-BY-NC-SA licenseC# Part ICC-BY-NC-SA

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg