Sunday, February 24, 2008

Ext In-Depth (Part 2)

Since my last post on Ext was cut-off in the middle, I plan to finish up on what I understand of Ext's meta-programming and cover a little bit of Ext's Bridge pattern.


Dynamic Sub-classing a parent class.


I'm going to spend my time talking about two functions: extend and override. This first, extend, is used to subclass at runtime. I find this behavior pretty impressive, but of course, so is the JavaScript language.

        extend : function(){
// inline overrides
var io = function(o){
for(var m in o){
this[m] = o[m];
}
};
return function(sb, sp, overrides){
if(typeof sp == 'object'){
overrides = sp;
sp = sb;
sb = function(){sp.apply(this, arguments);};
}
var F = function(){}, sbp, spp = sp.prototype;
F.prototype = spp;
sbp = sb.prototype = new F();
sbp.constructor=sb;
sb.superclass=spp;
if(spp.constructor == Object.prototype.constructor){
spp.constructor=sp;
}
sb.override = function(o){
Ext.override(sb, o);
};
sbp.override = io;
Ext.override(sb, overrides);
return sb;
};
}()


This function is documented as taking a "class inheriting behavior", a "class being extended" and an optional "literal with override members". I'll be a bit ADD here with my description. I may come back and clean it up, but here we go.

First of, let's talk about the io function. This is an inline version of Ext's override function. This function is responsible for replacing one object's methods with another's. This is done through method name.

Example ext usage:

var MyGridClass = Ext.extend(Ext.GridPanel, {
constructor: functon(){...},
myFunc: function(){ alert('Hai Wurld!'); }
});

var myGridInstance = new MyGridClass({ ...config...});


Now to the meat of the function:

The first thing the function does is test to see if it's a two argument or three arugment function. If it's only two arugment, then a "subclass" parameter has not been defined, so variables are maniuplated for this.

Next it creates a few local variables: F -> "null" function, sbp -> sub-class prototype (undefined), and spp -> super-class prototype (sp.prototype).

The next thing that happens is assigning F's prototype to be spp. This effectively makes F be a sub-class of the super class (i.e. var o = new F(); o.prototype.prototype == spp).

The next thing is a little assignment magic. The local variable sbp is assigned to the *old* subclass prototype, while the new sub-class prototype is assigned to "new F()". The sub-class now has F as a super-class. After that, we re-wire the sub-classes constructor and superclass. There's a little magic here to handle constructors. This is sort of Ext-specific as I understand it. (Meaning your constructor won't be called unless you're extending an Ext Component). Ext then ensures that each subclass contains an "override" method on it by placing a localized implementation of the override function on the subclass. The last thing the function does is apply the optional overrides object to the new subclass.

So, the description might be a little hazy, and that's due to my hazy understanding of some of the steps. I'll try to fill in a better description the more I grasp it. The point I wanted to get across was the F variable becoming a new Parent in the sub-class's hierarchy. Ridiculously cool behavior, and thank you Ext for giving me an implemnetation so I don't need to fry my brain thinking of how to do it myself!


Ext-Bridge: Choose your Ajax



Ext allows you to choose an underlying library. Ext 2.0.1 provides adapters for the following libraries: Yahoo! UI, Prototype/Scriptaculous and JQuery. Ext also has a home-grown solution for AJAX calls (that works great).

What is the bridge actually for? Well, I started perusing some of the adapter code to figure out what the adapter actually does and why I would want to use it. From what I can make out, Ext delegates certain functionality to an underlying library. If the library can't perform said functionality, then it provides its own implementation. Classic Bridge pattern.

So what does Ext pass through the bridge? I tried to compile a list.

  • Ajax requests (form-based and non-form-based)
  • Event Handling (Registering, propagation, scope and translations)
  • Animations
  • 2D Geometrical Mathematics (For UI rendering)
  • Dom Queries
  • Element Locations



The good news is this. If I really like the Jquery interface (which I do. It's one of the coolest feeling APIs I've seen), then I can make use of the API and still use Ext. Not only that, if I wanted to add a listener to ALL ajax requests, I can do so using the JQuery api, and I will get not only requests made with the JQuery API, but also those made with the Ext API. It really makes using two libraries easier.

Also, if I like the Scripaculous effect more than Ext effects, I can pull in the Ext-Prototype/Scripatculous bridge and make use of them. Then I don't have to give up my Prototype knowledge to start using Ext. I can use them together.

Saturday, February 23, 2008

30 Days of Purpose take 2

Not sure how many of you A) go to church and B) went through the 30 days of purpose book. I know through college graduation/moving etc. we ended up going through it 3 times (in 3 different churches). Anyway, on a similar vein, some church in Florida is taking on a 30 days of sex challenge. This is to help strengthen marriages in church members.

Sounds like a church I could really appreciate going to.


Find the link here.

Apache vs. Sun?

As a real quick post, I just wanted to show this: http://www.apache.org/jcp/sunopenletter.html.

Anyone have any thoughts here? I wonder what the current state of this issue is. Apache recently voted "no" to the J2EE 6 Spec because of concerns over treatment of this issue with the J2SE.

Knight Rider FTW

So tonight we watched the opener of Knight Rider for fun. OMG that was a fun show. Totally ridiculous and with a great 80s techno theme. I downloaded it so I can listen to it all the time now. If you're lucky I may even make my own rendition and post it online. Why not?

Just wanted to point out my favorite part in the first? episode: Pheonix. David Hasselhoff (Michael Knight) [or is that the other way around?] is in the Knight 2000(great year btw) and is trying to stop a plane from taking off. How does he do it? Of course, he plays chicken. At the last minute he jumps the car THROUGH THE WING of the airplane. Yeah, after a few "running the car through things" clips, it gets pretty commonplace. What's awesome is the PLANE EXPLODES! It was the best, and most unreasonable explosion I've seen in a long time. I love the 80s. I may go back and watch Die Hard again.

Friday, February 22, 2008

EJB 3.1 -> Becoming Usable?

Looks like I really need to take a closer look at EJB 3 (check this link for possible 3.1 features). I was required to learn EJB 2 for college, and GOOD LORD! Anyone else who had to use it (for simpler tasks) would probably agree with me.

Anyway, it looks like EJB 3 started over-coming problems by taking the Hibernate route. I'm a really big fan of the JPA. In fact, I think I like it slightly better than Grails ORM DSL. The only thing that's still killing me is the darn xml files. I DON'T NEED MORE XML! Yes it's a great configuration option. Many IDEs will even perform autocomplete given a .dtd or .xsd. The only thing that's annoying is I just annotated my class with a JPA annotation. Why can't my build discover that and great the persistence.xml file FOR me.

That's right... I don't want to make something that is completely redundant with what I just coded. Eclipse Dali (JPA plugin) is nice enough to offer me warnings if I haven't placed a "mapped" entity into persistence.xml. I can even right click persistence.xml and have it add the classes for me. Why, oh why has no build tool (i.e. Maven) offered me a way of auto-magik-ly creating this file? Especially when all the interesting configuration goes in other files ANYWAY. I'd like to see (and I tried to start) a build utility that will create a persistence.xml for my current maven build if I haven't already created one myself. Notice the convention over configuration here (Yes, grails community. pure groovy != convention). If I want to make this file and manage it, I still can. However my build is smart enough to handle it for me. YAY!

I made my first attempt at a Maven Mojo today that would accomplish this very feat. If I have any success (and I can push it through work's export control) you may be seeing it in the near future.

Anyway, EJB 3.1 is doing a lot of things right now a-days. Here's my opinion on the future of Server-Component-Frameworks

  1. Annotations-over-Interface
    Don't make me implement an interface if annotations provide the same behavior and MUCH greater flexibility
  2. Annotations-over-XML
    JPA was GREAT. I can keep all my mapping info in the object that is doing the mapping. Less brain-swap and mucking with multiple files to debug.
  3. DRY
    I should only have to do something ONCE for the system to find out about it.
  4. Selectable Infrastructure
    Let me choose what services of EJB I want. Sure the container is nice. I want some services and Entities in my J2SE app. Let me embedd the portions of the container that handle that into my Desktop app.
  5. Unit-testable
    EVERYTHING should be unit-testable.
  6. Integration-testable
    I should be able to run integration tests without much pain.
  7. Easier Web-Front-End
    Grails and Rails are kicking EJB applications in terms of speed of development mostly because it's so darn easy to control the flow of an app. This isn't quite an EJB concern, but having easier web-frameworks (like Stripes and Grails) emerge that can make use of EJB 3.1 will help it succed.
As an aside, I spent two days attempting to learn JSF and really got tired of all the duplicate info I'd be putting in XML files and code. I'm hoping JSF undergoes the same shift in thinking that EJB has, or I expect it to get blown away by faster methodologies (or kept due to a great marketing job).

Alright. So I need to finish my last post about EXT sometime. (I hardly got into the metaprogramming stuff). To all those of you who read this, I'll try to make my posts interesting and fun. I'll also try to not always rant about Programming. It IS what I do best though.

Wednesday, February 20, 2008

In Depth ExtJS (part one)

I've decided to cover Ext a little bit in my blog. At work, a co-worker and I are supposed to present what we've learned from using ext on our current project. I decided I'd try blogging a bit first. This is mostly because my blog tends to be written on-the-fly with no proof-reading, and is a great way to get my thoughts down. Lastly, all code in this blog entry (if not otherwise specified) is taken from the Ext source code. Ext is distributed under an LGPL license with an optional commericial license. It's all one of the out-of-the-box best looking UI libraries for Javascript I've seen yet.

In this blog I'm going to cover some of the basics of what Ext does for you. This is all taken from the ext-core.js source file (which on distribution is found in ext-all.js).

From what I can tell, ext-core.js is responsible for doing the following things:
  • Determining web-browser settings and set flags appropriately
  • Adding methods to core JavaScript objects to ensure consistency accross implementations
  • Defining helper functions to make programming & meta-programming easier.
The first item seems to be pretty standard and would happen in a LOT of Javascript libraries. The really interesting things happen in items 2 and 3.


Can has a method? I made u an indexOf, but IE eated it
One nice thing about EXT is that it will ensure that various methods are available on standard java types (you can see this in their docuemntation). I'm going to focus on the methods they add to Array, as they're simple, easy to understand and show the technique without mucking in details.


How does Ext add methods to every object? Prototypes! Because JavaScript is a Prototype-oo based system, all you need to do to add helper methods onto ANY array is add something to the array prototype (Array.prototype). This begs the question: What if someone else has already defined a function with the same name? You have two options here, you override it, or assume that it does what you want. In the case of Ext injecting methods into JavaScript core prototypes, it's pretty innocuous. Why? because it's only injecting methods that are available on one browser but not another. That always annoyed me when some browsers contained more helper methods for Arrays than others. What does Ext do if there already exists a slot with the same name? It does not add the functionality. This is done with the Ext.applyIf function.


Ext.applyIf(Array.prototype, {
indexOf : function(o){
for (var i = 0, len = this.length; i < len; i++){
if(this[i] == o) return i;
}
return -1;
},
remove : function(o){
var index = this.indexOf(o);
if(index != -1){
this.splice(index, 1);
}
return this;
}
});


So what's going on here? We're calling the Ext.applyIf function and passing in the Prototype for Arrays and an anonymous object containing two methods. Ext.applyIf will add the "new" slots onto the prototype if and only if those slots don't exist. This is how Ext manages to get around browser compatibility while still having helpful functions.

Here's a look at the Ext.applyIf function.

 applyIf : function(o, c){
if(o && c){
for(var p in c){
if(typeof o[p] == "undefined"){ o[p] = c[p]; }
}
}
return o;
},


As you can see, it's a fairly simple concept, just applied to good use.

JavaScript Meta-Programming

I never really know what to classify as Meta-Programming sometimes, so I'm going to use it in this circumstance to mean helper methods to make prototype OO easier.


So, along with the Ext.applyIf function there is an Ext.apply function. This appears to be used when constructing elements. Every element tags a "config" object in its constructor. Apply allows the element to place all the configuration properties into either itself OR a config slot that it has. Not only that, combined with applyIf (or just based on when you apply things), Every EXT element can have a "default" config object. When instantiated it would then call Ext.apply(this, default); Ext.apply(this, config); (assuming that config is passed in the constructor, default is available on the scope and this is the currently initializing component).


My favorite addition by Ext (which I just learned about last night) is the Ext.each method. This implements a true for-each loop on Javascript arrays. Here's a look at the code:


       each : function(array, fn, scope){
if(typeof array.length == "undefined" || typeof array == "string"){
array = [array];
}
for(var i = 0, len = array.length; i < len; i++){
if(fn.call(scope || array[i], array[i], i, array) === false){ return i; };
}
}


Now instead of writing:

for(var i=0, len = items.length; i < len; i++) {
alert(' Workin on ' + items[i]);
}


I get to write this:

Ext.each(items, function(item) {
alert('Workin on ' + item);
});


I guess it's not really a big savings, but it seems more friendly to me (as I love closures).

I wish I could cover more, but I don't really have the time right now. We'll have to do it in a separate post.

Monday, February 18, 2008

Ridicule the Ridiculous

This weekend I was attempting to try the new "ANTLRworks" studio on Ubuntu to see if I could see what all the ANTLR hype was about (I'm a JavaCC junkie).

Here's my beef with Sun:

Sun's JVM on Linux needs some help. Not only is it using some random way to render fonts (making all Java Apps look significantly different than the native OS), the GTK look and feel is ridiculously slow for some reason. I have a friend who also experienced similar problems on Fedora Core. This almost made me switch to the Metal look and feel. Unfortunately, the Metal look and feel is just to plain ugly for me, which soured my whole opinion of ANTLRworks.

Sun, why oh why did you not integrate with Linux better? GTK is open-source. That should make it pretty easy to look and feel like the GTK. I remember the Solaris I used in college had a ridiculously ugly Window manager, but that's not really an excuse anymore. (p.s. Is there a KDE look and feel at all?)

If I want to target Ubuntu/Fedora Core in the future, I'll use SWT.

For those of you who may be wondering, I'm running Gusty Gibbon (7.10) with Gnome running Sun's JRE 1.6 (Can't remember the update version).

Onto ANTLRworks.

This software boasts some AMAZING features for developing grammars. DFA diagrams, debugging, testing individual rules... I was really excited to get in and play. Especially since ANTLR has a lot of features beyond what I'm used to in JavaCC. My major complaints are as follows:

  • Somehow the ANTLR community ticked off the antlr-eclipse-plugin lead developer. Not only is the plugin no longer available, the source is gone. Instead I used the Maven-plugin for ANTLR3 to compile the grammar and unit-tests. Strike #1 -> ANTLR Community
  • I copy-paste some sample grammar code and put it in my .g file. Attempt to run ANTLR and I get a null-pointer-exception. NPE = Strike #2 -> ANTLR Software
  • Next I was trying to run the debugger in ANTLRworks to test out Rules. Because of the Eclipse plugin issues, ANTLRworks was my only source of nice syntax-highlighting and auto-formatting. Well, to make sure I wasn't duplicating efforts, I figured I could at least debug the grammar in ANTLRWorks before I passed it off to my eclipse project (for an Eclipse DLTK language add-on). Unfortunately I could not make the ANTLRWorks debugger work. It literally would just hang infinitely. This may have been an issue with my grammar, still I lost an hour or two trying to figure out the software when I could have been debugging. Strike #3 -> ANTLRWorks

So, am I giving up on ANTLR? Not yet. I'd like to have a "base" grammar file that could be used in multiple implementations on multiple languages, and I still want to try out the AST builders. Currently JavaCC doesn't really let me do that (although it doesn't force a dependency on itself in my output).

Thursday, February 14, 2008

Great way to confuse your coworkers

Next time you're doing multi-threading code, my co-worker Joel and I came up with a great plan to ensure your job and confuse your co-workers. I'm calling it String-Locks. Yes, String-locks are a great invention that will allow you to thoroughly understand a system while no-one else does. The key here is to learn how Java treats inline string literals. (Go and learn)

Now, you're ready for the meat of the idea. Because Java makes every object a Mutex with available wait and notify methods (along with being able to synchronize) you can get away with some really really neat tricks (and by tricks I mean ugly, nasty hacks). Not only is EVERY object a mutex, but string literals are considered of the class String. This allows the fun if("me".equals(other)) { } syntax.

Now, when you're writing "thread-safe" code, make sure you take advantage of this. Instead of using an arbitrary object for a lock or using "this" for a lock, you should use a string literal.


class ThreadSafeActor {
public void sendMessage(Message msg) {
synchronized("post office") {
this.postOffice.add(msg);
}
}
}


Notice the seemingly thread-safe looking code. If your team is not using an IDE you might be lucky enough that no one notices the string being passed to the synchronized keyword. Or they may be so used to groovy they mistake it for a method call with a closure. We know the real story, you're using the fact that Sun's JVM creates a cache of string literals it will use per classloader. Make doubly sure you're in an environment with more than one classloader, otherwise you lose some of the magic.

Now you have Single ClassLoader thread-safe code. Not only that, your mutexes may be used in arbitrary classes. You've completely broken encapsulation here. You can throw the same string literal in several classes for use as a mutex. Imagine the possibilities! And only you will know where each string is used and be able to avoid deadlock.

Not only that, look at the code itself.
class ThreadSafeActor2 {
public sendMessage(Message msg) {
synchronized("mail box") {
mailBox.send(msg);
"Josh".notify(); //Notify Josh to wake up and check his mail
}
}
}



Ah, the beauty. Of course you should ALWAYS program with Singletons. Not only is it easy to find an object (Just use ObjectName.getInstance()), then this threading strategy is much easier to pull off.

With this power at your fingertips, go and make revolutionary changes to your software

Wednesday, February 13, 2008

Best Practice, more like Best Schmactice

So, I've seen a lot of questions posted to user-lists for software that run along these lines:

"How do I do XYZ"
:: Response ::
"Is there a Best Practice for this?"

My answer: Here's a reasonable practice to solve your problem. Meaning, this solution worked great for me a couple times, is easier for me to maintain than other solutions, and has been adopted by other developers. It may not be the best practice in your situation. Without context, there is no best practice.

When you ask for a best practice you're really saying, "I don't have time to think through the pros and cons of various solutions, please let me know what works for most people, and I'll just use that." That's fine. In practice, I do this all the time, especially as deadlines roll on by. In fact, without "best practices", I would have struggled to deliver software.

The problem here I'm getting to is that a "Best Practice" is only best for a certain technology/scope. As technology is changing all the time, something that used to be "the best way" is now out of date and should be replaced with new technology. My favorite example: XML. Man, there was a time where throwing X in front of anything made it better, and using XML naturally made your software work better, and become more robust. I'm not busting XML here, I think it's a great solution to certain problems. However, XML is NOT a "Best Practice", it's more a reasonable thing to do. And now, with all the XML whiplash, people are going to the other extreme (see Groovy Community). I'm not bashing the Groovy community either, but I think they may be swinging too far in the other direction. (XML is still very useful in certain instances).

I know in practice, we use JSON for AJAX at work. Doesn't that kill the acronym? Perhaps it should be AJAJ now... Back to the point. Why do we use JSON for our AJAX calls instead of XML? In this situation, we can represent the same data in either XML or JSON, so why JSON? Well, the JSON Format is such that is easier to understand from a JavaScript Developer (I mean, it IS javascript). Also, JSON can be more easily compressed and sent over the network. Since it doesn't have redundant opening and closing tags. So I would argue in the case of AJAX, JSON is a much better way to transmit data. Notice I did not say content. Since web page content is either bastardized XML or formal (XHTML), it's obviously best to send web page content in XMLish fashion. Anyway, it's the context that's important here.

That brings me to AJAX. Should you make the whole site AJAX? AJAX does seem like a "Best Practice" for website creation. However, what about bookmarking? Whenever I want to send links to someone, I grab my address bar and email it. If all my content is ajaxed in, I no longer have that option. This means I need to go through some extra JavaScript magic to change the URL in the browser so that I can restore the same webpage state, without actually navigating different pages while the user click around on my Rich website. Don't think "Really Cool", Think about consequence.

Obviously adding Bling is probably the most important thing you can do for demos and showing the customer. Not only do you want to do the functionality, you want your software to look good. That's why you try new technology. However, if you stick to "Best Practices" how are you going to shine above any other software company?

My Theory:

Use "Best Practices" for the technology/problems that aren't important to your software's success, and use your creativity to produce optimal solutions for the things that are.

Tuesday, February 12, 2008

Technology... My Enemy, My Friend

So, at work I've recently been doing a LOT of learning, hacking, debugging, cursing new technologies. It's amazing how many new things are out there.

Here's a survey of what technologies I've learned or experimented with in the past 3 months
  • Groovy/Grails
  • Maven (more specifically, the parent pom magic and profiles)
  • Apache Archiva (see above)
  • Continuum
  • Eclipse Communication Framework
  • Eclipse RCP
  • Eclipse Buckminster
  • Spring (specifically, Web stack & OSGi)
  • ExtJS (Amazing-looking JavaScript UI library)
  • JQuery
What have I learned? Well, a few things. First, the Maven crowd is amazingly helpful. I've been randomly talking to the Maven Javascript Plugin author and he was willing to make fixes for me in a few short days! I also learned that, similar to what I heard about the Rails community, the Grails community is very opinionated about how software should be written, and I disagree with some of their major points (most of these dealing with small vs. large projects). Also, if you have the time to invest in a Maven parent pom (and an understanding of general project structure for your compnay) you can get away with very small build files for projects and a lot of nice baked in functionality. The final thing I learned is that none of the new technology really works well together.

First Rant: Grails

I gotta hand it to the Maven Grails plugin developers. It seems to me that grails (although not actively subverting their efforts) has made their jobs a helluva lot more difficult by decisions they've made. My first experience with the Maven Grails Plugin really turned me off to using Grails with any of my enterprise software. Maybe I should not complain about having to have Java, Groovy, Grails AND Maven installed for it to work together. However, Lift manages to work just fine inside Maven without requiring additional install, why shouldn't grails? Does grails expect me to throw out all my existing company Maven infrastructure (continuum, archiva, auto-generated documenation sites) to use their software? I really hope not. Look like I'll be installing grails on our continuum server, and hoping we can get the report generation to work. (After my next hard deadline of course).

That being said, I think Grails is an amazing framework, and offers a lot of functionality very quickly.

Second Rant: JavaScript

Wow, what a language! Javascript is phenomenal! I love this language. With great packages like Jquery and Ext, you can be extremely productive. Unfortunately, you're thwarted by a really poor container (and having to support non-standard DOM methods). Want to create a JS library? Easy to do with the Maven Javascript plugin. Not only can you automatically generate documentation and unit test, you can also minify your code library into a single js file. It's a real beauty. Then you notice some strangeness in how things are working in IE vs. Mozilla. I never really did any hard-core JavaScript before, so I wasn't really prepared for it. It's as bad as people gripe about.

Last Rant: Eclipse

Eclipse is a nice IDE. Tons of features, and free. I've looked into IntelliJ. GREAT IDE with lots of powerful features, however I don't know it yet, and I'm working on an Eclipse RCP app, so there's no switching now. As an Eclipse Plugin Developer myself, I realize it's very hard to create a fully-features plugin that really integrates well with eclipse and some technology. I have a ton of respect for people who do this for Maven, Groovy, Scala, etc. I just wish someone were paying these people more money (or if my workplace would donate money to their efforts) so that we could get some better support for things. Maven is sweeping through a lot of companies and support in eclipse is still sub-optimal. That's a big downer. I'm also disappointed that I can't use Maven to develop my RCP app (using Eclipse 3.3). The two seem like they could really benefit a lot from each other... OSGi Bundles + Maven Repo + Eclipse = heaven.

Well, that's enough ranting for now. In the future I may include special "how-tos" and additional rants. Maybe even speculation and completely false rumors.

Funny - Writing Unmaintainable Code
I enjoy humorous articles. So I'm going to include an excerpt from this one: Writing Unmaintainable code

Bedazzling Names
Choose variable names with irrelevant emotional connotation. e.g.:
marypoppins = ( superman + starship ) / god;
This confuses the reader because they have difficulty disassociating the emotional connotations of the words from the logic they’re trying to think about.