Lazycoder

6Oct/103

A third option for using jQuery templates

Dave Ward has a great post about defining jQuery templates. There's a third method that he doesn't mention in his post. The "embedd-and-grab/clone" method. I've used this method before for simple element cloning of templates.

HTML:
  1. <div id="templates">
  2.     <div id="hello">
  3.         <p>Hello, ${name}.</p>
  4.     </div>
  5. </div>

We can create a div, or really any element you want, to hold our templates. What does this gain us? Well if we are using a design tool, we can see what the template will look like before we have to render it. That may make it easier for a designer on your project. We don't have to make an AJAX call out to retrieve the external template, although Dave talks about how this really isn't an issue if you have caching set up correctly on your server. And frankly, for the amount of bytes that are in a typical template I can't imagine any successful AJAX request taking very long.

To use them, you simply grab the templates div and detach it from the DOM. If you assign the detached elements to a var, you can just use jQuery selectors to find the one you want to use. Because, remember most of the jQuery methods return the jQuery object itself.

JAVASCRIPT:
  1. var templates = ​$("#templates")​​​​​​​​​.detach();
  2. $.tmpl(templates.find("#hello").text(), person);​​​

Why do you want to use the detach method rather than the remove method? The detach method removes the elements from the DOM but keeps any jQuery data associated with them intact. Meaning you can use the $.data() method to add data to your templates and access the data before you compile your templates.
Dave Ward points out that I need to use "tempates.find()" rather than the default selector method on the jQuery object. Noted and updated

30Jun/1012

The hardest part of software development has nothing to do with code

People who complain about how much "more" code they have to write in an MVC project versus a Webforms project, or really any project, prove to me that they have absolutely no idea where the REAL work is in ANY development project.

The main work in any software development project is FIGURING OUT WHAT TO BUILD. How you build it is trivial compared to the amount of time and effort you SHOULD put into discovering the users needs and working with them to solve their problems and make their life better.

Remember, that's the number one purpose for any piece of computer hardware or software. This cannot be stressed and repeated enough.

COMPUTERS SHOULD MAKE OUR LIVES BETTER!

How do we write programs that make lives better? By writing programs that fulfill their needs and ease the pain of their work. We still aren't at a point where we have a common, easy to understand vocabulary when it comes to build software. We often get it wrong the first, second, and third times. That's where the discipline and engineering comes into play.

10Dec/098

Benchmarking a simple DOM based cloning template

Sara Chipps recently posted a simple DOM based clone template method she uses in one of her apps. "Easy HTML Templating with JQuery"

My template looks like this:

CODE:
  1. <script id="ItemTemplate" type="text/html"
  2.         <li class="item" value="|rowNumber|">
  3.               <input type=”text” id=”input|rowNumber|” />
  4.         </li>
  5.     </script>


Now within my code I need to put a place holder where I want my HTML to go. I have my unordered list called url_list.

CODE:
  1. <ul id="url_list"></ul>

Now, you see that most of my items look like this “|rowNumber|” I have a variable in my code called nextUniqueItemID (I believe in extremely descriptive variable names). Here is my “addItem” function.

JAVASCRIPT:
  1. function addItem() {
  2.         var list = $('#url_list'),
  3.                       items = list.find('li');
  4.         list.append($('#ItemTemplate’)
  5.                                     .html().replace(/\|rowNumber\|/gi, nextUniqueItemID++))
  6.     }

The use of global variables aside (cough,cough),I looked at it and, having used something like this myself, thought that it would work find for data sets containing a very small number of items. The problem is these kinds of clone based templates are VERY slow compared to the templating engines that are available for various JavaScript libraries.

I happened to read a post by Brian Landau called "Benchmarking Javascript Templating Libraries" this morning and wondered just HOW MUCH slower is the naive template method than a good template library?

I grabbed the benchmarking code and modified it to run the new clone based template method.

JAVASCRIPT:
  1. var nextUniqueItemID = 0;
  2.     function addItem() {
  3.         var list = $('#url_list'),
  4.         items = list.find('li');
  5.         list.append($('#ItemTemplate').html().replace(/\|rowNumber\|/gi, nextUniqueItemID++));
  6.     };
  7.    
  8.     $(document).ready(function(){
  9.         var output = $('#output');
  10.         $.benchmarks = {};
  11.    
  12.       $.benchmarks.test_simple = function(){
  13.         addItem();
  14.       };
  15.      
  16.       $.benchmarks.loop_test = function(){
  17.         for (var i=0; i <5; i++){
  18.           addItem();
  19.         }
  20.       };
  21.  
  22.       // use these lines to run the benchmark tests in your browsers JS console
  23.       // $.benchmark(1000, '#simple_test', $.benchmarks.test_simple);
  24.       // $.benchmark(1000, '#loop_test', $.benchmarks.loop_test);
  25.     });

Since the template Sara provided contains an input tag you get a different benchmark if you run the simple_test and the loop_test separately after refreshing your browser. You can run the tests for yourself here, the loop test *may* cause your browser to give you a "script is running slow" message, hit continue as the loop will eventually end. You may also get different numbers if you run the tests in IE, Chrome, and Safari.

results: using FF 3.5.5
Simple Test: 1.71s
Loop test: 31.534s

When you consider that the slowest loop test using a template library was just around 4.5s, you get a better idea of just how slow this method is when you have an input in your template.

So that's fine, but it's known that dynamically adding text inputs is slow in just about every browser and the original tests don't use inputs at all, just divs. So let's modify the template and see what the results are.

CODE:
  1. <script id="ItemTemplate" type="text/html">
  2. <div class="test"><h2>This is a test of |name|</h2><p>The homepage is <a href="|url|">|url|</a>.</p><p>The sources is: |source|</p></div>
  3. </script>

I modified the addItem function to account for the new data. n.b. The data I'm using is static, if you wanted to use a data source you would just modify this method to take in your data parameters.

JAVASCRIPT:
  1. function addItem() {
  2.         var list = $('#url_list'),
  3.         items = list.find('li');
  4.         list.append($('#ItemTemplate').html()
  5.             .replace(/\|name\|/gi, "Clone template method")
  6.             .replace(/\|source\|/gi, "http://girldeveloper.com/waxing-dev/easy-html-templating-with-jquery/")
  7.             .replace(/\|url\|/gi, "http://girldeveloper.com/waxing-dev/easy-html-templating-with-jquery/"));
  8.     };

results using FF 3.5.5 - refresh between each test
simple test: 1.285s
loop test: 3.771

results using ff 3.5.5 with no refresh between tests
simple test: 1.434
loop test: 4.227

So that's looking a little bit better. Not too much slower than the template libraries.

So what do the template libraries give you? Well the replace method works find provides your data is escaped properly. But say instead of a url in the "source" replacement, you use a file path like "file:\\foodrive\source.txt". Well it still gets replaced, but the text looks like this "file:\foodrivesource.txt". So in addition to the replacement, you have to make sure your data is properly escaped. A lot of template libraries will do this for you. Also notice that the addItem method has to do a DOM lookup on every iteration of the loop to get the template. If you have a large DOM, this could impact the performance.

3Nov/0910

Dependency Injection and Inversion of Control are not rocket surgery

I see a lot of people talking about how “advanced” techniques like dependency injection and inversion of control are and how their team won’t understand either technique.

 

Folks, this isn’t hard. In fact, both of these things are so simple I simply call it “using the programming language”.

 

Let’s look at dependency injection.

C#:
  1. public class MyClass
  2.     {
  3.         private DataTableReader _reader;
  4.         public MyClass()
  5.         {
  6.             _reader = new DataTableReader(new DataTable());
  7.         }
  8.         private void DoStuffWithTheReader()
  9.         {
  10.             while (_reader.Read())
  11.             {
  12.                 //do fun stuff with the reader.
  13.             }
  14.         }
  15.     }

See the reader variable? That's a dependency. You have to have it in there to do fun things later on. But we have to create it ourselves, which is one more thing that we have to do in our class constructor. In reality we also have to populate the DataTable. So what if we make the reader variable constructor parameter so that another class can do the work of creating the DataTable and the reader?

C#:
  1. public class MyClass
  2.     {
  3.         private DataTableReader _reader;
  4.         public MyClass(DataTableReader dataTableReader)
  5.         {
  6.             _reader = dataTableReader;
  7.         }
  8.         private void DoStuffWithTheReader()
  9.         {
  10.             while (_reader.Read())
  11.             {
  12.                 //do fun stuff with the reader.
  13.             }
  14.         }
  15.     }

There, that's better. Now our class doesn't have to worry about creating the reader and the DataTable. This, in a nutshell, is dependency injection. It's not very complicated is it? We've made our class construction a little simpler and if we want to unit test this, we don't have to do any complicated mocking, we can just new up our own DataTableReader instance and populate it with whatever test data we want. If you run into any funny looking data in the DoStuffWithTheReader method, you know that you don't have to look in this class at all to see where the funny data is coming from, only in whatever method is creating this class and passing in the DataTableReader.

Now is there anyone who thinks that developers on their team would have trouble understanding passing in a parameter? Should they really be a developer if they do?
Honestly, it's not that hard.

Ok, so let's look at inversion of control. The original definition of inversion of control I read was by Martin Fowler:

There's a big difference now in the flow of control between these programs - in particular the control of when the process_name and process_quest methods are called. In the command line form I control when these methods are called, but in the window example I don't. Instead I hand control over to the windowing system (with the Tk.mainloop command). It then decides when to call my methods, based on the bindings I made when creating the form. The control is inverted - it calls me rather me calling the framework. This phenomenon is Inversion of Control (also known as the Hollywood Principle - "Don't call us, we'll call you").

If you look at the previous example, you'll see that we have already inverted the control a bit just by using dependency injection. But the class still has a degree of control over WHAT concrete object is created, in this case a DataTableReader. What if we need to switch over to a SqlDataReader or an OleDbDataReader? Well, we could create three other classes that all take the specific type of data reader we might want to use. But that's a bad idea, you end up with the same logic spread all over the place. Instead we can use the IDataReader interface that all three classes implement.

C#:
  1. public class MyClass
  2.     {
  3.         private IDataReader _reader;
  4.  
  5.         public MyClass(IDataReader dataTableReader)
  6.         {
  7.             _reader = dataTableReader;
  8.         }
  9.         private void DoStuffWithTheReader()
  10.         {
  11.             while (_reader.Read())
  12.             {
  13.                 //do fun stuff with the reader.
  14.             }
  15.         }
  16.     }

Now our class not only doesn't have to worry about creating the DataTableReader, it doesn't even really care if it gets a DataTableReader at all. All it cares about is that the reader is referencing something that implements the IDataReader interface. This is a type of inversion of control. Most of the time people get confused between inversion of control and a container that enables inversion of control and dependency injection (like Ninject, StructureMap or Unity). You don't have to use a container to utilize these two techniques, it just makes it a little easier.

update:Also check out this great post "It’s all about the delivery"

update: I mistakingly thought it was hard to do D.I. in Python due to the inheritance mechanism in Python. Turns out, it's just as easy.

PYTHON:
  1. class MyClass():
  2.  
  3.     def __init__(self, dataTableReader):
  4.         self._reader = dataTableReader
  5.        
  6.     def DoStuffWithTheReader(self):
  7.         while(self._reader.Read()):
  8.             #Do Fun Stuff with the reader.
  9.             print(self._reader.item)

12Oct/099

Mocks versus stubs and fakes

I dislike using mocks I dislike using dynamic mocking/stubbing frameworks. because it means my tests have an extra dependency beyond just the SUT (System Under Test). I often find myself spending more time getting the mock to work correctly rather than my app code. The lambada + generics based Mock suites (Moq, RhinoMocks, etc), IMO, complicate the test and make them unreadable in some situations.

 

Compare the two examples in this post. One uses RhinoMocks to create a stub of IDataReader and the other uses the DataTableReader to create a stub for the test. Which example is simpler and has less chance to fail due to the stub?

 

 http://www.lazycoder.com/weblog/2008/12/12/mocking-idatareader-using-rhinomocks-35/

Using RhinoMocks

C#:
  1. IDataReader reader = MockRepository.GenerateStub<IDataReader>();
  2.             reader.Stub(x => x.Read()).Return(true).Repeat.Times(1);
  3.             reader.Stub(x => x.Read()).Return(false);
  4.             reader.Stub(x => x["ID"]).Return(Guid.Empty);
  5.             reader.Stub(x => x["FullName"]).Return("Test User");

Using DataTableReader

C#:
  1. DataTable table = new DataTable();
  2.             DataRow row = table.NewRow();
  3.             table.Columns.Add(new DataColumn("ID"));
  4.             table.Columns.Add(new DataColumn("FullName"));
  5.             row["DirectoryUserID"] = Guid.Empty;
  6.             row["FullName"] = "Test User";
  7.             table.Rows.Add(row);
  8.             DataTableReader reader = new DataTableReader(table);

Stubs/Fakes allow me more control over HOW the test fails and results in a test/fixture that is easier to read. I'm not saying that mocks aren't useful in certain situations, but I would favor a stub over a mock IMO, your test should only fail because of the code it is testing, not because of a mock.

 

Although it is fun to say "Mock ME? No mock YOU!".

update: I forgot to link to Rob's post that inspired this post. "Using Dependency Injection and Mocking For Testability"

update to the update: Jeremy Miller and Nikola Malovic both pointed out that I'm using the terminology incorrectly. It turns out I don't specifically hate mocks themselves, I dislike use dynamic mocking/stubbing frameworks due to the extra dependency they introduce into my tests. Thanks for the corrections. Back to reading Fowler for me!

14May/090

7 Habits For Effective Text Editing 2.0

Filed under: Tutorials No Comments