SlideShare a Scribd company logo
1 of 27
Coding Standards
and
Unit Tests
Jeevitesh.M.S
A bitter pill
I know one of the company, in the late 80s,
wrote a killer app. It was very popular, and lots of
professionals bought and used it. But then the
release cycles began to stretch. Bugs were not
repaired from one release to the next. Load times
grew and crashes increased. I remember the day I
shut the product down in frustration and never
used it again. The company went out of business
a short time after that.
Continuined…
Courtesy clean code book
» Robert C martin
A bitter pill
Two decades later I met one of the early employees of
that company and asked him
what had happened. The answer confirmed my fears.
They had rushed the product to
market and had made a huge mess in the code. As
they added more and more features, the
code got worse and worse until they simply could not
manage it any longer. It was the bad
code that brought the company down.
Courtesy clean code book
» Robert C martin
Why coding standard are important
• Easier to understand which in turn results in a
code, which is easier to develop and maintain.
• Code that is difficult to understand and maintain
runs the risk of being scrapped and rewritten.
• Greater maintainability.
• Greater scalability.
• Greater productivity.
Common excuse
Why does this happen to code? Why does good code rot so quickly
into bad code? We
have lots of explanations for it. We complain that the requirements
changed in ways that
original design. We the schedules that were too tight to do things
right.
We blather about stupid managers and intolerant customers and
useless marketing types
and telephone sanitizers. But the fault, is not in our stars, but in
ourselves.
We are unprofessional.
No. The managers and marketers look to us for the information they
need to make
promises and commitments; and even when they don’t look to us,
we should not be shy
about telling them what we think.
Continuined…
Courtesy clean code book
» Robert C martin
True professionals know that the second part of the is
wrong. You will not
make the deadline by making the mess. Indeed, the
mess will slow you down instantly, and
will force you to miss the deadline. The only way to
make the deadline—the only way to
go fast—is to keep the code as clean as possible at all
times.
Let’s say that you accept
that the only way to go fast is to keep your code clean.
Then you must ask yourself: “How
do I write clean code?”
Courtesy clean code book
» Robert C martin
Bjarne Stroustrup, inventor of C++
and author of The C++ Programming
Language
I like my code to be elegant and efficient. The
logic should be straightforward to make it hard
for bugs to hide, the dependencies minimal to
ease maintenance, error handling complete
according to an articulated strategy, and performance
close to optimal so as not to tempt
people to make the code messy with unprincipled
optimizations. Clean code does one thing
well.
Reading it should make you smile the way a well-
crafted well-designed
car would. Courtesy clean code book
» Robert C martin
Naming Convention
• Never use single letter or abbreviation
– Why ? Because your brain needs to compile
those words AND DO MAPPING so your focus is
lost. READIBILITY DECREASES
• Use full English descriptors that accurately
describe the variable/field/class/interface
• For example, use names like firstName,
grandTotal, or CorporateCustomer (camel casing),
• Use mixed case to make names readable.
• Avoid names that are similar or differ only in case
Meaning full name
• Choosing good names takes time but saves
more than it takes.
• Everyone who reads your code (including
you) will be happier if you do.
• The name of a variable, function, or class,
should answer all the big questions.
• It should tell you why it exists, what it does,
and how it is used. If a name requires a
comment,then the name does not reveal its
intent.
Implication
for (int j=0; j<34; j++) {
s += (t[j]*4)/5;
}
to
int realDaysPerIdealDay = 4;
const int WORK_DAYS_PER_WEEK = 5;
int sum = 0;
for (int j=0; j < NUMBER_OF_TASKS; j++) {
int realTaskDays = taskEstimate[j] * realDaysPerIdealDay;
int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK);
sum += realTaskWeeks;
}
Not all the times third person will be able to
understand the code if the naming convention
is cryptic.
People may miss understand the code. Which
leads to ….
Solution
• So go ahead and use computer
science,domain terms, algorithm names,
pattern names, math terms, and so forth.
Functions
• The first rule of functions is that they
should be small. The second rule of
functions is that they should be smaller than
that.
• Functions should hardly ever be 20 lines
long.
• It will difficult for BRAIN to map if it
extends the screen size .
Function
• Each function should narrate a story.
• FUNCTIONS SHOULD DO ONE THING.
THEY SHOULD DO IT WELL.
• Following this principle will bring different levels of
abstraction.
• Gets of lots of reusability on board.(avoid duplication)
• Testable
Functions
• Naming member functions
– The first word of the member function should be
a verb.
• Naming Accessor Member Functions
– Use prefix “get” to the name of the field /
attribute / property.
– Use prefix “is” to the name of the field /
attribute / property if the field is Boolean
– Examples
– getFirstName()
– isPersistent()
Function
• A long descriptive name is better than a
short mysterious name.
• A long descriptive name is better than a
long descriptive comment.
• Use a naming convention that allows
multiple words to be easily read in the
function names, and then make use of
those multiple words to give the function a
name that says what it does.
Comments
• The reason is simple. Programmers can’t
realistically maintain them.
• Only when non obvious are coded.
• Only the code can truly tell you what it does. It is
the only source of truly accurate information
• “Don’t comment bad code—rewrite it.”
• Nothing can be quite so damaging as an old jargon
comment that propagates lies and misinformation.
• Every time you write a comment, you should feel
the failure of your ability of expression.
Comments
// Check to see if the employee is eligible for full
benefits
if ((employee.flags & HOURLY_FLAG) &&
(employee.age > 65))
Or this?
if (employee.isEligibleForFullBenefits())
// format matched kk:mm:ss EEE, MMM dd, yyyy
Pattern timeMatcher = Pattern.compile(
"d*:d*:d* w*, w* d*, d*");
comments
• Clarification
• Warning of Consequences
– Example @Ignore("Takes too long to run").
– //SimpleDateFormat is not thread safe,
– //so we need to create each instance
independently.
– TODOs are jobs that the programmer thinks
should be done
Comments
// Utility method that returns when this.closed is true. Throws an
exception
// if the timeout is reached.
public synchronized void waitForClose(final long timeoutMillis)
throws Exception
{
if(!closed)
{
wait(timeoutMillis);
if(!closed)
throw new Exception("MockResponseSender could not be closed");
}
}
Naming
• Constants All in upper case .
– MINIMUM_BALANCE
Variable should start with small letter
– Single letter are only allowed in loops i.e., i,j.
For Interfaces START WITH I
• Don’t show the intelligence. Most often
intelligent code result in bug and
maintenance issue.
• Write the logic in very straight forward way.
So that it is easy for third person to
understand.
• Writing software is like any other kind of
writing like article.
• You get your thoughts down first, then you
massage it until it reads well.
Unit Tests
• Why testing?
– Improve software design
– Make software easier to understand
– Reduce debugging time
– Catch integration errors
• In short, to Produce Better Code
• Kent Beck developed the first xUnit automated test tool for
Smalltalk in mid-90’s.
• Junit has become the standard tool for Test-Driven
Development in Java (see Junit.org)
Unit Tests
Basics of software testing
There are two basics of software testing: blackbox testing
and whitebox testing.
• Blackbox Testing
Black box testing is a testing technique that ignores the
internal mechanism of the system and focuses on the output
generated against any input and execution of the system. It is
also called functional testing.
• Whitebox Testing 
White box testing is a testing technique that takes into
account the internal mechanism of a system. It is also called
structural testing and glass box testing.
Types of testing
• There are many types of testing like
• Unit Testing
• Integration Testing
• Functional Testing
• System Testing
• Stress Testing
• Performance Testing
• Usability Testing
• Acceptance Testing
• Regression Testing
• Beta Testing  
• Smoke and sanity testing
• Security testing
Junit Components
• Override the setUp() method to initialize object(s)
under test.
• Override the tearDown() method to release object(s)
under test
• assertX methods
• assertEquals(expected, actual)
• assertNull(Object object)
• static void assertTrue(boolean test)
• static void assertFalse(boolean test)
Results
Your results are here
Other general info
• About Agile Development.
• About Test Driven development.
• Fit – Testing based on Tables
• Cucumber – Testing based on Modern language
• Selenium – UI Driven testing framework.
• About Usability – book by name“Dont make me
think”
• JPGL: JPA Hibernate, Design patterns –Head first
design patterns

More Related Content

What's hot

Naming guidelines for professional programmers
Naming guidelines for professional programmersNaming guidelines for professional programmers
Naming guidelines for professional programmersPeter Hilton
 
Designing with tests
Designing with testsDesigning with tests
Designing with testsDror Helper
 
How to write good comments
How to write good commentsHow to write good comments
How to write good commentsPeter Hilton
 
How to write maintainable code
How to write maintainable codeHow to write maintainable code
How to write maintainable codePeter Hilton
 
Big Ball of Mud: Software Maintenance Nightmares
Big Ball of Mud: Software Maintenance NightmaresBig Ball of Mud: Software Maintenance Nightmares
Big Ball of Mud: Software Maintenance NightmaresGonzalo Rodríguez
 
The Smells Of Bad Design
The Smells Of Bad DesignThe Smells Of Bad Design
The Smells Of Bad Designguest446c0
 
Clean Code III - Software Craftsmanship
Clean Code III - Software CraftsmanshipClean Code III - Software Craftsmanship
Clean Code III - Software CraftsmanshipTheo Jungeblut
 

What's hot (7)

Naming guidelines for professional programmers
Naming guidelines for professional programmersNaming guidelines for professional programmers
Naming guidelines for professional programmers
 
Designing with tests
Designing with testsDesigning with tests
Designing with tests
 
How to write good comments
How to write good commentsHow to write good comments
How to write good comments
 
How to write maintainable code
How to write maintainable codeHow to write maintainable code
How to write maintainable code
 
Big Ball of Mud: Software Maintenance Nightmares
Big Ball of Mud: Software Maintenance NightmaresBig Ball of Mud: Software Maintenance Nightmares
Big Ball of Mud: Software Maintenance Nightmares
 
The Smells Of Bad Design
The Smells Of Bad DesignThe Smells Of Bad Design
The Smells Of Bad Design
 
Clean Code III - Software Craftsmanship
Clean Code III - Software CraftsmanshipClean Code III - Software Craftsmanship
Clean Code III - Software Craftsmanship
 

Similar to Coding Standards

YAGNI Principle and Clean Code
YAGNI Principle and Clean CodeYAGNI Principle and Clean Code
YAGNI Principle and Clean CodeLuan Reffatti
 
Clean Code (David Frame) - PHPBelfast Meetup 22/02/24
Clean Code (David Frame) - PHPBelfast Meetup 22/02/24Clean Code (David Frame) - PHPBelfast Meetup 22/02/24
Clean Code (David Frame) - PHPBelfast Meetup 22/02/24davidgrantframe
 
Clean code, Feb 2012
Clean code, Feb 2012Clean code, Feb 2012
Clean code, Feb 2012cobyst
 
How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....Mike Harris
 
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...DevDay.org
 
Clean code: understanding Boundaries and Unit Tests
Clean code: understanding Boundaries and Unit TestsClean code: understanding Boundaries and Unit Tests
Clean code: understanding Boundaries and Unit Testsradin reth
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tipsBill Buchan
 
Refactoring, 2nd Edition
Refactoring, 2nd EditionRefactoring, 2nd Edition
Refactoring, 2nd Editionjexp
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean CodingMetin Ogurlu
 
Clean code quotes - Citações e provocações
Clean code quotes - Citações e provocaçõesClean code quotes - Citações e provocações
Clean code quotes - Citações e provocaçõesAndré de Fontana Ignacio
 
The View - Lotusscript coding best practices
The View - Lotusscript coding best practicesThe View - Lotusscript coding best practices
The View - Lotusscript coding best practicesBill Buchan
 
Clean Code Software Engineering
Clean Code Software Engineering Clean Code Software Engineering
Clean Code Software Engineering Inocentshuja Ahmad
 
Software Development Essential Skills
Software Development Essential SkillsSoftware Development Essential Skills
Software Development Essential SkillsJohn Choi
 
TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019Paulo Clavijo
 
An Overview of automated testing (1)
An Overview of automated testing (1)An Overview of automated testing (1)
An Overview of automated testing (1)Rodrigo Lopes
 
Extreme Programming (XP): Revisted
Extreme Programming (XP): RevistedExtreme Programming (XP): Revisted
Extreme Programming (XP): RevistedMike Harris
 

Similar to Coding Standards (20)

Clean Code
Clean CodeClean Code
Clean Code
 
YAGNI Principle and Clean Code
YAGNI Principle and Clean CodeYAGNI Principle and Clean Code
YAGNI Principle and Clean Code
 
Clean Code (David Frame) - PHPBelfast Meetup 22/02/24
Clean Code (David Frame) - PHPBelfast Meetup 22/02/24Clean Code (David Frame) - PHPBelfast Meetup 22/02/24
Clean Code (David Frame) - PHPBelfast Meetup 22/02/24
 
Clean code, Feb 2012
Clean code, Feb 2012Clean code, Feb 2012
Clean code, Feb 2012
 
Clean code and code smells
Clean code and code smellsClean code and code smells
Clean code and code smells
 
How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....
 
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
 
Clean code: understanding Boundaries and Unit Tests
Clean code: understanding Boundaries and Unit TestsClean code: understanding Boundaries and Unit Tests
Clean code: understanding Boundaries and Unit Tests
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tips
 
Refactoring, 2nd Edition
Refactoring, 2nd EditionRefactoring, 2nd Edition
Refactoring, 2nd Edition
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean Coding
 
Clean code quotes - Citações e provocações
Clean code quotes - Citações e provocaçõesClean code quotes - Citações e provocações
Clean code quotes - Citações e provocações
 
The View - Lotusscript coding best practices
The View - Lotusscript coding best practicesThe View - Lotusscript coding best practices
The View - Lotusscript coding best practices
 
Clean Code Software Engineering
Clean Code Software Engineering Clean Code Software Engineering
Clean Code Software Engineering
 
Software Development Essential Skills
Software Development Essential SkillsSoftware Development Essential Skills
Software Development Essential Skills
 
Traits of a Good Engineer
Traits of a Good EngineerTraits of a Good Engineer
Traits of a Good Engineer
 
TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019
 
An Overview of automated testing (1)
An Overview of automated testing (1)An Overview of automated testing (1)
An Overview of automated testing (1)
 
Extreme Programming (XP): Revisted
Extreme Programming (XP): RevistedExtreme Programming (XP): Revisted
Extreme Programming (XP): Revisted
 
QA and scrum
QA and scrumQA and scrum
QA and scrum
 

Coding Standards

  • 2. A bitter pill I know one of the company, in the late 80s, wrote a killer app. It was very popular, and lots of professionals bought and used it. But then the release cycles began to stretch. Bugs were not repaired from one release to the next. Load times grew and crashes increased. I remember the day I shut the product down in frustration and never used it again. The company went out of business a short time after that. Continuined… Courtesy clean code book » Robert C martin
  • 3. A bitter pill Two decades later I met one of the early employees of that company and asked him what had happened. The answer confirmed my fears. They had rushed the product to market and had made a huge mess in the code. As they added more and more features, the code got worse and worse until they simply could not manage it any longer. It was the bad code that brought the company down. Courtesy clean code book » Robert C martin
  • 4. Why coding standard are important • Easier to understand which in turn results in a code, which is easier to develop and maintain. • Code that is difficult to understand and maintain runs the risk of being scrapped and rewritten. • Greater maintainability. • Greater scalability. • Greater productivity.
  • 5. Common excuse Why does this happen to code? Why does good code rot so quickly into bad code? We have lots of explanations for it. We complain that the requirements changed in ways that original design. We the schedules that were too tight to do things right. We blather about stupid managers and intolerant customers and useless marketing types and telephone sanitizers. But the fault, is not in our stars, but in ourselves. We are unprofessional. No. The managers and marketers look to us for the information they need to make promises and commitments; and even when they don’t look to us, we should not be shy about telling them what we think. Continuined… Courtesy clean code book » Robert C martin
  • 6. True professionals know that the second part of the is wrong. You will not make the deadline by making the mess. Indeed, the mess will slow you down instantly, and will force you to miss the deadline. The only way to make the deadline—the only way to go fast—is to keep the code as clean as possible at all times. Let’s say that you accept that the only way to go fast is to keep your code clean. Then you must ask yourself: “How do I write clean code?” Courtesy clean code book » Robert C martin
  • 7. Bjarne Stroustrup, inventor of C++ and author of The C++ Programming Language I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations. Clean code does one thing well. Reading it should make you smile the way a well- crafted well-designed car would. Courtesy clean code book » Robert C martin
  • 8. Naming Convention • Never use single letter or abbreviation – Why ? Because your brain needs to compile those words AND DO MAPPING so your focus is lost. READIBILITY DECREASES • Use full English descriptors that accurately describe the variable/field/class/interface • For example, use names like firstName, grandTotal, or CorporateCustomer (camel casing), • Use mixed case to make names readable. • Avoid names that are similar or differ only in case
  • 9. Meaning full name • Choosing good names takes time but saves more than it takes. • Everyone who reads your code (including you) will be happier if you do. • The name of a variable, function, or class, should answer all the big questions. • It should tell you why it exists, what it does, and how it is used. If a name requires a comment,then the name does not reveal its intent.
  • 10. Implication for (int j=0; j<34; j++) { s += (t[j]*4)/5; } to int realDaysPerIdealDay = 4; const int WORK_DAYS_PER_WEEK = 5; int sum = 0; for (int j=0; j < NUMBER_OF_TASKS; j++) { int realTaskDays = taskEstimate[j] * realDaysPerIdealDay; int realTaskWeeks = (realdays / WORK_DAYS_PER_WEEK); sum += realTaskWeeks; } Not all the times third person will be able to understand the code if the naming convention is cryptic. People may miss understand the code. Which leads to ….
  • 11. Solution • So go ahead and use computer science,domain terms, algorithm names, pattern names, math terms, and so forth.
  • 12. Functions • The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that. • Functions should hardly ever be 20 lines long. • It will difficult for BRAIN to map if it extends the screen size .
  • 13. Function • Each function should narrate a story. • FUNCTIONS SHOULD DO ONE THING. THEY SHOULD DO IT WELL. • Following this principle will bring different levels of abstraction. • Gets of lots of reusability on board.(avoid duplication) • Testable
  • 14. Functions • Naming member functions – The first word of the member function should be a verb. • Naming Accessor Member Functions – Use prefix “get” to the name of the field / attribute / property. – Use prefix “is” to the name of the field / attribute / property if the field is Boolean – Examples – getFirstName() – isPersistent()
  • 15. Function • A long descriptive name is better than a short mysterious name. • A long descriptive name is better than a long descriptive comment. • Use a naming convention that allows multiple words to be easily read in the function names, and then make use of those multiple words to give the function a name that says what it does.
  • 16. Comments • The reason is simple. Programmers can’t realistically maintain them. • Only when non obvious are coded. • Only the code can truly tell you what it does. It is the only source of truly accurate information • “Don’t comment bad code—rewrite it.” • Nothing can be quite so damaging as an old jargon comment that propagates lies and misinformation. • Every time you write a comment, you should feel the failure of your ability of expression.
  • 17. Comments // Check to see if the employee is eligible for full benefits if ((employee.flags & HOURLY_FLAG) && (employee.age > 65)) Or this? if (employee.isEligibleForFullBenefits()) // format matched kk:mm:ss EEE, MMM dd, yyyy Pattern timeMatcher = Pattern.compile( "d*:d*:d* w*, w* d*, d*");
  • 18. comments • Clarification • Warning of Consequences – Example @Ignore("Takes too long to run"). – //SimpleDateFormat is not thread safe, – //so we need to create each instance independently. – TODOs are jobs that the programmer thinks should be done
  • 19. Comments // Utility method that returns when this.closed is true. Throws an exception // if the timeout is reached. public synchronized void waitForClose(final long timeoutMillis) throws Exception { if(!closed) { wait(timeoutMillis); if(!closed) throw new Exception("MockResponseSender could not be closed"); } }
  • 20. Naming • Constants All in upper case . – MINIMUM_BALANCE Variable should start with small letter – Single letter are only allowed in loops i.e., i,j. For Interfaces START WITH I
  • 21. • Don’t show the intelligence. Most often intelligent code result in bug and maintenance issue. • Write the logic in very straight forward way. So that it is easy for third person to understand. • Writing software is like any other kind of writing like article. • You get your thoughts down first, then you massage it until it reads well.
  • 22. Unit Tests • Why testing? – Improve software design – Make software easier to understand – Reduce debugging time – Catch integration errors • In short, to Produce Better Code • Kent Beck developed the first xUnit automated test tool for Smalltalk in mid-90’s. • Junit has become the standard tool for Test-Driven Development in Java (see Junit.org)
  • 23. Unit Tests Basics of software testing There are two basics of software testing: blackbox testing and whitebox testing. • Blackbox Testing Black box testing is a testing technique that ignores the internal mechanism of the system and focuses on the output generated against any input and execution of the system. It is also called functional testing. • Whitebox Testing  White box testing is a testing technique that takes into account the internal mechanism of a system. It is also called structural testing and glass box testing.
  • 24. Types of testing • There are many types of testing like • Unit Testing • Integration Testing • Functional Testing • System Testing • Stress Testing • Performance Testing • Usability Testing • Acceptance Testing • Regression Testing • Beta Testing   • Smoke and sanity testing • Security testing
  • 25. Junit Components • Override the setUp() method to initialize object(s) under test. • Override the tearDown() method to release object(s) under test • assertX methods • assertEquals(expected, actual) • assertNull(Object object) • static void assertTrue(boolean test) • static void assertFalse(boolean test)
  • 27. Other general info • About Agile Development. • About Test Driven development. • Fit – Testing based on Tables • Cucumber – Testing based on Modern language • Selenium – UI Driven testing framework. • About Usability – book by name“Dont make me think” • JPGL: JPA Hibernate, Design patterns –Head first design patterns