0% found this document useful (0 votes)
18 views49 pages

Computer Programs Ict Lv2 Notes

The document provides an overview of computer program development, focusing on programming concepts, language translators, and programming paradigms. It explains the roles of programs, programming, and various types of language translators such as compilers, interpreters, and assemblers. Additionally, it covers programming paradigms like procedural, object-oriented, and event-driven programming, along with the importance of program specifications in software development.

Uploaded by

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

Computer Programs Ict Lv2 Notes

The document provides an overview of computer program development, focusing on programming concepts, language translators, and programming paradigms. It explains the roles of programs, programming, and various types of language translators such as compilers, interpreters, and assemblers. Additionally, it covers programming paradigms like procedural, object-oriented, and event-driven programming, along with the importance of program specifications in software development.

Uploaded by

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

COMPUTER PROGRAM DEVELOPMENT

ICT TECHNICIAN LEVEL 5

Wk1/L1 1: Introduction to Programming

Introduction to Programming
1. What is a Program?

A program is a sequence of instructions written in a programming language that tells


a computer how to perform a specific task.

Real-world analogy:
A recipe is like a program—it provides step-by-step instructions to prepare a
dish.
A musical score tells musicians how to play a song.

2. What is Programming?

Programming (coding) is the process of:


Analyzing a problem.
Designing a solution (algorithm).
Writing code in a programming language.
Testing & Debugging to fix errors.
Maintaining the program for updates.

Why Learn Programming?


Automation (e.g., payroll systems).
Problem-solving (e.g., weather prediction models).
Career opportunities (software development, AI, cybersecurity).

3. How Computers Understand Programs

Computers only understand binary (0s and 1s).


Humans write in high-level languages (Python, Java, C++).

Language translators convert human-readable code to machine code.

Definition of terms
Term Definition
A set of instructions written to perform a specific task on a
Program
computer.
The process of designing and writing a sequence of
Programming
instructions that a computer can execute.
Source Code Human-readable instructions written by a programmer in a
programming language.
Binary Code /
Low-level code that the computer understands (0s and 1s).
Machine Code
A program that converts the entire source code into
Compiler
machine code before execution.
A translator that converts and executes the source code line
Interpreter
by line.
Assembler Converts assembly language into machine code.
IDE (Integrated
A software suite that provides tools to write, debug, and run
Development
programs (e.g., VS Code, PyCharm).
Environment)

Language Translators

2.1 Types of Translators


(A) Assembler
Computers only understand machine code – a sequence of 0s and 1s. Writing
programs directly in binary is extremely difficult.
Assembly converts assembly language (low-level) → machine code.

The assembler generates machine code and handles memory addresses and labels.
Low-level and hardware-specific.
Fast and efficient in execution.
Requires detailed understanding of the hardware.

Advantages Disadvantages
 Efficient use of hardware  Difficult to learn and debug
 High performance  Non-portable (platform-specific)
 Precise control over system  Time-consuming to write large
resources programs
 Useful in time-critical systems

Used in:
Device drivers
Embedded systems
Real-time systems
Bootloaders

Example:
assembly
MOV AX, 05h ; Move value 5 into register AX
ADD AX, BX ; Add BX to AX
Translated into binary (e.g., 10110000 00000101).

(B) Compiler
A compiler is like a translator that reads the entire source code (all at once), checks it
for errors, and translates it into machine code. This machine code is stored in a
separate file which can then be executed.

Translates entire high-level program → machine code before execution.


Produces an executable file (machine code) eg - (.exe, .bin).

Advantages Disadvantages
 Faster execution after compilation.  Platform-dependent (needs
 Syntax checking done before recompilation for different OS).
execution.  Debugging is harder (errors shown
 Creates reusable executable files. after full compilation).
 Hides source code (protects logic).  Compilation can take time.
 Secure (source code hidden)

Examples:
C (gcc program.c -o program).
C++ (g++ [Link] -o app).

(C) Interpreter
An interpreter:
Reads, translates, and runs source code line-by-line.
Does not create a separate executable or object file.
Shows errors immediately when it reaches them.
Ideal for quick testing, scripting, or learning environments.

Advantages Disadvantages
 Easy to debug (errors appear as they  Slower than compiled code
happen)  Program must be re-interpreted
 Great for beginners every time it runs
 No need for separate compilation  Source code must be distributed
step (less secure)
 Cross-platform (can run code on any
machine with the interpreter)

Examples:
Language Interpreter
Python python or python3 CLI
JavaScript Browser JS engine or [Link]
Ruby ruby interpreter
PHP PHP engine
Bash Linux shell interpreters
MATLAB MATLAB runtime environment

2.2 Interpreter vs Compiler vs Assembler

Feature Interpreter Compiler Assembler

Language High-level High-level Assembly


Entire program at
Execution Line-by-line Entire program
once
Output No separate file Executable / binary Machine code
Reports all errors
Error Handling Stops at first error Stops on error
after compiling
Faster after
Speed Slower Fast
compiling
Low-level
Usage Scripting, testing Performance apps
hardware control

2.3 Just-In-Time (JIT) Compiler


A Just-In-Time (JIT) Compiler is a translator that converts intermediate code (often
bytecode) into native machine code just before execution, thereby combining
features of both interpreters and compilers to improve performance also known as
Hybrid approach (e.g., Java, .NET).

How it Works: Step-by-Step


i. High-level source code is first compiled into intermediate code (e.g., bytecode).
ii. The JIT compiler kicks in at runtime and converts this intermediate code into
native machine code.
iii. The native code is cached, so the program runs faster the next time the same
code runs.

Advantages of JIT Compilation


Advantage Description
Faster than interpretation because frequently used code is
Speed
compiled once and reused.
Efficiency Can optimize code based on actual runtime conditions.

Portability Intermediate code can run on any platform with the JIT runtime.

Security Bytecode is harder to reverse-engineer than source code.


Disadvantages of JIT compilation:

Disadvantag
Description
e
Startup
Takes some time during execution to compile bytecode.
Delay
Memory
Requires more memory for caching and runtime optimizations.
Usage
JIT compilers are more complex to implement than interpreters or
Complexity
static compilers.

Interpreter vs Compiler vs Assembler vs JIT Compiler


Feature Interpreter Compiler Assembler JIT Compiler
Intermediate
Input
High-level High-level Assembly Code (e.g.,
Language
Bytecode)
Executes
Machine code
line-by-line, Machine code Machine code
Output generated at
no output (Executable file) (Object file)
runtime
file
Execution Slow (line- Fast (after Fast (after first
Fast
Time by-line) compilation) execution)
Detects runtime
Stops at Detects low-
Shows all errors errors,
Error first error level errors
after optimizes
Detection during during
compilation during
execution translation
execution
No Saves Temporarily
Storage of Saves object
permanent to .exe, .class, or stores compiled
Output file .obj, .o
output .out native code
Python, Java, C#,
Example C, C++, Java
JavaScript, Assembly JavaScript (V8
Languages (partially)
PHP engine)
Optimizatio Runtime
Minimal Compile-time None
n optimization
Virtual
Embedded
Scripting, System/software machines,
Use Case systems,
education development browser
drivers
engines
High (code
High (runs on
runs Low (platform- Low
virtual machine
Portability anywhere dependent (hardware-
with JIT
interpreter binary) specific)
support)
exists)
Initial Slow Slow (due to Fast Slow (compiling
at runtime),
Execution
compile time) faster on repeat
Speed
runs
Reusability Not
Yes Yes Yes, if cached
of Output reusable

3. Practical Exercise

1. Which translator converts entire source code before execution?


A. Interpreter
B. Assembler
C. Compiler
D. JIT
Answer: C

2. What is the main role of an assembler?


A. Executes high-level code line-by-line
B. Converts source code into object files
C. Converts assembly language to machine code
D. Optimizes code at runtime
Answer: C

3. Which translator is used in environments like JVM and CLR?


A. Interpreter
B. Compiler
C. JIT Compiler
D. Assembler
Answer: C

4. What happens when an interpreter encounters an error?


A. Continues execution
B. Logs it and continues
C. Immediately stops
D. Compiles it anyway
Answer: C

5. Which of these languages is most commonly interpreted?


A. C++
B. JavaScript
C. Assembly
D. Swift
Answer: B

Section B: Fill in the Blanks


A compiler produces a __________ file after successful translation.
Assembly language is translated using an __________.
A __________ compiler optimizes code at runtime.
Interpreters execute code __________.
The output of an assembler is usually stored in a(n) __________ file.

Answers:
Executable
Assembler
JIT
Line-by-line
Object

Section c: Short Answer Questions


i. What is the main difference between a compiler and an interpreter?
ii. Why is JIT compilation considered faster over time compared to standard
interpretation?
iii. Give an example of a scenario where an assembler would be the preferred
translator.
iv. Explain why compiled programs are generally faster than interpreted ones.
v. What is the key benefit of using interpreted languages in teaching
environments?

Model Answer Highlights:

i. A compiler translates the whole program before execution, while an interpreter


translates and runs the code line-by-line.
ii. JIT compiles code during runtime and caches it, making repeated executions
faster due to optimization.
iii. Assemblers are ideal in low-level system programming like writing device drivers
or firmware.
iv. Because compiled programs are pre-translated to machine code, there's no
overhead during execution.
v. Interpreted languages offer instant feedback and are easier to debug for
beginners.
Wk1/L2: Programming Approaches & Practical Applications

1. Programming Paradigms

Programming paradigms are styles or approaches to programming that influence


how code is structured, written, and executed. Each paradigm provides a different
way of thinking about how to solve problems using a computer.
Think of paradigms as "programming philosophies" — different schools of thought
about how a program should be designed and how instructions should flow.

It is a fundamental style or model of programming that defines how problems are


approached and solved in a programming language

Major Programming Paradigms


Examples of
Paradigm Description
Languages
Code is organized into procedures or
Procedural functions. Emphasizes step-by-step C, Pascal, Python
execution.
Organizes code into objects that
Object-Oriented
combine data and behavior. Promotes Java, C++, Python
(OOP)
reuse and modularity.
Focuses on pure functions and avoids Haskell, Lisp,
Functional changing state. Uses expressions JavaScript
instead of statements. (partially)
Program flow is determined by
Event-Driven user/system events like clicks or JavaScript, [Link]
messages. Common in GUIs.
Based on formal logic. Programs
Logic Programming consist of facts and rules. The system Prolog
deduces answers.
Describes what the program should
Declarative SQL, HTML, Prolog
do, not how.
Gives the computer a sequence of
Imperative C, Java, Assembly
commands to change its state.

1.1 Procedural Programming


Structure: Code is organized into functions/procedures.
Approach: Top-down (break problem into smaller tasks).

Example Languages: C, Pascal.

Pros: Simple, easy to follow.


Cons: Hard to maintain for large projects.

Example in C:
c
#include <stdio.h>void greet() {
printf("Hello, World!");}int main() {

greet();
return 0;
}

1.2 Object-Oriented Programming (OOP)

Structure: Code is organized into objects (data + methods).

Key Principles:
Encapsulation: Bundling data + methods.
Inheritance: Reusing code from parent classes.
Polymorphism: One function, multiple forms.
Abstraction: Hiding complex details.

Example Languages: Java, C++, Python.

Example in Java:

class Vehicle {
void start() {
[Link]("Engine started.");
}
}

class Car extends Vehicle {


void honk() {
[Link]("Beep beep!");
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car();
[Link](); // Inherited from Vehicle
[Link]();
}}

1.3 Event-Driven Programming


Structure: Code runs in response to events (e.g., clicks, keypresses).

Example Languages: JavaScript, Visual Basic.


Example in JavaScript:

javascript
[Link]("myButton").addEventListener("click", () => {
alert("Button clicked!");});

1.4 Other Paradigms

 Functional Programming (FP):


Focuses on pure functions (no side effects).

Example: Haskell, Lisp.

 Logic Programming:
Uses rules and facts (e.g., Prolog).

Recap & Assessment (15 mins)


Quiz:
What is the difference between compilation and interpretation?
Name two OOP principles and explain them.
Which paradigm is best for GUI applications?

Group Discussion:
"Which programming approach is most versatile for modern software
development?"

1.0 Key Definitions


Term Definition
Program Specification A detailed written description of a
software program’s functionality,
features, inputs, outputs, and behavior
under different conditions.
Requirements Specification A document that outlines what the
system should do (the requirements),
including user needs.
Functional Re quirements Specifications describing what the
system should do (features, operations,
inputs, outputs).
Non-Functional Requirements Specifications that describe how the
system performs (e.g., speed, security,
usability).
Constraints Limitations or rules the program must
follow (e.g., must run on Windows, must
support 1,000 users).

2.0 What Is a Program Specification?


A program specification describes in detail what a program is supposed to do. It acts
as a blueprint or contract between the client and developer, ensuring everyone is
aligned before development starts.

Think of it as the instructions to build software — just like how a builder uses
architectural drawings.

3.0 Why Are Specifications Important?


- Avoid misunderstandings between developers and clients.
- Guide the coding, testing, and documentation process.
- Serve as a basis for validating the final product.
- Help identify potential issues early in the design phase.

4.0 Components of a Program Specification


- Program Title
- Overview
- Objectives
- Inputs
- Processing Logic
- Outputs
- Functional Requirements
- Non-Functional Requirements
- Constraints
- Assumptions

5.0 Example of a Simple Specification


Program Title: Student Grade Calculator
Overview: A desktop application to calculate final grades for students based on
assignment, midterm, and final exam scores.
Inputs:
- Student name
- Scores: Assignment (30%), Midterm (30%), Final (40%)
Processing:
- Compute final grade using weighted average.
Outputs:
- Final numeric grade
- Letter grade (A, B, C, D, F)
Functional Requirements:
- Input validation (scores must be between 0 and 100)
- Calculate grade automatically
- Display and print results
Non-Functional Requirements:
- Must run on Windows 10 and above
- Should respond within 2 seconds
Constraints:
- Must be implemented in Python
- Must store data in CSV format

6.0 Functional vs Non-Functional Specifications


Functional: Describes WHAT the system should do (e.g., generate report).
Non-Functional: Describes HOW the system performs (e.g., must load under 2
seconds).

7.0 Common Mistakes in Writing Specifications


- Being too vague
- Mixing design decisions into specifications
- Leaving out edge cases or error handling
- Ignoring user experience or usability

8.0 Exercises
1. Exercise 1: Identify Components
Given the statement:
“The payroll system should take employee hours worked and hourly rate, calculate
gross and net pay, and output a printable payslip. The system should run on Linux
servers and respond within 1 second.”

 Questions:
1. What is the input?
2. What is the output?
3. Name one functional and one non-functional requirement.

 Answers:
1. Employee hours worked, hourly rate
2. Printable payslip
3. Functional: Calculate gross and net pay; Non-functional: Respond within 1 second
2. Exercise 2: Short Answer
1. Define "program specification".
2. List any four elements that should be in a program specification.
3. What is the difference between assumptions and constraints?

 Sample Answers:
1. A document describing what a program should do, how it should behave, and
what it expects.
2. Inputs, Outputs, Functional Requirements, Constraints
3. Assumptions are expected conditions; constraints are restrictions or limitations.
Wk2 l1

Program specifications define what a computer program is intended to do. They can
be informal, like a blueprint or user manual, or formal, using mathematical or
programmatic terms. A program specification should clearly state the desired
outcome without dictating how it's achieved. This includes defining inputs, outputs,
and processing requirements.
Here's a breakdown of what program specifications entail:
Key Components:

 Input: Specifies the data the program will receive.

 Output: Describes the expected results or data the program will produce.
 Processing: Outlines the operations the program will perform on the input to
generate the output.
 Pre- and Post-conditions: Formal specifications often use these to define the
state of the program before and after execution.
 Error Handling: Specifies how the program should handle invalid inputs or
unexpected situations.
 Performance Requirements: May include speed, memory usage, or other
resource constraints.

Types of Specifications:

 Informal: Described in natural language, often with diagrams or examples.


 Formal: Uses mathematical notations or programming languages for precise
definitions.

Purpose of Program Specifications:

 Clarity: Ensures both developers and users understand what the program is
supposed to do.
 Testing and Validation: Allows for verification of the program's behavior against
its specifications.
 Communication: Acts as a contract between developers and clients.
 Maintenance and Evolution: Provides a reference point for future modifications
and improvements.
 These specifications are often publicly available and updated regularly

Software development lifecycle


SDLC, or Software Development Life Cycle, is a structured process that guides the
development of high-quality software from initial concept to final deployment and
maintenance. It's a framework that helps teams plan, design, build, test, and
maintain software systems in a systematic and efficient manner

Key phases in a typical SDLC:


1. Planning: Defining the project scope, objectives, and requirements.
2. Analysis: Gathering and analyzing user needs and system requirements.
3. Design: Creating the architecture, user interface, and technical specifications of
the software.
4. Development: Writing the code and building the software components.
5. Testing: Ensuring the software meets quality standards and functional
requirements through various testing methods.
6. Deployment: Releasing the software to the target environment.
7. Maintenance: Providing ongoing support, bug fixes, and updates to the
software.

Program development methodologies

Program / s/w development methodologies are structured approaches used to plan,


design, develop, and test software. They provide a framework for managing the
software development lifecycle, ensuring projects are completed efficiently and
effectively. Key methodologies include Agile, Waterfall, DevOps, and Scrum, each
offering unique benefits for different project types and team structures.
Common Software Development Methodologies:

Agile:
An iterative and incremental approach that emphasizes flexibility, collaboration, and
customer feedback throughout the development process. It's well-suited for projects
with evolving requirements or where rapid iteration is desired.

Waterfall:
A sequential, linear approach where each phase of development (requirements,
design, implementation, testing, deployment) must be completed before the next
begins. It's best suited for projects with well-defined requirements and a stable
scope.
DevOps:
Focuses on integrating development and operations teams to streamline the
software delivery pipeline. It emphasizes automation, continuous integration, and
continuous delivery, leading to faster release cycles and improved collaboration.
Scrum:
An Agile framework that uses short, time-boxed iterations called sprints to deliver
working software increments. It relies on roles like Scrum Master and Product
Owner, and artifacts like the sprint backlog.

Extreme Programming (XP):


An Agile methodology that emphasizes best practices like test-driven development,
pair programming, and continuous integration.
Rapid Application Development (RAD):
A methodology that prioritizes rapid prototyping and iterative development to
quickly deliver functional software. It is particularly useful when user feedback is
critical.
Feature-Driven Development (FDD):
A methodology that focuses on developing software in short, iterative cycles based
on features. It emphasizes domain object modeling and frequent releases.
Crystal methodology

Crystal methodology is one of the most lightweight and flexible approaches to


develop software. Moreover, it is made up of several agile processes, including Clear,
Crystal Yellow, Crystal Orange, and other uniquely characterized methods.

To conclude, the Crystal family focuses on the realization that each project has
unique characteristics. Hence, the policies and practices must be custom-tailored to
accommodate these features.
Lean Development:
A methodology that focuses on minimizing waste and maximizing value in the
development process. It emphasizes continuous improvement and eliminating non-
value-added activities.
Spiral Model:
An iterative and risk-driven approach that combines elements of prototyping and
waterfall methodologies. It is particularly useful for large, complex projects with high
levels of risk.
Rational Unified Process (RUP):
A software development process framework that provides a structured approach to
building and deploying software. It is based on best practices and includes a set of
best practices.
Dynamic Systems Development Method (DSDM):
An Agile methodology that focuses on delivering business value through iterative
development and user involvement.

Choosing the Right Methodology:


Selecting the appropriate methodology depends on various factors, including:
Project Size and Complexity:
Agile and Scrum may be suitable for smaller, less complex projects, while
Waterfall or Spiral may be better for large, complex projects.
Project Requirements:
If requirements are well-defined and stable, Waterfall may be a good choice.
If requirements are likely to change, Agile or RAD may be more appropriate.
Team Structure and Experience:
Agile and Scrum require a collaborative and self-organizing team. Waterfall may be
more suitable for teams with less experience.
Time and Budget Constraints:
Agile and RAD can help accelerate development and deliver value quickly.
Risk Tolerance:
The Spiral model is designed to manage risk throughout the development
process.
Wk 2, l2: Program Development Life Cycle (PDLC)

The Program Development Life Cycle (PDLC) is a process used in software


engineering to manage the development of software programs. The PDLC is similar
to the Software Development Life Cycle (SDLC) but is applied at a higher level, to
manage the development of multiple software programs or projects. This article
focuses on discussing PDLC in detail.

What is PDLC?

The PDLC is an iterative process that allows for feedback and adjustments to be
made at each phase, to ensure that the final product meets the needs of the
stakeholders and is of high quality.

 Program Development Life Cycle (PDLC) is a systematic way of developing


quality software.
 It provides an organized plan for breaking down the task of program
development into manageable chunks, each of which must be completed
before moving on to the next phase.

Diffrence

Aspect PDLC SDLC


Narrow: focused on one Broad: manages entire
Scope
program system/software project
User Individual developers Project managers, teams
Code, logic, testing of a Planning, risk management,
Focus
single unit integration, maintenance

Phases of PDLC

1. Planning: In this phase, the goals and objectives of the program are defined,
and a plan is developed to achieve them. This includes identifying the
resources required and determining the budget and schedule for the
program.
2. Analysis: In this phase, the requirements for the program are defined and
analyzed. This includes identifying the stakeholders, their needs and
expectations, and determining the functional and non-functional
requirements for the program.
3. Design: In this phase, the program's architecture and design are developed.
This includes creating a detailed design of the program's components and
interfaces, as well as determining how the program will be tested and
deployed.
4. Implementation: In this phase, the program is developed and coded. This
includes writing the program's source code and creating any necessary
documentation.
5. Testing: In this phase, the program is tested to ensure that it meets the
requirements and is free of defects.
6. Deployment: In this phase, the program is deployed and made available to
users.
7. Maintenance: After the deployment, the program is maintained by fixing any
bugs or errors that are found and updating the program to meet changing
requirements.

Steps in PDLC

The program development process is divided into the steps discussed below:

1. Defining the Problem

The first step is to define the problem. In major software projects, this is a job for
system analyst, who provides the results of their work to programmers in the form
of a program specification. The program specification defines the data used in
program, the processing that should take place while finding a solution, the format
of the output and the user interface.

2. Designing the Program

Program design starts by focusing on the main goal that the program is trying to
achieve and then breaking the program into manageable components, each of which
contributes to this goal. This approach of program design is called top-bottom
program design or modular programming. The first step involve identifying main
routine, which is the one of program's major activity. From that point, programmers
try to divide the various components of the main routine into smaller parts called
modules. For each module, programmer draws a conceptual plan using an
appropriate program design tool to visualize how the module will do its assign job.
Program Design Tools: The various program design tools are described below:

 Structure Charts: A structure chart, also called Hierarchy chart, show top-
down design of program. Each box in the structure chart indicates a task that
program must accomplish. The Top module, called the Main module or
Control module. For example:

 Algorithms: An algorithm is a step-by-step description of how to arrive at a


solution in the most easiest way. Algorithms are not restricted to computer
world only. In fact, we use them in everyday life.
 Flowcharts: A flowchart is a diagram that shows the logic of the program. For

example:
 Decision tables: A Decision table is a special kind of table, which is divided
into four parts by a pair of horizontal and vertical lines.

Conditions Rule 1 Rule 2 Rule 3 Rule 4 Rule 5


Username is
Yes Yes No No –
correct
Password is
Yes No Yes No –
correct
Guest Access
No No No No Yes
Requested

Actions
Grant full
✓ – – – –
access
Grant limited
– – – – ✓
access
Show error
– ✓ ✓ ✓ –
message
 Pseudocode: A pseudocode is another tool to describe the way to arrive at a
solution. They are different from algorithm by the fact that they are
expressed in program language like constructs.

Start

Prompt user: "Enter a number"

Read number

IF number <= 1 THEN

Display "The number is not prime"

ELSE

Set isPrime ← true

FOR i ← 2 TO number - 1 DO

IF number MOD i == 0 THEN

Set isPrime ← false

BREAK

END IF

END FOR

IF isPrime == true THEN

Display "The number is prime"

ELSE

Display "The number is not prime"

END IF

END IF
End

Start

Prompt user: "Enter a number"

Read number

IF number MOD 2 == 0 THEN

Display "The number is even"

ELSE

Display "The number is odd"

END IF

End

3. Coding the Program

Coding the program means translating an algorithm into specific programming


language. The technique of programming using only well defined control structures
is known as Structured programming. Programmer must follow the language rules,
violation of any rule causes error. These errors must be eliminated before going to
the next step.

4. Testing and Debugging the Program

After removal of syntax errors, the program will execute. However, the output of the
program may not be correct. This is because of logical error in the program. A logical
error is a mistake that the programmer made while designing the solution to a
problem. So the programmer must find and correct logical errors by carefully
examining the program output using Test data. Syntax error and Logical error are
collectively known as Bugs. The process of identifying errors and eliminating them is
known as Debugging.

5. Documenting the Program


After testing, the software project is almost complete. The structure charts,
pseudocodes, flowcharts and decision tables developed during the design phase
become documentation for others who are associated with the software project.
This phase ends by writing a manual that provides an overview of the program's
functionality, tutorials for the beginner, in-depth explanations of major program
features, reference documentation of all program commands and a thorough
description of the error messages generated by the program.

6. Deploying and Maintaining the Program

In the final phase, the program is deployed (installed) at the user's site. Here also,
the program is kept under watch till the user gives a green signal to it. Even after the
software is completed, it needs to be maintained and evaluated regularly. In
software maintenance, the programming team fixes program errors and updates the
software.

Benefits of PDLC

Provides a structured approach: PDLC provides a structured approach to developing


software, which helps to ensure that the program is developed in a logical and
organized way.

1. Facilitates communication: PDLC helps to facilitate communication between


different stakeholders, such as developers, project managers, and customers.
2. Identifies and manages risks: PDLC helps to identify and manage potential
risks during the development of the program, allowing for proactive
measures to be taken to mitigate them.
3. Improves quality: PDLC helps to improve the quality of the final product by
providing a systematic approach to testing and quality assurance.
4. Increases efficiency: By following a PDLC, the development process becomes
more efficient as it allows for better planning and organization.

Limitations of PDLC

 Can be time-consuming: Following a strict PDLC can be time-consuming, and


may delay the development of the program.
 Can be inflexible: The rigid structure of PDLC may not be suitable for all types
of software development projects, and may limit the ability to incorporate
changes or new ideas.
 Can be costly: Implementing a PDLC may require additional resources and
budget, which can be costly for organizations.
 Can be complex: PDLC can be complex, and may require a certain level of
expertise and knowledge to implement effectively.
 May not be suitable for smaller projects: PDLC may not be suitable for
smaller projects as it can be an overkill and would not be cost-effective.
WK3 L1: Styles of programming
Programming styles, also known as programming paradigms, are fundamental
approaches to structuring and organizing code. These styles dictate how a program is
designed and how its instructions are executed. Some prominent programming
styles include imperative, declarative, object-oriented, functional, and procedural.
This video explains the basics of programming styles and paradigms:

1. Imperative Programming:
let numbers = [1, 2, 3, 4];
let doubled = [];

for (let i = 0; i < [Link]; i++) {


[Link](numbers[i] * 2);
}

[Link](doubled); // Output: [2, 4, 6, 8]

 Imperative programming focuses on explicitly stating the steps the computer


must take to achieve a desired outcome.
 It involves directly manipulating the program's state through statements that
change the values of variables.

· Languages like C, C++, Java, Python, and JavaScript are often associated with
imperative programming.
· Examples include using loops (for, while) to iterate and modify variables, or
directly assigning values to memory locations.
· This style is characterized by its step-by-step approach, where the programmer
defines the sequence of operations the computer should follow.
2. Declarative Programming:
let numbers = [1, 2, 3, 4];
let doubled = [Link](num => num * 2);

[Link](doubled); // Output: [2, 4, 6, 8]

SELECT name
FROM employees
WHERE department = 'Sales' AND salary > 50000;

 Declarative programming emphasizes describing what the program should


achieve rather than how to achieve it.
 It focuses on expressing the logic of computation without specifying the exact
control flow.

· Languages like SQL, HTML, and functional programming languages often employ
declarative paradigms.
· SQL queries, for example, declare the desired result set without explicitly stating
the steps for retrieving data.
· Declarative programming can make code more concise and easier to understand,
especially for complex logic.

3. Object-Oriented Programming (OOP):

OOPs refers to languages that use objects in programming. Object-oriented


programming aims to implement real-world entities like inheritance, hiding,
polymorphism, etc in programming. The main aim of OOP is to bind together the data
and the functions that operate on them so that no other part of the code can access this
data except that function.

OOPs Concepts:

 Class
 Objects
 Data Abstraction
 Encapsulation
 Inheritance
 Polymorphism
 Dynamic Binding
 Message Passing

1. Class:

A class is a user-defined data type. It consists of data members and member functions,
which can be accessed and used by creating an instance of that class. It represents the
set of properties or methods that are common to all objects of one type. A class is like
a blueprint for an object.

For Example: Consider the Class of Cars. There may be many cars with different
names and brands but all of them will share some common properties like all of them
will have 4 wheels, Speed Limit, Mileage range, etc. So here, Car is the class, and
wheels, speed limits, mileage are their properties.

2. Object:

It is a basic unit of Object-Oriented Programming and represents the real-life entities.


An Object is an instance of a Class. When a class is defined, no memory is allocated
but when it is instantiated (i.e. an object is created) memory is allocated. An object
has an identity, state, and behavior. Each object contains data and code to manipulate
the data. Objects can interact without having to know details of each other’s data or
code, it is sufficient to know the type of message accepted and type of response
returned by the objects.

For example “Dog” is a real-life Object, which has some characteristics like color,
Breed, Bark, Sleep, and Eats.
Object

3. Data Abstraction:

Data abstraction is one of the most essential and important features of object-oriented
programming. Data abstraction refers to providing only essential information about
the data to the outside world, hiding the background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the speed of the car or applying brakes will stop
the car, but he does not know about how on pressing the accelerator the speed is
increasing, he does not know about the inner mechanism of the car or the
implementation of the accelerator, brakes, etc in the car. This is what abstraction is.

4. Encapsulation:

Encapsulation is defined as the wrapping up of data under a single unit. It is the


mechanism that binds together code and the data it manipulates. In Encapsulation, the
variables or data of a class are hidden from any other class and can be accessed only
through any member function of their class in which they are declared. As in
encapsulation, the data in a class is hidden from other classes, so it is also known as
data-hiding.
Consider a real-life example of encapsulation, in a company, there are different
sections like the accounts section, finance section, sales section, etc. The finance
section handles all the financial transactions and keeps records of all the data related
to finance. Similarly, the sales section handles all the sales-related activities and keeps
records of all the sales. Now there may arise a situation when for some reason an
official from the finance section needs all the data about sales in a particular month. In
this case, he is not allowed to directly access the data of the sales section. He will first
have to contact some other officer in the sales section and then request him to give the
particular data. This is what encapsulation is. Here the data of the sales section and
the employees that can manipulate them are wrapped under a single name “sales
section”.

5. Inheritance:

Inheritance is an important pillar of OOP(Object-Oriented Programming). The


capability of a class to derive properties and characteristics from another class is
called Inheritance. When we write a class, we inherit properties from other classes. So
when we create a class, we do not need to write all the properties and functions again
and again, as these can be inherited from another class that possesses it. Inheritance
allows the user to reuse the code whenever possible and reduce its redundancy.

6. Polymorphism:

The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. For
example, A person at the same time can have different characteristics. Like a man at
the same time is a father, a husband, an employee. So the same person posses
different behavior in different situations. This is called polymorphism.
Polymorphisn ==> poly, morphs - form

7. Dynamic Binding:

In dynamic binding, the code to be executed in response to the function call is decided
at runtime. Dynamic binding means that the code associated with a given procedure
call is not known until the time of the call at run time. Dynamic Method Binding One
of the main advantages of inheritance is that some derived class D has all the
members of its base class B. Once D is not hiding any of the public members of B,
then an object of D can represent B in any context where a B could be used. This
feature is known as subtype polymorphism.

8. Message Passing:

It is a form of communication used in object-oriented programming as well as parallel


programming. Objects communicate with one another by sending and receiving
information to each other. A message for an object is a request for execution of a
procedure and therefore will invoke a function in the receiving object that generates
the desired results. Message passing involves specifying the name of the object, the
name of the function, and the information to be sent.

# ===== OOP CONCEPTS DEMONSTRATION =====

# --- CLASS ---

# A blueprint for creating objects (defines properties and behaviors)

class Vehicle:

# Class variable (shared by all instances)

vehicle_count = 0
# Constructor (special method called when object is created)

def __init__(self, brand, model):

# --- ENCAPSULATION ---

# Protecting data by making it private (name mangling with __)

self.__brand = brand # Private attribute

self.__model = model # Private attribute

self.__mileage = 0 # Private attribute with default value

Vehicle.vehicle_count += 1

# --- DATA ABSTRACTION ---

# Exposing only essential features (public methods) while hiding implementation

def get_details(self):

return f"{self.__brand} {self.__model}"

def get_mileage(self):

return self.__mileage

def drive(self, distance):

if distance > 0:

self.__mileage += distance

return f"Driven {distance} km. Total mileage: {self.__mileage}"

return "Invalid distance"

# --- MESSAGE PASSING ---

# Objects communicate by sending messages (method calls)

def send_service_reminder(self):

if self.__mileage >= 10000:

return f"Service needed for {self.get_details()}"

return f"{self.get_details()} is still within service limit"


# --- INHERITANCE ---

# Creating a new class (Car) that inherits from Vehicle

class Car(Vehicle):

def __init__(self, brand, model, fuel_type):

super().__init__(brand, model) # Call parent class constructor

self.__fuel_type = fuel_type # Child class specific attribute

# --- POLYMORPHISM ---

# Same method name as parent but different implementation (Method Overriding)

def get_details(self):

return f"{super().get_details()} (Fuel: {self.__fuel_type})"

# Child class specific method

def refuel(self):

return f"Refueling {self.__fuel_type} for {self.get_details()}"

# --- DYNAMIC BINDING ---

# The actual method called is determined at runtime based on object type

def display_vehicle_info(vehicle):

print(vehicle.get_details()) # Calls appropriate get_details() based on object type

# ===== DEMONSTRATION =====

# --- OBJECTS ---

# Creating instances (objects) of the classes

vehicle1 = Vehicle("Toyota", "Hiace")

car1 = Car("Tesla", "Model S", "Electric")

# Using objects
print([Link](5000)) # Output: Driven 5000 km. Total mileage: 5000

print([Link](300)) # Output: Driven 300 km. Total mileage: 300

print(vehicle1.send_service_reminder()) # Message passing example

# --- ENCAPSULATION DEMO ---

# print(vehicle1.__brand) # This would fail - attribute is private

print(vehicle1.get_details()) # Proper way to access via public method

# --- INHERITANCE & POLYMORPHISM DEMO ---

print(vehicle1.get_details()) # Calls Vehicle's get_details()

print(car1.get_details()) # Calls Car's overridden get_details()

# --- DYNAMIC BINDING DEMO ---

display_vehicle_info(vehicle1) # Output: Toyota Hiace

display_vehicle_info(car1) # Output: Tesla Model S (Fuel: Electric)

# --- CLASS VARIABLE ACCESS ---

print(f"Total vehicles created: {Vehicle.vehicle_count}") # Output: 2

Why do we need object-oriented programming

 To make the development and maintenance of projects more effortless.


 To provide the feature of data hiding that is good for security concerns.
 We can solve real-world problems if we are using object-oriented programming.
 It ensures code reusability.
 It lets us write generic code: which will work with a range of data, so we don't have to write
basic stuff over and over again.

4. Functional Programming:

Functional programming is a programming paradigm in which we try to bind


everything in pure mathematical functions. It is a declarative style. Its main focus is
on “what to solve,” in contrast to an imperative style, where the main focus is on
“how to solve.” It uses expressions instead of statements. An expression is evaluated
to produce a value, whereas a statement is executed to assign variables. Those
functions have some special features discussed below.

Programming Languages that support functional programming: Haskell,


JavaScript, Python, Scala, Erlang, Lisp, ML, Clojure, OCaml, Common Lisp, Racket.
Concepts of Functional Programming

 Pure functions
 Recursion
 Referential transparency
 Functions are First-Class and can be Higher-Order
 Variables are Immutable

Pure Functions

These functions have two main properties. First, they always produce the same output
for same arguments irrespective of anything else.
Secondly, they have no side-effects i.e. they do not modify any arguments or
local/global variables or input/output streams.
Later property is called immutability. The pure function's only result is the value it
returns. They are deterministic.
Programs done using functional programming are easy to debug because pure
functions have no side effects or hidden I/O. Pure functions also make it easier to
write parallel/concurrent applications. When the code is written in this style, a smart
compiler can do many things - it can parallelize the instructions, wait to evaluate
results when needing them, and memorize the results since the results never change as
long as the input doesn't change.

Example of the Pure Function

sum(x, y) // sum is function taking x and y as arguments


return x + y // sum is returning sum of x and y without hanging
them
Recursion

There are no “for” or “while” loop in functional languages. Iteration in functional


languages is implemented through recursion. Recursive functions repeatedly call
themselves, until it reaches the base case.
example of the recursive function:

fib(n)
if (n <= 1)
return 1;
else
return fib(n - 1) + fib(n - 2);
Referential Transparency

In functional programs variables once defined do not change their value throughout
the program. Functional programs do not have assignment statements. If we have to
store some value, we define new variables instead. This eliminates any chances of
side effects because any variable can be replaced with its actual value at any point of
execution. State of any variable is constant at any instant.

Example:

x = x + 1 // this changes the value assigned to the variable x.


// So the expression is not referentially transparent.
Functions are First-Class and can be Higher-Order

First-class functions are treated as first-class variable. The first class variables can be
passed to functions as parameter, can be returned from functions or stored in data
structures. Higher order functions are the functions that take other functions as
arguments and they can also return functions.

Example:

show_output(f) // function show_output is declared taking


argument f
// which are another function
f(); // calling passed function

print_gfg() // declaring another function


print("hello gfg");

show_output(print_gfg) // passing function in another function


Variables are Immutable

In functional programming, we can’t modify a variable after it’s been initialized. We


can create new variables – but we can’t modify existing variables, and this really
helps to maintain state throughout the runtime of a program. Once we create a
variable and set its value, we can have full confidence knowing that the value of that
variable will never change.

# ===== FUNCTIONAL PROGRAMMING IN PYTHON =====

# 1. PURE FUNCTIONS (no side effects, same input → same output)

def pure_multiply(a, b):

return a * b # No side effects, only depends on inputs

# Impure version for contrast

GLOBAL_STATE = 2

def impure_multiply(a):
return a * GLOBAL_STATE # Depends on external state

# 2. RECURSION (instead of loops)

def recursive_sum(numbers):

if not numbers: # Base case

return 0

return numbers[0] + recursive_sum(numbers[1:]) # Recursive case

# 3. REFERENTIAL TRANSPARENCY

# Can replace expression with its value without changing behavior

def rt_example(x):

return pure_multiply(x, x) + pure_multiply(x, x) # Can be 2*(x*x)

# 4. FIRST-CLASS FUNCTIONS (treated like any other variable)

def greet(name):

return f"Hello, {name}"

def apply_func(func, arg):

return func(arg) # Function as argument

# 5. HIGHER-ORDER FUNCTIONS (take/return functions)

def create_adder(n):

def adder(x):

return x + n

return adder # Returns a function

# 6. IMMUTABILITY (variables don't change after creation)

from dataclasses import dataclass

@dataclass(frozen=True)

class ImmutablePoint:
x: int

y: int

# ===== DEMONSTRATION =====

if __name__ == "__main__":

# 1. Pure functions

print(pure_multiply(3, 4)) # Always 12

print(impure_multiply(3)) # Depends on GLOBAL_STATE

# 2. Recursion

print(recursive_sum([1, 2, 3])) # 6

# 3. Referential transparency

x=5

print(rt_example(x)) # 50

print(2 * (x * x)) # Same result

# 4. First-class functions

greeting = greet # Assign function to variable

print(apply_func(greeting, "Alice")) # "Hello, Alice"

# 5. Higher-order functions

add_five = create_adder(5)

print(add_five(10)) # 15

# 6. Immutability

point = ImmutablePoint(3, 4)

# point.x = 5 # Would raise FrozenInstanceError

print(point)

Advantages of Functional Programming


 Pure functions are easier to understand because they don’t change any states and depend
only on the input given to them. Whatever output they produce is the return value they give.
Their function signature gives all the information about them i.e. their return type and their
arguments.
 The ability of functional programming languages to treat functions as values and pass them
to functions as parameters make the code more readable and easily understandable.
 Testing and debugging is easier. Since pure functions take only arguments and produce
output, they don’t produce any changes don’t take input or produce some hidden output.
They use immutable values, so it becomes easier to check some problems in programs
written uses pure functions.
 It is used to implement concurrency/parallelism because pure functions don’t change
variables or any other data outside of it.
 It adopts lazy evaluation which avoids repeated evaluation because the value is evaluated
and stored only when it is needed.
 Parallel Safety: Immutability prevents race conditions
 Expressiveness: Higher-order functions enable powerful abstractions

Disadvantages of Functional Programming

 Sometimes writing pure functions can reduce the readability of code.


 Writing programs in recursive style instead of using loops can be bit intimidating.
 Writing pure functions are easy but combining them with the rest of the application and I/O
operations is a difficult task.
 Immutable values and recursion can lead to decrease in performance.

5. Procedural Programming:

Procedural Language is also known as 3GL which means third generation language. It
is a type of programming language that follows a procedure; set of commands or
guidelines that must be followed for smooth execution of the program. It works on
step by step basis. It requires the user to tell not only What to do but also How to do
it. Its basic idea is to have a program specify the sequence of steps that implements a
particular algorithm. Hence, Procedural languages are based on algorithms.

In this developers use variables, loops, and functions to create a program performing a
specific task which does calculations and displays a desired output.

It follows a top-down approach. It is carried out in a fixed sequence with a start and
end point. The entire program is divided into functions and its main focus is on
functions only. The program’s code executes linearly with logical steps. In this, the
code is written first and executed with some conditions. The procedure calls to decide
the conditions.

There are no data-hiding features in procedural language. It is command command-


driven language. It is operated by means of commands keyed in by the user or issued
by the program. In procedural language, both iterative and recursive calls are used. It
works through the state of the machine. It returns only restricted data types and
allowed values. It is highly efficient despite the fact the size of the program is quite
large and is not suitable for critical applications with complex code. It takes a lot of
time but it needs very less memory.

In procedural language, no access specifiers are used. For eg: In structure all the
members are public.

Features of Procedural Programming Language

 Local Variables: A local variable is a variable that is limited to a specific part of a program and
is announced locally in the procedural language, local on the specific function, as the only
place to access it.
 Global Variables: A global variable is a variable that is declared outside a function and is able
to be accessed by any function of the program. It is also known as the opposite of the local
variable.
 Modularity: The practice of splitting a program into modules or functions so that each
function is devoted to a certain task is referred to as modularity.
 Pre-Defined Functions: Pre-defined functions are the amplification of functions which are
already defined by the user and don't need the programmer to define them again. A built-in
function is already defined in the system libraries, so it is also called a library function.
 Parameter Passing: Parameter passing is a mechanism that allows the transfer of data
between different functions of the program. The parameters are passed between the called
and the calling function, thus allowing data exchange.

Types of Procedural Language

 FORTRAN: FORTRAN is a short form of FORmula TRANslation. It is an application in critical


engineering calculations and high-performance computing.
 C: It is a middle-level language. It is basically designed to write System software and requires
advanced programming skills to read and write the desired code.
 BASIC: BASIC is the short form of Beginner All Purpose Symbolic Instruction Code. It is a high-
level programming language that is simple to use.
 Pascal: Pascal is easy to learn. It produces transparent, efficient and reliable programs.
 ALGOL: ALGOL stands for Algorithmic Language. It is mostly used for scientific calculations.
 COBOL: COBOL stands for COmmon Business Oriented Language. It is easy to read, write and
understand. It is basically designed for Business Applications.
 Java: Java is a platform independent language. It generates a machine code from source
code with the help of Just In Time compiler.

# ===== PROCEDURAL PROGRAMMING DEMONSTRATION =====

# --- GLOBAL VARIABLE ---

# Accessible to all functions in the program

global_counter = 0

# --- PRE-DEFINED (BUILT-IN) FUNCTION ---

# Python comes with many pre-defined functions like len(), print(), etc.

def demonstrate_builtins():
numbers = [1, 2, 3, 4, 5]

length = len(numbers) # Using pre-defined len() function

total = sum(numbers) # Using pre-defined sum() function

print(f"List has {length} items totaling {total}") # print() is also pre-defined

# --- MODULARITY ---

# Breaking program into small, focused functions

def calculate_area(length, width):

"""Calculates rectangle area"""

return length * width

def calculate_perimeter(length, width):

"""Calculates rectangle perimeter"""

return 2 * (length + width)

# --- PARAMETER PASSING ---

# Demonstrating different parameter passing approaches

def update_counter(count):

"""Receives parameter by value (for immutable types)"""

count += 1

print(f"Local count value: {count}")

def update_list(items):

"""Receives parameter by reference (for mutable types)"""

[Link]("new item")

print(f"Updated list inside function: {items}")

# --- LOCAL VARIABLES ---

def process_data():

"""Demonstrates local variables"""

local_value = 100 # Local variable - only exists in this function

print(f"Local value: {local_value}")


# Uncommenting this would cause an error:

# print(another_local) # another_local not defined yet

another_local = 200 # Another local variable

return local_value + another_local

# --- GLOBAL vs LOCAL ---

def demonstrate_scope():

"""Shows interaction between global and local variables"""

local_var = 10 # Local variable

print(f"Local variable: {local_var}")

print(f"Global variable: {global_counter}") # Accessing global variable

# Uncommenting this would cause an error:

# print(local_value) # Can't access local_value from process_data()

# --- MAIN PROGRAM ---

def main():

print("=== Procedural Programming Demo ===")

# Using pre-defined functions

demonstrate_builtins()

# Demonstrating modularity

length, width = 5, 3

print(f"Area: {calculate_area(length, width)}")

print(f"Perimeter: {calculate_perimeter(length, width)}")

# Parameter passing examples

num = 10

print(f"Original value: {num}")

update_counter(num) # Pass by value (immutable)

print(f"After function call: {num}") # Original unchanged


my_list = [1, 2, 3]

print(f"Original list: {my_list}")

update_list(my_list) # Pass by reference (mutable)

print(f"After function call: {my_list}") # Original changed

# Local variables demonstration

result = process_data()

print(f"Process result: {result}")

# Scope demonstration

demonstrate_scope()

# Modifying global variable

global global_counter # Need to declare we're using global

global_counter += 1

print(f"Updated global counter: {global_counter}")

if __name__ == "__main__":

main()

Advantages of Procedural Language

 Easy to Understand: Procedural programming stops the programmer from writing more lines
of code and depicts the code in very simple steps that can be easily followed by the
programmer to understand it.
 Reusability: It paves way for easy code reusability.
 Modularity: It divides the programs into modules or functions and these functions use
different parts of the memory.
 Simplification: It simplifies the algorithm and makes it understandable by the programmer.
 Top-Down Approach: The program flows in linear direction.
 Versatile: Developers can use Procedural language for most basic programming projects.

Disadvantages of Procedural Language

 One can't solve real world problem.


 Encapsulation, Inheritance, Abstraction etc can't be performed.
 It is less secure as there is no security of data.
 Its semantics are tough and difficult to understand.
 It returns only restricted data types and allowed values.

In summary: Programming styles provide different ways to structure and organize


code, each with its own strengths and weaknesses. Understanding these styles
allows developers to choose the most appropriate approach for a given task and to
write more effective and maintainable code
Wk3 L2: Program Design Basics
Program design basics involve understanding the problem, creating a solution, and
then translating that solution into code. This process includes understanding the
program's purpose, designing the solution using tools like flowcharts and
pseudocode, and then writing, testing, and debugging the code. Good program
design leads to maintainable, efficient, and understandable code.
This video provides an overview of the system design process:

Key Steps in Program Design:


1. Understanding the Problem:
Clearly define what the program needs to achieve. This involves identifying
the problem, understanding the stakeholders, and researching potential
solutions.
2. Designing the Solution:

· Flowcharts: Use visual diagrams to represent the program's logic and workflow.

· Pseudocode: Write a high-level, informal description of the code in plain language before writing
actual code.

3. Writing and Testing the Code:


· Translate the pseudocode into a specific programming language. Thoroughly test
the code to identify and fix any errors (debugging).
4. Iteration and Improvement:
· Refine and improve the program based on testing and user feedback.

Fundamental Principles of Program Design:


Modularity: Breaking down the program into smaller, manageable modules or
components.
Abstraction: Hiding complex implementation details and exposing only necessary
information.
Encapsulation: Bundling data and the methods that operate on that data within a
single unit.
Separation of Concerns: Dividing the program into distinct parts, each responsible
for a specific aspect of the overall functionality.
SOLID Principles: A set of five design principles (Single Responsibility, Open/Closed,
Liskov Substitution, Interface Segregation, and Dependency Inversion) for building
robust and maintainable applications.

1. Single Responsibility Principle (SRP): "A class should have only one job."
→ Each component (class/function) should be responsible for one specific task. If it
handles multiple responsibilities, it becomes harder to maintain and modify.
Example Analogy: A chef should focus on cooking, not serving food or washing
dishes.
2. Open/Closed Principle (OCP)
"Software should be open for extension but closed for modification."
→ Add new features without changing existing code.
Example Analogy: A USB port allows new devices (e.g., keyboards, flash drives) to
work without modifying the port itself.
3. Liskov Substitution Principle (LSP)
"Subclasses must be substitutable for their parent classes."
→ Child classes should not break the expected behavior of the parent class.
Example Analogy: A Penguin is a bird, but if your code expects all birds to fly(),
forcing a penguin to inherit from Bird violates LSP.
Key Rules:
Child classes must fully implement parent class methods.
They shouldn’t strengthen preconditions (e.g., add restrictions).
They shouldn’t weaken postconditions (e.g., return unexpected types).

4. Interface Segregation Principle (ISP)


"Clients shouldn’t depend on interfaces they don’t use."
→ Prefer small, focused interfaces over large, monolithic ones.
Example Analogy: A Swiss Army knife has many tools, but you shouldn’t force a user
to depend on the scissors if they only need the screwdriver.

5. Dependency Inversion Principle (DIP)


"Depend on abstractions, not concrete implementations."
→ High-level modules (e.g., business logic) should not depend on low-level details
(e.g., databases, APIs).
Example Analogy: A light switch shouldn’t care whether it controls an LED bulb or an
incandescent one—it depends on the abstract idea of a "switchable device."
Use interfaces to define contracts.

Software Design Elements:

 Architecture: The overall structure and organization of the system.


 Modules: Reusable components that perform specific tasks.
 Components: Building blocks of the system that provide specific functionality.
 Interfaces: Define how different parts of the system interact with each other.
 Data: The information that the program processes.

Benefits of good program design:

 Improved code quality: Leads to more reliable and efficient code.


 Easier maintenance: Modular and well-structured code is easier to understand, modify, and
debug.
 Increased reusability: Modular components can be reused in other parts of the program or
in different projects.
 Reduced development time: Well-defined design can streamline the coding process.
Lucid charts demos >>>>>>>>>>>>>>>>>>>>> practicals
Wk 4, l1: Programming language generations
Programming languages are categorized into five generations, each representing a
significant advancement in how humans interact with computers. These generations
are: First Generation (1GL), Second Generation (2GL), Third Generation (3GL), Fourth
Generation (4GL), and Fifth Generation (5GL).
Here's a breakdown of each generation:
1. First Generation Languages (1GL): Machine Code
Characteristics: Directly executable by the computer's hardware, using binary code
(sequences of 0s and 1s). Extremely low-level and difficult for humans to program.
Examples: No specific examples, as 1GL is specific to the computer's architecture.
2. Second Generation Languages (2GL): Assembly Language
Characteristics: Use mnemonics (short, symbolic codes) to represent machine
instructions, making them slightly more readable and easier to program than 1GL.
Still requires translation into machine code by an assembler.
· Examples: Assembly languages for various processors (e.g., MASM, NASM).

3. Third Generation Languages (3GL): High-Level Languages


Characteristics: Higher-level languages that abstract away many of the hardware
details. Use more human-readable syntax and structures, allowing programmers to
focus on logic rather than specific machine operations.
· Examples: C, Java, Fortran, COBOL, Pascal, BASIC.

4. Fourth Generation Languages (4GL): Very High-Level Languages


Characteristics: Even higher level than 3GLs, often domain-specific (e.g., for
database management or report generation). Focus on specifying what needs to be
done rather than how, leading to faster development and easier maintenance.
· Examples: SQL, MATLAB, SAS, Visual Basic.

5. Fifth Generation Languages (5GL): Logic Programming and AI


Characteristics: Focus on problem-solving using constraints and rules. Used in
artificial intelligence and expert systems. Often involve visual programming
interfaces and focus on knowledge representation.
Examples: Prolog, OPS5.

Key Trends:
Increasing Abstraction: Each generation moved further away from the underlying
hardware, making programming more accessible and efficient.
· Domain Specialization: 4GLs and beyond tend to be specialized for specific tasks
or domains.
· Focus on Human Readability: Languages have evolved to be more like natural
language, making them easier to understand and use.
· AI and Machine Learning: 5GLs are heavily involved in the development of AI and
machine learning applications.

You might also like