L2 Coding - WB1 - PC1B.4.23
L2 Coding - WB1 - PC1B.4.23
CODING LANGUAGE
COMPILED CODE
INTERPRETED CODE
DEBUGGING
Workbook 1
How to use your learning materials
This course is delivered on a flexible learning basis. This means that most of your study
will take place away from your Assessor/Tutor. It helps to carefully plan your studying
so that you get the most out of your course. We have put together some handy tips for
you below.
Study Guidance
• Try to plan an outline timetable of when and where you will study.
• Try to complete your work in a quiet environment where you are unlikely to
be distracted.
• Set realistic goals and deadlines for the various elements of your course.
• Plan what you are going to study during each session, and try and achieve
this each time.
• After each session, reflect on what you have achieved and plan what you hope to
complete next time.
• Remember that not only do you have the support of your Assessor/Tutor, but it is
likely that your family, friends and work colleagues will also be willing to help.
Assessor/Tutor Support
• Your Assessor/Tutor will be available to support and guide you through the
programme. They are experts in your area of study and are experienced in helping
many different types of learners.
• They can help you to improve the standard of work you submit and will give
you useful feedback on areas in which you have excelled, as well as where
you can improve.
• Remember to listen to, or read, their feedback carefully. Ask if you are unsure about
any of the feedback you receive, as your Assessor/Tutor is there to help.
• Make note of any tips they give. Refer to the learning materials, as they contain the
information you need to complete the end-of-unit assessments.
• Look out for areas in which you can improve, and set yourself an action plan to make
sure you complete the required work.
• Take positive feedback on board; this demonstrates you are doing things right and
have a good understanding of the subject area.
• Use the feedback to avoid repeating any mistakes you may have made.
In this workbook, we will learn about different coding languages, including identifying
different procedural and object-oriented languages. We will also explore the different job
functions in coding and learn about the different stages of the software development
lifecycle. We will also explore basic computer terminology, including the acronyms used in
coding and some of the key coding principles, such as iterations and recursions. After this,
we will explore the different types of coding, including imperative, declarative, functional
and object-oriented coding, and the differences between compiled and interpreted code
and between pure functions and impure functions.
Contents
This workbook contains three sections: Page
Section 1: Understand the principles of coding 5
Section 2: Understand terminology used in coding 46
Section 3: Understand coding design principles 84
Section 4: Extension activities 114
Assessment 1
The assessments for this workbook can be found in: Learner contact details
Name:
Email:
When you have completed this workbook, you should Learner declaration
I confirm that the answers in Assessment 1 were completed by me, represent my own
you detailed written feedback on your progress. If you need any help in completing these assessments, refer to the
relevant section within Workbook 1, or contact your Assessor/Tutor.
Please tick one of the boxes below to show what your status will be when you complete
this course.
Remember that your assessment answers should be EMP 1 In paid employment for 16 hours or more
per week
EMP 2 In paid employment for less than 16 hours
per week
EMP 4 Self-employed for 16 hours or more per week
GAP 1 Gap year before
starting HE
EDU 1 Traineeship
EDU 2 Apprenticeship
Workbook 1 3
PLEASE READ!
Every effort has been made to ensure the content of this workbook is accurate at
the time of print/production. As some information can change, we recommend
that you check the latest guidance and advice to ensure your answers are
accurate and current.
4 © LCG 2021
Section 1: Understand the principles of coding
In this section, we will first look at the definition of coding and coding language. Then
we will explore some different coding languages, including the differences between
procedural and object-oriented languages, before learning what syntax is and what
technologies run code.
Next, we will identify and learn more about different job functions in coding, as well
as learning about the role of project management, team working and possible career
paths.
The section will end with a discussion of the software development lifecycle. This
will include learning about the key stages of the lifecycle and the importance of the
implementation, testing and deployment stages.
We can think of coding as similar to different languages. But instead of being used to
help people communicate with each other, coding languages help people communicate
with computers.
Computers are machines made using transistors. These devices essentially work like a
switch, where they are either ‘on’ or ‘off’. Computers all work by using a mathematical
language, called binary, which is made up of long strings of ones and zeros, where 1
means ‘on’ and 0 means ‘off’. However, binary is complex and difficult to use because
it doesn’t look anything like the languages we speak and understand.
So instead, computer engineers created different languages, which were easy
for people to understand and which could be translated into the binary code that
computers understand. Coding is the process of using these languages, or ‘codes’, to
tell computers what to do. Coding is also referred to as programming and code is also
called programming language.
There are two main levels of coding, or programming languages: high-level languages
and low-level languages. High-level languages are easier for people to use and
understand. They include the most common coding languages around today. Low-level
languages are closer to the binary language that computers use. They are harder for
humans to use, but are more memory efficient and faster to execute.
Workbook 1 5
Section 1: Understand the principles of coding
As we have already seen, coding or programming languages are sets of rules that both
humans and computers can use and understand. Computer programmers use different
coding languages to create software programs.
A program is a text file that serves as an instruction manual for a computer. When you
launch an application, you’re telling the computer to read the text file and execute the
commands it contains. There are a wide variety of coding languages and they have
been designed to do different things.
For example, one of the most popular coding languages, JavaScript, is used primarily
to develop web pages. Another popular language, Python, is used to develop software
programs and websites.
6 © LCG 2021
Section 1: Understand the principles of coding
coding is the process of using codes to tell computers what to do, whereas
coding language is different codes used by both humans and computers to do different things.
There are a huge variety of coding languages. Some were designed for particular uses,
while others have much wider or more general uses. Here we will look at some of the
most common.
This is one of the most established and widely-used programming languages in use
today. It was first released back in 1972 and is a complex, high-level language that has
influenced the development of many other languages, such C++, Java and Python. It is
mainly used for creating system applications, meaning that operating systems such as
Windows and Linux use C. It is also used to create games, graphics, and apps that use
lots of calculations.
Workbook 1 7
Section 1: Understand the principles of coding
C++
Here is a simple program in C++ to print out the phrase “Hello World”.
#include <iostream>
int main() {
std::cout << “Hello World!”;
return 0;
}
C#
Another language in the C family, C# was built specifically for Microsoft .NET and is a
combination of many of the features of C and C++. It is most often used for developing
code for Windows systems. Although it is the most technically complicated of the C
languages, it is not necessarily the most difficult to learn. It is considered one of the
best languages to use for programming custom software and is also commonly used in
video game development.
Python
This is one of the easiest high-level coding languages to learn and is very popular
with those who are new to coding. It is fairly intuitive to write and understand, which
makes it ideal for those who want to get a quick start in programming. It is also a
very versatile language and is popular for both general uses, such as developing web
applications, and specialised uses, such as artificial intelligence (AI) and machine
learning.
8 © LCG 2021
Section 1: Understand the principles of coding
Python is a very easy language to learn. Here is a simple program in Python to print out
the phrase “Hello World”.
Java
This is another versatile and general-purpose language that is good for beginners. It is
also very popular. This is partly because once you have written a piece of code in Java,
it can be run on just about any device using the Java platform. Some of its main uses
include business software, web applications and mobile apps. For example, Google’s
Android OS uses Java as its native language.
Here is a simple program in Java for printing out the phrase “Hello World”.
JavaScript
Despite its name, JavaScript isn’t actually related to Java. However, it does use a Java-
like syntax (the rules that define the structure of a language), which is where the name
comes from. It was created in 1995, in the early days of the Internet, and is used to
write code that runs in all major web browsers. Because of this, it has a wide range of
applications and is especially useful for making interactive and responsive web pages.
It’s often used alongside HTML and CSS to add elements like animations, video players
and browser-based games to web pages.
Workbook 1 9
Section 1: Understand the principles of coding
Swift
This is a more recent coding language. It was developed in 2014 for use in Apple’s iOS
and macOS applications. This means that not only does it run on all iPhones and iPads,
but it’s also the basis for other Apple-based operating systems, such as watchOS and
tvOS. However, it is also very easy to learn.
Ruby
This coding language has very simple syntax, which makes it very flexible and easy
to write. This has made it a favourite with start-ups, who need to move quickly.
Companies like Airbnb, Shopify and Bloomberg all initially built their websites using
Ruby. The other reason it’s popular with start-ups is that it is the basis for the popular
Ruby on Rails web application framework, which allows developers to build applications
around 40 percent faster than with other technologies.
PHP
PHP is another easy-to-learn coding language and is both free and open source. Like
JavaScript, it’s mainly used for web development. However, it is used on the server
side, rather than to develop websites, so is often used together with JavaScript. It has
been described as the paintbrush, while JavaScript is the paint. It is mostly used in
website development – for example, to manage dynamic content and databases on a
website.
SQL
10 © LCG 2021
Section 1: Understand the principles of coding
This is a highly specialised coding language that is primarily used in academic fields
and by large tech companies. It is a low-level language aimed at statistical computing
and graphical techniques. It comes with a vast library of tools, including machine
learning algorithms. Statisticians and data miners often use R to develop programs
for performing statistical software and data analysis packages. It is also useful for
professionals such as demographers, data scientists, and insurance actuaries to gain
statistical insights.
Workbook 1 11
Section 1: Understand the principles of coding
12 © LCG 2021
Section 1: Understand the principles of coding
Syntax refers to the rules that define the structure of a language. For example, in the
English language it includes rules like where to put the nouns, verbs, punctuation and
adjectives in a sentence. In computer programming, syntax is the same – it is the rules
that control the structure of the programming language, including symbols, punctuation
and words.
In coding, syntax is important because it provides the rules that compilers and
interpreters will follow to convert the code into a language the computer can
understand and to execute the program correctly when it is run.
Syntax refers to the words and symbols that are used to write the code, and the
specific order those words and symbols need to be in to allow us to communicate
effectively with a computer. Unlike spoken or written languages, however, computers
are really precise in how the syntax needs to be structured. Humans can read and
understand a sentence even if it has typos and mistakes, but if a computer finds a typo
in the code, it gets confused and has no idea what to do.
In fact, syntax is why we use the word ‘coding’ for computer programming. Each
programming language uses different words in a different structure to get the
computer to follow our instructions.
Every programming language has its own set of rules that make up its basic syntax.
Different languages may have rules for things like adding comments, using white space
or declaring variables.
Some examples of basic syntax in Java and C or C++ include:
Case Sensitivity: Java, C++, and Python are examples of languages that are case-
sensitive. Identifiers such as world and World have different meanings in these
languages. Languages such as Basic and SQL are insensitive, meaning world and
World have the same meaning in these languages.
Class Names: Java requires the first letter of each word in class names to be upper
case. For example, ILoveCoding. Languages such as C or C++ use an underscore to
separate words. So, in C, the class name would be i_love_coding.
14 © LCG 2021
Section 1: Understand the principles of coding
Programme Filenames: The name of a Java program file must match the class name,
with the extension ‘*.java” added to the name. For example, ILoveCoding.java would
be the name of the program file for the class ILoveCoding. C and C++ files require a
“*.c” or “*.cpp”.
int main() {
printf( “My first line of code” );
}
All C programs must begin with main() followed by a left curly bracket ( { ).
This indicates the start of the program. A right curly bracket ( } ) indicates the
end.
The print function (printf) is called, followed by what we want to print. The text
we want to print must be surrounded by quotation marks and enclosed in
parentheses.
All statements must end with a semicolon ( ; ). For example, if we want to
print a second sentence, we can add the following statement before the right
curly bracket:
The executed program would display: My first line of code has just printed!
Workbook 1 15
15
Section 1: Understand the principles of coding
a=2
if (a == 2)
print(“True”)
In Python, if statements need to end with a colon (:). Because one is missing
here, the program stopped running and an error message came up. To fix the
problem, the coder just needs to add in the colon:
if (a==2):
Now that we know a bit about what code is, we can ask what technologies use code
to run. But it may be easier to list the technologies that don’t use code to run. This is
because almost every technology uses code in some way. Building and running apps
and websites on computers, tablets and phones, smart TVs, connected devices, cars,
analysing data, operating traffic signals, operating robots – all use code.
If you look around your house, you may even find code involved in some surprising
places. For example, if you have a programmable microwave or coffee maker, those
use code, as does your smartwatch, Bluetooth speaker and wireless headphones.
16 © LCG 2021
Section 1: Understand the principles of coding
Workout gear that monitors your heart rate, breathing and movement uses code to
program the AI that tracks your workout stats. Even the humble light bulb can be
programmed to run code. The Philips Hue LED light bulb is one example. The bulbs use
code to connect to a mobile device, like a smartphone, to allow you to customise the
lighting in your home remotely – for example, by turning the lights on and off when you
are out, for safety.
Water bottles like H2OPal and HidrateSpark use code to connect to apps on your
smartphone, which can inform you about your hydration levels based on your physical
activity, the amount of water drunk in a certain period of time, and other statistics, and
recommend when it is time to take a drink. Some showers use code to allow bathers to
control temperature, scheduling and timing, to avoid wasting water and energy, and to
avoid fights for the bathroom.
Even ‘smart’ ice cubes have been developed that use sensors and code to anticipate
when a bar patron is running low and needs a drink refill, and communicates this to
the bar staff in real time. The cubes are designed to reduce crowds and queues, while
improving sales.
Knowledge Activity: Look around your home, school or workplace and see
how many items you can find that use code in some way. Is it more than you
thought?
Workbook 1 17
Section 1: Understand the principles of coding
The main job of a coding professional is to develop software. But within that simple
definition is actually a wide range of job functions. Computer coders work with software
developers, designers and programmers to plan each piece of the application or
software and then determine how each part will work together.
Some of the basic job functions of a coding professional include:
Writing and testing code for new programs. Computer coders work closely with
web and software developers to write code for new mobile applications or computer
programs. In some cases, coders might have a similar role to web designers, creating
the look, feel and functionality of a new software program.
Updating existing programs. Coders also create and install updates for existing
software. An update might include a bug fix, or enhancing functionality to improve the
user experience. Depending on the complexity of the update, these projects can take
anywhere from a few days to several months.
Identifying and correcting coding errors. On a daily basis, computer programmers
might assist in troubleshooting parts of a website or computer program that are not
functioning correctly. Often, problems are a result of an error in the code, and a coder
can help identify and correct the mistake quickly.
Rewriting programs for different operating systems. Often, programmers have
to rewrite code in different languages, so that programs and applications can be
compatible with different operating systems. For example, Windows and OS X programs
are coded differently.
Securing programs against cybersecurity threats. Many computer programmers
work in the cybersecurity field, helping to identify malicious software and fix software
that could be vulnerable to potential hacks. Additionally, programmers can write code
that prevents security breaches and data leaks. As the number and severity of cyber
attacks increases, demand for information security experts continues to rise.
Design graphical user interfaces (GUIs). GUIs are easy, point-and-click menu options
that allow non-technical users to easily use software. The GUI acts as a translator
between the user and the software code.
Using computer-assisted software engineering (CASE) tools. Some coders, especially
those working on large projects, use CASE tools to automate the repetitive parts of the
coding process. These tools enable a programmer to concentrate on writing the unique
parts of a program.
18 © LCG 2021
Section 1: Understand the principles of coding
While knowledge of at least one programming language, and having a strong interest
in computers, seem like obvious requirements for a coder, many of the other key skills
that employers look for may not be so obvious. Here are a few of the key skills that you
will need as a coding professional.
Workbook 1 19
Section 1: Understand the principles of coding
Abstract thinking
Abstract thinking is a foundation of coding. Because the development of the finished
product can’t be ‘seen’, coders have to develop an ability to think abstractly, so they
can visualise how the program will function when it is completed. Abstract thinking
also includes the ability to think about a subject or project on many levels at once.
Being able to balance different symbols, commands, and processes that are running
automatically with those that you need to more directly oversee/change is an
important, often overlooked part of coding.
Abstract thinking involves a willingness to see things from a different angle, or to draw
analytical conclusions from what might seem straightforward – to ‘think outside the
box’.
20 © LCG 2021
Section 1: Understand the principles of coding
Strong memory
Coders need to be aware of many different pieces of information at once, and know
how they’ll all react to each other. Being aware and able to visualise design, data flow,
algorithms, data structures, and how they affect each other will separate you from
the average coder. While working with the same languages, you’ll internalise syntax,
and it will feel less like using memory and more second nature to recall important
commands.
Communication skills
While many people envision coders as working alone in a darkened room, in reality
coders need to be able to work with and explain what they do to employers, clients,
consumers and co-workers with no coding experience. Successful coders listen to
feedback and are able to manage expectations, interpret vague descriptions and
honestly assess and communicate what is, and isn’t, possible. Coders are known for
their egos, but those willing to patiently give and accept advice and direction are far
more respected than snarling programmers that only relate to their desktops.
Knowledge Activity: Skills – Make a list of the skills needed for a career in
coding. Next to this, write down a rating of your ability in each skill, and where you
feel you need improvement. Now, make a plan for how you will gain experience in
these skills.
Workbook 1 21
Section 1: Understand the principles of coding
As you have probably realised, writing and developing a computer program can be a
huge job. Usually, there will be many people working on the same program, with each
person responsible for coding a particular part of the whole. It is the job of the project
manager to make sure that these are all completed, put together and tested in the
correct order and on time. The project manager shepherds a project from start to
finish, overseeing everything from brainstorming ideas to delivering final results.
These days, every member of the team has to have a basic level of project
management skills to be able to contribute to the overall direction of the project. For
example, knowledge of scheduling techniques can help coders organise and plan their
work. Because delivery dates are notorious for being missed, skills like knowing how to
schedule completion dates within date ranges versus a single date are very important.
Knowledge of scheduling techniques is also important because there will be many
times when your work depends on getting input from someone else first, or giving
input to others before they can do their work. So, it is also important to learn how to
estimate and schedule your time realistically – or you may end up with too little time in
which to complete your portion of a project.
Communication is another key project management skill. This means not only
communicating with the other team members, but communicating effectively, ensuring
all team members know how to estimate their time and keep their progress updated
in software the entire team can access. It can also include ensuring document sharing
and team updates are enabled, so there are no missed or mixed messages.
Often, one team member is appointed to co-ordinate and direct others in the team.
Project management skills such as a knowledge of Agile development can help with
this.
Another area where project management skills are useful is in producing technical
documentation. Too often, documentation isn’t part of the team’s normal workflow, but
it should be. It’s also important to be familiar with the different ways that documents
can be produced, such as using wikis, enterprise social tools and online project
management tools.
Risk management is another important project management skill. For example,
determining the risks of not delivering a stable, complete project on time, and how
to manage these risks. Risk management is most effective when distributed among
the project’s team members, so it is likely that you will have to do some type of risk
management in your career.
22 © LCG 2021
Section 1: Understand the principles of coding
One strategy is to make individual team members accountable for explaining the
potential risks in their project tasks to the greater group, such as producing precise
timelines for their piece of the project. Knowing how to do this will help you to be more
effective in your career.
Knowledge Activity: Which project management skill do you feel is the most
important and why?
Workbook 1 23
Section 1: Understand the principles of coding
As we have seen, coding often involves a team, where each member is responsible
for a piece of the whole project. There are many different roles within a coding team.
Depending on the size of the organisation, and of the team, each role may be filled by
one or more people, or one person may have several roles.
The following are the main roles within a coding team.
Project manager
As we have seen, the project manager is responsible for the overall flow and
management of a project, including budget, risk, scheduling and contract
management. Project managers in IT may be experienced coders, but many specialise
in project management, rather than technical skills, and may have little or no hands-on
experience. The role may involve:
• making sure that everyone is on track with project requirements, deadlines and
schedules
• meeting with project team members to identify and resolve issues
• submitting project deliverables and ensuring that they adhere to quality standards
• preparing status reports by gathering, analysing, and summarising relevant
information
• establishing effective project communication plans and ensuring their execution
• facilitating change requests to ensure that all parties are informed of the impacts on
schedule and budget
• coordinating the development of user manuals, training materials, and other
documents needed to enable successful implementation and turnover of the process
or system to the clients
• identifying and developing new opportunities with clients
• organising and tracking contracts
• conducting post-project evaluation and identifying successful and unsuccessful
project elements
24 © LCG 2021
Section 1: Understand the principles of coding
Product owner
Product owners manage the product development process to ensure that clients’
needs are met. Product owners help determine product features and manage the
product development, as well as liaising with customers or sales and marketing teams.
In a small organisation, this role may overlap with the project manager; in a large
organisation, it may be a separate role, with one product owner responsible for many
products. Some functions of this role include:
• strategising and presenting ideas for further development
• working with customers or in-house teams to define the product features
• leading the development process
• acting as the main point of contact between teams and customers or upper
management
• adjusting and improving each version of the product before release
• identifying areas of improvement
• keeping customers and upper management informed of the status of the product
Team lead
Usually this role is given to one of the product developers, who has leadership skills.
The team lead oversees the project and makes sure that everyone on the team knows
what they need to be doing – and when. The team lead also maintains communication
between remote development teams, upper management and clients. Team leads
also ensure that the team has sufficient performance levels and is also responsible for
conflict prevention and resolution.
• managing the day-to-day activities of the team
• motivating the team
• developing and implementing a timeline
• delegating tasks to team members
• conducting training as needed
• helping team members develop skills to improve their confidence, product knowledge,
and communication skills
• conducting performance reviews
Workbook 1 25
Section 1: Understand the principles of coding
Tech lead
This position may also be referred to as ‘architect’ or ‘analyst’ and may overlap with
or replace the role of project manager. Technical leads typically ensure the smooth
functioning of technical operations, monitor and evaluate staff progress, assist with
training and recruitment, set goals, and ensure overall client satisfaction. Some key
functions include:
• determining project requirements and developing work schedules for the team
• delegating tasks and achieving daily, weekly and monthly goals
• liaising with team members, management and clients to ensure projects are
completed to standard
• identifying risks and forming contingency plans
• analysing existing operations and scheduling training sessions and meetings to
discuss improvements
• keeping up to date with industry trends and developments
• updating work schedules and performing troubleshooting as required
• writing progress reports and delivering presentations to the relevant stakeholders
Full-stack developer
This is a programmer who does not specialise in one specific area. They have a broad
range of knowledge and skills, which allows them to work on both the front end (what
the user sees) and back end (the source code) of the system. Full stack developers will
be required to see out a project from conception to final product, which requires good
organisational skills and attention to detail. Some of the responsibilities of a full stack
developer include:
• developing front end website architecture
• designing user interactions on web pages
• developing back-end website applications
• creating servers and databases for functionality
• ensuring cross-platform functionality for mobile apps
• working alongside graphic designers to create web design features
• designing and developing APIs (application programming interface – code that allows
two applications to talk to each other)
26 © LCG 2021
Section 1: Understand the principles of coding
Front-end developer
Back-end developer
Back-end developers create, code and improve the servers, server-side applications
and databases that combine with front-end codes to create a functional, seamless
experience for the user.
The back-end developer uses their understanding of programming languages and tools
to create a more seamless experience for users. Some key responsibilities include:
• compiling and analysing data, processes and codes to troubleshoot problems and
identify areas for improvement
• writing code for servers and database applications
• troubleshooting and debugging code
• managing hosting environments
• building and maintaining web applications
• developing ideas for new programs, products or features by monitoring industry
developments and trends
Workbook 1 27
Section 1: Understand the principles of coding
The QA lead is responsible for end users’ reactions to the system. Similarly to a team
lead, the QA lead manages relations between QA team members and helps develop
and maintain quality standards. Responsibilities include:
• designing, implementing and improving quality standards
• analysing data to find areas for growth
• training, motivating and coaching employees to ensure that standards are met
• creating reports and analysing data to track progress
• reviewing processes in order to ensure that they align with current trends
Quality engineers ensure that a company’s products and processes meet established
quality standards by identifying shortfalls, developing corrective measures, and
implementing quality control systems.
28 © LCG 2021
Section 1: Understand the principles of coding
Software tester
A software tester is responsible for designing tests for software usability, running these
tests and preparing reports on the effectiveness and defects to the production team.
This role may also be called software test engineer or a quality assurance (QA) tester.
Responsibilities of the software tester include:
• reviewing software requirements and preparing tests
• testing software
• analysing test results, including errors, bugs, and usability
• preparing reports on the software testing and reporting to the design team
• participating in design reviews and giving input on potential problems and solutions
Depending on the organisation, this may be one role or two. UI/UX designers are
responsible for the design and implementation of all the experiences a user has when
interacting with a digital tool, such as a website or app. The UI/UX designer works
closely with marketing teams and graphic designers to ensure a useful, usable and
attractive final product.
The UI/UX may focus on design, rather than coding, or they may do both. Many people
in these roles have an educational background in design, art or psychology, rather than
computing, but they do also need to be knowledgeable about computing and coding,
so they understand what is possible and how to develop solutions. This role includes:
• investigating user experience design requirements
• developing the concept for UI/UX design strategies for an organisation or brand
• producing high-quality UX design solutions using wireframes, visual and graphic
designs, flow diagrams, storyboards, site maps, and prototypes
• designing, and sometimes coding, UI elements and tools such as navigation menus,
search boxes, tabs and widgets for digital assets
• testing UI elements such as banners, page layouts, page designs, page flows, and
target links for landing pages
• collaborating with marketing teams and internal/external designers to ensure the
creation and delivery of the final product
• using research and testing to analyse and predict user behaviour
Workbook 1 29
Section 1: Understand the principles of coding
Teamwork can refer to a number of different things, including working with others
toward a common goal or efficient and effective collaboration with other people.
However, just because people are working with each other doesn’t mean that they are
engaging in successful teamwork.
In software development, teamwork is extremely important. This is because effective
software development takes the work of many different people, all working together
for a common goal. While individual coders may work on their own to develop specific
parts of a complete system or program, unless everyone is working to a common
schedule and development plan, the project will be at risk of not being completed
successfully.
30 © LCG 2021
Section 1: Understand the principles of coding
When team members work together effectively, it can lead to greater efficiency and
can prevent coding and other development errors.
The key requirements for efficient teamwork are communication and collaboration.
Communicating with other coders about problems and specific work processes helps
team members to be more productive in their actions and improves their collaboration.
This is similar to how a complex machine, like an engine, works. When all the pieces
fit together as they should, and all parts are running at the right speed, the engine
can hum along and perform the actions that it was created for. However, when even
a single piece is out of place or not operating at the correct rate, the engine doesn’t
function properly and isn’t as efficient as it should be.
Supportive teamwork can also lead to greater creativity. When team members
feel comfortable, they are more likely to express new ideas, which can result in
advancements and innovations that might not have been part of the plan from the
start. Creativity can also help development teams find unique solutions to the common
problems they experience during projects.
Workbook 1 31
Section 1: Understand the principles of coding
Junior developer
Senior developer
32 © LCG 2021
Section 1: Understand the principles of coding
This is often the last technical level on the career ladder before management. It
involves the same basic skills as a senior developer, but may also require a few more
years of coding experience. While the lead architect may write code, they will spend
most of their time designing the systems that will then be developed by teams of senior
and junior developers.
An architect’s job is to use their experience to create the structure for a successful
software project. They co-ordinate what work needs to be done and make some of the
day-to-day decisions.
This is a mid-level management role. The development team lead will keep track of
workflow and productivity and report to a senior leader or manager. Their knowledge
of coding is useful for understanding the needs of projects, and for finding solutions to
any issues that arise, but they will not usually do any coding themselves. In fact, this
role often spends a lot of time managing people – hiring and firing, and mediating the
needs of the product manager and the development teams.
Senior leader
This role includes positions such as vice-president, chief technology officer and even
CEO. The main role of the senior leader is to manage the more junior leaders and to
provide a clear vision and leadership for their organisation or division.
A senior leader’s job is to make high level decisions and inspire their workforce to go
along with those decisions and the overall mission of the organisation. There is no day-
to-day coding involved at all at this level, but your experience in coding will help you
earn the respect of those lower down on the ladder and develop a clear understanding
of projects. The senior leader spends their time focusing on managing people.
Workbook 1 33
33
Section 1: Understand the principles of coding
Other careers
While a career in coding and software development may be the most obvious choice
for a coder, this is not your only choice. In fact, those with knowledge of coding are
in great demand in a variety of fields. Many of these are related areas, such as cyber
security, database administration, business intelligence analyst, etc. But the skills that
make a good coder can also be useful in a number of other careers.
Those looking for a customer-facing role might find a career in developer relations
or advocacy. Their role is to help establish and build a community around their
organisation’s software, games or other product. They are often involved in creating
demo applications, writing blog posts, speaking at conferences, and managing social
media accounts for tech-focused companies.
Sales engineer is another option. This is a sales role, but it usually involves selling
products to other engineers and developers, so they need to have some level of
technical expertise themselves. There are also roles in human relations and recruiting
for tech firms, where a knowledge of coding is a big bonus.
If you would rather remain in product development, you could consider a role in quality
assurance or as a test engineer. Both of these positions deal with testing software
before it goes live and require some coding, in addition to manual testing work.
Business analyst or project manager is another option. They typically work as a bridge
between the business and technical teams to ensure that requirements, limitations
and timelines are understood and followed. A position as product manager combines
technical background with analysis. The product manager may also examine the
company’s products to ensure they are desirable (customers want them), viable
(makes business sense) and feasible (can actually be built). This requires high-level
thinking and the ability to be creative.
There are also a wide variety of support roles available. These positions work behind
the scenes to keep everything running smoothly. These roles include systems
administration (sysadmin) or development operations (devops), who maintain large
servers; database administrators, who deal with security, provisioning, scaling, and
optimising data storage systems; site reliability engineer, who is responsible for
responding to and fixing critical issues that come up in production; and technical or
customer support.
Those who enjoy writing can find work as a technical writer or copywriter. Another
area much in demand is analytical roles, such as data scientist, or research and
development.
And, of course, if you have a great idea, you can always start your own company!
34 © LCG 2021
Section 1: Understand the principles of coding
Knowledge Activity: Research one or more careers that involve coding. Detail
what training and experience is required and the types of organisations that are
hiring.
The software development lifecycle refers to the methods and processes used to
create software. It usually includes the following phases: analysis of requirements,
planning, software design, software development, testing, deployment. A seventh step
of maintenance may also be added.
The reason for having a development lifecycle, instead of just sitting down and writing
the software, is that it offers a way to plan, schedule and estimate the time it will take
to complete the entire process. This helps to lower the cost of software development,
while also improving quality and shortening production time. By anticipating costly
mistakes like failing to ask the end-user or client for feedback, following a lifecycle
process can eliminate reworking and fixes.
In the next section, we will discuss each phase in greater detail.
Workbook 1 35
Section 1: Understand the principles of coding
Analysis of requirements
This is the first stage of the cycle, where an organisation has the idea of what type of
software to build. This may come from clients who ask for a particular type of software,
or your organisation may decide that it has a problem that needs fixing or a need to
develop a particular type of software.
This stage will often include an in-depth study of the market or a client’s existing
systems and should include gathering as much information as possible on what’s
needed.
This stage can also include feedback from stakeholders. Stakeholders are anyone
who stands to benefit from the application and could include potential customers,
developers, subject matter experts and sales reps.
A feasibility study may also be conducted. This is a way of finding out whether it makes
sense to go ahead with the project. Depending on the type of software, a feasibility
study might look at issues such as whether the organisation will make enough profit to
justify going ahead with the development, whether they have enough employees and
expertise to complete the project, whether the software will be supported by existing
computer systems and whether the project can be completed within the given schedule
and budget.
Planning
In the planning stage, project leaders set the terms of the project. This includes
calculating labour and material costs, creating a timetable and schedule and creating
the project’s team and leadership structure.
The purpose of the planning stage is to clearly define the scope and purpose of the
project. This is when the project manager plots the course of the project and what the
team needs in order to complete it successfully. It also sets boundaries to help keep
the project from expanding or shifting from its original purpose.
36 © LCG 2021
Section 1: Understand the principles of coding
Design
The design phase models the way a software application will work. It will often include
consideration of the following elements:
• Architecture – the design will specify the programming language, industry practices,
overall design, and use of any templates.
• User interface – the design will include details about how customers will interact with
the software, and how the software will respond to input.
• Platforms – the design defines the platforms on which the software will run, such as
Apple, Android, Windows version, Linux, or gaming consoles.
• Programming – this includes methods of solving problems and performing tasks in
the application.
• Communications – this defines how the application will communicate with other
assets, such as a central server.
• Security – this defines the measures taken to secure the application and may include
SSL traffic encryption, password protection, and secure storage of user credentials.
Prototyping may also be a part of the design phase. A software prototype demonstrates
a basic idea of how the application looks and works. This can then be shown to
stakeholders for feedback or to raise funds to complete the project.
This phase may also include preparing system and software design documents. These
include information about each part of the software, such as the type and size of the
database, architecture diagrams and details on which technology used, details of the
interface, listing of error messages, etc.
Implementation/software development
This is the actual writing of the software and is the longest phase in the software
development lifecycle. A small project might be written by a single developer, while
a large project might be broken up into units or modules and assigned to different
teams. Project management tools are used to keep track of the progress of each team
and to help developers track changes to the code.
Workbook 1 37
Section 1: Understand the principles of coding
Testing
Deployment
In the installation or deployment phase, the application is made available to users. For
an app, this may be as simple as having users download a link from the organisation’s
website, or downloading an application onto a smartphone from a payment portal such
as Apple’s App Store.
However, deployment can also be a complex process. For example, if the software is
being used to upgrade a company-wide database, the deployment could take some
time and involve the use of technical teams.
The main part of the development cycle is now finished. However, users may discover
bugs that weren’t found during testing, or find that some part of the software is not as
functional as it could be. Or, the software may need to be upgraded from time to time
in order to work with new operating systems and devices. The software developer may
also want to add new features occasionally, to keep the software popular and up to
date. These ongoing issues will all need to be resolved and may involve launching a
new development cycle.
38 © LCG 2021
Section 1: Understand the principles of coding
Knowledge Activity: Design a graphic that illustrates the different stages of the
software development lifecycle.
The planning stage is important because the rest of the project will not make sense if
the overall scope is not set out first. This phase is also where schedules are made and
resources are allotted, and without this planning, it is easy for projects to go over their
deadlines and budget.
This is also where organisations decide exactly what it is they want to accomplish,
considering what the end user wants to achieve, who is going to use the system, what
needs to be inputted to get the required output and what data is required to output,
etc. This is to make sure that everyone working on the project has a clear vision of
what they want the finished product to do.
You wouldn’t buy a new car by putting on a blindfold and randomly choosing a car.
The same is true for software development. If a project is not planned correctly with a
clear understanding of what’s required, what time frames you are working to, the costs
involved and what resources you will need to get the job done, then the entire project
can be jeopardised.
From a client’s point of view, the planning stage allows them to make sure that the
time frames and costs are realistic and that the software will do what they need it to
do.
Workbook 1 39
Section 1: Understand the principles of coding
The implementation stage involves putting the project plan into action. In other
words, this is when the actual coding work is done. While working, coders will follow
certain predefined coding guidelines. They also use programming tools like compilers,
interpreters and debuggers to generate and implement the code.
However, this stage is not just about sitting down at a desk and coding – especially
when the program is a large one and many people or teams are involved. In fact, there
are different models for how to organise the process of software development. For
example, in the Waterfall model, the process is broken down into steps or phases, and
each step only begins once the previous step is complete.
In the Spiral Model, in contrast, a prototype is built first, then different versions are
developed with each version gaining new functions and receiving feedback from the
customer before the next version is started.
In the Big Bang Model, the software is developed all at once, with very little planning.
40 © LCG 2021
Section 1: Understand the principles of coding
This is normally only used with repetitive or small projects that have very little risk of
failure and where very few coders are involved.
In one of the most common models, the Agile model, the coding tasks are divided into
sections, each with its own schedule. The software is then built incrementally.
In the RAD (Rapid Application Development) model, a prototype is developed first,
and very little planning occurs before the start of writing the software. Customer
requirements are gathered using workshops or focus groups and early testing of the
prototypes and different versions. This feedback is then used to develop the later
versions.
Workbook 1 41
Section 1: Understand the principles of coding
Testing is one of the most important parts of the software development lifecycle.
It helps companies to identify all the bugs and errors in the software before it is
deployed. If software bugs are not resolved before deployment, they can cause
problems and slowdowns and this will have a negative effect on the developer’s
reputation. Trying to fix issues at a later stage can also end up costing a lot in lost time.
Testing is usually conducted by QA (Quality Assurance) engineers. The techniques and
procedures they use vary depending on the software development model, the stage of
the process and the objectives of the testing procedure.
Software testers usually break down software testing in four main phases, which are:
Unit Testing, Integration testing, System testing and User acceptance testing.
Unit testing
This is performed on individual, smaller components of the software. These units can
be as small as individual functions, code components and even classes, or as large as
single features of the software.
Integration testing
In integration testing, testers combine different software modules at once and test
these modules together. These tests are a prerequisite to making sure that the
integrated system is prepared for system testing.
System testing
System testing is the procedure where the collective systems that were used in
integrated testing are combined and tested as a single, complete system – the finished
product. Here, testers evaluate the functions of the software and also see whether it
meets all of the requirements. Specific testing procedures look at performance, load,
reliability and security of the integrated system.
42 © LCG 2021
Section 1: Understand the principles of coding
In user acceptance testing, customers use the software to see if it meets their
requirements. They can ask the development team to make further enhancements in
the product if it is needed. This is also called beta testing.
After the software has been tested and is accepted by the users, it is time to actually
install, or deploy, it. For small projects, such as apps, this stage may simply involve
making the software publicly available for users to download. However, for complex
projects, this may involve a number of different steps and processes, including
software release, installation, testing, deployment and performance monitoring. Steps
may include:
• Communicate new deployment to the users – for example, through marketing.
• Conduct training – for example, if a new database is being installed at a large
organisation.
• Perform data entry or conversion.
• Install the system.
• Post-deployment review – making sure the software works as it is supposed to and
whether any enhancements or updates are needed.
• Revise documents – all the relevant documents must be reviewed and updated for
any changes that took place during deployment.
Workbook 1 43
Section 1: Understand the principles of coding
This is the final stage of the software development life cycle. The maintenance stage of
the software life cycle allows individuals to check the performance of the software after
it is launched to see if it is all working correctly. This stage is very important as it:
• ensures that the system remains running at peak performance levels
• solves any software bugs/problems that arise
• customises the software to users’ needs as these change
• adds increased functionality to the system
The maintenance phase is very important, because it supports users of the software
with updates, new functionality and security patches. Without these, people will
stop using, and buying, the software. Security updates and patches are particularly
important, because breaches can be very expensive and have very bad consequences
for organisations, for example, if they allow a hacker to steal data. So, failing to support
software with frequent security updates will ultimately have a negative effect on the
reputation of the software developer.
This stage is also the longest of all the stages. The maintenance stage will last as long
as the software is in use. Because most software programs remain in use until they
become obsolete, this can take many years. For example, Microsoft Office 2010 was
supported until 2020 – that meant that the company was still issuing updates and
patches until that time.
44 © LCG 2021
Section 1: Understand the principles of coding
Summary
Workbook 1 45
Section 2: Understand terminology used in coding
In this section, we are going to start by learning some more basic coding terminology,
including CPU, RAM and Data. Then we will explore some common coding acronyms
and terms, such as WET and DRY coding and open and closed code. Finally, we
will look at some of the key principles used when writing code, including iterations,
collection, recursion, variables, functions, queues, stacks and lists.
The Central Processing Unit (CPU) is the control centre of the computer. The CPU is
made up of complex electronic circuitry that executes stored program instructions to
convert data inputs to information outputs. All computers, no matter what size, must
have a CPU. The speed of the CPU plays a large part in determining the power of a
computer. Each new generation of microprocessors features a more powerful CPU that
can execute instructions more quickly than the previous generation.
Computer memory refers to the area where data and programs are stored. Memory
is not part of the CPU, but the CPU constantly interacts with it. There are two types of
computer memory: primary and secondary. The primary memory is temporary and only
holds instructions and data for a program while the program is executing. Secondary
memory is the more permanent storage, such as that provided by hard drives and flash
drives. The CPU uses mostly primary memory for storing program instructions and data.
The CPU consists of two main parts: the control unit (CU) and the arithmetic and
logic unit (ALU). The control unit is responsible for moving instructions and data from
secondary storage into main memory so an instruction can be executed. The control
unit also moves the results of an instruction to secondary storage.
The ALU receives interpreted instructions from the CU and performs computations
using logic gates. These are electronic circuits that have one or more inputs and one
output. The output is determined using electronic logic, which is based on digital
switches called logic gates. Each input into the logic gate must be in the form of 0
(false) or 1 (true).
46 © LCG 2021
Section 2: Understand terminology used in coding
Logic gates use Boolean operators, such as AND, OR and NOT, and different types of
logic gates represent different Boolean functions. For example, the AND gate usually
has two inputs (A and B). Both Input A AND Input B have to be 1 (or ON) in order for
the output to be 1. Otherwise the output is 0. In the NOT gate, in contrast, there is just
one input. In a NOT gate, Input A has to be 0 (or OFF) in order for the output to be 1.
Otherwise the output is 0. A NOT gate is sometimes called an inverter.
Groups of logic gates are called registers. These are dedicated memory locations in the
CPU itself.
Data from the ALU is transmitted to the other parts of the CPU along an electrical
pathway called an internal bus. The internal bus has two main parts: a data bus and an
address bus. These work together to transfer data to a specific destination.
The CPU works in a four-step process. First, the instruction is fetched from memory.
Then the instruction is decoded by the processor, then the operation is performed, and
finally, the results are sent and written into memory. These steps are referred to as the
instruction cycle of the CPU.
The CPU uses a program counter to keep track of which instruction to fetch next. The
counter is the address of the memory location that holds the next instruction to be
executed. It’s stored in a register, which is a dedicated memory location in the CPU
itself.
Decode
Store
Workbook 1 47
Section 2: Understand terminology used in coding
Hard drives can store large numbers of files, but they tend to run relatively slowly.
This is because accessing hard drive files requires the drive to move its mechanical
read/write head back and forth and to wait for the spinning plate of the hard drive to
move into the correct position. In order to speed things up, computers use random
access memory (RAM). This is the computer’s short-term storage centre; it stores the
information your computer is actively using so that it can be accessed quickly. The
more programs your system is running, the more memory you’ll need. The RAM is
made up of registers. Because RAM has no moving parts, the files can be read very
quickly.
RAM works together with the hard drive, which provides the long-term storage, to
provide quick access to files that the computer is actively using. Unlike hard drive
memory, however, the data stored in RAM is erased when it is no longer being used,
such as when you reboot the computer or when another program needs the space.
48 © LCG 2021
Section 2: Understand terminology used in coding
PROGRAM
1. instruction
Primary Memory 2. instruction
Main Memory 3. instruction
RAM 4. instruction
5. instruction
6. instruction
Decode
Store
Workbook 1 49
Section 2: Understand terminology used in coding
We tend to think of data as any type of information. In IT, however, data usually refers
to information that is being processed or stored by a computer. This may be in the form
of text documents, images, audio clips, software programs or other types of data.
At its most basic, computer data is made up of a bunch of ones and zeros; this is
known as binary data. Ultimately, all computer data is in binary format. This allows the
data to be easily transferred from one computer to another.
The main purpose of a computer program is to collect and process data. A computer
can change what it does depending on the data that it has to work with. The data that
is used in a program is referred to as the data values. Data values can come from:
• a file, database or other piece of software
• another computer or device
• a hardware sensor such as a camera or microphone
• internal systems
• mouse movements and button clicks
50 © LCG 2021
Section 2: Understand terminology used in coding
In coding, the term ‘data type’ has a special meaning. The data type is a way of
classifying data that tells the computer how the programmer intends to use the data.
The data type is stored as ‘variables’. A variable can be thought of as a named storage
location where data is stored for use by a program. Data stored in a variable can be
retrieved using that variable’s name and may be replaced by assigning a new value.
Ultimately, all data stored on a computer is stored as strings of zeros and ones, called
‘bits’. The ‘type’ of a particular variable determines how many bits are used for that
particular data item, and how the bits are to be interpreted.
When programmers develop computer software, data types must be assigned and
applied correctly in order to guarantee an error-free program. The data type determines
which operations can be safely executed to develop, transpose and apply the variable
to another computation.
Data types and subtypes may be different in different languages. Here are some of the
most commonly supported data types.
Integral types
• As in maths, integral data types include all whole numbers.
• The bits of integral types are interpreted as powers of two. The right-most bit, known
as the least significant bit, represents the number of 1s. The next bit represents the
number of 2s; the next bit represents the number of 4s, etc.
• Particular languages define different integral types based on the number of bits
stored and whether or not the bits are interpreted as signed or unsigned (an unsigned
integer is a type of integer that can hold zero and positive numbers, and a signed
integer holds negative, zero and positive numbers).
Workbook 1 51
Section 2: Understand terminology used in coding
Characters
• Most modern computer languages store alphabetic characters (a, b, c, etc.) by using
a numeric code to represent each one.
• Because the number of characters that needs to be stored is usually quite large,
while the number of bits needed to represent each character is small, individual
characters are usually stored as 8-bit unsigned integers. (8 bits is one ‘byte’.) Another
common name for this very small integer type is char.
• The most common way to encode 8-bit chars is by using the ASCII code, which can
be found online at http://www.asciitable.com/. For example, the ASCII code for the
capital letter ‘A’ is 65.
• In order to support a wide variety of special symbols, such as those used in foreign
languages, mathematics, science, graphics or elsewhere, Java and some other
languages support wide characters (wchars), which have 16 bits instead of 8.
Character strings
• These are collections of characters, such as words or sentences. Most computer
languages have some way of representing character strings, as well as a library of
methods for manipulating those strings.
• A string can contain any sequence of characters, and characters may be repeated.
The number of characters in the string is called its length. For example, the string
“hello world” has a length of 11.
struct StudentData{
char *stu_name;
int stu_id;
int stu_age;
52 © LCG 2021
Section 2: Understand terminology used in coding
• Unions: these are similar to structures, except that they only reserve enough space
for the largest contained data item, which is then shared by all of the defined fields
within the union. For example, creating a union for a group of cars and their prices, in
C, might look like:
union car
{
char name[50];
int price;
};
• Classes: these are also very much like structures, except that in addition to data, they
also contain the functions associated with the data. For example, we can create a
bicycle class in Java:
class Bicycle {
private int gear = 5;
// behavior or method
public void braking() {
System.out.println(“Working of Braking”);
}
}
In this example, we created a class named Bicycle. It contains a field named gear and
a method named braking(). We can now create any number of bicycles using this class.
All the bicycles will share the fields and methods of the class.
Workbook 1 53
Section 2: Understand terminology used in coding
Knowledge Activity: Research more about the different data types and give
examples of each type.
Now that we know a bit about data, we can look at some of the different ways that
data is stored.
Hard disk
Data is copied from the computer’s main memory (random-access memory or RAM),
and then written to the hard disk using a mechanical device called the disk drive. Hard
disks are considered permanent, as they cannot be removed from the computer, unlike
other storage devices.
As we have already seen, this is a type of storage that is accessible by the computer’s
CPU. Any open programs or files on a computer are temporarily stored in RAM while
being used. However, any data stored in RAM is lost when the power is turned off. This
makes RAM totally unsuitable for long-term, permanent data storage.
54 © LCG 2021
Section 2: Understand terminology used in coding
This is a memory chip that you cannot change the contents of. It is often used to store
the start-up routines in a computer (e.g. the core processor software, the basic input/
output system, or BIOS).
These are all types of optical storage, which uses optics (lasers) to read and write data.
Binary data is stored as changes to the texture of the disc’s surface. As the disk spins,
a laser is either reflected (1) or not reflected (0) by the ‘bumps’ on the disk. Writable
disks have a reflective layer that can be changed by the laser in the computer.
Originally, compact discs were used only for music (and DVDs only for movies), but
in the late 1980s, they began to be used for computer data storage. They have now
largely been replaced by less cumbersome types of storage. Many modern computers,
especially laptops, no longer come with a disc drive, although they are more common
with desktop computers.
Also known as a thumb drive, pen drive, flash drive, memory stick, jump drive, and USB
stick. The USB drive is a solid-state storage devices which use NAND flash memories
to store data. The drive plugs directly into the USB port of a computer. Flash memory
is smaller, faster, more efficient and more durable than optical media like CDs and
DVDs. However, their storage capacity is generally limited, so they are primarily used
for storing and moving around smaller amounts of data, such as presentations.
SD cards are commonly used for storing data in devices such as digital cameras and
mobile phones. Although there are different sizes, classes and capacities available,
they all use a rectangular design with one side ‘chipped off’ to prevent the card from
being inserted the wrong way around.
Workbook 1 55
Section 2: Understand terminology used in coding
A solid-state drive uses NAND flash memory (millions of transistors wired in a series
on a circuit board) to store data. They are sometimes used in devices such as tablets,
high-end laptops and smartphones instead of a traditional hard disk drive. Because
they do not have mechanical moving parts, they have a faster read/write speed,
noiseless operation, greater reliability and lower power consumption than traditional
hard disk drives. The biggest downside is cost, as an SSD has lower capacity than a
similarly-priced HDD.
Cloud storage
Now that most users have multiple devices, cloud storage is becoming a common way
to store data. Many businesses now also use cloud storage, because it can cost less
and take up less space than having an on-site server. It is also useful for organisations
where employees work remotely. Cloud computing involves accessing services over a
network using a collection of remote servers (‘the cloud’). Once data is uploaded to the
‘cloud’ it can then be accessed anywhere and from any device.
Knowledge Activity: Think about your computer, phone or tablet use and
note some of the different ways that data is stored.
56 © LCG 2021
Section 2: Understand terminology used in coding
Units are the smallest segments or groups of code that can be maintained and
executed independently. A unit is always executed as a whole. A unit may be an
individual function, method, procedure, module or object.
Unit testing is a type of software testing where individual units of a software are tested.
The purpose is to make sure that each individual unit of the software code performs as
expected. Unit testing is done during the development (coding phase) of an application.
In coding, the acronym DRY stands for Don’t Repeat Yourself. This is a principle in
software coding or development where the main aim is to reduce the amount of
repetition in the code.
Workbook 1 57
Section 2: Understand terminology used in coding
if (isPermitted(currentUser)) {
//allow execution of deletePage
} else {
//block execution
}
Here, the permission is just checked once, which avoids duplication and
enables re-use of the code.
58 © LCG 2021
Section 2: Understand terminology used in coding
Code that is not DRY is often referred to as WET, or Write Everything Twice, Write Every
Time, We Enjoy Typing or Waste Everyone’s Time. These are all cheeky ways of pointing
out that when code is not DRY, it can involve a lot of repetition and wasted energy.
For example, suppose a developer or coder is asked to add a comment field on a form
in a web application. They could add the text string ‘comment’ to the label, the HTML
tag, a read function name, a private variable, database DDL, queries, etc. That would
be a WET approach.
A DRY approach would eliminate that redundancy by using a framework that reduces
or eliminates all those editing tasks except the most important ones.
Keeping your code DRY is most helpful in places where it is likely that changes will be
made frequently. Having DRY code means you only need to make those changes in a
few areas, rather than in many parts of the program.
DRY code also reduces the chance for error. For example, if a change needs to be
made to the code, and it is WET, then you will need to make the change in a large
number of places. If you forget to change one, then your program could crash, or may
not work, as a result.
However, there are times when WET code is useful. For example, if the code is likely
to differentiate later on in the program, then having WET code may make that future
change easier.
Code that is too DRY can also create a headache for the next coder who uses your
code, as they may have a hard time figuring out how the code is organised. It also
shifts a lot of the development work nearer to the beginning of the project, and this
could, in turn, have an impact on the overall project timeline, especially on a big project
where lots of coders are involved. Some coders find that focusing on making a code
very DRY can also kill creativity.
This is why there needs to be a balance between WET and DRY.
Workbook 1 59
Section 2: Understand terminology used in coding
In general, open source refers to any program that has source code (the fundamental,
underlying code of a program) available for use or modification by anyone. Open source
software is usually developed as a public collaboration and made freely available.
By ‘freely available’, we mean that the source code is not just free to access, it
can also be used by anyone to develop custom applications and distribute those
applications to others.
All of the people who use the code, work to improve it and share what they have
learned are the code’s ‘community’. For an open source program to succeed, it needs
to have an active community. This is because it needs to be constantly adapted to
changing circumstances and have new applications and features developed to make it
more useful to a wide range of people.
However, simply putting your code online for others to see doesn’t necessarily make
it open source. There are a few requirements for it to actually be considered open
source code. There must also be no restrictions on the distribution or use of the code,
although the licence can require improved versions of the software to carry a different
name or version from the original software.
Just because an open source code is free to use doesn’t mean that the person who
developed the code is working for free. Open source software programmers do often
charge money for the software that they create or improve. The term ‘free’ refers to
freedom from restrictions on making changes to the code, and not necessarily to the
price. However, many open source developers do make the software free to use, and
make money by charging users for software services and support.
This way, the software remains free of charge, which helps to build the community, and
the programmer makes money by helping others install and run it. Some employers
specifically hire programmers with experience working on open source software.
For closed source software, usability is a major point. The software developer generally
guarantees that the software has already been tested for particular uses. User
manuals are also provided for immediate reference and quick training, and support
services are available to help with any problems or questions.
Open source software often lacks these types of formal support services. However,
60 © LCG 2021
Section 2: Understand terminology used in coding
the global communities that develop around open source software mean that new
functions and capabilities are developed very quickly and efficiently. Much of the early
Internet was built using open source, like the Linux operating system and the Apache
Web server application, and anyone using the Internet today benefits from open source
software, even if they do not realise it.
Workbook 1 61
Section 2: Understand terminology used in coding
In contrast to open source code, closed source code is proprietary software distributed
under a licensing agreement only to authorised users. The agreement will usually
prohibit private modification, copying, sharing and republishing of the code. So, users
cannot look at or alter the code in any way. For non-programmers, this is the way most
software is acquired.
For example, if you want to create and use spreadsheets, you would purchase a
spreadsheet program like Excel. In exchange for the purchase price, you would get
a licence to use the program yourself, but that license would also prohibit you from
looking at or changing the code. So, you could only do exactly what the program was
created to do.
Some of the key differences between open source and closed source include:
• Cost – one of the main advantages of open source software is the cost, which is
often free. However, open software providers are also increasingly charging for extras
like add-ons, integration and support services.
• Service – open source software relies on a loyal and engaged online user community
to deliver support, often through forums and blogs. But this support often fails to
deliver the high level of response that many users, especially business users, expect.
In contrast, closed source programs usually come with a great deal of ongoing service
and support. This is a key selling point for users with little or no technical skills.
• Innovation – open source software provides a large amount of flexibility and freedom
to change the software without restriction. However, some open source software
struggles to attract a large-scale community for research and development.
The inability to view or change the source code in closed source software also adds
to the security and reliability of this software. Closed source software can also have
its own dedicated communities that share ideas and strategies through forums and
surveys.
• Usability – open source software is usually not tested or reviewed by usability
experts, and it may not come with user guides.
For closed source software, usability is a main selling point, and user manuals are
provided for immediate reference and quick training. Most closed source software
also comes with dedicated support services, such as a helpline.
• Security – open source software does not have the same security as closed source
software, which has been developed in a controlled environment. Because open
source software is not always peer-reviewed or validated, a programmer can, for
example, embed a backdoor Trojan into the software.
62 © LCG 2021
Section 2: Understand terminology used in coding
Workbook 1 63
Section 2: Understand terminology used in coding
Collections framework
64 © LCG 2021
Section 2: Understand terminology used in coding
Java also provides a set of standard collection classes that implement the
Collection interfaces. Some of the classes provide full implementations that can
be used as-is and others are abstract class, providing skeletal implementations
that are used as starting points for creating concrete collections.
Some standard collection classes include AbstractCollection, which
implements most of the Collection interface, and AbstractList, which extends
AbstractCollection and implements most of the List interface.
Workbook 1 65
Section 2: Understand terminology used in coding
The control flow is simply the order in which the computer executes statements in a
code.
When a code is run, it moves in order from the first line in the file to the last line,
unless the computer runs across instructions that change the control flow, such as
conditionals and loops.
For example, imagine a script used to validate user data from a webpage form.
However, if, for example, the user leaves a required field empty, the script needs to
prompt them to fill it in. To do this, the script uses a conditional structure, such as if...
else, so that a different code executes depending on whether the form is complete or
not:
if (field==empty) {
promptUser();
} else {
submitForm();
}
This script might be inside a function that runs when the user clicks the Submit button
for the form. If a field is empty, it executes the instruction to prompt the user to fill it in;
otherwise, the script executes the command to submit the form.
There are different types of control flow statement, including:
• Sequencing (do this THEN this THEN this ...) – this is the most basic control flow. It
refers to executing statements one after another.
• Selection (if, unless, switch, case, ...) – this chooses one of several alternatives.
• Iteration (for, while, repeat, until, ...)
• Procedural Abstraction (subroutine call)
• Recursion (this involves defining the problem in simpler terms)
• Nondeterminacy (do this OR this OR ...that is, choose one arbitrarily or randomly)
• Concurrency (do multiple things at the same time)
66 © LCG 2021
Section 2: Understand terminology used in coding
Example: Selection
In this example, an ‘if’ statement is used to order the control flow (in Java, C, C++,
JavaScript):
Some languages have a syntax that manages to avoid all those ‘else-ifs’. For example,
Perl and Ruby have an UNLESS statement.
This algorithm will repeat step 4 until the bread is buttered. This saves us the time of
writing steps 2 and 3 out over and over.
Iteration, or ‘looping,’ allows us to simplify an algorithm by stating that we will repeat
certain steps until told otherwise. This makes designing algorithms quicker and simpler
because they don’t have to include lots of unnecessary steps.
There are two general ways in which programs can iterate or ‘loop’: count-controlled
loops and condition-controlled loops. Each type of loop works in a slightly different way
and produces different results.
Workbook 1 67
Section 2: Understand terminology used in coding
Count-controlled loops
These are used when you know in advance how many iterations (repeats) will be
needed. In programming, count-controlled loops use FOR statements.
For example, in Python, the FOR statement determines the starting point of the
iteration, and range states how many times the program will iterate. So, a program in
Python for adding up five inputted numbers might look like:
With each iteration, 1 is automatically added to the value of ‘count’. The program
keeps iterating as long as the value of ‘count’ is in the range specified in the loop (in
this case as long as ‘count’ is in the range 0 to 5). Once it reaches the end of the range
(5 iterations), the iteration stops. To have a different number of iterations, the value ‘5’
would simply have to be changed to a new number.
Condition-controlled loops
68 © LCG 2021
Section 2: Understand terminology used in coding
This algorithm would keep iterating, or repeating, until the password is entered
correctly. In this case, a condition-controlled loop is used because there is no way of
knowing in advance how many times a password will need to be entered before it is
correct.
In coding, condition-controlled loops use ‘while’ statements.
Now, consider this simple algorithm for adding up a series of inputted numbers:
1. Set the total to 0.
2. Set more numbers to ‘yes’.
3. While more numbers = ‘yes’, repeat these steps:
a. input a number
b. add the number to the total
4. Ask ‘Any more numbers? Yes/No’.
5. Print the total.
This algorithm would keep iterating until the answer in Step 4 is ‘No’. In other words,
it will continue to iterate WHILE there are more numbers to add. A condition-controlled
loop is used because there is no way of knowing in advance how many more numbers
will need to be entered before the user wants the algorithm to stop.
In Python, the code for this might look like:
total = 0
answer = “yes”
while answer == “yes”:
number = int(input(“Type in a number: “))
total = total + number
answer = input(“Any more numbers? yes/no”)
print(“The total is: “) print(total)
Workbook 1 69
Section 2: Understand terminology used in coding
Note that if ‘no’ is entered in answer to the question “Any more numbers?” then the
condition in line 3 would never be met. The program would then skip all the code
within the iteration and move on to the last line.
Many languages also allow you to construct iterations or loops that loop through items
in a collection, such as an array, list, set, string, lines in a file, files in a folder, etc.
Many languages also give you the opportunity to modify or change loop behaviour. For
example, they allow you to:
• completely break out of the whole loop using commands such as break (C, Java,
Ruby, JavaScript), exit (Ada, Modula), last (Perl)
• immediately abandon the rest of the current iteration and start the next iteration,
using commands such as continue (C, Java, JavaScript) or next (Perl, Ruby)
• start the current iteration over, such as with the command redo (Perl, Ruby)
• start the entire statement over from the very beginning using commands like retry
(Ruby)
70 © LCG 2021
Section 2: Understand terminology used in coding
count = 1
while count!= 100:
print(count)
count += 2
... continued
Workbook 1 71
Section 2: Understand terminology used in coding
continued....
At first glance, this program seems to be accurate, but because the count
starts at 1 and goes up by 2s (e.g. 3, 5, 7, 9, etc.), the condition ‘count does
not equal 100’ is always true (because the count will go from 99 to 101 –
skipping 100), so the iteration will occur infinitely.
Infinite loops like this can be a problem, because the program gets stuck
repeating a section of code over and over. However, infinite loops can be useful
if you want to ensure that a program does continue to run indefinitely. For
example, a program to control the timing on a traffic light could use an infinite
loop to make sure the light continues to cycle.
Recursion is the process of defining a problem (or the solution to a problem) in terms
of (a simpler version of) itself. The idea is to break a problem down in terms of one or
more smaller problems, and then add one or more base conditions that will stop the
recursion.
For example, an algorithm for “find your way home” might look like:
1. Are you at home (true/false). If true then stop moving.
2. Take one step in the direction of home.
3. Repeat until 1 is true.
Here, the solution to finding your way home takes three steps. First, we check to see
if we are at home and we don’t go home if we are already home. Secondly, we do a
very simple action that makes our situation simpler to solve. Finally, we redo the entire
algorithm.
You can see from this that a recursion is similar to an iteration – a recursive function is
one that calls itself.
72 © LCG 2021
Section 2: Understand terminology used in coding
The base case section describes the solution to the simplest possible problem. For
example, the base case in the problem “find the largest number in a list” would be
if the list had only one number. The base case in the algorithm above is if you are
already at home.
The “work toward base case” section is where the problem is simplified or broken
down into steps. For example, a list is divided into two parts. In the algorithm above,
the “work toward base case” is to take a step. The “recursive call” section is where
the algorithm repeats the work until a condition is met. In the algorithm above, it is to
take one step at a time until the condition of the base case (“Are you at home”) is met
(“yes”).
There are different types of recursive algorithms. The one above is a tail recursion. In a
tail recursion, the very last statement is the one that calls the recursive algorithm.
Example: Recursion
Here is an example of an algorithm (in Python) that uses a recursive function to find
the factorial of an integer (the number 3). The factorial of a number is the product of
all the integers from 1 to that number. For example, the factorial of 6 (written as 6!) is
1 x 2 x 3 x 4 x 5 x 6 = 720.
def factorial(x):
“””This is a recursive function
to find the factorial of an integer”””
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print(“The factorial of”, num, “is”, factorial(num))
Workbook 1 73
Section 2: Understand terminology used in coding
In this algorithm:
• The base case is x==1 and factorial () is the recursive function.
• If x does not = 1, then the algorithm will conduct the work towards the base case:
return (x * factorial(x-1)).
• This will repeat until x=1, after which the algorithm will print the output: The factorial
of 3 is 6.
This algorithm will recursively call itself by decreasing the number. Each function
multiplies the number with the factorial of the number below it until it is equal to one.
To see what this looks like a bit more clearly, we can expand the recursive call to show
each of the three recursions:
X = factorial (3)
Def factorial(n):
in this recursion 1 is returned – the
if n == 1: recursion stops because the base
return 1 condition, n==1, is met
else:
return n * factorial (n-1)
74 © LCG 2021
Section 2: Understand terminology used in coding
Stacks and queues can be thought of as rules for controlling data. They are dynamic,
linear arrays where you can order the way that data is inserted or deleted.
Stacks
There are two main functions associated with stacks: push is when you insert items
onto the ‘top’ of the stack; pop is when you retrieve the topmost item of data on the
stack. This is why the structure of a stack is referred to as LIFO – last in, first out.
Some basic operations that allow us to perform different actions on a stack include:
• Push – add an element to the top of a stack.
• Pop – remove an element from the top of a stack.
• IsEmpty – check if the stack is empty.
• IsFull – check if the stack is full.
• Peek – get the value of the top element without removing it.
Stacks are widely used in almost every aspect of computer design. Some common
uses of a stack are:
• To reverse a word – put all the letters in a stack and pop them out. Because of the
LIFO order of stacks, you will get the letters in reverse order.
• In compilers – compilers use the stack to calculate the value of expressions like 2 +
4 / 5 * (7 - 9).
• In browsers – the back button in a browser saves all the URLs you have visited
previously in a stack. Each time you visit a new page, it is added on top of the stack.
When you press the back button, the current URL is removed from the stack, and the
previous URL is accessed.
Workbook 1 75
Section 2: Understand terminology used in coding
76 © LCG 2021
Section 2: Understand terminology used in coding
Queues
A queue, in contrast, works like waiting in line to buy a movie ticket. The first person
in the line is the first to be served. So, say 100 pieces of data come into a single
processor. Number 1 will be processed first, then 2, then 3, and so on. This is referred
to as a FIFO structure – first in, first out.
Queues allow operations such as:
• Enqueue – add an element to the end of the queue.
• Dequeue – remove an element from the front of the queue.
• IsEmpty – check if the queue is empty.
• IsFull – check if the queue is full.
• Peek – get the value of the front of the queue without removing it.
So, why would a coder use a stack or a queue? They are tools used to complete a
certain task. For this reason, they are usually built on top of other structures to create
an overarching framework. For example, a queue might be built on top of a linked list.
Workbook 1 77
Section 2: Understand terminology used in coding
Lists
Lists are another type of data structure. They are used in functional programming
languages to store a collection of similar data items. They are similar to the use of
arrays in object-oriented programming. A list allows large amounts of information to be
easily referenced and moved around a programme.
The way to write data into a list varies from language to language. The values stored in
a list can be changed, added or removed from the list as the program proceeds.
# list of integers
my_list = [1, 2, 3]
A list can also include another list. This is called a nested list:
# nested list
my_list = [“mouse”, [8, 4, 6], [‘a’]]
78 © LCG 2021
Section 2: Understand terminology used in coding
A variable can be thought of as a sort of box that a computer uses to store the
information that is input. The value held in that box can change or ‘vary’ and a program
can use as many variables as needed. For example, if you are calculating the perimeter
of a square (which you do by adding up the length of each side), you might use a
variable (SIDE) to stand for the length of a side. Then, if you want to calculate the
perimeter of a different square, you can simply change the value of the SIDE variable.
Variables are a key element of programming. They are used for calculations, for storing
values for later use, in decisions and in iteration. All variables are made up of three
parts: a name, a type and a value.
How variables are used is similar across programming languages. Typically, the
variable is on the left, followed by an equal sign, followed by the item or items being
assigned. For example:
number = 10
The variable name is “number” and it has been assigned the value 10. You can also
assign variables as text, for example:
website = bbc.com
The variable name is “website” and it has been assigned the value bbc.com
Variables can be used for all types of reasons – to store numbers, to store text, to
store complex types of data, etc.
Workbook 1 79
Section 2: Understand terminology used in coding
A function is a small section of code that performs a specific task. The function
performs the task and returns a value to the main program.
A function can be repeated throughout a program, making it simpler and easier to write
the code. This is because if something needs to be changed in a function, it only needs
to be changed once, within the function code. This change will then appear wherever
the function is used in the program. Otherwise, the code would have to be changed
every time it appears in the program.
Example: Function
Here is an excerpt from a Python program that simulates the throwing of a dice:
import random sides = int(input(“How many sides does the dice have?”))
number = random.randint(1,sides)
print(number)
80 © LCG 2021
Section 2: Understand terminology used in coding
Now, if you were writing a program for a role-playing game, you could call (run) the
“import random sides” function at any point in the game where a die or dice need to
be thrown. This would save you from having to type in the same code every time.
Workbook 1 81
Section 2: Understand terminology used in coding
In coding, the term operand is used to describe any object that is being worked on by
an operator. An operator is a symbol that tells the compiler or interpreter to perform
a specific mathematical, relational or logical operation and produce final result.
For example, in ‘3 + 5’ the ‘3’ and ‘5’ are the operands and the plus symbol is the
operator. The entire calculation 3+5=8 is an operation.
In many programs, the arithmetic operators are similar to those used in maths, where
the + operator adds two numbers, the – operator subtracts, etc. However, the =
operator generally means ‘assign a value to a variable’.
For example, in Python, the += operator adds a value to an existing value stored in the
existing a variable. So, a+=b first adds the value contained in variable a to the value
contained in variable b. The result is then assigned to a new value stored in variable a.
Other operators, called equality operators, are used to compare values. For example, in
Python, the equality operator == compares two operands and will return the value True
if both are equal in value, and False if they are not.
Another category of operator are logical operators, such as AND, OR and NOT. For
example, the logical operator AND will evaluate two operands and return True if both
operands are True. Otherwise the AND operator will return False. The OR operator will
return the value True if either operand is True.
The logical NOT operator will return the inverse Boolean value of a single operand,
turning True to False and vice versa. This is useful, for example, when toggling between
True and False on different iterations of a loop.
Some programming languages such as Java and C++ have a ‘ternary’ operator (?:)
that evaluates an expression for a True or False condition and then returns one of
two specified values depending on the result of the evaluation. Python has a similar
operator, called a conditional expression, that uses the keywords if and else. These can
be used to assign the maximum or minimum value of two variables to a third variable.
82 © LCG 2021
Section 2: Understand terminology used in coding
Summary
Workbook 1 83
Section 3: Understand coding design principles
In this section, we will begin by finding out what is meant by imperative, declarative,
functional and object-oriented coding. We will also look at some other coding types and
their advantages and disadvantages. We will then move on to explore compiled and
interpreted code, including their advantages and disadvantages. Finally, we will explore
pure and impure functions and parallelism.
Imperare is the Latin word for ‘command,’ and imperative coding is a programming
paradigm (a coding paradigm is a way of thinking about software coding based on
a fundamental principle) where a program is made up of a clearly-defined series of
instructions to the computer. The code for imperative coding languages uses a series
of step-by-step commands that tell the computer what to do, often using control
structures like loops.
Imperative coding languages are usually easy to understand, because you can follow
the code step-by-step. However, this also means that imperative languages can be
quite long and require a lot of repetitive coding. Some of the best-known imperative
coding languages include Fortran, Java, Pascal, C, C++, BASIC, Assembler, COBOL,
Python and Ruby.
The different imperative languages can also be broken down into three types,
depending on how they are coded: structured, procedural and modular.
The structured programming style uses specific control structures, such as sequences,
selection and iteration in order to simplify the coding and create ‘shortcuts’.
In the procedural approach, the tasks that the program is being asked to perform are
divided into smaller sub-tasks. These sub-tasks are then individually described in the
code. This creates modules that can also be used in other parts of the program.
Modular programming takes this one step further by designing, developing and testing
the individual program modules independently of each other. The individual modules
are then combined to create the completed program.
84 © LCG 2021
Section 3: Understand coding design principles
You can start by defining the list of passwords that you want to be rejected:
const passwords = [
“123456”,
“password1”,
“admin”,
“mypassword”,
];
Workbook 1 85
Section 3: Understand coding design principles
86 © LCG 2021
Section 3: Understand coding design principles
Here, the list of longPasswords is defined (or ‘declared’) as the list of passwords
filtered for only those that are greater than or equal to 9 characters.
In order to understand functional coding, we need to first explain some basic terms
used with this type of programming. A pure function is a function that, when given the
same inputs, always returns the same output, and has no side effects. (A side effect is
a change in the program’s state. A function has a side effect if there is an observable
effect besides returning a value.) Pure functions are the simplest reusable building
blocks of code in a program.
Functional coding is a programming paradigm where software is constructed using
pure functions.
Immutability is another important principle of functional programming. This means that
once you’ve defined a variable, you can’t change it (although you can create a new
one). Another important principle of functional programming is that functions are ‘first
class entities’. That means that there are very few restrictions about where you can use
a function.
Functional programming is also declarative rather than imperative. So, it uses fewer
loops and conditions and more reusable functions and recursions. Because of this,
functional code tends to be more concise, predictable and easier to test and debug
that imperative or object-oriented code, although it can also be more difficult to learn.
It also tends to be a more efficient and mathematical approach to writing code. Clojure,
PureScript and Elm are types of functional languages, although some more common
languages, such as C++, Ruby and Python use some functional elements.
Because functional languages are based on mathematical principles, they are often
used as research tools in fields such as language development, to solve or prove
mathematical theorems and in some commercial projects.
Workbook 1 87
Section 3: Understand coding design principles
Languages like Java, C++, Ruby and Python are object-oriented. Object-oriented coding
is a programming paradigm that structures a program into simple, reusable sections
of code, called classes. These classes are then used as a sort of blueprint to create
more specific ‘objects’. An object is simply a collection of data (variables) and methods
(functions) that act on those data.
For example, we can think of class as a detailed sketch of a car. It contains all the
details about the engine size, shape, etc. that we need to build the car. Based on these
details, we can build the car. Car is the object. We can then use this blueprint (the
class) to create many objects (cars).
Classes are often used to represent broad categories, such as Vegetable or Car, which
share attributes. The classes define the attributes of the category (so, for car, the
attributes might include colour, year, engine size, number of doors, etc.), but not the
value of the attribute for a specific object (red, blue, number of cc’s, 4-door, etc.).
88 © LCG 2021
Section 3: Understand coding design principles
Classes can also contain ‘methods’, which are defined within the class and perform
an action on a specific type of object. For example, the Car class could have a method
called repaint that changes the colour attribute of the car.
Classes can also be used to create individual objects that represent specific examples
of the class, such as mycar or luxurycar. Each of these objects would have unique
values of the properties that are defined in that class.
For example, say we created a class, Car, to contain all the properties a car must have,
such as colour, engine size, brand and model. We then create an object, mycar, to
represent a specific car. We could then set the value of the properties defined in the
class to describe mycar, without affecting any other objects or the class template. This
class can then be used to represent any number of cars.
Some of the main principles of object-oriented programming include encapsulation,
abstraction, inheritance and polymorphism.
Encapsulation
This means that all the properties and methods of an object are kept free from
interference by other objects. In each object, we can have both private and public
variables and methods. Private variables and methods cannot be called or used by
other objects, whereas public ones can.
For example, let’s look at a role-playing game with a hero. The hero will have several
variables, such as name, outfit, hair colour. The hero may also have methods like
attack, walk, run and talk. These would be private variables and methods that can’t be
modified by other objects in the game. So, the hero would always be able to walk, run,
talk, etc.
The hero may also have variables such as health and methods such as damage. These
would be public and so could be modified by other objects. For example, an enemy
object (e.g. sword) would be able to call this method (damage) and change the value of
the variable (health) when it attacks the hero.
Abstraction
Inheritance
Similar objects can share some code or logic, but not be exactly the same. Inheritance
allows the logic in one object, called the parent, to be carried to another object, called
the child.
For example, in our game, there can be many enemies. These enemies can all be child
objects of a parent enemy object. Each enemy may have similar attributes, but also
different attributes, like outfit or weapon.
Polymorphism
Inheritance enables a parent object to define a child object. But what happens if the
child has a different way of implementing a method? Polymorphism is a way to solve
this problem by allowing us to use an object exactly like its parent, but have separate
methods.
For example, in our game, each enemy may have an Attack method that it inherits from
the parent, but with slight differences.
90 © LCG 2021
Section 3: Understand coding design principles
Imperative, declarative and OOP are not the only types of coding paradigms. Here are a
few other common coding paradigms.
Event-driven programming
Event-driven programming is a way of programming that uses ‘events’ as the basis for
developing the software. These events can be a user action, like clicking on a specific
button, picking an option from the drop-down menu, typing text into a field, etc. Events
can also be system-generated, such as a program loading. An event-driven application
is designed to detect these events as they occur, and then use an appropriate event-
handling procedure.
Event-driven programs can be written in any programming language, although
some languages (such as Visual Basic) are specifically designed to use event-driven
programming, and provide an integrated development environment (IDE) that includes
a large selection of built-in objects and controls which can respond to a range of
events. Almost all object-oriented and visual languages, such as C++ and Java, support
event-driven programming.
Workbook 1 91
Section 3: Understand coding design principles
Multi-paradigm coding
92 © LCG 2021
Section 3: Understand coding design principles
One of the major advantages of OOP is its reusability. The use of classes and objects
allows you to write sections of code once and then reuse them as many times as you
need – new objects can be easily created with small differences from existing ones.
OOP also allows you to use data hiding and abstraction so that only the necessary data
is visible. This helps to maintain the security of the code and the data.
Disadvantages of OOP include the fact that OOP programs tend to be much larger than
other types of programs, and they require a lot of work to create. This large size also
means that OOP programs are slower to execute than other programs.
In general, the use of pure functions makes these programs easier to test and leads
to fewer bugs. Functional code also tends to be easy to understand and to debug and
test. This is because the programs are written in a more concise way.
However, while writing pure functions is relatively easy, combining them into a
complete application or program can be quite difficult. The use of advanced maths
terminology in functional programming can also be intimidating, especially for
beginners to coding. Those just starting out may also struggle to understand recursion.
Workbook 1 93
Section 3: Understand coding design principles
The main advantages are the simplicity and ease of coding and using procedural
programs. The fact that the same code can be re-used at different places in the
program without copying it or re-writing it also makes procedural programming efficient
and relatively fast to write, as well as making it easy to keep track of the program flow.
Procedural programming is also very useful for general-purpose programming and for
beginners to coding; there are a large number of books and courses available using
tested algorithms, which make it easier to learn.
However, procedural languages do not offer security for the data they contain, and it
can be difficult to relate them to real-world objects. The difficulty of creating new data
types also reduces the ability to add extensions.
94 © LCG 2021
Section 3: Understand coding design principles
Workbook 1 95
Section 3: Understand coding design principles
In order to create a new software program, the coder first writes the program in a
source code. This is a specific programming language, such as C or Java. The source
code files are written and saved in a text-based format, which is easy to read and edit
by humans. However, the source code cannot be read and used by the computer. In
order for the computer to run the program, the source code needs to be converted into
machine code – which can be read by the computer. This process is called compiling.
Another method for translating source code into a language the computer can
understand is to use an interpreter. As the program proceeds, the interpreter translates
its functions and objects into ‘bytecode’. This bytecode can then be executed using the
program’s bytecode interpreter, also known as a virtual machine. Python, JavaScript
and Ruby are examples of languages that use interpreters.
96 © LCG 2021
Section 3: Understand coding design principles
An interpreter translates source code into object code one instruction at a time. It is
similar to a human translator translating what a person says into another language,
sentence by sentence. The resulting object code is then executed immediately. The
process is called interpretation.
Workbook 1 97
Section 3: Understand coding design principles
Compilers work in multiple steps – first they analyse the syntax and generate an object
code, which represents the program’s functions and statements in binary machine
code format. The compiler then combines the object code into a single binary machine
code file that can be executed by the computer.
In general, there are six stages of compiling a programme:
• lexical analysis
• symbol table construction
• syntax analysis
• semantic analysis
• optimisation
• code generation
During this stage, the compiler splits source code up into smaller pieces called
lexemes. For example, in the command:
String greeting = “hello”;
After splitting code into lexemes, the compiler creates a sequence of tokens. A token
is an object that describes a lexeme. It gives information about the lexeme’s purpose,
such as whether it’s a keyword, variable name or string literal. It also stores the
location data for the lexeme’s source code.
98 © LCG 2021
Section 3: Understand coding design principles
Syntax analysis
During syntax analysis, the compiler uses the tokens to create a representation of the
logical structure of a programme. This representation is called an abstract syntax tree
because it represents the syntax of the programming language as a hierarchical, tree-
like structure. This tree looks similar to syntax trees that linguists use to show how
human languages are related to each other.
The tree focuses on the rules of the language. It is hierarchical, which means the
individual programming statements are broken down into their parts.
In this phase, the compiler also checks the grammatical structure of the source code
and whether its syntax is correct. If there are any errors, it returns an error message
and the coder will need to correct these.
while b ≠ 0
if a > b
a := a − b
else
b := b − a
return a
Workbook 1 99
Section 3: Understand coding design principles
Statement sequence
while return
condition
compare variable
body name: a
op: ≠
variable constant
branch
name: b name: 0
compare
assign assign
op: >
Semantic analysis
In this stage, the compiler uses the abstract syntax tree to detect any semantic errors.
Examples of these include:
• assigning the wrong type to a variable
• declaring variables with the same name in the same scope
• using an undeclared variable
• using an incorrect variable name
Again, any errors that are found will need to be fixed by the coder. Once everything is
error-free, the compiler produces an annotated abstract symbol tree that describes the
values of its attributes.
Optimisation
In the optimisation stage, the compiler uses different methods to increase the
efficiency of the code. This might include processes such as:
• Dead code elimination, where the compiler gets rid of code that is never executed, or
if executed, its returned result isn’t used.
• Loop fusion – executing, in one loop, operations from the adjacent loops that have
the same iteration conditions.
• Instruction combining – instructions realising similar operations are combined into
one. For example, x = x + 10; x = x – 7; could be replaced with x = x + 3.
Code generation
Finally, the compiler converts the optimised intermediate code into machine code that
has same meaning as source code.
During the compilation process, the compiler may also generate one or more
intermediate codes, which we can think of as a program for an abstract machine. This
intermediate code is machine-independent. In other words, it will work on different
types of computer.
Workbook 1 101
Section 3: Understand coding design principles
Just like a compiler, an interpreter takes a high-level language (the source code)
and converts it into machine code. However, instead of translating everything and
then running the completed code, the interpreter translates a single line or section
of code at a time. Once it has finished translating that section, it will execute (run) it
immediately.
Interpreters usually use one of the following strategies:
1. Analyse the source code of each section, using tokens and a code tree, and execute
the instructions immediately.
2. Translate the source code into a more efficient intermediate form, similar to how
compilers optimise code, and then immediately execute this intermediate form.
3. Execute stored precompiled code that has been made by a compiler, which is part of
the interpreter system.
Usually, if the interpreter cannot run the code of a particular section because of an
error, it will return an error message and the coder will need to correct the code before
the interpreter can move on.
Workbook 1 103
Section 3: Understand coding design principles
Predictable means that identical inputs will always return identical outputs, no matter
how many times a pure function is called. In other words, a pure function can be run as
many times as we want, and as long as the inputs remain constant, the same output
will always be produced.
A side-effect is any operation your function performs that is not related to computing
the final output. Side effects can include things like:
• modifying a global variable
• modifying an argument
• making HTTP requests
• reading/writing files
Workbook 1 105
Section 3: Understand coding design principles
For example, here is a very simple pure function for adding two numbers:
// PURE FUNCTION
const pureAdd = (num1, num2) => {
return num1 + num2;
};
In this example, we can see that every time the input for num1 is 5 and the input for
num2 is 5, the output will be 10.
Pure functions are the basis of functional programming.
For example, here is an impure function that is similar to the pure function in the
example above:
//IMPURE FUNCTION
let plsMutateMe = 0;
const impureAdd = (num) => {
return (plsMutateMe += num);
};
This is also a function that adds two numbers. But here, one of the numbers
(plsMutateMe) changes randomly. So, even if the input (5) remains constant every
time, the output will be different each time.
So, why isn’t every function pure? We actually need impure functions because many
of the useful things that applications do require using impure functions. For example,
things like saving and retrieving information to a database and making http requests
are impure functions. However, coders do attempt to maximise the number of pure
functions they use. This is because pure functions tend to make code easier to test
and to understand.
Workbook 1 107
Section 3: Understand coding design principles
Dependency refers to when a piece of software relies (is dependent) on another piece
of software. In other words, if Code A requires Code B to be able to run, then we would
say that Code A is dependent on Code B – Code B is a dependency of Code A.
Dependencies exist because some sections of code or entire programs need to use
features in other code or programs.
Having dependencies for your code reduces the flexibility of your code and can even
completely ruin your program. For example, if your code relies on a dependency that
was written by someone else and that dependency has a bug that also affects your
code.
There have been cases where an organisation based their application around a
dependency or external service that shut down suddenly, causing them major losses.
Remember that pure functions cannot have any side effects. One way to make
functions with side effects into pure functions is to use dependencies. In this approach,
any side effects are placed into function parameters. They can then be treated as
some other function’s responsibility. This is called dependency injection. It can be
thought of as a sort of loophole for making impure functions pure.
Pure functions are important because there are many benefits to making functions
pure. Here are some of the most important.
Pure functions can be memoised. This means that their output (when given certain
inputs) can be cached (saved) when the function first runs, so that the function doesn’t
have to run again the next time those inputs are needed. This can help optimise
performance. Memorisation is possible with pure functions because every time you use
the same input, you get the same output.
Because the output of a pure function depends only on the input, pure functions are
easy to combine together into simple solutions. For example, you’ll often see functional
code written as a chain of function calls, like this:
val x = doThis(a).thenThis(b)
.andThenThis(c)
.doThisToo(d)
.andFinallyThis(e)
Here, a, b, c, d and e are all pure functions. Because each one is pure, the outputs of
any one function will not have any unpredictable effects on the other functions.
Workbook 1 109
Section 3: Understand coding design principles
Parallelisation is when a piece of code is broken down into a series of smaller steps,
which are then executed at the same time (in parallel).
If there is no data dependency between two pure expressions, then they can be
performed in parallel and cannot interfere with one another.
You can see an example of what that means in this code:
val x = f(a)
val y = g(b)
val z = h(c)
val result = x + y + z
Because there are no data dependencies between the first three expressions, they can
be executed in any order. The compiler or interpreter can run them in parallel, and only
merge their values in the final expression. This will save time.
Normally, software breaks a problem down into a series of instructions, which are
executed one after another in order, using a single processor. Parallelisation is a way of
speeding this up by breaking the problem into steps that can be executed at the same
time (in parallel) on different processors.
A non-computing example might be trying to put together a huge jigsaw puzzle. If
you were doing this alone, you might start with the corners. Then, once all the corner
pieces had been found, you would move onto the edges, then the middle, etc. But you
can speed this up if you grab a couple of friends to help. One of them can find all the
corner pieces, at the same time as another one finds all the edge pieces, and a third
works on the middle.
From a hardware perspective, almost all computers today are parallel. For example,
they have multiple processors, floating-point, graphics processing units, etc. Networks
are used to connect multiple stand-alone computers (nodes) to make larger parallel
computer clusters. Parallel computing allows more complex problems to be solved
much faster.
Workbook 1 111
Section 3: Understand coding design principles
Summary
Workbook 1 113
Section 4: Extension activities
Further your knowledge and understanding of the topics in this workbook by completing
the following extension activities.
Extension Activity 1: Choose a coding language that you are familiar with or
interested in, such as Python, Java or C and research how to write a simple
program in that language.
Workbook 1 115
Section 4: Extension activities
Workbook 1 117
DEFENSIVE PROGRAMMING