Archive for the 'Programming' Category

Google+ API Available

Google has just announced that the Google+ API is now available to the public:

http://googleplusplatform.blogspot.com/2011/09/getting-started-on-google-api.html

This is the first release of the API, and it only allows you to get read-only access to “public” information. I’m still a little unclear on what “public information” means (I mean, you DID type it into a social network…), but it looks like this API enables you to get the typical profile information as well as a list of that person’s “activities,” which are posts, check-ins, and shares. This release does NOT enable viral channels like requests, which are crucial to application/game discovery.

Here is the technical reference for the real meat of the story:

http://developers.google.com/+/api/

Code Smells

One of the hardest parts of building large applications when there’s more than a single developer involved is talking about the code that the team already has and is in the process of producing. Code is inherently abstract and difficult to describe, which makes the quality of the code even more abstract. Code quality is often times subjective as well, as people can have different points of view on the trade-offs that are made in a particular solution to a problem. Code quality can even be a very sensitive and personal issue to the people involved in writing the code as everyone sees it as a direct evaluation of their performance and skill.

It’s important when you’re having these types of conversations that you avoid miscommunication and understand each other clearly. Code “smells” help establish a vocabulary that can turn the abstract concepts expressed in code into something more concrete that is easier to point out, talk about, and generate alternatives to.

The Wikipedia article on Code Smells is as good a resource as I’ve ever found on them, and if you love reading about programming as much as I do, it’s incredibly interesting stuff.

The referenced pages are also great, particularly the one on Anti-Patterns, which describes practices and characteristics to avoid at all levels of an organization, all the way down to the code. If you can relate to too many of these anti-patterns, you may need to start thinking about why and how you can fix them!

Adobe Previews “EDGE” HTML5 Authoring Tool

We all knew Adobe had to respond to the recent HTML5 swell, so I think that the arrival of an HTML5 authoring tool, named “Edge,” is a pretty predictable response from Adobe.
Adobe Edge
In this video, Mark Anders demos a very early prototype of Edge which has a very familiar, Flash IDE-ish interface.
The famous Flash timeline is back, as well as the concept of “symbols” applied to the HTML context.  Most interesting to me is that Webkit is at the heart of the tool, rendering engine driving the live preview of the content.
In the video you also catch a couple glimpses of the source code that’s being generated, which at this point actually looks relatively maintainable and logical to the human programmer.  Granted, this is a pretty constrained scenario for the tool.  I predict that Edge will fill a role similar to Dreamweaver where it’s useful for less technically able people to build prototypes and relatively simple applications, and medium to large applications will still be created the old fashioned way, one line at a time by hand.

Introduction to MXML

If you’re here because you’ve just heard about MXML for the first time and have NO clue what it is, you should start by reading Wikipedia’s MXML article.

Some Background
MXML is an XML-based language that is functionally equivalent to ActionScript. When MXMLC compiles MXML, first it translates it to ActionScript, then compiles that ActionScript into bytecode. In fact, if you pass the -compiler.keep-generated-actionscript argument to MXMLC, you can actually see the ActionScript that is generated from your MXML class. There’s a common misconception that using MXML requires using the Flex Framework, or that Flex is MXML and vice versa. Those are not true. MXML is a declarative language, like HTML. Flex is Adobe’s UI component framework. The two are not dependent on each other, which the South Park project demonstrates.
MXML in a Nutshell

Here’s an example of a default MXML file, which we’ll examine below:

<?xml version=”1.0″ encoding=”utf-8″?>

<s:Application

xmlns:fx=”http://ns.adobe.com/mxml/2009 xmlns:s=”library://ns.adobe.com/flex/spark

xmlns:mx=”library://ns.adobe.com/flex/mx

minWidth=”955” minHeight=”600>

<fx:Declarations>

<!– Place non-visual elements (e.g., services, value objects) here –>

</fx:Declarations>

</s:Application>

Doctype Declaration

<?xml version=”1.0″ encoding=”utf-8″?>

The first line is required for all XML documents. It’s not unique to MXML and is essentially telling any parsers that read this file what to expect. You can basically take it for granted and not have to worry about it as long as you’re creating and working with MXML files within Flash Builder. If you’re using another editor, just make sure that you’re saving your files using utf-8 or you’ll run into nasty compilation problems.

Root Node

<s:Application minWidth="955" minHeight="600">

...

</s:Application>

There can only be 1 root node of any MXML document, and all other nodes must be contained by the root node. You can’t have 2 top level nodes in an MXML file, just like you can’t have 2 public classes in a single ActionScript class file. Also, the root node is normally a DisplayObjectContainer so you can place DisplayObjects within it. You could potentially create non-visual classes/components in MXML, but MXML’s strengths are laying out UI elements and rigging up event handling, so you would probably be better off using ActionScript in that case.

Namespace Declarations

xmlns:fx="http://ns.adobe.com/mxml/2009"

xmlns:bd="com.bdement.*"

Namespace declarations are equivalent to import statements in ActionScript, but they are a special attribute that must be present in the root node. The default namespace is http://ns.adobe.com/mxml/2009, which is required to make MXML “work,” regardless of whether you’re using the Flex Framework or not. xmlns:fx means “use a namespace called ‘fx,’” which lets you write tags that begin with <fx: and gives you access to all of the classes within that namespace. You can also import any package as a namespace by specifying it like the 2nd example.

The actual namespace (fx or mtvn, in the above lines) is arbitrary. For example, in the 2nd line I used “bd” as my namespace, but I could name it anything. Namespaces aren’t globally defined, so you can change them from class to class, although as a best practice you should name them consistently throughout your project.

Nodes

Every element within an (M)XML document is known as a node. Nodes are equivalent to declarations in ActionScript. Every time you specify a node like <ns:Object />, the resulting ActionScript will look like “new Object().”
Attributes

MXML gives you access to all of the public attributes exposed by a class. They’re set by declaring a value for them in MXML, like this:

<s:Application width="955" height="600">


This is the functional equivalent to the following ActionScript:
var myApp:Application = new Application();
myApp.width = 955;
myApp.height = 600;

Even in this simple example you can already see how MXML’s declarative structure is well-suited for “declaring” UI layouts.

Dynamic Attributes

Often you’ll want a particular value to change at runtime, and for that change to have some kind of effect on your UI. For example, a label that changes text when you click something.
To specify a dynamic attribute, wrap a reference to it in curly braces, as shown here:
<fx:Declarations> <fx:String id=”labelText>My Label</fx:String>

</fx:Declarations>

<s:Label text=”{labelText}/>

In this example we declared a String called “labelText,” and a Label that uses labelText’s value. The String is wrapped in a “Declarations” tag because it’s a non-visual element. All properties declared like this are given a public scope and are “bindable.” We’ll discuss more about data binding below.
As an alternative, you could also specify properties in script:

<fx:Script>

<![CDATA[

[Bindable(event="labelChanged")]

private var labelText:String = "My Label";

]]>

</fx:Script>

<s:Label text="{labelText}"/>

Here you’ll notice that instead of a Declarations tag, we used a Script tag, which contains a CDATA enclosure. The CDATA enclosure tells the MXML parser that content within the enclosure is “character data,” and will not follow (M)XML syntax.
The [Bindable] metadata tag means that the next property is available for data binding. Data binding is a handy, but often misused feature in MXML. For complete information on data binding, read Adobe’s Bindable Metatag Documentation.
Key Point: The key thing to know about data binding is that when you write a [Bindable] tag, always, 100% of the time, include a unique event name. If you don’t, your performance when using data binding will get really bad, really fast.
The reason is that if you don’t supply an event name, it defaults to “propertyChanged.” Then every time a property changes, Flash has to figure out which property changed, which becomes more expensive as you have more properties that are all dispatching that event. Also, if you view the ActionScript files generated from your MXML classes you can actually see how vastly different the generated code is when you do and don’t supply a property name.

Event Handlers

Event Handlers are specified in MXML very similarly to how attributes are specified, except they refer to a function rather than a property. For example:

<fx:Script>

<![CDATA[

protected function button1_clickHandler(event:MouseEvent):void

{

trace("Clicked!");

}

]]>

</fx:Script>

<s:Button id="button1" click="button1_clickHandler(event)"/>

You can probably see the connection pretty easily here, but notice that there are no curly braces in this case. Also notice that the magic variable “event” is being passed to the handler. “Event” is the naming convention used in MXML for the event that will be passed to your event handling function. You could also write event handlers like this, although I do not advocate it in all but the most trivial programs, I’m only showing this as a reference to show how the magic “event” comes out of nowhere:
<s:Button click="trace(event.type)"/>

FlexPMD

You probably haven’t heard about FlexPMD.  It’s an open source plugin from Adobe for Flex or Flash Builder.  You run it against your source code and it alerts you to “bad smells,” or potential bad practices, in your code.  These types of tools, from FlexPMD’s older brother, PMD from the Java world, and “Lint” from the C world have been around for a long time, checking over the shoulders of developers, and frustrating computer science students who are required to compile with no lint warnings.  (All my programming homework in college had this requirement, ugh!)

I ran FlexPMD against the source code for brandondement.com and was really impressed with the results.  Some of the results were of the “I don’t care about that” variety, but Flex PMD can be configured to ignore those, and many more were in the “Oh really?  You’re right!” category.  I’ve only just begun to use it, but even then I would highly recommend it for anyone who’s committed to becoming a better programmer.  More information about installation and use can be found at:

http://opensource.adobe.com/wiki/display/flexpmd/FlexPMD+Eclipse+plugin

Love Thy Flex Builder Keyboard Shortcuts

It never ceases to amaze me how after all the time I spend using Adobe’s tools, they always have a few more features that I’m not using but should be. So every now and then I go brush up on the keyboard shortcuts in Flex Builder, so here are a few highlights (Command = CTRL if you’re on Windows):

  • CTRL + 0 (even on Mac) – Quick Outline.  Hit this, then start typing to jump right to any variable or method definition in the class
  • Shift + Command + R – Open Resource.  Hit this, then start typing any file name to open it.  Works on all file types in your project
  • Command + L – Go To Line.  Opens a dialog where you type in a line number
  • Shift + Command + C – Puts a block comment around the selected text

Strangely there doesn’t seem to be a definitive guide to shortcuts in FB, even the LiveDocs look rather incomplete:

http://livedocs.adobe.com/flex/3/html/help.html?content=code_editor_9.html

But a search for “flex builder keyboard shortcuts” returns results from tons of blogs.  Here are a few more gems that weren’t in the LiveDocs:

  • Command + D – Deletes a line
  • Command + / – Comment/Uncomment a line
  • Shift + Command + D – Inserts an ASDoc-style comment, including parameter and return declarations!
  • Shift + Command + L – Opens an outline of all the keyboard shortcuts available

Also, if any of these don’t suit you, you can always go change them!  In the main menu, click Flex Builder -> Preferences -> General -> Keys (or just type “Keys” in the filter).  Coincidentally, this is the most definitive list I could find.

What keyboard shortcuts do you use that you can’t live without?

The Developer’s Cycle: Code, Test, Refactor

Most developers code, test until the code works, and then continue coding, happy that they’re so good and successful at their job.  When working this way, the split between coding and testing is roughly 50/50 for more junior developers, and trending towards 75/25 for more seasoned pros.  But when working this way, you lose the most valuable opportunity you have to better yourself and your work. Would you turn in a paper without proof reading it first?  Of course not!  When I work, I try to allocate 20% of the time I’m given for an assignment to planning and architecture, 60% for actually writing and testing code, and the final 20% to cleaning up the huge mess I made along the way, aka refactoring.  That’s it kids, the word of the day is “re-fac-tor-ing.”

Refactoring means taking a chunk of already working code, and making it “better.” It’s vitally important that the code already works, otherwise you’re still developing.  “Better” can mean lots of things, from more efficient to more readable, but when talking about refactoring, we’re mostly talking about more readable, which has trickle down effects making it more efficient.  The important thing is that you take the time to read what you just wrote. Like taking notes in class, if you can’t even read what you wrote the day before, how is anyone else supposed to?  Most of the time developers can read what they wrote, but not what anyone else wrote, which is the biggest problem that refactoring attempts to solve.

When refactoring, you should look for ways to simplify your code, making it more readable and maintainable.  Here are a few questions to ask yourself:

Is this code still used?

If it’s not, don’t comment it out, delete it! Version control can always resurrect it if needed, and you’ll be removing one potential point of confusion for someone maintaining your code down the line.

Is my code documented?

At a minimum you should have inline comments that provide a narrative of what the code block below is doing.  That’s usually enough for leaf classes that aren’t meant to be subclassed and are used sparingly.  As code becomes more reused, eventually becoming a library, it should have more complete documentation, like ASDocs.

Do my package, class, function, constant, and variable names still make sense?

This is huge. Names should have an instantly understandable and useful meaning to the human who’s reading your code.  Don’t be afraid to have names that are long, but look for ways to shorten the really, really long ones too.  Use that vocabulary, smart guy!  Flex Builder has a very nice feature called “Rename” that’s in the “Refactor” menu when you right click a name that is effective at making renaming a trivial task.

Is my code well formatted?

Telling developers where to put whitespace and line breaks is probably the most surefire way to make them secretly hate you.  But you, as a developer, should take pride in your craft and make an effort in making your code at least consistent.  If you write a function with 30 unbroken lines of code, it makes it difficult for someone else to scan what’s going on.  Sprinkle some line breaks and inline comments in there to logically chunk it up, and you’ve instantly saved your company time and money in the future.  By the way, Adobe publishes coding standards that their developers are supposed to follow when writing code for the Flex SDKs.  Does every line of the latest SDK conform to those standards?  No way!  But you can see that the developers make an attempt to make their code readable.

And finally…

Is there a simpler way to do this?  Is there a better algorithm?  Is there a function or library for this already?  Are my objects properly encapsulated and loosely coupled?  The answers to these questions will get easier for you to answer in time, but the fact that you’re asking them of yourself has already put you on the right path.