paazmaya.fi

The Website of Juga Paazmaya | Stories about Web Development, Japanese Martial Arts, Hardware prototyping and travelling

Remember to check type in dynamically typed languages

Several popular programming and scripting languages today are dynamically typed, for example PHP, Python, JavaScript and others. Dynamically typed means that a variable is not given a type when it is created but the type is determined when the part of code is running.

Dynamically typed language means that the variables are not specified to have a certain type when they are created, as it is the case in statically typed languages. Hence the type of any variable that arrives outside from the known scope.

JavaScript has a _typeof _operator that can be used for comparison of the existing data types, like shown in the example code below.

var i = 5;
if (typeof i === "number") {
    // i can be safely used as a number
}
else {
    // what to do on a failure?
}

PHP has a number of global functions, such as is_array, is_numeric or empty, for checking the type of the given variable. The example below checks if the variable is set to a value and then checks if it is a string. PHP has eight types available.

$s = "Hello there";
if (isset($s) && is_string($s))
{
    // $s has a value and it is a string
}
else
{
    // might be that $s was empty or it was not a string
}

Similar approach can be employed with Python and Ruby. In Ruby everything is an object, thus can have methods. One particularly useful method related to the topic is the kind_of member of Object. Python has a built-in function called type.

The reason for writing this short note, is to make myself to remember the topic. Sometimes when reviewing old code, my own or others, comes across functionality which assumes that the incoming variables are of a certain type but checking is done only against a black list, while it should be against a white list. Black list refers to checking which they are not, as opposed by white list that refers to checking against accepted types.