applied-programming-and-design-principles (1)
applied-programming-and-design-principles (1)
Higher
Nationals
Internal verification of assessment decisions – BTEC (RQF)
INTERNAL VERIFICATION – ASSESSMENT DECISIONS
Assignment title Sales Analysis System for Sampath Food City (PVT) Ltd
• Constructive?
Y/N
• Linked to relevant assessment
Y/N
criteria?
• Identifying opportunities
for improved performance? Y/N
Y/N
• Agreeing actions?
Does the assessment decision need
Y/N
amending?
Assessor signature Date
Confirm actioncompleted
Remedial action taken
Give details:
Internal Verifier
Date
signature
Programme Leader
Date
signature (if required)
LO1. Investigate the impact of SOLID development principles on the OOP paradigm
Resubmission Feedback:
Assignment Feedback
Formative Feedback: Assessor to Student
Action Plan
Summative feedback
Pearson
Higher Nationals in
Computing
Unit 20: Applied Programming and Design Principles
Assignment 01
General Guidelines
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.
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 page. 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.
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.
Assignment Brief
Student Name /ID Number MH Mohamed Ifham / E193622
Unit Number and Title Unit 20: Applied Programming and Design Principles
Assignment Title Sales Analysis System for Sampath Food City (PVT) Ltd
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)
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.
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 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
the developed application.
Grading Rubric
Grading Criteria Achieved Feedback
OBSERVATION RECORD
Learner name:
Qualification:
Unit number &
title:
Description of activity undertaken
Assessment criteria
Learner name:
Learner
Date:
signature:
Assessor
name:
Assessor
Date:
signature:
WITNESS STATEMENT
Learner
name:
Qualification:
Unit number
& title:
Description of activity undertaken (please be as specific as
possible)
Witness Job
name: role:
Witness Date
signature: :
Learner
name:
Learner Date
signature: :
Assessor
name:
Assessor Date
signature: :
Acknowledgement
I am deeply grateful to Ms. Mayurie for her guidance and support throughout this assessment.
Her insightful lectures and constructive feedback have been invaluable in helping me
understand key concepts such as object-oriented programming, SOLID principles, clean
coding, design patterns, and automated testing. Her patience and encouragement have been
instrumental in navigating the challenges of this project.
I would also like to extend my appreciation to my classmates for their collaboration and
support. Their diverse perspectives and thought-provoking discussions have greatly enriched
my learning experience and deepened my understanding of these complex topics.
Lastly, I am thankful for the opportunity to work on a project that simulates real-world
scenarios. This experience has allowed me to apply theoretical knowledge to practical
situations, enhancing my skills and understanding.
Table of Contents
OBSERVATION RECORD ............................................................................................... 1
LO1 Investigate the impact of SOLID development principles on the OOP paradigm. ......... 11
3.1.3.1 File handling techniques usage in Sampath Food City System .......................... 100
Activity 04: Perform automatic testing on a data processing application. ............................ 102
4.2 Comparison of Develop – produced and vendor -provided testing tool................... 106
Table Of Figures
Figure 1 Sampath Food city ..................................................................................................... 11
Figure 2 OOP ........................................................................................................................... 12
Figure 3 Types of OOP ............................................................................................................ 13
Figure 4 (Car Class) ................................................................................................................. 14
Figure 5 Inheritance ................................................................................................................ 19
Figure 6 Dependency ............................................................................................................... 21
Figure 7 Aggregation ............................................................................................................... 22
Figure 8 Composition .............................................................................................................. 23
Figure 9 (Abstraction Class Diagram) ..................................................................................... 24
Figure 10 (Abstraction Class Diagram Code).......................................................................... 25
Figure 11 (interface) ................................................................................................................ 26
Figure 12 (Interface Diagram Code ) ....................................................................................... 26
Figure 13 (Circle)..................................................................................................................... 27
Figure 14 Encapsulation .......................................................................................................... 28
Figure 15 (Encapsulation Code) .............................................................................................. 28
Figure 16 SOLID principles..................................................................................................... 29
Figure 17 Clean Code .............................................................................................................. 33
Figure 18 benefits of clean code .............................................................................................. 35
Figure 19 Design Pattern ......................................................................................................... 49
Figure 20 Types of Design Pattern .......................................................................................... 50
Figure 21 Data Structures ........................................................................................................ 52
Figure 22 Arrays ...................................................................................................................... 53
Figure 23 Linked List............................................................................................................... 54
Figure 24 Stacks....................................................................................................................... 54
Figure 25 Queues ..................................................................................................................... 55
Figure 26 Trees ........................................................................................................................ 56
Figure 27 Graphs...................................................................................................................... 57
Figure 28 (Monthly Sales Analysis) ........................................................................................ 58
Figure 29 Price analysis of each product ................................................................................. 60
Figure 30 (Weekly Sales Analysis).......................................................................................... 61
Figure 31 (Product preference analysis) .................................................................................. 64
Figure 32 Descriptive variable names...................................................................................... 66
Table Of Charts
1.0 Introduction
In today's fast-paced retail environment, data-driven decision-making has become crucial for
businesses to stay competitive. Sampath Food City (PVT) Ltd, a leading supermarket chain in
Sri Lanka, currently relies on a paper-based system for analysing monthly sales data, which is
prone to errors, time-consuming, and inefficient. To address these challenges, Data Labs (PVT)
Ltd, a premier software development company, has been tasked with developing a customized
software solution that automates and enhances the sales data analysis process. This assessment
focuses on creating a command-line interface-based sales data analysis system using Python,
aimed at improving the accuracy and efficiency of sales analysis across Sampath Food City's
branches. The new system will provide features such as monthly and weekly sales analysis,
price analysis, product preference analysis, and distribution analysis of total sales. By
leveraging object-oriented design principles, SOLID principles, clean coding techniques, and
appropriate design patterns, this project aims to deliver a robust, maintainable, and scalable
solution that will empower the management of Sampath Food City to make informed decisions
based on accurate and timely data insights.
Figure 2 OOP
In this example, the Car class is a blueprint that defines the properties of a car.
We create two objects, Toyota car and Chevrolet car which are instances of the Car class.
Both car objects can invoke start engine() method using their own values for
the make, model and year properties.
2. Encapsulation
Encapsulation is the concept of hiding the implementation details of an object from the outside
world and only exposing the necessary information through public methods. Encapsulation
helps protect the object's internal state from external interference and misuse. In Python, you
can achieve encapsulation using private attributes and methods, denoted by a double
underscore prefix (__).
In this example, the account number and balance attributes are private, meaning it can't be
accessed directly from outside the class. We interact with it through the deposit, withdraw,
and get balance methods.
3. Inheritance
Inheritance is a mechanism that allows a class to inherit properties and methods from another
class, called the superclass or parent class. The class that inherits is called the subclass or child
class. The child class inherits all the fields and methods of the parent class and can also add
new fields and methods or override the ones inherited from the parent class. Inheritance
promotes code reuse and helps create a hierarchical structure.
Let’s say we have a parent Vehicle class with a method named honk ().
The Car class inherits the color attribute and the honk method from the Vehicle class
promoting code reuse. The Car class also adds its own attributes and methods, such
as speed and accelerate.
4. Polymorphism
Polymorphism is the ability of an object to take on multiple forms. It enables you to write
generic code that can work with objects of multiple types, as long as they share a common
interface. A common way to achieve polymorphism is method overriding. Method overriding
is when a subclass provides a specific implementation of a method that is already defined in its
parent class.
For example, let’s say we have an interface Document which defines a method show().
Each subclass (Pdf, Word) of Document implements the show method differently (method
overriding), but the interface remains consistent giving the ability to iterate over both the
classes using a single for loop.
5. Abstraction
Abstraction is the concept of showing only the necessary information to the outside world while
hiding unnecessary details. Abstraction helps to simplify complex systems and focus on the
essential features. In Python, you can achieve abstraction using abstract base classes
(ABC) and abstract methods. Let’s say we have an abstract base class called Shape.
The Shape class is marked as an abstract class by inheriting from the ABC class (Abstract Base
Class). Inside the Shape class, we define an abstract method called area() using
the @abstractmethod decorator.
The Rectangle and Circle classes inherit from the Shape class. They provide their own
implementations of the area() method specific to their shapes. Note that the implementation
details are hidden from the outside world, and only the interface defined by the abstract class
is exposed. These are the basic principles of Object Oriented Programming. By applying these
concepts, you can write more organized, reusable, and maintainable code (Singh, 2024).
1. Generalization / Inheritance
Generalization is the practice of identifying shared attributes and behaviors among multiple
classes and encapsulating them within a common superclass or parent/base class. This parent
class includes the common properties and methods that are inherited by its subclasses. There
are two terms called Generalization and Inheritance:
• Generalization is the term that we use to denote abstraction of common properties into
a base class in UML.
• When we implement Generalization in a programming language, it is
called Inheritance.
• So, Generalization and Inheritance are the same, the terminology just differs depending
on the context where it is being used.
Generalization increases code reusability in software design, makes the code reusable, and
helps design the code in a more organized way. At the same time, it enables a class to extend
or modify the behavior of another class. An example using the class diagram:
Figure 5 Inheritance
2. Dependency
It refers to a relationship in which one class needs to use or access another class. This
relationship describes situations where one class depends on the properties or functionality of
another class. Namely, a change in one thing may affect another. It enables them to split
classes into smaller, more specific pieces. This encourages designing according to a design
principle where each class has a single responsibility (single responsibility principle).
Figure 6 Dependency
3. Aggregation
Aggregation represents a type of relationship in which a class can contain other classes.
The lifecycles of these classes are independent of each other, meaning the lifespan of one class
does not affect the other. This structural relationship typically denotes
a ‘whole/part’ relationship and is often expressed as a ‘has-a’ relationship, signifying that one
class possesses other classes.
Figure 7 Aggregation
4. Composition
Composition is a stronger version of aggregation. In composition, the parts are tightly
connected to the whole. When you create the whole object, you must also create its parts.
There’s a close relationship between the whole and its parts, and their lifecycles are
interdependent. This means that one object cannot work on its own; it’s an essential part of
another object, often described as an ‘is-a-part-of’ relationship.
Figure 8 Composition
5. Abstraction
The abstract class can be used to enable abstraction in OOP. It is designed to be extended by
other classes, serving as a blueprint for the creation of new classes that share common
attributes and behaviors. It is performed to be inherited by other classes, and it serves as
a template for those subclasses. Abstract classes provide a mechanism for sharing code among
related classes. When multiple classes have common attributes and methods, these can be
grouped in an abstract class, reducing code duplication. It defines a structure that subclasses
must adhere to. This helps maintain consistency in how related classes are designed and used.
It supports polymorphism, which means you can use instances of derived classes through a
reference to the abstract class. This allows for more generic and flexible code. (Polymorphism
explains the next topic…)
It can be extended to create new classes that inherit both the structure and behavior of the
abstract class. This simplifies the process of adding new functionality to your code.
6. Interface
An interface is an abstract structure that defines the methods (functions) and behaviors that a
class must implement. It provides a contract or agreement that specifies what methods and
behaviors a class should have. When a class implements an interface, it is required to provide
concrete implementations for all the methods defined in that interface. Interfaces
support polymorphism, allowing objects of different classes that implement the same interface
to be treated as instances of that interface type. (Polymorphism explains the next topic…) It
enables a class to implement multiple interfaces, promoting loose coupling. Loose coupling
makes the code more modular and easier to maintain.
Figure 11 (interface)
7. Polymorphism
Polymorphism is the concept that allows objects of different classes to be treated as if they
were instances of a common parent-class. It means that objects from various classes can be
used interchangeably if they adhere to the same interface or have a common base class. It
promotes code reuse by allowing you to use the same code with different classes, reducing
redundancy and enhancing maintainability. It simplifies code, enabling generic treatment of
objects. This eliminates the need for separate code for each specific class, allowing the creation
of generic code that works with any object adhering to a specific contract (interface or base
class). Moreover, it promotes the important OOP principle of abstraction. It empowers you to
abstract away the specifics of individual implementations and concentrate on the shared
behaviors among different objects.
Figure 13 (Circle)
In this sample, circle variable is referenced the Shape class, but created instance from the
circle class. So that, this variable cannot use the ChangeLocation method coming from the
circle class.
8. Encapsulation
Encapsulation involves enclosing an object’s internal data within the object and limiting direct
external access to that data. This is often done by using private or protected fields within the
class.
Public methods (getters and setters) are used to provide controlled and validated interactions
with the object’s data. It allows hiding the internal details of an object’s data. This is important
for maintaining data integrity and ensuring that the object’s state is not accidentally or
maliciously modified.
Figure 14 Encapsulation
In the sample code, the encapsulation is enabled using methods to explain it, however
properties are more useful to encapsulate the fields.
In this code, the Order class is juggling two responsibilities: calculating the total order amount
and generating an invoice. This violates the SRP, and it's time for a wardrobe change in your
code. Separate these responsibilities into different classes.
2. Open-Closed Principle (OCP)
The Open-Closed Principle suggests that classes should be open for extension but closed for
modification. It’s like having a versatile dress that you can accessorize to suit various
occasions:
By extending the behavior of the Shape class with the Circle and Rectangle classes, you
embrace the OCP, allowing you to introduce new shapes without altering the Shape class.
In this example, the Ostrich class can substitute its parent class, Bird, even though
its fly method behaves differently. This adheres to the LSP.
By crafting smaller, client-specific interfaces, you allow clients to implement only what they
need, avoiding the burden of unnecessary dependencies.
In this example, the Switch class depends on the abstraction of a light source (bulb) rather
than a specific implementation. This allows flexibility in choosing different light sources.
In Conclusion
SOLID principles are not just theoretical concepts; they’re practical guidelines that enhance
your code’s maintainability and adaptability. Just as a timeless wardrobe is essential, SOLID
principles are essential to becoming a proficient software developer. So, as you embark on your
coding journey, keep these SOLID design principles in mind. They will be your trusted
companions, ensuring your code remains elegant, maintainable, and, most importantly,
timeless (Leone, 2023).
Writing code is like giving a speech. If you use too many big words, you confuse your audience.
Define every word, and you end up putting your audience to sleep. Similarly, when you write
code, you shouldn’t just focus on making it work. You should also aim to make it readable,
understandable, and maintainable for future readers. To paraphrase software engineer Martin
Fowler, “Anybody can write code that a computer can understand. Good programmers write
code that humans can understand.” As software developers, understanding how to write clean
code that is functional, easy to read, and adheres to best practices helps you create better
software consistently. This article discusses what clean code is and why it’s essential and
provides principles and best practices for writing clean and maintainable code (codacy, 2023).
When teams adhere to clean code principles, the code base is easier to read and navigate, which
makes it faster for developers to get up to speed and start contributing. Here are some reasons
why clean code is essential.
• Readability and maintenance: Clean code prioritizes clarity, which makes reading,
understanding, and modifying code easier. Writing readable code reduces the time
required to grasp the code's functionality, leading to faster development times.
• Debugging and issue resolution: Clean code is designed with clarity and simplicity,
making it easier to locate and understand specific sections of the codebase. Clear
structure, meaningful variable names, and well-defined functions make it easier to
identify and resolve issues.
• Improved quality and reliability: Clean code prioritizes following established coding
standards and writing well-structured code. This reduces the risk of introducing errors,
leading to higher-quality and more reliable software down the line.
Now that we understand why clean code is essential, let's delve into some best practices and
principles to help you write clean code (codacy, 2023).
Here’s why clean code matters and can help acquire success in designing any project.
• Maintainability
A thoroughly documented code gives a person the chance to maintain it and use it for
a long period. Always remember that there could be someone working on the same code
after years, thus your goal should be that they understand your code well without any
prior knowledge. Make sure you leave comments and implement the logic in a
categorised, simple way.
• Scalable
With products being remodelled and upgraded over and over, it needs to scale as well.
One way of doing that is to have a strong existing code base and documentation for
designers to build upon.
• Logical
Once presented with a problem, every coder needs to pause and think about the logic
and prepare an algorithm first, without directly rushing into coding. A code written with
prior planning makes them good and clean. Such codes always have a justification and
understanding behind them which essentially tells us that it’s easy to understand.
• Readability
Clean coders work with the authors, they also have chapters & headings in the form of
classes, namespaces, and different methods. Their codes are like a book to read.
• Easy to test
It’s difficult to do automated testing if the underlying code is messy. Cleaner ones are
simpler to test and more to the point. It’s also easy to find mistakes from a clean
interface (CodeQuotient, 2021).
Like a beautiful painting needs the right foundation and brushstrokes, well-crafted code
requires adherence to specific principles. These principles help developers write code that is
clear, concise, and, ultimately, a joy to work with.
Example:
The example below uses the hard-coded number 0.1 to represent a 10% discount. This makes
it difficult to understand the meaning of the number (without a comment) and adjust the
discount rate if needed in other parts of the function.
Also, If the discount rate needs to be changed, it only requires modifying the constant
declaration, not searching for multiple instances of the hard-coded number.
2. Use Meaningful and Descriptive Names
Choose names for variables, functions, and classes that reflect their purpose and behavior. This
makes the code self-documenting and easier to understand without extensive comments.
As Robert Martin puts it, “A name should tell you why it exists, what it does, and how it is
used. If a name requires a comment, then the name does not reveal its intent.”
Example:
If we take the code from the previous example, it uses generic names like "price" and
"discount," which leaves their purpose ambiguous. Names like "price" and "discount" could be
interpreted differently without context.
3. Use Comments Sparingly, and When You Do, Make Them Meaningful
You don't need to comment on obvious things. Excessive or unclear comments can clutter the
codebase and become outdated, leading to confusion and a messy codebase.
Example:
This comment provides meaningful information about the function's behavior and explains
unusual behavior and potential pitfalls.
4. Write Short Functions That Only Do One Thing
Follow the single responsibility principle (SRP), which means that a function should have one
purpose and perform it effectively. Functions are more understandable, readable, and
maintainable if they only have one job. It also makes testing them very easy. If a function
becomes too long or complex, consider breaking it into smaller, more manageable functions.
Example:
The improved code separates the tasks into distinct functions. This results in more readable,
maintainable, and testable code. Also, If a change needs to be made, it will be easier to identify
and modify the specific function responsible for the desired functionality.
5. Follow the DRY (Don't Repeat Yourself) Principle and Avoid Duplicating Code or
Logic
Avoid writing the same code more than once. Instead, reuse your code using functions, classes,
modules, libraries, or other abstractions. This makes your code more efficient, consistent, and
maintainable. It also reduces the risk of errors and bugs as you only need to modify your code
in one place if you need to change or update it.
Example:
• Python:
o Use snake_case for variable, function, and class names.
o Use spaces over tabs for indentation.
o Put opening braces on the same line as the function or class declaration.
• JavaScript:
o Use camelCase for variable and function names.
o Use snake_case for object properties.
o Indent code with two spaces.
o Put opening braces on the same line as the function or class declaration.
o
Also, consider extending some of these standards by creating internal coding rules for your
organization. This can contain information on creating and naming folders or describing
function names within your organization.
One way to improve the readability and clarity of functions is to encapsulate nested if/else
statements into other functions. Encapsulating such logic into a function with a descriptive
name clarifies its purpose and simplifies code comprehension. In some cases, it also makes it
easier to reuse, modify, and test the logic without affecting the rest of the function. In the code
sample below, the discount logic is nested within the calculate product discount function,
making it difficult to understand at a glance.
Example:
8. Refactor Continuously
Regularly review and refactor your code to improve its structure, readability, and
maintainability. Consider the readability of your code for the next person who will work on
it, and always leave the codebase cleaner than you found it.
Version control systems meticulously track every change made to your codebase, enabling
you to understand the evolution of your code and revert to previous versions if needed. This
creates a safety net for code refactoring and prevents accidental deletions or overwrites.
Use version control systems like GitHub, GitLab, and Bitbucket to track changes to your
codebase and collaborate effectively with others (codacy, 2023).
• Example: Using a hash table for fast lookups instead of a list when implementing a
cache system ensures O(1) average time complexity for retrieval operations.
Benefit:
• The code not only becomes easier to manage but also performs better, as data structures
are used in the most appropriate and efficient manner for the task at hand.
Conclusion
The application of clean code techniques to data structure operations ensures that the codebase
is more robust, maintainable, and efficient. It directly impacts the quality of the software by
reducing errors, improving performance, and making the code easier to understand and extend.
This, in turn, leads to more reliable and scalable systems.
While developing a software solution, various discussions take place to plan and determine the
best possible procedure for the product development process. In this process, the group of
developers may be unable to come up with a commonly accepted approach to solve a specified
real-world problem. Due to differences in their problem-solving approach, software developers
provide various unique ways of building object-oriented software applications that solve a
particular problem. This uniqueness can lead to developer-favored variations in source code
that can make the software difficult to distribute, extend, reuse, and manage by fellow
developers. Hence, there is a need for standardization in the case of object-oriented software.
A creational design pattern deals with object creation and initialization, providing guidance
about which objects are created for a given situation. These design patterns are used to increase
flexibility and to reuse existing code.
• Factory Method: Creates objects with a common interface and lets a class defer
instantiation to subclasses.
• Abstract Factory: Creates a family of related objects.
• Builder: A step-by-step pattern for creating complex objects, separating construction
and representation.
• Prototype: Supports the copying of existing objects without code becoming dependent
on classes.
• Singleton: Restricts object creation for a class to only one instance.
A data structure is a storage that is used to store and organize data. It is a way of arranging data
on a computer so that it can be accessed and updated efficiently. A data structure is not only
used for organizing the data. It is also used for processing, retrieving, and storing data. There
are different basic and advanced types of data structures that are used in almost every program
or software system that has been developed. So we must have good knowledge about data
structures.
Data structures are the fundamental building blocks of computer programming. They define
how data is organized, stored, and manipulated within a program. Understanding data
structures is very important for developing efficient and effective algorithms. In this tutorial,
we will explore the most commonly used data structures, including arrays, linked lists, stacks,
queues, trees, and graphs (Geeksforgeeks, 2024).
In computer science, linear data structures are a kind of data structure where every element of
the data is ordered either linearly or sequentially. This indicates that every component has a
specific location in relation to the others. Put another way, the elements are arranged in a logical
order or sequence. Linear data structures are further divided into four types:
• Arrays
• Linked Lists
• Stacks
• Queues
1. Arrays
Figure 22 Arrays
An array is a fundamental and widely used data structure in computer science that organizes
elements of the same data type into a contiguous block of memory. The elements in an array
are accessed using an index or a key, which represents their position within the array. The index
usually starts at zero for the first element and increments by one for each subsequent element.
This structure allows for efficient random access to elements.
2. Linked Lists
A linked list is a linear data structure in which elements, called nodes, are connected
sequentially. Unlike arrays, where elements are stored in contiguous memory locations, linked
lists use pointers to link nodes together. Each node in a linked list consists of two parts: the
information or value it contains as well as a link or reference to the node behind it in the chain.
Usually, the final node indicates the end of the list by pointing to null.
3. Stacks
Figure 24 Stacks
Stacks are Last In, First Out (LIFO) data structures that enable items to be pushed to the top
and removed from the top. They are frequently employed in the implementation of function
call stacks and undo/redo capabilities. The two primary operations associated with a stack are:
3. Queues
Figure 25 Queues
Queues are data structures that operate on the First In, First Out (FIFO) principle. This means
that items can be added at the end of the queue and removed at the front. They are frequently
employed in task scheduling and buffering implementations. In a queue, elements are added at
one end, known as the “rear” or “enqueue” operation, and removed from the other end, known
as the “front” or “dequeue” operation. This ensures that the oldest elements are processed
before the newer ones (Mattoo, 2024).
Non-linear data structures are organizational formats in computer science where elements are
interconnected in a way that does not follow a sequential order. Unlike linear structures (e.g.,
arrays or linked lists), non-linear structures allow elements to have multiple successors,
forming complex relationships. These structures enable versatile modeling of relationships,
supporting more complex and interconnected representations of data in various computational
scenarios.
Trees
Figure 26 Trees
Graphs
Figure 27 Graphs
A set of nodes (also known as vertices) and the edges that join node pairs make up a graph data
structure. It is a flexible representation that is employed to simulate the relationships between
various elements. Generally, nodes in a graph stand for entities (such as towns, people, or web
pages), and edges show the connections or interactions between these things.
Graphs can be directed or undirected. Moreover, graphs may feature weighted edges, which
give a connection’s cost or strength a numerical value. Graphs are an essential and powerful
data structure in computer science, with applications across social networks, transportation
systems, and computer networks (Mattoo, 2024).
In developing software solutions for Sampath Food City, adhering to SOLID principles is
crucial for creating a robust, flexible, and maintainable codebase. The SOLID principles Single
Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency
Inversion provide a comprehensive framework for designing a sophisticated software
architecture that meets the complex needs of the supermarket network. Each principle focuses
on different aspects of design and development, collectively fostering a system that is scalable,
adaptable, and resilient to change. Below, we explore how each SOLID principle is applied
within the context of Sampath Food City, establishing the foundation for effective software
development practices (geeks, 2024).
1. Monthly Sales Analyse
Dependency Inversion Principle (DIP): The function relies on abstractions (such as data
sources and plotting libraries) rather than concrete implementations. This decoupling allows
for easy swapping of components (e.g., changing the data source) without modifying the core
price analysis logic, promoting flexibility and ease of maintenance.
In essence, the price_analysis function exemplifies how SOLID principles can be leveraged to
create modular, adaptable, and maintainable code for specific tasks like product price analysis
in the context of Sampath Food City's operations.
Liskov Substitution Principle (LSP): While not directly evident in this specific function, it
is designed with LSP in mind. Future enhancements could introduce subclasses or variations
of the function, ensuring that these new implementations can seamlessly replace the original
without disrupting the system's functionality.
Interface Segregation Principle (ISP): The function maintains a cohesive set of
responsibilities strictly related to weekly sales analysis. It avoids incorporating unnecessary
methods or functionalities, keeping the code focused and easier to manage, which aligns with
the principles of ISP.
Dependency Inversion Principle (DIP): The function depends on an abstraction (load_data)
for data retrieval rather than being tightly coupled to a specific implementation. This allows
for easy switching of data sources (e.g., different file formats or databases) without requiring
changes to the function itself, enhancing the system's flexibility and maintainability.
In conclusion, the weekly_sales_analysis function exemplifies the practical application of
SOLID principles in creating a well-structured, adaptable, and maintainable component within
the supermarket network's sales data analysis system.
Interface Segregation Principle (ISP): The observer classes only need to implement the
update method from the ProductPreferenceObserver interface. This focused interface adheres
to ISP, preventing classes from implementing unnecessary methods.
Dependency Inversion Principle (DIP): The ProductPreferenceAnalyzer depends on the
ProductPreferenceObserver interface, not on specific observer implementations. This
abstraction allows for flexibility in adding or changing observers without impacting the
analyzer's core logic.
Overall, the code's adherence to SOLID principles makes it a robust and adaptable solution for
Sampath Food City's product preference analysis. It ensures the system is easy to maintain,
extend, and modify, contributing to its long-term value and effectiveness.
Clean coding practices have played a pivotal role in the development of the Sampath Food City
system, ensuring the creation of code that is not only functional but also highly readable and
maintainable. By adhering to principles like using meaningful variable names, promoting
modularity, and following coding standards, we have significantly improved the overall clarity
of the codebase.
For example, within the monthly sales analysis and product preference tracking modules,
descriptive variable names enhance readability and reduce the likelihood of errors during
development or future modifications. Additionally, by adhering to the Single Responsibility
and Open/Closed principles, we have structured the code into well-defined classes with specific
functionalities. This modular approach makes the codebase easier to maintain, as changes can
be localized to specific areas without unintended consequences.
As the development of the Sampath Food City system progresses, consistent adherence to these
clean coding practices will remain a top priority. This commitment to writing clean code will
ensure that the system remains adaptable, maintainable, and scalable in the long term,
effectively supporting the company's evolving needs and objectives.
2. Modularization
Figure 33 Modularization
The code snippet showcases modularization, a clean coding technique, by employing distinct
classes to encapsulate specific functionalities. Each class acts as an independent module, such
as AddBranchCommand for adding branches, AddSaleCommand for adding sales, and
MonthlySalesAnalysis for analyzing monthly sales. This approach enhances code readability
by dividing complex tasks into smaller, focused units. These modules can also be reused in
different parts of the application, reducing code duplication and promoting efficiency.
Modularization also simplifies maintenance, as changes to one module are less likely to affect
others. This isolation also makes it easier to test individual modules thoroughly. The use of a
base Command class hints at the potential for further abstraction and shared behavior, which
can be achieved by implementing interfaces or abstract classes.
Clear naming conventions and thorough documentation are essential for maintaining code
clarity and organization. By adhering to modularization principles, the Sampath Food City
codebase becomes more manageable, efficient, and easier to maintain, contributing to a more
robust and scalable system.
Figure 35 Comments
The provided code snippet effectively demonstrates the use of comments to enhance readability
and maintainability, a key aspect of clean code techniques. Comments clarify the code's
purpose, logic, and functionality, making it more understandable for others. In the snippet, each
function is preceded by a clear and concise comment, such as `# Function for user login`, which
accurately describes its purpose without unnecessary verbosity. The benefits of using
comments include improved code understanding, as they help developers quickly grasp the
code's logic; facilitated code maintenance, by reminding developers of the original intent when
making changes; and enhanced collaboration through effective communication among team
members. It is crucial to balance comments with code to avoid clutter, keep comments up-to-
date as the code evolves, and ensure comments are meaningful by avoiding redundancy. By
consistently using clear and concise comments, the readability and maintainability of the
Python code for this system are significantly improved.
The benefits of maintaining consistent indentation and formatting are substantial: it improves
readability by making the code’s structure immediately apparent, reduces the likelihood of
syntax errors and logical mistakes, and facilitates easier modifications and reviews.
Additionally, it supports better collaboration by ensuring that multiple developers can work on
the code seamlessly when a standardized style is followed. To further ensure consistency,
employing a linter or code formatter is recommended, and adhering to style guides like PEP 8
can solidify formatting practices. Overall, by adhering to consistent indentation and formatting,
the code remains clean, maintainable, and conducive to collaborative development.
The selection and implementation of design patterns in the Sampath Food City system have
been both strategic and targeted, addressing the specific needs and challenges encountered
during development. Each design pattern has been chosen to solve particular design issues,
enhancing the system’s efficiency, flexibility, and maintainability. For example, the Observer
pattern is employed to enable effective communication between components, ensuring that
updates in one part of the system are automatically reflected in dependent components, as seen
in the Product Preference Analyzer. The Factory Method pattern is utilized for creating chart
observers, offering a flexible and scalable way to instantiate different chart types according to
specific needs. Moreover, the Decorator pattern is applied to the SalesAnalyzer, allowing for
the dynamic addition of features to the histogram observer and demonstrating a modular and
adaptable approach to code enhancement. Each design pattern has been carefully integrated
into the Sampath Food City system, reflecting a thoughtful approach to overcoming design
challenges and optimizing the overall architecture.
Automated testing has been a cornerstone in the development of the Sampath Food City system,
ensuring the identification and rectification of issues early in the development cycle. We
utilized a combination of unit testing, integration testing, and end-to-end testing to rigorously
validate individual components, interactions between components, and the overall system
behavior. Python frameworks like Pytest and Unittest were instrumental in systematically
creating and executing test scripts.
Unit tests verified the proper functioning of individual functions and methods, while integration
tests confirmed seamless interactions between different subsystems. End-to-end tests simulated
real user interactions to validate the application's complete flow. This automated testing
approach significantly aided in early bug detection and regression prevention, thereby
enhancing development efficiency through rapid feedback.
By integrating automated testing into the development lifecycle, we improved the
maintainability and scalability of the Sampath Food City system while ensuring it consistently
meets its functional requirements. This rigorous testing regimen ultimately contributes to a
more reliable, stable, and high-quality software product.
Automated testing is an indispensable part of modern software development, and the Sampath
Food City project is no exception. It empowers developers to detect and address issues early
on, resulting in increased development efficiency, reduced defects in production, and
ultimately, higher customer satisfaction. It also speeds up the development process due to the
increased speed and efficiency of testing, allowing for more frequent and confident deliveries.
Moreover, automated tests act as a safety net during code changes, safeguarding against
unintended regressions and ensuring the system's overall integrity.
• Unit test
A key component of software testing is unit testing, which involves evaluating specific features
or components of an application separately. This process guarantees that every software unit
operates as intended. Unit testing helps find and repair defects early in the development
process, greatly enhancing the quality and stability of the code, by concentrating on tiny,
manageable portions of the program.
Developers usually use different frameworks like JUnit, NUnit, or pytest to write and automate
unit tests. These tests verify the accuracy of the code by ensuring that, for a given set of inputs,
each function or method produces the desired outcomes (GeeksforGeeks, 2024).
Unit testing is a core software testing technique that involves the isolation and validation of
individual code components (units) in isolation from the rest of the system.
The provided code constitutes a robust suite of unit tests for the Sampath Food City system,
designed to rigorously validate various aspects of its functionality. These tests adhere to the
core principles of unit testing:
• Isolation: External dependencies are replaced with mock objects, ensuring that each test
focuses solely on the isolated unit under scrutiny.
• Automation: The unittest framework automates test execution, providing rapid
feedback on the correctness of individual units without manual intervention.
• Fast Execution: Tests are designed to run quickly, allowing for frequent execution and
enabling developers to identify issues promptly.
• Repeatability: The tests produce consistent results upon each execution, as long as the
tested code remains unchanged, ensuring reliability and predictability.
• Independence: Each test functions independently, preventing the success or failure of
one from influencing the outcome of others.
• Coverage: The tests cover a substantial portion of the codebase, including data loading,
command execution, utility functions, and sales analysis, enhancing the system's
overall robustness.
Specifically, the tests verify the following:
• TestDataLoaderFactory: Ensures the factory correctly creates a data loader and loads
data from CSV files.
• TestCommands: Validates the execution of commands like adding branches or sales,
checking their interaction with data storage.
• TestUtilityFunctions: Tests utility functions like user login, simulating successful and
unsuccessful scenarios.
• TestSalesAnalysis: Ensures the accuracy of sales analysis functions using sample data.
By adhering to these principles, the unit tests provide a comprehensive safety net for the
Sampath Food City system. They enable early detection of defects, streamline development,
and contribute to a more reliable and maintainable codebase.
Ensure Create an The printed output matches the expected. Output based on the
Display instance test
analysis of
prints Monthly
analysis. Sale
Analyser
Confirm Create an The printed output matches the expected. Output based on the
Display instance test data and parameters
filtered of
data prints Monthly
filtered Sales
data. Analyser
Rigorous testing of the MonthlySalesAnalyzer class has confirmed its effectiveness in handling
various data analysis and visualization tasks.
The preprocess_data method successfully adds essential 'Month' and 'Year' columns to the data
frame. The display_analysis method accurately prints analysis results that align with expected
outcomes from the test data. Additionally, the display_filtered_data method correctly prints
filtered data based on given parameters.
Further tests verified the load_data method's ability to load data accurately and the filter_data
method's effectiveness in filtering data as expected. The generate_plot method was also
validated to generate plots correctly, confirming the proper functioning of the visualization
aspect.
Overall, these comprehensive tests demonstrate that the MonthlySalesAnalyzer class performs
all its designated tasks with precision, including data preparation, analysis, filtering, and
visualization. The consistent results across the various tests ensure the reliability and accuracy
of the class's functionalities for monthly sales analysis.
• Integration Test
Software testing that involves testing the various units, modules, or components of an
application is called integration testing, or integration and testing (I&T). It is possible,
nevertheless, that distinct programmers coded these components. Testing the interfaces
between the modules is the goal of integration testing, which also aims to identify any flaws
that might occur when these parts are combined and require communication with one another
(Awati, 2024).
ntegration testing is a crucial step in the software development process, verifying that
individual modules or components function seamlessly when combined. Several types of
integration testing exist:
• Top-Down Integration Testing: This approach starts testing from the highest-level
modules, gradually moving down to lower levels. It verifies the behavior of higher-
level components before integrating and testing lower-level ones.
• Bottom-Up Integration Testing: In contrast, this method begins testing from the most
basic modules, progressively combining and testing them until all higher-level modules
are evaluated.
• Big Bang Integration Testing: This strategy involves integrating all or most
components simultaneously and testing the entire system as a whole. It doesn't follow
a step-by-step integration process but tests the complete integration in one go.
• Validates Data Flow: It ensures data is passed correctly between modules without loss
or corruption.
4.Use
WeeklySalesReporter
to display sales
analysis and generate
a chart.
5. Capture the
console output.
Expected Output
This type of testing is vital for ensuring a positive user experience, as it helps identify and
eliminate performance-related issues that could negatively impact users. Without performance
testing, problems such as slow response times or inconsistencies between the user interface and
the operating system could degrade the overall user experience. Performance testing allows
developers to validate whether a system meets specific speed, responsiveness, and stability
requirements under various workloads, ultimately leading to a better user experience.
Benefits of Performance Testing
• Identifying Bottlenecks: Performance testing helps locate performance bottlenecks,
such as slow code sections, inefficient algorithms, or resource-intensive processes. This
information allows developers to focus optimization efforts on the areas that will have
the most significant impact on performance.
• Ensuring Scalability: Scalability testing is a subset of performance testing that
assesses how well an application can handle increasing numbers of users or data
volumes. This information is crucial for planning future growth and ensuring the system
can maintain performance under heavier loads.
• Optimizing Resource Utilization: Performance testing helps optimize the use of
system resources, such as CPU time, memory, and network bandwidth. Efficient
resource management leads to better system performance and resource utilization.
• Validating System Architecture: Performance testing validates whether the system's
design can handle the expected workloads and user behavior throughout its lifecycle.
This ensures that the architecture is suitable for the application's requirements.
• Mitigating Risks: By proactively identifying and addressing performance issues,
performance testing reduces the risks associated with poor application performance,
system downtime, and user dissatisfaction.
• Enhancing User Experience: A responsive and reliable application, as verified
through performance testing, significantly improves the user experience. This is crucial
for user retention and overall satisfaction.
• Meeting Service Level Agreements (SLAs): Performance testing ensures that
applications meet the performance standards outlined in service level agreements. This
is particularly important for mission-critical applications where performance is a
contractual requirement.
The table details a performance test designed to assess the efficiency of the perform_operation
function. It measures the average time taken to execute the function 100 times using the
timeit.timeit tool. The test simulates realistic usage scenarios to ensure a comprehensive
evaluation. Results, including the average execution time of 0.09844560925001133 seconds,
are clearly displayed for analysis and comparison.
PyTest: A powerful and popular framework for Python that simplifies test discovery, fixtures,
and parameterized testing.
JUnit: Widely used for Java applications, offering annotations and assertions to define test
cases and verify outcomes.
TestNG: Extends JUnit, providing additional features like parallel execution, parameterization,
and test grouping, suitable for both unit and integration testing.
NUnit: Designed for .NET applications, enabling unit testing in C# and other .NET languages,
with attributes for setup, teardown, and test fixtures.
PyTest: Also suitable for integration testing, allowing validation of interactions between
components.
TestNG: Useful for managing integration tests and their dependencies with its annotations and
grouping mechanisms.
Test::Unit: A Ruby framework that organizes tests into suites and provides setup and teardown
mechanisms.
Apache JMeter: An open-source tool focusing on load testing and performance measurement,
simulating multiple users to evaluate application performance under various scenarios.
Apache Benchmark (ab): A command-line tool for basic performance testing of Apache HTTP
servers, measuring request rates and response times.
LoadRunner was selected for performance testing due to its specialized capabilities in
measuring system performance under varying loads. Its robust load testing and analysis
features provide valuable insights into system performance under different conditions.
By leveraging PyTest and LoadRunner, the project effectively addresses its unit, integration,
and performance testing requirements, ensuring a comprehensive and thorough testing process.
This table displays essential product information for Sampath Food City. It provides a clear
and concise list of products, each identified by a unique Product ID, alongside their
corresponding Product Name. This data serves as a crucial reference for tracking sales
transactions, analyzing product performance, and managing inventory. By assigning unique
identifiers to each product, the table enables efficient data management and facilitates various
analyses such as sales trends, product popularity, and inventory optimization.
Sales Data Analysis
Finally, the function presents a clear overview of the sales performance. It displays the sales
details for each day of the current week, along with the calculated total sales and average daily
sales figures.
In essence, this function automates the process of analyzing weekly sales data, offering
valuable insights into sales trends and overall performance during the current week.
The image shows a bar chart titled "Price Analysis of Each Product," which visually
summarizes the average price and price range for 104 products. Each product is represented by
a blue bar indicating its average price, with a lighter blue extension depicting the price range.
The price range varies significantly across products, with some reaching close to 300 units (the
specific unit is not labeled).
The accompanying Python code defines a system for product price analysis and visualization.
The ProductData class (implemented as a singleton) handles product data loading. The
PriceAnalysisStrategy class outlines the analysis process by merging sales and product data,
and calculating mean, maximum, and minimum prices. The PriceAnalyzer class manages the
overall analysis using the selected strategy, while the ChartDrawer class creates a bar chart to
visualize the results. The chart showcases average prices and price ranges with error bars.
For Sampath Food City, this system offers valuable insights into product pricing. The bar chart
reveals how different products are priced in comparison to each other, aiding in decision-
making regarding pricing strategies, inventory management, and promotions. The code can be
further improved by adding features such as error handling, more chart types, and interactive
elements for enhanced data exploration.
The Sampath Food City system has effectively incorporated list, set and arrays as an efficient
way of system strategies to enhance efficiency. For different tasks, the required characteristics
are as follows: lists offer novel modifications for many uses, sets offer fast membership
identification and distinct data, and arrays are well-suited for numerical calculations. This
arrangement ensures efficient handling of data within the system and hence a very efficient
implementation of the system.
Figure 53 (List)
Lists play a key role in the Sampath Food City system, particularly in managing and organizing
information related to monthly and weekly stock levels and sales data across various branches.
The 'branches' list, being concise and specific, facilitates quick retrieval of sales data based on
branch location. Lists are also instrumental in organizing monthly and product-related data in
a mutable format, allowing for easy modification and manipulation.
The flexibility of lists empowers the system to efficiently process large volumes of branch data,
making tasks such as filtering, aggregating, and analyzing information more manageable.
Additionally, the strategic use of lists contributes to the system's modular and scalable design,
aligning with clean coding principles and ensuring the system can accommodate future growth
and enhancements.
In essence, lists provide a versatile and efficient data structure within the Sampath Food City
system, facilitating seamless data handling and analysis for effective decision-making.
Figure 54 (Map)
he provided code snippet illustrates the use of a map data structure, known as a dictionary in
Python, which plays a crucial role in the command-based system for Sampath Food City. A
map is essentially a collection of key-value pairs where each key is unique and maps to a
specific value, allowing for efficient retrieval based on the key. In this context, the commands
dictionary maps string keys (which could represent user input or menu options) to various
values, including class names such as AddBranchCommand and MonthlySalesAnalysis, as
well as lambda functions like lambda: print("Logged out.").
This map serves as a command registry or menu system, enabling the dynamic retrieval and
execution of commands based on user input. For example, if the user inputs '2', the system
retrieves the corresponding value from the commands dictionary, such as AddSaleCommand,
and executes it. This design promotes efficient lookups and flexible storage of different
command types, enhancing the system's modularity and readability. The use of a map in this
manner supports a clean, organized approach to managing various commands and actions
within the Sampath Food City sales data analysis system, ensuring that command handling
remains efficient and easily maintainable.
In the Sampath Food City system, the utilization of data structures such as maps and lists
significantly enhances data organization and processing efficiency. Maps, represented by
structures like `commands`, efficiently manage and retrieve commands based on user input.
This allows for quick access to various functionalities, such as adding a new branch or
analyzing sales data, by associating specific keys with corresponding actions or classes. Lists,
such as `branches`, are used to manage ordered data sets, including monthly and product-
specific weekly data. These ordered collections support easy iteration and retrieval of
information, which is essential for generating reports and performing analyses. The integration
of maps and lists aligns with the system's goals of efficient data management and streamlined
operations, providing a robust framework for handling the complex data requirements of
Sampath Food City.
• Opening and Closing Files: The open() function initiates file interaction, requiring the
file's name/path and the mode (read, write, append). It returns a file object used for
subsequent operations. The close() method releases system resources once operations
are complete. The with statement ensures proper file closure, even in case of errors,
improving code reliability.
• Reading from a File: Data retrieval from files involves methods like read() (entire file
as a string), readline() (line by line), and readlines() (list of lines), offering flexibility in
handling file data.
• Writing to a File: The write() method modifies or adds data to files. Opening the file
in "write" mode ('w') prevents accidental overwriting. The with statement is again
recommended for clean-up and error handling.
• Using the with Statement: This construct streamlines file handling by automatically
opening and closing files within its block, even if errors occur, preventing resource
leaks and enhancing code clarity.
• Working with Binary Files: Non-text files (images, audio, etc.) are handled using
specific modes like 'rb' (read binary) and 'wb' (write binary) with the open() function.
• Seek and Tell: The seek(offset) method moves the file cursor to a specified position,
allowing reading or writing at specific points. The tell() method returns the cursor's
current position, facilitating precise file navigation.
These file handling techniques empower Python programs to interact effectively with various
types of files, enabling data storage, retrieval, and modification as needed.
Sets a random seed for the NumPy random number generator. A seed is a starting point for
generating random numbers. By setting a specific seed, you ensure that the sequence of random
numbers generated will be the same every time the code is run.
Uses the generated data to create a pandas DataFrame containing the columns "Date,"
"Branch," and "Sales."
Responsible for loading data from a CSV file into a Pandas DataFrame. It is likely part of a
larger class that handles data processing or analysis. The data_source attribute should be set
before calling this function to specify the location of the CSV file.
Assigns the string value "Sales.csv" to a variable named data_source. This variable is likely
used to specify the file path of a CSV file containing sales data.
The Sampath Food City system demonstrates proficient file handling techniques for seamless
data management. It begins by establishing a consistent random number generation for reliable
testing and analysis. The generated data is meticulously organized into a pandas DataFrame,
enhancing manipulation and analysis capabilities.
The system clearly specifies the filename "Sales.csv" for data storage, promoting organization
and accessibility. This DataFrame is then exported to the CSV file without an index, ensuring
compatibility with various data analysis tools. The absolute path assignment to data_source
further enhances code readability and maintainability.
The load_data method employs pandas' read_csv function, providing a smooth and efficient
way to load data into a DataFrame, and ensuring compatibility with diverse data formats.
Additionally, the system leverages a factory pattern to create an analyzer object tailored for
monthly sales data, which then loads data from the designated file. This enhances the system's
capacity for focused and specialized data analysis.
In conclusion, the Sampath Food City system's file handling, coupled with pandas' data
organization and analysis capabilities, ensures a robust, maintainable, and versatile solution
capable of effectively handling diverse data processing tasks.
Continuous Integration (CI) with Jenkins: To ensure continuous validation and streamline the
testing process, we integrated our automated tests into a CI/CD pipeline using Jenkins. This
setup allowed for automatic execution of unit and integration tests whenever code changes
were pushed to the repository. Continuous testing offered rapid feedback to the development
team, facilitating early detection and resolution of issues, which in turn enhanced code quality
and stability.
Additional Testing Methods (If Applicable): Beyond unit and integration testing, other
automated testing methods that might be used include:
System Testing: Automated system tests to verify the end-to-end functionality using tools and
techniques that ensure comprehensive evaluation.
Performance Testing: Tools or libraries to simulate user loads and measure system performance
under various conditions.
Security Testing: Automated security tests to identify and address potential vulnerabilities
within the system.
By detailing the chosen tools, implementation methods, and any additional automated testing
types, the effectiveness of the automatic testing approach in enhancing the quality and
reliability of the Sampath Food City sales data analysis system can be demonstrated.
Unit Testing
Unit testing has been crucial in building a robust and reliable Sampath Food City system. By
isolating and testing each software component, we've identified and addressed issues early,
preventing them from escalating into larger problems. Unit tests provide a safety net during
system updates and maintenance, ensuring new features or modifications do not disrupt
existing functionalities. Furthermore, automated unit testing quickly identifies any unintended
side effects from code changes, maintaining the core operations of the system. Additionally,
unit tests serve as live documentation, illustrating the expected behavior of each function or
class, which improves communication and understanding among developers. Overall, unit
testing has significantly contributed to code stability and quality, aligning with industry best
practices and fostering a dependable software solution.
System Testing
System testing is vital for verifying the integrated functionality, performance, and reliability of
the Sampath Food City software. It assesses the entire system, ensuring that all components
work together seamlessly in their intended environment. By simulating real-world scenarios
and applying diverse test cases, system testing evaluates responsiveness, scalability, and
reliability under realistic conditions, ensuring the software meets user expectations and handles
anticipated data volumes and traffic. This phase also uncovers high-level issues not apparent
in unit or integration testing, such as data flow, security, and overall system performance
problems. Early detection and resolution of these defects are crucial for delivering a reliable
final product. In summary, system testing provides a comprehensive check of integrated
components, accurately replicates the production environment, and identifies systemic flaws,
ensuring the software meets the company's requirements and performance benchmarks.
Acceptance Testing
Acceptance testing is the final validation step before software deployment, ensuring that the
developed solution meets Sampath Food City's business and user requirements. It involves real
users testing the system to ensure it aligns with their needs and expectations. This phase focuses
on user satisfaction and fulfilling business requirements, guaranteeing the delivered software
meets expectations and integrates smoothly into their workflow, ensuring a seamless transition
and user adoption. Additionally, acceptance testing verifies that the software supports and
enhances the company's operations, including sales, product selection, and overall supermarket
management. It acts as a final safeguard, identifying any functional discrepancies or usability
concerns before release. Addressing these concerns early minimizes post-implementation
problems, ensuring the software is both technically sound and strategically aligned with
organizational goals, instilling confidence in stakeholders regarding its deployment.
Performance Testing
Performance testing evaluates the responsiveness of the Sampath Food City system under
various conditions, simulating real-world usage to identify potential bottlenecks or
performance issues. It helps assess the software's scalability as the company and its data volume
grow, ensuring the system maintains speed and efficiency even with increased demands. This
process also identifies and rectifies performance issues by applying different stress levels,
enabling developers to optimize critical areas and enhance overall efficiency. The benefits of
performance testing are extensive, including improved user experience by minimizing
slowdowns and system failures, and identifying potential risks related to system performance
under high traffic or heavy data loads. Performance testing is indispensable for Sampath Food
City, as it assesses application scalability, identifies improvement areas, and enhances
usability, ensuring the system operates efficiently and meets the growing needs of the
supermarket network.
Security Testing
Security testing is crucial for protecting Sampath Food City's sensitive data and preventing
unauthorized access. Given the volume of customer details, sales records, and inventory data
handled, identifying and addressing system vulnerabilities is essential for safeguarding
information and maintaining customer trust. Security testing ensures compliance with industry
regulations, protecting the company from legal and financial repercussions while
demonstrating a commitment to data privacy. Beyond compliance, security testing actively
MH Mohamed Ifham(E193622) APDP pg. 104
When choosing between developer-produced and vendor-provided testing tools, factors like
flexibility, control, cost, support, and compatibility play a critical role. Both types of tools are
essential in software development, each with its own strengths and ideal use cases.
Conclusion
The development of the Sampath Food City sales data analysis system exemplifies a successful
blend of object-oriented programming principles, SOLID design principles, clean coding
practices, design patterns, and thorough testing methodologies. By adhering to these best
practices, we have built a robust, scalable, and maintainable system that enables the
supermarket network to extract valuable insights from its sales data. The modular design,
reinforced by SOLID principles and clean coding, ensures that the system can easily evolve
and adapt to future needs. Strategic use of design patterns such as Singleton, Factory Method,
and Observer enhances the system's flexibility, maintainability, and overall effectiveness.
Rigorous testing, including unit testing, integration testing, and performance testing, ensures
the system's reliability, stability, and performance under various conditions. This project
demonstrates the power of combining solid software engineering principles and practices to
deliver a high-quality solution that meets the complex data analysis needs of a modern
supermarket chain.
Self-Criticism
While I aim for accuracy and thoroughness, I recognize my limitations as a language model.
Sometimes, I might produce responses that lack depth or context, especially on complex or
specialized topics. Despite extensive training on large datasets, I may still reflect biases
inherent in the data, resulting in unintended or insensitive outputs. It's also important to
remember that I can't verify the factual accuracy of all information, so users should critically
assess my responses and consult additional sources when needed. I'm dedicated to continuous
improvement and welcome feedback to enhance my abilities and offer more helpful and
reliable support.
Gantt Chart
References
codacy, 2023. codacy. [Online]
Available at: https://blog.codacy.com/what-is-clean-code#WhatIsCleanCode
[Accessed 2024].
CodeQuotient, T., 2021. codequotient. [Online]
Available at: https://codequotient.com/blog/clean-code/
[Accessed 2024].
Doherty, E., 2024. educative.io. [Online]
Available at: https://www.educative.io/blog/object-oriented-programming#what-is-oop
[Accessed 2024].
Geeksforgeeks, 2024. geeksforgeeks. [Online]
Available at: https://www.geeksforgeeks.org/data-structures/
[Accessed 2024].
Geeksforgeeks, 2024. Geeksforgeeks. [Online]
Available at: https://www.geeksforgeeks.org/introduction-of-object-oriented-programming/
geeks, G., 2024. SOLID Principles in Programming: Understand With Real Life Examples.
[Online]
Available at: https://www.geeksforgeeks.org/solid-principle-in-programming-understand-
with-real-life-examples/
Gulati, V., 2024. scaler. [Online]
Available at: https://www.scaler.com/topics/design-patterns/what-are-design-patterns/
[Accessed 2024].
Leone, U., 2023. Stackademic. [Online]
Available at: https://blog.stackademic.com/solid-principles-are-the-cornerstone-of-well-
structured-and-maintainable-code-f8280910cbb5
[Accessed 2024].
Mattoo, S., 2024. intellipaat. [Online]
Available at: https://intellipaat.com/blog/what-is-data-structure/
[Accessed 2024].
Singh, A. P., 2024. blog.algomaster.io. [Online]
Available at: https://blog.algomaster.io/p/basic-oop-concepts-explained-with-code
[Accessed 2024].