41
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 1 From: Object-Oriented Analysis and Design with Applications by Grady Booch

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

Embed Size (px)

DESCRIPTION

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

Citation preview

Page 1: 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

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

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

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

3

Coding Standards -

Naming Conventions

Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore

Presented by Ashok GuduruTechnical Architect

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

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.

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

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

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

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

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

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

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

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

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

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

}}

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

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;

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

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";

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

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;

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

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;

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

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;  

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

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;

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

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;

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

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

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

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.

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

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

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

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

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

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);

}

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

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.

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

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; }

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

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

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

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

}

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

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

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

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

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

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) {

}}

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

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

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

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(){

// ...}

}

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

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

}

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

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

}

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

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

}

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

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

}

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

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

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

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;

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

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; }}

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

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; }}

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

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

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

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

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

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