Skip to main content

Blogs

Easing code reuse and refinement through the use of the entity-component pattern

In software development, there's an axiom that states that you should reuse code when it's possible and useful to do so. Common sense, right? Why WOULDN'T you reuse code? Not only does it save you from reimplementing functionality that you may have written before in othe projects, it also plays a big role in ensuring that your code is as bug-free as possible, due to the (obvious) fact that as code is used over and over again, bugs will pop up and be fixed.

In my experience, people typically try to solve the code reuse 'problem' using inheritance chains. By definition, it is true that classes who inherit do reuse code that was written in the parent. HOWEVER, the little bit of code that gets reused in this instance is not worth the inevitable huge, hard-to-see inheritance chain that is created. Inheritance locks your classes into a rigid, fragile system that can be tedious and difficult to break out of. There IS another solution -- composition. Anyone who has taken an undergrad course in software engineering will be familiar with it.

Composition is the 'technique' where, instead of inheriting from a parent, you add an instance of a class containing some functionality you want as a data member to your class. This loosens things up considerably by not enforcing a strict hierarchy on your code. It is common place for a class to contain several data members that represent various pieces of functionality. This system of composition works really well; however, it still doesn't guarantee flexibility and ease of use, as each piece of functionality might have its own interface, and making changes to that interface could require refactoring.

Enter the entity-component pattern, which standardizes interfaces for both consumers (classes which use functionality) and producers (classes which provide functionality) and promotes the reuse and refinement (!!) of bundles of code across a program (or set of programs). In this system, components are little bits of specific functionality (say, a control system, a position tracker, or logging system), which you can add to an entity (basically an empty shell) to create objects with unique behavior.

The benefits of the entity-component pattern are numerous, chief among them being the capability to write bits of code that can be easily reused across a possibly disparate set of use cases. The hierarchy associated with inheritance-based code reuse is also nearly non-existant, as the only inheritance that should be going on is categorical in nature. It also makes it easy to keep track of which entities use a particular piece of functionality, and to create a function that can generate a list of those entities to work with. Crafty.js (a Javascript game programming library) does just this. It provides a jQuery-inspired selector function that allows you to specify a string of components, and it returns a list of objects that contain those components for you to act on.

This blog post is example-less, I know, so my next one will begin documenting my journey to implement a jQuery-inspired entity-component system in either Python or Ruby. You'll have all the sample code you can stomach!

Till next time,
Dustin

The Case of the Awesome Web Framework, or why jQuery is Fantastic

Hi, I'm Dustin Mays, a student developer in A&S Computing Services. For the past two or three months, I've been hacking away at a super-sekrit web app for a researcher here at A&S. Since I've previously only targeted traditional offline computer environments, and had no prior web development experience, I had no idea what I had gotten myself into. Unlike traditional software development, web development is, for lack of a better word, "rough". Before I get to the meat of my post, allow me to give you a little background (if you're familiar with software development, feel free to skip the next two or three paragraphs).

First, where traditional software is typically written using one programming language (and optionally a language for storing structured data), modern web applications and websites will use at least three languages: CSS, HTML and Javascript. For the uninitiated, HTML is a document layout (or markup) language: it describes what items are on a page, and their general layout; CSS is a style language: it allows for fine-tuning of an element's (any item on a web page, like a block of text, an image, a link, etc) appearance and position; and JavaScript (which I'll be talking about most in this post) is a scripting language (surprise!) that runs as part of the web browser, and allows for the implementation of interactive functionality and client-side (in-browser) applications.

Second, the typical web app/website will need to support the three big Windows browsers (IE, Chrome, Firefox), as well as Safari on Mac OS X. Naturally, since all of these browsers are written by different companies/communities, they will have unique quirks, bugs, and features that make cross-browser development challenging, at best, and at worst, drives even the best developers to insanity. Traditional software has this problem as well, and many solutions have been implemented, the most popular class of solutions being the cross-platform frameworks. Cross-platform frameworks are bundles of code that wrap up similar functionality across disparate platforms and provide a common interface to that code. This allows the application developer to code against and deploy for the cross-platform framework, rather than the underlying operating systems directly. As you can imagine, this helps to make things much simpler for developers. Examples of cross-platform application frameworks include the GTK toolkit, the Qt toolkit, wxWidgets, FLTK, and GNUStep.

In the past few years, a similar trend has come about in the web development community. These tend to go by different names, depending on what buzzword or marketing point is the most popular, and are usually called cross-browser frameworks, or JavaScript frameworks, or Ajax frameworks. Web developers are now able to include one (or more!) of these frameworks in their websites and code against them, rather than having to target browsers and implement browser-specific functionality all the time (although it's still necessary once in a while).

Whew! That was a lot of background. Now we can get back to talking about my web app. Like I mentioned earlier, when I started on this web app, I was pretty inexperienced as a web developer. To make my life simpler, I checked out various web app frameworks, and was dissatisfied with nearly all of them; they either wanted to take control of the web app, or their programming interface was wonky, or they had too much functionality, or not enough functionality. Finally, though, I came across jQuery. jQuery. Just thinking about it makes me want to hack on something.

jQuery is a JavaScript framework for the developer who just wants to GET THINGS DONE with minimal fuss. It doesn't force a specific programming style on you, it doesn't force unnecessary boilerplate code or "features" on you, and it doesn't force ridiculous limitations on you. jQuery allows you to use the functionality that you want, when you want it, and it makes it super simple to do so.

jQuery has been a huge boon to me. For example, I like to split my code into manageable, logical chunks. This is standard practice in both JavaScript development and the traditional desktop software world, but HTML doesn't account for that, as it's expected that ALL the HTML code that's necessary for a page is in one big HTML file. This runs contrary to how I think and work, and jQuery had a solution: the jQuery.load() method.

Example Code:
---main.html---
<html>
   <head>
      <title>MAIN.HTML PAGE</title>
      <script src="js/jquery.js">
      <script src="js/main.js">
   </head>
   <body>
      <div id="iamadiv">
      </div>
   </body>
</html>

---helloworld.html---
<p>HELLO WORLD</p>

---js/main.js---
(function ($) {
   $("#iamadiv").load("/helloworld.html");
})(jQuery);

This is a very contrived example, but it is representative of the solution jQuery had for my problem. Basically, the code in js/main.js gets executed when its file is loaded, and then it loads the helloworld.html file and copies its contents into the div "iamadiv". The result is shown in the screenshot below.



The other example I want to cover is the ease with which jQuery enables the modification of the HTML document at runtime, of which you got a taste above. jQuery has this awesome feature called selectors, which enable you to easily select entities inside the DOM (the HTML document object model, which is basically a tree-like structure of everything in the current document). It looks like this:

--code--
$("#iamadiv")
--------

Note: jQuery has a function called jQuery(), which is how you access ALL the jQuery functionality. For simplicity's sake, they created a shortcut to jQuery() called $(). It's the same thing, just easier to type.

$() takes an argument, or series of arguments. These arguments are the selectors. Using CSS notation (and sometimes some jQuery-specific notation), you can pass as arguments the HTML entities that you want to modify. Not only can you select single entities (using the id selector "#"), you can select GROUPS of entities. There are many different ways to select groups, but the most popular are by HTML class and by entity type (e.g. all text inputs, all paragrahs, all divs, all buttons). This ability to modify the document at runtime has made it intuitive to create HTML forms where I can add extra options when a user clicks a button, add items to lists dynamically, and, when combined with jQuery UI, theme UI elements (like buttons, text boxes, etc).

Example Code:
---main.html---
<html>
   <head>
      <title>JQUERY SELECTOR AND JQUERY UI EXAMPLE</title>
      <script src="js/jquery.js"></script>
      <script src="js/jqueryui.js"></script>
      <script src="js/main.js"></script>
      <link type="text/css" href="css/smoothness/jquery-ui-1.8.13.custom.css" rel="Stylesheet" />
   </head>
   <body>
      <button id="supabutton">CLICK ME</button>
      <div id="textcontainer">
      </div>
   </body>
</html>

---main.js---
$(document).ready(function () {
   $("button").button(); // this uses the jQuery element selector to select all button entities,
});                                // and calls the jQuery UI button() method on the selected buttons to make them pretty!

$("#supabutton").live('click', function () {
   $("#textcontainer").append("WOAH<br />");
});

This bit of code requires the jQuery and jQuery UI libraries. The HTML file is all very hum-drum, nothing exciting in it, except for the inclusion of the jQuery and jQuery UI libs and CSS file. main.js is where the cool stuff happens. In here, there is a function $(document).ready(). This gets called after the HTML page has finished loading. In this function is a call to $("button").button(). This uses the jQuery element selector to select all buttons in the document (which in this case is ouronly button, supabutton) and calls the jQuery UI function $.button(). This applies the jQuery UI button theme to our button. Nifty.

Next is the $.live() function. Basically, what this does is add an event handler to every supabutton that is created (in this case, just the one). Event handlers are a way for a web site/web app (or any application, really) to respond to external stimuli, such as a button press, a resize of the browser window, editing of a text box, etc. In this case, this bit of code adds an event handler to supabutton for the 'click' event, and when supabutton is clicked, it appends the text 'WOAH' to the #textcontainer div. Awesome! This is realtime modification of the HTML document! Screenshots of this example are below.

Fig1. This shows the page in its fresh, just-loaded state. Note that the button has been themed by jQuery UI, and there is no other text on the page.



Fig. 2 Now, after clicking the button a few times, several lines with the text 'WOAH' have been added. Neat!



I hope I've given you an adequate taste of the awesomeness that is jQuery. It has really made my life easier, and my work immensely enjoyable. For those that are inclined, don't be afraid to try it! There is a small learning curve at first, especially with selectors, but everything after that is smooth sailing. Enjoy!

 

Edit:  Whoops! Forgot to add links to jQuery and jQuery UI.  jQuery jQueryUI