Intro to Objects in JavaScript

Despite what you might think, JavaScript supports programming in full object oriented style including inheritance, encapsulation and polymorphism. But before we dive into all those topics I’m going to start with the basics and demonstrate how to create and use a simple JavaScript object.

Lets say you have a web application that needs to track how long an AJAX request took. If you were writing it in Ruby, PHP or Python you’d have a timer object that you can start() and stop() and a seconds() method to get the number of seconds that passed between calling the first two methods.

To build this in JavaScript we first create our constructor:

Timer = function() {
  var seconds_passed = 0;
}

Here we are creating a Timer object with a private seconds_passed variable. To create this object we we simply create a new timer:

var elapsed_timer = new Timer();

This timer object now needs some public methods. We can attach a public method by using this.method_name:

Timer = function() {
  var seconds_passed = 0;

  this.start = function() {
    // implementation here
  }
}

Our Timer class now has a start() function. Additional public methods can be added in the same way.

To add a private method, don’t define it with the this keyword but instead create a regular function inside the class:

Timer = function() {
  function increment() {
    // implementation of private method here
  }
}

Now we have a Timer object with a public start method and a private increment method. The rest of the class is fairly simple, so lets jump to the finished solution.

Complete Example

Timer = function() {
  var timeout_id = null;
  var seconds_passed = 0;

  this.start = function() {
    increment();
  }

  this.stop = function() {
    clearTimeout(timeout_id);
    timeout_id = null;
  }

  this.seconds = function() {
    return seconds_passed;
  }

  function increment() {
    seconds_passed++;

    timeout_id = window.setTimeout(
      function() {
        increment();
      }
      , 1000
    );
  }
}

var elapsed_timer = new Timer();
elapsed_timer.start();

// do some stuff

elapsed_timer.stop();
alert(elapsed_timer.seconds());

There you have it. A simple JavaScript timer to keep track of time.

Software Complexity

Have you ever worked on a software project where you had no idea what would happen to other parts of the system if you made a code change? I have, but I have been able to ask developers on my team that know the system better than I do.

If it’s a larger software project and nobody on the team knows what a change would do, then it would be fair to say the software is overly complex and making forward progress is like wading through a swamp. Software projects, especially larger software projects absolutely must have code that is understandable. When designing software applications, a key component to the architecture is managing complexity to a workable level.

Managing complexity is the most important technical topic in software development. In my view, it’s so important that Software’s Primary Technical Imperative has to be managing complexity.

– Steve McConnell in Code Complete

Unless its a small project, no software developer can contain the design, constraints, and all the technical details in their head at the same time. Software must be made modular so that a developer can work on one section of code without worrying about the rest of the project.

How do you deal with complexity?

  1. Break up the problem into sub-problems and sub-tasks so you don’t have to solve everything at the same time.
  2. Contain the complexity to one part of the code.
  3. Before you solve the complex issue take a step back and make sure you have to solve it that way. There might be a vastly simpler problem that you can solve that will still fulfill your requirements.

Tackle software complexity before it defeats your software project.

Catch Symfony Form Errors

Have you built a form while developing with the symfony form framework that appears to work fine but fails because of an unknown error? Here is the simplest and easiest way to catch most errors.

First open the web page with the form and fill it in with valid input. Then, open the form php file, temporarily delete all your custom form render code and replace it with echo $form. Go back to the web page and click your form submit button. It should show you any validation errors that appear in the form but were missing on your customized version, because this time it’s rendering the form with the default settings. At the very least it could show you something you missed and hint at the solution.

Your test form would look like this:

<form action="<?php echo url_for('user/'.($form->getObject()->isNew() ? 'create' : 'update').(!$form->getObject()->isNew() ? '?id='.$form->getObject()->getId() : '')) ?>" method="post" <?php $form->isMultipart() and print 'enctype="multipart/form-data" ' ?>>
<table>
  <tfoot>
  <tr>
    <td>
      <?php echo $form->renderHiddenFields() ?>
      <input type="submit" value="Save">
    </td>
  </tr>
  </tfoot>
  <tbody>
    <?php echo $form ?>
  </tbody>
</table>
</form>

Symfony CRUD Generator

The symfony CRUD generator is a very useful tool for speeding up your web development. When you need a list of items that you can list and edit, you are most likely building a standard CRUD (create-read-update-delete) interface. This is common functionality that is found in most applications. Since this is such a common task, it makes perfect sense that the symfony web framework has a tool to build it for you.

For example: Lets say your web application allow users to sign-up (surprise!) and you need a user management tool in the admin section to manage these users. To create this in symfony, you’d run the following:

./symfony propel:generate-crud admin user User

This assumes you have an admin application, and a User model file. With that one line, it will create a listing of all users with the ability to edit and delete them. It generates HTML and PHP code that you can modify to your requirements. Fantastic for less than a minute of work!