• Easy Object Oriented JavaScript

    I love object oriented programming. Not because I have the crazy misconception that it is the ultimate programming paradigm but because it fulfills my desire to organize, categorize and modularize my code. Consequently I like to bring OO ideas into whatever language I’m working on. Now being primarily a ColdFusion developer I work a lot with JavaScript. But one thing that really took me a while to get a grasp of is making my JavaScript code object oriented.

    I happen to really like JavaScript…mostly. It has some really weird quirks sometimes and parts of it seem poorly designed but overall it is a very powerful and fun language to work with. Its power and quirkiness is very evident when trying to write object oriented code. There seem to be at least three ways to write OO code with JS with all three being completely different. JavaScript just isn’t clear when it comes to OO and doesn’t have any easy to use mechanisms for doing things like inheritance. This is what really tripped me up for a long time. I’d read tutorials and books that would cover the subject (OO) but they’d all do things differently and not explain why they were doing it the way they were.

    Thankfully though I stumbled upon Douglas Crockford’s JavaScript videos this year and opened my eyes on a few things when writing object oriented code. This is what I’ve learned and how I do OO with JavaScript now.

    First thing first, objects. In JS, creating an object is as easy as doing the following:

    myObject = {};
    

    Wow, that was easy. No “new” operator or any other mumbo jumbo (is new considered an operator?). Just that one simple line. That simple line creates a singleton object as soon as it is executed. Usually though, you want to have some actually have some functionality in your objects so let’s do that now. There are a couple of ways to do that.

    // OPTION 1
    myObject1 = {
        sayHello: function(){
            alert("hello world");
        },
        sayGoodbye: function(){
            alert("goodbye");
        }
    }
    
    myObject.sayHello(); // alerts hello
    myObject.sayGoodbye(); // alerts goodbye
    
    // OPTION 2
    myObject2 = {};
    
    myObject2.sayHello = function(){
        alert("hello world");
    }
    
    myObject2.sayGoodbye = function(){
        alert("goodbye");
    }
    
    myObject2.sayHello(); // alerts hello
    myObject2.sayGoodbye(); // alerts goodbye
    

    Both option 1 and option 2 do the same thing but have somewhat different syntaxes. I don’t know if I use either more than the other. It just depends of the circumstances.

    Now one thing you might be wondering is how to have multiple instances of this object? JavaScript doesn’t really have a concept of classes, only objects, which is what this is. Essentially, you’d need to make a new copy of the object every time you wanted a new instance. This is actually very, very easy to do. Simply wrap the object in a function that returns a new instance. Here is how it works.

    function myObject(){
        var obj = {};
    
        obj.sayHello = function(){
            alert("hello world");
        }
    
        obj.sayGoodbye = function(){
            alert("goodbye");
        }
    
        return obj;
    }
    
    myObject = myObject();
    myObject.sayhello();
    myObject.sayGoodbye();
    

    The wrapper function acts as a class and constructor for the object. Every time the myObject function is called it returns a new instance of your object. You can even have private methods and can pass in constructor parameters.

    function greeter(name){
        var obj = {};
        obj.name = name;
    
        // private function
        function greet(){
            alert("hello " + obj.name);
        }
    
        obj.sayHello = function(){
            greet();
        }
    
        return obj;
    }
    
    myObject = greeter("Dustin");
    myObject.sayhello(); // alerts "hello Dustin"
    

    Simple and concise. Another nice thing about this method is that inheritance is a breeze.

    function parentObject(){
        var obj = {};
    
        obj.sayGoodbye = function(){
            alert("goodbye");
        }
    
        return obj;
    }
    
    function greeter(name){
        // This causes the object to "inherit" from parentObject
        var obj = parentObject();
    
        obj.name = name;
    
        // private function
        function greet(){
            alert("hello " + obj.name);
        }
    
        obj.sayHello = function(){
            greet();
        }
    
        return obj;
    }
    
    myObject = greeter("Dustin");
    myObject.sayhello(); // alerts "hello Dustin"
    myObject.sayGoodbye(); // alerts "goodbye" - sayGoodbye is inherited from parentObject
    

    What is happening is that greeter calls the parentObject “constructor” to get an object, then modifies it with its own methods, essentially inheriting the functionality from parentObject. Very powerful but very simple. This is only possible because JavaScript objects are modifiable. Many language do not allow objects to be modified with new methods but JavaScript is an exception. Scala, Ruby, and other languages allow this and, in my opinion, this makes for some very concise yet powerful features.

    Unfortunately, this method of doing OO in JS is not something I’ve seen even though it is very straight forward. I suspect that is because object mutability seem to be a rare thing among most mainstream languages like Java. As languages like Ruby gain in popularity I imagine that might change.

  • Old School Batch Programming and Code Generation

    Recently I had the opportunity to do some old school Windows batch file programming at work. At first I was not too interested in using a language (is that even the correct word for it?) as old as DOS, but after I got into the project it was actually rather fun.

    First, a little back story about the project. The company I work for uses many mainframe systems today that it has used for decades. But, like most big companies, it has many modern server systems as well. To use these systems together we often have to move files containing large amounts of data between servers and mainframes. To accomplish this task, a piece of software called Connect:Direct is used.

    Because of the way we used this software, the setup and maintenance was really a pain. First, to setup a file to be moved to/from a mainframe and server, a Connect:Direct “process” has to be setup which consists of a file containing some propriety code to instruct Connect:Direct on what the process should do and how it should run. The file was just text containing some code with a CDP extension. In addition to the CDP file, we had two more simple files per process. One simple batch file so the users of the process can run it simply by double clicking on an icon and a simple text file to be used by the batch file which contains some instructions on which CDP file to use and some variables to use. What that meant was three files per process and a maintenance nightmare. Why a maintenance nightmare you ask? Because a server was recently done away with so every single of our 300 files had to have some details changed.

    Since my coworkers and I knew we would have to change many files we decided to streamline the process a bit. Initially we decided to just combine the batch files into one and have a simple menu so the users could choose the process they wanted from there. Since I was the one writing the batch file I got to work.

    After a bit of work though, I realized that more could be done than merely combining the batch files – we could actually do some code generation. That’s right, code generation with a batch program. Now obviously it couldn’t be too complex seeing how this would be done in a batch program, but a rudimentary form of code generation is possible.

    What I ended up doing was generating the text and CDP files on the fly, executing the Connect:Direct process with them, and then deleting the files afterwards. All the configuring is done in the batch file by setting few variables containing the changing data. What this resulted in was the elimination of 300 files and and extremely easy way to modify processes as well as an easy way to add new processes in the future.

    Before this project I had done a very limited amount of batch file work before. Perhaps what we did could have been done in some other “better” way, but I doubt in the time it took to get this up and running. Batch files might not be very sophisticated, but don’t underestimate there power. Under the right circumstances, they can really prove to be invaluable.

  • Getters and Setters in Scala

    In object oriented programming, getters and setters are something that most would agree have some real world benefits. Unfortunately, they can sometimes be annoying to write. They usually do not consist of a lot of code, but when you have the write the same thing over and over and over it gets old really fast. In my experience, most getters and setters are very much alike so it stands to reason that there must be a “better” way to accomplish the same result.

    In some languages there is support of some kind of “missing_method” syntax that allows the language to dynamically create getters and setters just by looking at the name of the method that doesn’t exist in the object. For example, in ColdFusion, there exists an “onMissingMethod” method that, when included, automatically executes when a method does not exist. This onMissingMethod gets passed the method name that was trying to be accessed and any arguments passed in. Then, by inspecting the method name (lets say, setAge) the method type and property can be determined. From “setAge” it can be determined that the method is a setter and that it should set the property “age”.

    Recently though I’ve done a lot of reading about and playing with Scala and I’ve found that it does things quite a bit different than ColdFusion, Java, and most other languages I’ve seen.

    As a first example, lets see an example of a basic class definition in Scala.

    class Person() {
     var name = ""
     var age = 0
    }

    At first glance you might think that this class only allows you to instantiate a person object but not anything more. But actually, once instantiated, you can set and get the properties by doing the following:

    // Instantiate a person object
    person = new Person()
    
    // Print the object's age and name properties
    println(person.age)
    println(person.name)

    To set the properties to different values you would do the following:

    // Set the properties to different values
    person.age = 34
    person.name = "Dustin Martin"

    Pretty simple so far. You might be thinking to yourself the same thing I thought when I saw an example like this: these aren’t getters and setters! And you are right, that is not what this is. This is simply retrieving the public properties directly from the object. In most languages this would be a very bad idea. What happens when you need to validate the age is in a certain range before it is set? What happens if you want to format the name in a particular way before returning it? In Java or other languages you would be in trouble right about now and probably kicking yourself for not taking the time to write getters and setters. If you wanted to switch from directly accessing the public properties to getters and setters you would either have to find some strange work-around or implement the getters and setters and change any code that access those properties directly to use the getters and setters instead.

    In Scala though, it is no big deal to directly access public properties. You could easily change to using getters and setters by making a couple simple changes to your class.

    class Person() {
     // Private age variable, renamed to _age
     private var _age = 0
     var name = ""
    
     // Getter
     def age = _age
    
     // Setter
     def age_= (value:Int):Unit = _age = value
    }

    What this code is doing is pretty simple. First, the variable “age” is renamed to “_age” and made private with the private keyword. Next, the getter is added by the line:

    def age = _age

    This code simply defines a method called “age” and returns the “_age” variable. Scala doesn’t require the return keyword but it would just have easily be written as:

    def age = return _age

    In addition to not requiring the return keyword, Scala doesn’t mandate the use of curly braces around a method body if the body consists of a single expression.

    Next, a setter had to be added to set the new private variable.

    def age_= (value:Int):Unit = _age = value

    This line is a bit more tricky but I’ll explain. First, the method name is “age_=“. The underscore is a special character in Scala and in this case, allows for a space in the method name which essentially makes the name “age =”. The parentheses and contents dictate the value and type that needs to be passed in. The “:Unit” code is equivalent to returning void. The remaining code is setting the “_age” variable to “value”. These things allow the method to be used in the same way as directly accessing the public property.

    person.age = 99

    But wait! Where are the parentheses in this supposed method call?! In Scala, parentheses are usually optional. The previous line could just as easily been written as

    person.age =(99)
    // OR
    person.age_=(99)

    As you can see, Scala has some unconventional ideas that provide a solid, well thought out, and an abbreviated syntax to access object properties.