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

CLEAN CODING AND DEVOPS Final.pptx

  • 1.
  • 2.
    UNIT I INTRODUCTION TOCLEANCODING • 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 TODEV-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 • Cleancode is code that is easy to understand , easy to change and easy to modify. • Use easy names for variables and methods.
  • 6.
    How to writeclean 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 cleancode • 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 CleanCode • 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 cleancode • 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.
  • 11.
    Good code • Easyto 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 Goodcode #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 • Poorcoding 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 badcode #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 isthe 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 standsfor 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 staticvoid main(String[] args) { System.out.println("Hello, World!"); } }
  • 18.
  • 19.
    UNMARSHALLING • Unmarshalling isthe 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 forclean 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 forclean 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 forclean 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 forclean method/function names • Avoid past tense verb forms. Example: fun opened() {} fun closed() {}
  • 25.
    Best practice forclean 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 forclean variable names • Avoid complicated prefixes such as Hungarian notation. Example: var f_strFirstName = "Joy”
  • 27.
    FUNCTION • A functionis 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 needfunctions • 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 libraryfunctions • 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 • InPython 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  Inorder 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("Pleaseenter 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 NoiseWords 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 • UsePronounceable 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 domainand 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 exceptionsand 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 exceptionsand 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 • Thegoal 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 staticvoid 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 • Alwaystry 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 Yourselfin 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’tbe 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 addobvious 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'tuse 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 staticvoid 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 commentout 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 • Useas 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 formattingis 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 codeis 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  Thenumber 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 numbersusing 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 • Verticalopenness-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 • DependentFunctions. 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 • Horizontalformatting 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 • HorizontalOpenness: 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 • Indentationis 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; publicstatic void myMethod() { int var1 = 1; { int var2 = 2; } } }
  • 70.
    An object isa 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 classis 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 • Letus 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”.
  • 73.
  • 74.
    Data Abstraction • Abstractionis 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{ abstractint 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.
  • 78.
  • 79.
  • 80.
    DTO • DTO- DataTransfer 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.