2008-04-21

Make your Eclipse rock

Eclipse is one of the greatest IDEs available out there. In my opinion it's the best, because in comparison with other choices such as Intellij IDEA, Eclipse is free and open. People say NetBeans are getting good, however I am too skeptic to believe. As it's the matter of preference, I will stick with Eclipse.

Yet, after a fresh and clean install Eclipse (v3.3 as of this moment) is not yet kicking. A few crucial things are missing. I'll give out my recipe to making Eclipse rock. So, let's get on with that:

  1. Fresh install from www.eclipse.org. As I'm NOT doing J2EE/Web/XML stuff at home, Eclipse IDE for Java Developers is the best choice for me.
  2. Give it more RAM! Default values are pathetic, so you should edit your eclipse.ini to look like this:
    -showsplash
    org.eclipse.platform
    --launcher.XXMaxPermSize
    256M
    -vmargs
    -Dosgi.requiredJavaVersion=1.5
    -Xms256m
    -Xmx1024m
    -XX:PermSize=256m
    Say bye to those possible out of memory and permgen space errors.
  3. Fine-tune the Preferences. Go straight to workspace and open Window -> Preferences.
    General:
    Check "Show heap status" - it's nice to see how much heap you've got.
    General -> Appearance:
    Uncheck "Show text on the perspective bar". That gives more space for perspective icons.
    Check "Show traditional style tabs". Performance.
    Uncheck "Enable animations". Performance.
    General -> Editors -> Text Editors:
    Check "Insert spaces for tabs". You may not want that if you're a tab fan.
    Check "Show print margin". 80 is good.
    Check "Show line numbers". Who would not want to see line numbers by default?
    General -> Editors -> Text Editors -> Spelling:
    Uncheck "Enable spell checking". Performance. And hell, that's no Microsoft Word.
    General -> Startup and Shutdown:
    Uncheck "Mylin Tasks UI" from "Plug-ins activated on startup". Unless you REALLY want to use Mylin. I think it sucks and terribly slows Eclipse down.
    General -> Workspace:
    Choose "UTF-8" as your "Text file encoding". Unicode is the way to go.
    Choose "Unix" as your "New text file line delimiter". This is also is the way to go.
    Java -> Code Style -> Formatter:
    Click "Edit..." on Eclipse [built-in] profile. Set new profile name. In "Identation" tab set "Tab policy" to "Spaces only". You may skip this if you're a tab dude.
    Java -> Compiler -> Errors/Warnings:
    You may want to harden your compiler warnings for more beautiful and strict development. I tend to override these:
    In "Code style": "Undocumented empty block" -> "Warning".
    In "Unnecessary code": "Unnecessary 'else' statement" -> "Warning".
    In "Unnecessary code": "Unnecessary cast or 'instanceof' operation" -> "Warning".
    In "Unnecessary code": "Unnecessary declaration of thrown checked exception" -> "Warning".
    Java -> Compiler -> Javadoc:
    Set "Malformed Javadoc comments:" -> "Warning".
    Set "Only consider members as visible as: " -> "Private".
    You want your Javadoc clean, don't you.
    Java -> Editor -> Content Assist -> Advanced:
    In content assist proposal list uncheck entries marked with "(Mylin)" and check the alternatives: "Other Java Proposals", "Template Proposals", "Type Proposals".
    In cycling list check all same entries: "Other Java Proposals", "Template Proposals", "Type Proposals".
    Web and XML -> XML Files -> Source:
    In "Formatting" section check "Indent using spaces" and set Indentation size to "2". Otherwise you will end up with tabs in your XML.
  4. Subversive - the best Eclipse plug-in for SVN support:
    Help -> Software Updates -> Find and Install. Search for new features to install. Add two New Remote Sites - "Subversive SVN Connectors" with URL: http://www.polarion.org/projects/subversive/download/eclipse/2.0/update-site/ and "Subversive plug-in" with URL: http://download.eclipse.org/technology/subversive/0.7/update-site/
    Check http://www.eclipse.org/subversive/downloads.php for latest URLs.
    Install new components. Skip Mylin integration and sources.
  5. Maven plug-in. You MUST know what Maven is, otherwise don't do Java. Seriously. You may choose from Tycho and Q: http://maven.apache.org/eclipse-plugin.html
    I was a long-time user of Tycho, however Q looks really promising. I'm trying it right now for the first time. Yeah, definitely, go for Q. Installation is easy, just add New Remote Site:
    Q4E: http://q4e.googlecode.com/svn/trunk/updatesite/
  6. XML Buddy. Your light weight swiss army knife in Eclipse XML editing. Download plug-in manually from http://xmlbuddy.com and drop it into your Eclipse plugins folder, then restart.
  7. JADClipse. Your daily Java decompiler. Best for those times when you need to go under the hood. Make this a habit. You will need JAD in your PATH: http://www.kpdus.com/jad.html
    Then download JADClipse plug-in from http://jadclipse.sourceforge.net/, drop it to Eclipse plugins folder and restart.
Enjoy your tools!

Hierarchical Model View Controller - beyond MVC

I would like to share a few articles I've written back in 2005/2006 while working on an open source project - Hierarchical MVC Web framework - Claw:

Long gone post #2.

It is a common pattern in Java community (NOTE: I thought so back then, though found out that it's not really common at all), while it seems like PHP developers think there is no heaven like MVC. For those, who are interested in HMVC concepts, read this (and notice the date – quite an oldie, eh?):

http://www.javaworld.com/javaworld/jw-07-2000/jw-0721-hmvc_p.html

I haven't found a single open source PHP framework with HMVC implementation, that's why Claw was born. Are there any more of this kind? Did I miss anything? Please let me know if I did. Anyway, the long URL above would most probably be helpful for Java GUI application developers, I must say that I do not understand more than a half of that document, and never actually read the code examples carefully, so I think it is easier for me to rewrite the concepts the way I understand them and the way they work in Claw Framework. Before that you may take a glance at another Javish explanation of Hierarchical MVC here:

http://www.thecentric.com/wiki/index.php/HMVC_Tutorial

Did not get that one either, but at least it's shorter and easier to read. If you really bothered yourself to at least briefly look through that information (and shame on you if you did not, and I know you did not), you should have found out the key advantages of HMVC pattern are something like:

  • Defined intralayer communication and isolation from higher layers
  • Defined interlayer communication with minimal coupling
  • Localization of exposure to third-party code
  • Reduced dependencies between disparate parts of the program
  • Encouraged reuse of code, components, and modules
  • Increased extensibility while easing maintainability

Back to our shop architecture – here is the draft of my HMVC-inspired implementation:



For those who see a spaceship or a piece of DNA chain – bigger blocks are controllers, small tablets – controller actions (you can call them functions, methods or events if you like), black arrows show possible routes to some point of application and dotted lines show which action belongs to which controller. Now imagine the flattened requests:

http://www.shop.com/
http://www.shop.com/list/
http://www.shop.com/list/category
http://www.shop.com/list/category/4
http://www.shop.com/list/search/query.hammer
http://www.shop.com/list/category/4/product/2524
http://www.shop.com/list/search/query.hammer/product/2524
http://www.shop.com/product/2524
http://www.shop.com/list/search/query.hammer/page.4/product/2524
http://www.shop.com/list/category/25/page.42/product/11945/reviews
http://www.shop.com/list/search/query.big+fork/sort.price/order.asc/page.18/product/114/review
http://www.shop.com/product/1545/reviews

These requests would go easily without any custom mappings, URL rewriting or any other hacks you would have to do in plain old MVC. I guess these links need no special explanation, but just in case, let's examine the longest one piece by piece:

/ IndexPage – root controller for the following hierarchy
/list ListPage – controller for accessing product lists
/search ListPage::search -search action invoked on list controller
/query.big+fork ListPage::search – argument 'query' => 'big fork'
/sort.price ListPage::search – argument 'sort' => 'price'
/order.asc ListPage::search – argument 'order' => 'asc'
/page.18 ListPage::page – argument 'page' => 18
/product ProductPage – controller for single product related logic
/114 ProductPage – numeric argument => 114
/review ProductPage::review – action for adding new review


We simply form this chain element by element, so the application grows like a tree, and when you need a new branch, you simply put a tiny piece of code on top of the tree, without having to touch what has already grown big. But you have all the information inherited in the way. In our example above, when user is reviewing product #114, application is aware that he/she came from a product list page 18 of search for “big fork” by price, so when it comes to rendering navigation and layouts, you could even show search results along with review form, if you would want that for some weird reason. But it's nice to have the power, no? Those who ever developed large systems should be nodding.
How do controllers inherit data? The picture below should help you visualize the process:



As application is executed, each controller (Page) may set some variables. Child controllers can set their own, though, when you are trying to get a variable that current controller does not have, system falls back to parent and checks if this variable is not there, and if it is, the value is returned. Recursion goes to the bottom of the chain if required. And since any point you can redeclare variables, so beyond a certain point the value will be as redeclared (though parent controllers will still use the old one). As you build your application layering the controllers one upon another, at the end of what I call “chain reaction”, application collects the flattened set of variables and passes them to final view (which is flattened after playing the puzzle within same reaction):



This is simply a composite view, with parts and layers, that each controller inherits from the parent and can manipulate it, rewrite it, etc. Final view is rendered only when chain reaction is over, and view layers are “flat” in final position. This is the time when variables are stamped in, so before final controller hits the breaks, nothing is rendered – this lazy kind of work saves resources.

Model View Controller and Enterprise Applications

I would like to share a few articles I've written back in 2005/2006 while working on an open source project - Hierarchical MVC Web framework - Claw:

Long gone post #1.

At this era of frameworks popping out of nowhere, crowds of people being obsessed with Ruby on Rails and Zend releasing their own framework, it's really a headache to choose the right tools for the right job. One thing is for sure – every good web developer knows – Model-View-Controller pattern is the right way to go.

Yes, MVC is a great pattern, no doubt that it's necessary to separate your business logic from graphical representation and database implementation. However, let's try implementing the following application using MVC:



What we have here is a simple structure of online shop, where users can choose the goods either by browsing categorized list of products, or by using the search feature. Product items may also have customer reviews, and visitors may add their own opinion for every product in the store. In real world you application structures are far more complicated than this one, but still, let's try modeling the MVC approach for this application.

Model

As a great fan of Object Oriented Programming, I would use a Domain Model pattern for the business logic part of the application. My components would be:

Category – tied up to the Product with many-to-many relation

  • getProducts - retrieves a list (an array) of Product objects, which belong to the Category
  • getTitle - retrieves a string with Category title
Product – tied up to Category with many-to-many relation, and to Review with one-to-many relation
  • getCategories - retrieves a list of Category objects, which the Product belongs to
  • getTitle - retrieves a string with Product title
  • getPrice – retrieves a price value object (to make it simple – just float value)
  • getReviews – retrieves a list of Reviews for this Product
  • addReview(Review) – adds a Review for this Product
Review
  • getAuthor – gets the author of Product review
  • getContent – gets the text
  • getRating – gets rating given to Product by the reviewer
After having my Domain Model ready, I would take care of persisting it to Database. Here you are on your own. I would go for Active Record implementation this time, as my model is dead simple. For more sophisticated cases Active Record would be a pain in the rear, so I would go for a serious ORM tool (such as Propel – http://propel.phpdb.org for PHP or Hibernate – http://www.hibernate.org for Java). So, we're done with our Model. No sweat! Time for the letter V in the MVC triad.

View

Personally for me, View part of any web application is the major headache, especially when you have got a State of Art prototype to follow, and your designer often complains that checkbox should be two pixels down in Internet Explorer, but four pixels up in Opera. Anyway, despite these annoying things implementing View in the MVC triad is a piece of cake. I prefer a Two Step View even in simplest situations, so I am going for it. There would be a plain HTML skeleton with empty body as the second step layer for each View, and the first step is upon the Controller.
The following problem may occur if you would want the following things done properly within your Views for current application architecture – How to Back-link Product items with the list they were accessed from. It may be the Category List, Search Result List or none, if user went directly to product. Of course, user can use browser back button, but what if he/she goes to read Product Reviews, afterwards, add a new one, then returns to Product View? I believe back button will not help you here. You could store required information in session or cookie variables, however, this adds unwanted complexity and introduces possible new bugs. Avoiding this functionality may annoy visitors, forcing them to repeat their search again, perhaps navigate through result pages to reach the point they were at. For now, let's keep our mind off this and see how to deal with Controllers.

Controller

Finally, we are about to liven up our application with user request processors, referred as Controllers. Normally, MVC frameworks use a Front Controller as one entry point for the whole application, which routes URL requests, invoking Input Controllers and their actions. How could the Controller architecture look with our current Online Shop application? It would probably end up like this:

Front Controller – the entry point which routes URL requests

Front
  • index – the action that is taken when user comes directly to your application root. Main page layout is set for View, some promo Product links attached, navigation menu for Product categories and search input
  • search – this is the action that search input leads to. It processes search query and forms a list of results, paging is involved.
  • category – here we have a list of Products by category, perhaps there would be options to sort items by title, price, ascending and descending order, also, including paging.
Product
  • index – action is taken when user views the product. Some identification should be passed along with request variables.
  • reviews – displays current product reviews
  • review – displays a form where user can add the review for the Product. It also processes form variables, validates them and writes the review to database.
Simple as that. We have mapped out our application with merely two Input Controllers! Let's see how some user URL request scenarios may look like and what would they map to:
  • / -> Front/index
  • /search -> Front/search (may display a search form with advanced options)
  • /search?q=sledgehammer&page=3 -> Front/search (third page of search for “sledgehammer”)
  • /search/sledgehammer/3 -> Front/search (same third page of search for “sledgehammer” with custom request rewriting – I will go on using this style of requests from now on)
  • /category/tools -> Front/category (category type is tools, first page of listing)
  • /category/food/price/asc/4 -> Front/category (food Products listed by price in ascending order, fourth page of navigation)
  • /product/2455 -> Product/index (would display information of product #2455)
  • /product/2455/reviews -> Product/reviews (displays all reviews for product #2455)
  • /product/2455/review -> Product/reviews (displays a form where user can submit her/his own review)
Everything looks nice, this scheme would work perfectly well, but the problem is – there are certain points where you loose the flow. Likewise, imagine you were at /search/sledgehammer/3, and clicked on a lovely “Almighty Masher”, which linked to /product/2455. You've certainly wanted some reviews of this great tool in action, and followed the “User Reviews” link to /product/2455/reviews. After reading for a while, you discover that “Almighty Masher” is just one overpriced piece of junk, and you want to fall back to the search you were doing. Well, back button is fine, click one, click two, and we're back on the track! But what if your application required users to be logged in to read the reviews? When you happily click “User Reviews” link, an unexpected screen appears asking you to log in, or even worse, offering you to register. Wise applications usually redirect user back to where he was going after logging in / registration process. It does not break the back button, you say? Perhaps, but it sure decreases the comfort of navigation (especially if your registration process had 7 steps).

Another disadvantage is that if you are in /product/2455/reviews and you still want to see the information of your product in the Reviews View, you will have to pull out the Product using the ID which comes along with request. And you will have to do this in /product/2455/review as well, or the reviewer may simply forget the exact title of the item. That leads to code duplication – every method of Product input controller must have some lines that find the Product. It's like shooting darts to different areas on the target – each area gets hit on it's own, as you cannot hit for both “10” and “15” with single shot due to the fact that there is no union on the target grid. With MVC pattern developers usually map the native applications tree (or in sophisticated cases – graph) hierarchy into plain two-dimensional grid enriched with variables. It can be compared to mapping Objects with many references, collections and relationships into Relational Database Management System. It's simple when your application is Farmer Joe's personal guest book, but what if you're working on something as large as E-bay or Amazon.com? You would sweat cats and dogs and spend months on writing meta-data and configuring your ORM tools to make your beautiful hierarchy broken down to the grid. And you would sure have to do the same with your controllers. But do you have to? I would not take this burden upon my shoulders, as my choice is Hierarchical MVC.