C#, .NET, Java - General Naming and Coding Conventions

0 %
100 %
Information about C#, .NET, Java - General Naming and Coding Conventions
Technology

Published on March 4, 2014

Author: ashokguduru

Source: slideshare.net

Description

C#, .NET, Java - General Programming Naming and Coding Conventions

Complexity: A physician, a civil engineer, and a computer scientist were arguing about what was the oldest profession in the world. The physician remarked, "Weil, in the Bible, it says that God created Eve from a rib taken out of Adam. This clearly required surgery, and so I can rightly claim that mine is the oldest profession in the world. "The civil engineer interrupted, and said, "But even earlier in the book of Genesis, it states that God created the order of the heavens and the earth from out of the chaos. This was the first and certainly the most spectacular application of civil engineering. Therefore, fair doctor, you are wrong: mine is the oldest profession in the world. "The computer scientist leaned back in her chair, smiled, and then said confidently, "Ah, but who do you think created the chaos?" From: Object-Oriented Analysis and Design with Applications by Grady Booch 1

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 2

Coding Standards Naming Conventions Presented by Ashok Guduru Technical Architect Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 3

Naming Conventions and Style • Source code is a form of expression and so quality-of-expression must be a primary concern. • Poor quality-of-expression creates ongoing costs and impacts the productivity (hence the reputation) of the team that produces it. • Therefore software authors must learn to clearly express the intention of variables, methods, classes, and modules. Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 4

Naming Conventions and Style What is the purpose of this (python) code? list1 = [] for x in theList: if x[0] == 4: list1 += x; return list1 Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 5

Naming Conventions and Style Improved code… flaggedCells = [] for cell in theBoard: if cell[STATUS_VALUE] == FLAGGED: flaggedCells += cell return flaggedCells Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 6

Naming Conventions and Style Even more improved code… flaggedCells = [] for cell in theBoard: if cell.isFlagged(): flaggedCells += cell return flaggedCells Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 7

Naming Conventions and Style • PascalCasing (a.k.a Proper Casing) – Use Pascal Casing for class/Type names and method names public class ClientActivity { public void ClearStatistics() { //... } public void CalculateStatistics() { //... } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 8

Naming Conventions and Style • camelCasing – Use camelCasing for method arguments and local variables public class UserLog { public void Add(LogEvent logEvent) { int itemCount = logEvent.Items.Count; // ... } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 9

Naming Conventions and Style • Do not use Hungarian notation // Correct int counter; string name; // Avoid int iCounter; string strName; Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 10

Naming Conventions and Style • do not use Screaming Caps for constants or readonly variables // Correct public static const string ShippingType = "DropShip"; // Avoid public static const string SHIPPINGTYPE = "DropShip"; Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 11

Naming Conventions and Style • Avoid using Abbreviations. Exceptions: abbreviations commonly used as names, such as Id, Xml, Ftp, Uri //Correct UserGroup userGroup; Assignment employeeAssignment; //Avoid UserGroup usrGrp; Assignment empAssignment; //Exceptions CustomerId customerId; XmlDocument xmlDocument; FtpHelper ftpHelper; UriPart uriPart; Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 12

Naming Conventions and Style • use PascalCasing for abbreviations – 3 characters or more – 2 chars use both uppercase HtmlHelper htmlHelper; FtpTransfer ftpTransfer; UIControl uiControl; Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 13

Naming Conventions and Style • do not use Underscores in identifiers. – Exception: You can prefix private static variables with an underscore //Correct public DateTime ClientAppointment; public TimeSpan TimeLeft; //Avoid public DateTime Client_Appointment; public TimeSpan Time_Left; //Exception private DateTime _registrationDate; Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 14

Naming Conventions and Style • Use predefined type names instead of system type names like Int16, Single, UInt64, etc. //Correct string firstName; int lastIndex; bool isSaved; //Avoid String firstName; Int32 lastIndex; Boolean isSaved; Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 15

Naming Conventions and Style • use implicit type var for local variable declarations. Exception: primitive types (int, string, double, etc) use predefined names. var stream = File.Create(path); var customers = new Dictionary<int?, Customer>(); //Exceptions int index = 100; string timeSheet; bool isCompleted; Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 16

Procedural code gets information then makes decisions. Object-oriented code tells objects to do things. --Alec Sharp Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 17

Naming Conventions and Style • use noun or noun phrases to name a class public class Employee { } public class BusinessLocation { } public class DocumentCollection { } The above style distinguishes type names from methods, which are named with verb phrases. Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 18

Naming Conventions and Style • Use '-able' as a suffix for interfaces • Name interfaces with adjective phrases, or occasionally with nouns or noun phrases public interface IObservable { } public interface ISerializable { } //More Examples… Enumerable, Printable, Drinkable, Shootable, Rotatabl e, Readable, Writable, Groupable Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 19

Naming Conventions and Style • Types (Classes and Structs) are made of members: methods, properties, events, constructors, and fields. The following sections describe guidelines for naming type members. 20

Naming Conventions and Style • Give methods names that are verbs or verb phrases. public class String { public int CompareTo(...); public string[] Split(...); public string Trim(); } public static class Console { public static void Write(string format, object arg0) public static void WriteLine(char value); public static void SetWindowSize(int width, int height); public static void SetWindowPosition(int left, int top); public static void ResetColor(); public static Stream OpenStandardError(int bufferSize); } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 21

Naming Conventions and Style • Names of Properties: Unlike other members, properties should be given noun phrase or adjective names. That is because a property refers to data (object state), and the name of the property reflects that. • Always use PascalCasing to name properties. • DO name properties using a noun, noun phrase, or adjective. • DO NOT have properties that match the name of "Get" methods as in the following example: public string TextWriter { get {...} set {...} } public string GetTextWriter(int value) { ... } This above pattern typically indicates that the property should really be a method. Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 22

Naming Conventions and Style • Names of Properties: Name the collection properties with a plural phrase describing the items in the collection instead of using a singular phrase followed by "List" or "Collection." private static double[] _sizeBins; public ICollection Instruments { get; set; } public int[] Temperatures { get; set; } public string[] Operators { get; set; } public string[] SizeRanges { get; set; } public string[] TrendChartColumns { get; set; } public string[] SampleDateIntervals { get; set; } public string[] XYChartColumns { get; set; } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 23

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 24

Naming Conventions and Style • Names of Properties: Name Boolean properties with an affirmative phrase (CanSeek instead of CantSeek). Optionally, you can also prefix Boolean properties with "Is," "Can," or "Has," but only where it adds value. Public class Stream { public bool CanSeek { get {...} set {...} } public bool IsOpen { get {...} set {...} } public bool IsModifiable { get {...} set {...} } public bool AllowChanges { get {...} set {...} } public bool HasPassed { get {...} set {...} } public bool IsWritable { get {...} set {...} } public bool CanModify { get {...} set {...} } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 25

Naming Conventions and Style • Names of Properties: CONSIDER giving a property the same name as its type. – For example, the following property correctly gets and sets an enum value named Color, so the property is named Color: public enum Color {...} public class Control { public Color Color { get {...} set {...} } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 26

Naming Conventions and Style • Name source files according to their main classes. Exceptions: file names with partial classes reflect their source or purpose, e.g. designer, generated, etc. //Located in Task.cs public partial class Task{ //...} //Located in Task.generated.cs public partial class Task{ //...} • Use one file per type (class, interface, enum, delegate, struct, event, attribute, exception etc.) Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 27

Naming Conventions and Style • Organize namespaces with a clearly defined structure. // Examples namespace Company.Product.Module.SubModule namespace Product.Module.Component namespace Product.Layer.Module.Group • vertically align curly brackets. // Correct class Program { static void Main(string[] args) { } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 28

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 29

Naming Conventions and Style • declare all member variables at the top of a class, with static variables at the very top. public class Account { public static string BankName; public static decimal Reserves; public string Number {get; set;} public DateTime DateOpened {get; set;} public DateTime DateClosed {get; set;} public decimal Balance {get; set;} // Constructor public Account() { // ... } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 30

Naming Conventions and Style • Use singular names for enums • Use plurals for bit field (Flagged) enums public enum Color { Red, Green, Blue, Yellow, Magenta, Cyan } [Flags] public enum Dockings { None = 0, Top = 1, Right = 2, Bottom = 4, Left = 8 } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 31

Naming Conventions and Style • do not explicitly specify a type of an enum or values of enums (except bit fields) // Don't public enum Direction: long { North = 1, East = 2, South = 3, West = 4 } // Correct public enum Direction { North, East, South, West } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 32

Naming Conventions and Style • do notsuffix enum names with Enum //Don't public enum CoinEnum { Penny, Nickel, Dime, Quarter, Dollar } // Correct public enum Coin { Penny, Nickel, Dime, Quarter, Dollar } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 33

Naming Conventions and Style • do notsuffix enum names with Enum //Don't public enum CoinEnum { Penny, Nickel, Dime, Quarter, Dollar } // Correct public enum Coin { Penny, Nickel, Dime, Quarter, Dollar } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 34

Naming Conventions and Style • Some examples of BAD varibale names int Cutomer_Name; int CustName; int CSTMR-NM; int empName; int intDrvrCde; int drvrcode; int d; //elapsed time in days int tempId; //not sure Temperature or String logininfoJSON Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore Template 35

Naming Conventions and Style • Some examples of GOOD varibale names int int int int elapsedTimeInDays; daysSinceCreation; daysSinceModification; fileAgeInDays; Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 36

Naming Conventions and Style • Identify the problems in the following code public class MenuItem { public int MenuID { get; set; } //Manu public public public public Details List<System.Web.Mvc.SelectListItem> Category { get; set; } string Alerts { get; set; } bool IsSKU { get; set; } bool IsDirectOrderable { get; set; } //Restaurant Details public List<System.Web.Mvc.SelectListItem> Restaurant { get; set; } public List<System.Web.Mvc.SelectListItem> AvailableTime { get; set; } public DateTime AvailableFrom { get; set; } public DateTime AvailableTo { get; set; } //Price Details public double Price { get; set; } //Add-on details public bool IsAddonSelectMandatory { get; set; } public List<System.Web.Mvc.SelectListItem> AddonType { get; set; } public List<System.Web.Mvc.SelectListItem> Addon { get; set; } public string RecipeDescription { get; set; } public List<MenuItem> MenuItems { get; set; } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 37

Naming Conventions and Style • Identify the problems in the following code public class ItemCategory { public string CategoryName { get; set; } public string CategoryDescription { get; set; } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 38

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 39

When a tester didn't find any cool bugs, then he basically has two options to think about. a) The software is good enough to go live b) The software wasn't tested well enough Typically, the developer thinks it is "a". And, of course, the tester always fears it could be option "b". Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 40

You have to experience what you want to express -- Vincent van Gogh Thank you! Ashok Guduru Blog: http://www.ashokg.com Twitter: @AshokGudurc To be Contd… 41

Add a comment

Related presentations

Presentación que realice en el Evento Nacional de Gobierno Abierto, realizado los ...

In this presentation we will describe our experience developing with a highly dyna...

Presentation to the LITA Forum 7th November 2014 Albuquerque, NM

Un recorrido por los cambios que nos generará el wearabletech en el futuro

Um paralelo entre as novidades & mercado em Wearable Computing e Tecnologias Assis...

Microsoft finally joins the smartwatch and fitness tracker game by introducing the...

Related pages

General Naming Conventions

General Naming Conventions.NET Framework (current version) Other Versions ... C#, for example, ...
Read more

C# Coding Standards and Naming Conventions - dofactory.com

C# Coding Standards and Naming Conventions. Below are our C# coding standards, naming conventions, ... consistent with the Microsoft's .NET Framework and ...
Read more

Naming Guidelines

Framework Design Guidelines Naming Guidelines. ... of naming conventions in the ... naming conventions as general code ...
Read more

What are the naming conventions in C#? - Stack Overflow

What are the naming conventions in C#? ... This document describes the coding style guideline for native C++ and .NET (C# and VB.NET) ...
Read more

Naming convention (programming) - Wikipedia, the free ...

... a naming convention is a set of ... One widely used Java coding style ... The built-in JavaScript libraries use the same naming conventions as Java.
Read more

Naming Conventions & Coding Standards for .NET

Naming Conventions & Coding Standards for .NET. ... Naming Conventions/Coding Standard ... · Juval Lowy & IDesign.net’s C# Coding ...
Read more

Naming Conventions for .NET / C# / WPF Projects - Stack ...

Naming Conventions for .NET / C# Projects. ... C# Coding Standard for C# . It look very good. And of course Design Guidelines for Developing Class Libraries.
Read more

CSharp Coding Standards - Chair of Software Engineering

Lance Hunt C# Coding Standards for .NET http ... 4.1 General ... this document covers Naming Conventions , Coding Style , ...
Read more

Naming Conventions - CodeProject - CodeProject - For those ...

Naming conventions; Author: Marla Sukesh ; Updated: 27 Jul 2013; Section: Programming Tips; Chapter: General ...
Read more