Naming Variables, Methods, Classes, Etc. Svetlin Nakov Telerik Corporation www.telerik.com.

Slides:



Advertisements
Similar presentations
Revealing the Secrets of Self-Documenting Code Svetlin Nakov Telerik Corporation For C# Developers.
Advertisements

Revealing the Secrets of Self-Documenting Code Svetlin Nakov Telerik Corporation For C# Developers.
Code Correctness, Readability, Maintainability Svetlin Nakov Telerik Corporation
Coding Standard: General Rules 1.Always be consistent with existing code. 2.Adopt naming conventions consistent with selected framework. 3.Use the same.
1 Java Programming Basics SE-1011 Dr. Mark L. Hornick.
Coding Standards for Java An Introduction. Why Coding Standards are Important? Coding Standards lead to greater consistency within your code and the code.
Variables and Powerful Naming Ryan Ruzich. Naming Considerations The most important consideration in naming a variable is that the name fully and accurately.
Correctly Formatting the Source Code Svetlin Nakov Telerik Software Academy academy.telerik.com.
Inheritance Inheritance Reserved word protected Reserved word super
Lab#1 (14/3/1431h) Introduction To java programming cs425
Revealing the Secrets of Self-Documenting Code Svetlin Nakov Telerik Corporation
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
15-Jun-15 Beginning Style. 2 Be consistent! Most times, you will enter an ongoing project, with established style rules Follow them even if you don’t.
Style Rules II: Names and Naming. Overview Today we will discuss: –Reasons for naming conventions –Rules for naming variables, classes, and methods.
26-Jun-15 Beginning Style. 2 Be consistent! Most times, you will enter an ongoing project, with established style rules Follow them even if you don’t.
Introduction to Java CS 331. Introduction Present the syntax of Java Introduce the Java API Demonstrate how to build –stand-alone Java programs –Java.
Abstract Data Types (ADTs) Data Structures The Java Collections API
Naming Variables, Methods, Classes, Etc. Doncho Minkov High-quality Programming Code codecourse.telerik.com Technical Trainer
Object Oriented Design and UML
Revealing the Secrets of Self-Documenting Code Svetlin Nakov Telerik Corporation For C# Developers.
Java: Chapter 1 Computer Systems Computer Programming II.
Naming Identifiers Naming Variables, Methods, Parameters, Properties, Constants, Classes, Interfaces, Etc. SoftUni Team Technical Trainers Software University.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
National Diploma Unit 4 Introduction to Software Development Data types, variables and constants.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
Quality Code academy.zariba.com 1. Lecture Content 1.Software Quality 2.Code Formatting 3.Correct Naming 4.Documentation and Comments 5.Variables, Expressions.
Comp 248 Introduction to Programming Chapter 6 Arrays Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
CS61B L03 Building Objects (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  (
Improving the Quality of Existing Code Svetlin Nakov Telerik Corporation
Code Correctness, Readability, Maintainability Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 11 Structured Data.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
1 Object Oriented Design and UML Class Relationships –Dependency –Aggregation –Interfaces –Inheritance Interfaces Reading for this Lecture: L&L 6.4 – 6.5.
10-Nov-15 Java Object Oriented Programming What is it?
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Even More Java. Java Packages What is a package? Definition: A package is a grouping of related types providing access protection and name space management.
Revealing the Secrets of Self-Documenting Code Svetlin Nakov Telerik Corporation
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
Communicating in Code: Naming Programming Studio Spring 2009.
GoodOO Programming Practice in Java © Allan C. Milne v
Naming Identifiers Naming Variables, Methods, Parameters, Properties, Constants, Classes, Interfaces, Etc. SoftUni Team Technical Trainers Software University.
Programming with Microsoft Visual Basic th Edition
Variables 1. What is a variable? Something whose value can change over time This value can change more than once over the time period (no limit!) Example:
Recitation 5 Enums and The Java Collections classes/interfaces 1.
Naming Variables, Methods, Classes, Etc. Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Generic Programming and Inner classes ge·ner·ic 1a : relating or applied to or descriptive of all members of a genus, species, class, or group : common.
High-Quality Programming Code Code Correctness, Readability, Maintainability Svetlin Nakov Technical Trainer Software University
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Aside: Running Supplied *.java Programs Just double clicking on a *.java file may not be too useful! 1.In Eclipse, create a project for this program or.
1 1  Lecture 11 – Structured Data FTMK, UTeM – Sem /2014.
Today Javadoc. Packages and static import. Viewing API source code. Upcoming Topics: –protected access modifier –Using the debugger in Eclipse –JUnit testing.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
Chapter Structured Data 11. Combining Data into Structures 11.2.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
The Essentials of a Java Program JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
Stacks and Queues. 2 Abstract Data Types (ADTs) abstract data type (ADT): A specification of a collection of data and the operations that can be performed.
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
More About Objects and Methods
Working with Java.
CSE 143 Introduction to C++ [Appendix B] 4/11/98.
Chapter 1: Computer Systems
Tonga Institute of Higher Education
Beginning Style 27-Feb-19.
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
Chap 2. Identifiers, Keywords, and Types
Presentation transcript:

Naming Variables, Methods, Classes, Etc. Svetlin Nakov Telerik Corporation

1. General Naming Guidelines  The Power of Meaningful Names 2. Naming Classes / Types / Applications  Naming Classes, Interfaces, Types, Delegates, Enumerations, Namespaces, packages, Files, Folders, Assemblies / JARS, Applications 3. Naming Methods and Method Parameters 4. Naming Variables and Constants 5. Other Naming Guidelines 2

 Always use English  How you will feel if you read Vietnamese code with variables named in Vietnamese?  English is the only language that all software developers speak  Avoid abbreviations  Example: scrpCnt vs. scriptsCount  Avoid hard-to-pronounce names  Example: dtbgRegExPtrn vs. dateTimeBulgarianRegExPattern 4

 Always prefer using meaningful names  Names should answer these questions:  What does this class do? What is the intent of this variable? What is this variable / class used for?  Examples:  FactorialCalculator, studentsCount, Math.PI, configFileName, CreateReport  Incorrect examples:  k, k2, k3, junk, f33, KJJ, button1, variable, temp, tmp, temp_var, something, someValue 5

 Whether a name is meaningful or not depends on its context (its enclosing type)  Examples of meaningful names:  Generate() in the class LabyrinthGenerator  Find(string fileName) in the class FileFinder  Deposit(decimal amount) in the class Account  Examples of meaningless names:  Generate() in the class Program  Find(string fileName) in the class Program 6

 Junior developers often use meaningful names that are in fact meaningless  Bad naming examples:  Topic6Exercise12, LoopsExercise12, Problem7, OOPLecture_LastExercise  Yes, Topic6Exercise12 indicates that this is solution to exercise 12, but what is it about?  Better naming:  MaximalNumbersSubsequence 7

 Naming types (classes, structures, etc.)  Use PascalCase character casing  Examples:  RecursiveFactorialCalculator, TreeSet, XmlDocument, IEnumerable, Color, TreeNode, InvalidTransactionException, MainForm  Incorrect examples:  recursiveFactorialCalculator, recursive_factorial_calculator, RECURSIVE_FACTORIAL_CALCULATOR 9

 Use the following formats:  [Noun]  [Adjective] + [Noun]  Examples:  Student, FileSystem, BinaryTreeNode, Constants, MathUtils, CheckBox, Calendar  Incorrect examples:  Move, FindUsers, Fast, Optimize, Extremly, FastFindInDatabase, Check, CheckBox 10

 Following formats are acceptable:  ' I ' + [Verb] + ' able '  ' I ' + [Noun], ' I ' + [Adjective] + [Noun]  Examples:  IEnumerable, IFormattable, IDataReader, IList, IHttpModule, ICommandExecutor  Incorrect examples:  List, FindUsers, IFast, IMemoryOptimize, Optimizer, FastFindInDatabase, CheckBox 11

 Following formats are acceptable:  [Verb] + ' able '  [Noun], [Adjective] + [Noun]  Examples:  Serializable, Enumerable, Comparable, Runnable, CharSequence, OutputStream  Incorrect examples:  list, FindUsers, Run, Inumber, OPTIMIZER, IMemoryOptimize, FastFindInDatabase, 12

 Several formats are acceptable:  [Noun] or [Verb] or [Adjective]  Use the same style for all members  Examples:  enum Day {Monday, Tuesday, Wednesday, …}, enum AppState {Running, Finished, …}, enum WindowState {Normal, Maximized, …}  Incorrect examples:  enum Color {red, green, blue, white}, enum PAGE_FORMAT {A4, A5, A3, LEGAL, …} 13

 Several formats are acceptable:  [Noun] or [Verb] or [Adjective]  Use PascalCase for the enumeration and CAPITALS for its members  Examples:  enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }, enum Color { RED, GREEN, BLUE }  Incorrect examples:  enum Color {red, green, blue, white}, enum PAGE_FORMAT {A4, A5, A3, LEGAL, …} 14

 Attributes  Add 'Attribute ' as suffix  Example: WebServiceAttribute  Incorrect example: WebService  Collection Classes  Add 'Collection ' as suffix  Example: StringsCollection  Incorrect example: ListOfStrings 15

 Exceptions  Add 'Exception ' as suffix  Use informative name  Example: FileNotFoundException  Incorrect example: FileNotFoundError  Delegate Classes  Add 'Delegate ' or ' EventHandler ' as suffix  Example: DownloadFinishedDelegate  Incorrect example: WakeUpNotification 16

 Annotations  Use PascalCase   Incorrect example:  Exceptions  Add 'Exception ' as suffix  Example: UnsupportedEncodingException  Incorrect example: FileNotFoundError 17

 How long could be the name of a class / struct / interface / enum?  The name should be as long as required  Don't abbreviate the names if this could make them unclear  Your IDE has autocomplete, right?  Examples: FileNotFoundException, CustomerSupportNotificationService  Incorrect examples: FNFException, CustSuppNotifSrvc 18

 Namespaces naming guidelines  Use PascalCase  Following formats are acceptable:  Company. Product. Component. …  Product. Component. …  Example:  Telerik.WinControls.GridView  Incorrect examples:  Telerik_WinControlsGridView, Classes 19

 Packages naming guidelines  Use camelCase  Following formats are acceptable:  com. company. product. component. …  product. component. …  Example:  com.apple.quicktime, hibernate.core  Incorrect examples:  IBM.DB2.Data, ibm.db2_data, Eclipse.Core 20

 Project folders' names should follow the project namespaces / packages  Examples:  com  apple  quicktime  Telerik.WinControls.GridView  Incorrect examples:  com_apple_quicktime, quicktime.src 21

 Files with source code should have names matching their content  File containing a class Student should be names Student.cs / Student.java  Example:  StudentDAO.cs, Constants.java, CryptographyAlgorithms.java  Incorrect examples:  MyProgram.cs, SourceCode.java, __d2.cs, WebApplication1.jsp, Page1.aspx 22

.NET assembly names should follow the root namespace in its class hierarchy  Examples:  Telerik.WinControls.GridView.dll  Oracle.DataAccess.dll  Interop.CAPICOM.dll  Incorrect examples:  Telerik_WinControlsGridView.dll  OracleDataAccess.dll 23

 JAR files names should consist of single word or several words separated by hyphen  Can contain version information  Examples:  ant-apache-log4j.jar  xalan25.jar  Incorrect examples:  Ant.Apache.Log4J.jar  Oracle.JDBC.Drivers.jar 24

 Applications should be named meaningfully  Use [Noun] or [Adjective] + [Noun]  Use PascalCase  Examples:  BlogEngine  NewsAggregatorSerivice  Incorrect examples:  ConsoleApplication4, WebSite2  zadacha_14, online_shop_temp2 25

 Methods naming guidelines  Use meaningful method names  Method names should answer the question:  What does this method do?  If you cannot find a good name for a method, think about does it have clear intent  Examples: FindStudent, LoadReport, Sinus  Incorrect examples: Method1, DoSomething, HandleStuff, SampleMethod, DirtyHack 27

 Use PascalCase / camelCase for C# / Java  Example (C#): LoadSettings  Example (Java): loadSettings  Prefer the following formats:  [Verb], [Verb] + [Noun], [Verb] + [Adjective] + [Noun]  Examples: Show, LoadSettingsFile, FindNodeByPattern, ToString, PrintList  Incorrect examples: Student, Counter, White, Generator, Approximation, MathUtils 28

 Methods returning values should describe the returned value  Examples:  ConvertMetersToInches, not MetersInches or Convert or ConvertUnit  Meters2Inches is still acceptable  CalculateSinus is good but Sinus is still acceptable  Ensure that the unit of measure is obvious  Prefer MeasureFontInPixels to MeasureFont 29

 Methods should have a single purpose!  Otherwise they cannot be named well  How to name a method that creates annual incomes report, downloads updates from internet and scans the system for viruses?  CreateAnnualIncomesReportDownloadUpda tesAndScanForViruses is a nice name, right?  Methods that have multiple purposes (weak cohesion) are hard to be named  Need to be refactored instead of named 30

 Use consistent naming in the entire project  LoadFile, LoadImageFromFile, LoadSettings, LoadFont, LoadLibrary, but not ReadTextFile  Use consistently the opposites at the same level of abstraction:  LoadLibrary vs. UnloadLibrary, but not FreeHandle  OpenFile vs. CloseFile, but not DeallocateResource  GetName vs. SetName, but not AssignName 31

 How long could be the name of a method?  The name should be as long as required  Don't abbreviate  Your IDE has autocomplete  Examples:  LoadCustomerSupportNotificationService, CreateMonthlyAndAnnualIncomesReport  Incorrect examples:  LoadCustSuppSrvc, CreateMonthIncReport 32

 Method parameters names  Preferred form: [Noun] or [Adjective] + [Noun]  Should be in camelCase  Should be meaningful  Unit of measure should be obvious  Examples: firstName, report, usersList, fontSizeInPixels, speedKmH, font  Incorrect examples: p, p1, p2, populate, LastName, last_name, convertImage 33

 Variable names  Should be in camelCase  Preferred form: [Noun] or [Adjective] + [Noun]  Should explain the purpose of the variable  If you can't find good name for a variable check if it has a single purpose  Exception: variables with very small scope, e.g. the index variable in a 3-lines long for-loop  Names should be consistent in the project 35

 Examples:  firstName, report, usersList, fontSize, maxSpeed, font, startIndex, endIndex, charsCount, configSettingsXml, config, dbConnection, createUserSqlCommand  Incorrect examples:  foo, bar, p, p1, p2, populate, LastName, last_name, LAST_NAME, convertImage, moveMargin, MAXSpeed, _firtName, __temp, firstNameMiddleNameAndLastName 36

 The name address the problem we solve, not to the means used to solve it  Prefer nouns from the business domain to computer terms  Examples:  accounts, customers, customerAddress, accountHolder, paymentPlan, vipPlayer  Incorrect examples:  accountsLinkedList, customersHashtable, paymentsPriorityQueue, playersArray 37

 Give to boolean variables names that imply true or false  Use positive boolean variable names  Incorrect example:  Examples:  hasPendingPayment, customerFound, validAddress, positiveBalance, isPrime  Incorrect examples:  notFound, run, programStop, player, list, findCustomerById, isUnsuccessfull 38 if (! notFound) { … }

 Naming counters  Establish a convention, e.g. [Noun] + ' Count '  Examples: ticketsCount, customersCount  State  Establish a convention, e.g. [Noun] + ' State '  Examples: blogParseState, threadState  Variables with small scope and span  E.g. loop counters  Short names can be used, e.g. index, i, u 39

 Do really temporary variables exist?  All variables in a program are temporary because they is used temporary only during the program execution, right?  Temporary variables can always be named better than temp or tmp : 40 // Swap a[i] and a[j] int temp = a[i]; a[i] = a[j]; a[j] = temp; // Swap a[i] and a[j] int oldValue = a[i]; a[i] = a[j]; a[j] = oldValue;

 How long could be the name of a variable?  Depends on the variable scope and live time  More "famous" variables should have longer and more self-explaining name  Acceptable naming examples:  Unacceptable naming examples: 41 for (int i=0; i<users.Length; i++) if (i % 2 == 0) if (i % 2 == 0) sum += users[i].Weight; sum += users[i].Weight; class Student { public string lastName; public string lastName;} class Student { private int i; private int i;} class LinkedList { public int flag { get; set; } public int flag { get; set; }}

 In C# and Java prefix / suffix notations are not popular  What is Hungarian notation?  Using prefixes to denote the variable types, e.g. lpcstrText, lpdwFlags, cbMultiByte, hWnd  The Hungarian notation works well in unmanaged languages like C / C++  Do not use Hungarian notation in C# and Java  Don't use prefixes / suffixes to denote the variable data type 42

 Use CAPITAL_LETTERS for const fields and PascalCase for readonly fields  Use meaningful names that describe their value  Examples:  Incorrect examples: 43 private const int READ_BUFFER_SIZE = 8192; public static readonly PageSize DefaultPageSize = PageSize.A4; private const int FONT_SIZE_IN_POINTS = 16; public const int MAX = 512; // Max what? Apples or Oranges? public const int BUF256 = 256; // What about BUF256 = 1024? public const string GREATER = ">"; // GREATER_HTML_ENTITY public const int FONT_SIZE = 16; // 16pt or 16px? public const PageSize PAGE = PageSize.A4; // Maybe PAGE_SIZE?

 Use CAPITAL_LETTERS for Java constants  Use meaningful names  Constants should describe their value  Examples:  Incorrect examples: 44 private static final int READ_BUFFER_SIZE = 8192; public static final PageSize DEFAULT_PAGE_SIZE = PageSize.A4; private static final int FONT_SIZE_IN_POINTS = 16; public static final int MAX = 512; // Max what? public static final int NAME = "BMW"; // What name? Car name? public static final int BufSize = 256; // Use CAPITALS public static final int font_size_pixels = 16; // CAPITALS public static final PageSize PAGE = PageSize.A4; // PAGE_SIZE?

 Don't use numbers in the identifiers names  Example:  PrintReport and PrintReport2  What is the difference?  Exceptions:  When the number is part of the name itself, e.g. RS232Port, COM3, Win32APIFunctions  Don't use Cyrillic or letters from other alphabet  E.g. FindСтудентByName, DisplayΩ2Protein 46

 Giving a misleading name is even worse than giving a totally unclear name  Example:  Consider a method that calculates the sum of all elements in an array  Its should be named Sum or CalculateSum  What about naming it CalculateAverage or Max or CheckForNegativeNumber ?  It's crazy, but be careful with "copy-paste" 47

 Microsoft sometimes use really bad naming in their API libraries (especially in Win32 API)  Examples:  Navigate and Navigate2 methods in Internet Explorer ActiveX control ( MSHTML.DLL )  WNetAddConnection3 method in Multiple Provider Router Networking API ( MPR.DLL )  LPWKSTA_USER_INFO_1 structure in Win32  Don't follow them blindly, just think a bit! 48

 Sun and Oracle sometimes use really bad naming in their Java code  Examples:  The methods offer() / poll() in java.util.Queue  Why not enqueue() / dequeue() ?  Class.forName() loads a class using the current class loader ( java.lang.Class )  Don't follow them blindly, just think a bit! 49

50 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.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()); Console.WriteLine(r.ReadInt32());}r.Close();fs.Close(); Source:

Live Demo

Questions?