May 26, 2010

PURE HTML Templates

I’ve been pressured into writing about PURE templates by a couple of my colleagues at ThoughtWorks. My blogging has died down after rolling off my previous iPhone project, but while doing some work in ASP.NET MVC I came across something useful. A very nice HTML templating engine.

My biggest complaint when looking at HTML templating engines is that they are very similar to PHP or ASP code, littering my HTML with different forms of placeholders. They are very simple and quick to pick up, but very limited once you need to do something more than map A onto B without creating a lot of one off functions that will fit in one line.

<script type="text/html" id="item_tmpl">
  <div id="<%=id%>" class="<%=(i % 2 == 1 ? " even" : "")%>">
    <div class="grid_1 alpha right">
      <img class="righted" src="<%=profile_image_url%>"/>
    </div>
    <div class="grid_6 omega contents">
      <p><b><a href="/<%=from_user%>"><%=from_user%></a>:</b> <%=text%></p>
    </div>
  </div>
</script>

Introducing PURE Templates

Have a look at this fully functional example (view source) using PURE. There is some HTML and a small script block. In the block is a javascript object literal representing the data and a single call to PURE giving the root of the HTML template and the data to render. Clean HTML, very little code and no dirty template placeholders. This shows that, in the happy day scenario, PURE is very simple and easy to use, like most other templating engines.

However, as the web becomes more and more about creating and interacting with services. Consuming third party sources becomes necessity and those sources will not be providing data in the human readable format your require, nor will their names be exactly what you need.

For these situations, we need something more powerful than all these happy day templates can provide (assuming you don’t just want to remap everything you consume). In PURE, they accommodate this by way of a Directive. At a basic level, a directive is a javascript object literal defining how to map your data onto your HTML. The keys are CSS Selectors and the values are Actions, where Actions can be strings, objects or functions.

  <!-- HTML template -->
  <ul>
    <li></li>
  </ul>

  <script>
    var data = {
      legs:4,
      animals:[
        {name:'dog', legs:4},
        {name:'cat', legs:4},
        {name:'bird', legs:2},
        {name:'mouse', legs:4}
      ]
    };

    //declaration of the actions PURE has to do
    var directive = {
      'li':{
        'animal<-animals':{
          '.':'animal.name'
        },
        sort:function(a, b){
          return a.name > b.name ? 1 : -1;
        },
        filter:function(a){
          return a.context.legs === a.item.legs;
        }
      }
    };

    // note the use of render instead of autoRender, and the 2nd argument
    $('ul').render(data, directive);
</script>

source

The above example  shows what a directive looks like while consuming data that must be iterated over. It also shows how the directive can accommodate sorting and filtering, which can come in handy at times. If you like what you see, check out the rest of the demos or the tutorials.

March 29, 2010

Objective-c Inheritance & Message Passing

Came across an interesting result while overriding a base class last week. Assume we have a class with two methods, one overloading the other as follows.









Assume both methods are defined within the interface (intentionally public). Now when we inherit from this class and override the first method (create:id), where does the "create:int" message in the second method get passed too? It is calling "self" from the context of the parent, but we just overrode the method in the child.





Given the above, where does the message go? Will it call create:id on the child or the parent?

Turns out, it is all in what you declare within your interface for the child. Define




in the child interface and it will pass the message to the child (using your override). Don't and the message will instead go to the parent. Thought it was very curious behavior as a C# guy.

March 6, 2010

Objective-C Libraries and Tools

There are quite a few open source cocoa touch libraries and frameworks.

OCMock, the winner by default when it comes to mocking in objective-c. It is actually a really decent mocking framework with all the elements you would come to expect (mocks, stubs and partial mocks). Setting it up can be a bit of a pain, fortunately Colin Barret has figured that out for us already.

Google Toolbox, augments the SenTestingKit (OCUnit) providing more assertions, log tracking, binding testing and more. A very visual tutorial on setting up Google Toolbox.

GHUnit, I am still spending time with this one. Seems promising so far. Key features are running individual tests, running tests from the command line (easier) and testing macros.

UISpec is a test automation tool. It’s key feature is that it can run automation tests within the simulator (OCUnit must deploy to the iPhone). Documentation is pretty sparse.

ASIHTTPRequest is a library that wraps the CFNetwork API, handling quite a bit of the grunt work for you. Great for working with RESTful services.

json-framework, another key element of working with RESTful services. JSON is lighter weight and uses key-value pairs to represent data. This plays very nicely with the KVC techniques you should be using in Cocoa.

SpeedLimit, this is a great utility for simulating the network speeds you are likely to have on the iPhone.

March 2, 2010

IPhone Development Guide

Just a collection of information and useful advice that I have collected. Hope this helps you get started.

Start where I started doing something simple hello world type examples. All of the icodeblog tutorials are worth doing if you are starting out (though watch out for the SQLite ones as Core Data replaces that now). Try this one to get a feel for interface builder and this one next for tying the code into IB. It can take a little while to learn the name of the different controls you will be using. This tutorial is on one of the navigation controls, the UITabBarController, which visually rests on the bottom of the window and will be one of your staples.

Cocoa has a learning curve of its own, get up to speed on Key-Value Coding (further reading), the framework makes use of many dictionaries. There is also a good post (with even more links) on the MVC Model used on the iPhone. It differs slightly from other representations of the Model View Controller pattern.

Model-View-Controller design patternsource

The primary difference is in the behavior between the different flows back to the view. On the iPhone, only your controller should be interacting with the UIView where as traditionally it is acceptable for the Model to have some interactions (Notifications or checking state).

Matt Gallagher’s blog is probably something that you want to subscribe to. A few of my favorites:

February 23, 2010

30 Days of iPhone Development

Having programmed professionally in C# for the last four years, something new was certainly welcome. I decided to give objective-c a month before really expressing my opinions of the language, so it doesn’t come off as, “I hate it, it isn’t what I am familiar with”. Since I have done objective-c almost exclusively for the last month, so give me some credit.

The IDE

Xcode described in one word would be, sufficient. It gets the job done and if you are running Snow Leapord version 3.2 is a bit better than 3.1.2 (Leapord) that I am running. The differences are minimal though. My major gripes are that xcode uses something called “groups” which look like folders, but are not. You can “group” your code into actual files and they will look the same, but you have to do that on the command line (or Finder), which is a bit unexpected. So assuming you didn’t know that and had been working on a project for a while it could look something like this.

Picture 1 Picture 2

Bit disappointing to see that mess when you assumed you had created some sort of order in all the chaos. Also, files are not listed alphabetically. You can have .m files listed before the .h or after. Whatever strikes your fancy.

The Debugger

I don’t really mind the debugger and it can be really helpful for… well… debugging. It’s good, honest. However, Xcode loves putting everything into its own window, so the debugger is not on the same page as your coding window (akin to eclipse). This is done so things like console output, stack trace and variables in scope can be displayed, but it still feels vastly inferior to the Visual Studio debugging experience where that kind of information is pulled in during debugging, but context remains the same.

Also, whoever decided the break points needed more than one state needs to be shot. Seriously, why would I want a breakpoint that the debugger won’t enter? There is undoubtedly some way to change this, as the forcing save alert before running and undo alerts can be done away with, but I have not found it yet. In the meantime, it means I need to add breakpoints and re-click them if I start coding and need to debug the same piece of code again. You know, try something, debug, it fails, try something else, debug the new solution.

Note: Undo trick is in user defaults.

defaults write com.apple.Xcode XCShowUndoPastSaveWarning NO

Header Files

Having little real experience with C/C++, header files are not something I have ever really had to worry about. All I can say is they are huge waste of time. People complain about unit testing, but these are worse and with none of the benefits. I understand why they have to be written in C/C++, but the thing is you don’t even need them in objective-c. They are there to prevent warnings and give guidance on how to use your code. Essentially nothing is private, so you have to be careful what you show (hence header files). Below is an example of a “public” method called logMySimpleString.

#import <UIKit/UIKit.h>

@interface MyClass : NSObject {
	NSString *aSimpleString;
}

- (void) logMySimpleString;

@property(nonatomic, retain) NSString *aSimpleString;

@end

@implementation MyClass
@synthensize aSimpleString

- (void) logMySimpleString {
	NSLog(@"%@", aSimpleString);
}

@end

Objective-c 2.0 includes support for auto properties, you can see one declared above. Aside from how obviously useless the header file is, look at the three places I have to reference aSimpleString to have an autoproperty. While nicer than writing the getters and setters by hand, it still introduces a lot of repeat code that offers very little value.

Templates and Customization

Finally, more of the positive! Templates for files and projects in xcode are pretty easy to accomplish. This post covers it pretty well, but if you are familiar with ReSharper templates, they are almost as easy and certainly the same fashion. You have to put them into an Xcode/user directory which is unique for iPhone SDK elements (see below).

/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/File Templates

To its credit, most of Xcode is pretty customizable with really good short-cuts. You can define your own in preferences.

Picture 3

Objective-c!

Objective-c is a superset of the C language, so you can both include and use C/C++ code along with your objc code. Yea… that wouldn’t sell me on it either… Sometimes this means you can include useful libraries, but mostly it just means some of your code will go off into some foreign and scary land.

Fortunately, this new language comes with a completely different framework. Coming from ASP.NET/WinForms background, I am very pleased to be working in an MVC pattern which is really well implemented for the iPhone. I also love the observer pattern via NSNotifications. I’ll probably do a post on that next as they are pretty slick.

There is a good document on the apple site on other patterns common to cocoa. There is also a good one on implementing a singleton, which you’ll need if you don’t want to create Big Ball of Mud in your AppDelegate.

I’ll probably continue this later with an observer example using NSNotifications and talk more about how some of the Small Talk elements work within Objective-c.

January 21, 2010

StackOverflow - Garbage In, Garbage Out


I have been using stackoverflow for over a year now. It surprises me how great the answers you can find there are and in some cases, the pure quality and effort some individuals will put into them. Take this iPhone question for example.

A stackoverflow user is asking a question about the best way to pass data to ViewControllers in the iPhone (Which uses MVC for its UI). The top answer there is both informative and useful in that it provides a concise answer, as well as, example code to get the user started. Obviously this question took time out of someone else's day to think about and reply, then edit and update. Truly a wonderful example of the simple yet highly valuable resource stackoverflow can be.

Then you get questions like this one. I've seen that question both asked and answered over and over for years now. I've even asked it myself at one point and let me just say that providing an explicit answer to that question never did me any favors. The question is born out of looking for the wrong solution. The stackoverflow user, in this case, is looking for the wrong solution and getting it handed to him on a silver platter.

This is just like using a calculator, they always give you an answer, they don't always give you the right one. Stackoverflow is full of people eager to give you an answer to your question, but no one will spend the time questioning the origins of it.

December 10, 2009

sp_help

I am ashamed to admit I never knew about the sp_help and sp_helptext commands in sql server until today. Why has no one ever shown me this earlier?

sp_help will find a stored proc by just providing its name. It will then show all the matches, where they are located and what parameters they take.

sp_helptext will something similar, expect it will display the actual stored procedure. Much easier than hunting through a list.

 
Copyright © CodeCuriosity | Theme by BloggerThemes & frostpress | Sponsored by BB Blogging