SlideShare uma empresa Scribd logo
1 de 81
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 for all but the most
transient of objects.
• 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);
c = a%b;
printf("a % b = %d n",c);
return 0;
}
Output:
a+b = 13
a-b = 5
a*b = 36
a/b = 2
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);
}
return 0;
}
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()
{ // ... }
private void pourWater()
{ // ... }
}
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.
• Even a switch statement only with 2 cases is longer than 10
lines.
• 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():
Clean Code - Functions
• Function Arguments-use limited no of argument inside the
function.
Example:
Bad code
Add address(road,block,city,state,country)
Rules:
Avoid output arguments-function will take some inputs and return
outputs. So, don’t call functions by output arguments.
Clean Code - Functions
Ask Question: A function can ask questions about the input
argument. file_exists = file_exists('myfile') - this simple function
check if the file named myfile exists or not and return a boolean
value.
No Side Effects: function should only have a responsibility to
fulfill.
Transform & Return: A function can transform the input
argument and return it.
Have no duplications
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.
DISTINCT NAME
• Use Pronounceable Names-Ensure that names are pronounceable.
• Example:
Date generation Timestamp;
Date modification Timestamp;
Date genymdhms;Date modymdhms;
• Use Searchable Names
If a variable or constant might be seen or used in multiple places in a
body of code, it is essential to give it a search-friendly name.
• Pick One Word per Concept-Avoid using different but similar
words to define the same concepts. Ex:FetchValue() vs GetValue()
vs RetrieveValue()
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];
Defining meaningful context
• You can add context by creating a class name Address and make
those variables as attributes of this class. This is the better solution.
• Example
Public Class address
{
String firstname();
String lastname();
}
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. Very often the
code is changed but the old comments remain the same.
• One of the more common motivations for writing comments is
bad code.
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 explanation of intent.
• 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");
}
}
Comment rule
Don't comment out code.
• Do not leave the code commented out.
• As senior developers, you should not approve these kinds of codes
of your junior developers.
• "Before you commit, remove all “commented-out” code“
Use as explanation of intent.
• Sometimes a comment goes beyond just useful information about
the implementation and provides the intent behind a decision.
Comment rule
• Use as clarification of code.
Sometimes it is just helpful to translate the meaning of some
argument or return value into something that’s readable.
Exactly what our goal is in some cases. That is why we must add
comment that clarify more and justify why we have not taken a
particular action.
Use as warning of consequences.
Sometimes it is useful to warn other programmers about certain
significances.
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. Topmost parts of the source file should provide the high
level concepts or abstractions and details should increase as we
move downward.
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);
}
}
Vertical Formatting
• Vertical openness-The blank lines that separate the package
declaration, the import(s), and each of the functions.
• Vertical density/distance.-Implies close association. Concepts that
are closely related should be kept vertically close to each other.
• Variable declarations-Closely related concepts (variables or
functions) should not be separated into different files. Instance
variable declarations should be in one location and most preferably
on the top of the class, or at least in the bottom.
Vertical Formatting
• Dependent Functions. If one function calls another, they should be
vertically close, and the caller should be above the callee, if at all
possible. This gives the program a natural flow.
• Conceptual Affinity. Certain bits of code want to be near other bits.
They have a certain conceptual affinity. this affinity might be based
on a direct dependence, such as one function calling another, or a
function using a variable. … Affinity might be caused because a
group of functions perform a similar operation.
Horizontal Formatting
• Horizontal formatting deals with the horizontal width and
horizontal distance between elements.
• Lines should be of the sizes Max100-120 characters.
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.
Example:
x = 1;
x + = 1;
count++;
public void method(Argument arg, Argument2 arg2)
{
y = -b / (2*a); y = c*2 +y*5;
}
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
• 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 “a class is a
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.
• OO code makes it hard to add new functions because all the
classes must change.
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.
CLEAN CODING AND DEVOPS Final.pptx

Mais conteĂşdo relacionado

Mais procurados

Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationViji B
 
Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2MOHIT TOMAR
 
Functions in c++
Functions in c++Functions in c++
Functions in c++Maaz Hasan
 
Function in c program
Function in c programFunction in c program
Function in c programumesh patil
 
Functions in C
Functions in CFunctions in C
Functions in CKamal Acharya
 
User defined functions
User defined functionsUser defined functions
User defined functionsRokonuzzaman Rony
 
Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C LanguageNitesh Kumar Pandey
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and StringTasnima Hamid
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and PackagesDamian T. Gordon
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++Aabha Tiwari
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT03062679929
 
Break and continue
Break and continueBreak and continue
Break and continueFrijo Francis
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingabhay singh
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programmingprogramming9
 
Operators in C++
Operators in C++Operators in C++
Operators in C++Sachin Sharma
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloadingMd. Ashraful Islam
 
data types in C programming
data types in C programmingdata types in C programming
data types in C programmingHarshita Yadav
 
C++ programming function
C++ programming functionC++ programming function
C++ programming functionVishalini Mugunen
 

Mais procurados (20)

Data types in c++
Data types in c++Data types in c++
Data types in c++
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Functions in C
Functions in CFunctions in C
Functions in C
 
User defined functions
User defined functionsUser defined functions
User defined functions
 
Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Break and continue
Break and continueBreak and continue
Break and continue
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
 
Operators in C++
Operators in C++Operators in C++
Operators in C++
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
 
data types in C programming
data types in C programmingdata types in C programming
data types in C programming
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 

Semelhante a CLEAN CODING AND DEVOPS Final.pptx

05 Lecture - PARALLEL Programming in C ++.pdf
05 Lecture - PARALLEL Programming in C ++.pdf05 Lecture - PARALLEL Programming in C ++.pdf
05 Lecture - PARALLEL Programming in C ++.pdfalivaisi1
 
Presentation c++
Presentation c++Presentation c++
Presentation c++JosephAlex21
 
Programming Language
Programming  LanguageProgramming  Language
Programming LanguageAdeel Hamid
 
C++primer
C++primerC++primer
C++primerleonlongli
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slidesluqman bawany
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddSrinivasa GV
 
73d32 session1 c++
73d32 session1 c++73d32 session1 c++
73d32 session1 c++Mukund Trivedi
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptxmiki304759
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basicsLovelitJose
 
ProgrammingPrimerAndOOPS
ProgrammingPrimerAndOOPSProgrammingPrimerAndOOPS
ProgrammingPrimerAndOOPSsunmitraeducation
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptxVijalJain3
 
Functions in c
Functions in cFunctions in c
Functions in creshmy12
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVAMuskanSony
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principlesdeonpmeyer
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programmingRutvik Pensionwar
 
C#unit4
C#unit4C#unit4
C#unit4raksharao
 

Semelhante a CLEAN CODING AND DEVOPS Final.pptx (20)

c++ Unit I.pptx
c++ Unit I.pptxc++ Unit I.pptx
c++ Unit I.pptx
 
05 Lecture - PARALLEL Programming in C ++.pdf
05 Lecture - PARALLEL Programming in C ++.pdf05 Lecture - PARALLEL Programming in C ++.pdf
05 Lecture - PARALLEL Programming in C ++.pdf
 
Presentation c++
Presentation c++Presentation c++
Presentation c++
 
Programming Language
Programming  LanguageProgramming  Language
Programming Language
 
C++primer
C++primerC++primer
C++primer
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slides
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tdd
 
c#.pptx
c#.pptxc#.pptx
c#.pptx
 
73d32 session1 c++
73d32 session1 c++73d32 session1 c++
73d32 session1 c++
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
ProgrammingPrimerAndOOPS
ProgrammingPrimerAndOOPSProgrammingPrimerAndOOPS
ProgrammingPrimerAndOOPS
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
Functions in c
Functions in cFunctions in c
Functions in c
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Prog1-L1.pdf
Prog1-L1.pdfProg1-L1.pdf
Prog1-L1.pdf
 
C#unit4
C#unit4C#unit4
C#unit4
 

Mais de JEEVANANTHAMG6

Introduction to NodeJS JSX is an extended Javascript based language used by R...
Introduction to NodeJS JSX is an extended Javascript based language used by R...Introduction to NodeJS JSX is an extended Javascript based language used by R...
Introduction to NodeJS JSX is an extended Javascript based language used by R...JEEVANANTHAMG6
 
1. Arithmetic Operations - Addition and subtraction of signed numbers.pptx
1. Arithmetic Operations - Addition and subtraction of signed numbers.pptx1. Arithmetic Operations - Addition and subtraction of signed numbers.pptx
1. Arithmetic Operations - Addition and subtraction of signed numbers.pptxJEEVANANTHAMG6
 
7. Input Output Operations.pptx
7. Input Output Operations.pptx7. Input Output Operations.pptx
7. Input Output Operations.pptxJEEVANANTHAMG6
 
MIPS IMPLEMENTATION.pptx
MIPS IMPLEMENTATION.pptxMIPS IMPLEMENTATION.pptx
MIPS IMPLEMENTATION.pptxJEEVANANTHAMG6
 
EITK UNIT - III.pptx
EITK UNIT - III.pptxEITK UNIT - III.pptx
EITK UNIT - III.pptxJEEVANANTHAMG6
 
Arithmetic for Computers.ppt
Arithmetic for Computers.pptArithmetic for Computers.ppt
Arithmetic for Computers.pptJEEVANANTHAMG6
 
6. Addressng Modes.pptx
6. Addressng Modes.pptx6. Addressng Modes.pptx
6. Addressng Modes.pptxJEEVANANTHAMG6
 
1.Basic Structure of Computer System.ppt
1.Basic Structure of Computer System.ppt1.Basic Structure of Computer System.ppt
1.Basic Structure of Computer System.pptJEEVANANTHAMG6
 

Mais de JEEVANANTHAMG6 (9)

Introduction to NodeJS JSX is an extended Javascript based language used by R...
Introduction to NodeJS JSX is an extended Javascript based language used by R...Introduction to NodeJS JSX is an extended Javascript based language used by R...
Introduction to NodeJS JSX is an extended Javascript based language used by R...
 
1. Arithmetic Operations - Addition and subtraction of signed numbers.pptx
1. Arithmetic Operations - Addition and subtraction of signed numbers.pptx1. Arithmetic Operations - Addition and subtraction of signed numbers.pptx
1. Arithmetic Operations - Addition and subtraction of signed numbers.pptx
 
7. Input Output Operations.pptx
7. Input Output Operations.pptx7. Input Output Operations.pptx
7. Input Output Operations.pptx
 
MIPS IMPLEMENTATION.pptx
MIPS IMPLEMENTATION.pptxMIPS IMPLEMENTATION.pptx
MIPS IMPLEMENTATION.pptx
 
EITK UNIT - III.pptx
EITK UNIT - III.pptxEITK UNIT - III.pptx
EITK UNIT - III.pptx
 
UNIT I.ppt
UNIT I.pptUNIT I.ppt
UNIT I.ppt
 
Arithmetic for Computers.ppt
Arithmetic for Computers.pptArithmetic for Computers.ppt
Arithmetic for Computers.ppt
 
6. Addressng Modes.pptx
6. Addressng Modes.pptx6. Addressng Modes.pptx
6. Addressng Modes.pptx
 
1.Basic Structure of Computer System.ppt
1.Basic Structure of Computer System.ppt1.Basic Structure of Computer System.ppt
1.Basic Structure of Computer System.ppt
 

Último

NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...Amil Baba Dawood bangali
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfRajuKanojiya4
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESNarmatha D
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxsiddharthjain2303
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating SystemRashmi Bhat
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxVelmuruganTECE
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 

Último (20)

NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdf
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIES
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptx
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating System
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptx
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 

CLEAN CODING AND DEVOPS Final.pptx

  • 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 for all but the most transient of objects. • 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); c = a%b; printf("a % b = %d n",c); return 0; } Output: a+b = 13 a-b = 5 a*b = 36 a/b = 2
  • 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); } return 0; }
  • 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() { // ... } private void pourWater() { // ... } }
  • 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. • Even a switch statement only with 2 cases is longer than 10 lines. • 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. Clean Code - Functions • Function Arguments-use limited no of argument inside the function. Example: Bad code Add address(road,block,city,state,country) Rules: Avoid output arguments-function will take some inputs and return outputs. So, don’t call functions by output arguments.
  • 38. Clean Code - Functions Ask Question: A function can ask questions about the input argument. file_exists = file_exists('myfile') - this simple function check if the file named myfile exists or not and return a boolean value. No Side Effects: function should only have a responsibility to fulfill. Transform & Return: A function can transform the input argument and return it. Have no duplications
  • 39. 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 .
  • 40. 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)
  • 41. 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.
  • 42. DISTINCT NAME • Use Pronounceable Names-Ensure that names are pronounceable. • Example: Date generation Timestamp; Date modification Timestamp; Date genymdhms;Date modymdhms; • Use Searchable Names If a variable or constant might be seen or used in multiple places in a body of code, it is essential to give it a search-friendly name. • Pick One Word per Concept-Avoid using different but similar words to define the same concepts. Ex:FetchValue() vs GetValue() vs RetrieveValue()
  • 43. 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];
  • 44. Defining meaningful context • You can add context by creating a class name Address and make those variables as attributes of this class. This is the better solution. • Example Public Class address { String firstname(); String lastname(); }
  • 45. 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.
  • 46. 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
  • 47. 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 }
  • 48. 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
  • 49. 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. Very often the code is changed but the old comments remain the same. • One of the more common motivations for writing comments is bad code.
  • 50. 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); } }
  • 51. 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 explanation of intent. • Use as clarification of code. • Use as warning of consequences.
  • 52. 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); }
  • 53. 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); }
  • 54. 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
  • 55. 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
  • 56. 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"); } }
  • 57. Comment rule Don't comment out code. • Do not leave the code commented out. • As senior developers, you should not approve these kinds of codes of your junior developers. • "Before you commit, remove all “commented-out” code“ Use as explanation of intent. • Sometimes a comment goes beyond just useful information about the implementation and provides the intent behind a decision.
  • 58. Comment rule • Use as clarification of code. Sometimes it is just helpful to translate the meaning of some argument or return value into something that’s readable. Exactly what our goal is in some cases. That is why we must add comment that clarify more and justify why we have not taken a particular action. Use as warning of consequences. Sometimes it is useful to warn other programmers about certain significances.
  • 59. 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.
  • 60. 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. Topmost parts of the source file should provide the high level concepts or abstractions and details should increase as we move downward. Types: 1.Vertical Formatting 2. Horizontal Formatting
  • 61. 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.
  • 62. 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); } }
  • 63. Vertical Formatting • Vertical openness-The blank lines that separate the package declaration, the import(s), and each of the functions. • Vertical density/distance.-Implies close association. Concepts that are closely related should be kept vertically close to each other. • Variable declarations-Closely related concepts (variables or functions) should not be separated into different files. Instance variable declarations should be in one location and most preferably on the top of the class, or at least in the bottom.
  • 64. Vertical Formatting • Dependent Functions. If one function calls another, they should be vertically close, and the caller should be above the callee, if at all possible. This gives the program a natural flow. • Conceptual Affinity. Certain bits of code want to be near other bits. They have a certain conceptual affinity. this affinity might be based on a direct dependence, such as one function calling another, or a function using a variable. … Affinity might be caused because a group of functions perform a similar operation.
  • 65. Horizontal Formatting • Horizontal formatting deals with the horizontal width and horizontal distance between elements. • Lines should be of the sizes Max100-120 characters. Example: x = 1; X + = 1;
  • 66. 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.
  • 67. Example: x = 1; x + = 1; count++; public void method(Argument arg, Argument2 arg2) { y = -b / (2*a); y = c*2 +y*5; }
  • 68. 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.
  • 69. Horizontal Formatting Class MyClass{ instanceVar; public static void myMethod() { int var1 = 1; { int var2 = 2; } } }
  • 70. 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
  • 71. • 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 “a class is a group of objects which are common to all objects of one type”.
  • 72. 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”.
  • 74. 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.
  • 75. 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()+" %"); }}
  • 76. 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.
  • 77. 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. • OO code makes it hard to add new functions because all the classes must change.
  • 80. 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.