Beginning Coding Tips

Since I’ve been involved in coaching at BCIT, I’ve started to get a better insight into the learning processes and tools required to get a grasp of ‘programming stuff’.

Programming isn’t easy by any stretch, so I may not be able to nail exactly what it is that may be that single ‘aha’ moment of clarity that makes programming all easy from that point on, or if there are required to be many of these along the road. Or if there is a road, or a meandering goat path, or a highway.

I’ll begin with the basics you have to understand. I won’t rehash a lot of what should be covered, just various observations and clarifications.

Basics

Variables

OK, so maybe not that interesting, but the whole concept of variables, their being at the very simplistic level a box that holds something in memory.

Understand naming conventions – does your language care about upper and lower case when naming variables? Javascript does, and is probably the cause of the greatest frustration with all levels of coders. Just be aware that if something isn’t working, this could be the simple reason.

Variable Types

Variables have a type associated with them — this is a bit of a peek behind the curtain into how they might be stored internally. Usually a variable will either be a number, a string, or an object.

A number is basically something you can conceptually punch into a calculator  to do some math with and it’ll make sense. Historically, computers have liked to store numbers in specialized formats so you may find in other languages different types that represent integers (whole numbers only) and floating point (all numbers, including fractions) and your having to choose the right type for what you’re doing.

A string is literally just text, aka a string of characters you can type on your keyboard (and many more you can’t easily type) – alphabet, numbers, emoji, characters from the world’s languages, etc. Strings are quoted with single or double quotes.

An object variable is, well, an object (see objects later).

Automatic Type Conversion

Types can be converted from one to another if it makes sense – the string “123.45” can be converted into the number 123.45. But the string “A123.45” can’t be converted.

Javascript attempts to do automatic type conversion when it makes sense; but beware of the rules; i.e. the following weirdness:

"3" * "2"    // this returns the number 6
"5" + 1      // returns the string "51"
"5" - 1      // returns number 4

You can see that it’s beneficial to explicitly tell Javascript what you want done instead of relying on the automatic type conversion, which you can do by calling the Number() and String() functions:

Number("3") * Number("2")   // returns 6
"5" + String(1)             // returns "51"
Number("5") - 1             // returns 4

Variable Scope

Understanding when a variable is ‘alive’ and valid is a huge concept. Most current languages allow the same variable name to be declared again within a different lexical scope; i.e. inside a function as well as in the surrounding code. These are logically two different variables, so do not get confused.

In this Javascript example, the variable ‘a’ is declared twice; within the function, and outside the function. The inner ‘var’ makes a whole new local variable ‘a’ that is independent of the outer ‘a’ which has a global scope.

var a=3;      // global

function f()
{
  var a = 5;   // independent (local) variable
}

function g()
{
    // in here, you can access global 'a'
}

Whereas in the following example, the inner ‘a’ actually refers to the outer ‘a’, which may or may not be intentional.

var a=3;      // global

function f()
{
  a = 5;      // affects the global a
}

Quirks abound in Javascript due to its automatic variable declaration:

function f()
{
  a = 5;      // creates a global variable a !!!
}

Having functions ‘reach outside’ their scope is usually a bad practice and can lead to unintentional side-effects.

Best Practice:  Always declare variables with ‘var’ instead of allowing Javascript to figure out if you’re using a new variable or an existing one.

PHP Note: Of course, PHP has to different. PHP scopes variables only to the scope they are declared in. This is a very frequent pitfall for PHP programmers used to other languages. Global variables look like they’re declared, yet they’re unassigned when you try to use them.

Access to a global variable in an outer scope has to be explicitly declared. Why? probably to protect you from accidentally changing a global variable. So to access a global from a function, you need the global keyword like so:

$g = 5     // a global variable
function addG($num)
{
  global $g;    // have to have 'global' here..
  return $g + $num;
}

Functions

Understanding that functions are ideally written without any reliance on external knowledge of who’s calling the function. In standard terms, this is to reduce side-effects as noted above.

Functions written this way can also be modular; think about giving someone else this function to use in their code – will it be possible, or will you have to do something to their code or yours in order to make it work properly?

Parameter Passing

Understanding that parameters in a function are placeholders within that function and allow you to specify functionality without needing to know anything about who’s calling the function.

This again is an example of scope – function parameters are simply just scoped to the function.

Objects

Understanding the concept of objects is essential in working with the HTML DOM and pretty much needed to anything useful such as storing/retrieving data. So much functionality is wrapped inside objects, or arrays of objects, and so forth.

Understand that just about everything has been ‘object-ified’ — it’s one way of looking at the world in programming terms of objects, functions, fields, and events.

Arrays / Collections

Objects become more useful when you can have more than one of them (money, for example, or students, or houses).

Understand moving through collections of objects one at a time, or directly through key values. You’ll do this often; i.e. grab a list of student objects and display all names on the screen.

More advanced concepts

Dig into HTTP

Understand a little bit about the mechanics behind web traffic – GETs, POSTs, cookies, and so on, so that you know that a server is involved somewhere – not everything useful executes purely in the browser.

This positions you well to use the raft of services available through REST web services, etc., and inevitably to try to debug some of your applications that use web services.

Object Models

An Object Model, viewed through Javascript googles is a bunch of related objects, with properties and functions to manipulate those functions. An OM tries to model something in the real or abstract world in some sort of logical way so that you can do useful things with it programmatically. An Object Model for a car might look like this:

var car = {
  make: "Mazda",
  model: "CX-5",
  radioPresets: [ "104.5", "96.1", "89.3" ],
  startTheCar: function() {},
  driveTo: function(location) {},
  pickUp: function(persons) {},
  setRadioToPreset: function(presetNo) {}
}

So a car object becomes a handy way to encapsulate in one handy package useful information about an instance of a car (“properties” such as make and model) and to also encapsulate the useful functions a car can perform (driveTo a location), otherwise known as “methods”.

The packaging aspect is a convenience in that you can call methods and access properties using the “.” operator; i.e.

car.make = "Volvo";
car.pickUp(["Martin", "Kathy"]);
car.driveTo("Home");
car.setRadioToPreset(1);

You can hopefully envision a world where objects interact with other objects (cars interacting with road objects), objects containing other objects (cars containing arrays of people objects to represent their occupants), objects composed from other smaller objects (car containing an engine object, a radio object, 4 wheels objects), each composed of sub-objects.

Aside for sticklers: the code above is really for illustrative purposes; current Javascript provides a way of defining objects through functions and prototypes in a more object-oriented way (i.e. compared to something like Java or C#).

HTML DOM

More on DOM stuff later; for now, understand that this is an object model (hence the “OM” in “DOM”) that represents in a tree-like form what you see in a browser. You can manipulate the objects in the tree (setting properties and calling methods) to control the visuals in the browser window.

Javascript braces hell

Start to understand Javascript’s approach of functions as parameters to functions, and the resulting nested curly braces. Format your source code properly to foster readability

Events

Understand the concept of events as notifications that occur due to some user or system action.  Remember that everything is an object, and objects can trigger events when something happens to them – like when a page is loaded, or when an image notices that a mouse pointer has moved into its field of view.

Frameworks

Finally, we get to Frameworks. Frameworks are just pre-written code, not magic. The advantage is building stuff faster, likely more bug-free, and more functionality than doing it yourself. The downside is frameworks sometimes don’t do exactly what you want, and you can easily get into a kid in a candy store situation of grabbing this UI gadget that uses such-and-such framework, and another one using a different framework — with the downside of bloating your page and making it slow or buggy if the frameworks don’t play nice with each other.

But they sure save a lot of time, so just be aware and do your homework.

Philosophy

Reusability and Modularity

I mentioned one tip earlier – write your code in a way that someone might be able to re-use something you wrote without really needing to modify it much, or at all. A simple rule

If you have a simple function, regardless of how trivial, think about whether it could be refined in a way so that someone could either include the piece of script, or include the function (copy/paste) and use it right away. If not, then it means that there is some dependency on something that exists that shouldn’t be there — probably on a variable you have in your code.

Continuous Improvement – Refactoring

It’s rare for a beginner programmer to understand how best to break code into reusable and modular bits.

On one hand, if you don’t break down a module into potentially reusable pieces, then you end up having a huge, monolithic piece of code that looks like it has a lot of repetitive stuff in it.

At the other end of the spectrum, you might break something down into much too many small pieces that, while modular, may seem excessively fussy, and may make code readability suffer.

What to do? I typically notice code that I’ve written a few times; say,

document.getElementbyID("welcome").innerHTML = "Hi There";
document.getElementbyID("status").innerHTML = "123";
document.getElementbyID("status").innerHTML = "456";

And think…maybe I can make a function with parameters to do the same thing, and name it something more descriptive. So I refactor my code a little:

function DisplayText(element, text)
{
   document.getElementbyID(element).innerHTML = text;
}

DisplayText("welcome", "Hi There");
DisplayText("status", "123"); DisplayText("status", "456");

Better! This illustrates a simple way to cut down typing at least. And you can go one further:

function DisplayText(element, text)
{
   document.getElementbyID(element).innerHTML = text;
}

function DisplayStatus(statusText)
{
   DisplayText("status", statusText);
}
DisplayText("welcome", "Hi There");
DisplayStatus("123");
DisplayStatus("456");

And so forth. Is this better than just the straight document.getElementByID method? Not necessarily, as perhaps readability is impacted (someone will have to check to see what DisplayStatus() does the first time they see it).

But what happens if you want to change where the status message goes? Then you just go to one place, DisplayStatus() instead of the two (or more) places in the code you would need to if you used the document.getElementbyID() technique.

All I can really advise around modularity or creating functions is to be alert for

  1. repeated code – that may be a candidate for creating functions to do stuff and to minimize cut/paste errors
  2. useful functionality – maybe I need to put “, ” in between two strings to format a name (“Doe, John”). That might be useful elsewhere, so a function would be a great idea.
  3. centralized functionality – things I know I may want to change often or later – like DisplayStatus() above. Maybe I want to make the message appear in a red colour or different font. Making it centralized ensures that when I change the function, all possible places that I display the status also change with it.
  4. deferment – should I just toss in a function as a placeholder for now, and get on with the rest of the coding that I have in my head, and get back to that later?  I.e.  BigMathFunction(x, y, z, a, b)
  5. plain old readability. Can I just chunk up a huge function into smaller functions and call them in the same sequence; i.e. BeginningPart(), MiddlePart(), EndPart()