The Principles of Programming

Author: Theodore Odeluga

This is a Node command line project and Node.js can be downloaded from here

Instructions for running a command line program with Node.js can be found here

The source files for this project can be downloaded from here

Computer programming is essentially the act of giving a computer a set of instructions.

One might consider whether the same is simply accomplished by say, clicking a button on a user interface.

The answer is “yes” to both - more or less (with the caveat that before the computer “knows what to do” (in response to that button click), the programmer first needs to tell the computer how to respond to it).

Either way, the principles of programming boil down to instructions – or specifically – providing different types of instruction.

In the course of this article, we’ll be looking at some examples which break down the core elements of software development.

The aim is to not only help you arrive at an understanding of the fundamentals, but to start you on your own journey in this fascinating and compelling area.

JavaScript is the language we’ll be using throughout the article. It’s been selected not just for its relative simplicity but also, it’s ubiquity; it runs in every browser – all of which of course are free to download and install.

Let’s begin.

I think the first thing to do is clarify and differentiate the meaning of certain key terms.

You’ll often hear the phrases “computer programming”, “programming”, “software development” and “software engineering” all used together.

Don’t get confused by the conflation of these terms in the same context because in truth they’re all interchangeable – all of them more or less mean the same thing.

A software engineer is essentially a computer programmer as a software developer is also a software engineer.

Software engineering at its heart is simply programming.

It’s also worth mentioning at this point that there are of course now several specialized technical roles which involve programming.

I’m sure you’ve heard of at least one of them – database developer / administrator, data scientist / engineer, web developer.

To be specific, the writing of source code-based instructions would vary in terms of emphasis and form for each of the above disciplines.

For instance, a web developer is essentially a computer programmer who specializes in building interactive web-based applications.

They would use a relevant technology (i.e. – a server-side programming language such as PHP or a Python-compatible code-library / framework such as Flask or Django)).

This evolution of the role which started out under the title “web designer” and is now labelled “web developer” reflects the fact that many websites now are more like interactive desktop programs rather than the static read-only documents which characterized the web back in the 1990s.

In another part of the spectrum, a machine learning engineer for instance wouldn’t have much if anything to do with web interfaces but would perform tasks just as detailed as those carried out by a back-end developer.

Yet another area to clarify are the “differences” between the terms “programming” and “scripting”.

These definitions are not strict (again, they are used interchangeably) but came about through the idea that initially, languages such as JavaScript were used to write small programs containing just a few lines of code (colloquially called “scripts” by programmers) and a distinction was made between this and “proper programming” where professional developers would write large enterprise level applications involving thousands or millions of lines of code, using more powerful compiled languages such as C++.

This view was more down to subjective bias in the developer community than anything else.

As alluded to, the line between “scripting” and “programming” is now blurred, as certain interpreted languages (again, previously collectively referred to as scripting languages) – such as Python and JavaScript are used to build enterprise level software, as demonstrated by big famous companies such as Netflix and Amazon, both of whom use these technologies when building software for the global public or internal systems for use among their own staff.

All the different approaches to code and engineering in software are a subject in their own right. But that’s enough of the preamble.

To make this real, we need to dive into some useful examples.

Variables and datatypes

In code, variables are essentially data containers. They are categorized by type and these different types are referred to as datatypes.

Variables are so called because the values they contain constantly change – or vary.

Different types of variable store different types of information.

For example, one type of variable called a string can store alpha-numeric or special characters.

Numbers are another datatype.

Number variables are interesting because there are different types of numeric variable.

As well as the obvious one – number, others include:

Integer – a type of variable that stores whole numbers.

Floating-point number or float – a type of variable that stores decimals.

Certain programming languages such as C++ break down the categorization even further by defining different types according to the amount of memory space they take up.

For instance, in C++, you can have a 32-bit integer and a 64-bit integer.

Here are examples of all the variable types described.

Number

let mynumber = 58;

String

let mystring = 'This is a string';

Float

let myfloat = 3.14159265;

There are different styles to writing variables in code. It’s important to choose a style and stick with it for your code’s consistency.

These styles can also be applied to function names (more about functions later in the article).

One style is called Pascal case.

function MyPascalCaseNamedFunction(){
console.log('Pascal case capitalises first letters ' +
'of words joined together in a function ' +
'name.');
}
MyPascalCaseNamedFunction();

Another called snake case uses underscores.

function my_snakecase_named_function(){
console.log('Snake case names break up words with underscores.');
}
my_snakecase_named_function();

Yet another is called camel case.

function camelCaseFunction(){
console.log("In camel case, the first word is in lowercase" +
"and every subsequent word has it's first letter" +
"capitalised.");
}
camelCaseFunction();

You can learn more about code naming conventions from the w3schools.com website – a great resource for learning programming.

One thing to mention is that in some programming languages, the datatype of the variable is preceded by a description (i.e. - an abbreviation such as int for integer) before the variable is declared.

For instance, this is how an integer is declared in C++.

int myNum = 15;

C++ (for example) is a strictly typed or type-safe language. That is, datatypes declared in the language must remain the same type throughout their use. Their type cannot be changed at runtime (when the program runs after compilation or interpretation (The difference between interpreted and compiled languages is beyond the scope of this tutorial but you can learn more about the difference here)).

JavaScript is not type-safe. That is, variable datatypes in JS can be changed at runtime, meaning the same variable can accept a different type of data “on the fly”.

For instance, this is valid code in JavaScript.

The variable is first declared as a string…

let five = 'five';

…but then reused as a number.

five = 5;

This capability can be a double-edged sword. It can be extremely convenient – reusing the same variable in a different context, but can also make debugging more difficult (more about debugging below).

This flexibility in JavaScript remains a contentious issue among programmers. Some like the convenience, others dislike the ambiguity and potential for errors that it creates.

The best approach is to be careful if you write code this way and follow sensible best-practice – which is probably to stick with one purpose for each variable.

If you’re interested in studying this particular topic further, you can look at TypeScript, a version of JavaScript created by Microsoft which is type-safe. Learn more about it here.

One final thing to mention about declaring variables is a recent change in format specific to JavaScript.

Before, in JavaScript, variable names were preceded by the keyword ‘var’.

var myvariable = 58;

The way to do it now is by using the keyword ‘let’.

let myvariable = 58;

Arguably, the previous style was more intuitive but using the keyword ‘let’ is now the convention, so please stick with it.

You can learn more about modern JavaScript here.

Statements

In programming, a statement is similar to the construct were all familiar with from human language.

In code, a statement is simply a line of expression conveying some form of meaning.

Meaning in programming is expressed in logical terms – often numerically, given that computers as we know, are particularly good at working with numbers.

Here’s an example (don’t worry about anything that might look unfamiliar at this stage).

console.log(1 > 0); // Output: true

The value of the log parameter above is just a regular math equation.

Much of the structure – or syntax (another term from normal language) in a programming language resembles mathematical structures.

In fact, some code structures are identical to those found in math. For instance, the syntax for conditional statements and their usage of less than or more than symbols, as well as other logical operators, come straight from their equivalents in mathematics. We’ll see some examples shortly.

Functions

In programming, functions are simply collections of statements. Functions are extremely useful as they’re reusable, which of course saves time and effort.

Here’s an example of a programmatic function.

function myfunction(){
console.log('This is a basic function definition.');
}
myfunction();

Functions are the essential building blocks of computer programming and as you progress with your learning, you’ll see how powerful they are.

Parameters and arguments

Parameters – also referred to as arguments – are a special kind of variable and a way to set – or initialize the “value context” of a particular function before running the function.

This means it’s possible to affect how the whole function works under a certain condition (influencing other non-parameterized variables in the process).

A function can contain more than one parameter.

The reason for setting a parameter’s value in advance is to customize a copy or instance of a function so that it can be ready for a changed condition.

This approach to programming is particularly powerful.

Here’s an illustration of how calling parameterized functions can be extremely useful.

The following function calculates the square root of whichever value you provide to it – or pass to it – through its parameter.

The function also tells the user if the square root of the numeric value passed by the user is an integer or an irrational number.

function mysquareroot(mynumber){
let mysqrt = Math.sqrt(mynumber);
if(mynumber % mysqrt == 0){
console.log("The square root of " + mynumber + " (" + mysqrt + ")" + " is a rational number.");
} else {
console.log("The square root of " + mynumber + " (" + mysqrt + ")" + " is an irrational number.");
}
}
mysquareroot(4); //Try these values: 16, 32, 64, 4096
//mysquareroot(81);
//mysquareroot(9);

This function can be repeatedly activated or called as shown above as many times as you like with a different value each time.

Each function call only requires the programmer to reference the function by name in one line of code using different parameter values.

This means you can always get the full benefit of a function’s capability without having to rewrite the function in full each time.

Comments

You would have seen those strange lines next to each function call formed of two forward slashes (//).

These lines are the start of special pieces of text called comments and when the program runs, the computer ignores them. However, comments are very useful to programmers – especially programmers who work in teams (most professional programmers work in teams).

Comments can even help the original author of the code, as when code becomes complex (as is often the case), comments can not only explain what the code is doing – which is very useful for your fellow coders on the team – but can also remind you of the logic you were following when you were writing it.

If you write some and then come back to it weeks or months later after having not worked on it in all that time, comments are a great way to refresh your memory.

Comments essentially come in two styles. C style languages – languages based on the syntax of an old language called C (such as Java, JavaScript and C++) use two types of comment format.

This format is for single line comments.

//This style is for single line comments

This format is for long, detailed comments.

/*This style is for comments
involving detailed descriptions
of functionality.*/

Data structures

A data structure is a way to store or work with multiple variables or variable values at the same time.

There are as you’ve guessed, different types of data structure.

The simplest and most common type is the array.

Arrays can contain multiple values of the same datatype or different datatypes (the former use is more common than the latter).

Here's an example of an array.

let fruit = ['apple','orange','pear','banana'];

As stated, the array is the data structure you’ll see and use the most. The other types are slightly more advanced and outside the scope of this tutorial but if you’re curious, this article provides more information.

Conditional statements

Conditional statements were briefly mentioned in the general section on statements.

These special clauses in code work with keywords such as IF, ELSE, OR and WHILE and they express Boolean logic as derived from Boolean algebra.

Boolean algebra was introduced by a mathematician named George Boole in the mid-19th century and was invented to test logic in simple ways. Boolean logic tests are characterized by assessing whether a statement is true or false.

Like functions, Boolean logic is a powerful tool in programming and affects the flow of a program.

In a similar way to parameters, conditional statements make programs dynamic – that is, able to do different things on demand at different times according to changes in the data’s conditions.

Here’s a simple example.

let earth = 'round';
let shape = 'round';

if(earth == shape){
console.log('true');
} else {
console.log('false');
}

Loops

Loops are another aspect of programming you’ll inevitably encounter.

A loop is a structure which automatically repeats the execution of a function or set of functions until a specific condition is met.

Loops are driven by variables called iterators (the word iterate means to repeat).

Traditionally in programming, this is often the “I” iterator but as you can see in the example below, you can use any letter to create one. Indeed, in “nested” loops (a loop running within a loop), you’d use another letter to signify the inner loop from the outer one.

Loops are typically used to repeatedly test a condition. While the condition remains true, the loop continues to cycle. In a loop, a value can change with each cycle. As a result of these incremental value changes, a condition which started out as true will eventually become false (in most cases the value will be changeable). Once the condition is false as the loop arrives at the specified value, the loop stops.

Here's an example of a typical for loop.

function BasicLoop(){

let i;

/*Computers start counting at zero so the
'50' below is actually fortynine.*/

let fortynine = 50;
console.log('count to 49:');

//This is a for loop

for(i=0; i < fortynine; i++){
console.log("counted " + i + " times.");
}

}

//Here’s an example of a nested loop.

/*Write a function that merges and sorts
two unsorted lists with a nested loop.*/

let i;
let j;
let k;
let count = -1;
let join = [];
let sorted = [];
let A = [0,1,3,5,7];
let B = [2,4,6,8,10];

/*Join the two arrays*/

for(i = 0; i < A.length; i++){
join.push(A[i]);
}

for(j = 0; j < B.length; j++){
join.push(B[j]);
}

/*Sort merged array*/

function sortmerged() {

/* NESTED LOOP EXAMPLE -
A nested loop can be seen as a 'combo-loop':

combining two separate loops together,
where one loop runs inside another.
You can combine different types of loops.
Here, a while loop (the outer loop) works
with a for loop (the inner loop).
The for loop runs inside the while loop.*/

while(sorted.length != join.length){ // Start outer loop
count++;
for(k=0; k < join.length; k++){ // Start inner loop
if(count == join[k]){
sorted.push(join[k]);
} // Close conditional statement
} // Close inner loop
} // Close outer loop

} // Close function

sortmerged();
console.log(sorted);

//Here's a simple while loop

function mywhileloop() {

let count = 0;

while(count < 10){
count++;
console.log(count);
}

}
mywhileloop();

Function symbols - curly braces

Just before we move on to the section on classes, we need to look at two other important symbol types for functions used within C style programming languages.

You've seen them in action throughout the code samples of this article. It's time now to explain them.

Curly braces come in two forms. The opening curly brace { and the closing curly brace }.

Each type must match the other type in terms of how many of the other type there is.

In other words, the number of opening curly braces must match the number of closing curly braces.

As you've seen, curly braces act like the "front door" and "back door" of a house when it comes to programmatic functions.

As locked doors provide security for a home, in programming, curly braces serve the same purpose - they are container elements which protect everything inside them.

This protection is used for the safety of a functions "scope".

Scope governs all of a functions content - essentially protecting its variables and statements from interference by other functions and variables outside the function.

Scope will be discussed in further detail later in the article.

Here's an example of the requirement for opening and closing curly braces.

function MyFunction(){ // 1 opening curly brace...

console.log('The numbers of opening curly braces and closing curly braces must match.');

} //...must be matched by 1 closing curly brace.

Function symbols - brackets

Brackets () are placed after the function name and just before the opening curly brace of a function.

function MyFunction(){ <---Brackets just before curly brace

console.log('Each function name should be followed by a single set of brackets "()"');

}

These simple but vital rules of syntax are particularly important when programs become complex - such as when they're 'object-oriented' and 'class based'.

Classes and objects

Classes can be imagined as programs running within programs.

They are blocks of code containing multiple functions (or to use the technical term from object-oriented programming, methods).

The 'program-within-program' idea comes from the fact that in real-world software systems, classes are often themselves large modules of code, which when well designed, are like 'standalone' programs in their own right, making them portable and versatile, meaning they can be moved and reused inside other (even larger) programs.

Conversely, a class can also be used inside another module of code by referencing an instance of it (or one of its methods) via a single line of code.

Methods (class functions) run inside a class and can be collectively or individually called using dot notation – a way to represent the hierarchical relationship between a class and its methods in a simple way.

Here are some examples:

Call one method of a class instance at time.

MySuperClass.MyClassMethod();

let Object1 = new MySuperClass();
let Object2 = new MySuperClass();
let Object3 = new MySuperClass();

Call multiple methods of a class simultaneously using a loop.

for(i=0; i < allclasses; i++){

Object1.MyClassMethod();
Object2.MyClassMethod();
Object3.MyClassMethod();

}

Similar to functions, classes can be reused. Copies of classes are also called instances or specifically, objects (hence the term object-oriented programming).

A class is essentially a template and can be customized as well as reused (in a similar way to a parameterized function).

The class system in object-oriented programming is hierarchical and terms from the biological world are used to describe the relationships between classes.

A class created from another class (the copy or object) is a child of the main class which is also referred to as the superclass or parent.

A good analogy and visual metaphor for this is Russian dolls. These toys start out with one large doll containing all the other smaller dolls, where each subsequent doll from the previous one is one size smaller than the last.

When a copy or object is derived from a class in OOP it inherits the parent’s capabilities and characteristics (the process of course is specifically referred to as inheritance).

These capabilities are defined by the methods (the classes internal functions) and the classes characteristics are defined by the variables of those internal functions. These internal variables are referred to in OOP as attributes or properties. Attributes and properties can also be referred to as fields or members.

The theory of object-oriented programming posits that everything in the real-world is an object (an entity with two main aspects – what it does (its behavior) and how its described (its characteristics)) and that all real-world objects can be modelled in code (via properties or attributes describing characteristics and methods which describe behaviors).

Encapsulation is another important aspect of OOP.

This refers to the idea that everything a class needs (its data - defined by properties) and what it does (its methods) are self-contained and self-sufficient within it.

Encapsulation is defined by scope – a programming rule determining which functions or data can interact with each other.

Scope can either be local – that is, restricted to a class or function internally – or global – accessible by any function or variable in the program.

Scope essentially protects the integrity of data and functions. Just think of those Russian dolls again and how the largest doll acting as the container protects all the smaller dolls inside.

Global variables in general programming are discouraged as this can make it difficult to ascertain what has affected a function or variable when a program goes wrong (known as a bug in programming terms. Bugs come about through mistakes in code – and every programmer makes them).

Local variables are better to use as they make functions and classes self-sufficient and when it comes to debugging, makes it easier to find and fix faults in code.

One last OOP concept to explain is polymorphism. This is a conflation of the word poly which means “many” and morphism, which derives from the word “morph” – to change form.

Polymorphism in OOP describes what happens when parameterized functions are in action.

Through polymorphism, objects and functions effectively take on many forms because when they are customized and repurposed, each polymorphic function or object is effectively a different entity on each separate occasion, doing different things at different times in each incarnation.

It’s this single powerful aspect which made object-oriented programming very popular among developers at one point.

OOP was invented decades ago to help organize code in programs when software products became too large and complex in their design and functionality to manage.

In the past, before OOP, programming was done by using a method known as procedural programming.

Procedural programming was a pretty basic technique. In this fashion, each line of code was written to follow a separate instruction in a step-by-step algorithm. (The term algorithm simply means a series of sequential and logical steps to fulfil a task).

This approach became particularly cumbersome when programs got larger and more complicated, but this all changed when OOP came along and transformed the way developers wrote software.

Since then, attitudes in the developer community have become divided around whether OOP is a good methodology or not for software development (one disadvantage of OOP is that software performance can degrade when software is comprised of “too many” objects).

Functional programming (simply breaking up large complex programs into sets of smaller interactive functions) is often seen as a preferable alternative.

Here is some further OOP code. As per the article, these demos are based on a JavaScript implementation. I would encourage you to look at the way other languages implement OOP. The Java language and the Python language are particularly illustrative in this regard.

Encapsulation.

//The speed variable works - it's in scope

class Car {

constructor() {
this.speed;
}

brake(){
console.log("Car braking...");
}
}

let toyota = new Car();
toyota.speed = 60;
console.log(toyota.speed);

//Error (undefined) - flightspeed variable is outside the scope of Car

let flightspeed = 120;
console.log(toyota.flightspeed);

Inheritance.

//Inheritance

let mercedes = new Car();
mercedes.brake();

You can also extend an object by giving it a unique capability its parent doesn’t possess. The object will still retain its parent’s capability as well as its own.

//Extension
class Truck extends Car {

//Unique method
carry_load(){
console.log("Carrying large load...");
}

}

//Truck is a unique object but can still use Cars methods
let truck = new Truck();
truck.brake();

This is the power of polymorphism. Another way to implement polymorphism is with interfaces. Interfaces are "empty methods" that are deliberately left blank so they can be used as customisable templates.

By using the interface approach, an object can inherit from a parent class and even reuse the parent classes methods, but also execute its own unique versions of those methods.

This is polymorphism in a nutsell - a function can be synonymous with an identical function in another child of the parent class but each child implements the method differently.

As per the definition outlined earlier:

Through polymorphism, objects and functions effectively take on many forms because when they are customized and repurposed, each polymorphic function or object is effectively a different entity on each separate occasion, doing different things at different times in each incarnation.

//Polymorphism with interfaces

class Plane {

constructor() {

}

takeoff(){

}

fly(){

}

land(){

}

}


//Private jet version of plane

class PrivateJet extends Plane {

takeoff(){
console.log('Regular take off...');
}

fly(){
console.log('Regular flying...');
}

land(){
console.log('Regular landing...');
}

}

let privateplane = new PrivateJet();

privateplane.takeoff();
privateplane.fly();
privateplane.land();


//Fighterjet version of plane

class FighterJet extends Plane {

takeoff(){
console.log('Vertical take off...');
}

fly(){
console.log('Twisting, Rolling...');
}

land(){
console.log('Touching down on aircraft carrier...');
}

}

let fighter = new FighterJet();

fighter.takeoff();
fighter.fly();
fighter.land();

We’ve covered a lot of theory in this article and I thank you for sticking with the material so far.

To round off with something practical, we’ll implement a small, fun game which will demonstrate some of the principles discussed above.

Traditionally, “Hello World!” is an exercise given to new programmers as their first project. This is simply where newbies write some code that prints those words to the screen.

We’ll do something more interesting in this article. We’ll create a version of “Higher Lower”, where you have fun trying to guess a hidden number.

In this game, the player has to make 10 guesses at the number generated by the computer.

The computer will prompt you by saying whether the hidden number is higher or lower than the one you’ve guessed. If you make 10 incorrect guesses, you lose and have to start over.

As were working with JavaScript, we don’t need to do any fancy set up. JS works with all browsers and so we can simply save and run our code using whichever browser we’ve installed.

Let’s start by building the program’s interface.

Copy and paste the HTML below into a text file and save it under the file name index.html.

<!DOCTYPE html>
<html>
<head>

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Higher Lower</title>

<link rel="stylesheet" type="text/css" href="css/ui.css" />
<script src = "js/app.js"></script>

</head>
<body>

<!-- Input - text -->
<input id = "solutioninput" >

<!-- Input - button -->
<div id = "inputbtn">Guess</div>

</body>
</html>

HTML (Hyper Text Markup Language) is not a programming language as such. It simply creates a structural framework to organize a web applications interface using tags or elements.

You can learn more about HTML here.

As the interface is structured by HTML, the layout of the interface is controlled by CSS in the ui.css file.

Copy and paste the code below into a file named and saved as ui.css

#solutioninput {

/*dimensions*/
width: 30%;

/*position*/
margin-top:1%;
margin-left: 33%;

/*format*/
color:white;
background-color:grey;
border: 1px solid white;

/*font*/
font-family:Verdana,sans-serif;
font-weight:bold;
font-size:200%;

}

#inputbtn {

/*format*/
color:white;
background-color:grey;
border: 1px solid white;

/*font*/
font-family:Verdana,sans-serif;
font-weight:bold;
font-size:150%;

/*text*/
text-align:center;
line-height:5rem;

/*dimensions*/
width: 30%;
height: 15%;

/*position*/
margin-top: 30%;
margin-left: 33.5%;

}

body{
background-image: linear-gradient(to right, blue , aqua);
}

If you go on to specialize in web development, particularly client-side development (otherwise known as front end web development), you’ll need to know about CSS (Cascading Style Sheets).

You can learn more about CSS here.

Now, finally, create and open another text file and then copy / save this code into it.

window.onload = GlobalFunction;
function GlobalFunction(){

let tries = 0;

function higherlower(){

let answerbtn = document.getElementById("inputbtn");
let inputtext = document.getElementById("solutioninput");
let solution = Math.round(Math.random()*100);

if(answerbtn == document.getElementById("inputbtn")){
answerbtn.onclick = function(){

if(inputtext.value == solution){
alert("CORRECT!");
}

if(inputtext.value > solution){
tries++;
alert("TOO HIGH!");
}

if(inputtext.value < solution){
tries++;
alert("TOO LOW!");
}

if(tries == 10 || tries > 10){
alert("HIT THE REFRESH BUTTON AND START OVER.");
tries = 0;
}

}
}
}

higherlower();

}

Save this as app.js

Make sure that app.js is saved in a subfolder named 'js' and that the ui.css file is saved in a subfolder named 'css'.

Ensure that these subfolders are stored in a folder simply named 'higherlower'.

The HTML file should be saved in 'higherlower', standing alone outside of all the subfolders.

If you have any issues, please refer to the code in the project package which you can download from the link at the top of the article.

The way to activate the game is to simply double click index.html. It should open the app in your default browser. The way to play is to enter your guesses into the text field at the top of the page. After this, click the button underneath to see if your guess matches the number randomly generated by the computer. You can learn more about random numbers in JavaScript here..

If you guess correctly, the program congratulates you. If you fail to guess correctly 10 times, you’ll have to start over.

Don’t just play this game. Play with the code as well. See what changes occur when you make your own changes. Ultimately, try to create your own game.

Conclusion

Thanks for reading. I hope this has been a good and useful introduction to the world of coding.

Keep reading as many tutorials as you can and practice your new skills as much as you can, but most of all, have fun. All the best and please visit again soon.