0% found this document useful (0 votes)
7 views50 pages

Unit 5 Coding and Unit Testing

Uploaded by

serenelightt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views50 pages

Unit 5 Coding and Unit Testing

Uploaded by

serenelightt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Software Engineering - 303105253

Introduction & Programming


Chapter-5: Coding with
and Unit Testing
ESP8266

Dr. Chintan Thacker


Associate Professor
Department of Artificial Intelligence and Machine Learning
Content

1. Programming principles and guidelines


2. Programming practices
3. Coding Standards
4. Incremental development code
5. Management of code evaluation
6. Unit Testing – procedural units, classes
7. Code Inspection
8. Metrics (size, complexity, cyclomatic, Halstead,
knot count)

INDEX
9. Comparison of different Metrics
Programming Principles and Guidelines
• Programming principles are fundamental rules that guide developers
to write correct, maintainable, and efficient code.
• Important Principles:
1. KISS (Keep It Simple, Stupid): Code should be simple and easy to
understand. Avoid unnecessary complexity in logic and structure.
2. DRY (Don't Repeat Yourself): Avoid duplication of code by using functions,
classes, and modules.
Example: Instead of repeating the same logic in multiple places, use a
reusable function
Programming Principles and Guidelines
• Important Principles:
3. Modularity: Program should be divided into independent modules.
Complex task can be further divided into sub-tasks
4. Single Responsibility Principle: One module/class should perform only one
function
5. Readability: Code should be very easy to read and understand
6. YAGNI (You Aren't Gona Need It): Avoiding adding features that might
never be used. Only write code that is necessary for the current
requirement
Programming Principles and Guidelines
• Programming guidelines ensure code consistency, readability, and quality
across projects.
 Code Readability & Clarity
 Use meaningful variable and function names
 Follow consistent indentation and formatting
 Write comments for complex logic
 Code Structure & Organization
 Follow a modular approach
 Avoid deep nesting
 Use consistent naming conventions
Programming Principles and Guidelines
 Error Handling & Exception Management
 Use try-catch (or try-except) for error handling
 Code Optimization & Performance
 Use efficient algorithms & data structures
 Avoid unnecessary computations
 Use caching/memorization when needed
 Security Best Practices
 Avoid hardcoding sensitive information
 Validate user inputs
Programming Principles and Guidelines
 Code Documentation
 Write doc-strings for functions and classes
 Version Control & Collaboration
 Use Git for version control
 Follow proper branching strategy
 Testing & Debugging
 Write unit tests using frameworks like JUnit, PyTest, etc.
 Use logging instead of print statements for debugging.
Programming Principles and Guidelines
• Programming Practices ensure are recommended techniques followed
during software development to improve code quality and reliability.
1. Writing Readable and Maintainable Code
2. Modular and Structured Programming
3. Version Control and Collaboration
4. Code Optimization and Efficiency
5. Error Handling and Debugging
6. Testing and Code Review
7. Secure Coding Practices
8. Documentation and Code Standards
Coding Standards
• Coding Standards are a set of predefined rules that specify how source
code should be written, formatted, and documented to ensure uniformity,
readability, and maintainability of software.
• Objectives:
1) Improve code readability and understanding
2) Maintain uniform coding style across the project
3) Reduce errors and debugging time
4) Simplify code maintenance and enhancement
5) Support teamwork and collaboration
Coding Standards
• Naming Standards: Defined rules for naming identifiers. Class names,
Function names, Variables, Constants

class StudentRecord
{
int totalMarks;
final int MAX_MARKS = 100;
};
Coding Standards
• Layout/Formatting Standards: Defines how code should be visually
structured. Proper indentation, Use of Spaces, Line length control, one
statement per line
if(marks >= 40) {
result = "Pass";
}
else {
result = "Fail";
}
Coding Standards
• Commenting Standards: Defines how and where comments should be
written
// This method calculates total marks
int calculateTotal(int a, int b) {
return a + b;
}
• Programming Practice Standards: Defines acceptable coding practices.
Avoid hard-coding, Avoid duplicate code, Use Constants, Proper execution
handling
Incremental Development of a Code
• Incremental Development of Code is a software development approach in
which the complete system is designed, developed, tested, and delivered
in small parts (increments) instead of building the entire system at once.

• Each increment adds new functionality to the existing system, and the
software grows step by step until the final product is completed.

• Build a little → Test it → Get feedback → Improve → Add more features


Incremental Development of a Code
Phases (Process) of Incremental Development
1. Planning & Requirements Analysis: Identify key features and break them
into smaller increments.
2. Design & Implementation: Develop the first increment and ensure it meets
a small, well-defined goal.
3. Testing & Evaluation: Perform testing for bugs and performance issues.
4. Integration & Deployment: Deploy the working part of the system to users
or testers.
5. Repeat for the next increment: Based on feedback, refine and expand the
software in the next cycle.
Incremental Development of a Code
Characteristics of Incremental Development
1. Software is divided into small functional modules
2. Each increment is fully functional and tested
3. New features are added without disturbing existing code
4. User feedback is taken after every increment
5. Errors are detected early, reducing risk
Example: (Train Reservation System)
IC1: User Registration & Login Module IC4: Payment Module, Ticket Confirm
IC2: Train Search & View Train Schedule IC5: Ticket Cancel, Refund process
IC3: Ticket Booking & Seat Availability
Incremental Development of a Code
Example of Incremental Development
Imagine developing an E-commerce website using incremental development:
 Increment 1 – Implement login and user authentication.
 Increment 2 – Develop product listing and search functionality.
 Increment 3 – Add shopping cart and checkout.
 Increment 4 – Implement order tracking and payment integration.

Each increment is tested and integrated before moving to the next.


Management of Code Evaluation
• Code evaluation is a systematic process of reviewing, testing, and analyzing
source code to ensure correctness, quality, efficiency, and compliance with
coding standards
Techniques of Code Evaluation:
1) Code Review
Informal examination of code by developers
Identifies logical and syntax errors
E.g. A senior developer check login module for validation
2) Peer Review
Code is reviewed by fellow team members
Improves code quality and knowledge sharing
E.g. One developer reviews another developer’s module before integration
Management of Code Evaluation
3) Static Code Analysis
Code is analyzed without execution
Detects complexity, unused variables, and standard violations

4) Automated Testing
Uses tools to test code automatically
Ensures correctness and performance
E.g. Using JUnit to automatically test all methods of a class

Benefits:
1) Early detection of Bugs
2) Improve performance and efficiency
3) Better code readability and maintainability
4) Reduced cost of fixing errors
Testing
• Testing refers to evaluating a system or application to identify and rectify
any discrepancies between expected and actual results

Why Testing is Required??

• Errors are introduced during requirement, design, and coding


• Untested software may fail in real-time usage
• Cost of fixing bugs increases after deployment

Software testing is broadly classified into:


• Levels of Testing
• Techniques of Testing
• Functional vs Non-Functional Testing
Testing
Need of Testing:
1) Bug Detection: Identify and fix bugs in the software from minor to critical
errors that can cause system failure

2) Ensure Reliability: Provides confidence about system’s reliability in terms of


performance under various conditions

3) Confirms Compliance: Verifies if the software meets as per the needs of the
customer

4) Enhance User-Experience: Improve the end-user experience


5) Saves Time and Money: Identifying and rectifying issues during testing is
more cost-effective and efficient
6) Improves Maintenance: A well-tested software is easier to maintain and
update, providing a stable foundation for future development
Testing
Principles of Software Testing
 All the tests should meet the customer’s requirements.
 To make our software testing should be performed by a third party.
 Exhaustive testing is not possible (can’t test every single possible
input and scenario for software)
 All the tests to be conducted should be planned before implementing
it
 Start testing with small parts and extend it to large parts.
Testing
Testing
1. Manual: Manual testing is like checking each part of a project by
hand, without using any special tools. People, like developers, do
each step of the testing themselves.

2. Automated: Automated unit testing is a way of checking if software


works correctly without needing lots of human effort. We use special
tools made by people to run these tests automatically.
Testing
Types of Unit Testing

The unit tes ng types are listed below −


a) Black Box Testing:
• The testing is done without the internal knowledge of the products. It is also called
Functional testing.
OR The tester is unaware of the internal structure of the item being tested.
• Black-box testing focuses on software’s external attributes and behavior. This type
of testing looks at an application’s software’s expected behavior from the user’s
point of view.
Testing
b) White Box Testing:
• White-box testing or glass-box testing is a software testing technique that tests the
software by using the knowledge of internal data structures, physical logic flow,
and architecture at the level of source code. OR
White Box Testing - the internal structure is known to the tester
• This testing works by looking at testing from the developer’s point of view.
Testing
c) Gray Box Testing:
• Gray Box Testing is a combination of the Black Box and White Box Testing. The
internal structure is partially known in Gray Box Testing.
• Gray-box testing is well suited for web application testing.
Black-box Testing
A) Functional Testing:
• It is performed to check whether the application is working as per the software’s
functional requirements or not. Various types of functional testing are Unit testing,
Integration testing, System testing, Smoke testing, and so on.

B) Non-Functional Testing:
• It is a type of software testing that checks the application for non-functional
requirements like performance, scalability, portability, stress, etc. Various types of
non-functional testing are Performance testing, Stress testing, Usability Testing,
and so on.
Functional Testing
i) Unit Testing:
• Unit testing is the process of testing the smallest parts of your code, like individual functions
or methods, to make sure they work correctly. It’s a key part of software development that
improves code quality by testing each unit in isolation.
ii) Integration Testing:
• It is a level of the software testing process where individual units are combined and tested as
a group. The purpose of this level of testing is to find faults in the interaction between
integrated units.
iii) System Testing:
• It is a level of the software testing process where a complete, integrated system/software is
tested. The purpose of this test is to evaluate the system’s compliance with the specified
requirements.
Non-Functional Testing
i) Performance Testing:
• It focuses on evaluating the performance and scalability of a system or application. The goal of
performance testing is to measure system performance under various loads and conditions
ii) Usability Testing:
• Usability testing is preferred to evaluate a product or service by testing it with the proper users. To
understand whether the machine is ready to come on the market, potential customers test the
machines.
iii) Capability Testing:
• It is performed on an application to check its compatibility (running capability) on different
platforms/environments. This testing is done only when the application becomes stable. This
means simply test software application functionality on various software, hardware platforms,
networks browser etc.
Integration Testing
I) Incremental Testing:
• Incremental testing builds and tests a system module by module, finding
bugs early in smaller parts. E.g. Top-Down and Bottom-Up

II) Non Incremental Testing:


• Non-incremental testing, also known as big-bang testing, is a software
testing approach where all components or modules of a system are
integrated, and the entire system is tested as a whole.
Incremental Testing
I) Top down Testing:
• Top-down testing approach in which testing is done by integrating or joining two or
more modules by moving down from top to bottom. In these, high-level modules
are tested first, and then low-level modules are tested. Then, finally, integration is
done to ensure that the system is working properly.
II) Bottom Up Testing:
• Bottom-up Testing is a type of incremental integration testing approach in which
testing is done by integrating or joining two or more modules by moving upward
from bottom to top. In these, low-level modules are tested first, and then high-
level modules are tested.
a) Load Testing:
Performance Testing
• Determines how the software application behaves while being accessed by multiple users
simultaneously.
b) Stress Testing:
• We give unfavorable conditions to the system and check how it perform in those conditions.
c) Scalability Testing:
• A process to perform the function correctly when changes are made in the size or volume of
the system to meet a growing need.
d) Stable Testing:
• To check the quality and behavior of the software under different environmental
parameters.
• It is defined as the ability of the product to continue to function over time without failure.
Unit Testing Tools
1. JUnit − JUnit is a unit tes ng framework for Java programming language

2. NUnit − It is a unit tes ng framework for .NET

3. PHPUnit − It is a unit tes ng framework for PHP

4. EMMA - It is a free and open source framework working with Java

5. JMocKit - It is open source Unit testing tool. It is a code coverage tool with line and
path metrics
Code Inspection
• Code inspection aims to review the software code and examine for any errors. This
is known as code verification.
• This code verification checks the software code in all aspects and finds out the
errors that exist in the code.
Purpose of code inspection:
1. It checks for any error that is present in the software code.
2. It checks whether the coding standard is followed or not.
Common Tools for Code Inspection:
 SonarQube (Static Code Analysis)
 Linting Tools (e.g., ESLint, Pylint)
 Code Review Tools (e.g., GitHub Code Review, Crucible)
Code Inspection
Code Inspection Process:
• Planning – Selecting the code for inspection.
• Preparation – Reviewers study the code and related documents.
• Meeting – Discussing issues and suggesting improvements.
• Rework – Developers fix identified issues.
• Follow-up – Ensuring corrections were properly implemented.

Advantages Of Code Inspection : Disadvantages of Code Inspection:


 Improves overall product quality. 1) Requires extra time and planning
 Discovers the bugs/defects in software code. 2) The process is a little slower
 Helps to learn from previous defects.
Software Metrics
• Software Metrics are quantitative measures used to evaluate the size and
complexity of software – i.e. measure software quality and performance

• Size Measure Metrics: measure the Physical size of the Software


Measure

Size Complexity
Measure Measure
Software Metrics
• Size measure is derived by considering the size of software , How big the
Software is !! E.g. Line of Code (LOC), no. of classes and functions etc.
• Easy to calculate & Simple to understand but more LOC != better software

• Set of size measure is given below:

• Size = Kilo Line of Code


• Effort = Person month
• Productivity = KLOC/Person-month
• Cost = $/KLOC
• Quality = Number of faults / KLOC
• Documentation = Pages/KLOC
Software Metrics
• Complexity metrics measure the Logical difficulty and Control Structure
Complexity of a Program.

• Types of Complexity Metrics:


1) Cyclomatic Complexity
2) Halstead Metrics
3) Knot Count
Software Metrics
1) Cyclomatic Complexity: measures the number of independent execution
paths in a program

Formula
𝑉 𝐺 = Number of decision statements + 1
OR
𝑉 𝐺 = 𝐸−𝑁+2
Where:
E = Number of edges in control flow graph
N = Number of nodes

If V(G) value is more then its highly


Complex and difficult to Test
Software Metrics
Software Metrics
2) Halstead Metrics: measure program complexity based on Operators and
Operands
• Basic Terms:
n₁ = Number of distinct operators
n₂ = Number of distinct operands
N₁ = Total no. of occurrences of operators
N₂ = Total no. of occurrences of operands
• Formulas:
Program Length N = N1 + N2 Difficulty D = (n1/2) * (N2/n2)
Program Vocabulary n = n1 + n2 Effort E = D * V
Volume V=N log 𝑛
Software Metrics
Guideline for calculating operands and operators:
1. All the variables and constants are considered as operands. main is also considered as an operand
2. Local variables with same name, if occurring in different functions are counted as unique operand.
3. Function calls are considered as operators.
4. The looping statements, do … while, while, for, are operators. The statements if, if … else, are
operators. The switch … case statements are considered as operators.
5. The reserve words, returns, default, continue, break, sizeof are all operators.
6. The brackets, commas, semicolons, are operators.
7. The unary and binary operators are considered as operators. The & is considered as operator.
8. In arrays, array name and index are considered as operands and [ ] is considered as operator.
9. All hash directives can be ignored.
10. Comments are not considered.
11. In Goto statement, goto is considered as operator and label as operand.
Software Metrics
For example:
#include<stdio.h>
int main()
{
int a = 5, b = 10, c;
if (a > b)
{
c = a + b;
}
return 0;
}
Software Metrics
For example: Operators: int = , if > + return { } ( )(n1=9)
#include<stdio.h> N1: int=2, =3, if=1, ,2 , >=1, +=1, return=1 ,{}=1,()=1(13)
int main() { Operands: a, b, c, 5, 10, 0, main (n2=7)
int a = 5, b = 10, c; N2 = a-2, b-2, c-1, 5-1, 10-1, 0-1 (8)
if (a > b) { Program vocabulary n = n1+n2 = 16
c = a + b; Program Length N = N1 + N2 = 21
} Program Volume V = 21×log2(16) = 84
return 0; D = (9/2) * (8/7) = 5.14
} E = 5.14 * 84 = 432
Software Metrics
Software Metrics
3) Knot Count: measure the number of crossing (intersections) in the CFG of a
program
• A Knot occurs when two control flow paths cross each other in the CFG
• If Edges crossing each other in CFG -> It forms a Knot
• More Crossings -> More tangled Logic -> Higher Complexity
Purpose:
• To measure structural complexity
• To detect poorly structured programs
• To improve maintainability
Software Metrics
3) Knot Count:
int i = 0; if (a > 0)
while(i < 10){ {
if(i % 2 == 0){ goto L1:
[Link]("Even"); }
} else { if (b > 0)
[Link]("Odd"); {
} L1:
i++; [Link](“Hello”);
} -> Proper Nesting, No Crossing } -> Crossing the logical flow
Comparison of Different Software Metrics

Metric Measures Formula Advantage Limitation

LOC Size Count lines Simple No logic measure

Cyclomatic Path complexity Decisions + 1 Helps testing Ignores size

Halstead Mental effort V = N log₂ n Mathematical Complex

Structural Detects bad


Knot Count Count crossings Rarely used
complexity design
PPT Content Resources Reference :

1. Book Reference
Software Engineering: A Practitioner's Approach, by [Link] published
by TMH.
2. Reference Books:
3. Software Engineering, 8th Edition by Sommerville, Pearson.
4. Software Engineering 3rd Edition by Rajiv Mall, PHI.
5. An Integrated Approach to Software Engineering by Pankaj Jalote Wiley India, 2009.

You might also like