SDLC and Agile in Software Engineering
SDLC and Agile in Software Engineering
CSE 325
-Information and System Design-
Group 03
Lecture 03
Group Members:
SDLC (Software Development Life Cycle) is a framework that software development teams use
to plan, design, build, test, and deploy software applications. In other words, a life cycle model
maps the various activities performed on a software product from its inception to retirement.
Different life cycle models may plan the necessary development activities into phases in different
ways.
1. Planning and requirement analysis: Requirement Analysis is the most important and
necessary stage in SDLC. This phase involves:
1
Figure 2: Steps of Requirement Analysis
• Assessing the feasibility of the project in terms of resources, budget, and timelines.
Feasibility consists of Economic, Legal, Technical and Schedule feasibility.
• Developing a high-level project plan
• Defining the project team roles and responsibilities
• Choosing project management approach and methodology to be used
• Obtaining necessary approvals and funding for the project.
2. Defining Requirements: Following things are done in the second phase of SDLC.
• Requirements Analysis: Once the requirements have been gathered, they are
analyzed to identify any inconsistencies, ambiguities, or conflicts.
• Requirements Specification: The requirements are documented in a clear and
concise manner.
• Requirements Review: The Requirements Specification document is reviewed
by stakeholders to ensure that all requirements have been captured accurately and
completely.
Overall, the defining requirements phase is critical to the success of a software project as
it lays the foundation for the rest of the SDLC phases.
2
3. Designing the Software: In the design phase, the program developer scrutinizes whether
the prepared software suffices all the requirements of the end-user. Additionally, if the
project is feasible for the customer technologically, practically, and financially. Once the
developer decides on the best design approach, he then selects the program languages like
Oracle, Java, etc., that will suit the software.
5. Testing: the testing phase is a critical stage that helps ensure the quality, reliability, and
functionality of the software product. The following are some of the activities that are
typically done in the testing phase:
• Test Planning
• Test Case Development
• Test Execution
• Defect Tracking
Once all the testing activities are complete, the software product is signed off,
indicating that it has passed all the required tests and is ready for release.
3
6. Deployment and Maintenance:
Deployment: Once the software testing phase is over and no bugs or errors left in the
system then the final deployment process starts. Based on the feedback given by the
project manager, the final software is released and checked for deployment issues if any.
Maintenance: After the deployment of a product on the production environment,
maintenance of the product i.e. if any issue comes up and needs to be fixed or any
enhancement is to be done is taken care of by the developers. Mainly following 3 activities
occur:
• Bug fixing
• Upgrade
• Enhancement
• Waterfall model
• Iterative model
• Agile model
4
1.3 Benefits of Software Development Life Cycle
Software Development Life Cycle helps to manage risk, improves software quality, promotes
collaboration and communication, enables efficient resource utilization, and provides a standardized
development process. Some of the benefits are:
Collaboration
Better
project
management
Software
Quality
Development
software
Life Cycle
Efficiency
Customer
satisfaction
2. Improved project management: SDLC helps project managers to define clear project
objectives, identify risks, allocate resources, and manage timelines and budgets effectively.
This helps to ensure that the project is delivered on time, within budget, and to the
expected quality standards.
5
ensure that the software application is developed according to the requirements of the
end-users. This helps to improve customer satisfaction and reduces the risk of costly
rework or project failure.
5. Increased efficiency: SDLC enables software development teams to identify and address
issues early in the development process, reducing the need for costly rework or revisions
later on. This helps to improve efficiency, reduce costs, and ensure that the software
application is delivered on time and within budget.
• Costly: It is difficult to estimate the actual cost of the entire project and the project
overruns. It may lead to an increase in the cost of software development especially if the
customer requirements are not understood properly.
Despite its limitations, SDLC (Software Development Life Cycle) is a widely accepted approach
to software development because it offers several benefits which surpasses these limitations.
6
2. Agile Manifesto and Scrum Framework
• Individuals and interactions over processes and tools: This value emphasizes the
importance of communication and collaboration between team members, and the idea
that people are more important than processes or tools.
• Responding to change over following a plan: This value emphasizes the importance
of flexibility and adaptability in the development process, and the idea that change is
inevitable and should be embraced rather than resisted.
1. Our highest priority is to satisfy the customer through early and continuous delivery of
valuable software.
2. Welcome changing requirements, even late in development. Agile processes harness change
for the customer’s competitive advantage.
4. Business people and developers must work together daily throughout the project.
7
5. Build projects around motivated individuals. Give them the environment and support
they need, and trust them to get the job done.
6. The most efficient and effective method of conveying information to and within a
development team is face-to-face conversation.
8. Agile processes promote sustainable development. The sponsors, developers, and users
should be able to maintain a constant pace indefinitely.
10. Simplicity, the art of maximizing the amount of work not done, is essential. [Approximately
80% of product value comes from 20% of the features. So avoid implementing unnecessary
features.]
11. The best architectures, requirements, and designs emerge from self-organizing teams.
12. At regular intervals, the team reflects on how to become more effective, then tunes and
adjusts its behavior accordingly.
• Scrum: This framework can be viewed as short waterfall model. It involves a team
(or multiple teams) and some requirements. Scrum teams operate in set periods of
time, called sprints, usually lasting between two and four weeks Before a sprint/cycle
the teams get requirements. The teams analyse, work on the requirements and deliver
a ready-to-ship software after the cycle. Scrum framework involves multiple sprint of
incremental development. This framework is more suitable when working with fixed set of
requirements.
8
Figure 4: Scrum Framework
• Kanban: This framework is more suitable for dynamic requirements. The requirements
9
are sorted based on their priority. The priority order of requirements can change from
time to time. When a team member is free, he/she selects the top requirement from the
priority order and starts working on it. So, the team members need to be adept and
experienced. Used when designing something innovative for the market.
The Scrum Values are particularly important in environments where experimentation is core to
making progress.
10
The Scrum Framework consists of roles, artifacts, and events.
2.3.1 Roles
• Product Owner: The product owner is responsible for defining and prioritizing the
product backlog. Product owner is someone who -
– Understands the requirements well enough to prevent the team from being stuck
whenever a decision about requirement is needed.
– Communicates with stakeholders and customer.
• Development Team: The development team is responsible for building the product
increment. The team is self-organizing and cross-functional, meaning that they have all
the skills and expertise necessary to -
– Define
– Build
– Test
11
the required product
2.3.2 Events
Good communication is essential in scrum process and is carried out through meetings, called
events. Scrum events include the following:
• Daily Scrum: The daily scrum is a short, stand-up daily meeting where the team
discusses progress and obstacles.
• Sprint: A Sprint is the time frame in which work must be completed – most often 4
weeks. New Sprints start right after the end of the previous one.
• Sprint Planning: The sprint planning meeting is held at the beginning of each sprint,
and it is used to plan the work that will be completed during the sprint.
• Sprint Review: The sprint review is held at the end of each sprint, and it is used to
demonstrate the increment to stakeholders and receive feedback.
12
2.3.3 Artifacts
An artifact is something of historical interest that warrants being reexamined. In Scrum product
development, artifacts are used to see what has been done and what is still in the queue.
It is useful to look at Scrum artifacts in meetings/events.
Scrum artifacts include the following:
• Product Backlog: The product backlog is a prioritized list of features or user stories
that the team will work on during the sprint. Most valued features are given highest
priority. The product backlog is owned by the product owner, and it is the responsibility
of the team to deliver the items on the backlog.
• Sprint Backlog: The sprint backlog is a list of items from the product backlog that
the team commits to completing during the sprint. The sprint backlog is owned by the
development team, and it is the responsibility of the team to deliver the items on the
sprint backlog.
• Product Increment: The increment is the sum of all the completed items at the end of
the sprint – as well as what’s been created during all previous Sprints. The increment
must be usable and potentially releasable, meaning that it should be of high quality and
ready to be delivered to the customer.
• Burn down: A burn down chart is a visual representation of the amount of work that
still needs to be completed.
• Quality product.
• Teamwork.
• Flexibility.
• Reduced risk.
• Decreased time to market. Scrum aims to release products and their features in predictable
increments using well-defined sprints.
• Higher return on investment (ROI). Constant feedback leads to less costly mistakes late
in the process and a better product with fewer defects. Decreased time to market and
incremental releases bring in revenue faster.
13
The Scrum Framework is designed to be flexible and adaptable, allowing teams to respond
to changing requirements and deliver high-quality products. The framework emphasizes
transparency, inspection, and adaptation, and it encourages teams to work collaboratively
and continuously improve their processes.
14
3. User Requirement Analysis and Stories
• Provides a clear and concise description of the technical work that needs to be done.
• Provides a basis for testing and ensuring the quality of the system.
15
3.3 Spike Story
A spike story is a type of user story that is used to investigate a particular technical problem or
issue. A spike story is typically time-boxed and has a specific goal or outcome. Spike stories are
often used when a team is unsure about the feasibility of a particular solution or approach and
needs to do some exploration or research before proceeding with development. Spike stories are
useful for reducing technical risk and increasing confidence in a solution.
The benefits of spike story are:
• Provides a basis for testing and ensuring the quality of the system.
• Identifying stakeholders: This involves identifying all the individuals or groups that
have a stake in the software system and who will be affected by its development and use.
16
• Documenting requirements: This involves documenting the requirements in a clear,
concise, and unambiguous way that can be easily understood by stakeholders, developers,
and testers.
User requirement analysis is an iterative process that requires ongoing communication and
collaboration between stakeholders, developers, and testers to ensure that the system meets the
needs and expectations of users.
17
4. Software Testing and Quality Assurance
There are various types of software testing techniques used in the industry. The selection of
testing technique depends on the requirements, complexity, and nature of the software system.
Here are some of the most common types of software testing:
3. Unit Testing: Validating that each software unit performs as expected. A unit is the
smallest testable component of an application.
4. Functional Testing: This type of testing ensures that the software system or application
is functioning as per the specified requirements. Functional testing includes both manual
and automated testing methods, such as unit testing, integration testing, system testing,
and acceptance testing.
18
7. Usability Testing: Usability testing is done to evaluate the ease of use, user interface,
and user experience of the software system. It includes user acceptance testing, user
experience testing, and user interface testing.
9. Regression Testing: Regression testing is done to ensure that the changes made in the
software system do not affect its existing functionality. It includes automated testing and
manual testing.
Few can argue against the need for quality control when developing software. Late delivery or
software defects can damage a brand’s reputation — leading to frustrated and lost customers. In
extreme cases, a bug or defect can degrade interconnected systems or cause serious malfunctions.
Consider Nissan having to recall over 1 million cars due to a software defect in the airbag sensor
detectors. Or a software bug that caused the failure of a USD 1.2 billion military satellite
launch. The numbers speak for themselves. Software failures in the US cost the economy USD
1.1 trillion in assets in 2016. What’s more, they impacted 4.4 billion customers.
Though testing itself costs money, companies can save millions per year in development and
support if they have a good testing technique and QA processes in place. Early software testing
uncovers problems before a product goes to market. The sooner development teams receive test
feedback, the sooner they can address issues such as:
• Architectural flaws
• Security vulnerabilities
• Scalability issues
When development leaves ample room for testing, it improves software reliability and high-quality
applications are delivered with few errors. A system that meets or even exceeds customer
expectations leads to potentially more sales and greater market share.
19
4.1.3 Benefits of Software Testing
Software testing is an essential part of the SDLC and offers several benefits, including:
1. Improved Quality: Software testing helps in identifying defects and errors in the software
system, thereby improving its quality and reliability.
2. Increased Customer Satisfaction: Software testing ensures that the software system
meets the customer’s requirements and expectations, thereby increasing customer satisfaction.
3. Cost-Effective: Testing defects early in the development cycle reduces the cost of fixing
the defects in the later stages, making it cost-effective.
4. Reduced Time to Market: Software testing ensures that the software system is free of
defects and errors, reducing the time to market.
Software testing follows a common process. Tasks or steps include defining the test environment,
developing test cases, writing scripts, analyzing test results and submitting defect reports.
Testing can be time-consuming. Manual testing or ad-hoc testing may be enough for small builds.
However, for larger systems, tools are frequently used to automate tasks. Automated testing
helps teams implement different scenarios, test differentiators (such as moving components into
a cloud environment), and quickly get feedback on what works and what doesn’t.
1. Early Testing: Testing should be done early in the development cycle to identify defects
and errors in the software system.
2. Test Automation: Test automation helps in reducing the time and effort required for
testing and ensures consistency in the testing process.
3. Traceability: Test cases should be traceable to the requirements, ensuring that all the
requirements are tested.
4. Test Coverage: Test coverage should be comprehensive, covering all the functionalities
and scenarios of the software system.
20
5. Test Environment: The test environment should be similar to the production environment,
ensuring that the testing results are accurate.
6. Test Data: Test data should be realistic and relevant, ensuring that the testing results
are accurate.
7. Reporting: Testing results should be reported accurately and clearly, including the
defects and errors found in the software system.
8. A good testing approach encompasses the application programming interface (API), user
interface and system levels. As well, the more tests that are automated, and run early,
the better. Some teams build in-house test automation tools. However, vendor solutions
offer features that can streamline key test management tasks such as:
• Continuous testing: Project teams test each build as it becomes available. This type
of software testing relies on test automation that is integrated with the deployment
process. It enables software to be validated in realistic test environments earlier in
the process – improving design and reducing risks.
• Configuration management: Organizations centrally maintain test assets and
track what software builds to test. Teams gain access to assets such as code,
requirements, design documents, models, test scripts and test results. Good systems
include user authentication and audit trails to help teams meet compliance requirements
with minimal administrative effort.
• Service virtualization: Testing environments may not be available, especially early
in code development. Service virtualization simulates the services and systems that
are missing or not yet completed, enabling teams to reduce dependencies and test
sooner. They can reuse, deploy and change a configuration to test different scenarios
without having to modify the original environment.
• Defect or bug tracking: Monitoring defects is important to both testing and
development teams for measuring and improving quality. Automated tools allow
teams to track defects, measure their scope and impact, and uncover related issues.
• Metrics and reporting: Reporting and analytics enable team members to share
status, goals and test results. Advanced tools integrate project metrics and present
results in a dashboard. Teams quickly see the overall health of a project and can
monitor relationships between test, development and other project elements.
21
4.1.5 Conclusion
Software testing is an essential part of the SDLC that helps in identifying defects, errors, and
bugs in the software system. It offers several benefits, including improved quality, increased
customer satisfaction, and cost-effectiveness.
Abbreviated as SQAP, the software quality assurance plan comprises the procedures, techniques,
and tools that are employed to make sure that a product or service aligns with the requirements
defined in the SRS(software requirement specification).
22
The plan identifies the SQA responsibilities of a team, and lists the areas that need to be
reviewed and audited. It also identifies the SQA work products. The SQA plan document
consists of the below sections:
1. Purpose section
2. Reference section
8. Testing methodology
1. Creating an SQA Management Plan: The foremost activity includes laying down a
proper plan regarding how the SQA will be carried out in your project.
23
Along with what SQA approach you are going to follow, what engineering activities will be
carried out, and it also includes ensuring that you have the right talent mix in your team.
2. Setting the Checkpoints: The SQA team sets up different checkpoints according to
which it evaluates the quality of the project activities at each checkpoint/project stage.
This ensures regular quality inspection and working as per the schedule.
4. Executing Formal Technical Reviews: An FTR is done to evaluate the quality and
design of the prototype.
In this process, a meeting is conducted with the technical staff to discuss the actual quality
requirements of the software and the design quality of the prototype. This activity helps in
detecting errors in the early phase of SDLC and reduces rework effort in the later phases.
6. Enforcing Process Adherence: This activity insists on the need for process adherence
during the software development process. The development process should also stick to
the defined procedures.
This activity is a blend of two sub-activities which are explained below in detail:
• Product Evaluation: This activity confirms that the software product is meeting
the requirements that were discovered in the project management plan. It ensures
that the set standards for the project are followed correctly.
• Process Monitoring: This activity verifies if the correct steps were taken during
software development. This is done by matching the actually taken steps against the
documented steps.
7. Controlling Change: In this activity, we use a mix of manual procedures and automated
tools to have a mechanism for change control.
24
By validating the change requests, evaluating the nature of change, and controlling the
change effect, it is ensured that the software quality is maintained during the development
and maintenance phases.
8. Measure Change Impact: If any defect is reported by the QA team, then the concerned
team fixes the defect.
After this, the QA team should determine the impact of the change which is brought by
this defect fix. They need to test not only if the change has fixed the defect, but also if
the change is compatible with the whole project.
For this purpose, we use software quality metrics that allow managers and developers to
observe the activities and proposed changes from the beginning till the end of SDLC and
initiate corrective action wherever required.
9. Performing SQA Audits: The SQA audit inspects the entire actual SDLC process
followed by comparing it against the established process.
It also checks whether whatever was reported by the team in the status reports was
actually performed or not. This activity also exposes any non-compliance issues.
10. Maintaining Records and Reports: It is crucial to keep the necessary documentation
related to SQA and share the required SQA information with the stakeholders. The test
results, audit results, review reports, change requests documentation, etc. should be kept
for future reference.
11. Manage Good Relations: In fact, it is very important to maintain harmony between
the QA and the development team.
We often hear that testers and developers often feel superior to each other. This should
be avoided as it can affect the overall project quality.
5. Change management
25
6. Educational programs
7. Vendor management
8. Security management
9. Safety
There are several techniques for SQA. Auditing is the chief technique that is widely adopted.
However, we have a few other significant techniques as well. Various SQA Techniques include:
1. Auditing: Auditing involves inspection of the work products and its related information
to determine if the set of standard processes were followed or not.
2. Reviewing: A meeting in which the software product is examined by both the internal
and external stakeholders to seek their comments and approval.
3. Code Inspection: It is the most formal kind of review that does static testing to find
bugs and avoid defect growth in the later stages. It is done by a trained mediator/peer
and is based on rules, checklist, entry and exit criteria. The reviewer should not be the
author of the code.
4. Design Inspection: Design inspection is done using a checklist that inspects the below
areas of software design:
26
5. Simulation: A simulation is a tool that models a real-life situation in order to virtually
examine the behavior of the system under study.
6. Functional Testing: It is a QA technique that verifies what the system does without
considering how it does it. This type of black box testing mainly focuses on testing the
system specifications or features.
10. Path Testing: It is a white box testing technique where the complete branch coverage is
ensured by executing each independent path at least once.
11. Stress Testing: This type of testing is done to check how robust a system is by testing
it under heavy load i.e. beyond normal conditions.
12. Six Sigma: Six Sigma is a quality assurance approach that aims at nearly perfect products
or services. It is widely applied in many fields including software. The main objective of
six sigma is process improvement so that the produced software is 99.76% defect-free.
4.2.5 Conclusion
27
5. Tools for Software Engineering Projects
Project management tools and version control systems play a critical role in software development.
These tools have revolutionized the way software is created, making the process more efficient
and streamlined. They allow developers to collaborate seamlessly, manage tasks, track progress,
and maintain version history. The subsequent sections will explore the rationale behind project
management and version control systems, as well as delve deeper into Git.
2. Distributed Version Control System: Instead of relying on a central server to store all
versions of a project’s files, distributed version control systems allow developers to clone a
copy of the repository onto their own hard drive, giving them full access to the project’s
history. The process of getting new changes from a repository is known as pulling, and
moving one’s own changes to a repository is known as pushing. Mercurial, Git and Bazaar
are amongst the most popular distributed version control systems.
28
Merging
Tagging
Branching
Automation
Code
Management
Reusability
Efficiency
Rollback
to
Previous
Version Backup Version
Control and
System Restore
Disaster
Recovery
Simultaneous
Editing
Collaboration
Tracking
Code Changes
Reviews
Revert
Team
Changes
Communication
Change
Compare
Log
Versions
1. Complete change history: Version control systems allow for the storage of a long-term
change history of every file, including information about the author, date, and purpose
of each change. This history enables developers to go back to previous versions of the
software to identify the root cause of bugs or to fix issues in older versions.
2. Branching and merging: VCS tools provide the ability to work on independent streams
of changes through the creation of branches, which can be merged back together to verify
that the changes do not conflict. Teams may adopt different branching workflows, such as
branching for each feature or release.
3. Traceability: VCS tools enable traceability by connecting each change made to the
software to project management software like Jira. Annotated histories of the code can
help with root cause analysis, understanding the code’s purpose, and making harmonious
changes that align with the system’s intended long-term design. This is especially important
for working with legacy code and for accurate estimation of future work.
29
5.3 Exploring Git: An Overview
Git is by far, the most widely used version control system in the world today. Git is a Distributed
Version Control System (DVCS), which means it has a distributed architecture. This allows
each developer’s working copy of the code to be a repository that holds the full history of all
changes. Some terminologies about the git interface are explained below:
Snapshots/Commits:
Git captures changes to a directory and its contents as a sequence of snapshots, each of which
represents the complete state of files and sub-directories within a top-level directory. Additionally,
git store metadata such as the author of each snapshot, associated messages, and other relevant
information.
Branches:
In Git, a history is a directed acyclic graph (DAG) of snapshots. These snapshots are referred
to as commits in Git. A commit history can be visualized as a series of commits and their
relationships, where each commit points to its parent.
In Git, commits can be branched, allowing multiple developers to work independently on different
parts of a project in parallel. This means one group of developers can work on the master
branch, while another group can work on implementing new features. Later, these changes can
be merged into the master branch.
30
Staging area:
Instead of creating a new snapshot based on the current state of the working directory, Git uses
a staging area to specify which modifications should be included in the next snapshot. This
allows for clean snapshots and gives developers greater control over the contents of each commit.
1. Proper commit messages: A commit message should be brief, yet descriptive enough
to understand what the commit is about. The first line should be a summary, followed by
a blank line and then a more detailed explanation of the changes.
2. Commit often: Frequent commits can help in keeping your changes concise and relevant,
thereby promoting the practice of committing only the related changes. It also enables one
to share their code more often with other team members. This allows smoother integration
and avoids the risk of merge conflicts. On the other hand, making infrequent and large
commits can complicate the process of conflict resolution.
3. Use branches: Git allows one to work on multiple branches, making it easier to separate
different features or bug fixes. It is recommended to create a branch for each feature, bug
fix, or task, and merge it back to the main branch when it’s complete.
4. Push changes regularly: It is recommended to push the changes to the remote repository
as soon as one has a working copy. This ensures that the changes are safely stored and
can be accessed by other team members. Delaying the push of one’s changes can lead to
synchronization issues and make it harder to resolve conflicts when merging with other
changes.
5. Use pull requests for code review: Before merging code into the main branch, it is
recommended to use pull requests to allow other team members to review the changes.
This can help catch errors, improve code quality, and ensure that the changes fit into the
overall project.
6. Regularly pull changes from remote repositories: To avoid conflicts and ensure
working with the most up-to-date version of the codebase, one should regularly pull changes
from remote repositories.
31
7. Keeping the repository clean: Unnecessary files or changes, such as temporary files or
IDE-specific files should not be commited. A .gitignore file can be used to exclude files
that don’t need to be versioned.
1. Task and project tracking: Project management tools allow teams to create and assign
tasks, set deadlines, and track progress. This helps to ensure that everyone is on the same
page and that work is progressing as planned.
3. Resource management: These tools can help teams manage resources such as people,
time, and budget. They can also help to identify and resolve resource conflicts.
4. Reporting and analytics: Project management tools often include reporting and
analytics capabilities that allow teams to monitor progress, identify issues, and make
data-driven decisions.
5. Integration with other tools: Many project management tools can be integrated with
other software applications such as code repositories, testing tools, and deployment tools.
This helps to streamline the development process and ensure that everyone is working
with the same information.
2. Task management: Asana allows users to create tasks, assign them to team members,
set due dates, and track progress.
32
Figure 11: A glimpse of Asana’s intuitive interface for efficient project management
5. Integration with other tools: Asana integrates with a wide range of third-party
tools, such as Slack, Google Drive, and Dropbox, to streamline workflows and improve
productivity.
6. Reporting and Analytics: Asana offers reporting and analytics features that help users
track project progress and team performance.
33
6. Best Practices for Clean and Readable Code
Name: Sohaib
ID: 1805026
Clean and readable code is essential for software development because it helps improve
maintainability, reduce complexity, facilitate collaboration, increase efficiency, and enhance the
user experience.
Well-written code is easy to understand, modify, and maintain, reducing the time and effort
required for future development and maintenance. Clean code also reduces the complexity of
software systems, making them easier to manage, troubleshoot, and debug.
Robustness
Maintenance
Clarity
Consistency
34
Clean code is not just about following specific conventions, but also about understanding
the underlying principles of good software design. Experienced developers have a deeper
understanding of these principles and are better able to apply them in practice.
While writing clean code is a subjective process, there are certain principles that can be followed
to produce better, cleaner and more readable code.
• Singleton: This pattern ensures that there is only one instance of a class in the
system, providing global access to the object.
• Factory Method: This pattern provides an interface for creating objects, allowing
subclasses to define the type of objects to be created.
• Observer: This pattern defines a one-to-many relationship between objects, so that
when one object changes state, all its dependents are notified and updated.
These patterns (and many others) provide solutions to common problems in software
development and promote best practices in object-oriented design. By following these
patterns, developers can create code that is more modular, reusable, and maintainable,
resulting in software systems that are more flexible, extensible, and easier to manage.
2. DRY Principle: The DRY (Don’t Repeat Yourself) principle is a software development
principle that states that every piece of knowledge or logic should have a single, unambiguous,
and authoritative representation within a system. In short, DRY principle tells us to
reduce repetitions in our code.
Here’s an example of code that violates the DRY principle, and how it can be refactored
to be more clean and readable by applying the principle:
35
# Without Dry Principle
def calculate_price(item):
price = 0
if item['type'] == 'fruit':
price = item['weight'] * 1.5
elif item['type'] == 'vegetable':
price = item['weight'] * 1.0
elif item['type'] == 'meat':
price = item['weight'] * 4.0
return price
In the code above, the same calculation (multiplying the item’s weight by a specific factor)
is repeated multiple times for different types of items. This code is hard to understand
and difficult to maintain. For example, if the rate of any item changes, then it becomes
harder to update the rate.
Now, consider the following code :
This code is shorter, repetition free and more easier to read and maintain.
3. Writing shorter functions and classes: Shorter functions and classes are often
considered to be better for creating clean and readable code. This is because breaking
down code into smaller, more focused units can make it easier to understand and reason
about. Each function or class can be designed to address a specific context and objective,
resulting in a more modular and readable codebase.
Shorter functions and classes are generally easier to comprehend because they have a
narrower focus and do fewer things. This makes it easier to identify their purpose and
understand their behavior. Additionally, shorter functions and classes are often more
reusable, since they are less tightly coupled to the specific context in which they were
36
written.
Shorter functions and classes are easier to test, which is another advantage of breaking
down code into smaller, more focused units.
1. Fixing Major Bugs: Code review is not only focused on identifying and fixing major bugs
in the code. Its objective is to improve overall code quality, maintainability, and adherence
to coding standards. This involves identifying potential issues, providing feedback, and
suggesting improvements to the code, even if they may not be critical bugs.
2. Readable and Relevant Naming Conventions: Code reviews maintain relevant and
readable naming conventions, leading to clean and understandable code. They identify
inconsistent and misleading names, ensuring consistency and meaningfulness. This reduces
time spent on maintenance and improves collaboration, effectively communicating intent
and purpose.
3. Shorter Classes: Bigger classes and functions can make the code harder to understand
and modify, resulting in lower overall code quality. By limiting class sizes to 50 lines or
less, developers can ensure that classes are focused on a single responsibility and are easier
to maintain and modify. Smaller classes can also make the code easier to read and test,
reducing the time required to identify and fix bugs.
5. Avoid Commenting Out Unused Code: Commenting out unused code can lead to
confusion, as it can make it difficult for developers to distinguish between what is relevant
37
and what is not. It also adds unnecessary clutter to the codebase, which can increase the
likelihood of errors and decrease overall readability. Instead, developers should remove
unused code entirely or consider using version control systems to keep track of old or
unused code.
# Inconsistent Formatting
def isEven(x):
if(x%2==0 ): # using a tab here, extra space
return True # using 2 spaces here instead of tabs
else:
return False
# Consitent Formatting
def isEven(x):
if ( x % 2 == 0 ): # Used Spaces more consistently
return True # Used Tabs
else:
return False
6.3 Documentation
Code Documentation is the process of writing descriptions and explanations of the code
and its functionality. It includes comments, annotations, and other forms of text that provide
additional information about the codebase.
Documentation is helpful in many ways. First, it helps other developers understand how the
code works and how to use it. Second, it helps in maintaining the code in the future by providing
a clear understanding of its purpose and behavior. Third, it serves as a reference guide for
developers who might be working on the code in the future, saving time and effort.
38
6.3.1 Example of documentation
Parameters
----------
shape : int or tuple of int
Shape of the new array, e.g., ``(2, 3)`` or ``2``.
dtype : data-type, optional
The desired data-type for the array, e.g., `numpy.int8`.
Default is `numpy.float64`.
order : {'C', 'F'}, optional, default: 'C'
Whether to store multi-dimensional data in row-major
(C-style) or column-major (Fortran-style) order in
memory.
Returns
-------
out : ndarray
Array of zeros with the given shape, dtype, and order.
"""
6.3.2 Objective
• Short Summary: A one-line summary that does not use variable names or the function
name, e.g.
39
• Deprecation warning: A section to warn users that the object is deprecated, e.g.
@deprecated(
reason="""Since Python 3.4, you can use the standard function
:func:`statistics.mean`.""",
version="2.5.0",
)
def mean(values):
• Parameters: Description of the function arguments, keywords and their respective types.
• Warnings and Exceptions: Warn the user about the restrictions and exceptions raised
by the function. One such example is the Numpy’s matrix inverse function:
def inv(a):
"""
Compute the (multiplicative) inverse of a matrix.
Given a square matrix `a`, return the matrix `ainv` satisfying
``dot(a, ainv) = dot(ainv, a) = eye(a.shape[0])``.
Parameters
----------
a : (..., M, M) array_like
Matrix to be inverted.
Returns
-------
ainv : (..., M, M) ndarray or matrix
(Multiplicative) inverse of the matrix `a`.
Raises
------
LinAlgError
If `a` is not square or inversion fails.
40
6.3.3 Comments
Comments in code are necessary for providing additional context and explanations of what
the code does, the rationale behind it, and how it operates. Comments can also help other
developers understand the intention behind the code, and provide guidance on how to modify
or improve it.
• Good code speaks for itself Good code is self-explanatory and easy to understand
without the need for excessive commenting. Well-named variables, functions, and classes
help to convey the intent and purpose of the code. While some comments can be helpful,
relying too heavily on them can indicate underlying issues with the code’s design or
readability.
41
6.3.4 Tools for documentation
• Markdown: Markdown is a simple markup language for creating text formatting like
headings, lists, and links. It makes documentation writing and organization easier, supports
version control systems, and can be converted to HTML or other formats for sharing
across platforms.
42