C#, .NET, Java - General Naming and Coding Conventions
-
Upload
ashokguduru -
Category
Technology
-
view
527 -
download
6
description
Transcript of C#, .NET, Java - General 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?"
1From: Object-Oriented Analysis and Design with Applications by Grady Booch
2Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
3
Coding Standards -
Naming Conventions
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
Presented by Ashok GuduruTechnical Architect
4
Naming Conventions and Style
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
• 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.
5
Naming Conventions and Style
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
What is the purpose of this (python) code?
list1 = []for x in theList:
if x[0] == 4:list1 += x;
return list1
6
Naming Conventions and Style
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
Improved code…
flaggedCells = []for cell in theBoard:
if cell[STATUS_VALUE] == FLAGGED:flaggedCells += cell
return flaggedCells
7
Naming Conventions and Style
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
Even more improved code…
flaggedCells = []for cell in theBoard:
if cell.isFlagged():flaggedCells += cell
return flaggedCells
8
Naming Conventions and Style
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
public class ClientActivity{
public void ClearStatistics() {
//...}public void CalculateStatistics() {
//...}
}
• PascalCasing (a.k.a Proper Casing)– Use Pascal Casing for class/Type names and
method names
9
Naming Conventions and Style
• camelCasing– Use camelCasing for method arguments and local
variables
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
public class UserLog{
public void Add(LogEvent logEvent){
int itemCount = logEvent.Items.Count;// ...
}}
10
Naming Conventions and Style
• Do not use Hungarian notation
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
// Correctint counter;string name;
// Avoidint iCounter;string strName;
11
Naming Conventions and Style
• do not use Screaming Caps for constants or readonly variables
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
// Correctpublic static const string ShippingType = "DropShip";
// Avoidpublic static const string SHIPPINGTYPE = "DropShip";
12
Naming Conventions and Style
• Avoid using Abbreviations. Exceptions: abbreviations commonly used as names, such as Id, Xml, Ftp, Uri
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
//CorrectUserGroup userGroup;Assignment employeeAssignment;
//AvoidUserGroup usrGrp;Assignment empAssignment; //ExceptionsCustomerId customerId;XmlDocument xmlDocument;FtpHelper ftpHelper;UriPart uriPart;
13
Naming Conventions and Style
• use PascalCasing for abbreviations – 3 characters or more – 2 chars use both uppercase
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
HtmlHelper htmlHelper;FtpTransfer ftpTransfer;UIControl uiControl;
14
Naming Conventions and Style
• do not use Underscores in identifiers. – Exception: You can prefix private static variables
with an underscore
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
//Correct
public DateTime ClientAppointment;
public TimeSpan TimeLeft;
//Avoid
public DateTime Client_Appointment;
public TimeSpan Time_Left;
//Exception
private DateTime _registrationDate;
15
Naming Conventions and Style
• Use predefined type names instead of system type names like Int16, Single, UInt64, etc.
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
//Correct
string firstName;
int lastIndex;
bool isSaved;
//Avoid
String firstName;
Int32 lastIndex;
Boolean isSaved;
16
Naming Conventions and Style
• use implicit type var for local variable declarations.
Exception: primitive types (int, string, double, etc) use predefined names.
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
var stream = File.Create(path);
var customers = new Dictionary<int?, Customer>();
//Exceptions
int index = 100;
string timeSheet;
bool isCompleted;
17
Procedural code gets information then makes
decisions.
Object-oriented code tells objects to do things.
--Alec Sharp
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
18
Naming Conventions and Style
• use noun or noun phrases to name a class
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
public class Employee
{
}
public class BusinessLocation
{
}
public class DocumentCollection
{
}
The above style distinguishes type names from methods, which are named with verb phrases.
19
Naming Conventions and Style
• Use '-able' as a suffix for interfaces• Name interfaces with adjective phrases, or occasionally with nouns
or noun phrases
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
public interface IObservable
{
}
public interface ISerializable
{
}
//More Examples…
Enumerable, Printable, Drinkable, Shootable, Rotatable, Readable, Writable, Groupable
20
• Types (Classes and Structs) are made of members: methods, properties, events, constructors, and fields. The following sections describe guidelines for naming type members.
Naming Conventions and Style
21
Naming Conventions and Style
• Give methods names that are verbs or verb phrases.
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
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);
}
22
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:
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
public string TextWriter { get {...} set {...} } public string GetTextWriter(int value) { ... }
This above pattern typically indicates that the property should really be a method.
23
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."
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
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; }
24Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
25
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.
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
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 {...} }
}
26
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:
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
public enum Color {...}
public class Control { public Color Color { get {...} set {...} }}
27
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.
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
//Located in Task.cspublic partial class Task{ //...}
//Located in Task.generated.cspublic partial class Task{ //...}
• Use one file per type (class, interface, enum, delegate, struct, event, attribute, exception etc.)
28
Naming Conventions and Style
• Organize namespaces with a clearly defined structure.
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
// Examplesnamespace Company.Product.Module.SubModulenamespace Product.Module.Componentnamespace Product.Layer.Module.Group
• vertically align curly brackets.// Correctclass Program{
static void Main(string[] args) {
}}
29Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
30
Naming Conventions and Style
• declare all member variables at the top of a class, with static variables at the very top.
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
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;}
// Constructorpublic Account(){
// ...}
}
31
Naming Conventions and Style
• Use singular names for enums • Use plurals for bit field (Flagged) enums
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
public enum Color{
Red, Green, Blue, Yellow,Magenta,Cyan
}
[Flags]public enum Dockings{
None = 0, Top = 1, Right = 2, Bottom = 4, Left = 8
}
32
Naming Conventions and Style
• do not explicitly specify a type of an enum or values of enums (except bit fields)
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
// Don'tpublic enum Direction: long{
North = 1,East = 2,South = 3,West = 4
}
// Correctpublic enum Direction{
North, East,South,West
}
33
Naming Conventions and Style
• do notsuffix enum names with Enum
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
//Don'tpublic enum CoinEnum{
Penny,Nickel,Dime,Quarter,Dollar
}
// Correctpublic enum Coin{ Penny,
Nickel,Dime,Quarter,Dollar
}
34
Naming Conventions and Style
• do notsuffix enum names with Enum
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
//Don'tpublic enum CoinEnum{
Penny,Nickel,Dime,Quarter,Dollar
}
// Correctpublic enum Coin{ Penny,
Nickel,Dime,Quarter,Dollar
}
35
Naming Conventions and Style
• Some examples of BAD varibale names
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
int Cutomer_Name;int CustName;int CSTMR-NM;int empName;int intDrvrCde;int drvrcode;int d; //elapsed time in daysint tempId; //not sure Temperature or Template
String logininfoJSON
36
Naming Conventions and Style
• Some examples of GOOD varibale names
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
int elapsedTimeInDays;int daysSinceCreation;int daysSinceModification;int fileAgeInDays;
37
Naming Conventions and Style
• Identify the problems in the following code
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
public class MenuItem{ public int MenuID { get; set; }
//Manu Details public List<System.Web.Mvc.SelectListItem> Category { get; set; } public string Alerts { get; set; } public bool IsSKU { get; set; } public 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; }}
38
Naming Conventions and Style
• Identify the problems in the following code
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
public class ItemCategory{
public string CategoryName { get; set; } public string CategoryDescription { get; set; }}
39Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore
40
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 liveb) 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
41
Thank you!
To be Contd…
You have to experience what you want to express
-- Vincent van Gogh
Ashok GuduruBlog: http://www.ashokg.com
Twitter: @AshokGudurc