"…mais ce serait peut-être l'une des plus grandes opportunités manquées de notre époque si le logiciel libre ne libérait rien d'autre que du code…"

Archive for mars 2007

Oracle : quelques commandes intéressantes

Posted by Noam sur mars 20, 2007

Quelques commandes que j’utilise (avec sqldeveloper)  pour produire le code de mes classes métier:

– SELECT ‘public static readonly string ‘ || REPLACE(INITCAP(cname),’_’, ») || ‘ = « ‘ || cname || ‘ »;’ FROM col WHERE tname = ‘tablename’

– SELECT ‘, new CAttributTable ( ‘ || REPLACE(INITCAP(cname),’_’, ») || ‘ )’ FROM col WHERE tname = ‘tablename’

– SELECT ‘public string Value’ || REPLACE(INITCAP(cname),’_’, ») || ‘ { get { return CUtilConversion.ToString(DataValue,’ || REPLACE(INITCAP(cname),’_’, ») || ‘); }}’ FROM col WHERE tname = ‘tablename’

– SELECT ‘MyValue +=  » ‘ || REPLACE(INITCAP(cname),’_’, ») || ‘= » + CUtilConversion.ValueSQL(Value’ || REPLACE(INITCAP(cname),’_’, ») || ‘) + « \n »;’ FROM col WHERE tname = ‘tablename’

Posted in active record, Architecture logicielle, Oracle | Leave a Comment »

Vidéo: Design patterns in Python

Posted by Noam sur mars 17, 2007

Vidéo: http://video.google.com/videoplay?docid=-3035093035748181693&q=user%3A%22Google+engEDU%22&hl=fr

Design Patterns must be studied in the context on the language in which they’ll get implemented (the Gang of Four made that point very strongly in their book, though almost everybody else seems not to have noticed:-). This talk explores several categories of classic « elementary » DPs in a Python context — Creational, Masquerading, Adaptation, and Template.

Posted in vidéo | Leave a Comment »

Java5, annotations

Posted by Noam sur mars 17, 2007

Java5

-GUICE: http://google-code-updates.blogspot.com/2007/03/guice-googles-internal-java-dependency.html

Google has been using a blazingly fast, innovative, Java 5-based dependency injection framework in mission critical applications for quite some time.

The project is lead by Bob Lee, and we are pleased to say that we have released it to the community as open source software.

Guice wholly embraces annotations and generics, thereby enabling you to wire together and test objects with less effort than ever before. Annotations finally free you from error-prone, refactoring-adverse string identifiers.

Guice injects constructors, fields and methods (any methods with any number of arguments, not just setters). Guice includes advanced features such as custom scopes, circular dependencies, static member injection, Spring integration, and AOP Alliance method interception, most of which you can ignore until you need it.

Guice already has a community around it, and already powers Struts 2’s plugin architecture.

We asked Bob Lee a few questions about the project:

Why was Guice created?

We created Guice hoping to write less code and break up a multi-million line app. We looked at existing solutions, but we saw a lot of doors opened by the new Java 5 features. When I started from scratch I followed a use case driven approach and built a real application. As I wrote I was constantly asking myself « how do I really want to be writing this? ».

I value pragmatism and followed Josh Bloch’s API design advice, especially, « when in doubt, leave it out. »

Finally, we strove most of all for maintainability. Can a new programmer sit down at a million line code base and maintain it? We think type safety is a huge factor here.

Who should use Guice?

Anyone writing Java code. We see Guice as a lighter weight alternative to the factory pattern.

More information:

Labels: , ,

Posted in design pattern, java | Leave a Comment »

Tools for Web testing, Web recording/playback, nose unittest extensions, and code coverage.

Posted by Noam sur mars 17, 2007

Sources

Other web testing resources:

Introduction

Author: Titus Brown

 

Contents

At PyCon ’07, I gave a talk on testing tools in which I « performed » nine live demos of features from twill, scotch, pinocchio, and figleaf. These are tools for Web testing, Web recording/playback, nose unittest extensions, and code coverage.

This is the source code for that talk.

The Python code should work on any UNIX-like machine; I gave my talk with my MacBook, running Python 2.3.

Note that the only demo that didn’t work during the talk was the first one, in which I used ‘subprocess’ to start a CherryPy server. Since this is contraindicated IMO (I suggest using wsgi_intercept; see Demo 2) I was more or less happy that it failed. (It failed because I made a last minute adjustment to the command that ran app.py, and didn’t test it before the talk… ;(

 

Files

You can get the entire source code (including this text) at

http://darcs.idyll.org/~t/projects/pycon-07-talk-source-latest.tar.gz

The latest version of this README should always be accessible at

http://darcs.idyll.org/~t/projects/pycon-07-talk-source/README.html

 

Warning

This was billed as an « intermediate » talk at PyCon, and I jumped right into code rather than giving a detailed introduction. This document follows that strategy — so go look at the code and read what I have to say afterwards!

 

Feedback

I’m interested in your comments. Please either drop me an e-mail directly or go comment on the associated blog post.

 

Requirements

You will need twill 0.9b1 (the latest available through easy_install), nose 0.9.1 (the latest available through easy_install), scotch (latest), figleaf (latest), and pinocchio (latest). You will also need to have CherryPy 3.x and Django 0.95 installed.

You may need to adjust your PYTHONPATH to get everything working. Check out env.sh to see what I put in my path before running everything.

 

Demo 1: Testing CherryPy

Purpose: show how to use twill to test a (very simple!) CherryPy site.

twill is a simple Web scripting language that lets you automate Web browsing (and Web testing!) Here I’ll show you how to use it to run a few simple tests on a simple CherryPy site.

The CherryPy application under test is in cherrypy/app.py. You can check it out for yourself by running python app.py; this will set up a server on http://localhost:8080/.

The URLs to test are: http://localhost:8080/, which contains a form; http://localhost:8080/form/, which processes the form submit; and http://localhost:8080/page2/, which is just a simple « static » page.

The twill test script for this app is in cherrypy/simple-test.twill. All it does is go to the main page, confirm that it loaded successfully and contains the words « Type something », fills in the form with the string « python is great », and submits it. The final command verifies that the output is as expected.

If you wanted to run all of this stuff manually, you would type the following (in UNIX):

python app.py &twill-sh -u http://localhost:8080/ simple-test.twill

So, how do you do it with twill and nose?

Take a look at the unit test source code in cherrypy/demo1/tests.py. This is a nose test that you can run by typing

nosetests -w demo1/

from within the cherrypy/ subdirectory.

Try running it.

You should see a single ‘.’, indicating success:

.----------------------------------------------------------------------Ran 1 test in 2.069sOK

Now try

nosetests -w demo1/ -v

You should see

tests.test ... ok----------------------------------------------------------------------Ran 1 test in 2.069sOK

So yes, it all works!

Briefly, what is happening here is that:

  1. tests.py is discovered and imported by nose (because it has the magic ‘test’ in its name); then setup(), test(), and teardown() are run (in that order) because they are names understood by nose.
  2. setup executes the application app.py, capturing its stdout and stderr into a file-like object (which is accessible as pipe.stdout). setup has to wait a second for app.py to bind the port, and then sets the URL of the Web server appropriately.
  3. test then runs the twill script via twill.execute_file, passing it the initial URL to go to.
  4. teardown calls a special URL, exit, on the Web app; this causes the app to shut down (by raising SystemExit). It then waits for the app to exit.

A few notes:

  1. setup and teardown are each run once, before and after any test functions. If you added in another test function — e.g. test2 — it would have access to url and pipe and an established Web server.

  2. Note that url is not a hardcoded string in the test; it’s available as a global variable. This lets any function in this module (and any module that can import tests) adjust to a new URL easily.

  3. Also note that url is not hardcoded into the twill script, for the same reason. In fact, because this twill script doesn’t alter anything on the server (mainly because the server is incredibly dumb 😉 you could imagine using this twill script as a lifebeat detection for the site, too, i.e. to check if the site is minimally alive and processing Web stuff properly.

  4. What if the Web server is already running, or something else is running on the port?

  5. More generally, what happens when the Popen call goes awry? How do you debug it?

    (Answer: you’ve got to figure out how to get ahold of the stdout/stderr and print it out to the environment, which can be a bit ugly.)

  6. What happens if /exit doesn’t work, in teardown?

    (Answer: the unit tests hang.)

Notes 4-6 are the reasons why you should think about using the wsgi_intercept module (discussed in Demo 2) to test your Web apps.

 

Demo 2: Testing CherryPy without exec’ing a process

Purpose: demonstrate the use of wsgi_intercept.

The use of subprocess in Demo 1 was a big ugly problem: once you shell out to a command, doing good error handling is difficult, and you’re at the mercy of the environment. But you needed to do this to run the Web server, right?

Well, yes and no. If your goal was to test the entire Web stack — from your OS socket recv, through the CherryPy Web server, down to your application — then you really need to do things this way.

But that’s silly. In general, your unit and functional tests should be testing your code, not CherryPy and your OS; the time for testing that everything works together is later, during your staging and end-to-end testing phase(s). Generally speaking, though, your OS and Web server are not going to be simple things to test and you’re better off worrying about them separately from your code. So let’s focus on your code.

Back to the basic question: how do you test your app? Well, there’s a nifty new Python standard for Web app/server interaction called WSGI. WSGI lets you establish a nicely wrapped application object that you can serve in a bunch of ways. Conveniently, twill understands how to talk directly to WSGI apps. This is easier to show than it is to explain: take a look at cherrypy/demo2/tests.py. The two critical lines are in setup(),

wsgi_app = cherrypy.tree.mount(app.HelloWorld(), '/')twill.add_wsgi_intercept('localhost', 80, lambda: wsgi_app)

The first line asks CherryPy to convert your application into a WSGI application object, wsgi_app. The second line tells twill to talk directly to wsgi_app whenever a twill function asks for localhost:80.

Does it work?

Well, you can try it easily enough:

nosetests -w demo2/ -v

and you should see

tests.test ... ok----------------------------------------------------------------------Ran 1 test in 0.827sOK

So, yes, it does work!

Note that the test itself is the same, so you can actually use the test script simple-test.twill to do tests however you want — you just need to change the test fixtures (the setup and teardown code).

Note also that it’s quite a bit faster than demo1, because it doesn’t need to wait for the server to start up.

And, finally, it’s much less error prone. There’s really no way for any other process to interfere with the one running the test, and no network port is bound; wsgi_intercept completely shunts the networking code through to the WSGI app.

(For those of you who unwisely use your own Web testing frameworks, wsgi_intercept is a generic library that acts at the level of httplib, and it can work with every Python Web testing library known to mankind, or at least to me. See the wsgi_intercept page for more information.)

 

Demo 3: Basic code coverage analysis with figleaf

Purpose: demonstrate simple code-coverage analysis with figleaf.

Let’s move on to something else — code coverage analysis!

The basic idea behind code coverage analysis is to figure out what lines of code are (and more importantly aren’t) being executed under test. This can help you figure out what portions of your code need to be tested (because they’re not being tested at all).

figleaf does this by hooking into the CPython interpreter and recording which lines of code are executed. Then you can use figleaf’s utilities to do things like output an HTML page showing which lines were and weren’t executed.

Again, it’s easier to show than it is to explain, so read on!

First, start the app with figleaf coverage:

figleaf app.py

Now, run the twill script (in other window):

twill-sh -u http://localhost:8080/ simple-test.twill

Then CTRL-C out of the app.py Web server, and run

figleaf2html

This will create a directory html/; open html/app.py.html in a Web browser. You should see a bunch of green lines (indicating that these lines of code were executed) and two red lines (the code for page2 and exit). There’s your basic coverage analysis!

Note that class and function definitions are executed on import, which is why def page2(self): is green; it’s just the contents of the functions themselves that aren’t executed.

If you open html/index.html you’ll see a general summary of code files executed by the Python command you ran.

 

Demo 4: More interesting code coverage analysis with nose and figleafsections

Purpose: demonstrate the figleafsections plugin that’s part of pinocchio.

The figleafsections plugin to pinocchio lets you do a slightly more sophisticated kind of code analysis. Suppose you want to know which of your tests runs what lines of code? (This could be of interest for several reasons, but for now let’s just say « it’s neat », OK?)

For this demo, I’ve constructed a new pair of unit tests: take a look at cherrypy/demo3/tests.py. The first test function (test()) is identical to Demo 2, but now there’s a new test function — test2(). All that this function does is exercise the page2 code in the CherryPy app.

Now run the following commands in the cherrypy/ directory:

rm .figleafnosetests -v --with-figleafsections -w demo3annotate-sections ./app.py

This runs the tests with a nose plugin that keeps track of which tests are executing what sections of app.py, and then annotates app.py with the results. The annotated file is app.py.sections; take a look at it!

When you look at app.py.sections you should see something like this:

-- all coverage --| tests.test2| | tests.test

| | |        | #! /usr/bin/env python

| import cherrypy

|

| class HelloWorld(object):

|     def index(self):

+   |         return """<form method='POST' action='/form'>

|                   Type something: <input type='text' name='inp'>

|                   <input type='submit'>

|                   </form>"""

|     index.exposed = True

|

|     def form(self, inp=None, **kw):

+   |         return "You typed: \"%s\"" % (inp,)

|     form.exposed = True

|

|     def page2(self):

+     |         return "This is page2."

|     page2.exposed = True

|

|     def exit(self):

|         raise SystemExit

|     exit.exposed = True

|

| if __name__ == '__main__':

|     cherrypy.quickstart(HelloWorld())

What this output shows is that tests.test executed the index() and form() functions, while tests.test2 executed the page2() function only — just as you know from having read cherrypy/demo3/tests.py. Neat, eh?

See my blog post on the subject for some more discussion of how this can be useful.

 

Demo 5: Writing a simple twill extension to do form « fuzz » testing

Purpose: show how easy it is to write twill extensions.

Since twill is written in Python, it’s very easy to extend with Python. All you need to do is write a Python module containing the function(s) that you want to use within twill, and then call extend_with <module>. From that point on, those functions will be accessible from within twill. (Note that extension functions need to take string arguments, because the twill mini-language only operates on strings.)

For example, take a look at cherrypy/demo4/randomform.py. This is a simple extension module that lets you fill in form text fields with random values; the function fuzzfill takes a form name, a min/max length for the values, and an optional alphabet from which to build the values. You can call it like this:

extend_with randomformfuzzfill <form> 5 15 [ <alphabet> ]

If you look at the randomform.py script, the only real trickiness in the script is where it uses the twill browser API to retrieve the form fields and fill them with text. Conveniently, this entire API is available to twill extension modules.

Let’s try running it! The twill script cherrypy/fuzz-test.twill is a simple script that takes the CherryPy HelloWorld application and fills in the main page form field with a random alphanumeric string. As in Demo 2, we can put this all together in a simple unit test framework; see cherrypy/demo4/tests.py for the actual code.

You can run the demo code in the usual way:

nosetests -w demo4/ -v

If you run it without output capture, you’ll even see the random text we inserted:

% nosetests -w demo4/ -v -stests.test ... 127.0.0.1 - - [15/Mar/2007:19:08:14] "GET / HTTP/1.1" 200 166 "" ""closing...

==> at http://localhost/

Imported extension module 'randomform'.

(at /Users/t/iorich-dev/talk-stuff/cherrypy/demo4/randomform.pyc)

127.0.0.1 - - [15/Mar/2007:19:08:14] "GET / HTTP/1.1

" 200 166 "" ""

closing...

==> at http://localhost/

fuzzfill: widget "inp" using value "0jX0vUXye0"

Note: submit is using submit button: name="None", value=""

127.0.0.1 - - [15/Mar/2007:19:08:14] "POST /form HTTP/1.1

" 200 23 "" ""

ok

closing...

You typed: "0jX0vUXye0"

[15/Mar/2007:19:08:14] ENGINE CherryPy shut down

----------------------------------------------------------------------

Ran 1 test in 0.617s

OK

(Look for the text after « You typed »…)

 

Demo 6: Django fixtures for twill/wsgi_intercept

Purpose: show how to use wsgi_intercept and twill to test a simple Django app.

OK, I’ve shown you how to write automated tests for CherryPy Web apps. Let’s try it out for Django, now!

Since I don’t actually know any Django, let’s just try the Django intro app, a simple poll site that lets users select choices in a poll. The admin interface is a bit tough to test with twill, because it uses JavaScript, but we can test the main poll site easily enough.

Take a look at django/demo/tests.py for some code.

The first function you should look at is actually the last function in the file: TestDjangoPollSite.test. This function goes to « /polls », clicks on the « pycon » choice in the poll, submits it, and verifies that « pycon » has received 1 vote. (Unlike the CherryPy demos, here we’re using the twill Python API, rather than the scripting language.)

Behind this fairly simple looking test function lies two layers of fixtures.

The TestDjangoPollSite.setup() function is run before the test() function, and it serves to reset the vote count in the database; it’s very much like a unittest fixture, in that it’s run prior to each test* function in TestDjangoPollSite. (If there were a teardown() function in the class, it would be run after each test* function.)

The tests.setup() and tests.teardown() serve the same purpose as their CherryPy analogs in Demo 2: setup() initializes Django and sets up the wsgi_intercept shunt mechanism so that twill can talk to the Django app directly through WSGI. In turn, teardown cleans up the WSGI shunt.

Demos 1/2 and Demo 6 collectively demonstrate (hah!) how easy it is to use twill to start testing your Django and CherryPy apps. Even the simple level of testing demonstrated here serves an important purpose: you can be sure that, at a minimum, your application is configured properly and handling basic HTTP traffic. (More complicated tests will depend on your application, of course.)

(Thanks to Mick for his post — I swiped his code!)

 

Demo 7: Recording and examining a Django session with scotch

Purpose: show how to use scotch to record a Django test.

(For this demo, you’re going to need an extra shell window, e.g. an xterm or another ssh session.)

Make sure you have scotch installed, and then run run-recording-proxy. This sets up an HTTP proxy server on port 8000 that records traffic into memory (and saves into a file when done). You should see

** scotch proxy server running on 127.0.0.1 port 8000 ...** RECORDING to filename 'recording.pickle'

OK, now, in another shell, go into django/mysite/ and run python manage.py runserver localhost:8001. This runs the simple Django polling application on port 8001. You should see

Validating models...0 errors found.Django version 0.95.1, using settings 'mysite.settings'Development server is running at http://localhost:8001/

Quit the server with CONTROL-C.

Now go to your Web browser and open the URL http://localhost:8001/polls/. You should see a page with a link containing the link text « what’s up? » This tells you that the Django app is running.

Set your Web browser’s HTTP proxy to ‘localhost’, ‘8000’. Make sure that your proxy settings forward ‘localhost’ (by default, Firefox does not send localhost requests through the proxy mechanism).

All right, now hit reload! If everything is working right, you should see the same « polls » page, but this time you’ll be going through the scotch proxy server. Check out the window in which you ran scotch — it should say something like

REQUEST ==> http://localhost:8001/polls/++ RESPONSE: 200 OK++ (77 bytes of content returned)++ (response is text/html; charset=utf-8)

(# 1)

If so, great! It’s all working! (If not, well… one of us did something wrong ;).

OK, now go back to your Web browser and click through the poll (select « what’s up? », and choose « pycon », and then hit « submit »).

You should see a bunch more output on the proxy screen, including something like this (after the form submit):

REQUEST ==> http://localhost:8001/polls/1/vote/(post form)choice:  "3"++ RESPONSE: 302 FOUND

++ (0 bytes of content returned)

++ (response is text/html; charset=utf-8)

(# 4)

REQUEST ==> http://localhost:8001/polls/1/results/

Already you can see that this is moderately useful for « watching » HTTP sessions, right? (It gets better!)

OK, now hit CTRL-C in the proxy server shell, to cancel. It should say something like « saved 5 records! » These records are saved into the file recording.pickle by default, and you can look at some of the files in the scotch distribution (especially those under the bin/ directory) for some simple ideas of what to do with them.

All right, so you’ve seen that you can record HTTP traffic. But what can you do with the recording?

 

Demo 8: Convert the Django session into a twill script

Purpose: use scotch to generate a twill script from the recording in Demo 7.

Well, one immediately useful thing you can do with the recording is generate a twill script from it! To do that, type

translate-recording-to-twill recording.pickle

in the proxy window. You should get the following output:

# record 0go http://localhost:8001/polls/# record 2#   referer = http://localhost:8001/polls/

go http://localhost:8001/polls/1/

# record 3

#   referer = http://localhost:8001/polls/1/

fv 1 choice '3'

submit

Don’t be shy — save this to a file and run it with twill-sh! It should work.

So that’s pretty convenient, right? It’s not a cure-all — generating tests from recording can get pretty ugly, and with scotch I don’t aim to provide a complete solution, but I do aim to provide you with something you can extend yourself. (There are lots of site-specific issues that make it likely that you’ll need to provide custom translation scripts that understand your URL structure — these aren’t terribly hard to write, but they are site specific.)

 

Demo 9: Replaying the Django session from the recording

Purpose: use scotch to play back the Web traffic directly and compare.

OK, and now for the last demo: the ultimate regression test!

Leave the Django site running (or start it up again) and, in the proxy window, type play-recorded-proxy recording.pickle. This literally replays the recorded session directly to the Django Web app and compares the actual output with the expected output.

You should see something like this:

==> http://localhost:8001/polls/ ...... 200 OK (identical response)==> http://localhost:8001/polls/1 ...

... 301 MOVED PERMANENTLY (identical response)

==> http://localhost:8001/polls/1/ ...

... 200 OK (identical response)

==> http://localhost:8001/polls/1/vote/ ...

... 302 FOUND (identical response)

==> http://localhost:8001/polls/1/results/ ...

... 200 OK

++ OUTPUT DIFFERS

OLD OUTPUT:

====

<h1>what's up?</h1><ul>

<li>the blue sky -- 0 votes</li>

<li>not much -- 0 votes</li>

<li>pycon -- 2 votes</li>

</ul>

====

NEW OUTPUT:

====

<h1>what's up?</h1>

<ul>

<li>the blue sky -- 0 votes</li>

<li>not much -- 0 votes</li>

<li>pycon -- 5 votes</li>

</ul>

====

What’s happening is clear: because we’re not resetting the database to a clean state, the vote counts are being incremented each time we run the recording — after all, in each recording we’re pushing the « submit » button after selecting « pycon ».

Anyway, this is a kind of neat regression test: does your Web site still return the same values it should? Note that it’s very fragile, of course: if your pages have date/time stamps, or other content that changes dynamically due to external conditions, you’re going to have write custom filter routines that ignore that in the comparisons. But it’s at least a neat concept.

(Again, I should note that this is neat, but it’s not clear to me how useful it is. scotch is very much a programmer’s toolkit at the moment, and I’m still feeling my way through its uses. I do have some other ideas that I will reveal by next year’s PyCon…)

 

Conclusions

I hope you enjoyed this romp through a bunch of different testing packages. I find them useful and interesting, and I hope you do, too.

Note that this stuff is my hobby, not my job, and so I tend to develop in response to other people’s requests and neat ideas. Send me suggestions!

Posted in Architecture logicielle, python, tests, Web Frameworks | 1 Comment »

Python et Ruby: une petite introduction

Posted by Noam sur mars 17, 2007

Source: http://www.indexel.net/1_6_4780__3_/4/51/1/Python_et_Ruby___deux_concurrents_serieux_pour_PHP.htm

Python et Ruby : deux concurrents sérieux pour PHP

Approche objet facile à appréhender, syntaxe épurée, code compact : Python et Ruby sont deux langages qui partagent beaucoup de qualités. Un engouement renforcé par l’émergence des frameworks Django et Ruby on Rails.

Voici deux langages dont on parle beaucoup depuis quelques mois, bien que leur naissance remonte à plus de dix ans. Ruby est en effet né en 1995 au Japon. Tandis que Python a vu le jour aux Pays-Bas en 1990 où il a d’abord eu une vocation système. Ils ont plusieurs points communs dont certains qu’ils partagent avec PHP. Tout d’abord, comme ce dernier, ce sont des langages de script, autrement dits interprétés, qui imposent donc un environnement d’exécution sur le serveur. D’autre part, même s’ils ont une vocation généraliste, ils sont particulièrement adaptés au développement d’applications web. Mais ils se différencient de PHP et de bien d’autres langages par une syntaxe particulièrement simple.

« Très expressive, celle de Python le fait ressembler au pseudo langage que l’on utilise pour décrire le plus succinctement possible des algorithmes, si bien qu’un programme est quatre à cinq fois plus court que son équivalent en Java », explique Tarek Ziadé (photo), architecte chez Emencia, éditeur d’un framework entièrement écrit en Python, dédié au développement de sites marchants modulaires et configurables. Pratiquement les mêmes qualificatifs sont employés par les inconditionnels de Ruby.

Une syntaxe épurée

« Un code Ruby est encore plus simple à lire et à écrire que du PHP, tant la syntaxe est épurée, notamment grâce aux points virgules facultatifs et à l’absence de caractères spéciaux. C’est presque du langage naturel ! », affirme Eric Daspet (photo), consultant formateur chez SQLI Institut. Selon lui, « Quinze lignes de code PHP peuvent ainsi être condensées en cinq lignes de Ruby ». Par quelle grâce une telle compacité est-elle possible ? « Par exemple, en Ruby, une itération sur un tableau peut être décrite en une seule ligne », affirme Richard Piacentini, fondateur de Nuxos Group, une SSLL spécialisée dans la réalisation de sites Web.

Ces qualités sont synonymes d’un apprentissage accéléré, d’une productivité accrue des développeurs, d’une amélioration de la qualité du code et d’une maintenance facilitée. Python et Ruby sont en outre fortement soutenus par la communauté open source et sont disponibles sous Linux, Windows et MacOS. Enfin, ils bénéficient d’un engouement supplémentaire depuis l’émergence récente de frameworks vraiment professionnels – Django (pour Python) et Ruby on Rails. « Ce dernier supporte particulièrement bien les technologies Web 2.0, notamment en générant à la volée le code Ajax », précise Eric Daspet.

En France, Python et Ruby sont éclipsés par PHP

Ruby et Python se différencient toutefois entre eux, au moins sur un point. En digne héritier de Smalltalk, Ruby a dès le départ été pensé pour la programmation orientée objet. « Il met en oeuvre cette notion de façon bien plus simple que C++ ou même Java », estime Richard Piacentini (photo). De son côté, Python se distingue par sa capacité à manipuler les données sans même avoir besoin de les typer. « De plus il est conçu pour s’interfacer facilement avec d’autres langages, ce qui permet d’utiliser des bibliothèques externes écrites par exemple en C++ ou Java », complète Tarek Ziadé, également séduit par son modèle objet qui, même s’il a été greffé sur un langage initialement procédural, offre une grande souplesse.

Ces deux langages percent de façon significative dans de nombreux pays, mais plus lentement en France, où la communauté PHP est particulièrement forte. « Ruby et Python sont en effet directement concurrents de PHP mais beaucoup moins de Java, qui reste mieux adapté à la réalisation d’applications complexes, avec des transactions distribuées », note Eric Daspet. En attendant que l’Hexagone rattrape son retard, de nombreux utilisateurs feront du Python comme monsieur Jourdain faisait de la prose. Ce langage est en effet intégré à la suite OpenOffice 2.0 dans laquelle il est le pendant des Macro VB de Microsoft Office.

Posted in python, ruby | Leave a Comment »

Critique de l’architecture ASP.NET

Posted by Noam sur mars 13, 2007

J’ai mis en évidence quelques points d’une étude réalisée par Guillaume Saint-Etienne (document original: http://docs.google.com/View?docid=dhp3ggmx_24p2k9h7)

Le document modifié: http://docs.google.com/Doc?id=dcc3chdz_3fbp8z6

ASP.Net fait-il du Model View Controler (nativement)?

La réponse est définitivement NON

http://codebetter.com/blogs/jeremy.miller/archive/2006/02/01/137457.aspx

Même si Microsoft a tenté d’affirmer le contraire pour céder à la mode des MVC et montrer que ASP.Net est super bien foutu.

Le problème avec ASP. Net est qu’il n’y a qu’un objet qui traite les demandes http, c’est l’objet PAGE.

C’est lui qui a le contrôle de tout, et donc il mélange le code dit de «contrôle», et le code qui pilote la «visualisation» des éléments en html.

Et bien souvent, on mélange aussi le code qui pilote le «Modèle» c’est à dire l’obtention des données directement depuis la base de données avec Ado.Net (c’est ce qu’on obtient lorsqu’on fait du WYSIWYG dans Visual Studio en choisissant les Sql Data Source et les glissant-déposant sur l’ihm).

Cet anti-modèle (ou anti–pattern) a été souvent pointé du doigt par les architectes et développeurs, car en plus de faire produire du code spaghetti (bien que orienté objet), il rend impossible les tests systématisés (automatisés).

Egalement, les bugs sont plus durs à corriger et plus nombreux, car on n’isole pas assez les responsabilités dans les lignes de code. Tout est mélangé dans le code-behind.

Et au final, on peut se demander si l’on a fait beaucoup de progrès depuis Asp ( sans .Net) ?

Bref, le modèle MVC apporte de réelles améliorations et il est préférable de le suivre dès lors qu’on écrit un site de plus d’une dizaine de pages et surtout un site où on aura beaucoup de feedback de la part des utilisateurs et beaucoup d’améliorations successives à apporter.

Autant dire que c’est indispensable quand on a un projet à la méthode Agile (type MSF, Scrum, Xtreme Programing …).

Il faut donc, pour faire du MVC avec ASP.Net écrire du code supplémentaire soi-même, ce qui n’est pas un travail négligeable.

Ou bien si l’on est un peu plus malin, utiliser un Framework qui le fait à notre place.

C’est le rôle du projet Monorail : http://www.castleproject.org/monorail/index.html

L’idée est de se dire : MVC c’est bien. Je veux en faire (pour tous les avantages cités, notamment la ‘testabilité’). Mais je veux choisir quel système va s’occuper de la Vue (c’est à dire le RENDU au format HTML ou un autre format similaire, tant qu’à faire).

En ASP.Net tel que nous le propose Microsoft , il y a peu d’alternatives aux WebForms pour choisir son moteur de rendu (sinon écrire des composants qui enchainent les ‘ Response.Write’ mais je ne connais personne de sérieux qui se soit lancé dans cette voie là).

Il faut alors chercher sur le web pour trouver des projets indépendants, beaucoup étant inspirés de ce qui se fait dans la communauté Java.

Monorail utilise ASP.Net comme base de fonctionnement. Il est programmé en tant que filtre ISAPI, invoqué par le ASP.Net Worker Process (apnet_wp.exe).

Monorail ressemble fortement à Rails en Java ( et Ruby on Rails) qui a une forte popularité chez les développeurs

Cela se voit en jetant un coup d’œil à leur API respectives :

http://api.rubyonrails.org/

http://www.castleproject.org/monorail/documentation/v1rc2/manual/mrtypedocs/index.html

Monorail propose d’utiliser ActiveRecords qui se base sur Nhibernate. Nhibernate se base quant à lui sur Ado.Net

 

On est loin d’Ado.Net mais toutes ces surcouches sont tout autant de lignes de codes que vous n’avez pas à écrire.

Car au final c’est très simple à utiliser et tout automatique.

Mais on peut tout à fait utiliser tout autre technique d’accès aux données.

 

Et si on a un plus gros projet, et/ou que l’on veut coller à une architecture solide, on aura tantôt fait d’utiliser comme vue un objet de la couche Applicative (Application Layer ou Service Layer comme décrite par Martin Fowler et al.)

Cf mon billet à ce sujet : http://www.dotnetguru2.org/gse/index.php?p=530&more=1&c=1&tb=1&pb=1

Cette couche permet un grand découplage et surtout une séparation de la responsabilité du code (Separation of Concern). Ces objets de la couche applicative sont spécialisés dans le traitement final et haut niveau (c’est à dire le plus prés de l’interface graphique et des actions de l’utilisateur).

Leur fonctionnement est quasi-procédural et n’exposent que des méthodes.

Par contre ces méthodes travaillent (en entrée et en sorties) avec les objets entités (ou data objects).

Il y a une isolation entre les 2. Dans ce type d’architecture les objets entités n’exposent que des propriétés.

Donc dans un modèle MVC/MVP le M de Modèle pourra être un objet «métier» ou Service qui par ses méthodes offrent des capacités métiers (incluant l’inévitable CRUD mais présenté en d’autres termes, en des termes complètement adaptés aux utilisations de haut niveau, c.a.d. IHM et services).

Ce M fera forcément référence a des objets entités qui structurent l’information (comme le fait si bien les objets générés par tout outil de mapping Objet/Relationnel).

 

 

Posted in Architecture logicielle, ASP.NET | Leave a Comment »

La FSF invite les constructeurs à aider le libre

Posted by Noam sur mars 6, 2007

La FSF invite les constructeurs à aider le libre
Par Vincent Hermann, rédaction de PC INpact
http://fr.news.yahoo.com/06032007/308/la-fsf-invite-les-constructeurs-aider-le-libre.html

La Free Software Foundation a récemment publié une page dédiée
http://www.fsf.org/resources/hw/how_hardware_vendors_can_help.html
(en anglais) à l’ouverture du matériel au monde du logiciel libre. Selon la
Fondation elle-même, il s’agit de détailler des méthodes pour les grands
constructeurs pour « travailler avec la communauté du logiciel libre en vue
d’établir une relation mutuellement bénéfique ».
La FSF indique donc cinq points principaux à travailler :
– Le développement de pilotes libres pour le matériel
– La vente de machines sans système d’exploitation préinstallé
– Le retrait de certains blocages dans les BIOS
– Le support de BIOS libres
– Le rejet des DRM Peter Brown, le directeur de la Fondation, explique : «
Avec l’utilisation grandissante des logiciels libres et le rejet de Vista,
les grands constructeurs tels que HP, Dell, Lenovo et Sun ont l’opportunité
et la responsabilité de mettre à disposition du marché du matériel adapté aux
utilisateurs de logiciels libres, matériel qui correspond aux requis éthiques
pour la liberté, la vie privée et la sécurité de l’utilisateur. Nous espérons
que cette page aidera à focaliser l’attention sur ce qui doit être fait dans
les mois à venir. »
Après la proposition par Greg Kroah-Hartman de développer des pilotes libres
pour les constructeurs qui en font la demande, la FSF enfonce donc le clou
avec un sujet récurrent. Si en France la vente liée est un sujet qui
préoccupe les utilisateurs, la récente interrogation de Dell concernant
l’ouverture à Linux a propulsé les rapports entre les constructeurs et le
monde du libre sous les projecteurs.
La communauté du libre se montre donc prête à travailler avec les sociétés
vendant du matériel. Quant aux réactions de ces dernières, il faudra
probablement quelques mois avant de voir quelque chose de concret, si tant
est que ces réactions aillent dans le sens de la FSF.

Posted in FSF, logiciel libre | Leave a Comment »

Design patterns (motifs de conception)

Posted by Noam sur mars 6, 2007

Sources: Extrait du GNU/Linux Magazine N°92 de mars 2007, le GOF1 de 1996.

Je connais les design patterns depuis octobre 1996. C’est en effet à cette date que j’ai acheté le célèbre livre GOF (Gang Of Four: Erich Gamma,Richard Helm, Ralph Johnson, John Vlissides) « Design patterns, catalogue de modèles de conception réutilisables » paru aux éditions « International Thomson Publishing France », Paris, 1996, ISBN 2-84180-054-7.

Les design patterns sont des descriptions de solutions de conception qui créent un vocabulaire pour les développeurs. A l’origine de l’émergence même de la notion même de patterns, on retrouve 2 développeurs smalltalk célèbres, K. Beck et W. Cunningham. Voir le site http://hillside.net/patterns/ .

Les design patterns sont très importants car ils constituent un socle de vocabulaire qui permet aux développeurs de communiquer plus rapidement. Le plus important dans un design pattern est son nom, son intention et la solution. Son nom crée le vocabulaire qui va permettre aux développeurs d’échanger et communiquer de manière plus efficace. Il est très important de comprendre, si vous lisez un livre sur les design patterns, que vous ne preniez pour graver dans le marbre l’implémentation proposée.

Les design pattern sont intéressants car ils permettent aux développeurs d’avoir accès à des solutions éculées, connues et validées par les experts. Un patterns n’est pas une astuce technique ou un hack spécifique à un petit problème spécifique, mais une solution souvent simple à un problème qui se répète. On dit qu’un pattern existe s’il est apparu 3 fois dans des applications ou frameworks différents.

Un brin d’histoire

Les design patterns et Smalltalk sont une longue histoire d’amour. En effet, Kent Beck le guru Smalltalk qui a inventé eXtreme Programming et remis à la mode les tests unitaire, a été un des premiers avec Ward Cunningham à créer un groupe de discussion autour des patterns: le Hillside group. Selon ses propres dires, Ralph Johnson, un des 4 auteurs du fameux livre « Design patterns » aussi appelé Gang Of Four (GOF) était arrivé aux premières réunions de travail avec tous les patterns écrits en Smalltalk.

Il est important de ne pas se soucier son on n’implémente pas un patterns dans son application favorite. Nous le répétons: savoir quand appliquer ou pas un pattern est plus important que l’appliquer. …La version 2 du GOF (en cours d’écriture, mars 2007) verra une certaine refonte dans les patterns représentés. Il existe d’autres livres sur les patterns comme la série « Pattern Languages of Program Design »

Voici personnellement les design patterns que j’ai utilisé:

  • Singleton: ce design pattern est utilisé pour gérer les ressources: on veut s’assurer qu’une seule instance de la ressource est utilisée.
  • Observateur: définit une interdépendance de type un à plusieurs, de façon telle que, quand un objet change d’éta, tous ceux qui en dépendent en soient notifiés et automatiquement mis à jour.

Je vais consacrer 2 billets à ces 2 modèles de conception.

Posted in Architecture logicielle, C++, design pattern, java, smalltalk | Leave a Comment »

Zope/Plone, Ruby on Rails, Turbogears, Django and J2EE.

Posted by Noam sur mars 6, 2007

http://video.google.com/videoplay?docid=6297126166376226181&q=oodt.jpl.nasa.gov
Better Web Application Framework
A practical comparison between Zope/Plone, Ruby on Rails, Turbogears, Django and J2EE.

Une vidéo pour comparer les frameworks Web suivants:

  • Zope/Plone
  • Ruby On Rails
  • Turbogears
  • Django
  • J2EE

Dommage que la vidéo ne soit pas de bonne qualité. On ne voit pas les exemples qui sont tapés dans les fenêtres d’édition de code. Le son par contre est bon.
Sans surprise J2EE « sucks ».

Posted in java, python, ruby | Leave a Comment »

Blogmarks du 26/2 au 3/3 2007

Posted by Noam sur mars 2, 2007

  • http://pipes.yahoo.com/ (Pipes is an interactive feed aggregator and manipulator. Using Pipes, you can create feeds that are more powerful, useful and relevant)
  • http://dabodev.com/pycon2007?3 (Dabo Desktop Application Framework PyCon 2007 was held on February 23-25, 2007, in Addison, Texas. One of the sessions given there was a 45-minute talk entitled Developing Desktop Applications with Dabo, given by Ed Leafe, and filmed by Paul McNett. The video of the session is available here; it has been broken into 6 segments, due to YouTube’s limit of 10 minutes per video)
  • http://www.artima.com/weblogs/viewpost.jsp?thread=196889 (New Python 3000 Video and Slides by Guido van Rossum February 26, 2007 Summary Video and powerpoint slides of my recent Python 3000 talks are now online. I gave two versions of a new talk on Python 3000 (a.k.a. Py3k or Python 3.0) recently. The first time, a preview, was on February 14, at Google in Mountain View. It is now up on Google Video)

Posted in python, web2.0 | Leave a Comment »