Jan 31

This post is my 2 cents contribution to the debate on persistance stack architecture. I try to write short post (the shorter it is…the understanding greater is), but this time —with such a topic— I can only fail on this point. So this post will be followed by other posts :-).

I will not start from scratch explanation on the different approachs, the wording and so on…you will find some links in this post that I find usefull and I do not want to be redundant with them. I would like to enlarge the scope of the persistance stack to higly customizable environement and also the various features required by an Entreprise Management Application (taht I will name EMA) relying on a persistance layer.

What are the different layers (required or not)

You will find here an excellent article on the different layers of a typical persistence stack and further…to the UI. The UI is key but I will not address this question in this post. You will notice the author talk about a Persistence Layer which is different from an Persistence Stack. I use the word “Persistance Stack” to express all the layers that are requiered to build an application that use a database without the UI. These layers are usually (from the upper level to the RDBMS middleware):

  • Service Layer
  • Domain Layer
  • Data modeling
  • Persistance Layer
  • RDBMS middleware 

About the interest to respect layering

It’s just about commion sense : by layering correctly you will decouple your code and allow easier replacement of components as there are inricated. Most of the time, developers are doing naturally as it give an impression of over complicated the code. The important point they have to though about that an Entreprise Software relying on database will grow and evolve (faster at the begining) and you will write at the end touthands lines of code. If the rules and delimitations are clear from the begining, you will avoid a real mess of large classes.

Now let see in details the aim of each layers. I will go from down to top to express clearly the boundaries of each layer (starting from top tempt to mix the layer and put the code/requirement at a higher level than it should).

Persistance layer

The persistance layer is juste about persistance…obvious but not always respected. Persisance is only about storing and retreiveing data, nothing else. You can use an ORM (Object Relational Mapping) framework as Hibernate or TopLink for example. It’s only bout storing, that means no validation, no business logic at all, and the objects should be limited to structures, no methods. There is no real interest to build it’s own persistance layer as most of the time your requirement are fulfilled by the most advanced frameworks. That does not means you should not take care in the choice of this framework as this layer is the key for the performances: having a poor framework (even a rich ones depending on how you will use them) will dramaticcaly impact performance by generating useless or not optimized RDBMS queries.

Most of the time these objects are named DAO objects or DAL objects (for Data Access Layer objects).

Tow extensions to EMA that may be include in this layer are rights and partitioning. Rights management is the ability to give read/write access to attributes of the DAL objects. The Partitioning is the ability to segregate the read/write access to DAL objects. These fucntionality have obviously a business aspect,e specially for the partitioning. But for performance reasons (espacially for partitioning which is usually implemented using a where statement), this might be implemented in this layer.

ORM..a myth or not? 

The different post, disucssions and articles I’ve read about persistance stack are highlighting the interest of doing OOP (Object Oriented Programing) especially in the domain layer. Most of the argument yield to the mandatoiness of using an ORM which is the key pivotal framework to step from a relational database to a obejct oriented coding space. This a myth to me and is only relevant for folks that love OOP and particularely love debate about the beauty of it.

ORM use have to be limited to what it is design for: just create DAO objects for upper layer. Some folks abuse of this because they are mixing it with the higher level layers which is strong mistake. I’ve looked at Hibernate and NHibernate (to simplify: NHibernate have the same capabilities than Hibernate v2, but in a .Net environment). As a framework it provides lots of different ways to operate with the RDBMS layer, but you usually use on 10% of them as you are doing some assements. IMHO, this is not a mistake to do so, if you take care that this assement will not have a strong impact on the other layers. You will never be able to take some decisions that have absolutely no impact, but you can mitigate this.

An example of assement is to chose the same type for keys: there is a real advantage to do it, but it will have an impact on the Domain Layer and the evolution of your application (if the type is long…evolve to GUID for example may be tricky if they are exposed and used in the other layers). On this specific point, a good practice is to never expose internal keys outside of the layer but to expose business keys in the Service and Domain layers. For each object, exposing 2 kind of business kay is useful: an international one, and a business one. The international one is a key that won’t varie from a language to another, that is usually a sequence of numbers, which is used by external programs to synchronize data for example. The business one is a key that is usually used by humans over business process as a social key for a employee for example, or a barcode for an asset.

Data Modeling

This layer is most of time mixed with the Domain Layer and Persistence layer, but it can be useful to detail its contract.

In my opinion, part of the contractrthis layer is the dual of the relationship aspect in RDBMS. I deed, you have to define the relationship between various objects in the persistance layer (as a purchase order have order lines for example), but you have to define some low level behaviour. Some of you could say that I start to introduce some business logic here…no, i don’t but you are right: we should not introduce business logic here yet. The behaviour I’m talking about are related to the impact on relationships and complex custom types during CRUD (Create Retrieve Update Delete) operations made by the persistance layer.

A complex custom type is a type that rely on more than one attribute of a DAO object. Here are 2 examples.

Currencies: Handling of currencies is not simple, you have to be able to do arithmetics operations on them, and convert them. Obviously a double type field is not enough, neither a string (when I say string, is a string having only one information, not a string containing an xml description of a currency object with multiple attributes). So in the data modeling you could declare that the currency attribute of the value object will be rely on a set of attributes (amount, currency symbol, reference value in $, date of reference convertion) of a DAL object.

Enumeration: Some enumerations fields may have these requirement. First: the user can add new values. Secondly: some values used by the business layers may not be removed. A typical example is the status of a purchase order. The aim is to present some choices to the end-users (all values already entered by other users for a status plus some predefined fixed values). For technical reasons you may store a predefined fixed value in an attribute and other values into another field, but you want your applciation not to be aware of this.

As you see these are low level behaviour. That the same for relationship: if an object of type A is linked to an (or a collection of) object B, B should be deleted if its parent (from a relationship perspective) A is deleted or B should be attached to another object of type A? Does it makes sense to have an object of type B without an association to an object of type A? All this behaviour have a business rational but this have to be implemented in this layer.

Regarding this last sentence, it really make sense to gather together as much as possible the configuration of almost all layers inside one location. In a metadata driven environement, this is absolutely not an issue to mix configuration of different layer inside a unique location (a file or a a folder)…more over, I would recommend it.

Where do I put business logic?

To continue here

Other interesting links
Segregation/Distinction between Service Layer and Domain Layer

Jan 08

Here is really great post on principals to write maintenable code. More over this can be extended to improve supportability of the products.

Most of the developers are doing development only! It does not sound like a problem for you…I thing we are at the exact barrier between real development and hobby work. I’m not that fan of Agil development as it does not work well if not apply correctly and with a minimum of knowledge, experience and willing to do it. Nevertheless, Agil methodology as the real advantage to melt the concerns and responsability of QA, dev, CM over the entire team. From what I’ve seen, usually, development task are only 20 to 40% of to whole process to implement new features (and I don’t take into account the maintenance, support and bug fixe after release). Do not use the fake argument that it depends on the environment (Language, Framework, QA automation rate…etc), it’s just wrong. I prefer by far having a developper that knows less about a language or a framework but concerned by CM, QA, comprehensiveness and maintenability of features/code than a rely strong developer that will force to use the last framework release that he knows and break build process…even if his coding skills are higher. To make it shorter: don’t care about improving efficiency about 10% on 20-40% of the process, but I care if it’s on 60%-80% of the process plus maintenance, evolution…etc.

A sentence from the article that are fiond terribly true: “there is an inflection point where a coder mindlessly spewing out code transforms into a thoughtful software craftsman capable of creating maintainable code. That inflection point happens the day a coder first stops, lifts his/her nose out of the coding window, and says to him/herself “where should this code go?”.
I’ve seen this many times and is named “Seperation of concerns”. That does not mean using Spring is mandatory do code correctly :-), but as soon as a developer start to think this way, he will improve maintenability, componentization, and avoid spagetty development with useless interdepedencies. We see new languages as Ruby, Python that are marketed as “less code to implement the same feature” than with other languges as Java and C#. I agree that simplicity is fondamental and less code also, but this should not lead to weird code that can’t be maintained: if seperation of concerns leads to 3 additional lines of code to do a back-and-forth between 2 layers…that’s good.

Dec 24

Dans un précédent billet j’ai parlé des vertues du typage et quand sans lui, il fallait avoir un bon nombre de tests pour éviter les regressions. Cette batterie de tests n’est —selon moi— pas suffisante, voires impossible a mettre en place suivant les situations. Dans le cas ou vous écrivez un framework par exemple, vous ne pouvez imposer des tests aux utilisateurs de votre framework afin de compenser tout changement d’API.

Les langages dynamiques sont par définition des languages avec un typage faible…voire inexistant. J’ai lu dans un billet sur RubyCLR, que l’intéret de tout typage tombait de par l’usage de Test Driven Development. C’est tout simplement faux et que c’est l’utilsation de TTD et langugae dynamique donnent cette impression.

Une grande partie des nouvelles technologies suivent le même schéma d’adoption. Dans un premier temps, la nouvelle technologie est adoptée par énormément d’utilisateur et une certaine euphorie accompagne cette adoption. A ce stade, les sociétés commence à se pencher dessus sans l’adopter vraiment ou alors de manière expérimentale. On voir alors tout un tas de détracteurs apparaitres qui par la meme occasion mettent en exèrgue certains défauts (faux mythe) et la technologie est alors quelque peu délaissée. Si elle ne disparait pas, elle va survivre et progressivement etre adoptée par plus en plus de personnes … y compris les sociétés.

La survie de la technologie dépend uniquement de sa vraie valeur intrinsèque. Je pense que les languages dynamiques sont au premier stade: beaucoup d’”early adopters” avec peu de vrai applications/framework l’utilsations ou alors en tant qu’outil. Ou voit alors quelquesfan annoncer l’inutilité du typage. C’est abhérent car le typage n’est pas uniquement un artéfact due à la faible abstaraction des premiers langagues: le typage défini un modèle, et le modèle est au centre de tout a partir du moment ou il faut développer un système/application complexe qui est appeller à évoluer. C’est à ce point fondamental que certaines méthodologies commencent par le modèle avant le développement lui même (MDA).

Je pense donc que pour l’instant les languages dynamiques offrent une rapidité de dévelopment inégalée bien utile aucx development d’outils internes, de test ou de prototypage…mais n’enlève rien au besoin fondamental de typage/contrat des entitées utilisées dans une application ou un système complexe afin qu’il puisse évoluer.

Dec 17

Voici un article très intéressant sur les anti-pattern en SOA.

Dec 12

Si on demande aux aficionados des langages sois-disant nobles comme le C# ou Java, ils diront que oui. Je partage en partie cet avis, mais il est tout a fait possible d’avoir les inconvénients du Javascript en Java ou C# voire AOP. Je ne tiens pas a lancer le vaste débat sur quel langage de programmation est le meilleur, car cela finit toujours par des discussions assez stériles, mais je tiens a parler d’un point en particulier: le typage. 

Il est vrai que le javascript n’est pas typé ce qui ne permet pas une détection des problème compile-time mais run-time…ce qui me pose tout de même un sérieux problème. Ce qui est étonnant, c’est de voir à quel point les nouveaux développements en langages typés tendent a essayer d’aller dans la même voie que le javascript. En effet, avec l’arrivée des AOP comme spring et les développements autour des WebServices avec des invocations dynamiques ou les WebServices qui sont eux même non typés…on arrive aux mêmes problèmes. Au final on obtient du code très fragile et difficiles a faire évolués sans une batterie de tests impressionnante.

Dec 03

De l’utilisation abusive de buzzword à leur intérêt voir l’utilisation qui en est faite, il y a en général un fossé indiscutable. Je prendrai pour exemple SOA et MDA.

Il est vrai que MDA est moins connu mais il n’en est pas moins pas utilisé à des fins de markéting sans vrai intérêt derrière. Pour SOA, il est clair que l’on est dans le domaine du concept que tout le monde met à sa sauce…voire même les clients eux-mêmes. SOA veut dire “Service Oriented Architecture”, qui n’est ni plus ni moins un concept pour définir une séparation claire entre implémentation et application. Les mauvaises langues diront que c’est ni plus ni moins que le concept de design pattern : Façade…je dois avouer que je ne leur donne pas tord!
Je parle dans cette article de SOA et MDA car le concept MDA (”Model Driven Architecture”) est en partie en recouvrement avec le SOA car le MDA est basé sur une description claire du modèle des applications afin de pouvoir les porter sur des implémentation différentes.
Revenons au SOA. Comme je l’ai dit, il requière une séparation entre application (objets métiers, workflow, …etc) et l’implémentation, le but étant de pouvoir faire ce comprendre des applications d’architecture différentes et qu’elles puissent interagir. Le fait qu’une application soit exposée en Web Service n’en fait pas de facto une application SOA, mais il est vrai que 90% du chemin a été parcouru car une architecture WebService se repose (dans 99% des cas) sur du SOAP (over HTTP) qui est —lui— un standard…donc le canal de communication est déjà en place et il ne reste plus qu’a exposer des objets qui sont indépendants de l’implémentation. Si par exemple l’application retourne des images dans un format propriétaire…perdu! Ou encore s’il faut faire un appel pour ouvrir une transaction, puis la fermer après l’appel…on est encore trop proche de l’implémentation.
Autre problème souvent sous-estimé: le versioning! Si les objets manipulés, ou les méthodes changes d’une version à une autre, l’interaction avec les autres applications devient un cauchemar alors que SOA intrinsèquement cherche a gommer ces problématiques. Bref n’est pas SOA qui veut, même si tout le monde prétend l’être afin de pouvoir placer ce buzzword dans leur plaquettes.
Le concept MDA est quand a lui moins un buzzword, mais a-t-il sa place dans une plaquette marketing (ce qui est souvent le cas). A mon avis c’est un terme qui ne doit pas sortir d’une R&D car il n’offre que peut d’avantages en tant que Client excepté le fait d’avoir une documentation claire et précise d’une ou plusieurs applications de son système d’information. Le principe est simple: la ou les applications sont défini dans un modèle qui va décrire les objets métiers, les worklows — bref, tout ce qui compose une application — indépendamment de l’implémentation (2 ou 3 tiers, J2EE ou .Net, …etc.). Ce concept est beaucoup plus pragmatique que SOA car il permet entre autre de simplifier les des migrations d’implémentation en assurant minimisant le risque de voir apparaître des bugs. Pour les applications particulièrement sensibles comme les applications financières c’est un atout majeur. Il permet aussi d’assurer des modifications substantielles dans les mêmes conditions. Là ou je trouve qu’il y a de l’abus, c’est que documentations technique exhaustive est tout à fait valable, or je n’ai jamais vu une documentation technique markétée MDA !!

Nov 29

L’export vers Excel est une fonctionnalité importante pour tout application Web particulièrement si elle stocke/manipule des donnée. En effet, Excel est un outils très apprécié des utilisateurs finaux pour faire de l’intégration basic avec une très forte flexibilité. Dans cette article je ne décrierai pas comment mettre en place une servlet.

Sous certaines conditions, on peut se reposer entièrement sur la fonction d’export d’IE:

  • Si votre application Web ne requière pas d’authentification,
  • Vous n’avez pas a supporter d’autres browser autres que IE,
  • Vous n’avez besoin d’exporter que les données présentes dans la page.

Si vous ne remplissez pas tous les critères ci-dessus, vous pouvez alors développer une servlet qui se chargera de retourner une réponse de type excel. Pour cela il faut faire une reset sur la réponse, positionner le type, quelques paramètres et enfin les données.

Le reset ce fait par:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
  …
  response.reset();

Attention, si vous faite seulement response.resetBuffer(), dans ce cas cela ne reset pas l’expiration.

Ensuite, il faut donner le type de donner qui va etre retourner. Il peut s’agire de:

  • csv (Comma Separated Value): les valeurs sont séparées par des virgules
  • application/vnd.ms-excel: les données peuvent être d’au moins 3 types
    • les valeurs sont séparées par de tabulations,
    • du xml contenant les valeurs mais aussi des infos de formatage.
    • un binaire contenant le contenu exacte du fichier excel (a noter que dans ce cas on peut utiliser “application/octet-stream”, en n’oubliant pas de donner l’extention “xls” au nom de fichier)

Dans l’exemple que je donne, j’utiliserais le format tabulé. Pour fournir le type il faut:

  response.setContentType(”application/vnd.ms-excel”);

Il faut ensuite spécifier le nom de fichier et optionnelement d’autres paramètres. Il est important d’utilise l’extention “xsl” pour Excel car IE est un peu sensible à ce niveau.

  response.addHeader(”Content-Disposition”, “inline;filename=myReport.xls”);

Si vous voulez que l’utilisateur ai le choix entre sauver ou ouvrir le fichier, il faut changer l’attachement en:

  response.addHeader(”Content-Disposition”, “attachement;filename=myReport.xls”);

Là où IE/Excel sortent un peu des standards, c’est que vous risquez d’avoir des problèmes de CodePage. On peut en théorie spécifier la CodePage mais il se trouve que Excel n’en tient pas compte, cela dépend de la code page de l’OS et de la langue d’Excel…et encore vous risquez d’avoir des problèmes avec le symbole € par exemple. Dans ce cas, il n’y a pas d’autre solution que de générer un flux/fichier au format Excel (je ne ferais un autre article à ce sujet).
Ensuite il faut compléter la réponse avec les données. Pour ce faire, utiliser le response.getWriter() ou response.getOutputStream(), et ajouter les titres des colonnes (optionnel) et les données :

  writer.println(”col1\tcol2\tcol3\t”);
  writer.println(”val11\t val12\tval1\t”);
  writer.println(”val21\t val22\t val23\t”);
  writer.println(”val31\t val32\t val33\t”);

Cela donne au final :

import java.io.IOException;
import java.io.PrintWriter;     

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
  response.reset();
  response.setContentType(”application/vnd.ms-excel”);
  response.addHeader(”Content-Disposition”, “attachement;filename=myReport.xls”);
  PrintWriter writer = response.getWriter();
  writer.println(”col1\tcol2\tcol3\t”);
  writer.println(”val11\t val12\tval1\t”);
  writer.println(”val21\t val22\t val23\t”);
  writer.println(”val31\t val32\t val33\t”);
  return;
}

Nov 27

Lors d’une recheche sur Google, je suis tombé  sur ce tutoriel qui explique l’ouverture de nouvelles fenetres en JavaScript. Il n’y a rien de très magique, mais tout y est bien expliqué et est très utile pour les non spécialistes (ou débutants) en Javascripte.