After many years of working with different programming and scripting languages, one of the things that fascinates me most is the subtle ways they approach the same task from different angles.  In this instance, I’ll focus on multiple condition-checking methods.  That’s a fancy name for something you probably use all the time and didn’t know it.

  • Intended Audience:  Beginner to Intermediate Script Writer
  • Intended aptitude:  Not easily offended

Packer-truck

Let’s start with a fixed sample condition to use for the remainder of this article.  I’m going to use a variable named ItemType (in appropriate dialect for each language, of course).

What is a “condition check”?

In simplest terms, it’s the process of checking for a particular condition or set of conditions.  Clear as mud?  Okay, how about this…

It’s when you check if a value is equal to some other value, greater than or less than or within, or not within, or part of, or whatever.   For example, checking if an employee’s age is equal to, greater than, or less than 55.  If the employee is 55 and your condition check is “if employee-age = 55 …” then the condition is said to be “true” or ‘evaluates to true’.

NOTE:  I’m not trying to teach programming or scripting languages here.  This is just an exercise in comparing the ways each of the mentioned languages supports single and multiple condition checking.  That’s all.

A Word About Languages

Pardon the pun.  Spoken languages adapt pieces of other languages all the time.  If you pause for a moment, you can probably think of at least three words which are not native to your language, but are used in casual conversation.  The same concept should be applied to programming languages.  Unless you see how things are done in other languages, you’ll never know how efficient or practical your current toolset really is.

One of my professors once told us that until you’ve finished at least three distinct projects in three distinctly different programming languages, you can’t call yourself a “programmer” any more than a mechanic could claim that title while only knowing what a box-end wrench is.

The other thing I’d like to mention is that, too often, we unknowingly associate a particular language with a particular way of coding it.  But since most of these languages are *not* case sensitive as it pertains to variable names, function names, and so on, we can use a consistent approach.  So, I’m going with lower-case coding wherever possible, for this article.  At least, that’s my intent. Let’s get started.

Batch

Batch is every Windows admin’s favorite scripting tool.  I’m kidding.  It’s been beat up and smeared with paint and lipstick, made fun of, and left by the roadside.  But Batch is still heavily used and rightly so.  It’s simple, reliable, and fast.

The problems with this language tend to emerge when pushing it into areas for which other tools are more effective.  A good analogy would be something like Batch is like a hammer.  It’s great for pounding nails, but not so great at tightening nuts and bolts.  So, just because a language can accomplish a particular task, doesn’t mean it’s the best choice for doing so.  This is akin to pounding nails with a screwdriver.

Now, let’s pound some nails.

if EXIST "%programfiles%\Sample\foo.txt" (
  echo The file exists!
) else (
  echo File was not found.
)

Simple enough, and fairly efficient.  If the specified file exists, we echo (display) one statement, otherwise (else) we display another.

Now, let’s try a multiple-condition scenario.  We’ll check if the variable’s assigned value is equal to, greater than or less than a stated value.

if NOT DEFINED ItemType (
  set ItemType=6
)

if %ItemType% EQU 5 (
  echo Type is 5
) else (
  if %ItemType% GTR (
    echo Type is greater than 5
  ) else (
    echo Type is less than 5
  )
)

This is obviously really simplistic.  But it illustrates a less-efficient model for dealing with comparative numeric values.  Nested “if” statements can drive anyone to insanity with enough repetition.  Don’t get too wrapped up in the quoting of strings, since each language deals with that aspect slightly different.  Let’s stay focused on condition checking.

As I said, there’s nothing wrong with Batch scripting.  It’s a fantastic “glue” and “wrapper” for other scripts and processes.  Hence the name “batch”.  It’s the duct-tape of scripting.  When you start using FOR and TOKENS it’s time to call 911 or another script language, whichever is closest.

Beyond Batch

The following languages have some built-in advantages over Batch when it comes to multiple-condition checking.  The one which looks, smells and feels the closest to Batch is KixTart.  This language enjoyed a peak in popularity about a decade ago, but has gradually been less mentioned in most IT shops.  Anyhow, back to the discussion.

VBscript

The flagship language of the age-old, fully-baked, uncorked and ready to pour COM-oriented Windows Scripting Host platform is VBScript.  It’s still a major force in the Windows technology world, primarily for two reasons:  It’s built up a huge following and support ecosystem, and Microsoft still weaves it into every product somewhere (even Windows 10)

Dim ItemType : ItemType = 5

if ItemType = 5 Then
  result = "type is 5"
elseif ItemType > 5 Then
  result = "type is more than 5"
else
  result = "type is less than 5"
end if

Notice the ‘elseif’ statement, which Batch doesn’t provide.  It’s not a jaw-dropping feature, but helpful.

There is also a “select case” feature, which the others below also share (in different ways) that allows for more compact coding of things like this, however… Select-Case only allows for matching exact values (equal to).  It doesn’t allow you to compare values (greater, less, etc.).  However, when you’re dealing with a known range of possible values, such as enumerations, it can be very useful ( and easier to look at )…

For a moment, let’s assume that “ItemType” represents a categorical value, rather than an open-ended, non-fixed value.  Maybe the range is 1 through 5 only.

select case ItemType
  case 5
    result = "Capital assets"
  case 4
    result = "Leased assets"
  case 3
    result = "Borrowed assets"
  case else
    result = "Unknown category"
end select

PowerShell

The syntax for replicating the “select-case” model in PowerShell is nearly identical to VBscript, as well as JavaScript, KiXtart, and even Visual LISP.  But let’s start with the basics…

if ($ItemType -eq 5) {
  $result = "type is 5"
} elseif ($ItemType -gt 5) {
  $result = "type is more than 5"
} else {
  $result = "type is less than 5"
}

Another way to spew this code (like that word, spew?  me too) is to unstack the code a bit.  This is probably more familiar to you from what most “real” authors use…

if ($ItemType -eq 5) 
{
  $result = "type is 5"
}
elseif ($ItemType -gt 5)
{
  $result = "type is more than 5"
}
else
{
  $result = "type is less than 5"
}
write-verbose "i really hate unstacked code!"

Applying the same enumerated example, we can use the switch-case model…

switch ($ItemType) {
  1 {$result = "type is alpha"; break}
  2 {$result = "type is beta"; break}
  3 {$result = "type is delta"; break}
  default {$result = "I have no idea"}
}

Unstacked ugliness looks like this…

switch ($ItemType) {
  1
  {
    $result = "type is alpha"
    break;
  }
  # ... you get the idea, sheesh!
}

JavaScript

By most measurements, JavaScript is by far the most widely-used computer scripting language on the planet Earth.  Before you start in with “Now, just wait a darn minute!...” think of every LAMP-stack web site on Earth, and every web site that uses a client-side ECMAScript implementation.  Every spin on it from JSON and JQuery to Angular and so on.  Right-click on any web page and view the source.  It’s there.  Case closed.  Done.  Move along.

JavaScript, which is the de facto instantiation of ECMAScript, is powerful, flexible and fairly compact by modern standards.  It’s also extendible (hence my blabber about Angular and JSON, etc.).  And once you’ve worked with it enough, it’s not a difficult jump to learn Perl, PowerShell or C# even.  Mostly because they share some common traits and names.

Simple IF/THEN/ELSE in JavaScript…

if (ItemType == 5) {
  result = "type is 5"
} elseif (ItemType > 5) {
  result = "type is more than 5"
} else {
  result = "type is less than 5"
}

The less painful switch-case approach looks like this…

switch (ItemType) {
  case 5:
    result = "type is 5";
    break;
  case 3:
    result = "type is 3";
    break;
  default:
    result = "type is unknown";
}

If you fail to include the break; statements, the JS evaluator will continue running through the entire block of code like a blind bull in a China shop.  Real messy.

Visual LISP

(I’m picking up the banjo and harmonica now.  Imagining I’m telling a story beside a relaxed campfire.  Gather ’round kids…)

Visual LISP, like most other LISP dialects, is close to my heart for many reasons.  LISP was the first programming language I actually worked with (and got paid for).  It can spoil a programmer in some respects that are hard to adjust to later on.  One of my colleagues once said that “starting out with LISP is like having your first date with porn star”.  I don’t know what that means, so I just smile and nod.

The nature of LISP is very fluid, dynamic, and loosely structured.  The bounds are strictly enforced, like an electric fence.  But the inside yard is like a Woodstock festival with an open bar, a giant ball pit, a bungie jumper, catapult and swimming pool filled with dolphins, uhhh, in programming terms that is.

I went from LISP right to C++ and Java.  Talk about going from grilled steak to Sam’s Club frozen burger patties.  First World problems of course.  I know that sentence is going to piss off some die-hard nerds.  Sorry, but it’s just my way of expressing my experiences.

Less sophisticated geeks like to poke fun at LISP for the reliance on parentheses (…).  Yes, that was a jab.  (cough-cough).  But in reality, every language has some sort of duct-tape-bandaid that hurts to pull.  C# has the semi-colons.  VB has the semi-COBOL-ish verbose statement names.  And PowerShell has the rather tricky way of defining function argument sets.  Whatever.

All programming languages are great in some respect.  Just like food.  There’s something great and not-so-great about every type of food there is.  You find what tastes good, and doesn’t kill you, and move on.  Okay, I’ll admit that Ada was really bad.

Here’s a simple IF/THEN/ELSE construct done with LISP…

(if (= ItemType 5) 
  (princ "\nType is 5")
  (princ "\nType is not 5")
)

The LISP (cond) statement is short for “condition”, as in “checking the following condition” .  If the expression evaluates to True, the adjacent code is processed.  Otherwise, it moves to the next condition statement until it hits the “else” which is (t).  Think of (t) as “default” in JavaScript.

(setq ItemType 5)

(cond
  (= ItemType 5) (princ "\nType is 5") )
  (> ItemType 5) (princ "\nType is more than 5") )
  (t (princ "\nType is less than 5") )
)

Try this on…

(cond
  (= (+ ItemType 1) 5) (princ "\nType is 4")
  (> (* ItemType 1.5) 4.5) (princ "\nType is more than 3.5")
  (t (setq ItemType (fix (/ ItemType 0.75))) )
)

And I didn’t even pick up the bong with (lambda) or (mapcar) in the bowl.  Oh man. (mapcar + lambda + apply + read + eval = mmmmmmm….)  – Sorry.  I drifted off with a stupid grin for a second.  I’m okay now.

If you’re really into PowerShell, it does provide the means to tack on some semi-derivation with switch-case using things like -wcmatch.  But technically, that’s only deriving the input, not the condition checks, so it’s not getting admitted to my imaginary adult-oriented theme park.

KiXtart

Last but not least, I have to pay respects to KiXtart, aka “kix”.  The amazing product produced by Ruud van Velson, who works for Microsoft in the Netherlands.  The best way to describe this language is like this…

A bunch of over-caffeinated script writers are sitting around a table, legs shaking uncontrollably, trying desperately to see their smartphone screens through their smudged glasses, and one says “Hey.  Wouldn’t it be nice if we could borrow Tim’s blender, pour in Batch and VBscript some Perl-ish features, and make a nerd smoothie?”  And the others perk up “Hell yeah!” And they Ruud beat them to it.  Roll the credits.

Seriously, it’s got the familiar look and feel of Batch scripting, the nice features of WSH and VBScript, especially the ability to load COM tools like Scripting.FileSystemObject (even though you may not need it), or WMI namespaces and classes, and so on.  It supports library importing, like Perl and PowerShell do.   It supports object-oriented coding like Python, PowerShell, VB and C#, but it’s somehow magically managed to remain fairly simple.  Yes.  The command reference is surprisingly brief and yet doesn’t leave very many holes.

If you’re really familiar with Batch, and VBScript, you might feel some of the statements are *weird*, such as IF and ENDIF, or SELECT and ENDSELECT.  There’s also no sign of “then” to be found, which can kind of be a relief.

if $ItemType = 5 
  $result = "type is 5"
elseif $ItemType > 5
  $result = "type is more than 5"
else
  $result = "type is less than 5"
endif

And the somewhat related Switch-Case model uses the SELECT-CASE syntax as follows…

select
  case $ItemType = 5
    $result = "type is 5"
  case $ItemType = 3
    $result = "type is 3"
  case ($ItemType > 1) and ($ItemType < 3)
    $result = "type is 2"
  case 1
    $result = "type is unknown"
endselect

The biggest difference with SELECT in KiXtart is how it employs the LISP approach to evaluated condition checking.  But it also doesn’t require an explicit break to jump out of the condition block.  That’s one of the really cool things (besides the other being that it’s a truly “portable” engine that can be invoked within installing anything, even across a network if desired).

Perl

Perl and PHP share a lot of syntax, particularly in the basic condition checking realm.

if ( $ItemType eq 5 ) {
  $result = "alpha";
} else {
  $result = "beta";
}

The Perl switch statement is much like KiXtart (or the other way around actually).  It looks like it evaluates the input condition at each case level.  But it actually doesn’t.  It still works with static (scalar) values.

switch ($ItemType) {
  case 5 {$result = "alpha"}
  case 4 {$result = "beta"}
  case [1..3] {$result = "range between 1 and 3"}
  else {$result = "unknown"}
}

Hopefully, by this point you can see the similarities between languages such as Perl and PowerShell.

Adding Nerd Sauce

You may be thinking “so, when would I get an opportunity to use one of these other languages in my daily work?”.  That’s a fair question.  But don’t assume that a task can only be accomplished using one language.  Using Batch to invoke PowerShell or VBscript is not uncommon, but that’s only a rudimentary example of what I’m leading into here.  You can invoke nearly any program or script from any other.

If you get some free time, I strongly encourage you to explore this more on  your own.  Make a script that doesn’t just call another script with it’s unique handler (interpreter), make a script that writes the other script and then invokes it.  Scripting scripts.  Yes.  It’s not only feasible, it can come in handy for more situations than you’d expect.

This is like learning how to use multiple tools to build a shop project.  A table for example, usually involves more than one tool in order to cut, shape, assemble and finish the project.  The same can be said for other tasks in our daily lives.  You don’t usually cook a meal with only one ingredient (excluding microwave meals), and you certainly can’t brew decent beer with only one ingredient.   So, why is it programmers often insist one language is the optimal solution for every task?

Explore this if you can, but remember: there’s a difference between “can” and “should”.  But knowing the capabilities and options makes you more versatile and capable.  Like a karate student who returns from studying at different martial arts schools around the world, and comes back to kick truckloads of bad-guy’s asses.  Starts with Judo, switches to Kenpo and Jiu Jitsu, and finishes them off with Krav Maga and a cigar.

But seriously, as I mentioned near the top of this article, when you start to gather more familiarity with other tools, you inevitably create a virtual toolbox of resources you can apply to future tasks.  Don’t be surprised if one day you’re faced with an incredibly complicated project and you soon hear yourself picking it apart by proposing hitting individual pieces of the project with different tools and processes, all of which serve a common goal.

Summary

The point of all this is to ease you into looking at other languages than you may be currently familiar with.  Rather than beat you over the head with heavy books and tons of lecturing, it might be better to pick one area to compare them by (conditions).  Pick another task area, such as date values, or strings, and compare the features for that area between different languages.  That’s where you start to really figure out for yourself whether the language  you’ve been using is really the best tool for the job.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s