Saturday, June 30, 2012

Do You Know What Day It Is?



Have you ever sat in on a meeting like this?




Person 1:  The customer wants a green background on this page.



Person 2: Do we know they're going to stick with green?  Maybe we need a configuration option for background color.



Nobody wants to disagree and the manager never comes to these boring design meetings so there is quiet before somebody says...



Person 3: A configuration option just for background color is kind of weak, we'd be better off allowing choices for all colors.



Person 4: Is this an instance level configuration, or do we let the end-user pick her color?



Person 2 (the original troublemaker): well it really has to be instance level, but the end-user can override, that way we satisfy all possibilities.



From here the debate continues until they've decided to create a skinning system with lots of UI color pickers and other stuff, and they wrap up with:



Person 6: Well this sounds great, but what should we make the default background color?



...and nobody can remember that:




The customer specifically asked for green, only green, and nothing but green.



Is this an exaggeration?  Perhaps, but I've sat in meetings that come close.  Seems to me that I've sat in meetings that were worse, but I'd hate to slander anybody, and being as I'm not perfect myself, we'll leave that one alone for now.



So anyway, there were many things going wrong in that meeting, but we're going to stick with the simple fact that nobody there knew this one simple rule, the first rule of system design, which should be burned into your brain, which you should repeat before and during any design or architecture meeting:





Today's Constant is Tomorrow's Variable.



This is not so much a rule as an observation, but when you realize that it is true on almost any level, it can become a guiding rule, something that actually lets you make decisions with confidence, decisions that turn out to work well.



The problem is that most people in technology don't know what day it is.  They make one of two mistakes, they either:


  1. constantly plan, estimate, design, or program for tomorrow's variable when all they need to do is handle the simpler case of today's constant.

  2. or they don't realize that when "the customer changed the requirements!!!" the customer is doing what everybody does, taking something simple from yesterday and making it a bit more complex today.


So you can turn this around and say, "Everything I do today will get changed tomorrow.  It will become more complicated.  Everything I think is fixed or constant will float or become a variable."













What It Means



We've all learned (hopefully) that you don't embed constants in code because it makes the code difficult to change.  We define the constants in headers, or we accept all values from outside sources as parameters.  This makes the code more flexible, and it is a good thing.  The code is more robust, it can handle more cases without breaking or needing alteration.



The trick to using Ken's first and only rule of system design, "Today's Constant is Tomorrow's Variable" is to recognize the many forms of "constants" that we build into our systems in hard-to-reach places, making it hard to change them when tomorrow comes and they are no longer fixed and constant.



Another trick to using the rule is to always know what day it is.  Most of what I do today will involve features that may never change.  It is extremely easy to see how they might change, but impossible to know for sure.  So we leave them constant for today.













Back To That Meeting




Let's go back to that meeting we started with.  Here is how it goes when somebody knows that "Today's Constant is Tomorrow's Variable."





Person 1:  The customer wants a green background on this page.



Person 2: Do we know they're going to stick with green?  Maybe we need a configuration option for background color.



Our Hero:  We don't know they are going to stick with green because we never know if any customer is ever going to stick with anything, and we all know that today's constant is tomorrow's variable.  However, I hope we've put the styles into a style sheet and not embedded them directly into the HTML so we can change it later if we have to, right?





Somebody mumbles that yes in fact we do use style sheets, and the meeting moves on.













Is That  Lame Example?



That's a pretty lame example really, who doesn't use style sheets?  And who embeds constants in their code?





Well kiddies it turns out that we didn't always use style sheets.  When I got interested in web pages CSS was still optional (Yes! Believe it!) and you put your style information directly into tags, which was basically embedding constants into code, and it didn't take long before you intuitively realized this was not right, and you discovered CSS.  





It is amazing how often that basic pattern repeats itself, trying to identify what you thought was a constant, realizing it is "buried in code", and turning it into a variable.













Today's Post Is Tomorrow's Promise





I'll be posting a lot more on this subject, using a very reliable and strict schedule based on a host of variables that mostly comes down to whenever-the-hell-I-feel-like-it(TM).  





Cheers.



Tuesday, June 26, 2012

ListUIs: Adding Decorations to Cells

This is a follow-up to my previous article: TreeUI's: Adding Decorations to Cells.

What is a "Decoration" again?

A decoration is a UI component overlayed inside or on top of another component.

Muted-color minimal buttons/decorations are becoming increasingly common in modern UIs. This is great way to add extra functionality for power users without adding too much visual clutter.

Here is a screenshot of part of my current Firefox window. There are 6 decorations showing:

  • The star bookmarks a page.
  • The down arrow presents a list of recent URLs.
  • The circular arrow refreshes the page.
  • The left side of the search field lets me change search engines.
  • The word "Google" is also a decoration indicating what search engine is being used.
  • The right side of the search field commits my search.
  • ... but there are only 3 non-decorative UI elements showing: the URL field, the history button, and the search field. The decorations add a lot of subtle controls in a small space.

    As an accessibility side-note: it's worth mentioning that decorations usually do not receive keyboard focus as you navigate the interface with the tab key. They are second-class citizens when it comes to your window hierarchy. You probably need to provide alternate ways to access these features (menu shortcuts, for example) to help reach a wider target audience.

    List Decorations

    The section above talked about decorations in general, but what are some examples of decorations for list elements?

    Above are search results in a recent youtube query: when you mouse over a thumbnail there is an optional button to add a video to your queue.

    Also you could provide buttons to delete list elements, reload, or show progress indicators.

    On the right is a new-ish decoration for sound files observed on Mac OS 10.7. When you mouse over the graphic: a play button fades in. When you click the play button: the outer ring appears, and the gray arc proceeds clockwise representing the playback of your sound.

    The same playback controls are used for movies, however for movies the controls fade away as soon as you mouse out of the preview area.

    (Traditionally these controls have been presented with a thin horizontal row of controls along the bottom of a sound/movie. I'm not trying to argue that Apple's new circular timeline is any better than a horizontal timeline: both could be presented with overlayed controls.)

    Implementation

    In Swing, JLists (and JTrees) use renderers, where one component is rubber stamped for every element in the list/tree.

    This is a great scalable model (because tens of thousands of elements can safely be rendered without too much overhead), but it lacks mouse input. To implement decorations on a list, I developed the DecoratedListUI. This UI manages multiple ListDecorations, which are rubber-stamp overlays to your existing ListCellRenderers.

    All you have to do is invoke the following:


    ListDecoration[] arrayOfDecorations;
    ...
    myList.setUI( new DecoratedListUI() );
    myList.putClientProperty( DecoratedListUI.KEY_DECORATIONS, arrayOfDecorations);

    Example

    Here is an example that emulates the Mac playback controls with a list of 5 sounds:

    You can download this jar (source included) here.

    (Note: usually I make an effort to keep my jars small in file size so you can easily plug them in to other projects, but in this case: I ended up bundling several megabytes of wav files inside the jar. So while this jar is nearly 2 MB, the code you need is probably less than 100 KB. Sorry for the inconvenience.)

    In this applet: each sound file is an element of a JList. When you select a sound file: decorations appears to play/pause and delete the sound.

    In theory you could make some decorations always visible (this might be especially useful for a loading indicator, or a warning indicator?), but personally I want actionable buttons to be limited in number to keep the interface simple.

    Also, in case you were wondering: the music file icon is a scalable javax.swing.Icon. I noticed in some contexts on my Mac the background had a sort of plastic glazed look and not a radial gradient, but I decided not to fixate on that level of detail. My replicas are never intended to be pixel-perfect copies, just reasonable likenesses.

    And if anyone knows how to reduce the flickering observed in this (and other) applets: please let me know! This does not reproduce when launched as a desktop application, so I'm not sure exactly how to debug this.

    Saturday, June 23, 2012

    Liens pratiques de la semaine

    Vous trouverez dans ce billet une s�lection de liens pratiques autour des technologies Eclipse qui m'ont particuli�rement int�ress�es ces derni�res semaines.   

    Eclipse
    • Angelo Zerr pr�sente le projet Eclipse Libra via trois billets (billet 1, billet 2 et billet 3). Le projet Eclipse Libra fournit un ensemble d'outils pour les applications d'entreprise bas�es sur OSGi. Plus pr�cis�ment Eclipse Libra regroupe les outils du projet WTP et PDE. Dans le cadre des billets d'Angelo, il montre comment construire un WAR � partir d'une application RAP.   
    Java 
    •  Si vous recherchez une biblioth�que Java permettant de lire des vid�os sous diff�rents formats Xuggler peut faire l'affaire. Il s'agit d'un wrapper Java pour ffmpeg.
    • JavaCV est un wrapper Java des principales biblioth�ques qui manipulent du contenu multim�dia (OpenCV, ffmpeg...).
    Divers
    • Un billet tr�s int�ressant qui parle du Cloud pour le d�veloppeur.
    • ownCloud est une solution alternative � DropBox. Cette solution de partage permet tout comme DropBox de disposer d'un client install� sur son poste (Linux, Windows et MAC OS) pour synchroniser des fichiers. ownCloud fournit �galement des modules suppl�mentaires permettant de synchroniser d'autres types de ressources (calendrier, contacts, vid�os...). J'ai eu le m�me coup de c�ur qu'� l'�poque avec Redmine. J'utilise actuellement ownCloud en test mais j'ai du malheureusement d�sactiver le partage de fichier entre utilisateur puisque ce module am�ne � une occupation anormale du processeur. Esp�rons que les prochaines versions stabilisent ce probl�me. A surveiller de pr�s. 


    Sunday, May 27, 2012

    TreeUIs: Adding Decorations to Cells

    This article discusses a modified TreeUI that lets you add decorations on the right side of your tree. (See this other article for a similar discussion focusing on JLists.)

    What do I mean by "Decoration"?

    The short answer is, "I'm not exactly sure." It's similar to a button or a label (depending on which one you want), and that's how most users will perceive it, but it is not actually a JComponent, and it does not exist in the Swing hierarchy of your window.

    In a JTree: every cell is rendered via a TreeCellRenderer. The same renderer is consulted for every row in the tree, so the intended usage is for one component to be used to display potentially thousands of different values. This is referred to as "stamping", because the renderer is repeatedly painting to the tree without actually belonging to it.

    This is a wonderful design regarding memory use, but it becomes difficult to add functionality to trees the same way you can add functionality to text fields and other Swing components -- because you don't have a solid grasp on the hierarchy of elements involved.

    The decoration model partially addresses this issue. Swing components are (usually) very well suited to this kind of augmentation. There is nothing sacred about the current implementation of the JTree and how it renders: these components are designed to flexible and, when possible, improved to meet your needs.

    Examples

    To help paint a better picture of what I'm describing, here is an applet demonstrating tree decorations:

    This applet (source code included) is available here. Here is a summary of each decoration:

  • Progress Indicator: the root node takes a few seconds to load. While it is loading: a progress indicator appears on the right side of the tree. As soon as the tree is fully loaded: the indicator is hidden.
  • Refresh Button: Once the progress indicator is dismissed, the root node will show a refresh button when it is selected. (When clicked, the node re-loads like it did before.)
  • Play/Pause Buttons: when the "Playable" node is selected a play/pause toggle is present. (In this demo nothing actually plays, but this was designed with audio playback in mind.)
  • Warning Indicator: this node shows a pulsing warning icon when selected. (Thanks to the Silk icon set for the image!)
  • Rating Stars: this node shows 5 rating stars when selected. This is a good demonstration of the current limits of the decoration implementation: clicking and dragging does not work like I would want it to.
  • Delete Button: this removes the selected node from the list.
  • The delete button is actually the original motivation for this project: I didn't want the user to have to click a tree node and then navigate somewhere else in the UI to the delete button. In my case this saved several pixels, cleaned up the layout, and made the user's task more efficient. Also because the button is adjacent to what it modifies: there is little room for confusion about which object the user is acting on.

    However I am also worried that this model can introduce too much visual clutter (aka "over-stimulation"). To limit the amount of controls the user needs to process I made most of the decorations only appear in a row when that row is selected. Also this helps guard against accidentally clicking the wrong button, which becomes increasingly important when your controls become smaller. Restraining the number of decorations is just a suggestion, though: you can make all your decorations visible all the time if you want to. (For example: if you're always dealing with very advanced users, or if your tree is usually going to be relatively small.)

    And lastly: as a personal preference I added an option to highlight the width of the entire row. By default the BasicTreeUI only highlights the text of the tree node when it is selected, but this tree is a kind of hybrid between a tree and a list (or a tree and a table?): so highlighting the entire row seemed like a good idea.

    Implementation

    The DecoratedTreeUI is an extension of the BasicTreeUI, so it inherits most of the standard tree functionality.

    It takes the existing TreeCellRenderer (that the JTree stores) and places it inside its own renderer. On the right side of that renderer it adds all the appropriate decorations as JLabels. As the demo above shows: different tree nodes can have different decorations.

    The decoration object you need to supply is represented with three methods:

    public abstract static class TreeDecoration {
    public abstract Icon getIcon(JTree tree, Object value, boolean selected, boolean expanded,
    boolean leaf, int row, boolean isRollover,boolean isPressed);

    public abstract boolean isVisible(JTree tree, Object value, boolean selected, boolean expanded,
    boolean leaf, int row, boolean hasFocus);

    public abstract ActionListener getActionListener(JTree tree, Object value, boolean selected, boolean expanded,
    boolean leaf, int row, boolean hasFocus);
    }

    These are the only methods you need to implement to add decorations to your tree. And there is also built-in support for the BasicTreeDecoration (for simple labels/buttons) and RepaintingTreeDecoration (for decorations that continually need to repaint).

    To install decorations, call:

    myTree.setUI(new DecoratedTreeUI());
    myTree.putClientProperty( DecoratedTreeUI.KEY_DECORATIONS, myArrayOfDecorations );

    Also to give you complete control over how the icons are positioned: there is no padding between decorations. That's not because I think zero padding is a good idea (it's not), but this lets you pad your icons with however many pixels you think is appropriate (instead of an arbitrary amount I made up).

    The rest of the implementation is probably relatively boring: the hard parts included identifying the simplest methods I needed to override to add the functionality I wanted, and adding a simple model to arm/disarm the decorations so they really behaved like buttons. As of this writing: the final implementation is about 500 lines of code (not counting comments), so it's not that daunting in the end.

    Thursday, May 24, 2012

    Liens pratiques de la semaine

    Vous trouverez dans ce billet une s�lection de liens pratiques autour des technologies Eclipse qui m'ont particuli�rement int�ress�es ces derni�res semaines.   

    Eclipse
    Java
    • Sonar 3.0 est disponible (nouveaut�s) et page de t�l�chargement
    • Un billet qui pr�sente une comparaison entre SQL et JPQL.
    Divers
    • Vagrant est une solution permettant de faciliter la virtualisation de son environnement de d�veloppement. 


    Saturday, April 28, 2012

    Liens pratiques de la semaine

    Vous trouverez dans ce billet une s�lection de liens pratiques autour des technologies Java et Eclipse qui m'ont int�ress�es ces derni�res semaines. Vous trouverez �galement un bilan de choses int�ressantes d�couvertes lors de Devoxx France 2012.

    Eclipse
    • Nouveaux sucres syntaxiques pour Xtend le nouveau langage de la fondation Eclipse. 
    • JNect un plugin Eclipse qui fournit une passerelle Java pour le capteur Microsoft Kinect. La vid�o montre l'utilisation du capteur au niveau de l'IDE Eclipse.
    • Eclipse Orion, l'IDE dans le navigateur, passe en 0.5 M1 (page de nouveaut�s et page de t�l�chargement).
    • Une s�rie de billets r�alis�e par Angelo Zerr qui traite de la mise en place d'une architecture Eclipse RCP/RAP avec Spring DM et Spring Data JPA. Comme d'habitude les billets sont tr�s d�taill�s et illustr� par une d�mo.
    • Les transparents de la conf�rence EclipseCon 2012 sont disponibles en t�l�chargement sur cette page.
    • EclipseLink dans sa version 2.4 supportera les solutions de stockage NoSQL. Un billet int�ressant qui montre comment int�grer la prise en compte du mode de stockage dans les classes Java. Avec Hibernate OGM, on se retrouve avec deux solutions diff�rentes. A quand une standardisation au niveau JPA ?
    • EclipseTotale fournit des liens tr�s int�ressants sur des pr�sentations donn�es � l'EclipseCon 2012 expliquant le fonctionnement du socle Eclipse 4.
    • EclipseDayToulouse, une conf�rence pour les amoureux de la plateforme Eclipse, se d�roulera le 24 mai prochain � Toulouse. Developpez.com est partenaire presse de cet �v�nement.
    Java
    • Peut-�tre en retard sur ce point l� o� trop focalis� sur le d�veloppement de clients lourds, j'ai d�couvert Bootstrap lors de discussions � Devoxx. Ce n'est pas une biblioth�que ni un framework mais une feuille de style CSS d�velopp�e par Twitter. Avec cette feuille, cr�er une page Web devient tr�s facile. Visionnez cette vid�o pour vous faire un aper�u rapide. Au fait, le site Web d'Xtend utilise Bootstrap.
    • Byteman est un outil qui permet d'injecter du code Java dans une classe d�j� charg�e par le classloader. Il permet donc de faire de la modification dynamique de bytecode. Je vais essayer de faire un billet sur ce sujet.
    • Si vous souhaitez faire du Push serveur avec GWT vous pouvez utiliser GWTEventService.
    • J'ai d�couvert une nouvelle fa�on de coder un singleton, passer par un �num�r�. Voici un article de Lars Vogel qui montre comment faire.
    PS : � noter pour la prochaine fois, ne pas laisser d�p�rir mon blog ;-)

    Wednesday, April 11, 2012

    Devoxx France 2012, j'y serai et vous ?

    La semaine prochaine se tiendra � Paris la conf�rence Devoxx France 2012. D'apr�s Nicolas Martignole un des organisateurs, la conf�rence se fera � guichet ferm�.  Tr�s bonne nouvelle pour les organisateurs.

    Je ne vais pas vous faire une nouvelle pr�sentation de cet �v�nement mais juste vous dire que j'y serai sur les trois jours. Au niveau des sessions qui m'int�ressent, j'essaierai de suivre en priorit� celles en relation avec le NoSQL (Cassandra, MongoDB notamment), les retours d'exp�rience de solutions technologiques en production et des sessions plus techniques sur le fonctionnement du c�ur de Java. Par contre, je n'ai pas trop vu de session Eclipse, un drame !!!

    Par ailleurs, je serai reconnaissable puisque je porterai en plus du badge de la conf�rence, un badge Developpez.com. En fait, la majorit� des membres de l'�quipe Java de Developpez.com porteront un badge suppl�mentaire. N'h�sitez donc pas � m'interpeler, je serai ravis de discuter avec vous.

    Au fait et vous, vous y serez ?