Tuesday, July 31, 2007

Flex Image Repository (Application wide image cache)

written by Marcel Panse

Flex has some options for image caching on its own, but it leaves the image caching for the browser to handle. This creates differences between browsers (i have written applications that caches really well in IE but not so well in FF). This browser cache isn't very reliable, plus it takes a really small amount of time to retrieve (because it is http based and it needs a http call to retrieve) what causes the image to flicker. What i really want is some sort of application wide caching mechanism for images.

Another thing is that it works (offcourse) also for AIR applications, so it should work both with online and offline files. The thing that makes these files unique is the location of the file, what could be either 'http://...' or 'file://...'

The solution is really simple. Create a class that can store images in a map (like a java hash-map). This class should be a singleton and have a couple of methods like:
- lookup(location:String)
- cacheImage(location:String, image:Bitmap)

And everywhere in your application when you use an Image object just set the source to the bitmap from the repository (instead of a url).
How to load the bitmap from an online or offline file is a whole different story (and much more complicated). I will discuss that in my next blog entry.

Sunday, July 08, 2007

Refactoring your Templates

StringTemplate is a template engine written by Terence Parr, the author of the popular ANTLR parser generator. It is based upon the idea of Enforcing a strict Model-View separation in Template Engines. Its features allows you to restructure you templates to be more maintenance friendly: so therefore I chose the title "Refactoring your Templates".

What is a template?

Templates are textual files with "holes" in it that that can be filled with data. Besides these holes templates also need facilities for: looping through items, conditional formatting, template fragments and string formatting.

How does JSP handle this?

JSP uses scriptlets inside the template: small fragments of code. These code fragments give full access to the Java language. The danger of using java code for control flow is that templates are not fully separated from underlying data computations. For instance: programmers may choose to quickly embed a JDBC query inside a template. They also lack facilities for reuse: object-oriented features like inheritance and components are not available.

How does StringTemplate do better?

  • Templates contain no code fragments.
  • Templates can be named and may accept attributes.
  • Templates can be grouped in a single file.
  • Template groups can use inheritance to reduce template duplication.

Templates do not embed code fragments, that allows you to use the same template on different platforms. Naming templates allows you to call templates inside other templates and those calls can receive arguments. Grouping templates into a single file is convenient when you break up templates into smaller parts. Inheritance of templates allows you to override named templates in a group. This feature is nice if you need similar but slightly different results. For example when your program generates SQL and you want to support different SQL database dialects.

How do I use StringTemplate?

This article is a quick introduction to StringTemplate, for more information please see the documentation. The StringTemplate essentials in six bullets:

  • Holes inside the template are marked using dollars, for instance: $username$.
  • Every substitution argument must be calculated beforehand and assigned, using the setAttribute("username", "Foo Bar").
  • Properties of attributes syntax: $person.email$.
  • Conditional substitution syntax is: $if(title)$<h1>$title$</h1>$endif$.
  • Results of template substitution is available using the toString() method.

Requiring arguments to be assigned beforehand makes sure that your code has no order-of-computation dependencies, that make your code difficult to change.

Example template "page.st"

 <html>
<head>
<title>$title$</title>
<meta name="keywords" content="$keyword; separator=","$"/>
</head>
<body>

<h1>Hello $username$!</h1>

<ul>$person:{
<li><a href="mailto:$attr.email$">$attr.name$</a></li>}$
</ul>

</body>
</html>

Example Java code

 import org.antlr.stringtemplate.*;

class Person {
       public String name;
       public String email;

       Person(String name, String email) {
             this.name = name;
             this.email = email;
       }
}

public class Main {

       /**
        * Simple StringTemplate example.
        * @param args
        * @throws IOException
        */

       public static void main(String[] args) throws IOException {
             StringTemplateGroup group = new StringTemplateGroup("website", ".");
             StringTemplate page = group.getInstanceOf("page1");
             page.setAttribute("title", "StringTemplate Rocks!");
             page.setAttribute("username", "Foo Bar");
             page.setAttribute("keyword", "foo");
             page.setAttribute("keyword", "bar");
             page.setAttribute("person",
                    new Person("Webmaster", "webmaster@domain.com"));
             page.setAttribute("person",
                    new Person("Manager", "manager@domain.com"));
             page.setAttribute("item", "bar");
             System.out.println(page.toString());
       }
}

Example result

 <html>
<head>
<title>StringTemplate Rocks!</title>
<meta name="keywords" content="foo,bar"/>
</head>
<body>

<h1>Hello Foo Bar!</h1>

<ul>
<li><a href="mailto:webmaster@domain.com">Webmaster</a></li>
<li><a href="mailto:manager@domain.com">Manager</a></li>
</ul>

</body>
</html>

Templates can be applied to attributes

The example code assigns more items to the person attribute, that are formatted into a list of links. The syntax used is:

 $person:{<ul><a href="mailto:$attr.email$">$attr.name$</a></ul>}$ 

The text between the curly brackets is a template to format a person. There is no need for special looping syntax, because the template is applied to each person.

Extract templates into separate files and call them by name

The person template can be extracted into a separate file and called by its name.

Example template "email_link.st"

 <li><a href="mailto:$attr.email$">$attr.name$</a></li> 

Change inside template "page.st"

 [...]
<ul>
$person:email_link()$
</ul>
[...]

Templates with named arguments

The default argument name is "attr", however it is also possible to use named arguments:

Example template "label_input.st"

 <p>
  <label for="$id$">$label$</label><br/>
  <input name="$id$" id="$id$" type="text" value="$value$"/>
</p>

Example call

 <form>
$label_input(id="test",label="Message",value="Hello World")$
</form>

Example results

 <form>
<p>
  <label for="test">Message</label><br/>
  <input name="test" id="test" type="text" value="Hello World"/>
</p>
</form>

Advanced features

Examples and documentation are in the excellent StringTemplate documentation. More  advanced features of StringTemplate are:

  • Template group files
  • Template inheritance

Group files use the *.stg extension and embed a number of named templates. When you have lots of small templates, this might be more convenient.

Templates are ordered in named groups. It is possible to use an existing template group as a basis and override/extend some templates.

Conclusion

StringTempate helps ANTLR to add a new language backend without adjusting a single line of code. This is a showcase of the power of StringTemplate and how it helps to define complex templates in a clean way.

StringTemplate available for different platforms: Java, C# and Python. It is an interesting project if you need clean templates, certainly worth a look!

Links:

Friday, July 06, 2007

Code Complexity

written by Daniel Rijkhof

About

This blog entry is quick read summary about code complexity. It gives a definition of code complexity and several signs how to notice code complexity. It also provides a brief description how to measure code complexity and suggests a way to keep it low.
Most of the concepts are taken from Structure 101 help section.

This blog entry is based upon my code complexity presentation for www.greetz.com.

Definition of Code Complexity

Reg. Charney defines Code Complexity as:
the amount of effort needed to understand and modify the code correctly.
see http://www.linuxjournal.com/article/8035.

Excessive complexity: When is a code-base too complex?

Signs of Logical complexity:
  • part of the design is no longer fit for its purpose
  • unclear purpose
  • adding new features becomes harder than it should be
Signs of Structural complexity:
  • the code is hard to understand
  • changes have unexpected side effects


The need to know about code complexity

Keeping track of code complexity helps to:
  • Predict (future) feature implementation times
  • prioritize areas of the code for structural refactoring
What happens if you don't manage complexity?
It will cost!

Manage complexity like debt
Howard Cunningham 'Mr. Wiki' compared complexity with debt:
"Manage complexity like debt"
skipping designs = borrowing money
maintenance headaches = interest payments
refactoring = repaying debt
cannot refactor = cash-flow insolvency
creating engineering policies = devising financial policies


Andy Hunt extends the analogy concisely:
"Just like real debt, it doesn't take much to get to the point where you can never pay it back, where you have so many problems you can never go back and address them."


What can we do? Measure Complexity!

Although we cannot specify the amount of effort needed. We can calculate a complexity index.

This index enables us to:
  • Compare projects
  • Monitor trends (getting more or less complex)
  • Discover which items at what level are causing the complexity.


Measuring Code Complexity

Measure the complexity at every level of design breakout, method, class, package and
high-level package (High level packages contain only other high-level packages or leaf packages).

Measuring occurs by counting items and dependencies it immediately contains.

Method complexity is usually calculated by cyclomatic complexity.

About Cyclomatic complexity

What is Cyclomatic complexity?
A measurement for the complexity of a peace of source code.
What does it measure?
The number of linearly independent paths through a peace source code.

Cyclomatic Complexity @ wikipedia

Calculating Cyclomatic Complexity

To calculate cyclomatic complexity build a graph that describes the control flow of the program. The nodes of the graph correspond to the commands of a program. A directed edge connects two nodes if the second command might be executed immediately after the first command.






The number of linearly independent paths through the first method is 3, and the second is 2.

In Structure 101, class, package and high-level package complexity is calculated by counting items and dependencies they immediately contain (screenshot from Structure 101 help):



Design Tangles
Design tangles are cyclic, package-level dependencies. Design Tangle Metric quantifies the amount of cyclic dependencies.



Refactoring
Defenition of Refactoring:
improving the design of existing code.

Always Refactor when adding new features to you code.

Quote Chris Chedgey:
"You use personality, charisma, leadership and/or donuts to convince your team that henceforth, they will not add any more complexity debt to the code base. Now watch what happens..."

I suggest reading Chris blog item: http://chris.headwaysoftware.com/2006/10/reducing_comple.html.

The need to Rebuild
In some cases redesign and rebuild is faster then refactoring. The complexity index of the tipping point cannot be determined.

Future Vision
Chris Chedgey says: "keep a lid on it"
I agree!

  • Monitor complexity (Structure 101)
  • Keep complexity low (stay away from the need to rebuild)



Resources

Structure 101 Help see http://www.structure101.com
Cyclomatic Complexity @ wikipedia

Chris Chedgey blog entries:
http://chris.headwaysoftware.com/2006/09/complexity_over.html
http://chris.headwaysoftware.com/2006/10/reducing_comple.html


http://www.linuxjournal.com/article/8035

Wednesday, July 04, 2007

Flex and AIR application with one codebase

written by Marcel Panse

I'm creating my first AIR application, or better i'm porting my existing webapplication to an AIR project. The application is all about online imaging and the one thing it is missing is local file access; a perfect setup for an AIR application.

First i wanted to just make my Flex project AIR compatible.. but weird enough that is not possible. I added a Apollo buildcommand and apollo nature to my project file, but flexbuilder can't handle both a flex nature and a apollo nature, so he just picks one and youre project isn't flex compatible anymore (you get an error when lauching through the Run... buttons).

So i went for the next approuch, too seperate projects with the same codebase. There are several options to achieve this.
1. Create libraries and modules for common code
2. Create a symlink to the source dir

The first one looks the best option but needs a lot of refactoring at the moment in the project, thats what we are going to do when there is more time (this is a proof of concept).
The latter is the easyest solution. I Created an AIR project and created a symlink by clicking:
New -> Folder -> Advanced -> 'Link folder to the file system'
and linked it to the source dir.

Now i still continue to work on my Flex Project and once in a while i can create an AIR Installer file by simply clicking the button in the other project.

Next i created a 'Seamless Installer'. This piece of code simply checks wether the user has the AIR runtime and let the user install your application including the runtime or just the application.

You create this 'badge' by copying the badge.swf from
'sdks/moxie/samples/badge/badge.swf'
and create a html file like:
<html>
<head>
<title>title</title>
</head>
<body>
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="217" height="180" id="badge" align="middle">
<param name="allowScriptAccess" value="all" />
<param name="movie" value="badge.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#FFFFFF" />
<param name="FlashVars" value="appname=ApplicationTitle&appurl=http://localhost/application.air&airversion=1.0.M2&buttoncolor=008811&messagecolor=000000" />
<embed src="badge.swf" quality="high" bgcolor="#FFFFFF" width="217" height="180" name="badge" align="middle" allowScriptAccess="all" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" FlashVars="appname=ApplicationTitle&appurl=http://localhost/application.air&airversion=1.0.M4&buttoncolor=008811&messagecolor=000000"/>
</object>
</body>
</html>

Simply use the flashVars to config the badge.
BTW. If you want to adjust the badge, the .fla is also in the samples dir..