0% found this document useful (0 votes)
19 views130 pages

Unit 20 - Applied Programming and Design Principles - 2022 - Imasha Emmanuel (E197182)

The document outlines the internal verification process for assessment decisions related to the BTEC Higher National Diploma in Computing, specifically for a project on a Sales Analysis System for Sampath Food City. It includes guidelines for assessment criteria, feedback mechanisms, and a comprehensive assignment brief detailing the tasks and learning outcomes for students. Additionally, it emphasizes the importance of adhering to academic integrity and proper referencing to avoid plagiarism.

Uploaded by

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

Unit 20 - Applied Programming and Design Principles - 2022 - Imasha Emmanuel (E197182)

The document outlines the internal verification process for assessment decisions related to the BTEC Higher National Diploma in Computing, specifically for a project on a Sales Analysis System for Sampath Food City. It includes guidelines for assessment criteria, feedback mechanisms, and a comprehensive assignment brief detailing the tasks and learning outcomes for students. Additionally, it emphasizes the importance of adhering to academic integrity and proper referencing to avoid plagiarism.

Uploaded by

imashaprasad1000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 130

Higher Nationals

Internal verification of assessment decisions – BTEC (RQF)


INTERNAL VERIFICATION – ASSESSMENT DECISIONS
Programme title BTEC Higher National Diploma in Computing - Software Engineering
Assessor Internal Verifier
Unit(s) Unit 20: Applied Programming and Design Principles
Assignment title Sales Analysis System for Sampath Food City (PVT) Ltd
Student’s name
List which assessment Pass Merit Distinction
criteria the Assessor has
awarded.
INTERNAL VERIFIER CHECKLIST
Do the assessment criteria awarded match
those shown in the assignment brief? Y/N

Is the Pass/Merit/Distinction grade awarded


justified by the assessor’s comments on the Y/N
student work?
Has the work been assessed
Y/N
accurately?
Is the feedback to the student:
Give details:

• Constructive?
Y/N
• Linked to relevant
Y/N
assessment criteria?
• Identifying opportunities
for improved performance? Y/N

Y/N
• Agreeing actions?
Does the assessment decision need
Y/N
amending?
Assessor signature Date

Internal Verifier signature Date


Programme Leader signature (if
Date
required)

Confirm action completed


Remedial action taken

Give details:

Assessor signature Date

Internal Verifier
Date
signature 1
Programme Leader
Date
signature (if required)
Higher Nationals - Summative Assignment Feedback Form
Student Name/ID Imasha Emmanuel (00180239)

Unit Title Unit 20: Applied Programming and Design Principles


Assignment Number Assessor
8/6/2024 Date Received 1st
Submission Date
submission
Date Received 2nd
Re-submission Date
submission

2
Assessor Feedback:

LO1. Investigate the impact of SOLID development principles on the OOP paradigm

Pass, Merit & Distinction P1 P2 M1 D1


Descripts
LO2. Design a large dataset processing application using SOLID principles and clean coding techniques

Pass, Merit & Distinction P3 P4 M2


Descripts

LO3. Build a data processing application based on a developed design


Pass, Merit & Distinction P5 M3
Descripts

LO4. Perform automatic testing on a data processing application


Pass, Merit & Distinction P6 P7 M4 D2
Descripts

Grade: Assessor Signature: Date:

Resubmission Feedback:

Grade: Assessor Signature: Date:

Internal Verifier’s Comments:

Signature & Date:


* Please note that grade decisions are provisional. They are only confirmed once internal and external moderation has taken place and grades decisions have been agreed at the
assessment board.

Assignment Feedback
Formative Feedback: Assessor to Student

3
Action Plan

Summative feedback

Feedback: Student to Assessor

Assessor signature Date

Student signature Date

Pearson
4
Higher Nationals in
Computing
Unit 20: Applied Programming and Design Principles
Assignment 01

General Guidelines

5
1. A Cover page or title page – You should always attach a title page to your assignment. Use previous page as your cover sheet
and make sure all the details are accurately filled.
2. Attach this brief as the first section of your assignment.
3. All the assignments should be prepared using a word processing software.
4. All the assignments should be printed on A4 sized papers. Use single side printing.
5. Allow 1” for top, bottom , right margins and 1.25” for the left margin of each page.

Word Processing Rules

1. The font size should be 12 point, and should be in the style of Time New Roman.
2. Use 1.5 line spacing. Left justify all paragraphs.
3. Ensure that all the headings are consistent in terms of the font size and font style.
4. Use footer function in the word processor to insert Your Name, Subject, Assignment No, and Page Number on each pag e.
This is useful if individual sheets become detached for any reason.
5. Use word processing application spell check and grammar check function to help editing your assignment.

Important Points:

1. It is strictly prohibited to use textboxes to add texts in the assignments, except for the compulsory information. eg: Figures,
tables of comparison etc. Adding text boxes in the body except for the before mentioned compulsory information will result
in rejection of your work.
2. Carefully check the hand in date and the instructions given in the assignment. Late submissions will not be accepted.
3. Ensure that you give yourself enough time to complete the assignment by the due date.
4. Excuses of any nature will not be accepted for failure to hand in the work on time.
5. You must take responsibility for managing your own time effectively.
6. If you are unable to hand in your assignment on time and have valid reasons such as illness, you may apply (in writing) for an
extension.
7. Failure to achieve at least PASS criteria will result in a REFERRAL grade .
8. Non-submission of work without valid reasons will lead to an automatic RE FERRAL. You will then be asked to complete an
alternative assignment.
9. If you use other people’s work or ideas in your assignment, reference them properly using HARVARD referencing system to
avoid plagiarism. You have to provide both in-text citation and a reference list.
10. If you are proven to be guilty of plagiarism or any academic misconduct, your grade could be reduced to A REFERRAL or at
worst you could be expelled from the course.
11. If you are proven to be guilty of plagiarism or any academic misconduct, your grade could be reduced to A REFERRAL or at
worst you could be expelled from the course.

6
Student Declaration

I hereby, declare that I know what plagiarism entails, namely to use another’s work and to present it as my own without attributing
the sources in the correct way. I further understand what it means to copy another’s work.

1. I know that plagiarism is a punishable offence because it constitutes theft.


2. I understand the plagiarism and copying policy of the Pearson UK.
3. I know what the consequences will be if I plagiaries or copy another’s work in any of the assignments for this program.
4. I declare therefore that all work presented by me for every aspects of my program, will be my own, and where I have made
use of another’s work, I will attribute the source in the correct way.
5. I acknowledge that the attachment of this document signed or not, constitutes a binding agreement between myself and
Pearson, UK.
6. I understand that my assignment will not be considered as submitted if this document is not attached to the attached.

Student’s Signature: Date:


(Provide E-mail ID) (Provide Submission Date)
[email protected] 8/6/2024

7
Assignment Brief
Student Name /ID Number Imasha Emmanuel (00180239)

Unit Number and Title Unit 20: Applied Programming and Design Principles

Academic Year 2022/2023

Unit Tutor Mr. Vishmal Gamage

Assignment Title Sales Analysis System for Sampath Food City (PVT) Ltd

Issue Date

Submission Date 8/6/2024

IV Name & Date

Submission Format:
Part 1.
Report- Submit a professional report with appropriate report formatting and guidelines followed. All the research
data should be referenced along with in-text citations using the Harvard referencing system.

Part 2
A fully functional standalone software system (command-line interface based)

Unit Learning Outcomes:


LO1 Investigate the impact of SOLID development principles on the OOP paradigm.

LO2 Design a large dataset processing application using SOLID principles and clean coding techniques.

LO3 Build a data processing application based on a developed design.

LO4 Perform automatic testing on a data processing application.

Assignment Brief and Guidance:

8
Assignment Brief
Scenario.
‘Data Labs’ is a leading software development company in Sri Lanka. They are focusing on helping businesses to
build their businesses through creative and effective solutions. Assume that you work as an apprentice software
developer for Data Labs company. As a part of your role, you have been asked to develop a software system
(command-line interface based) for the following scenario using python programming language.

Sampath Food City (PVT) Ltd is one of the main supermarket networks in Sri Lanka. Currently, Sampath
Food City has several branches island wide. At present, transactions of each branch are recorded through
a point of sale (pos) system. At the end of each month, recorded data of each point of the sales system are
transferred to a centralized database. Top-level management of the company use the centralized data to do
the monthly sales data analysis of the whole company at the end of the month to find insights to take
managerial decisions for the company. Currently, the company uses a paper-based manual system to do
monthly sales data analysis. Some weaknesses and drawbacks that have occurred in the manual system
such as human errors leading to inaccurate information, time consuming, data redundancy, inconsistency
and difficulty to find insights affect the business performance negatively.
Therefore, the management of Sampath Food City has decided that using a customized software system
for sales data analysis is the solution for eliminating above mentioned weaknesses and drawbacks of the
existing sales data analysis process.
Assume yourself as a software developer of Data Labs (PVT) Ltd and assigned to develop a sales data
analysis system (command-line interface based) using python programming language for scenario given
above.
New system should provide following features:
 Monthly sales analysis of each branch.
 Price analysis of each product
 Weekly sales analysis of supermarket network
 Product preference analysis
 Analysis of the distribution of total sales amount of purchases

Develop a command-line interface-based solution for the above scenario and produce a report covering the
following tasks.

Activity 1

 Investigate the characteristics of the object-orientated paradigm, including class relationships


(inheritance, association, composition, aggregation) and evaluate the impact pf SOLID principles (single
9
responsibility principle, open/closed principle, Liskov’s substitution principle, interface segregation
principle and dependency inversion principle) by taking suitable examples incorporating UML diagrams
and coding samples. Your answer should include suitable examples to evaluate the impact of SOLID
principles in Object oriented Development.

 Explain how clean coding techniques can impact on the use of data structures and operations when
writing algorithms by taking suitable examples from the given scenario. Analyse each of the creational,
structural and behavioral design patterns with relevant examples.

Activity 2

 Design a large data set processing application, utilising SOLID principles, clean coding techniques, a design
pattern and data structures by providing justifications for selected design pattern and selected data
structures.
 Design a suitable testing regime for the application developed with a provision for automated testing,
selected test types and selected automatic testing tools, and provide justifications for the selections.
Refine the design to include multiple design patterns by justifying the reasons for the inclusion of each
design pattern for the given scenario.

Activity 3

Build a large dataset processing application based on the design produced, by using python programming
language and provide evidence for the usage of data structures and file handling techniques. Your answer must
include an assessment of how effective the use of SOLID principles, clean coding techniques and programming
patterns on the application developed. Take suitable examples from the developed application to elaborate your
answer.

Activity 4
 Examine the benefits and drawbacks of different methods of automatic testing of applications and
software systems available for automatic testing by taking examples from the developed application.
Provide an action plan to address the identified drawbacks of testing of the developed application.
 Implement automatic testing of the developed application by using selected testing tools and provide
evidence for the automatic testing. Discuss how developer-produced and vendor-provided automatic
testing tools differ for applications and software systems by taking suitable examples from the testing of

10
the developed application.

11
Grading Rubric
Grading Criteria Achieved Feedback

LO1 Investigate the impact of SOLID development principles on the


OOP paradigm.
P1 Investigate the characteristics of the object orientated paradigm,
including class relationships and SOLID principles.

P2 Explain how clean coding techniques can impact on the use of data
structures and operations when writing algorithms.

M1 Analyse, with examples, each of the creational, structural and


behavioral design pattern types.

D1 Evaluate the impact of SOLID development principles on object


orientated application development.

LO2 Design a large dataset processing application using SOLID


principles and clean coding techniques.
P3 Design a large data set processing application, utilising SOLID
principles, clean coding techniques and a design pattern.

P4 Design a suitable testing regime for the application, including


provision for automated testing.

M2 Refine the design to include multiple design patterns.

LO3 Build a data processing application based on a developed design

P5 Build a large dataset processing application based on the design


produced.

12 Applied Programming and Design Principles Assignment no 1


M3 Assess the effectiveness of using SOLID principles, clean coding
techniques and programming patterns on the application developed.

LO4 Perform automatic testing on a data processing application.


P6 Examine the different methods of implementing automatic testing
as designed in the test plan.
P7 Implement automatic testing of the developed application.

M4 Discuss the differences between developer-produced and vendor-


provided automatic testing tools for applications and software
systems.

D2 Analyse the benefits and drawbacks of different forms of


automatic testing of applications and software systems, with
examples from the developed application.

13 Applied Programming and Design Principles Assignment no 1


1
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
OBSERVATION RECORD

Learner name:
Qualification:
Unit number &
title:
Description of activity undertaken

Assessment criteria

How the activity meets the requirements of the assessment


criteria

Learner name:
Learner Date
signature: :
Assessor
name:
Assessor Date
signature: :
1
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
WITNESS STATEMENT

Learner
name:
Qualification:
Unit number
& title:
Description of activity undertaken (please be as specific as
possible)

Assessment criteria (for which the activity provides evidence)

How the activity meets the requirements of the assessment


criteria, including how and where the activity took place

Witness Job
name: role:
Witness Dat
signature: e:
Learner
name:

2
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Learner Dat
signature: e:
Assessor
name:
Assessor Dat
signature: e:

3
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Contents
OBSERVATION RECORD..................................................................................................................................1
WITNESS STATEMENT......................................................................................................................................2
Figure Numbers..................................................................................................................................................5
Table Numbers...................................................................................................................................................7
Acknowledgement..............................................................................................................................................8
Introduction........................................................................................................................................................9
LO1 Investigate the impact of SOLID development principles on the OOP paradigm...................................10
1.1 Object-Oriented Programming (OOP)..........................................................................................................10
1.1.1 Main Principles of OOP............................................................................................................................10
1.1.2 Benefits of OOP............................................................................................................................................15
1.1.3 Foundational building blocks of Object-Oriented Programming (OOP)........................................................17
1.1.4 Class Relation................................................................................................................................................19
1.1.5 SOLID Principles in OOP................................................................................................................................23
1.2 Clean Coding................................................................................................................................................28
1.2.1 Clean Coding Techniques.........................................................................................................................29
1.2.2 Data Structures and Operations..............................................................................................................31
1.3 Design patterns in software engineering......................................................................................................34
1.3.1 Design Pattern Types...............................................................................................................................35
1.4 Evaluate the impact of SOLID development principles........................................................................................52
1.4.1 The impact of SOLID principles on object-oriented application developing a sales data analysis system for
Sampath Food City................................................................................................................................................53
LO2 Design a large dataset processing application using SOLID principles and clean coding techniques....54
2.1 Designing a large dataset processing application for Sampath Food City............................................................54
2.2 Designing a suitable testing regime for the sales data analysis system for Sampath Food City..........................57
2.3 Testing regime is particularly suitable for Sampath Food City's sales data analysis system................................59
2.4 Refining the design to include multiple design patterns......................................................................................63
LO3 Build a data processing application based on a developed design..........................................................75
3.1 Building a Large Dataset Processing Application for Sampath Food City (PVT) Ltd.............................................75
3.2 Assessing the effectiveness of employing SOLID principles, clean coding techniques, and programming patterns
in the development of Sampath Food City (PVT) Ltd.................................................................................................78
LO4 Perform automatic testing on a data processing application....................................................................82
4.1 Examine the different methods of implementing automatic testing for the data processing application
developed for Sampath Food City (PVT) Ltd..............................................................................................................82
4.2 Test Plan for Sampath Food City (PVT) Ltd. Sales Data Analysis System..............................................................85
4.3 Test Plan for Sampath Food City (PVT) Ltd. Sales Data Analysis System..............................................................88

4
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
4.4 Discuss the Difference between developer produced and vendor – provided automatic testing tools..............97
4.5 Considering the testing needs for Sampath Food City's sales data analysis system..........................................101
4.6 Benefits and Drawbacks of different forms of automatic testing of Application and software systems...........104
Conclusion...............................................................................................................................................................108
Appendix........................................................................................................................................................109
References......................................................................................................................................................111
Image Links....................................................................................................................................................111

Figure Numbers
Figure 1 Main Principles of OOP.......................................................................................................................9
Figure 2 Encapsulation.....................................................................................................................................10
Figure 3 Abstraction.........................................................................................................................................11
Figure 4 Inheritance.........................................................................................................................................12
Figure 5 Polymorphism....................................................................................................................................13
Figure 6 OOP Class and Objects......................................................................................................................15
Figure 7 Foundational building blocks of Object-Oriented Programming (OOP)..........................................16
Figure 8 Class Relation (Author's Work).........................................................................................................18
Figure 9 Association........................................................................................................................................18
Figure 10 Composition.....................................................................................................................................19
Figure 11 Aggregation.....................................................................................................................................20
Figure 12 Inheritance.......................................................................................................................................21
Figure 13 UML Class Diagram (Author's Work)............................................................................................23
Figure 14 Sequential Graph (Author's Work)..................................................................................................24
Figure 15 Encapsulation: Protecting the sales data within SalesRecord. (Author's Work).............................25
Figure 16 Inheritance: Extending Product for different types of items (e.g., perishable goods). (Author's
Work)...............................................................................................................................................................25
Figure 17 SalesRecord (Author's Work)..........................................................................................................25
Figure 18 Clean Code.......................................................................................................................................27
Figure 19 Singleton Pattern (Author's Work)..................................................................................................35
Figure 20Factory Method Pattern (Author's Work).........................................................................................36
Figure 21 Abstract Factory Pattern (Author's Work).......................................................................................37
Figure 22 Builder Pattern (Author's Work)......................................................................................................38
Figure 23 Prototype Pattern (Author's Work)..................................................................................................39
Figure 24 Adapter (Wrapper) Pattern (Author's Work)...................................................................................40
Figure 25 Composite Pattern (Author's Work)................................................................................................41
Figure 26 Flyweight Pattern (Author's Work).................................................................................................43
Figure 27 Decorator Pattern (Author's Work)..................................................................................................44
Figure 28 Observer Pattern (Author's Work)...................................................................................................46
Figure 29 Strategy Pattern (Author's Work)....................................................................................................47
Figure 30 Command Pattern (Author's Work).................................................................................................48
Figure 31 State Pattern (Author's Work)..........................................................................................................49
Figure 32 Mediator Pattern (Author's Work)...................................................................................................50
Figure 33 Design Pattern: Strategy Pattern (Author's Work)...........................................................................55
Figure 34 Abstract Factory Pattern for Data Loading (Author's Work).........................................................62
Figure 35 Composite Pattern for Data Analysis (Author's Work)...................................................................63
5
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Figure 36 Decorator Pattern for Report Generation (Author's Work).............................................................64
Figure 37 Strategy Pattern for Data Processing (Author's Work)....................................................................65
Figure 38 Observer Pattern for Real-Time Dashboard Updates (Author's Work)...........................................66
Figure 39 Factory Method Pattern for Report Creation (Author's Work)........................................................67
Figure 40 Abstract Factory Pattern for Data Loading (Author's Work).........................................................68
Figure 41 Composite Pattern for Data Analysis (Author's Work)...................................................................69
Figure 42 Decorator Pattern for Report Generation (Author's Work).............................................................70
Figure 43 Strategy Pattern for Data Processing. (Author's Work)...................................................................71
Figure 44 Observer Pattern for Real-Time Dashboard Updates (Author's Work)...........................................72
Figure 45 Factory Method Pattern for Report Creation. (Author's Work).......................................................73
Figure 46 DataLoader Class Example (Author's Work)..................................................................................74
Figure 47 SalesAnalysis Interface and Implementations Example (Author's Work)......................................75
Figure 48 AnalysisFactory Example (Author's Work).....................................................................................76
Figure 49 Assessing the effectiveness of employing SOLID principles..........................................................77
Figure 50 DataLoader class (Author's Work)..................................................................................................78
Figure 51 SeasonalSalesAnalysis (Author's Work).........................................................................................78
Figure 52 Readability and Maintainability (Author's Work)...........................................................................79
Figure 53 AnalysisFactory (Author's Work)....................................................................................................80
Figure 54 Unit Testing (Author's Work)..........................................................................................................81
Figure 55 Integration Testing (Author's Work)...............................................................................................82
Figure 56 Functional Testing (Author's Work)................................................................................................82
Figure 57 Regression Testing (Author's Work)...............................................................................................83
Figure 58 Performance Testing (Author's Work).............................................................................................83
Figure 59 Monthly sales Analysis 1 (Author's Work).....................................................................................90
Figure 60 Monthly sales Analysis 2 (Author's Work)....................................................................................91
Figure 61 Price Analysis by product (Author's Work).....................................................................................92
Figure 62 Weekly sales analysis (Author's Work)...........................................................................................93
Figure 63 Product performance Analysis 1 (Author's Work)..........................................................................94
Figure 64 Product performance Analysis 2 (Author's Work)..........................................................................94
Figure 65 Product performance Analysis 3 (Author's Work)..........................................................................95
Figure 66 Types of Automated Testing...........................................................................................................96

6
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Table Numbers
Table 1 SOLID Principles in OOP...................................................................................................................23
Table 2 Utilizing SOLID Principles (Author's Work).....................................................................................55
Table 3 Data Analysis and Processing (Author's Work)..................................................................................61
Table 4 Advantages of AWS Deployment (Author's Work)...........................................................................62
Table 5 Security Measures on AWS (Author's Work).....................................................................................62
Table 6 Scalability on AWS (Author's Work).................................................................................................62
Table 7 Test Cases (Author's Work)................................................................................................................86
Table 8 Test Plan for Sampath Food City (PVT) Ltd. Sales Data Analysis System (Author's Work)............90
Table 9 Developer Produced Automatic Testing Tool Advantages & Disadvantages (Author's Work).........98
Table 10 Vendor-Provided Automatic Testing Tools Advantages and Disadvantages (Author's Work)........99

7
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Acknowledgement

I am deeply grateful to those who have played a crucial role in completing my course on Applied
Programming and Design Principles. First and foremost, I sincerely thank Mr. Vishmal Gamage for his
dedicated guidance and insightful feedback, which have been invaluable throughout this learning journey.

I also extend my appreciation to my friends and peers for their collaborative spirit, engaging discussions,
and unwavering support. Your contributions have significantly enriched my understanding and made this
academic endeavour an enjoyable experience.

Lastly, I wish to thank the entire faculty and lecturers at ESOFT Metro Campus. Your commitment to
providing quality education, fostering a conducive learning environment, and nurturing our intellectual
growth is greatly appreciated.

8
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Introduction
In the rapidly evolving field of software development, the pursuit of creating applications that are efficient,
robust, maintainable, and scalable requires a profound understanding of advanced programming languages
and design principles. The introduction of Object-Oriented Programming (OOP) has transformed the
approach developers take to problem-solving, providing a framework for organizing complex systems into
manageable, interconnected objects. However, to fully harness the power of OOP, it is essential to follow
design principles that enhance software quality and flexibility.

Among these principles, the SOLID principles are particularly noteworthy, guiding the development of
software that is easy to understand, modify, and extend. These principles emphasize the importance of single
responsibility, open-closed design, Liskov substitution, interface segregation, and dependency inversion. By
adhering to these principles, developers can create systems that are robust, efficient, and adaptable to
changing requirements.

This assignment embarks on an exploration of Applied Programming and Design Principles, with a focus on
the SOLID principles and their impact on OOP. The goal is to equip students with the knowledge and skills
needed to design and implement software systems that meet industry standards for quality and
maintainability. Through a series of tasks, students will examine the characteristics of the OOP paradigm,
design and build a large dataset processing application using clean coding techniques and perform automatic
testing to ensure the reliability and efficiency of their software.

As we delve into these concepts, we will tackle the challenges of processing large datasets in real-world
scenarios, providing a practical context for applying the theoretical principles discussed. This assignment is
not just about learning to code; it is about embracing a philosophy of software development that values
clarity, flexibility, and sustainability. By the end of this journey, students will have gained a deeper
understanding of how to apply SOLID principles and clean coding techniques to develop software that
stands the test of time.

9
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
LO1 Investigate the impact of SOLID development principles on the OOP paradigm.

1.1 Object-Oriented Programming (OOP)


Object-Oriented Programming (OOP) is a paradigm in software development that organizes code into
objects, which are instances of classes that encapsulate both data and behaviours. This approach allows for
modular design, making it easier to manage and maintain complex systems by promoting code reusability
and scalability. OOP principles, such as inheritance, polymorphism, encapsulation, and abstraction, enable
developers to create flexible and adaptable software architectures. The adoption of OOP has significantly
transformed software engineering by providing a structured framework for addressing complex problems
and enhancing collaboration among developers. (Wikipedia's Object-Oriented Programming)

1.1.1 Main Principles of OOP


The main principles of Object-Oriented Programming (OOP) are encapsulation, inheritance, polymorphism,
and abstraction. Encapsulation involves bundling the data and methods that operate on the data within a
single unit or class, and restricting access to some of the object's components, which is a means of
preventing unintended interference and misuse of the data. Inheritance allows a class to inherit
characteristics (attributes and methods) from another class, promoting code reuse. Polymorphism enables
objects of different classes to be treated as objects of a common super class, particularly through method
overriding and overloading, enhancing flexibility and integration. Abstraction simplifies complex systems
by modeling classes based on essential qualities while hiding the unnecessary details (Wikipedia's Object-
Oriented Programming page).

Figure 1 Main Principles of OOP

10
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
11
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
1. Encapsulation

Encapsulation is one of the fundamental principles of Object-Oriented Programming (OOP). It involves


bundling the data (attributes) and methods (functions) that operate on the data into a single unit, known as a
class. This principle restricts direct access to some of an object's components, which can help prevent
unintended interference and misuse. By using access modifiers like private, protected, and public,
encapsulation allows a class to hide its internal state and require all interaction to be performed through an
object's methods, ensuring better control over the data and promoting modularity and maintainability.

Figure 2 Encapsulation

Private/Internal Interface
The private or internal interface of a class includes attributes and methods that are accessible only within the
class itself. These elements are essential for the internal operations and integrity of the object but are not
meant to be visible or accessible from outside the object. The private access modifier ensures that internal
data and implementation details are shielded from external access, protecting the object's state and behavior
from unintended modification or misuse.
Public/External Interface
In contrast, the public or external interface of a class consists of attributes and methods that are accessible
from outside the class. These elements are designed for use by other parts of the application and facilitate
the object's communication with the external world. By exposing a limited and controlled set of
functionalities, the public interface enables interaction with the object without revealing its internal
workings.

12
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Benefits of Encapsulation
 Improved Modularity: Encapsulation separates components into self-contained units, allowing for
independent development, testing, and maintenance.
 Increased Security: It protects an object's integrity by hiding its internal state and preventing
unintended or malicious modifications.
 Ease of Maintenance: Encapsulation simplifies updates and maintenance by minimizing the impact
of changes on other parts of the program.
 Enhanced Usability: It provides a clear interface, making the software easier to use without needing
to understand complex details.
 Data Hiding: Encapsulation secures data by controlling what is visible to the outside world,
ensuring controlled manipulation of objects.
 Implementation Flexibility: It allows for changes in the class's internal workings without affecting
its interface or dependent code.
 Reduced Complexity: Encapsulation reduces software complexity by encapsulating complex
functionalities within classes.
 Facilitates Testing: It enhances the ability to perform unit testing on each class independently,
improving reliability and robustness.

2. Abstraction
Abstraction is a core principle of Object-Oriented Programming (OOP) that focuses on simplifying complex
systems by modelling classes based on essential qualities while hiding unnecessary details. This principle
allows developers to manage complexity by concentrating on the high-level functionalities of an object
rather than its intricate internal workings. Abstraction involves defining abstract classes and interfaces that
represent the broad concepts and functionalities common to a group of objects. By using abstraction,
developers can create a more manageable code structure, facilitating easier maintenance and enhancing the
clarity of the software design.

Figure 3 Abstraction

13
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Abstraction
 Streamlines Complexity and Boosts Code Clarity: Abstraction simplifies understanding by hiding
complex implementation details, making the code more readable.
 Promotes Code Reusability and Structure: It organizes code better and allows for the reuse of
components, enhancing code efficiency.
 Enhances Data Security through Concealment: Abstraction secures sensitive information by
limiting exposure to users, protecting against unauthorized access.
 Increases Productivity by Abstracting Lower-level Details: It allows developers to focus on
higher-level functionality without delving into the minutiae of implementation.

Advantages of Abstraction
 Simplified, User-friendly Interfaces: Provides an uncomplicated interface for user interaction,
hiding underlying complexities.
 Concealment of Complex Code: Keeps the intricate details of implementation out of sight,
contributing to a cleaner design.
 Enhanced Security Measures: Protects data by restricting direct access and manipulation,
safeguarding against breaches.
 Simplified Maintenance: Facilitates easier updates and maintenance of software, as changes to the
code often don't affect the abstraction layer.

3. Inheritance
Inheritance is a fundamental principle of Object-Oriented Programming (OOP) that enables a new class,
called a subclass or derived class, to inherit attributes and methods from an existing class, known as the
superclass or base class. This mechanism promotes code reuse and establishes a hierarchical relationship
between classes, allowing developers to create more complex systems by building on existing functionality.
Through inheritance, subclasses can extend or override the behaviour of the superclass, enabling the creation
of specialized classes that share common features while also introducing unique characteristics. This
principle not only streamlines code maintenance and reduces redundancy but also enhances the scalability
and organization of the codebase.

14
Figure 4 Inheritance
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
4. Polymorphism
Polymorphism is a core principle of Object-Oriented Programming (OOP) that allows objects of different
classes to be treated as objects of a common superclass. This principle enables a single interface to represent
different underlying forms (data types). There are two main types of polymorphism: compile-time (or static)
polymorphism and runtime (or dynamic) polymorphism. Compile-time polymorphism is achieved through
method overloading, where multiple methods have the same name but different parameters within the same
class. Runtime polymorphism is achieved through method overriding, where a subclass provides a specific
implementation of a method already defined in its superclass. Polymorphism enhances flexibility and
integration in software design, allowing developers to write more generic and reusable code. It simplifies
code maintenance and allows for the extension and modification of existing code without altering the
external behaviour of the system.

Figure 5 Polymorphism

5. Modularity
Modularity involves breaking a software system into distinct, interchangeable components, with each
component encompassing all the necessary elements to perform a specific function. Object-oriented
programming (OOP) naturally supports this modularity by utilizing classes and objects, which simplifies the
processes of maintenance, debugging, and updating software.

6. Reusability
OOP promotes the reuse of software components by allowing classes and objects developed for one
application to be utilized in another. This reduces redundancy and minimizes the effort needed to create new
software solutions.

15
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
7. Dynamic Binding
Dynamic binding, also known as late binding, involves determining which method to call at runtime. This
feature of OOP enables more flexible and adaptable code execution, as the specific code to be executed is
decided during runtime based on the context. These attributes together enhance the robustness,
maintainability, and flexibility of software created with the OOP paradigm, making it a popular choice in
software development.

1.1.2 Benefits of OOP


Modularity: The source code for an object can be developed and maintained separately from other objects.

Reusability: Objects can be reused across different applications, allowing developers to leverage existing
components rather than creating new ones from scratch.

Pluggability and Debugging Ease: If an object encounters issues, it can be replaced with another object as
a module, simplifying debugging and maintenance.

Flexibility Through Polymorphism: OOP enables the definition of a single interface with multiple
implementations, offering greater flexibility.

Effective Problem Solving: By decomposing software into smaller, manageable pieces, developers can
focus on individual components without being overwhelmed by the entire system.

OOP principles are integral to software development and are widely used in languages like Java, C++, and
Python. These principles provide a structured approach to programming that improves code readability,
reusability, and maintainability. According to Doherty (2020), the benefits of OOP include:
1. Improved Software Maintainability: Encapsulation allows updates to be made to objects without
impacting other parts of the code, reducing the risk of disrupting existing functionalities.
2. Reusability: Inheritance allows engineers to create new classes based on existing ones, saving time
by reusing proven code rather than starting from scratch.
3. Scalability: The modular nature of OOP supports the addition and removal of objects, aiding in the
management of large-scale applications and enabling parallel development.
4. Improved Productivity: The emphasis on reusability and modeling enhances developer productivity
by reducing the time and effort required for new projects.
5. Enhanced Quality of Software: OOP encourages thorough planning and analysis, resulting in more
flexible, understandable, and maintainable code, leading to higher software quality.
6. Facilitates Good Design Practices: OOP principles help in creating software designs that align with
real-world processes, making it easier for developers to conceptualize and address problems
effectively.
7. Support for Parallel Development: OOP allows different classes and objects to be developed
simultaneously, improving team collaboration and reducing development time.
8. Dynamic Binding: OOP supports dynamic binding, where the code executed in response to a
function call is determined at runtime, promoting flexible and extensible systems.
9. Better Simulation of Real-World Entities: OOP aids in modeling complex systems and real-world
entities, enhancing the software’s effectiveness and user experience.

16
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Individual objects, which are specific instances of an abstract class, like `myCar` or `goldenRetriever`, are
created using class templates as blueprints. Each object holds unique values for the properties defined in the
class. For example, if a `Car` class is defined with properties such as color, brand, and model, you can create
an instance of this class, like `myCar`, to represent a particular car. The property values for `myCar` can be
set to describe this specific vehicle without impacting other instances or the class template itself. This
approach allows the `Car` class to be reused to represent multiple cars, each with its own unique attributes.
Individual objects, such as myCar or goldenRetriever, are instances created from class templates, each
holding unique values for the properties defined in the class. For example, a Car class might define attributes
such as color, brand, and model, and specific instances like myCar would have unique values for these
attributes.

Figure 6 OOP Class and Objects

17
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
1.1.3 Foundational building blocks of Object-Oriented Programming (OOP)
The fundamental elements of Object-Oriented Programming (OOP) are classes, objects, methods, and
attributes. Classes act as blueprints for creating objects, which are instances that encapsulate data and
functionality defined by the class. Methods are functions within a class that perform actions or operations on
the object's data, while attributes are data variables that hold specific details about the objects. These
components work together to model complex systems as collections of interacting objects, simplifying the
design, maintenance, and scaling of applications.

Figure 7 Foundational building blocks of Object-Oriented Programming (OOP)

1. Classes
A class serves as a template for creating objects, outlining a set of attributes (properties) and methods
(behaviors) shared by all objects of that class. It encapsulates both the data and the functions needed to
manipulate that data, providing an abstract framework that defines the structure and behavior of objects
created from it.

18
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
2. Objects
An object is a specific instance of a class, and memory is allocated only when objects of that class are
instantiated. Each object contains both data members (attributes defined by the class) and methods
(functions associated with the class) to handle and manipulate this data. Although objects are created from
the same class, they can have distinct values for their attributes, enabling them to display varying behaviors.

3. Methods
Methods are functions defined within a class that act on the data stored in an object. They perform
operations on the object's attributes, typically to execute the object's behaviors. Methods can be considered
as actions an object can undertake or operations that can be applied to it, and they may alter the object's state
or carry out computations based on its attributes.

4. Attributes
Attributes, also known as properties or fields, represent the data stored within an object or class. They define
the state or characteristics of a class or object and are specified in the class definition. Each object can have
distinct values for these attributes, differentiating it from other objects of the same class.

In addition to these fundamental elements, OOP incorporates several advanced concepts to enhance object
interactions and design patterns:
 Inheritance: Enables a new class to inherit properties and methods from an existing class,
supporting code reuse and hierarchical relationships.
 Polymorphism: Allows objects of different classes to be treated as objects of a common superclass,
providing flexibility through method overriding and overloading.
 Encapsulation: Involves hiding an object's internal state from the outside world and exposing it only
through defined interfaces, safeguarding data integrity and simplifying interaction.
 Abstraction: Focuses on simplifying complex systems by exposing only essential elements,
enabling developers to work with high-level constructs without needing to understand every detail.
These concepts and building blocks collectively form the foundation of OOP, offering a robust framework
for organizing and managing intricate software systems.

19
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
1.1.4 Class Relation
In Object-Oriented Programming (OOP), the interactions and relationships between classes are crucial for
creating robust and scalable applications. Accurately modelling these relationships helps represent real-
world scenarios effectively within software systems. Key relationships include:

Class
Relation

Composistio
Association Aggreation
n

Aggreation

Composition
Figure 8 Class Relation (Author's Work)

1. Association

20
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Figure 9 Association

Association signifies a relationship between two classes where one class interacts with or utilizes another. It
broadly refers to any connection between instances of two classes, including cases where one instance is part
of another. Associations can be either unidirectional, where one class is aware of the other, or bidirectional,
where both classes recognize each other. For instance, in a scenario involving passengers and airplanes, an
association might be represented where a `Passenger` class interacts with an `Airplane` class. This could be
unidirectional if the `Passenger` class is aware of the `Airplane` class but not vice versa, or bidirectional if
both the `Passenger` and `Airplane` classes are aware of each other.

21
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
2. Composition

Figure 10 Composition

Composition is a specific type of association that depicts a "whole part" relationship between a composite
(the whole) and its components (the parts), characterized by strong ownership. In composition, the existence
of the contained objects is directly tied to the lifespan of the container object; when the container is
destroyed, its components are also destroyed. This relationship is often referred to as a "has-a" relationship.
For example, a `Library` (the whole) includes `Books` (the parts); if the `Library` is removed, the `Books`
within it are also removed.

22
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
3. Aggregation

Figure 11 Aggregation

Aggregation is a type of association that represents a "whole part" relationship but with more flexible
ownership than composition. In aggregation, the lifespan of the parts is independent of the whole; the
components can exist separately from the container. This is also a "has-a" relationship, where components
can belong to multiple aggregates or exist independently. For example, a `Library` and `Books` illustrate
aggregation: a `Library` contains `Books`, but the `Books` can exist independently of the `Library` and can
be part of different libraries or collections.

23
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
4. Inheritance

Figure 12 Inheritance

Inheritance in Object-Oriented Programming (OOP) allows a new class to inherit attributes and methods
from an existing class, known as the superclass or parent class. This concept enables code reuse and
establishes a hierarchical structure among classes. For example, if there is an `Animal` class with general
attributes and methods, both `Dog` and `Lion` classes can be inherited from `Animal`. The `Dog` class
would gain all the properties and behaviors defined in `Animal`, while adding or modifying features specific
to dogs. Similarly, the `Lion` class would inherit from `Animal`, incorporating its attributes while including
lion-specific characteristics. This "is-a" relationship helps in creating a more organized and less redundant
codebase.

24
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
1.1.5 SOLID Principles in OOP
The SOLID principles are five key design guidelines intended to enhance the clarity, adaptability, and
maintainability of software designs. These principles are essential in object-oriented programming (OOP)
and are crucial for developing a well-structured design architecture.
Principle Acronym Description
Single Responsibility Principle SRP A class should have only one
reason to change, meaning it
should be responsible for only
one aspect of functionality.
Open/Closed Principle OCP Software components (such as
classes, modules, or functions)
should be designed to be
extendable without modifying
existing code.
Liskov Substitution Principle LSP Substituting objects of a
superclass with objects of a
subclass should not alter the
correctness of the program,
ensuring that subclasses can
replace their super classes
without issues.
Interface Segregation Principle ISP Clients should not be forced to
depend on methods they do not
use. Instead, create specific
interfaces for distinct needs.
Dependency Inversion Principle DIP High-level modules should rely
on abstractions rather than
concrete implementations, and
low-level modules should also
depend on abstractions. The
direction of dependency should
be reversed, with abstractions not
depending on details.
Table 1 SOLID Principles in OOP

Adhering to the SOLID principles results in software that is more comprehensible, easier to debug, and more
adaptable, which is essential for creating scalable and robust designs in object-oriented programming.

In the context of developing a sales data analysis system for Sampath Food City using Python, applying
Object-Oriented Programming (OOP) principles and class relationships helps create modular, maintainable,
and scalable software. This system is designed to analyse various aspects such as monthly sales, product
price analysis, weekly sales, product preferences, and the distribution of total sales amounts. The
implementation will include UML diagrams and code examples to illustrate OOP concepts, class
relationships (such as association and composition), and SOLID principles in action.

25
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Example: Sales Data Analysis System
Scenario: A command-line interface-based system for analyzing sales data from multiple branches of
Sampath Food City.

UML Class Diagram

Figure 13 UML Class Diagram (Author's Work)

26
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Figure 14 Sequential Graph (Author's Work)

In the SalesDataAnalysisSystem:
 SalesDataAnalysisSystem comprises multiple Branches (using composition), meaning that each
branch is an integral part of the system and cannot exist independently.
 Each Branch contains multiple SalesRecords (also using composition), indicating that sales records
are closely tied to and managed by each branch.
 SalesRecord and Branch both have an association with Product, meaning they reference and
interact with product information.
 Item extends Product through inheritance, adding specialized attributes to differentiate it from the
general product class.

27
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Encapsulation: Protecting the sales data within SalesRecord.

Figure 15 Encapsulation: Protecting the sales data within SalesRecord. (Author's Work)

Inheritance: Extending Product for different types of items (e.g., perishable goods).

Figure 16 Inheritance: Extending Product for different types of items (e.g., perishable goods). (Author's Work)

SOLID Principles:
Single Responsibility Principle (SRP): The Branch class is responsible solely for managing branch-specific
data and operations, such as maintaining and storing instances of SalesRecord.

Figure 17 SalesRecord (Author's Work)

Open/Closed Principle (OCP)


The system allows for the addition of new analytical features without altering the existing code. For
instance, a new method to analyze product preferences or price trends can be added to extend functionality
while keeping the base structure intact.

28
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Liskov Substitution Principle (LSP)
Perishable Product can be used wherever a Product is expected, ensuring that extending product types does
not disrupt the existing functionality.

Interface Segregation Principle (ISP)


As the system expands, interfaces (or abstract classes in Python) can be utilized to ensure that classes only
implement the functionalities they require. This would allow for the creation of specific interfaces for
different types of sales analyses.

Dependency Inversion Principle (DIP)


High-level modules, such as the analysis tools, should depend on abstractions rather than concrete classes
like SalesRecord or Product. This can be achieved by defining interfaces for data access and manipulation,
which are then implemented by these classes.
This approach, tailored to the sales data analysis system for Sampath Food City, demonstrates how OOP
principles, class relationships, and SOLID principles contribute to developing a modular, maintainable
system capable of evolving to meet future requirements. By abstracting complex details, encapsulating data,
and ensuring classes are open for extension but closed for modification, the system becomes more robust
and adaptable.

29
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
1.2 Clean Coding
Clean coding is the practice of writing code that is easy to read, understand, and maintain. It involves
following best practices and principles such as meaningful naming conventions, clear and concise
comments, modular design, and adherence to coding standards. Clean code minimizes complexity and
redundancy, making it easier for developers to debug, test, and extend the software. By prioritizing
readability and simplicity, clean coding enhances collaboration among team members and contributes to the
overall quality and longevity of the software project. (Clean Code: A Handbook of Agile Software
Craftsmanship)

Figure 18 Clean Code

Key Aspects of clean coding

1. Readability
 Code should be clear and easy to understand at a glance. This involves using descriptive variable and
function names, adhering to consistent naming conventions, and logically organizing the code.
2. Simplicity
 Strive for the simplest solution possible, avoiding unnecessary complexity. Simple code is easier to
understand, test, and maintain. This includes avoiding over-engineering and minimizing
dependencies.
3. Use of Comments
 While clear code should be largely self-explanatory, comments are crucial for explaining the "why"
behind certain decisions, especially when the reasoning isn't immediately obvious. Avoid excessive
or redundant comments.
4. Consistent Style
 Maintaining a consistent coding style throughout the project enhances readability and reduces
cognitive load for developers. This includes consistent formatting, punctuation, and other stylistic
elements.
5. Refactoring

30
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
 Regularly review and refactor code to improve its structure and reduce duplication. Refactoring
keeps the codebase manageable and maintainable over time.

6. Testing
 Writing tests for your code is essential. Automated tests ensure that your code works as intended and
make it safer to refactor and add new features in the future.
7. Documentation
 Good documentation complements clean code by providing a high-level overview of the system,
setup instructions, usage guidelines, and architectural details. Documentation is vital for new team
members and long-term maintenance.
8. Error Handling
 Proper error handling is critical for writing robust and easy-to-debug code. Clearly define how
different errors are managed and reported.

1.2.1 Clean Coding Techniques


Clean coding techniques involve a set of practices designed to produce code that is easy to read, maintain,
and extend. These techniques emphasize clarity and simplicity, ensuring that code is written with
meaningful variable names, logical organization, and a consistent style. Refactoring is regularly performed
to improve code structure and reduce redundancy. Proper use of comments explains the rationale behind
complex decisions, while excessive comments are avoided. Automated testing is integral, providing
confidence that code functions correctly and safely support future changes. Additionally, comprehensive
documentation provides necessary context and usage information, while robust error handling enhances
reliability and debugging ease. Collectively, these techniques foster a coding environment where high-
quality, maintainable software can be developed and sustained over time.

1. Meaningful Naming Conventions


 Use descriptive and unambiguous names for variables, functions, classes, and other identifiers.
 Avoid using abbreviations and single-letter names except for loop counters.
2. Clear and Concise Comments
 Write comments that explain the why, not the what, of your code.
 Keep comments relevant and up to date with code changes.
3. Modular Design
 Break down complex problems into smaller, manageable functions or classes.
 Each module should have a single responsibility.
4. Adherence to Coding Standards
 Follow the established coding standards and guidelines for your language and framework.
 Consistent coding style improves readability and maintenance.
5. DRY Principle (Don't Repeat Yourself)
 Avoid code duplication by abstracting common logic into functions or classes.
 Reuse code instead of copying and pasting.
6. SOLID Principles
 Follow the SOLID principles to write scalable and maintainable code:
o Single Responsibility Principle
o Open/Closed Principle
o Liskov Substitution Principle
o Interface Segregation Principle
31
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
o Dependency Inversion Principle
7. Error Handling
 Implement robust error handling and logging.
 Use exceptions and error codes appropriately to manage unexpected situations.
8. Code Formatting
 Use consistent indentation, spacing, and braces placement.
 Format code according to the project or language guidelines.
9. Readable Logic
 Write simple and clear logic that is easy to follow.
 Avoid overly complex or nested conditional statements.
10. Refactoring
 Regularly refactor code to improve its structure and readability.
 Remove unnecessary code and optimize performance where needed.
11. Automated Testing
 Write unit tests and integration tests to verify the functionality of your code.
 Ensure that tests cover edge cases and potential error conditions.
12. Documentation
 Document public APIs, libraries, and complex algorithms.
 Provide usage examples and explanations for your codebase.
13. Version Control
 Use version control systems like Git to manage code changes.
 Write clear and concise commit messages describing the purpose of changes. (Clean Code: A
Handbook of Agile Software Craftsmanship)

32
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
1.2.2 Data Structures and Operations
Data structures and operations are fundamental components in computer science and programming,
providing the means to store and manipulate data efficiently. Common data structures include arrays, linked
lists, stacks, queues, hash tables, trees, and graphs, each offering unique advantages for different types of
tasks. Operations on these data structures, such as insertion, deletion, traversal, and searching, are designed
to handle data efficiently and effectively. Understanding the strengths and limitations of various data
structures helps in selecting the most appropriate one for a given problem, thereby optimizing performance.
For example, hash tables allow for fast retrieval operations, while trees provide sorted data management.
Mastery of data structures and operations is crucial for developing optimized algorithms and high-
performance applications. (GeeksforGeeks)

Arrays: Arrays store elements of the same type, indexed by numerical positions. They are ideal for
accessing elements sequentially or randomly by their index.

Linked Lists: Composed of nodes containing data and a reference to the next node, linked lists are effective
for dynamic memory allocation and frequent insertions or deletions.
Stacks: Stacks follow the Last In, First Out (LIFO) principle, with operations limited to pushing (adding)
and popping (removing) elements. They are useful for backtracking algorithms, parsing, and maintaining
function calls.

Queues: Queues operate on a First In, First Out (FIFO) basis, where elements are added at the back and
removed from the front. They are used in scheduling, buffering, and breadth-first search algorithms.

Hash Tables: Hash tables map keys to values for fast data retrieval. They are useful for quick access to
elements by identifier, such as in caching implementations.

Trees: Trees are hierarchical structures with a single root node and child nodes. Binary trees and binary
search trees (BSTs) are common types, suitable for hierarchical data representation and efficient search,
insert, and delete operations.

Graphs: Graphs consist of nodes (vertices) connected by edges and can be directed or undirected. They are
essential for representing networks and are used in algorithms for searching, pathfinding, and network flow
analysis.

Heaps: Heaps are tree-based structures that satisfy the heap property. They are used in sorting algorithms
(heap sort) and implementing priority queues.

Operations
1. Insertion: Adding an element to a data structure.
2. Deletion: Removing an element from a data structure.
3. Traversal: Accessing each element in a data structure to perform operations.
4. Searching: Finding an element that matches a condition.
5. Sorting: Arranging elements in a specific order.
6. Merging: Combining two sequences into one, often in sorted order.
7. Partitioning: Dividing a data structure into parts, often used in quicksort.
8. Balancing: Adjusting a data structure (commonly trees) to maintain optimal structure and efficiency.

33
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Choosing the right data structure and operations is fundamental to algorithm design, directly impacting
performance and complexity. Understanding their properties and use cases helps developers implement
efficient and correct algorithms.
Clean Coding Techniques and Data Structures
Clean coding techniques play a crucial role in selecting and implementing data structures and operations,
ensuring algorithms are efficient, maintainable, and readable. Here’s how these principles apply:
1. Clarity Through Meaningful Names: Using descriptive names for data structures and operations
enhances clarity. For example, naming a list sortedCustomerIds instead of list1 clearly indicates its
content and state.
2. Simplicity with Appropriate Data Structures: The KISS (Keep It Simple, Stupid) principle
encourages using the simplest suitable data structure. For instance, an array for direct index access or
a hash table for fast lookups, inserts, and deletes.
3. DRY Principle in Algorithm Design: Abstracting repeated operations into reusable functions
adheres to the DRY (Don't Repeat Yourself) principle, reducing redundancy and potential errors.
This makes future modifications easier and centralizes changes.
4. Decomposition into Small, Focused Functions: Breaking down algorithms into smaller, focused
functions improves modularity and testability. Each function performs a specific operation,
enhancing understanding and maintenance.
5. Consistency in Data Structure Usage: Consistent use of data structures across an application aids
readability and maintainability. For example, consistently using List for sequences and .add() for
insertions.
6. Effective Error Handling: Robust error handling prevents unexpected crashes and ensures
algorithm reliability. Anticipating and managing potential errors like removing elements from an
empty list or accessing nonexistent keys is essential.
7. Automated Testing for Algorithms: Implementing automated tests ensures correctness and
resilience. Testing various scenarios, including edge cases, validates the algorithm’s behavior under
all conditions.
8. Refactoring for Optimization and Readability: Revisiting and refactoring code can reveal
opportunities for performance improvements and enhanced readability. For example, replacing
nested loops with more efficient data structures like Set for unique elements.

Developing a Sales Data Analysis System for Sampath Food City


Applying clean coding principles to develop a sales data analysis system impacts the use of data structures
and operations in tasks like monthly sales analysis, price analysis, weekly sales analysis, product preference
analysis, and distribution of total sales.

Clarity Through Meaningful Names: Naming a list monthlySalesData instead of a generic list1 clearly
indicates it stores sales data for the month.
Simplicity with Appropriate Data Structures: Using a Dictionary or HashMap for productPriceMapping
enables fast lookups essential for price trend analysis, simplifying implementation and improving
performance.

DRY Principle in Algorithm Design: Implementing a reusable filterRecords function for filtering sales
records by different criteria reduces code duplication.

Decomposition into Small, Focused Functions: Breaking down the system into functions like
calculateTotalSales, determineBestSellingProduct, and analyzePriceTrends enhances modularity and
maintainability.

34
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Consistency in Data Structure Usage: Consistently using List for sequences of sales records and
Dictionary for mapping products to prices aids readability and predictability.
Effective Error Handling: Robust error handling ensures reliability. For instance, checking for missing
sales data when analyzing weekly sales prevents errors.

Automated Testing for Algorithms: Automated tests for functionalities like monthly sales aggregation and
weekly trend analysis ensure expected performance under various scenarios.

Refactoring for Optimization and Readability: Revisiting and refactoring the code, such as replacing
nested loops with more efficient data structures, can optimize performance.
Incorporating clean coding techniques ensures the sales data analysis system is functional, reliable, and
maintainable. These practices provide a solid foundation for building robust, scalable software systems
adaptable to changing business needs.

35
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
1.3 Design patterns in software engineering
Design patterns in software engineering are reusable solutions to common problems encountered during
software development. These patterns provide a proven approach to designing and implementing software
systems by offering standardized templates for solving specific design issues. Common design patterns
include Singleton, Observer, Factory Method, and Strategy, each addressing various aspects of software
architecture and design. By applying design patterns, developers can improve code maintainability,
scalability, and robustness, ensuring that software is both flexible and efficient. ("Design Patterns: Elements
of Reusable Object-Oriented Software" by Gamma et al)

Accelerate Development: Design patterns offer established solutions to frequent problems, allowing
developers to build on proven methods rather than reinventing the wheel. This efficiency can notably
shorten the development process.

Avoid Common Pitfalls: By utilizing design patterns, developers can sidestep known issues and challenges
that might arise during early development phases. These patterns, honed over time, contribute to creating
more reliable and effective solutions.

Promote Reusability: Design patterns provide versatile solutions applicable to various projects and
situations, facilitating code reuse and fostering consistent development practices across different software
systems.

Improve Communication: Adopting design patterns introduces a shared vocabulary among developers,
enhancing the clarity of discussions and understanding of system design and architecture within and between
teams.

Support Ongoing Enhancement: Well-documented and widely recognized, design patterns benefit from
continuous refinement and evolution, making them more dependable compared to custom, one-off designs.
This ongoing improvement builds on collective knowledge, ensuring better quality over time.

36
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
1.3.1 Design Pattern Types
Design patterns are categorized into three main types: creational, structural, and behavioural. Creational
patterns focus on object creation mechanisms, aiming to make the process more flexible and efficient.
Examples include the Singleton and Factory Method patterns. Structural patterns deal with the
composition of classes and objects to form larger structures, enhancing the way components are assembled;
notable examples are the Adapter and Composite patterns. Behavioural patterns address interactions and
responsibilities among objects, aiming to improve communication and delegation; patterns like Observer
and Strategy fall into this category. Each type addresses different aspects of software design, providing
tailored solutions to common design challenges.

Creational Patterns
Creational patterns focus on abstracting the process of object creation, allowing for more flexibility and
control over how and when objects are instantiated. Instead of directly using constructors to create objects,
these patterns provide mechanisms to manage the instantiation process, which can be particularly useful for
adapting to changes and improving code modularity. Common creational patterns include:
 Singleton: Ensures that a class has only one instance and provides a global access point to this
instance.
 Factory Method: Defines an interface for creating objects but allows subclasses to modify the type
of objects that are created.
 Abstract Factory: Offers an interface for creating families of related or dependent objects without
specifying their concrete classes.
 Builder: Facilitates the construction of complex objects by separating the construction process from
the representation, allowing for step-by-step assembly.
 Prototype: Enables the creation of new objects by copying an existing object, known as the
prototype.
Analysis of Design Pattern Types in Sales Data Analysis System

Creational Design Patterns: In the context of a sales data analysis system for Sampath Food City,
creational patterns can greatly enhance flexibility and scalability. For instance, the Singleton pattern might
be used for a central configuration manager that ensures only one instance of configuration settings is used
throughout the system. The Factory Method pattern could be employed to generate different types of
reports (e.g., monthly sales, price analysis) without needing to hardcode the report types. Abstract Factory
might be used to create various types of data processing tools (e.g., data aggregators, analyzers) that are
related but have different implementations. The Builder pattern can be useful for constructing complex
report objects step-by-step, allowing customization in the process of report generation. Lastly, the Prototype
pattern could be applied to duplicate existing report templates for creating new reports with similar
structures but varying data.

Structural Design Patterns: Structural patterns focus on the composition of classes and objects to form
larger structures. For example, the Adapter pattern could be used to integrate data from different sources or
formats into the sales data system, ensuring compatibility and smooth data flow. The Composite pattern
might be applied to handle hierarchical data structures, such as organizing sales data by regions and
products, allowing operations to be performed uniformly across different levels of the hierarchy.

Behavioral Design Patterns: Behavioral patterns deal with the interactions and responsibilities among
objects. The Observer pattern could be implemented to update various parts of the system whenever sales
data changes, such as refreshing dashboards or triggering alerts. The Strategy pattern might be used to

37
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
select different data analysis algorithms (e.g., statistical methods, trend analysis) dynamically based on the
requirements of the sales analysis.

Each of these patterns contributes to a more flexible, maintainable, and scalable design for the sales data
analysis system, allowing for efficient management and adaptation of the system’s functionality.

1. Singleton Pattern

Use Case: Ensuring that there is only one instance of the database connection manager or configuration
manager across the entire system is crucial for effective access control, resource management, and
maintaining a consistent application state. This approach helps in managing resources efficiently and
avoiding conflicts or inconsistencies that might arise from having multiple instances handling these critical
tasks.

Figure 19 Singleton Pattern (Author's Work)

In this setup, `ConfigurationManager` guarantees that configuration settings are centrally controlled and
accessible across the entire application, preventing inconsistencies and the creation of multiple instances.

38
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
2. Factory Method Pattern
Use Case: Dynamically generating analysis objects tailored to the specific type of analysis required—such
as monthly sales, weekly trends, or product preferences—enables the system to accommodate new analysis
types without altering the existing code. This approach allows for easy expansion and modification of the
system to include additional analytical capabilities.

Figure 20Factory Method Pattern (Author's Work)

AnalysisFactory facilitates the dynamic creation of various analysis strategies based on user input or system
settings, enhancing both flexibility and scalability. This approach allows the system to adapt to different
analytical needs and easily incorporate new analysis types without requiring modifications to existing code.

39
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
3. Abstract Factory Pattern
Use Case: Handling diverse data sources with different formats (such as CSV, JSON, XML) can be
streamlined using an abstract factory. This factory would offer a standardized interface for generating parser
objects tailored to each data format, making it straightforward to extend the system to accommodate
additional data sources in the future.

Figure 21 Abstract Factory Pattern (Author's Work)

This pattern ensures the system remains adaptable to new data formats or sources by adding new factories,
without modifying the core data processing logic.

40
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
4. Builder Pattern

Use Case: For building intricate queries or data analysis pipelines that require multiple stages and
configurations, the Builder pattern facilitates step-by-step assembly. This approach ensures that the
construction process is transparent, and the resulting object is customized to meet specific requirements.

Figure 22 Builder Pattern (Author's Work)

The Builder pattern offers a flexible approach for constructing complex objects, allowing the system to
efficiently address a range of analysis needs.

41
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
5. Prototype Pattern

Use Case: Rapidly creating or scaling analysis configurations without incurring the cost of a lengthy
initialization process each time. The Prototype pattern enables cloning of existing configurations, which can
then be adjusted or customized as required.

Figure 23 Prototype Pattern (Author's Work)

This pattern proves invaluable when analysis configurations are frequently used with minor adjustments,
enhancing resource efficiency and reducing initialization time. These examples demonstrate that Creational
design patterns provide effective strategies for managing object creation in a flexible, efficient, and scalable
way. By abstracting the instantiation process, these patterns enable the sales data analysis system to adapt to
evolving requirements and diverse data sources with minimal changes, establishing a strong foundation for
future growth and maintenance.

Structural Patterns
Structural patterns focus on how classes and objects are arranged to create larger structures. They ensure that
modifications to one part of a system do not necessitate changes throughout the entire system. These
patterns also minimize the impact of changes, requiring only minimal adjustments in other parts. Key
structural patterns include:
 Adapter (or Wrapper): Enables objects with incompatible interfaces to work together.
 Composite: Builds tree structures to represent part-whole hierarchies, allowing both individual
objects and compositions to be treated uniformly.
 Proxy: Acts as a surrogate or placeholder for another object, managing access to it.
 Flyweight: Decreases the cost of creating and managing numerous similar objects.
 Bridge: Decouples an object's abstraction from its implementation, allowing both to evolve
independently.
 Decorator: Facilitates the dynamic addition of new behaviors to objects without altering their
original code.

42
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Structural Design Patterns in Sales Data Analysis System
Structural patterns enhance software design by providing straightforward methods to establish relationships
between entities. They contribute to the scalability and adaptability of a system in evolving environments.

1. Adapter (Wrapper) Pattern


Use Case: When integrating third-party libraries or APIs for advanced analytics or data visualization that
have incompatible interfaces with the existing system, the Adapter pattern can bridge the gap. By wrapping
these libraries in an adapter that matches the expected interface, seamless integration is achieved, allowing
the system to utilize external resources effectively.

Figure 24 Adapter (Wrapper) Pattern (Author's Work)

In this setup, the AnalyticsAdapter ensures compatibility between the ExternalAnalyticsLibrary and the
system. It allows the advanced analytics capabilities of the library to be utilized seamlessly without
modifying the existing codebase.

43
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
2. Composite Pattern
Use Case: Managing a hierarchical structure of product categories, where operations such as sales
aggregation can be performed on individual products or entire categories consistently. This approach
facilitates uniform handling of both individual items and groups of items, simplifying operations and
enhancing the ability to analyze data across different levels of the hierarchy.

Figure 25 Composite Pattern (Author's Work)

44
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
3. Proxy Pattern
Use Case: Managing access to resource-intensive sales data analyses or ensuring security by controlling
access to this data. The Proxy pattern can serve as an intermediary, offering controlled access to the actual
data or analysis object. It can enforce security measures, manage resource allocation, or perform lazy
initialization to optimize performance.

This pattern ensures that only authorized users gain access to sensitive or resource-intensive data, thereby
preserving system integrity and optimizing performance.

45
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
4. Flyweight Pattern
Use Case: Optimizing memory usage when representing many similar sales transaction records. The
Flyweight pattern can be utilized to share common state across multiple objects, rather than storing this state
individually in each object. This approach minimizes memory consumption and improves efficiency by
managing shared data centrally and reusing it among instances.

Figure 26 Flyweight Pattern (Author's Work)

By employing the TransactionFactory, the system efficiently manages memory usage by reusing
TransactionFlyweight instances with identical state. This approach reduces memory consumption and
enhances performance by consolidating shared data among multiple transaction records.

46
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
5. Decorator Pattern
Use Case: Adding new features like logging, caching, or error handling to the sales data processing pipeline
without altering the existing classes. The Decorator pattern enables the dynamic enhancement of an object's
functionality by wrapping it with additional behaviour, thus extending its capabilities without modifying the
core implementation.

Figure 27 Decorator Pattern (Author's Work)

The LoggingDecorator adds logging functionality to the SalesDataProcessor, demonstrating how the
Decorator pattern allows for the dynamic extension of capabilities without altering the existing codebase.

These examples highlight how Structural design patterns can greatly improve the design of a sales data
analysis system, making it more adaptable, maintainable, and efficient as it evolves to address new
requirements.

47
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Behavioral Patterns
Applying behavioral design patterns to a sales data analysis system can greatly enhance its functionality and
maintainability. Here’s how each pattern could be applied in your scenario:
1. Observer Pattern: In a sales data analysis system, you could use this pattern to update various parts
of the system when the sales data changes. For example, when new sales data is received, the system
could automatically notify and update dashboards, reports, and alert systems that are dependent on
the sales data.
2. Strategy Pattern: This pattern could be used to define different analysis algorithms, such as
calculating total sales, sales growth, or sales by region. By encapsulating these algorithms as separate
strategies, the system allows for dynamic switching between different analysis methods without
modifying the core logic.
3. Command Pattern: You could use this pattern to handle complex operations like generating reports,
executing data queries, or performing batch updates. Each of these operations could be encapsulated
as a command object, enabling features such as queuing, undoing, or retrying operations.
4. Iterator Pattern: For accessing large sets of sales data, this pattern provides a way to iterate through
data elements without exposing the underlying data structure. This is useful for processing records in
batches or generating reports based on the data.
5. State Pattern: This could be applied to manage different states of data processing or analysis. For
example, the system could switch between states such as “initializing,” “processing,” “completed,”
and “error,” altering its behavior based on the current state.
6. Mediator Pattern: In a system with multiple components, such as data processors, analyzers, and
reporting tools, the Mediator pattern can manage the interactions between these components. This
reduces dependencies and makes the system easier to maintain.
7. Memento Pattern: This pattern could be used to implement undo functionality for data analysis
tasks or to restore the system to a previous state in case of errors. It’s useful for preserving snapshots
of analysis configurations or states.
8. Chain of Responsibility Pattern: For handling various stages of data processing, such as validation,
transformation, and aggregation, this pattern allows each stage to process the data or pass it along to
the next stage in the chain. This modular approach facilitates easy addition or modification of
processing steps.
These patterns can help build a robust, adaptable, and maintainable sales data analysis system by improving
how objects interact and manage their responsibilities. Applying behavioral design patterns to a sales data
analysis system for Sampath Food City can greatly boost the system’s functionality, making it more
adaptable, efficient, and manageable. These patterns focus on optimizing the interactions and responsibilities
of objects within the system, leading to clearer, more scalable, and robust designs.

48
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Behavioral Design Patterns in Sales Data Analysis System

1. Observer Pattern

Use Case: In a sales data analysis system, it's crucial to keep various components like dashboards, reports,
and alerts synchronized with the latest sales data. The Observer pattern can be employed to manage this
requirement efficiently. When new sales data is introduced or existing data is modified, the Observer pattern
ensures that all dependent components (observers) are promptly notified and updated. This approach
guarantees that users always have access to the most current information, facilitating real-time insights and
timely decision-making.

Figure 28 Observer Pattern (Author's Work)

The Observer pattern ensures that updates to sales data are instantly communicated to all relevant
components, such as dashboards and reports, without creating tight dependencies between them. This
decoupled approach allows for real-time synchronization and seamless updates across the system.

49
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
2. Strategy Pattern
Use Case: Customizable data analysis methods. Users might need various analytical approaches, such as
trend analysis or comparative analysis. The Strategy pattern enables selecting and applying different
algorithms dynamically at runtime.

Figure 29 Strategy Pattern (Author's Work)

This flexibility enables the system to easily integrate new analysis methods as business requirements change
and evolve.

50
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
3. Command Pattern
Use Case: Operations that can be undone, like correcting data entries or reversing data transformations. The
Command pattern allows these actions to be encapsulated, facilitating the implementation of undo
capabilities and managing more intricate operations.

Figure 30 Command Pattern (Author's Work)

This pattern enhances system robustness by enabling potentially disruptive operations to be performed and,
if necessary, safely undone.

51
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
4. State Pattern
Use Case: Handling intricate data processing workflows that include various stages like data validation,
enrichment, analysis, and reporting. The State pattern enables an object to change its behavior based on its
current internal state.

Figure 31 State Pattern (Author's Work)

The workflow can be easily modified or expanded by adding new states, enhancing the system's
adaptability.

52
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
5. Mediator Pattern

Use Case: The Mediator pattern simplifies complex interactions between various system components, such
as user interfaces, data storage, and analysis modules. By centralizing communication and managing how
objects interact, it streamlines coordination and reduces dependencies, making the system easier to maintain
and extend.

Figure 32 Mediator Pattern (Author's Work)

The Mediator pattern streamlines interactions between various components of the system, fostering loose
coupling and improving maintainability. By leveraging Behavioral design patterns, the sales data analysis
system can handle complex data processes and workflows efficiently. This methodology ensures that the
codebase remains flexible, well-organized, and easy to extend or modify. Consequently, it supports the
development of a robust and user-friendly system that can seamlessly adapt to evolving requirements.

53
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
1.4 Evaluate the impact of SOLID development principles
The SOLID principles, introduced by Robert C. Martin, provide essential guidelines for enhancing the
maintainability, scalability, and manageability of object-oriented software development. These principles are
foundational for creating systems that are clear, testable, and adaptable. Here's an overview of how each
SOLID principle affects application development:

1. Single Responsibility Principle (SRP): Impact: SRP asserts that a class should have only one
reason to change, meaning it should have a single responsibility. This principle simplifies class
design, making it easier to understand, test, and maintain. By focusing each class on a specific task,
the software becomes more modular, promoting reuse and reducing the risk of bugs during
modifications.
2. Open/Closed Principle (OCP): Impact: OCP indicates that software entities should be open for
extension but closed for modification. This principle encourages using abstract classes or interfaces
to add new functionality without altering existing code. The result is a stable core system that can
evolve over time without compromising reliability or requiring extensive retesting of current
features.
3. Liskov Substitution Principle (LSP): Impact: LSP ensures that subclasses can replace their base
classes without affecting the correctness of the program. This adherence to LSP strengthens the
application's robustness by ensuring that subclasses extend base classes appropriately, leading to a
more flexible and interoperable design.
4. Interface Segregation Principle (ISP): Impact: ISP states that clients should not be forced to
depend on methods they do not use. By breaking down larger interfaces into smaller, specific ones,
ISP reduces inter-class dependencies, simplifying refactoring, modification, and understanding. This
principle promotes a decoupled architecture, where components can be developed and tested
independently.
5. Dependency Inversion Principle (DIP): Impact: DIP proposes that high-level modules should not
depend on low-level modules, but both should depend on abstractions. Moreover, abstractions should
not rely on details, but details should rely on abstractions. DIP decreases coupling between different
application parts, enhancing resilience to changes and improving testability. It helps create a system
that aligns with business requirements while avoiding specific implementation constraints.

Overall Impact on Object-Oriented Application Development:


 Maintainability: SOLID principles foster a design where responsibilities are clearly defined and
dependencies minimized, making the system easier to maintain.
 Scalability: Systems built with SOLID principles can scale more effectively due to their modular
nature, enabling isolated expansion of functionalities.
 Testability: A design adhering to SOLID principles is more testable, with smaller, well-defined
classes that have fewer dependencies, simplifying isolation during testing.
 Flexibility: The principles promote flexibility by allowing new features or changes to be integrated
with minimal disruption to the existing system.
 Understandability: Adhering to SOLID principles results in a more coherent and comprehensible
codebase, easing the onboarding process for new developers and reducing cognitive complexity.
Overall, the SOLID principles are crucial for developing object-oriented applications that are robust,
maintainable, and adaptable to change, leading to high-quality, long-lasting software solutions.

54
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
1.4.1 The impact of SOLID principles on object-oriented application developing a sales data analysis
system for Sampath Food City
The impact of SOLID principles on the development of a sales data analysis system for Sampath Food City
involves both significant advantages and practical challenges. Let's explore these effects with scenario
examples:
Single Responsibility Principle (SRP)
 Strengths: SRP promotes system clarity and modularity. In the context of the sales data system,
having distinct classes such as SalesDataFetcher for retrieving data, DataAnalyzer for analyzing it,
and ReportGenerator for creating reports ensures that each class has a clear and singular purpose.
This separation simplifies understanding, maintenance, and modifications, such as changing report
formats without affecting the data fetching logic.
 Challenges: Excessive application of SRP can lead to an overly fragmented system. For instance, if
every small task within the ReportGenerator is broken down into separate classes, it might result in a
system that is harder to navigate, with unnecessary complexity.
Open/Closed Principle (OCP)
 Strengths: OCP allows for extending functionality with minimal disruption to existing code. For
example, if the system needs to introduce a new analysis type like geographic sales trends, a new
class, GeographicSalesAnalyzer, can be added to extend a base SalesAnalyzer interface without
altering existing analysis components.
 Challenges: Designing systems to accommodate future changes can sometimes lead to over-
engineering. Anticipating every possible future requirement might introduce unnecessary abstraction
layers, increasing complexity and making the system harder to understand.
Liskov Substitution Principle (LSP)
 Strengths: LSP ensures that subclasses can be used interchangeably with their parent classes without
affecting system correctness. In the sales data system, this allows different data source subclasses
(e.g., CSVDataSource, JSONDataSource) to be used interchangeably, facilitating the addition of new
data formats.
 Challenges: Strict adherence to LSP might complicate subclass design. Ensuring that subclasses
fully adhere to LSP can introduce additional abstractions, which may add unnecessary complexity
where simpler solutions could be effective.
Interface Segregation Principle (ISP)
 Strengths: ISP reduces dependencies by creating specific interfaces for different needs. For instance,
having separate interfaces for viewing sales reports, updating inventory, and managing user accounts
avoids the drawbacks of a monolithic interface, enhancing modularity and reducing unnecessary
dependencies.
 Challenges: The proliferation of interfaces can increase system complexity. Managing many small
interfaces might obscure the overall system architecture, potentially complicating development and
maintenance.
Dependency Inversion Principle (DIP)
 Strengths: DIP improves flexibility by decoupling high-level modules from low-level modules
through abstraction layers. In the sales data system, separating the ReportGenerator from
DataStorage via an abstraction allows for changing storage strategies without modifying the report
generation logic.
 Challenges: Implementing DIP can introduce initial complexity and require sophisticated techniques
like dependency injection. This might be seen as overhead for simpler projects. Additionally, abstract
layers can sometimes obscure data flow, making it less transparent.
In summary, applying SOLID principles to the development of the sales data analysis system underscores
the need to balance theoretical benefits with practical considerations. While these principles provide a strong
foundation for creating maintainable and scalable applications, their implementation must be context
55
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
sensitive. Overemphasis on any single principle without considering project-specific needs can lead to
increased complexity and development time. The key is to apply SOLID principles thoughtfully, focusing on
the areas that provide the most significant benefits while maintaining system simplicity and developer
productivity.

LO2 Design a large dataset processing application using SOLID principles and clean coding
techniques.

2.1 Designing a large dataset processing application for Sampath Food City.
Designing a large-scale dataset processing application for Sampath Food City, which analyzes sales data
from multiple branches, requires a meticulous approach that incorporates SOLID principles, clean coding
techniques, and design patterns. The goal is to create a system that is flexible, maintainable, and scalable,
capable of performing various types of data analyses.
System Overview
The application is designed to process and analyze sales data from various branches of Sampath Food City.
It will provide insights such as monthly sales analysis, product price analysis, weekly sales trends, product
preferences, and the distribution of total sales amounts.

Utilizing SOLID Principles

Single Responsibility Principle (SRP)


 DataLoader: Loads data from various sources such as CSV files and databases.
 DataProcessor: Converts raw data into a structured format.
 Analyzer: Conducts specific analyses on the processed data.
 ReportGenerator: Creates reports based on the analysis results.
Open/Closed Principle (OCP)
 Abstract classes or interfaces for Analyzer and ReportGenerator allow the addition of new types of
analyses and reports without modifying existing code.
Liskov Substitution Principle (LSP)
 Subclasses of Analyzer (e.g., MonthlySalesAnalyzer, ProductPreferenceAnalyzer) can be used
interchangeably without affecting the overall functionality of the application.
Interface Segregation Principle (ISP)
 Separate interfaces for data loading, processing, analyzing, and reporting ensure that classes only
implement methods relevant to their specific functionalities.
Dependency Inversion Principle (DIP)
 High-level modules, such as the main application logic, depend on abstractions (e.g., interfaces for
data loading and analysis) rather than on concrete implementations.

Clean Coding Techniques


 Meaningful Names: Use descriptive names for classes, methods, and variables (e.g.,
SalesDataLoader, processSalesData).
 Keep It Simple (KISS): Implement the simplest solutions for data processing and analysis tasks.
 Don't Repeat Yourself (DRY): Common functionalities (e.g., filtering data by date or product ID)
are implemented in utility classes or methods.
 Small Functions: Break down tasks into small, manageable functions.

56
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
 Error Handling: Implement comprehensive error handling for data loading, processing, and
analyzing phases.
 Automated Testing: Write unit and integration tests for each component.

57
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Component Responsibility SOLID Application
DataLoader Loads sales data from various SRP: Focuses solely on data
sources such as CSV files, loading. OCP: Can be extended
databases, or APIs. to support new data sources
without modifying existing code.
DIP: Uses interfaces to represent
loaders for different data types,
ensuring dependency inversion.
DataProcessor Cleans and standardizes the SRP: Dedicated to data
loaded data, preparing it for processing. OCP: Allows the
analysis. addition of new processing steps
through a processing interface
without altering the core process.
LSP: Ensures that any subclass
can be used interchangeably,
promoting reuse and flexibility.
Analyzer Conducts analyses on processed SRP: Each analysis strategy is
data, such as calculating monthly focused on a specific task. OCP:
sales, analysing product Uses the Strategy pattern to
preferences, or identifying sales introduce new analysis strategies
trends. seamlessly. LSP & DIP: An
IAnalyzer interface ensures
analyzers are substitutable and
decoupled from concrete
implementations, adhering to
both Liskov Substitution and
Dependency Inversion principles.
ReportGenerator Creates and formats reports based SRP: Dedicated solely to report
on the analyses, which might be generation. OCP: Supports
displayed on a dashboard, adding new report formats as
emailed to managers, or stored as subclasses of a Report interface
documents. without modifying existing code.
ISP: Exposes only necessary
methods for report generation,
ensuring interface segregation.
Table 2 Utilizing SOLID Principles (Author's Work)

58
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Design Pattern: Strategy Pattern
The Strategy pattern is especially appropriate for the Analyzer component, as it enables different types of
analyses to be implemented as distinct strategies. This pattern allows for the selection of an analysis strategy
at runtime, thereby increasing flexibility.

Figure 33 Design Pattern: Strategy Pattern (Author's Work)

System Architecture
 DataLoader: Reads sales data from multiple sources.
 DataProcessor: Standardizes and cleans the data.
 SalesDataAnalyzer: Uses different AnalysisStrategy implementations for specific analyses.
 ReportGenerator: Generates reports based on the analysis results.
This design meets the requirements by applying SOLID principles, clean coding practices, and the Strategy
pattern, ensuring the system remains maintainable, scalable, and adaptable to future needs.

59
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
2.2 Designing a suitable testing regime for the sales data analysis system for Sampath Food City
Developing an effective testing regime for the sales data analysis system at Sampath Food City entails
creating a thorough approach that includes unit testing, integration testing, and system testing, with a
significant focus on automation. This regime should verify that each component of the system from data
loading to report generation works correctly both individually and in conjunction with other components.

1. Unit Testing

Objective: Ensure that each individual component performs as expected.


Tools: Use testing frameworks such as pytest for Python.
Components & Strategy:
 DataLoader: Validate functionality by testing various data sources (CSV, database, API). Simulate
real data by mocking external data sources.
 DataProcessor: Verify the accuracy of data cleansing and standardization processes using diverse
datasets, including edge cases like incorrect formats and missing values.
 Analyzer: Test each type of analysis (e.g., monthly sales, product preferences) with predefined
datasets to ensure correct results.
 ReportGenerator: Assess the generation of various report formats to confirm accurate data
representation. Utilize mock data to check layout and content correctness.

2. Integration Testing

Objective: Confirm that components work together correctly and interact properly with external systems.
Tools: Employ TestContainers for testing with real databases in Docker containers or use similar tools for
other dependencies.
Components & Strategy:
 DataLoader and DataProcessor: Test the end-to-end pipeline from data loading through processing
to ensure data integrity and proper transformation.
 DataProcessor to Analyzer: Verify that the data processed by the DataProcessor is accurately
analyzed by the Analyzer, with results aligning with expectations.
 Analyzer to ReportGenerator: Ensure that analysis results are correctly transferred to the
ReportGenerator, and that the final reports are generated as intended.

3. System Testing

Objective: Validate the system's overall functionality and performance in an environment that closely
resembles production.
Tools: Use Selenium for UI testing and JMeter (or similar tools) for performance testing.
Components & Strategy:
 End-to-End Workflow: Test the full process from data loading and processing to analysis and
report generation to ensure the system operates as expected.
 Performance Testing: Evaluate the system’s ability to efficiently handle large datasets and produce
reports within acceptable time limits.
 User Acceptance Testing (UAT): Involve end-users in testing to confirm the system meets business
requirements and user expectations.

60
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
4. Automated Testing

Objective: Maximize automation to facilitate rapid feedback during development and deployment
phases.
Implementation:
 Continuous Integration (CI): Incorporate automated tests into a CI pipeline using tools like
Jenkins, GitLab CI, or GitHub Actions. This setup ensures that tests are executed automatically with
each code committed.
 Test Coverage Tools: Utilize tools like coverage.py (for Python) to gauge test coverage and identify
untested code segments.
 Mocking and Stubbing: Employ mocking frameworks (e.g., Mockito for Java, unit test. mock for
Python) to simulate external dependencies during unit testing.

This comprehensive testing strategy ensures that the sales data analysis system is thoroughly validated
throughout all stages of development. By combining detailed component tests with broader system
evaluations, it helps in early detection and resolution of issues. Automation enhances testing efficiency
and effectiveness, enabling continuous development and deployment with confidence in the system’s
reliability and performance.

61
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
2.3 Testing regime is particularly suitable for Sampath Food City's sales data analysis system.
The proposed testing regime is well-suited for Sampath Food City's sales data analysis system due to its
thorough approach, which guarantees reliability, performance, and user satisfaction in a complex, data-
intensive environment. This suitability is due to:

1. Handling Complex Data


Data Diversity and Volume: Sampath Food City manages extensive sales data from multiple branches in
various formats and structures. The comprehensive unit and integration testing strategies ensure that the
system accurately loads, processes, and analyzes this varied data, addressing edge cases and maintaining
data integrity.
2. Critical Business Decision-Making
Precision and Dependability: Sales analyses are vital for inventory management, marketing strategies, and
overall business growth. System testing, particularly end-to-end workflows and performance evaluations,
ensures that the system provides accurate and timely reports, serving as a reliable foundation for decision-
making.

3. Scalability and Performance


Managing Growth: As Sampath Food City grows, the system must efficiently handle increasing data
volumes without compromising performance. Performance testing assesses the system’s scalability and
responsiveness under heavy loads, preparing it for future expansion.

4. Fast Development and Deployment


Continuous Integration and Deployment: In the competitive retail sector, swiftly implementing new
features or analyses is crucial. Automated testing within a CI/CD pipeline enables quick, secure updates,
minimizing downtime and ensuring that new functionalities are rigorously tested before release.

5. User Experience and Adoption


Meeting Staff Needs: The success of the system depends on its acceptance by Sampath Food City’s staff,
who need user-friendly tools to improve their workflows. User Acceptance Testing (UAT) engages end-
users in the testing process, ensuring the system meets their requirements and preferences, which boosts
adoption and satisfaction.

6. Regulatory Compliance and Data Security


Protecting Data: Given the sensitivity of sales data, it is crucial to ensure compliance with data protection
regulations. The thorough testing regime, particularly system testing, helps identify and address security
vulnerabilities, safeguarding both customer and business data.

7. Cost Efficiency
Avoiding Expensive Errors: Detecting and fixing issues during development is far more cost-effective than
addressing them after deployment. By emphasizing early and automated testing, the regime reduces the
likelihood of costly, reputation-damaging errors in the live environment.
This testing approach is specifically designed to meet the operational, strategic, and technical needs of
Sampath Food City’s sales data analysis system. It addresses the essential requirements for accuracy,
reliability, and scalability, ensuring that the system effectively supports the company's goals. By enabling
rapid development cycles, ensuring data integrity, and enhancing user satisfaction, this regime is key to
delivering a robust and efficient tool for business intelligence and decision-making.

62
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Technological Stack for Sampath Food City (PVT) Ltd

For Sampath Food City (PVT) Ltd.'s sales data analysis, a customized technological stack that leverages
Python's strengths—especially with libraries like Pandas and PrettyTable (Tabulate)—integrated into an
AWS cloud environment provides a comprehensive solution. This setup is designed to handle data analysis,
visualization, deployment, and maintenance effectively, ensuring scalability, security, and operational
efficiency.
Technological Stack for Sampath Food City (PVT) Ltd.'s Sales Data Analysis and Processing:

1. Data Analysis:
 Python Libraries:
o Pandas: Essential for data manipulation, cleaning, and analysis, Pandas supports complex
data operations and provide flexible data structures.
o PrettyTable (Tabulate): Enhances the presentation of data in tabular format, improving
readability for analysis results and reports.
2. Data Visualization:
 Matplotlib & Seaborn: For creating a wide range of visualizations to help interpret data trends and
patterns effectively.
3. Cloud Integration:
 AWS Cloud Services:
o Amazon S3: Used for scalable storage of data files, including sales data and analysis results.
o Amazon EC2: Provides computer capacity for running data processing tasks and analysis
workloads.
o Amazon RDS: Manages relational databases securely and efficiently, supporting data storage
and querying needs.
4. Deployment and Maintenance:
 AWS Lambda: Enables serverless computing for executing code in response to events, such as data
updates or processing tasks.
 AWS CloudWatch: Monitors and manages system performance, providing insights into resource
utilization and operational health.
5. Scalability and Security:
 Scalability: The stack is designed to handle growing volumes of data as the company expands,
ensuring smooth performance and efficiency.
 Security: AWS provides robust security features to protect data and ensure compliance with relevant
regulations.
6. Efficiency:
 Automated Workflows: Integration with CI/CD pipelines facilitate automated deployment and
updates, reducing manual intervention and downtime.
This technological stack ensures that Sampath Food City (PVT) Ltd.'s sales data analysis system is robust,
scalable, and secure, effectively supporting their data-driven decision-making processes and overall business
goals.

63
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Component Purpose Key Features
Pandas Data analysis and manipulation High-performance DataFrames,
integration from various sources,
data preprocessing and
transformation, efficient data
handling.
PrettyTable Tabular data presentation Lightweight and simplifies
tabular data handling, adjustable
table formatting, integrates with
Pandas DataFrames.
Table 3 Data Analysis and Processing (Author's Work)

Integration with Python:


 Ease of Integration: Python allows for the smooth incorporation of Pandas and PrettyTable,
enhancing the software system's capabilities.
 Roles:
o Pandas: Handles data loading, cleaning, transformation, and detailed analysis.
o PrettyTable: Improves the presentation of analysis results, providing clear and structured
output.
Benefits of Python, Pandas, and PrettyTable:
 Adaptability: This combination is highly versatile, efficiently addressing Sampath Food City (PVT)
Ltd.'s specific sales data analysis requirements.
 Efficiency and Insight: The use of Pandas for data manipulation and analysis, combined with
PrettyTable for organized presentation, offers stakeholders valuable and actionable insights.
Outcome for Sampath Food City (PVT) Ltd.:
 Data-Driven Decision-Making: Provides actionable insights that support informed decision-
making.
 Actionable Insights: Delivers clear and concise information to help decision-makers drive company
growth.
 User-Friendly Solution: Offers a powerful yet accessible tool for thorough sales data analysis.
Deployment and Maintenance in AWS Environment:
 Installation and Upkeep Plan: Deploying on AWS brings benefits like cost efficiency and
scalability. A strategic plan is essential for installation, security, and ongoing maintenance to
leverage these advantages effectively.

64
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Advantages of AWS Deployment
Advantage AWS Services Description
Cost-effectiveness Pay-as-you-go model Minimizes initial expenses by
charging based on usage.
Flexibility EC2, S3, VPC, RDS, Lambda Facilitates scalable resource
management and adaptability.
Reliability High availability, fault tolerance Guarantees consistent operational
performance and minimizes
downtime.
Table 4 Advantages of AWS Deployment (Author's Work)

Leveraging AWS Services: AWS offers a comprehensive range of services that support hosting,
management, and application scaling, including capabilities for computing, storage, networking, security,
and monitoring.

Security Measures on AWS


Security Measure Implementation
Network Security VPC, security groups, network ACLs
Data Encryption SSL/TLS, AWS KMS
Access Management IAM policies
Monitoring CloudWatch, CloudTrail
Table 5 Security Measures on AWS (Author's Work)

Scalability on AWS:
Scalability on AWS: AWS offers a range of scalability tools, including Auto Scaling, Elastic Load
Balancing, and managed database services such as Amazon RDS and DynamoDB. It also provides
serverless solutions like AWS Lambda, all designed to handle varying workloads and support future
expansion.
Scalability Tool Functionality
Auto Scaling Automatically adjusts compute resources based on
demand.
Elastic Load Balancing Balances incoming traffic to enhance performance
and reliability.
Managed Database Services Adjusts database resources dynamically using RDS
or DynamoDB.
Serverless Architecture Provides on-demand scaling of compute resources
with Lambda.
Table 6 Scalability on AWS (Author's Work)

The deployment and maintenance strategy on AWS, utilizing its scalable services and security features,
guarantees the system’s reliability, performance, and preparedness for future growth. This thorough
approach ensures that Sampath Food City (PVT) Ltd. is well-equipped for data-driven decision-making,
supported by a robust and adaptable technology stack.

65
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
2.4 Refining the design to include multiple design patterns.

Refining the design of the sales data analysis system for Sampath Food City by incorporating multiple
design patterns can greatly enhance its architecture, maintainability, and scalability. Integrating additional
patterns allows for better management of various concerns and ensures the system remains adaptable to
future changes.

1. Abstract Factory Pattern for Data Loading To handle a range of data sources (such as CSV, JSON,
databases, etc.) and accommodate future additions, we can employ the Abstract Factory pattern. This pattern
provides a way to create data loader objects for different types of data sources.
Implementation Benefit: It streamlines the addition of new data sources by establishing a common
interface for creating loaders, thereby increasing the system's flexibility and scalability.
Example: Suppose Sampath Food City needs to integrate data from various sources, like CSV files for daily
transactions and APIs for real-time sales data.
Abstract Factory Implementation: Define a DataSourceFactory interface with methods such as
createFileLoader () and createAPILoader (). Implement concrete factories like CSVDataSourceFactory and
APIDataSourceFactory that provide instances of CSVDataLoader and APILoader, respectively.

66
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Figure 34 Abstract Factory Pattern for Data Loading (Author's Work)

This approach allows for seamless integration of new data sources by simply adding new factories,
eliminating the need to modify existing data loading code.

2. Composite Pattern for Data Analysis


In scenarios where analyses are composite (such as combining monthly sales trends with product preference
insights), the Composite pattern allows for consistent handling of both simple and complex analyses.
Implementation Benefit: This pattern supports the creation of complex analyses from simpler components,
enhancing reusability and easing the management of various analysis types.
Example: Suppose you want to integrate monthly sales analysis with product preference insights to create
comprehensive reports.
Composite Implementation: Define an AnalysisComponent interface with an analyze () method.
Implement this interface with LeafAnalysis for straightforward analyses (like monthly sales) and
CompositeAnalysis for more complex analyses that aggregate multiple analyses, including product
preferences.

67
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Figure 35 Composite Pattern for Data Analysis (Author's Work)

This pattern enables the flexible and dynamic combination of different analyses.

68
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
3. Decorator Pattern for Report Generation
Enhancements or modifications to reports, such as incorporating headers, footers, or encryption, can be
dynamically applied using the Decorator pattern. This approach allows for the flexible addition of features to
reports without altering the core report generation logic.
Implementation Benefit: Enhances customization and feature extension of reports while adhering to the
open/closed principle.
For example, to add a watermark or encryption to reports without modifying the original report generator:
Decorator Implementation: The ReportDecorator class implements the same interface as ReportGenerator
and holds an instance of it. Concrete decorators, such as WatermarkDecorator and EncryptionDecorator, add
their respective functionalities.

Figure 36 Decorator Pattern for Report Generation (Author's Work)

69
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
4. Strategy Pattern for Data Processing
Data processing requirements can vary depending on the type of analysis being performed. By utilizing the
Strategy pattern in the data processing phase, we can dynamically choose between different processing
algorithms such as filtering or aggregating at runtime.
Implementation Benefit: This approach allows us to modify the data processing strategy according to the
analysis requirements without changing the client code responsible for processing.
Strategy Implementation: We define a DataProcessingStrategy interface with a process () method.
Concrete implementations of this interface provide specific data processing strategies. The DataProcessor
class then uses a strategy object to handle the data processing.

Figure 37 Strategy Pattern for Data Processing (Author's Work)

70
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
5. Observer Pattern for Real-Time Dashboard Updates

For dashboards that show real-time sales data analysis, applying the Observer pattern allows the dashboard
to automatically reflect updates in the analysis results without requiring manual refreshes.
Implementation Benefit: This pattern improves the user experience by delivering up-to-date analysis
results, which in turn enhances decision-making efficiency.
Observer Implementation: The Dashboard class implements an Observer interface to update itself
whenever there are changes in the SalesData (the subject). The SalesData class maintains a list of observers
and notifies them of any updates.

Figure 38 Observer Pattern for Real-Time Dashboard Updates (Author's Work)

71
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
6. Factory Method Pattern for Report Creation

Different report types (such as PDF, HTML, and Excel) require distinct generation logic. The Factory
Method pattern is useful for encapsulating the creation of report objects, facilitating the addition of new
report formats.
Implementation Benefit: This approach simplifies the integration of new report formats by adhering to the
open/closed principle and making the report generation process more manageable.
Integrating Multiple Design Patterns: The Factory Method pattern involves defining an interface for
creating objects while allowing subclasses to determine the specific class to instantiate. For report
generation, this means creating a base ReportGenerator interface with a method for generating reports and
then implementing this interface in subclasses that handle different report formats.

Figure 39 Factory Method Pattern for Report Creation (Author's Work)

By incorporating these design patterns, the sales data analysis system gains increased adaptability,
maintainability, and scalability. The Abstract Factory and Factory Method patterns enhance flexibility in
object creation, while the Composite pattern streamlines the management of complex analyses. The
Decorator and Strategy patterns offer runtime flexibility for customizing reports and processing data.
Meanwhile, the Observer pattern ensures that the system responds promptly to real-time data updates,
thereby enhancing the overall user experience.

72
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
The choice of each design pattern in the sales data analysis system for Sampath Food City addresses needs
and challenges related to creating a flexible, maintainable, and scalable system. Each pattern is included to
meet specific requirements and overcome unique obstacles in the system's development.

1. Abstract Factory Pattern for Data Loading

Sales data is obtained from various sources (CSV, databases, APIs) and comes in different formats. The
Abstract Factory pattern facilitates the creation of a set of related objects (loaders for each data source)
without needing to specify their exact classes. This design supports the system's extensibility, making it easy
to add new data sources as the business grows or alters its data storage methods.

Justification: Different branches of Sampath Food City may use various formats for sales data (such as
CSV, JSON, or databases). Using an Abstract Factory pattern enables smooth integration of these diverse
data sources.

Figure 40 Abstract Factory Pattern for Data Loading (Author's Work)

This pattern facilitates the addition of new data formats as the company expands, ensuring that the system
remains adaptable.

73
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
2. Composite Pattern for Data Analysis

When analysis requires integrating multiple smaller analyses into a larger, composite one (such as merging
sales trends with product performance metrics), the Composite pattern allows for treating both individual
analyses and their combinations uniformly. This approach simplifies the creation of complex analyses, and
its modular design ensures that new composite analyses can be incorporated with minimal adjustments to the
existing system.

Justification: To deliver a thorough analysis, it may be necessary to combine individual analyses (such as
daily sales and product preferences) into a unified, comprehensive view.

Figure 41 Composite Pattern for Data Analysis (Author's Work)

This approach allows for constructing complex analyses from simpler components, thereby improving both
flexibility and maintainability.

74
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
3. Decorator Pattern for Report Generation

Different reports might need extra formatting or features (such as encryption or compression) to meet
specific user requirements. The Decorator pattern enables these features to be added dynamically to reports
without changing the core report generation logic. This flexibility is essential for a system that must
accommodate various stakeholder needs while adhering to the open/closed principle.

Justification: Reports may need dynamic features like encryption for security. The Decorator pattern allows
these features to be introduced without modifying the original report generation logic.

Figure 42 Decorator Pattern for Report Generation (Author's Work)

75
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
4. Strategy Pattern for Data Processing.

Data processing may need to employ different strategies based on the type of analysis or user preferences
(such as filtering methods or aggregation techniques). The Strategy pattern allows the data processing
strategy to be chosen at runtime, providing the flexibility to adapt to various analysis needs without altering
the client code. This adaptability is crucial for a system that handles large and diverse datasets.

Justification: The method of data processing can vary depending on the analysis type (e.g., normalizing
data for trend analysis or aggregating data for monthly sales). The Strategy pattern accommodates these
variations efficiently.

Figure 43 Strategy Pattern for Data Processing. (Author's Work)

This design provides the flexibility to dynamically adjust data processing strategies based on the specific
needs of the analysis.

76
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
5. Observer Pattern for Real-Time Dashboard Updates

The system features dashboards that present real-time analysis results. The Observer pattern ensures these
dashboards are updated automatically whenever the underlying data changes, thereby enhancing the user
experience with timely insights. This pattern aligns with the system's objective of efficiently delivering
actionable intelligence to decision-makers.

Justification: Dashboards providing real-time insights need to refresh instantly as new data is received or
analyses are completed.

Figure 44 Observer Pattern for Real-Time Dashboard Updates (Author's Work)

This ensures that decision-makers receive the most up-to-date insights without manual intervention, thereby
enhancing operational efficiency.

77
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
6. Factory Method Pattern for Report Creation.
Reports must be generated in different formats (such as PDF, HTML, and Excel), each with its own
generation logic. The Factory Method pattern encapsulates the creation of report objects, making it easier to
add new report formats. This approach reduces the need for code modifications and adheres to the
open/closed principle, allowing the system to accommodate changing reporting requirements without
affecting existing functionalities.

Justification: Given the diverse report format preferences across departments, encapsulating report creation
simplifies the process of extending support for new formats.

Figure 45 Factory Method Pattern for Report Creation. (Author's Work)

Each design pattern addresses a particular challenge within the sales data analysis system, ranging from
managing diverse data sources and complex analysis needs to ensuring flexible report generation and real-
time updates. The implementation of these patterns in the Sampath Food City system demonstrates how
design patterns effectively resolve common software development issues while also accommodating the
specific requirements of a scalable, data-intensive application.

78
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
LO3 Build a data processing application based on a developed design.

3.1 Building a Large Dataset Processing Application for Sampath Food City (PVT) Ltd.
Sampath Food City (PVT) Ltd. aims to enhance decision-making through data-driven insights derived from
its sales data. The proposed application will process and analyze large datasets from multiple branches,
requiring a system that is efficient, scalable, maintainable, and adaptable. This demands a design that strictly
adheres to SOLID principles, utilizes clean coding practices, and leverages Python’s powerful data
structures and file handling capabilities.

Application Design and Structure: The architecture of the data analysis application for Sampath Food City
is modular, dividing responsibilities across data loading, analysis, and presentation layers. This modularity
ensures compliance with the Single Responsibility Principle (SRP), enhancing maintainability and enabling
easy future extensions.
DataLoader Class Example: The DataLoader class is solely responsible for ingesting sales data,
exemplifying the SRP. Its straightforward purpose is to load data from a CSV file into a Pandas DataFrame,
making it ready for analysis.

Figure 46 DataLoader Class Example (Author's Work)

79
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
SalesAnalysis Interface and Implementations Example:

By defining a SalesAnalysis abstract base class, we establish a blueprint for various analysis behaviors.
Implementations such as MonthlySalesAnalysis and PriceAnalysis provide specific analysis logic, adhering to the
Open/Closed Principle by enabling the system to introduce new analysis types without modifying existing ones.

Figure 47 SalesAnalysis Interface and Implementations Example (Author's Work)

80
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Implementation of Data Structures and File Handling:
Pandas play a crucial role in managing the large datasets at Sampath Food City. Its DataFrame structure is
key to efficiently performing data processing tasks, such as aggregating monthly sales data and filtering
records for price analysis. The choice of Pandas highlights the system's capability to effectively handle large
datasets.

Application of SOLID Principles:


The Dependency Inversion Principle is demonstrated through the AnalysisFactory, which abstracts the
creation of specific analysis instances. This decouples the analysis logic from the client code, enhancing the
system’s flexibility and testability.

AnalysisFactory Example:
The AnalysisFactory facilitates the dynamic creation of analysis objects, allowing for the easy addition of
new analysis types without modifying the client code.

Figure 48 AnalysisFactory Example (Author's Work)

81
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
3.2 Assessing the effectiveness of employing SOLID principles, clean coding techniques, and
programming patterns in the development of Sampath Food City (PVT) Ltd.
Evaluating the impact of implementing SOLID principles, clean coding practices, and design patterns in
developing Sampath Food City (PVT) Ltd.'s sales data analysis application reveals several significant effects
on the application's quality, maintainability, scalability, and the overall development process. Here’s a
detailed assessment:

Figure 49 Assessing the effectiveness of employing SOLID principles

1. Adherence to SOLID Principles

Single Responsibility Principle (SRP): By designing each class and module to have a single responsibility,
the codebase has been significantly simplified, making it easier to understand, debug, and test individual
components. For instance, separating data loading, data processing, and reporting into distinct classes
ensures that changes in one part of the system (e.g., changing the data source format) do not require
modifications in other areas, thus reducing the risk of introducing bugs during updates.

Example: The DataLoader class is solely responsible for loading data from various sources (e.g., CSV
files). This focused responsibility allows for easier adaptation, such as extending data loading capabilities to
new formats like JSON or Excel, without altering other parts of the system.

82
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Figure 50 DataLoader class (Author's Work)

Open/Closed Principle (OCP):


Applying the Open/Closed Principle enabled us to extend the system's functionality without altering existing
code. By using an abstract SalesAnalysis class, it became easy to introduce new types of sales analyses
(such as trend analysis or seasonal adjustment analysis) as business requirements evolved. This approach
enhances the application's longevity and adaptability to Sampath Food City's expanding needs.

Example: The abstract base class SalesAnalysis allows for the addition of new types of analyses (e.g.,
SeasonalSalesAnalysis) without requiring changes to the existing analysis framework.

Figure 51 SeasonalSalesAnalysis (Author's Work)

83
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Liskov Substitution Principle (LSP):
Ensuring that subclasses can be used interchangeably with their base class without compromising the
application's correctness resulted in a more reliable and robust design. This principle was crucial in
preserving the integrity of our data analysis pipeline, allowing for seamless substitution of different analysis
strategies.

Interface Segregation Principle (ISP):


By creating client-specific interfaces rather than general-purpose ones, we prevented clients from being
forced to depend on interfaces they did not use. This approach led to focused, lightweight interfaces for data
analysis, enhancing the system's modularity and simplifying the integration of new functionalities.

Dependency Inversion Principle (DIP):


Decoupling high-level modules from low-level modules, such as data source management and analysis
algorithms, through abstraction resulted in a more flexible and testable architecture. The AnalysisFactory
pattern exemplifies this principle by enabling dynamic selection of analysis methods without hard
dependencies.

2.Clean Coding Techniques:


Readability and Maintainability: Adopting clean coding practices—such as meaningful naming
conventions, consistent coding styles, and thorough documentation—enhanced the accessibility of the
codebase for new developers and simplified maintenance. This is essential for ongoing development and
enhancement of the application.
Modularity and Testing: A modular design made testing and debugging easier. Functions and classes that
followed clean coding principles were more cohesive and less coupled, facilitating unit tests and
contributing to higher code quality and reliability.
Example: Meaningful naming and modular functions within the analysis classes improved readability and
maintainability. Comprehensive comments and documentation clarified the purpose and usage of each
component.

Figure 52 Readability and Maintainability (Author's Work)

84
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
3.Employment of Programming Patterns
Factory Method Pattern: This pattern facilitated flexible object creation for various analysis types based
on runtime conditions. It enhanced extensibility and minimized the complexity of object creation in the
client code.
Example: The AnalysisFactory dynamically instantiates analysis classes according to user input, enabling
the addition of new analysis types without necessitating modifications to the client code.

Figure 53 AnalysisFactory (Author's Work)

Strategy Pattern: This pattern was crucial in defining a range of algorithms (analysis strategies),
encapsulating each one, and enabling their interchangeability. It allowed the application to adjust its analysis
behavior dynamically based on user needs or data context, without modifying how the client interacts with
the strategies.

The integration of SOLID principles, clean coding techniques, and programming patterns greatly enhanced
the development of a robust, scalable, and maintainable sales data analysis application for Sampath Food
City (PVT) Ltd. This structured approach streamlined development, ensured adaptability to evolving
business requirements, and promoted a culture of quality and excellence in software development practices
within Data Labs.

85
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
LO4 Perform automatic testing on a data processing application.

4.1 Examine the different methods of implementing automatic testing for the data processing
application developed for Sampath Food City (PVT) Ltd.
To evaluate different methods of implementing automatic testing for the sales data processing application
developed for Sampath Food City (PVT) Ltd., we will focus on several key approaches that align with the
designed test plan. Automatic testing ensures the application performs correctly across various scenarios and
upholds high-quality standards over time.

1.Unit Testing:

Unit testing involves testing individual components or units of the application in isolation. For the sales data
analysis application, this includes testing functions or methods like data loading, specific analysis
computations, or report generation.
 Tools: Python’s unit test framework or pytest.
 Example: Testing the load_data function from the DataLoader class to verify that it accurately reads
data from a CSV file and returns a DataFrame.

Figure 54 Unit Testing (Author's Work)

86
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
2. Integration Testing:
Integration testing focuses on evaluating the interactions between various components of the application to
ensure they function together correctly. This involves testing the end-to-end workflow, from data loading
through analysis to report generation.
 Tools: pytest, utilizing its fixtures feature to handle test dependencies and setup.
 Example: Testing the integration between the MonthlySalesAnalysis class and the DataLoader class
to confirm that monthly sales reports are correctly generated from the data loaded by DataLoader.

Figure 55 Integration Testing (Author's Work)

3.Functional Testing:
Functional testing assesses whether the application meets its functional requirements by evaluating its
behavior from an end-user perspective. This testing involves verifying that the application performs its
intended functions correctly, such as generating a sales analysis report from provided data.
 Tools: You can use pytest for functional testing or higher-level tools like Selenium for testing web-
based interfaces.
 Example: Executing a series of commands via the CLI interface to generate a sales analysis report
and verifying that the report’s output and format meet the expected criteria.

Figure 56 Functional Testing (Author's Work)

87
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
4. Regression Testing
Regression testing verifies that recent updates or modifications have not caused any unexpected issues or
disrupted existing features. This testing involves re-running previously established test cases to ensure that
the application's core functionalities remain intact after changes.
Tools: Automated test suites using frameworks like unit test or pytest, often integrated with CI/CD tools
such as Jenkins, GitHub Actions, or GitLab CI.
Example: After introducing a new analysis feature, you would re-run all existing test cases for various
analysis types to confirm that existing functionalities are still working correctly.

Figure 57 Regression Testing (Author's Work)

5. Performance Testing
Although often deferred to later stages of development, performance testing is essential for applications that
handle large datasets. It evaluates how well the application performs under different load conditions.
Tools: Custom scripts utilizing the time it module or advanced tools such as Locust.
Example: Assessing the time taken to process large datasets with various analysis types to ensure that
performance adheres to specified benchmarks.
Implementation in the Test Plan: Integrate performance testing by measuring execution times and
resource usage to ensure the application can handle large volumes of data efficiently and meets performance
criteria.

Figure 58 Performance Testing (Author's Work)

88
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Each automatic testing method corresponds to particular test cases outlined in the test plan. For example,
unit tests align with cases that target specific functionalities, such as data loading. In contrast, integration
tests address scenarios involving interactions between multiple components, such as the complete workflow
from data loading through to report generation.
Implementing these tests involves:
 Creating test cases that encompass all functionalities outlined in the test plan.
 Using the chosen tools to automate these tests.
 Integrating these tests into a CI/CD pipeline for ongoing testing and validation.
By meticulously applying and managing these automatic testing methods, you enhance the robustness and
efficiency of the Sampath Food City sales data analysis application, which directly supports its success and
durability.

4.2 Test Plan for Sampath Food City (PVT) Ltd. Sales Data Analysis System
Designing a test plan for the system involves specifying test cases to validate the functionality of each
system component. The plan should encompass various testing levels, such as unit testing, integration
testing, system testing, and acceptance testing.

Test Plan for Sampath Food City (PVT) Ltd. Sales Data Analysis System
 Test Plan ID: SFC-SDA-TP-001
 Introduction: This document outlines the testing strategy and framework for the Sales Data
Analysis System at Sampath Food City (PVT) Ltd. It details the resources needed, test scope,
methodology, and objectives.
 Test Scope: This plan includes testing of the entire application, covering the DataLoader module,
Analysis modules, Command-Line Interface (CLI), and the integration among these components.
 Test Objectives:
o Verify the functionality of each module individually.
o Ensure data integrity throughout the data processing pipeline.
o Confirm that the system meets all specified functional requirements.
 Resources:
o Test Environment: Python 3.x with required libraries installed.
o Test Data: Sample datasets in CSV format.
o Tools: pytest for automated testing, coverage.py for assessing test coverage.

89
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Test Cases:
ID Test Case Objective Expected Result
TC01 Load CSV data using Verify that the Data is successfully
DataLoader DataLoader loads CSV loaded into a
files without errors. DataFrame.
TC02 Handle non-existent Verify that DataLoader DataLoader raises a
CSV file in DataLoader handles file-not-found FileNotFoundError.
errors gracefully.
TC03 Process monthly sales Confirm that monthly Monthly sales figures
data sales data is calculated are accurate.
correctly for each
branch.
TC04 Generate weekly sales Ensure weekly sales Report shows accurate
analysis report analysis aggregates data sales data per week.
correctly.
TC05 Conduct price analysis Verify that the price Average prices
of products analysis reflects the calculated match
correct average prices. expected values.
TC06 Perform product Assess if the product Product rankings are
preference analysis preference analysis consistent with sales
ranks products correctly. data.
TC07 Test CLI for monthly Check the CLI's ability CLI generates the report
sales report generation to generate monthly without errors.
sales reports.
TC08 Integration test for data Validate the integration Data flows correctly and
flow and data flow between analysis is accurate.
modules.
TC09 Regression test after Ensure that new features All previous tests pass.
adding new analysis haven't disrupted
feature existing functionality.
TC10 Performance test for Measure the Processing completes
large dataset processing application's within an acceptable
performance with large time frame.
datasets.
Table 7 Test Cases (Author's Work)

90
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Test Execution
 Automated tests will be written using pytest and executed against the application.
 Test datasets of varying sizes and characteristics will simulate real-world usage scenarios.
 Performance tests will be conducted to measure response times and resource utilization.
Test Deliverables
 Test case documentation.
 Test scripts and associated code.
 Test reports, including coverage reports and analysis.
Acceptance Criteria
 All tests must pass.
 Code coverage should exceed 80%.
 Performance benchmarks must meet predefined thresholds.
Risk Analysis
 Insufficient test coverage could result in undetected bugs.
 Performance issues with large datasets may necessitate optimization.
This test plan serves as a roadmap for ensuring the quality and functionality of the Sampath Food City
(PVT) Ltd. sales data analysis system. It needs to be reviewed and approved by the project stakeholders
before execution.

91
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
4.3 Test Plan for Sampath Food City (PVT) Ltd. Sales Data Analysis System

Test Objective: To ensure the system delivers precise sales data analysis via a command-line interface,
facilitating effective decision-making.
ID Test Case Expected Actual Output Pass/
Output Fail
TC0 Load CSV Data from Pass
1 Data the CSV
file is
loaded
correctly
into the
system.
TC0 Monthly Monthly Pass
2 Sales sales
Analysis figures for
by Branch a specific
branch are
accurately
calculated.
TC0 Price The system Pass
3 Analysis calculates
by Product and reports
the average
price per
product.

92
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
TC0 Weekly A report Pass
4 Sales detailing
Analysis weekly
for the sales for
Network the entire
network is
generated.

TC0 Product Products Pass


5 Preference are ranked
Analysis based on
sales to
show
preference
s.

93
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
TC0 Sales Total sales Pass
6 Distributio are
n Analysis distributed
in the
report
based on
various
criteria.

Table 8 Test Plan for Sampath Food City (PVT) Ltd. Sales Data Analysis System (Author's Work)

94
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Coding’s for the Output

Monthly sales Analysis

Figure 59 Monthly sales Analysis 1 (Author's Work)

95
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Figure 60 Monthly sales Analysis 2 (Author's Work)

96
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Price Analysis by product

Figure 61 Price Analysis by product (Author's Work)

97
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Weekly sales analysis

Figure 62 Weekly sales analysis (Author's Work)

98
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Product performance Analysis

Figure 63 Product performance Analysis 1 (Author's Work)

Figure 64 Product performance Analysis 2 (Author's Work)

99
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Figure 65 Product performance Analysis 3 (Author's Work)

100
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
4.4 Discuss the Difference between developer produced and vendor – provided automatic testing tools.
Developer-produced and vendor-provided automatic testing tools are essential components of the software
development lifecycle, offering numerous features that enhance and simplify the testing process. Here’s an
overview of these tools and some examples:

Figure 66 Types of Automated Testing

Developer-Created Automated Testing Tools


These tools are typically developed by the open-source community or by developers specifically for use by
other developers. They are known for their flexibility, customizability, and seamless integration with other
open-source tools, often being free or low-cost.
Examples include:
 JUnit: A widely used framework for unit testing in Java.
 PyTest: An effective tool for creating both simple and complex functional tests for Python
applications.
 Selenium: A versatile framework for web application testing that includes a playback tool for
creating functional tests without needing a separate scripting language.
 Mocha: A comprehensive JavaScript test framework that operates on Node.js and in the browser,
facilitating straightforward and enjoyable asynchronous testing.
 RSpec: A Behavior-Driven Development (BDD) framework for Ruby.

101
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Developer-Produced Automatic Testing Tools Advantages and Disadvantage
Aspect Advantages Disadvantages
Cost-Effectiveness Typically, free and open-source.
Learning Curve Offers high levels of May have a steep learning curve
customization and flexibility. due to extensive customization
options.
Customization and Flexibility Highly adaptable to specific
needs.
Support Extensive resources and plugins Support is limited to community
available through the community. forums and documentation.
Community Support Strong support from a wide array
of resources.
Consistency Good integration with other Quality and experience can vary.
open-source tools.
Integration Seamless integration with other
open-source tools.
Innovation Rapid adoption of new
technologies.
Table 9 Developer Produced Automatic Testing Tool Advantages & Disadvantages (Author's Work)

Vendor-Provided Automated Testing Tools


These are commercial tools created by companies, typically offering dedicated support and a user-friendly
experience. Although they are generally less customizable than developer-created tools, they are designed to
integrate smoothly with other commercial software products. These tools often come with significant
licensing fees.
Examples include:
 HP QuickTest Professional (QTP), now known as Micro Focus UFT (Unified Functional
Testing): A popular tool for automating functional and regression tests for various software
applications and environments.
 IBM Rational Functional Tester (RFT): A tool for automating tests including functional,
regression, GUI, and data-driven tests.
 TestComplete: Developed by SmartBear Software, this tool offers comprehensive testing for
desktop, mobile, and web applications, and supports multiple scripting languages.
 Tosca Testsuite by Tricentis: Focuses on continuous testing and integrates with numerous CI/CD
tools. It is recognized for its model-based test automation and test data management capabilities.
 LoadRunner by Micro Focus: Primarily used for performance testing, it simulates numerous users
interacting with the application software to record and analyze the performance of key components.

102
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Vendor-Provided Automatic Testing Tools Advantages and Disadvantages
Aspect Advantages Disadvantages
Comprehensive Support Offers professional and dedicated
support.
Cost Part of larger tool suites with Licensing fees can be substantial.
integrated solutions.
User-Friendly Designed to be easy to use. Customization options may be
limited.
Reliability Subject to rigorous testing and Integration with external tools
quality control. may be lacking.
Out-of-the-Box Functionality Requires minimal setup and Updates may be less frequent,
configuration. leading to potential innovation
lag.
Table 10 Vendor-Provided Automatic Testing Tools Advantages and Disadvantages (Author's Work)

Choosing Between Developer-Produced and Vendor-Provided Tools


The decision between using developer-produced and vendor-provided testing tools often hinges on various
factors such as budget constraints, project needs, team size, and required functionalities. Developer-
produced tools are often favored for their flexibility, community support, and cost-effectiveness, making
them ideal for agile and dynamic development settings. In contrast, vendor-provided tools may be selected
for their robustness, dedicated support, and integration with broader tool suites, especially in larger projects
or organizations where these benefits outweigh the higher costs.

103
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Developer-Produced Automatic Testing Tools
Developer-produced testing tools are open-source or internally created tools designed to address the unique
needs of development teams. Examples include JUnit, PyTest, and Selenium (for web applications).
 Customization and Flexibility: These tools generally offer high levels of customization. Teams can
alter the source code to meet specific testing requirements or integrate with other tools within their
development environment.
 Cost: Many developer-produced tools are open-source and available at no cost, which can
significantly lower the expenses associated with software projects.
 Integration: Due to their open-source nature, these tools often have strong community support, with
a wide range of plugins and integrations to enhance their functionality.
 Support: While extensive community support is available, dedicated support may be limited unless
the team opts for paid versions or third-party services.
 Learning Curve: The learning curve can be steeper for new team members, especially when dealing
with complex customizations and extensions.

Overview of Vendor-Provided Testing Tools:


Vendor-provided tools are commercial products offered by companies specializing in software testing
solutions. Examples include HP's LoadRunner, QTP (QuickTest Professional), and Microsoft's Test
Manager.
 Customization and Flexibility: These tools are typically less flexible in terms of customization
compared to developer-produced tools. They are designed to function effectively out of the box for a
broad range of applications but may not be ideal for highly specific use cases.
 Cost: Vendor-provided tools often come with licensing fees, which can be a significant expense.
 Integration: Although vendor-provided tools may offer integrations with popular development
environments, customizing or extending these integrations can be more challenging compared to
open-source alternatives.
 Support: A significant advantage of vendor-provided tools is the dedicated support offered by the
vendor, which often includes training, customer service, and troubleshooting assistance.
 Learning Curve: Vendor-provided tools generally have a less steep learning curve, as they are
designed to be user-friendly and come with extensive documentation and support services.

Making the Choice:


 Project Size and Budget: Smaller projects or those with limited budgets may favor developer-
produced tools due to their cost-effectiveness and flexibility. Conversely, larger projects or
organizations might prefer the reliability and support of vendor-provided tools, which can justify the
higher investment.
 Specific Needs and Customization: Projects with highly specialized testing workflows might
benefit from the adaptability of developer-produced tools. On the other hand, projects with standard
testing requirements might find vendor-provided tools to be a quicker and more straightforward
solution.
 Team Expertise: The choice may also depend on the team's existing knowledge. Teams familiar
with specific open-source tools might prefer to stick with them, while teams experienced with
commercial tools might opt for those instead.
Selecting between developer-produced and vendor-provided automatic testing tools should be based
on a comprehensive evaluation of project needs, team expertise, budget limitations, and the required
level of support and customization.

104
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
4.5 Considering the testing needs for Sampath Food City's sales data analysis system
In the context of Sampath Food City’s sales data analysis system, selecting the right testing tools is essential
for ensuring the application’s reliability and performance. Here’s an overview of suitable developer-
produced and vendor-provided automatic testing tools for this scenario:

Developer-Produced Automatic Testing Tools:


Developer-produced tools are typically open-source and crafted by developers for various testing needs,
from unit testing to browser automation. They are known for their flexibility and strong community support.
 PyTest: A versatile testing framework for Python, PyTest is well-suited for writing both simple unit
tests and complex functional tests. Since the sales data analysis system is based on Python, PyTest
can effectively handle small-scale tests as well as integration testing by simulating various data
processing scenarios.
 Selenium: Ideal for web-based components of the system, such as dashboards used for visualizing
sales data, Selenium provides browser automation tools for testing web applications. If Sampath
Food City needs to test web interfaces, Selenium can simulate user interactions to assess UI/UX
aspects.
 Jest: If the system includes JavaScript for front-end components or services, Jest is a valuable tool
for testing JavaScript code, including Node.js backend services or React-based frontend interfaces.

Vendor-Provided Automatic Testing Tools


Vendor-provided tools are commercial products that come with licensing fees but provide robust
features, dedicated support, and comprehensive documentation, making them well-suited for
enterprise-level applications.
 Micro Focus UFT (Unified Functional Testing): Previously known as QTP (QuickTest
Professional), UFT offers automated testing capabilities for web, desktop, mobile, and robotic
process automation (RPA) applications. Its visual test creation environment and reusable test
components can be highly beneficial for managing complex test scenarios in Sampath Food City's
system.
 IBM Rational Functional Tester (RFT): This tool is designed for automated functional and
regression testing, supporting a wide variety of applications. RFT features scriptless testing options
and is useful for GUI testing and verifying system functionality across different platforms.
 Tricentis Tosca: An integrated testing suite that focuses on continuous testing with a scriptless
approach, making it accessible to non-technical testers. Tosca’s model-based test automation can
help ensure that the sales data analysis system meets all business requirements and effectively handle
data-driven testing.

105
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
For Sampath Food City's sales data analysis system, understanding the differences between
developer-produced and vendor-provided automatic testing tools is essential for selecting tools that
match the project's goals, budget, and technical needs. Here's a detailed comparison specifically
tailored for Sampath Food City:

Developer-Produced Automatic Testing Tools


 Customization and Flexibility: Benefit for Sampath Food City: Given the system's potential for
unique data analysis needs across various branches, the high level of customization offered by tools
like PyTest or Selenium is particularly valuable for adapting tests to specific scenarios.
 Cost-Effectiveness: Benefit: Open-source tools such as PyTest help reduce costs, which is
advantageous if the project has budget constraints.
 Community Support: Benefit: A strong community offers extensive resources, plugins, and
integrations that can accelerate the testing process. However, depending solely on community
support may present challenges in urgent or critical situations.
 Integration with Development Tools: Benefit: These tools typically integrate smoothly with CI/CD
pipelines and version control systems like Git, improving the overall development workflow.

106
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Vendor-Provided Automatic Testing Tools
 Comprehensive Support and Training: Advantage for Sampath Food City: Given the complexity
of the system and its widespread use across multiple branches, having access to dedicated support
and training can minimize downtime and ensure smooth operations.
 Integrated Solutions: Advantage: Tools like Micro Focus UFT and IBM RFT provide integrated
testing environments that address various testing needs (GUI, performance, functional) within a
single platform, simplifying the overall testing process.
 Reliability and Stability: Advantage: Vendor tools undergo rigorous testing and quality assurance,
offering a level of reliability crucial for business-critical applications.
 Ease of Use and Accessibility: Advantage: These tools are designed to be user-friendly, making
them more accessible for team members with varying levels of technical expertise.
 Cost: Disadvantage for Sampath Food City: The licensing fees for these tools can be quite high,
which may pose a significant challenge to the project's budget.
 Customization Limitations: Disadvantage: Vendor tools may have less flexibility in customization
compared to developer-produced tools, which could be a limitation when testing highly specific or
unconventional aspects of the sales data analysis system.

Conclusion for Sampath Food City


The decision between developer-produced and vendor-provided testing tools depends on several
critical factors:
 Budget and Resources: If budget constraints are a major concern, developer-produced tools may be
the better option, assuming the team can effectively manage and customize these tools.
 Technical Requirements and Complexity: For systems with complex and specific testing needs
requiring significant customization, developer-produced tools may offer the necessary flexibility.
Conversely, for broader testing coverage and ease of use, vendor-provided tools might be more
appropriate.
 Support and Reliability Needs: If the project requires dependable support and seamless integration
within a comprehensive testing framework, the cost of vendor-provided tools could be justified by
their robust support and reliability.
 Team Expertise: The team’s experience and comfort with the tools should also influence the
decision, as choosing familiar tools can help reduce the learning curve and boost productivity.
In practice, a hybrid approach might be the most effective solution for Sampath Food City,
combining the strengths of both developer-produced and vendor-provided tools to ensure
comprehensive, efficient, and cost-effective testing coverage.

107
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
4.6 Benefits and Drawbacks of different forms of automatic testing of Application and software
systems.
Analyzing the benefits and drawbacks of different forms of automatic testing offers valuable insights for the
development and maintenance of Sampath Food City's sales data analysis system.

Unit Testing
Benefits:
 Rapid Feedback: Unit testing provides immediate feedback by identifying issues at the code level.
For example, a unit test for the calculateMonthlySales function in Sampath Food City's system
ensures that sales are correctly aggregated per branch.
 Simplified Debugging: It helps to pinpoint the exact location of a problem, facilitating easier
debugging.
Drawbacks:
 Limited Scope: Unit tests focus on individual units in isolation and may miss issues that occur from
interactions between different components.
 Maintenance Overhead: As the codebase evolves, unit tests need to be updated, which can be time-
consuming.
Evaluation: Unit testing is crucial for validating the reliability of individual components, such as
calculations and data processing functions. However, to ensure comprehensive coverage, a robust suite of
unit tests is needed, which can be resource-intensive to develop and maintain.

Sampath Food City Example: A unit test for calculateMonthlySales verifies the accuracy of sales
aggregation. Yet, if this function depends on other components, like data preprocessing, unit tests alone
might not detect integration issues.

Integration Testing

Benefits:
 Ensures Component Compatibility: Integration testing confirms that different modules, such as
DataLoader and SalesAnalyzer, interact correctly and function together as intended.
 Detects Interface Defects: It identifies issues in the interactions between integrated components,
which is crucial for systems where the accuracy of data flow is essential.
Drawbacks:
 Complex Setup: Setting up integration tests requires a more intricate configuration to accurately
simulate real-world usage scenarios.
 Increased Execution Time: These tests can be slower than unit tests due to the complexity involved
in testing multiple components in tandem.
Evaluation: Integration testing helps bridge the gap between unit testing's focus on individual components
and the need to ensure that modules work together smoothly. The main challenge is to accurately simulate
real-world scenarios, which can be complex, especially when involving external systems or databases.

Sampath Food City Example: Testing the interaction between DataLoader and SalesAnalyzer modules is
essential. However, tests must be meticulously designed to handle various data formats and potential issues
in data loading, which could impact the accuracy of the analysis output.

108
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Functional Testing

Benefits:
 User Perspective Testing: Evaluates the application from the end-user’s viewpoint, such as
ensuring that the CLI correctly outputs the required sales reports.
 Comprehensive Coverage: Tests the application's external interfaces and user interactions,
verifying that all features perform as expected.
Drawbacks:
 Can Miss Internal Defects: May not detect underlying code issues that do not currently affect
functionality but could cause problems later.
 Resource-Intensive: Demands significant resources to create tests that cover all potential use cases
and scenarios.

Evaluation: Functional testing is crucial for confirming that the system meets all specified requirements
from the perspective of end-users. Although it provides thorough coverage, developing a comprehensive
suite of tests to address every functionality can be time-consuming and may not capture every nuance of
user interactions.

Sampath Food City Example: Ensuring that the CLI produces accurate sales reports based on provided
input parameters is critical. However, accounting for all possible user inputs and scenarios, such as invalid
dates or product codes, requires extensive test cases.

Performance Testing

Benefits:
 Assesses Scalability: Measures how the system performs under high loads, which is essential for
Sampath Food City during peak sales periods.
 Identifies Bottlenecks: Helps to pinpoint performance issues, such as slow database queries that
may affect the generation of monthly sales reports.
Drawbacks:
 Requires Specialized Tools and Skills: Performance testing often needs specialized knowledge and
tools to implement and interpret effectively.
 Time-Consuming: Setting up and executing performance tests, particularly those that simulate real-
world usage scenarios, can be time intensive.

Evaluation: Performance testing is crucial for systems that handle large amounts of data, ensuring they can
manage peak loads without significant performance degradation. The main challenges are the need for
specialized tools and the complexity of creating realistic load simulations.

Sampath Food City Example: Simulating the load of end-of-month data processing to identify potential
bottlenecks is vital. However, replicating the production environment and data volumes accurately for
testing can be difficult.

109
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Regression Testing

Benefits:
 Protects Against New Defects: Ensures that new changes do not interfere with existing
functionalities, which is essential for ongoing updates in Sampath Food City's system.
 Facilitates Continuous Integration: Can be automated in CI/CD pipelines to provide ongoing
validation.
Drawbacks:
 Test Suite Management: Managing and updating the regression test suite can become increasingly
complex as the codebase expands.
 Execution Time: Running a comprehensive regression suite can be time-consuming, particularly for
larger applications.
Evaluation: Regression testing is vital for confirming that new updates do not disrupt existing features, thus
preserving system integrity over time. The main challenges include maintaining an updated test suite and
balancing comprehensive coverage with the time required for execution.

Sampath Food City Example: Automating regression tests to run with each update ensures that new
features, such as additional metrics, do not affect existing functionalities like report generation. However, as
the system evolves, the test suite will grow, potentially increasing the time needed to validate updates.
Each type of automatic testing provides distinct benefits for ensuring the quality and reliability of Sampath
Food City's sales data analysis system, but also presents its own challenges. A balanced approach—
prioritizing unit and integration tests during the development phase for quick feedback and focusing on
performance and regression testing as the system matures—can help mitigate these challenges. This strategy
ensures comprehensive coverage, maintains system integrity, and optimizes resource allocation throughout
the software development lifecycle.

When evaluating the testing needs for Sampath Food City's sales data analysis system, it's important to
weigh the advantages and disadvantages of developer-produced versus vendor-provided automatic testing
tools:

Developer-Produced Automatic Testing Tools

Advantages:
 Cost-Effectiveness: Developer-produced tools are often open-source and free, making them a
budget-friendly choice for Sampath Food City. This helps in optimizing resource allocation without
incurring additional costs.
 Customization and Flexibility: Tools like PyTest and Selenium allow for significant customization,
which is beneficial for handling the specific datasets and analysis scenarios involved in sales data
analysis across various branches.
 Community Support: The open-source nature of these tools provides access to extensive
community knowledge, plugins, and extensions, which can enhance testing workflows and address
issues effectively.

Disadvantages:
 Learning Curve and Integration Effort: Adopting these tools may require considerable time and
effort to learn, integrate into the existing development pipeline, and ensure compatibility with other
tools used in the project.
 Inconsistent Support: Community support can be unpredictable and may not always provide timely
or adequate solutions, potentially causing delays in project timelines.

110
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Considering these factors will help Sampath Food City determine whether developer-produced tools align
with their specific needs and constraints or if a different approach is warranted.
Vendor-Provided Automatic Testing Tools

Advantages:
 Comprehensive Support and Reliability: These tools offer professional support, training, and
thorough documentation, which can be advantageous for teams new to automated testing or needing
quick deployment. Their reliability and stability help ensure consistent and accurate testing results.
 Integrated Solutions and Ease of Use: Tools like Micro Focus UFT and IBM Rational Functional
Tester are designed to be user-friendly and integrate seamlessly with various software systems. This
makes the testing process more straightforward and can shorten the time to market.
 Out-of-the-Box Functionality: With built-in templates and workflows, these tools can quickly adapt
to standard testing scenarios, reducing setup time and boosting immediate productivity.
Disadvantages:
 Cost: Licensing fees for vendor-provided tools can be substantial, which may be a significant
consideration for a large-scale project like Sampath Food City's that might need multiple licenses
across different branches.
 Limited Customization: These tools might not fully address specific needs related to sales data
analysis, such as testing custom algorithms or proprietary data formats, potentially limiting the depth
and scope of testing.

Conclusion for Sampath Food City


The choice between developer-produced and vendor-provided tools should be based on several key
considerations, including budget constraints, the complexity of testing needs, and team expertise. Evaluating
these factors will help determine the best approach to meet Sampath Food City's testing requirements
effectively.

Budget and Cost: When budget constraints are tight, developer-produced tools may be more suitable due to
their lower cost.

Complexity and Specificity of Testing Needs: The unique requirements of Sampath Food City's sales data
analysis system might benefit from the flexibility and customization capabilities of developer-produced
tools.

Team Expertise and Support Needs: If the development team has limited experience with automated
testing, the extensive support and user-friendliness of vendor-provided tools could be essential.

Conclusion: Sampath Food City could benefit from a hybrid approach, using open-source tools for tailored
testing scenarios while employing vendor-provided tools for their robustness and support in more standard
testing processes. This approach would help balance cost, flexibility, and reliability.

111
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Conclusion
This assignment explored the complexities of designing, implementing, and testing a sales data analysis
system for Sampath Food City (PVT) Ltd. We examined the theoretical and practical aspects of SOLID
principles, clean coding practices, and various design patterns to create a robust and maintainable software
system.

In developing the DataLoader class and evaluating different automatic testing strategies, we addressed the
specific needs of Sampath Food City, focusing on efficient and accurate data processing and analysis.
We analyzed the trade-offs between developer-produced and vendor-provided testing tools, assessing how
each option aligns with project factors such as budget, team expertise, and technical requirements. Through
specific examples, we demonstrated the application of unit, integration, functional, performance, and
regression testing, highlighting the advantages and challenges of each method. This analysis emphasized the
need for a balanced and comprehensive testing strategy that utilizes various methodologies to ensure system
reliability, performance, and user satisfaction.

The evaluation of automatic testing methods, coupled with real-world examples from the Sampath Food
City system, offered insights into optimizing testing processes to minimize risks, enhance system quality,
and meet operational needs.

This assignment illustrated the intricacies of developing and testing modern software applications,
underscoring the importance of applying solid software engineering principles. It highlighted the iterative
process of learning and applying different development and testing approaches in a practical context,
providing valuable lessons in software development, project management, and quality assurance.

112
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
Appendix

113
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
114
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
References

Object-Oriented Programming (OOP) - (https://en.wikipedia.org/wiki/Object-


oriented_programming)

Main Principles of OOP - (https://en.wikipedia.org/wiki/Object-oriented_programming)

Clean Coding Techniques - (https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/


dp/0132350882)

Data Structures and Operations - https://www.geeksforgeeks.org/data-structures/

Design patterns in software engineering - (https://refactoring.guru/design-patterns)

Image Links
Figure 67 Main Principles of OOP - Principles of OOP. OOP stands for Object Oriented… | by Venushi Kavitha De
silva | Medium

Figure 68 Encapsulation - Encapsulation in Object Oriented Programming (OOPS) (enjoyalgorithms.com)

Figure 69 Abstraction - Abstraction in Java - GeeksforGeeks

Figure 70 Inheritance - Inheritance in OOP. The capability of a class to derive… | by Omer Shafique | Medium

Figure 71 Polymorphism - Perl | Polymorphism in OOPs - GeeksforGeeks

Figure 72 OOP Class and Objects - What Is Object-Oriented Programming? Understanding The Basics | by Unstop |
Medium

Figure 73 Foundational building blocks of Object-Oriented Programming (OOP) - Building Blocks of OOP.
Introduction: | by HEET PAREKH | Medium

Figure 74 Clean Code - Why is Clean Code Important?. “You are reading this book for two… | by Miktad Öztürk |
Software and Technology | Medium

Figure 75 Assessing the effectiveness of employing SOLID principles - Establishing a SOLID Foundation | PPT
(slideshare.net)

Figure 76 Types of Automated Testing - What is Test Automation? Types, Best Practice, Challenges, Benefits
(accelq.com)

115
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles
116
Imasha Emmanuel (00180239) UNIT_20 - Applied Programming and Design Principles

You might also like