P2 Theory

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

P2 Theory

Making Code Legible

• Indentation: This involves adding spaces or tabs at the beginning of code lines to
visually represent the structure of the code, showing how code blocks are related to
each other.
• Blank Lines: These are used to separate sections of code, making it clear where one
section ends and another begins. It helps in visually organizing code for better
readability.
• Capitalization of Keywords: In programming languages where keywords are case-
sensitive, the correct capitalization is essential. Even in languages where it's not,
following the convention can help distinguish keywords from variables.
Making Code Legible

• Sensible Variable Names: Choosing clear and descriptive names for variables
makes it easier for others (and yourself) to understand what the variable
represents without needing additional comments. For instance, using
employeeSalary instead of es or temp.
• Comments: These are annotations in the source code that explain what the code is
doing. Comments are not executed as part of the program. They are crucial for
maintaining code and making it understandable to others.
• Prettyprint: This refers to the stylized display of source code, where the code is
printed with visual styling such as syntax highlighting, proper indentation, and
color-coded elements based on the language syntax to make it more readable.
Identifiers

• Constant:
⚬ A constant is an identifier whose value is fixed and not changeable once
defined. It represents a value that remains the same throughout the execution
of a program.
⚬ Example: CONSTANT PI = 3.14159 (In many programming languages, the
keyword const is used to define a constant, like the mathematical constant PI.)
• Variable:
⚬ A variable is an identifier used for a storage location in memory that can hold
different values during the execution of a program. Variables are mutable,
meaning their value can be changed.
⚬ Example: int count = 0 (Here, count is a variable of type int which can store
integer values, initially set to 0.)
Identifiers

• Arrays:
⚬ An array is an identifier for a collection of items, where each item is of the same
data type. The items in an array are stored in contiguous memory locations and
can be accessed using an index.
⚬ Example: int numbers[5] = {1, 2, 3, 4, 5} (This declares an array named numbers
with 5 integer elements.)
Verifying Data

• It's the process of checking that data has not changed during transfer or input to a
computer. The aim is to ensure that data is copied or entered exactly as intended.
• Methods include:
⚬ Double Entry: Requiring data to be entered twice and comparing the two entries
for discrepancies.
⚬ Parity Check: Using parity bits to check whether data has been altered during
transmission.
⚬ Checksum: Calculating a value based on the data that can be used to detect
errors after transmission or storage.
• Example of context: When transferring a file from Computer A to Computer B,
verification ensures that the file has reached Computer B successfully and that its
contents are unchanged.
Validating Data

• This refers to the process of checking that data meets certain predefined criteria
before it is processed or used.
• Validation checks include:
⚬ Range Check: Ensuring a value falls within a specified range (e.g., age should be
between 0 and 120).
⚬ Presence Check: Verifying that important data fields are not left empty.
⚬ Length Check: Ensuring that data contains the correct number of characters
(e.g., a phone number has 10 digits).
⚬ Format Check: Checking that data is in a specified format (e.g., a date in the
format DD/MM/YYYY).
⚬ Character Check: Ensuring that data contains only permissible characters (e.g.,
an email address should include '@').
⚬ Type Check: Confirming that data is of the correct data type (e.g., numerical
fields should not contain letters).
Types of Test
Data
• Normal Data:
⚬ Data that precisely fits the criteria for a valid promotional code.
⚬ Example: A1B2C3D4 (A code that meets the 8-character alphanumeric
requirement.)
• Abnormal Data:
⚬ Data that does not meet the criteria and should be rejected by the input
validation.
⚬ Example: XYZ (Too short) or 1234567890 (Too long), or !?#& (Non-alphanumeric
characters).
Types of Test
Data

• Extreme Data:
⚬ The largest or smallest data values that are still within the valid range and
should be accepted.
⚬ Example: A1B2C3D4 (Exactly 8 characters, testing the upper limit if 8 is the
maximum).
• Boundary Data:
⚬ Data values that are on the edge of being valid or invalid to test the system's
handling of input limits.
⚬ Example: 1234567A (Just at the lower boundary of the length requirement) and
A12345678 (Just over the upper boundary, which should be rejected).
Stages of Program
Design
• Analysis:
⚬ In this initial stage, the requirements are gathered, and the purpose of the
software is defined. Stakeholder input is crucial here to ensure the software will
meet their needs.
⚬ [e.g., Conducting interviews, surveys, and reviewing existing systems for
improvement.]
• Design:
⚬ Here, the software's architecture is planned. It involves outlining the overall
system architecture, defining data structures, software architecture, interface
designs, and algorithms.
⚬ [e.g., Creating data flow diagrams, UML models.]
Stages of Program
Design

• Coding:
⚬ This is the actual writing of the program using the chosen programming
languages. Developers translate the design documents into executable code.
⚬ [e.g., Implementing the design in Java, C++, Python, etc.]
• Testing:
⚬ After coding, the software is tested for defects and to ensure it meets the
requirements. This stage can involve unit testing, integration testing, system
testing, and acceptance testing.
⚬ [e.g., Using automated testing tools, debugging, and beta testing with users.]
Stages of Program
Design

• Maintenance:
⚬ Post-deployment, the software needs to be updated and maintained to deal
with new requirements or fix issues not found during testing. It's an ongoing
process that ensures the software continues to perform well over time.
⚬ [e.g., Updating software to add features, fix bugs, or adapt to new operating
systems.]
Tools in Program
Development
⚬ Editor:
⚬ A software where the source code is written in a high-level language.
⚬ [For example, Integrated Development Environments (IDEs) like Visual Studio or
Eclipse.]
• Translator (Compiler/Interpreter):
• Converts high-level language into machine code.
• [Compilers translate the entire code at once, whereas interpreters do it line-by-
line.]
• Debugger:
• A tool for testing the program and detecting errors.
• [Allows stepping through code, setting breakpoints, and inspecting variables.]
Integrated Development Environment

• Features of an IDE:
⚬ Pretty Print: Formats code with proper indentation and spacing, enhancing
readability (e.g., auto-formatting a messy code block into a clean, organized
structure).
⚬ Automatic Indentation: Adjusts the indentation level automatically when writing
code to reflect the logical structure (e.g., auto-indenting the contents of a loop).
⚬ Syntax Checking: Identifies and flags syntax errors as code is written (e.g.,
missing semicolons or unmatched parentheses).
⚬ Highlights any undeclared variable: Alerts the developer when code refers to a
variable that hasn't been declared (e.g., highlighting a typo in a variable name).
⚬ Type Checking: Ensures that values assigned to variables are compatible with
their declared types (e.g., preventing the assignment of a string to an integer
variable).
Integrated Development Environment

• Features Provided by an IDE That Assist in "Initial Error Detection":


⚬ Dynamic Syntax Checking: Checks code for errors as it is typed, without needing
to compile first (e.g., real-time alerts for misspelled keywords).
⚬ Tree Checking: Analyzes the abstract syntax tree for structural issues in the code
(e.g., ensuring all opened braces have a corresponding closing brace).
⚬ Identification of Unused Variables: Detects variables that have been declared
but not used in the code, which could indicate an error or inefficiency (e.g., a
variable set up for a loop that is never executed).
Finding Errors in
Code
• Dry Run/Trace Table: Manually stepping through code logic on paper to predict the
outcome of each line (e.g., tracking variable values through iterations of a loop).
• Breakpoint: Setting a point in the code where execution will halt, allowing
examination of the current state (e.g., to investigate the state of variables when a
specific condition is met).
• Variable Watch: Monitoring the values of selected variables during execution to
spot unexpected changes (e.g., observing a counter variable in a loop).
• Stepping: Moving through code one line or instruction at a time, observing the
execution flow and variable states (e.g., step-by-step execution to pinpoint where
a logic error occurs).
Development
Methods
Waterfall Method

• Principles:
⚬ Linear: Each stage is completed before the next begins, making it easy to
understand and manage due to its structured nature.
⚬ Well Documented: Every phase has its own documentation requirements,
ensuring a comprehensive paper trail.
⚬ Low Customer Involvement: Customers or end-users are typically involved at
the beginning and the end of the process, which limits feedback during the
development.
Waterfall Method

• Stages:
⚬ Analysis: Understanding and documenting the system requirements.
⚬ Design: Creating the architecture and design documents based on the
requirements analysis.
⚬ Coding: Writing the actual code in the programming language of choice.
⚬ Testing: Verifying the code meets the requirements and is bug-free.
⚬ Maintenance: Upkeep after deployment, including bug fixes and updates.
Waterfall Method

• Benefits:
⚬ Easy to Manage: The clear structure means stages do not overlap, which
simplifies planning and task delegation.
⚬ Works Well for Smaller Programs: Its straightforward approach is often suitable
for smaller, well-defined projects.
Waterfall Method

• Drawbacks:
⚬ Difficult to Make Late Changes: If requirements change, it is harder to go back
and alter work that has already been completed.
⚬ Not Suited for Projects Subject to Change: Programs that require flexibility due to
changing requirements are not ideal for this method.
⚬ Working Program Produced Late: A functional version of the software is not
available until late in the life cycle, delaying feedback.
⚬ Not Suitable for Complex Projects: The lack of iteration can hinder the
development of complex, evolving systems.
The Waterfall Method's structured approach makes it easier to manage and
understand, but its rigidity can be a drawback, especially for projects where
requirements are likely to evolve.
Iterative Method

The Iterative Model is a software development approach that emphasizes repetition


and gradual refinement of the software project through multiple iterations, each
building on the previous ones. Here's a breakdown of its structure, principles, benefits,
and drawbacks:
• Structure of the Iterative Model:
⚬ Begins with an initial version (First Waterfall), followed by multiple rounds of
development. Each round extends the development if the previous one is
successful, leading to further extended and improved versions until the final
product is achieved.
Iterative Method

Principles:
• Incremental Development: The program development lifecycle is repeated in small
segments, with improvements at each stage.
• High Customer Involvement: Customers or users are involved throughout the
process, seeing parts of the system after each iteration, which ensures continuous
feedback and satisfaction.
Iterative Method

Benefits:
• Easier to Test and Debug: Smaller, manageable sections of the software are
developed and tested, making it simpler to identify and fix issues.
• More Flexible: It's easier to alter requirements as the project evolves,
accommodating changes in scope or user needs.
• Customer Involvement: Stakeholders see the system develop over time, reducing
the likelihood of surprises at project completion.
Iterative Method

Drawbacks:
• Whole System Definition: Requires a clear understanding of the final system at the
start, which can be challenging.
• Planning: Needs thorough planning throughout the process, considering each
iteration's impact on the next.
• Not Suitable for Simple Projects: The complexity of the iterative approach might not
be justified for small, straightforward projects.
The Iterative Model's focus on repeated cycles allows for continuous refinement and
adaptability, with the potential for frequent customer feedback and the ability to
incorporate changes more readily than the Waterfall Model. However, it demands a
well-defined initial concept and careful management to ensure each iteration moves
the project closer to its final goals.
Rapid Application Development

Structure of RAD:
• The program is divided into modules, and each module is assigned to a different
team. Each team typically goes through the stages of Analysis, Design, Coding,
Testing, and Maintenance in sequence.
Principles of RAD:
• Minimal Planning: RAD emphasizes less upfront planning and more on adapting to
changes as the project progresses.
• Use of Prototypes: Where possible, RAD relies on the development of prototypes,
which are practical, working models of the desired system or features.
• High Customer Involvement: RAD involves customers throughout the development
process to gather feedback and ensure the final product meets their needs.
Rapid Application Development

Benefits of RAD:
• Reduced Development Time: Due to its iterative nature and use of prototypes, RAD
can significantly cut down the overall time required for development.
• Rapid Feedback: Customers see working versions of the product early on and can
provide feedback that can be quickly incorporated into the next iteration.
• Flexibility: The approach allows for adjustments based on customer feedback,
making it easier to accommodate changes in requirements.
• Ease of Modification: Since each part of the system is developed in modules,
modifications can be made without affecting the entire system.
Rapid Application Development

Drawbacks of RAD:
• Need for Modularity: The system under development must be modular to fit the RAD
approach.
• Skilled Team Requirement: RAD requires a team of skilled developers who can
adapt to rapid changes and work independently on different modules.
• Not Suitable for Small Projects: The approach may not be cost-effective or
practical for simple projects where a more straightforward development method
could suffice.
In essence, RAD enables a more responsive and flexible development process by
allowing rapid changes and adaptation as requirements evolve. It is particularly useful
for projects where time to market is a critical factor and for systems that can be
modularized to allow different teams to work on different parts concurrently.
Transferrable Skills

Transferrable skills in programming are fundamental concepts and practices that


apply across different programming languages. Understanding these skills allows a
programmer to recognize and use them when learning a new language:
• Declaration: Recognizing how variables and functions are declared. This might vary
in syntax but the concept of defining a data type and identifier remains consistent.
⚬ [e.g., int number; in C++ vs var number in JavaScript.]
• Assignment: Understanding the assignment of values to variables.
⚬ [e.g., number = 5; is common across many languages.]
• Sequence: Recognizing the linear execution of statements.
⚬ [e.g., executing lines of code one after another.]
• Selection: Identifying decision-making structures such as if-else statements.
⚬ [e.g., if condition in one language is conceptually similar to another, despite
syntax differences.]
Transferrable Skills

• Repetition/Iteration: Recognizing loops such as for, while, and do-while.


⚬ [e.g., Loop constructs may differ in syntax but the logic of repeating actions is
universal.]
• Subroutines: Understanding functions or methods in one language helps identify
them in another.
⚬ [e.g., void functionName() { } might be the structure in one language, while
another may use function functionName() { }.]
• Parameters Passed Between Modules: Identifying how data is passed into and out
of functions or modules.
⚬ [e.g., Function parameters/arguments are a common concept, even if
parameter passing mechanisms differ.]
Transferrable Skills

• Input-Output: Recognizing how a program interacts with the user or other systems
to receive and return data.
⚬ [e.g., print() in Python vs System.out.println() in Java for output, and similar
variations for input.]
These skills are foundational to programming and, once mastered, provide a solid basis
for learning and adapting to new languages and technologies.
Transferrable Skills

Albert, an experienced programmer, would be able to understand a program written in


a high-level language he's not familiar with due to several reasons tied to the
universality of programming concepts:
• Transferrable Skills: His experience means he's familiar with common programming
concepts that are applicable across languages. This includes understanding how to
follow the logic of the code, regardless of syntax.
⚬ [e.g., Recognizing a loop even if it's written in a different syntax than he's used to.]
• Basic Control Structures: Fundamental structures like loops, conditional statements
(if-else), and variable declarations tend to have similar purposes in different
programming languages, even if their syntax varies.
⚬ [e.g., for loops for iteration or if statements for decision-making, which are
common in many languages.]
Transferrable Skills

• Comments and Naming Conventions: Well-commented code and descriptive


variable names can convey the intent of the code sections, making it easier to
understand what each part of the program is supposed to do.
⚬ [e.g., Comments explaining the purpose of a function or why a particular logic is
used.]
Albert's foundational knowledge of programming principles allows him to abstract and
translate his understanding to a new language, deciphering the program's structure
and logic.
Types of
Maintenance
• Corrective Maintenance:
⚬ Occurs when testing reveals a fault or error in the program which is then
corrected.
⚬ The primary reason for corrective maintenance is to amend the algorithms and
eliminate errors.
⚬ [For example, fixing a bug that causes a program to crash when a specific input
is given.]
• Adaptive Maintenance:
⚬ Involves changes made to a program in response to specification changes, such
as new requirements or advancements in technology.
⚬ Reasons for adaptive maintenance include responding to changes in business
rules, operational environment, or compliance regulations.
⚬ [Such as updating an application to work with a new operating system.]
Types of
Maintenance
• Perfective Maintenance:
⚬ Deals with implementing new or changed user requirements which involve
functional enhancement of the system.
⚬ It aims to improve both the function and efficiency of the code, modifying
functionalities as per the user's evolving needs.
⚬ [For instance, adding a new feature to meet the latest market trends.]
• Preventive Maintenance:
⚬ Involves performing activities to prevent the occurrence of errors. It is more
about proactive measures to ensure the long-term efficiency and reliability of
the software.
⚬ [This could include refactoring code to improve readability and reduce
complexity.]
Types of
Maintenance

Each type of maintenance serves a unique purpose, from fixing existing issues
(corrective) to adapting to new requirements (adaptive) or enhancing features
(perfective), to preventing future problems (preventive). These maintenance activities
ensure that software remains functional, relevant, and efficient throughout its use.
Types of
Errors
In programming, errors can generally be classified into three main types, each with
distinct characteristics and implications:
• Syntax Errors:
⚬ These are mistakes in the use of the language of the program. They are akin to
grammatical errors in a spoken language and usually prevent the code from
compiling or interpreting successfully.
⚬ Example: Missing a semicolon at the end of a statement or a typo in a keyword.
• Logic Errors:
⚬ Occur when a program doesn't perform as expected due to an error in the logic
or algorithm. The code compiles and runs, but it doesn't do what it's supposed to
do.
⚬ Example: Incorrectly using a < operator instead of <= in a loop condition, leading
to an off-by-one error
Types of
Errors

• Runtime Errors:
⚬ These errors surface while the program is running. They often occur due to illegal
operations that cannot be determined until the program is in progress.
⚬ Example: Trying to access an array element that is out of bounds or dividing a
number by zero, which may cause the program to crash or terminate
unexpectedly.
Understanding and being able to identify these errors is critical for debugging and
ensuring the reliability and correctness of a program. Each type requires different
strategies for detection and resolution.
Stepwise
Refinement

Stepwise refinement is a programming method where an algorithm or a large problem


is broken down into smaller, more manageable parts or steps that can be programmed
individually. This approach simplifies the development process and enhances code
clarity and maintainability.
What is stepwise refinement?
• It's the process of breaking down an algorithm into smaller parts (detail) to a level
where they can be directly programmed.
• Each sub-task in this process can be considered a module that is refined separately.
• Modules or subroutines in this context can be functions or procedures, each
encapsulating a specific task or functionality.
Subroutines and Modules

Uses of subroutines in a program include:


• To perform a frequently used operation that can be called when needed, which can
be reused by other programs.
• [Example: A print function that formats and prints documents in different parts of the
software.]
Why it's a good practice to construct the program using modules:
• It creates a more manageable and understandable solution.
• Subroutines or modules can be independently tested, making the program easier to
maintain.
• [Example: A sorting algorithm used in different parts of an application can be tested
once and reused, ensuring consistency and reducing errors.]
Subroutines

Advantages of sub-routines:
• Allow the subroutine to be called in multiple places, reducing code duplication.
• Subroutines can be tested independently, facilitating easier and more focused
testing.
• If the task changes, the change needs to be made only once, within the subroutine,
and it's reflected wherever the subroutine is called.
• Reduces unnecessary duplication of code and logic.
• Enables a team to work on different parts of the solution simultaneously.
By using stepwise refinement and subroutines, a complex problem like a train
management system can be decomposed into modules such as scheduling, ticketing,
and routing, each of which can be developed and tested separately. This modular
approach leads to more robust and maintainable code.
Fuctions &
Procedures
Procedures:
• A procedure is a sequence of steps that performs a task but does not return a value
to the caller. It's identified by a name and is called to execute a specific sub-task.
• [Example: A printDocument procedure that sends a document to a printer but does
not return any value.]
Functions:
• A function is similar to a procedure but is designed to return a value to the caller
after executing its sub-task.
• [Example: A calculateSum function that returns the sum of two numbers.]
Passing
Parameters
Methods of Passing Parameters Between Modules:
• By Value:
⚬ The actual value of a variable is passed to the function or procedure. Inside the
function, a copy of the argument is made, and the original variable remains
unchanged.
⚬ [Example: Passing an integer 5 to a function will allow the function to use the
value 5, but any changes to it will not affect the original variable.]
• By Reference:
⚬ The address (reference) of the variable is passed, allowing the function or
procedure to modify the original variable.
⚬ [Example: If a variable x is passed by reference to a function, any changes to
this variable within the function will reflect in the original variable x outside the
function.]
Structured Programming

Support of Structured Programming in the Implementation of Sub-Tasks: Structured


programming supports the creation of sub-tasks through:
• Subroutines: These are general blocks of code, including both procedures and
functions, that perform defined tasks.
• Functions: Functions are structured to return data, making code reusable and more
logical.
• Procedures: Procedures structure code into clear, reusable blocks without requiring
a return value.
• Parameters: Parameters allow passing of data into functions and procedures,
making them flexible in the tasks they perform.
Structured programming promotes the use of these constructs to make programs
easier to understand, maintain, and debug. It encourages modular design, where each
module can be developed and tested independently, thus improving code quality and
development efficiency.

You might also like