SlideShare a Scribd company logo
CLEAN CODING AND
DEVOPS
UNIT I
INTRODUCTION TO CLEANCODING
• Coding principles introduction-Bad and Good
code-marshalling and unmarshalling-Names and
Functions-distinct names-Defining meaningful context-Usage
of domain and function names-Usage of exceptions and its
error code names/descriptions. Right comments and types of
formatting- Clean and bad comments-Vertical and horizontal
formatting-Objects and data structures-Data abstraction-Data
and object antisymmetric-Data transfer objects.
UNIT II
INTRODUCTION TO DEV-OPS
• An overview about DevOps,-Why it is needed? how it is
different from traditional IT & Agile - DevOps Principles,-
DevOps Lifecycle - An overview about CI/CD pipeline and
various tools- setup a complete CI/CD pipeline from scratch
using DevOps tools - How DevOps is used in various
technologies/industries.
UNIT III
ADVANCED DEV-OPS
• An overview of advanced DevOps concepts - Automatic
Rollback & Provisioning, Scalability, Clustering &
Infrastructure as Code An overview of Cloud computing -
-Why DevOps on cloud - IBM Cloud services - Setup a
CI/CD pipeline in Cloud
Clean coding
• Clean code is code that is easy to understand , easy to change
and easy to modify.
• Use easy names for variables and methods.
How to write clean code?
• Clean code isn’t language specific.
• Always write readable format.
• Use meaningful names for variables, functions, and methods.
• One function only performs one specific task.
• Review code regularly.
Characteristic of clean code
• Clean code should be readable.
• Clean code should be elegant.
• Clean code should be simple and easy to understand.
• Clean code should be easy to understand, easy to
change and easy to taken care of.
• Clean code should run all the tests.
Principles of Clean Code
• Meaningful Names- Always use a meaningful name for
variables, functions, and others.
• Deep Nesting-Sometimes we use nested loops that are
difficult to understand. The way to handle that is to
extract all loops into separate functions instead.
• Follow a Naming Convention-to create precise and
meaningful naming conventions
Principles of clean code
• Stay DRY-DRY stands for “Don’t Repeat Yourself”. we
follow the ”single responsibility principle”, there is no
need to repeat code, because our programming is
focused and created in a way that encourages reuse, not
repetition.
• Avoid duplication and unnecessary operation the code .
• Eliminate the repetition.
Good and bad code
Good code
• Easy to understand.
• Good code is well- organized , Data and operations in
classes fit together
• Uses meaningful naming conventions.
• Code should be well-tested.
Example for Good code
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d n",c);
c = a-b;
printf("a-b = %d n",c);
c = a*b;
printf("a*b = %d n",c);
c = a/b;
printf("a/b = %d n",c);
Bad code
• Poor coding standard and style.
• Complex and not straight forward.
• Duplicate function.
• No documentation.
• Unnecessarily use of loops and jumps statements.
• Take lot of times and resource to execute than usual.
Example for bad code
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;
{
c = a+b;
printf("a+b = %d n",c);
}
{
c = a-b;
printf("a-b = %d n",c);
}
MARSHALLING
• Marshalling is the process of transforming Java objects
to XML file.
• In other words it is the process of creating a bridge
between managed code and unmanaged code.
XML
• XML stands for eXtensible Markup Language
• XML is a markup language much like HTML
• XML was designed to store and transport data
• It has sender information.
• It has receiver information
• It has a heading
• It has a message body
•
Example
class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello, World!");
}
}
Example
<?xml version="1.0" encoding="UTF-8"?>
<text>
<name>hello world</name>
</text>
UNMARSHALLING
• Unmarshalling is the process of converting XML content
to Java objects.
Clean code : Naming
• Names must be clear and understandable.
• Names are everywhere in software. We name our
variables, our functions, our arguments, classes, and
packages. We name our source files and the directories .
We name our jar files and war files.
Best practice for clean class names
• Use noun for class names.
Example: class student {}
class car {}
• Avoid verb for class names.
Example: class Perform {}
class Performed {}
class Performing {}
Best practice for clean class names
• Avoid single-letter class names.
Example: class P {}
class L {}
• Avoid using plural for a normal class.
Example: class cars{}
• Avoid abbreviations
Example: class stu {}
Best Practice for clean method/function
names
• Use present tense verbs for method names.
Example: fun open() {}
fun close() {}
• Avoid function name verb + “ing”.
Example: fun opening() {}
fun closing() {}
Best Practice for clean method/function
names
• Avoid past tense verb forms.
Example: fun opened() {}
fun closed() {}
Best practice for clean variable names
• Avoid single-letter variable names.
Example: var s = 12
var i = 8
• Use a meaningful name can clarify its purpose.
Example: var size = 12
var index = 8
Example: int age; float weight; char gender;
Best practice for clean variable names
• Avoid complicated prefixes such as Hungarian
notation.
Example:
var f_strFirstName = "Joy”
FUNCTION
• A function is a block of statements that performs a
specific task.
• In other word divide a large program into the small
building blocks known as function.
Why we need functions
• To improve the readability of code.
• Improves the reusability of the code.
• Debugging of the code would be easier.
• Reduces the size of the code.
FUNCTION
Predefined standard library functions
• Standard library functions are also known as built-in functions.
Functions such as print(),max(),min(),pow(), str(), chr() are
standard library functions.
User-defined functions on the other hand, are those functions
which are defined by the user at the time of writing program.
User-defined functions
• In Python a function is defined using the def keyword:
Example1:
def welcome():
print("Hello from a function")
Example 2:
def add(x,y):
sum = x + y
return sum
num1 = 5
num2 = 6
print("The sum is", add(num1, num2))
Clean Code - Functions
• BE SMALL
The first rule of writing functions is functions should be small.
They should not have more than an average of 30 code lines.
(not counting line spaces and comments).
Every function in this program was just two, or three, or four
lines long. Each was transparently understandable.
Clean Code - Functions
• DO ONE THING-SINGLE RESPONSIBILITY
PRINCIPLE
“Functions should do one thing. They should do it well.
should perform just one responsibility.
• Single Level of Abstraction (SLAB) – as the name suggests,
recommends writing a method/function in a single level of
abstraction.
• Mixing levels of abstraction within a function is always
confusing.
Clean Code - Functions
public class CoffeeMaker
{
public void makeCoffee()
{
grindBeans();
boilWater();
PourWater();
}
private void grindBeans()
{ // ... }
private void boilWater()
{ // ... }
Clean Code - Functions
• Avoid Switch Statement
Switch statement:
• The switch statement is a multi-way branch statement. It
provides an easy way to execute different parts of code based
on the value of the expression.
• Switch statement is ugly.
• Moreover, Switch cases perform N responsibilities by its
design. They should be avoided as long as possible.
Clean Code - Functions
switch(num1 > num2)
{
case 0:
printf("%d is Maximum number", num2);
break;
case 1:
printf("%d is Maximum number", num1);
break;
}
Clean Code - Functions
• Use descriptive names.-The name of a function should
describe exactly what it does.
• Naming is the most necessary thing for writing clean codes.
Developers will read your code by names of variables,
functions, classes, methods, interfaces. The name should sound
like a story, not something unknowable.
• Example
def multiply():
DISTINCT NAME
In order to declare different (or) unique and memorable
name for variable, function and method.
Avoid confusion among other programmer and user.
Example:
Python Program to find Total, Average, and Percentage of Five
Subjects .
EXAMPLE
english = float(input("Please enter English Marks: "))
math = float(input("Please enter Math score: "))
computers = float(input("Please enter Computer Marks: "))
physics = float(input("Please enter Physics Marks: "))
chemistry = float(input("Please enter Chemistry Marks: "))
total = english + math + computers + physics + chemistry
average = total / 5
percentage = (total / 500) * 100
print("nTotal Marks = %.2f" %total)
print("Average Marks = %.2f" %average)
print("Marks Percentage = %.2f" %percentage)
DISTINCT NAME
Avoid Noise Words
Noise words are the words that do not offer any additional
information about the variable.
Some popular noise words are:
The (prefix)
Info
Data
Example
If your class is named UserInfo, you can just remove the Info and
make it User. If your class is named BookData ,you just remove
the data make it book.
Defining meaningful context
• Sometimes variable names require additional data to give
context to general variable names like firstName, LastName,
city, zipcode etc. In such a case adding a prefix like
addrfirstName and addrLastName will denote it being a part of
a larger Address class.
• char firstname[20], lastname[20];
• char addrfirstname[20],addr lastname[20];
Usage of domain and function names
Function names
• Functions name should be a verb . By design, a function
should have only one responsibility. If the name is anything
other than a verb, then either you are naming it wrong or there
are some problems in the architecture.
• Domain names Remember that the people who read your
code will be programmers. So go ahead and use computer
science (CS) terms- algorithm names, pattern names, math
terms whenever needed.
Usage of exceptions and its error
code names/descriptions.
• An exception (or exceptional event) is a problem that arises
during the execution of a program.
• The Exception Handling in Java is one of the
powerful mechanism to handle the runtime errors so that the
normal flow of the application can be maintained.
An exception can occur for many different reasons:
• A user has entered an invalid data and name.
• A file that needs to be opened cannot be found.
• Network connection problem
Usage of exceptions and its error code
names/descriptions.
Java try and catch
• The try statement allows you to define a block of code to be
tested for errors while it is being executed.
• The catch statement allows you to define a block of code to be
executed, if an error occurs in the try block.
Try {
// Block of code to try
}
catch(Exception e)
{
// Block of code to handle errors
}
Example
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}}}
Output: Something went wrong
Comments rules
• The goal of every programmer should be to write code so
clean and expressive that code comments are unnecessary.
• When we think about comments in code, we have in mind
comments that explain what code is doing. The problem with
comments is that they are not always updated.
Example
class Factorial{
public static void main(String args[]){
int i,fact=1;
int number=5;//It is the number to calculate factorial
for(i=1;i<=number;i++) //increment the number
{
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
Comments rules
• Always try to explain yourself in code.
• Don't be redundant.
• Don't add obvious noise.
• Don't use closing brace comments.
• Don't comment out code. Just remove.
• Use as clarification of code.
• Use as warning of consequences.
Comments rules
Explain Yourself in Code
• It only takes a few seconds to clear the majority of your
thoughts in code.
Example:
// student is eligible for blood donation
if (student.age >= 17 && student.weight >= 58.0
&& student.height >= 1.55)
{
scheduleBloodDonatingSessionWith(student);
}
Comments rules
• Don’t be redundant.
Saying the same thing over and over again…
Example:
// if the student is at least 18 years of age
if (student.age> = 18){
// send meeting invitation to the student
notificationService.sendMessageTo(student, meetingInvitation);
}
else // if the student is younger than 18 years
{
// sends a meeting invitation to the student’s legal guardian
notificationService.sendMessageTo(student.parent,meetingInvitation);
}
Comment rule
Don't add obvious noise.
• Sometimes you see comments that are nothing but noise. They
repeat the obvious and provide no new information.
Bad comment
i++; //increment I
OR
return 1;// returns 1
Comment rule
• Don't use closing brace comments.
• Frequently programmers comment on the closing braces. This may
be important with long functions and deeply embedded structures.
So if you want your closing braces to be described, try to shorten
your functionalities.
• } // End of While Block
} // End of if block
} // End of outer if block
} // End of method
example
class Palindrome
{
public static void main(String args[])
{
int r,sum=0,temp;
int n=454; //It is the number variable to be checked for palindrome
temp=n;
while(n>0)
{
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
} // End of while block
if(temp==sum)
System.out.println("palindrome number ");
else
System.out.println("not palindrome");
}
}
Formatting
• Code formatting is important because is all about communication and
read.
• The reader should be able to understand the gross structure of the
code in a glance. The shapes made by blocks of text help you
communicate overall structure.
• Easy to read, maintain and extend.
Formatting
• Source code is like a newspaper article. The farther down we
go, the more detailed the article gets. This is the same for
code.
Types:
1.Vertical Formatting
2. Horizontal Formatting
Vertical Formatting
✔ The number of lines of code is should be less than 500 lines.
Smaller files are easier to understand than big files. Big files
take longer to read and so more time is spent reading code and
than doing the actual work.
✔ Vertical formatting deals with the vertical size and vertical
distance between elements.
✔ Similar function/concepts grouped together.
Swap two numbers using temporary
variable
public class SwapNumbers {
public static void main(String[] args) {
float first = 1.20f, second = 2.45f;
System.out.println("--Before swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
float temporary = first;
first = second;
second = temporary;
System.out.println("--After swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
}
}
Horizontal Formatting
• Horizontal formatting deals with the horizontal width and
horizontal distance between elements.
• Lines should be of the sizes Max100-120 characters.
• Olden days 80 characters allowed.
Example:
x = 1;
X + = 1;
Horizontal Formatting
• Horizontal Openness: How we used the horizontal spaces to
the code. On the other hand, didn’t put spaces between the
function names and the opening parenthesis. This is because
the function and its arguments are closely related. Separate
arguments to highlight the comma and show that the
arguments are separate.
Horizontal Formatting
Indentation
• Indentation is also part of horizontal formatting. A source file
contains a hierarchy of scopes like class, method, block etc.
• It is a good practice to indent the lines of source code
according to their hierarchy levels so that it would be easy to
visualize the concept.
• indentation of blocks of code to convey program structure
• Indentation refers to the spaces at the beginning of a code line.
Horizontal Formatting
Class MyClass
{
instanceVar;
public static void myMethod()
{
int var1 = 1;
{
int var2 = 2;
}
}
}
An object is a real-world thing that has properties and actions. In
other words, an entity that has state and behavior is known as an
object.
Objects and Data structures
Class
• A class is a blueprint for the object. Before we create an
object, we first need to define the class.
• In other words, a class can also be defined as “group of objects
which are common to all objects of one type”.
Class Example
• Let us consider two objects Samsung Galaxy S4 and iPhone.
Suppose Samsung Galaxy S4 have some properties like width =
“6.98 cms”, height = “13.6 cm”, OS = “Android”, brand =
“Samsung”, price = “1000$” and actions are call(),
sendMessage(), browser(), share().
• Now, suppose iPhone has some properties such as width = “5.86
cm”, height = “12.3 cms”, OS = “iOS”, brand = “Apple”, price =
“1200$” and actions are call(), sendMessage(), browse(),
share().
• Both objects have some different properties and actions but the
type is the same “Phone”. This is the class. i.e the name of the
class is “Phone”.
Example
Data Abstraction
• Abstraction is method of hiding the implementation details
and showing only the functionality, basically Provides
guidelines to build a standard product.
Example :
• You know how a car look like and how to drive, but you don’t
know how to build a car.
Example
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{ output:
int getRateOfInterest(){return 7;} Rate of interest:7%
} Rate of interest:8%
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}
Object &Data structure
• Difference between objects and data structures.
• Objects: Hide their data (be private) and have functions to
operate on that data.
• Data Structures: show their data (be public) and have no
meaningful functions.
Data and object
antisymmetric
• Procedural code (code using data structures) makes it easy to
add new functions without changing the existing data
structures.
• Procedural code makes it hard to add new data structures
because all the functions must change.
• OO code, on the other hand, makes it easy to add new classes
without changing existing functions.
Object
Data structure
DTO
• DTO- Data Transfer Object.
• It is used to transfer the data between classes and modules of
your application.
• This is a form of a data structure which is a class with public
variables and no functions and sometimes called DTO.
UNIT I cloud computing ppt cloud ccd all about the cloud computing

More Related Content

Similar to UNIT I cloud computing ppt cloud ccd all about the cloud computing (20)

PPTX
Object Oriented Programming Using C++.pptx
bscit6
 
PPTX
Best Coding Practices in Java and C++
Nitin Aggarwal
 
PPTX
Presentation on topic of c and c++ programming language.(.pptx
panawarahul7
 
PPTX
ProgrammingPrimerAndOOPS
sunmitraeducation
 
PPTX
STRUCTURED PROGRAMMING (USING C PROGRAMMING).pptx
stevecom2010
 
PPTX
Learn c++ Programming Language
Steve Johnson
 
PPT
Oops lecture 1
rehan16091997
 
PPTX
C++ overview
Prem Ranjan
 
PPTX
POLITEKNIK MALAYSIA
Aiman Hud
 
PPTX
C language
Mukul Kirti Verma
 
PPTX
c#.pptx
JoselitoJMebolos
 
PPT
73d32 session1 c++
Mukund Trivedi
 
PPTX
Module--fundamentals and operators in java1.pptx
Radhika Venkatesh
 
PPTX
c++.pptxwjwjsijsnsksomammaoansnksooskskk
mitivete
 
PDF
Agile_goa_2013_clean_code_tdd
Srinivasa GV
 
PPTX
Java-Intro.pptx
VijalJain3
 
PPTX
Design Like a Pro: Scripting Best Practices
Inductive Automation
 
PDF
DOC-20240718-WA0006..pdf34642235632567432
alishafgh391
 
PPTX
Design Like a Pro: Scripting Best Practices
Inductive Automation
 
PPTX
Introduction Of C++
Sangharsh agarwal
 
Object Oriented Programming Using C++.pptx
bscit6
 
Best Coding Practices in Java and C++
Nitin Aggarwal
 
Presentation on topic of c and c++ programming language.(.pptx
panawarahul7
 
ProgrammingPrimerAndOOPS
sunmitraeducation
 
STRUCTURED PROGRAMMING (USING C PROGRAMMING).pptx
stevecom2010
 
Learn c++ Programming Language
Steve Johnson
 
Oops lecture 1
rehan16091997
 
C++ overview
Prem Ranjan
 
POLITEKNIK MALAYSIA
Aiman Hud
 
C language
Mukul Kirti Verma
 
73d32 session1 c++
Mukund Trivedi
 
Module--fundamentals and operators in java1.pptx
Radhika Venkatesh
 
c++.pptxwjwjsijsnsksomammaoansnksooskskk
mitivete
 
Agile_goa_2013_clean_code_tdd
Srinivasa GV
 
Java-Intro.pptx
VijalJain3
 
Design Like a Pro: Scripting Best Practices
Inductive Automation
 
DOC-20240718-WA0006..pdf34642235632567432
alishafgh391
 
Design Like a Pro: Scripting Best Practices
Inductive Automation
 
Introduction Of C++
Sangharsh agarwal
 

Recently uploaded (20)

PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PPT
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
PDF
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
PDF
Electrical Engineer operation Supervisor
ssaruntatapower143
 
PPTX
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
PPTX
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
PPTX
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
PPTX
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PDF
Zilliz Cloud Demo for performance and scale
Zilliz
 
PPTX
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
PPTX
Hashing Introduction , hash functions and techniques
sailajam21
 
PPTX
Element 7. CHEMICAL AND BIOLOGICAL AGENT.pptx
merrandomohandas
 
PPTX
Introduction to Design of Machine Elements
PradeepKumarS27
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
PPTX
MobileComputingMANET2023 MobileComputingMANET2023.pptx
masterfake98765
 
DOCX
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
PPTX
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
Electrical Engineer operation Supervisor
ssaruntatapower143
 
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
Zilliz Cloud Demo for performance and scale
Zilliz
 
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
Hashing Introduction , hash functions and techniques
sailajam21
 
Element 7. CHEMICAL AND BIOLOGICAL AGENT.pptx
merrandomohandas
 
Introduction to Design of Machine Elements
PradeepKumarS27
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
MobileComputingMANET2023 MobileComputingMANET2023.pptx
masterfake98765
 
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
Ad

UNIT I cloud computing ppt cloud ccd all about the cloud computing

  • 2. UNIT I INTRODUCTION TO CLEANCODING • Coding principles introduction-Bad and Good code-marshalling and unmarshalling-Names and Functions-distinct names-Defining meaningful context-Usage of domain and function names-Usage of exceptions and its error code names/descriptions. Right comments and types of formatting- Clean and bad comments-Vertical and horizontal formatting-Objects and data structures-Data abstraction-Data and object antisymmetric-Data transfer objects.
  • 3. UNIT II INTRODUCTION TO DEV-OPS • An overview about DevOps,-Why it is needed? how it is different from traditional IT & Agile - DevOps Principles,- DevOps Lifecycle - An overview about CI/CD pipeline and various tools- setup a complete CI/CD pipeline from scratch using DevOps tools - How DevOps is used in various technologies/industries.
  • 4. UNIT III ADVANCED DEV-OPS • An overview of advanced DevOps concepts - Automatic Rollback & Provisioning, Scalability, Clustering & Infrastructure as Code An overview of Cloud computing - -Why DevOps on cloud - IBM Cloud services - Setup a CI/CD pipeline in Cloud
  • 5. Clean coding • Clean code is code that is easy to understand , easy to change and easy to modify. • Use easy names for variables and methods.
  • 6. How to write clean code? • Clean code isn’t language specific. • Always write readable format. • Use meaningful names for variables, functions, and methods. • One function only performs one specific task. • Review code regularly.
  • 7. Characteristic of clean code • Clean code should be readable. • Clean code should be elegant. • Clean code should be simple and easy to understand. • Clean code should be easy to understand, easy to change and easy to taken care of. • Clean code should run all the tests.
  • 8. Principles of Clean Code • Meaningful Names- Always use a meaningful name for variables, functions, and others. • Deep Nesting-Sometimes we use nested loops that are difficult to understand. The way to handle that is to extract all loops into separate functions instead. • Follow a Naming Convention-to create precise and meaningful naming conventions
  • 9. Principles of clean code • Stay DRY-DRY stands for “Don’t Repeat Yourself”. we follow the ”single responsibility principle”, there is no need to repeat code, because our programming is focused and created in a way that encourages reuse, not repetition. • Avoid duplication and unnecessary operation the code . • Eliminate the repetition.
  • 10. Good and bad code
  • 11. Good code • Easy to understand. • Good code is well- organized , Data and operations in classes fit together • Uses meaningful naming conventions. • Code should be well-tested.
  • 12. Example for Good code #include <stdio.h> int main() { int a = 9,b = 4, c; c = a+b; printf("a+b = %d n",c); c = a-b; printf("a-b = %d n",c); c = a*b; printf("a*b = %d n",c); c = a/b; printf("a/b = %d n",c);
  • 13. Bad code • Poor coding standard and style. • Complex and not straight forward. • Duplicate function. • No documentation. • Unnecessarily use of loops and jumps statements. • Take lot of times and resource to execute than usual.
  • 14. Example for bad code #include <stdio.h> int main() { int a = 9,b = 4, c; { c = a+b; printf("a+b = %d n",c); } { c = a-b; printf("a-b = %d n",c); }
  • 15. MARSHALLING • Marshalling is the process of transforming Java objects to XML file. • In other words it is the process of creating a bridge between managed code and unmanaged code.
  • 16. XML • XML stands for eXtensible Markup Language • XML is a markup language much like HTML • XML was designed to store and transport data • It has sender information. • It has receiver information • It has a heading • It has a message body •
  • 17. Example class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
  • 19. UNMARSHALLING • Unmarshalling is the process of converting XML content to Java objects.
  • 20. Clean code : Naming • Names must be clear and understandable. • Names are everywhere in software. We name our variables, our functions, our arguments, classes, and packages. We name our source files and the directories . We name our jar files and war files.
  • 21. Best practice for clean class names • Use noun for class names. Example: class student {} class car {} • Avoid verb for class names. Example: class Perform {} class Performed {} class Performing {}
  • 22. Best practice for clean class names • Avoid single-letter class names. Example: class P {} class L {} • Avoid using plural for a normal class. Example: class cars{} • Avoid abbreviations Example: class stu {}
  • 23. Best Practice for clean method/function names • Use present tense verbs for method names. Example: fun open() {} fun close() {} • Avoid function name verb + “ing”. Example: fun opening() {} fun closing() {}
  • 24. Best Practice for clean method/function names • Avoid past tense verb forms. Example: fun opened() {} fun closed() {}
  • 25. Best practice for clean variable names • Avoid single-letter variable names. Example: var s = 12 var i = 8 • Use a meaningful name can clarify its purpose. Example: var size = 12 var index = 8 Example: int age; float weight; char gender;
  • 26. Best practice for clean variable names • Avoid complicated prefixes such as Hungarian notation. Example: var f_strFirstName = "Joy”
  • 27. FUNCTION • A function is a block of statements that performs a specific task. • In other word divide a large program into the small building blocks known as function.
  • 28. Why we need functions • To improve the readability of code. • Improves the reusability of the code. • Debugging of the code would be easier. • Reduces the size of the code.
  • 29. FUNCTION Predefined standard library functions • Standard library functions are also known as built-in functions. Functions such as print(),max(),min(),pow(), str(), chr() are standard library functions. User-defined functions on the other hand, are those functions which are defined by the user at the time of writing program.
  • 30. User-defined functions • In Python a function is defined using the def keyword: Example1: def welcome(): print("Hello from a function") Example 2: def add(x,y): sum = x + y return sum num1 = 5 num2 = 6 print("The sum is", add(num1, num2))
  • 31. Clean Code - Functions • BE SMALL The first rule of writing functions is functions should be small. They should not have more than an average of 30 code lines. (not counting line spaces and comments). Every function in this program was just two, or three, or four lines long. Each was transparently understandable.
  • 32. Clean Code - Functions • DO ONE THING-SINGLE RESPONSIBILITY PRINCIPLE “Functions should do one thing. They should do it well. should perform just one responsibility. • Single Level of Abstraction (SLAB) – as the name suggests, recommends writing a method/function in a single level of abstraction. • Mixing levels of abstraction within a function is always confusing.
  • 33. Clean Code - Functions public class CoffeeMaker { public void makeCoffee() { grindBeans(); boilWater(); PourWater(); } private void grindBeans() { // ... } private void boilWater() { // ... }
  • 34. Clean Code - Functions • Avoid Switch Statement Switch statement: • The switch statement is a multi-way branch statement. It provides an easy way to execute different parts of code based on the value of the expression. • Switch statement is ugly. • Moreover, Switch cases perform N responsibilities by its design. They should be avoided as long as possible.
  • 35. Clean Code - Functions switch(num1 > num2) { case 0: printf("%d is Maximum number", num2); break; case 1: printf("%d is Maximum number", num1); break; }
  • 36. Clean Code - Functions • Use descriptive names.-The name of a function should describe exactly what it does. • Naming is the most necessary thing for writing clean codes. Developers will read your code by names of variables, functions, classes, methods, interfaces. The name should sound like a story, not something unknowable. • Example def multiply():
  • 37. DISTINCT NAME In order to declare different (or) unique and memorable name for variable, function and method. Avoid confusion among other programmer and user. Example: Python Program to find Total, Average, and Percentage of Five Subjects .
  • 38. EXAMPLE english = float(input("Please enter English Marks: ")) math = float(input("Please enter Math score: ")) computers = float(input("Please enter Computer Marks: ")) physics = float(input("Please enter Physics Marks: ")) chemistry = float(input("Please enter Chemistry Marks: ")) total = english + math + computers + physics + chemistry average = total / 5 percentage = (total / 500) * 100 print("nTotal Marks = %.2f" %total) print("Average Marks = %.2f" %average) print("Marks Percentage = %.2f" %percentage)
  • 39. DISTINCT NAME Avoid Noise Words Noise words are the words that do not offer any additional information about the variable. Some popular noise words are: The (prefix) Info Data Example If your class is named UserInfo, you can just remove the Info and make it User. If your class is named BookData ,you just remove the data make it book.
  • 40. Defining meaningful context • Sometimes variable names require additional data to give context to general variable names like firstName, LastName, city, zipcode etc. In such a case adding a prefix like addrfirstName and addrLastName will denote it being a part of a larger Address class. • char firstname[20], lastname[20]; • char addrfirstname[20],addr lastname[20];
  • 41. Usage of domain and function names Function names • Functions name should be a verb . By design, a function should have only one responsibility. If the name is anything other than a verb, then either you are naming it wrong or there are some problems in the architecture. • Domain names Remember that the people who read your code will be programmers. So go ahead and use computer science (CS) terms- algorithm names, pattern names, math terms whenever needed.
  • 42. Usage of exceptions and its error code names/descriptions. • An exception (or exceptional event) is a problem that arises during the execution of a program. • The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained. An exception can occur for many different reasons: • A user has entered an invalid data and name. • A file that needs to be opened cannot be found. • Network connection problem
  • 43. Usage of exceptions and its error code names/descriptions. Java try and catch • The try statement allows you to define a block of code to be tested for errors while it is being executed. • The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. Try { // Block of code to try } catch(Exception e) { // Block of code to handle errors }
  • 44. Example public class Main { public static void main(String[ ] args) { try { int[] myNumbers = {1, 2, 3}; System.out.println(myNumbers[10]); } catch (Exception e) { System.out.println("Something went wrong."); }}} Output: Something went wrong
  • 45. Comments rules • The goal of every programmer should be to write code so clean and expressive that code comments are unnecessary. • When we think about comments in code, we have in mind comments that explain what code is doing. The problem with comments is that they are not always updated.
  • 46. Example class Factorial{ public static void main(String args[]){ int i,fact=1; int number=5;//It is the number to calculate factorial for(i=1;i<=number;i++) //increment the number { fact=fact*i; } System.out.println("Factorial of "+number+" is: "+fact); } }
  • 47. Comments rules • Always try to explain yourself in code. • Don't be redundant. • Don't add obvious noise. • Don't use closing brace comments. • Don't comment out code. Just remove. • Use as clarification of code. • Use as warning of consequences.
  • 48. Comments rules Explain Yourself in Code • It only takes a few seconds to clear the majority of your thoughts in code. Example: // student is eligible for blood donation if (student.age >= 17 && student.weight >= 58.0 && student.height >= 1.55) { scheduleBloodDonatingSessionWith(student); }
  • 49. Comments rules • Don’t be redundant. Saying the same thing over and over again… Example: // if the student is at least 18 years of age if (student.age> = 18){ // send meeting invitation to the student notificationService.sendMessageTo(student, meetingInvitation); } else // if the student is younger than 18 years { // sends a meeting invitation to the student’s legal guardian notificationService.sendMessageTo(student.parent,meetingInvitation); }
  • 50. Comment rule Don't add obvious noise. • Sometimes you see comments that are nothing but noise. They repeat the obvious and provide no new information. Bad comment i++; //increment I OR return 1;// returns 1
  • 51. Comment rule • Don't use closing brace comments. • Frequently programmers comment on the closing braces. This may be important with long functions and deeply embedded structures. So if you want your closing braces to be described, try to shorten your functionalities. • } // End of While Block } // End of if block } // End of outer if block } // End of method
  • 52. example class Palindrome { public static void main(String args[]) { int r,sum=0,temp; int n=454; //It is the number variable to be checked for palindrome temp=n; while(n>0) { r=n%10; //getting remainder sum=(sum*10)+r; n=n/10; } // End of while block if(temp==sum) System.out.println("palindrome number "); else System.out.println("not palindrome"); } }
  • 53. Formatting • Code formatting is important because is all about communication and read. • The reader should be able to understand the gross structure of the code in a glance. The shapes made by blocks of text help you communicate overall structure. • Easy to read, maintain and extend.
  • 54. Formatting • Source code is like a newspaper article. The farther down we go, the more detailed the article gets. This is the same for code. Types: 1.Vertical Formatting 2. Horizontal Formatting
  • 55. Vertical Formatting ✔ The number of lines of code is should be less than 500 lines. Smaller files are easier to understand than big files. Big files take longer to read and so more time is spent reading code and than doing the actual work. ✔ Vertical formatting deals with the vertical size and vertical distance between elements. ✔ Similar function/concepts grouped together.
  • 56. Swap two numbers using temporary variable public class SwapNumbers { public static void main(String[] args) { float first = 1.20f, second = 2.45f; System.out.println("--Before swap--"); System.out.println("First number = " + first); System.out.println("Second number = " + second); float temporary = first; first = second; second = temporary; System.out.println("--After swap--"); System.out.println("First number = " + first); System.out.println("Second number = " + second); } }
  • 57. Horizontal Formatting • Horizontal formatting deals with the horizontal width and horizontal distance between elements. • Lines should be of the sizes Max100-120 characters. • Olden days 80 characters allowed. Example: x = 1; X + = 1;
  • 58. Horizontal Formatting • Horizontal Openness: How we used the horizontal spaces to the code. On the other hand, didn’t put spaces between the function names and the opening parenthesis. This is because the function and its arguments are closely related. Separate arguments to highlight the comma and show that the arguments are separate.
  • 59. Horizontal Formatting Indentation • Indentation is also part of horizontal formatting. A source file contains a hierarchy of scopes like class, method, block etc. • It is a good practice to indent the lines of source code according to their hierarchy levels so that it would be easy to visualize the concept. • indentation of blocks of code to convey program structure • Indentation refers to the spaces at the beginning of a code line.
  • 60. Horizontal Formatting Class MyClass { instanceVar; public static void myMethod() { int var1 = 1; { int var2 = 2; } } }
  • 61. An object is a real-world thing that has properties and actions. In other words, an entity that has state and behavior is known as an object. Objects and Data structures
  • 62. Class • A class is a blueprint for the object. Before we create an object, we first need to define the class. • In other words, a class can also be defined as “group of objects which are common to all objects of one type”.
  • 63. Class Example • Let us consider two objects Samsung Galaxy S4 and iPhone. Suppose Samsung Galaxy S4 have some properties like width = “6.98 cms”, height = “13.6 cm”, OS = “Android”, brand = “Samsung”, price = “1000$” and actions are call(), sendMessage(), browser(), share(). • Now, suppose iPhone has some properties such as width = “5.86 cm”, height = “12.3 cms”, OS = “iOS”, brand = “Apple”, price = “1200$” and actions are call(), sendMessage(), browse(), share(). • Both objects have some different properties and actions but the type is the same “Phone”. This is the class. i.e the name of the class is “Phone”.
  • 65. Data Abstraction • Abstraction is method of hiding the implementation details and showing only the functionality, basically Provides guidelines to build a standard product. Example : • You know how a car look like and how to drive, but you don’t know how to build a car.
  • 66. Example abstract class Bank{ abstract int getRateOfInterest(); } class SBI extends Bank{ output: int getRateOfInterest(){return 7;} Rate of interest:7% } Rate of interest:8% class PNB extends Bank{ int getRateOfInterest(){return 8;} } class TestBank{ public static void main(String args[]){ Bank b; b=new SBI(); System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %"); b=new PNB(); System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %"); }}
  • 67. Object &Data structure • Difference between objects and data structures. • Objects: Hide their data (be private) and have functions to operate on that data. • Data Structures: show their data (be public) and have no meaningful functions.
  • 68. Data and object antisymmetric • Procedural code (code using data structures) makes it easy to add new functions without changing the existing data structures. • Procedural code makes it hard to add new data structures because all the functions must change. • OO code, on the other hand, makes it easy to add new classes without changing existing functions.
  • 71. DTO • DTO- Data Transfer Object. • It is used to transfer the data between classes and modules of your application. • This is a form of a data structure which is a class with public variables and no functions and sometimes called DTO.