Posts Tagged ‘javascript’

Event driven architecture should be a must go (esp. for client side JavaScript)!

While reading Getting Started with Twitter Flight, I realized that only events provided an effective decoupling between data producers and consumers. Not Object Oriented Programming. Not services. Sounds crazy? Sounds wrong? Read on and let me know.

At first, with events, some benefits immediately pop up:
– internal changes have not effect on external code. None at all. No renaming or bigger change affect the other components, even the ones depending on this component (as long as the event itself is untouched).
– willing to change the event? Just have a look to who depends on it. No need to try to track use of some service/object/whatnot all the way through your application. And in JavaScript, doing so would be especially bad: no type, no compiler. Only plain text search through methods name (at best). Good luck with that. And if others depend on your code, well, they’re basically screwed. With events, it’s way simpler to do changes. Even deciding to version public events could be easy.

But, actually, events provide way more: they decouple events producers from listeners. Sounds trivial, for sure, but going deeper it means no need to inject some service, register somehow somewhere for callbacks, no need to look at an object with plenty of methods/stuff in it. The API to communicate with others parts of the software is actually uniform! You won’t have a specific way of doing it for each need. You just want the payload, no need to read some non existing documentation to figure out to use the crap.

The mental noise is tremendously reduced. You need to signal something to others? Easy, fire an event. You want to know of something? Easy, listen to the event. That’s true decoupling, way more that some abstract FooService with plenty of methods, related objects and extra funky behaviors or dependencies. Just the stuff you need, always through the same mechanism.

What does it mean in practice?

Well, very nice stuff:
– willing to test something when receiving an event? Plain simple, just fire it! No need to mock or whatnot the sender.
– needing to add 10 new ways of firing the same event in the UI? Plain simple, you just fire the event in the new places and all the listeners will get them. No need to change the listeners!
– you need to kill some component and fire the same event in a different way? Fear not, delete without looking anywhere else and produce the same event wherever you need it.
– you rely on some external component that you want to swap for something better. For sure, since you’re on the UI side, you didn’t code defensively. So you’ve plenty of reference to the old component’s events. Screwed? Not at all, write a component translating the events from the new format to the old one and… done!

Such ease of coding is something I would love to have whatever the language, be it Java, Scala and even more JavaScript, which has way less tooling for code exploration and refactoring.

It made me realized a funny point: Object Oriented Programming (OOP) came with the concepts of objects to encapsulate logic and data, and (public) methods to communicate with others objects. Actually, in the beginning of OOP, methods where sometimes called messages. It’s still used and visible in Ruby nowadays. Theses messages were supposed to help decoupling. The internals would be nicely hidden from the others, only the stuff needed by the outside would be visible.

Yet, in fact, you can’t get the message/public method without the object. And the object doesn’t come for free. You need to get an hand on it, to figure out what it intends you to do and so forth. The decoupling aspect of methods is pretty bad in the end. Whereas for events, it’s all bright and sunny 😉 You can get the message without the object mess. Crazily good no ? And you can change the internal, even drastically (aka delete), without affecting the outside at all.

It sounds like the Single responsibility principle done right isn’t it? Damned, I tried for so long to do that in plain old OOP…

Anyway, thanks a lot Tom, the author of Getting Started with Twitter Flight, for having made me realize this point so clearly.

All is not rosy though for sure. Infrastructure code, utilities, libraries and the like may still be used in many different parts of the same application. However, this kind of code is generally pretty focused, trying to do one thing well, and has few, if any, state. As such it’s easily testable and refactoring is seldom needed. Should the need arise, it’s generally pretty strait forward. Domain related code is a completely different story: state is everywhere, refactoring frequent. So an event driven architecture, if only for domain and application level code, already provides plenty. And is, IMHO, way better than all the alternatives I know of as of now.

Étiquettes : , , ,

Wicket et ses fonctionnalités de templating

juin 19, 2010 1 commentaire

[This note is also available in English.]

Wicket fournit des fonctionnalités de templating. Rien de bien folichon, mais c’est tout de même bien pratique, surtout quand il faut intégrer du JavaScript.

Ces fonctionnalités sont cependant très peu discutées voir même, je suspecte, globalement inconnues. Aussi, creusons un peu la chose!

Comme tout système de templating, tout tourne autour de texte contenant des variables, définies par ${variable} et dont les valeurs sont données via Java.

Voyons un exemple simple, un fichier de template nommé javascript.tpl:


Wicket permet d’aisément accéder à ces templates en tant que ressources mises dans des packages Java, via la classe PackagedTextTemplate:

public PackagedTextTemplate(final Class clazz, final String fileName)

Par exemple:

PackagedTextTemplate jsTemplate = new PackagedTextTemplate(this.getClass(), "javascript.tpl");

Ainsi, le template se trouve à côté de la classe Java et de l’html l’utilisant, rendant le tout aisé d’utilisation.

Les variables sont fournies au moyen d’une simple Map:

Map parameters = new HashMap();
parameters.put("variable","test working");

Au final ce template trônera certainement au milieu d’html. Aussi Wicket fournit plusieurs options pour cela:

  • contribution au header html:
    add(TextTemplateHeaderContributor.forJavaScript(jsTemplate, new  Model((Serializable) parameters)));
  • accolé à des éléments du body html:

    Label myScript = new Label("myScript", new JavaScriptTemplate(jsTemplate).asString(parameters));

    Html :

    <wicket:container wicket:id="myScript"></wicket:container>

Vous avez sans doute remarqué que, dans chacun des cas, je ne fournis pas le tag qui devrait entourer le tout. Pas d’inquiétude à avoir, Wicket le fait pour vous.
L’html résultant est en effet:

<script type="text/javascript"><!--/*--><![CDATA[/*><!--*/
alert('test working');

Si le template contenait plutôt du CSS, il faut juste utiliser un CssTemplate au lieu du JavaScriptTemplate.

Quelques info supplémentaires sont disponibles sur le wiki wicket: Including CSS resources.


Étiquettes : , , , ,

Playing with Wicket’s templates

janvier 28, 2010 3 commentaires

[Ce billet est également disponible en français.]

Wicket comes with some templating facilities. Nothing fancy, but still they’re quite handy, especially when integrating JavaScript components.

These functionalities aren’t much advertised and I would say even quite unknown. So, let’s dig in !

Basically, this templating is about some text containing variables, for example ${variable}, whose values are provided through Java code.

Let’s take a simple example, a template file named javascript.tpl containing :


Wicket is nice enough to provide an easy to access the templates as package resources, through the PackagedTextTemplate class :

public PackagedTextTemplate(final Class clazz, final String fileName)

For example :

PackagedTextTemplate jsTemplate = new PackagedTextTemplate(this.getClass(), "javascript.tpl");

Thus the template can be next to the .html page and the Java class using it, making the whole quite cohesive.

Providing the variables is done through a simple Map :

Map parameters = new HashMap();
parameters.put("variable","test working");

And then, you most probably want to include this template in some html. Wicket provides you different options :

  • as an header contribution :
    add(TextTemplateHeaderContributor.forJavaScript(jsTemplate, new  Model((Serializable) parameters)));
  • directly next to some element in the html file:
    Java side :

    Label myScript = new Label("myScript", new JavaScriptTemplate(jsTemplate).asString(parameters));

    Html side :

    <wicket:container wicket:id="myScript"></wicket:container>

You may have noticed that, in both cases, I didn’t provided the surrounding script tag (and the appropriate inner wrapping). Fear not, Wicket does it for you !
Indeed, the rendered html is :

<script type="text/javascript"><!--/*--><![CDATA[/*><!--*/
alert('test working');

If the template was about some CSS stuff, one would just need to wrap it using a CssTemplate instead of the JavaScriptTemplate.

A bit more info are available there Including CSS resources.


Étiquettes : , , , ,

Defining JavaScript variables…

septembre 3, 2009 Laisser un commentaire


Do you know the difference in JavaScript between these variables declarations :

– myVar = « foo »

– var myVarVar = « foo »

In fact, the first one will have an unlimited scope, and thus accessible from the outer world, whereas the second one will only be accessible at this level and below.

As such, this is why the line « $.fn.myFunction = function(){bla};  » is used to declare new function to the jQuery object.

Similarly, make sure you use « var » in front of your own JavaScript variables to avoid name collisions !

Hope it helps !


PS : funny how I’ve plenty of long posts in mind but not yet written (out of laziness/lack of time) while at the same time I’m eager to write small ones on stuff I’ve just discovered… May be I should consider twitter more closely !

PPS : the (french) source of this post :

Étiquettes : , ,

Book review : Learning JQuery

juillet 17, 2009 Laisser un commentaire

I recently read Learning JQuery, the version of 2007. I was reading it as a casual reader, just to get a better hand on JQuery.

My feeling about it is the following : it seems good at providing technical details but fails at « empowering » the reader and providing the big picture. I say « it seems » because I had difficulties to keep reading it, since I didn’t feel it attractive. So I’ve finished it through « scanning »… From an avid reader like me, that’s really an unusual move. Furthermore, I didn’t find advices/best practices about plugin usage and integration, which I was especially looking for.

Conclusion : grab it only if you’re an avid javascript developer willing to develop plugins and not afraid of connecting the chapters together yourself…

Ps : With further use of JQuery and hence of this book, I now realize that its index is very poor 😦

Étiquettes : , , ,
%d blogueurs aiment cette page :