SlideShare una empresa de Scribd logo
1 de 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 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

Más contenido relacionado

La actualidad más candente

Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
Alessandro Baratella
 
Bits of Advice for the VM Writer, by Cliff Click @ Curry On 2015
Bits of Advice for the VM Writer, by Cliff Click @ Curry On 2015Bits of Advice for the VM Writer, by Cliff Click @ Curry On 2015
Bits of Advice for the VM Writer, by Cliff Click @ Curry On 2015
curryon
 
Basic Sql Handouts
Basic Sql HandoutsBasic Sql Handouts
Basic Sql Handouts
jhe04
 

La actualidad más candente (20)

Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Bits of Advice for the VM Writer, by Cliff Click @ Curry On 2015
Bits of Advice for the VM Writer, by Cliff Click @ Curry On 2015Bits of Advice for the VM Writer, by Cliff Click @ Curry On 2015
Bits of Advice for the VM Writer, by Cliff Click @ Curry On 2015
 
Java String
Java StringJava String
Java String
 
The Functional Programmer's Toolkit (NDC London 2019)
The Functional Programmer's Toolkit (NDC London 2019)The Functional Programmer's Toolkit (NDC London 2019)
The Functional Programmer's Toolkit (NDC London 2019)
 
JavaScript Conditional Statements
JavaScript Conditional StatementsJavaScript Conditional Statements
JavaScript Conditional Statements
 
Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013
 
Java arrays
Java arraysJava arrays
Java arrays
 
PLSQL Tutorial
PLSQL TutorialPLSQL Tutorial
PLSQL Tutorial
 
Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09
 
Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
Dapper & Dapper.SimpleCRUD
Dapper & Dapper.SimpleCRUDDapper & Dapper.SimpleCRUD
Dapper & Dapper.SimpleCRUD
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptx
 
Basic Sql Handouts
Basic Sql HandoutsBasic Sql Handouts
Basic Sql Handouts
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Sql.pptx
Sql.pptxSql.pptx
Sql.pptx
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
 
JavaScript - Chapter 15 - Debugging Techniques
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging Techniques
 
Json
JsonJson
Json
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & Interface
 

Destacado (6)

Naming Conventions
Naming ConventionsNaming Conventions
Naming Conventions
 
Java & J2EE Coding Conventions
Java & J2EE Coding ConventionsJava & J2EE Coding Conventions
Java & J2EE Coding Conventions
 
QSpiders - Enum Java Topic
QSpiders - Enum Java Topic QSpiders - Enum Java Topic
QSpiders - Enum Java Topic
 
Steel Naming Conventions
Steel Naming ConventionsSteel Naming Conventions
Steel Naming Conventions
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
 
Java packages
Java packagesJava packages
Java packages
 

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

CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
frwebhelp
 

Similar a C#, .NET, Java - General Naming and Coding Conventions (20)

14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
Jscript part2
Jscript part2Jscript part2
Jscript part2
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 
Constructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
 
CSharp Advanced L05-Attributes+Reflection
CSharp Advanced L05-Attributes+ReflectionCSharp Advanced L05-Attributes+Reflection
CSharp Advanced L05-Attributes+Reflection
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
Code snippets
Code snippetsCode snippets
Code snippets
 
Taller evento TestingUY 2017 - API Testing utilizando Chakram
Taller evento TestingUY 2017 - API Testing utilizando ChakramTaller evento TestingUY 2017 - API Testing utilizando Chakram
Taller evento TestingUY 2017 - API Testing utilizando Chakram
 
CSharp presentation and software developement
CSharp presentation and software developementCSharp presentation and software developement
CSharp presentation and software developement
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
Writing code that writes code - Nguyen Luong
Writing code that writes code - Nguyen LuongWriting code that writes code - Nguyen Luong
Writing code that writes code - Nguyen Luong
 
TechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
TechkTalk #12 Grokking: Writing code that writes code – Nguyen LuongTechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
TechkTalk #12 Grokking: Writing code that writes code – Nguyen Luong
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
OO in JavaScript
OO in JavaScriptOO in JavaScript
OO in JavaScript
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
C# 7.0 Hacks and Features
C# 7.0 Hacks and FeaturesC# 7.0 Hacks and Features
C# 7.0 Hacks and Features
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

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

  • 1. 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
  • 2. Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 2
  • 3. Coding Standards Naming Conventions Presented by Ashok Guduru Technical Architect Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 3
  • 4. 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
  • 5. 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. 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
  • 11. 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
  • 12. 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
  • 13. 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
  • 14. 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
  • 15. 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
  • 16. 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
  • 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 17
  • 18. 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
  • 19. 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
  • 20. 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
  • 21. 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
  • 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: 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
  • 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." 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
  • 24. Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 24
  • 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. 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
  • 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: public enum Color {...} public class Control { public Color Color { get {...} set {...} } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 26
  • 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. //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
  • 28. 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
  • 29. Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 29
  • 30. 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
  • 31. 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
  • 32. 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
  • 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 33
  • 34. 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
  • 35. 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
  • 36. 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
  • 37. 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
  • 38. 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
  • 39. Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 39
  • 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 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
  • 41. 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