First thoughts about Java

October 31, 2005

Something does not work. In my head, I mean. If you know me, you should be aware I’m pretty skeptical about Java. Let’s say that the first thing I do when I hear someone talking about Java is: Hey, there is Python out there, that is much better.

Still I heard much talking about Java Tiger, that is to say Java 5 (or 1.5, I still haven’t figured out which is the correct version number). There are *generics* (that is to say “templates” if you know C++). And autoboxing. These were the two single things I hated most in Java. Still I won’t talk about it here, there is plenty of places on the Internet when someone says that a strongly typed language that forces you to cast everytime you have to use a resizeable collection simply sucks.

I’ve quite changed my mind on this, but let’s go further. With generics it is not necessary anymore.
And with autoboxing you have not to change integer types back and forth from Integer objects.

So, I bought Core Java Volume I, written by Horstmann and Cornell. In fact I find it a well made book. It’s clear. And complete. Probably it’s not meant for a newbie. But I already new some Java and am quite skilled in C++ and Python, at least. I’m not new to theoretical object oriented programming (and for this I have to thank my university teachers) and have made many practical stuff, in very different environments, ranging from QT and Python or Cocoa to old C version GTK 1.

I thought I’d read it in some time, just to know what was happening out there in the Java world. Well. I was impressed. Java 1.5 is much better than Java 1.3. Its standard library is fabolous (something I knew even if not believed). And programming Java is not bad.

It has faults. And that is something that Core Java authors do not fear to stress. I find it really honest. It’s not a fan book. They like Java, but they are able to show its weaknesses.

This morning I bought Core Java Volume II. There are many things to learn… it’s really interesting. Even if I tend not to program cross platform anymore (thanks to Cocoa) I occasionally need some crossplatform environment.
QT 4 is giving me some troubles, and I think I could give Java a try… well, I won’t say more. ☺

And, oh… one of the first thing I chose to develop is a small plotting applet (which could be extended, if I have time to finish it and to make code readable). And I chose not to use 1.5 features, to let more people use it. Well… in fact a part from a pair of crappy hacks I had to do since it’s not as dynamic as I liked and I could not use generics, it is not that bad. Oh, the code I’m talking about is this:

public void stateChanged(ChangeEvent event){
    JComponent source = (JComponent)event.getSource();
    if(source.getClass() == spinner.getClass()){
        /* wow... heavycode! */
        newValue = ((Double)((JSpinner)source).getValue()).doubleValue();
        newValue *= factor;
        slider.setValue((int)newValue);
    } else if (source.getClass() == slider.getClass()){
        /* wow... heavycode! */
        newValue = ((JSlider)source).getValue();
        newValue /= factor;
        spinner.setValue(new Double(newValue));
    }
    firePropertyChangeEvent(
            new PropertyChangeEvent(this, "syncChange", new Double(0.), 
                    new Double(newValue) ));
}

Probably there is a javish cleaner solution. But in Python it would have been

def stateChanged(event):
    source = event.getSource()
    # source.factor is appended to each source before passing it
    # and can be > 1 or 
Advertisements

Python: messing with getattr

October 30, 2005

In this post we show how to use the getattr built-in, why and where it is worth using it. It is an introductory post and only a minimal python knowledge is requied.

In fact it could be interesting even to those who don’t know Python, since it shows some advantages of a dynamic programming language.

Introduction

I think that every python programmer sooner or later wrote some legacy
code that resembled Cmd module.
If you don’t know Cmd module you should take a look at it, even if it’s not necessary to understand this article.

At least sooner or later you may have had the necessity to call a method on an object depending on some user input/network input/gui input. Think about a line based server: a popserver or an smtp server, for example. The client send strings and the first part of the string is the “command” to be executed. Depending on which “command” the user chose, the proper function has to be called.

Let’s think about a POP server. It is a simple example, it has few commands and I’m quite familiar with it (since I’m writing one). Of course you can think about some “menu based” textual application

Anyway… there are several POP commands: RETR, TOP, USER, PASS, QUIT, DELE, etc.

Of course you could write something like (of course this would be in a “POPServer” object)

# pop commands are never longer than 4 characters
command = cline[:4]
if command=="USER":
    self.do_user(cline)
elif command=="PASS":
    self.do_pass(cline)
...
else:
    self.answer("-ERR Invalid command")

This would be a very unpythonic way to code. You can avoid a lot of useless typing using getattr built-in

getattr

getattr(object, “name”) returns the attribute named “name” from object object. This is simple and effective. Of course it follows usual python name resolution and

getattr(object, "name")(arg1, ..., argn)

if the same as

object.name(arg1, ..., argn)

(ellipses are not part of python code 😉 )
In fact if object has no “name” attribute, AttributeError is raised. And of course nobody would use the getattr form unless “name” is not a literal string but something known only at runtime (ok, in python nothing is known at compile time… but you got what I meant).

1+1=1.5

I think at this point everybody understood how we can use getattr to make above code more readable. The first thing we would write would be

command= cline[:4]
try:
    getattr(self, "do_" + command)(cline)
except AttributeError:
    self.answer("-ERR Invalid command")

This code is almost correct. It is quite secure (if you do not name methods that should not be called by the client with a name starting with “do_”) and works as expected, but has a major drawback.
If some code inside the “do_command” method raises an AttributeError (or an exception that is a subclass of AttributeError) this exception is caught even if it should not.

In fact if you do a lookup in a dictionary and you don’t find the key, you get a KeyError, subclass of AttributeError and it is caught, even if the server should have crashed. In fact debugging becomes a mess: you do have no informations on where the exceptions generates.

1+1=2: the solution

You could be tempted to use a hasattr before getattr instead of the try block. But remember Python philosophy about exceptions: EAFP (it’s easier to ask forgiveness than permission). That is to say, try to do what you want to do and if you were not allowed fix it.

In some other languages it is more common the LBYL approach (look before you leap/check before doing something if you were allowed): unfortunately it has some disadvantages both for readability and performance. Still in other languages, as I said, LBYL is the more common and “correct” way to proceed.

So the code becomes

command= cline[:4]
try:
    action = getattr(self, "do_" + command)
except AttributeError:
    self.answer("-ERR Invalid command")
else:
    action(cline)

An else clause is executed if there were no exceptions and is outside
the try block, so exceptions are free to propagate.

Many of the ideas in this post come from the reading of Python in a Nutshell chapter about exceptions. I think every python programmer should have that book on his desk.


BBEdit

October 30, 2005

BBEdit What BBEdit really excels in is WebDevelopement.
It can manage entire websites, live preview documents with WebKit, edit remote documents through FTP or SFTP.

Its glossaries are a powerful but easy to use tool that can be used (for example) to work with Latex and can substitute in many case autocompletion (in fact they are better).

In fact it is far more powerfull than dedicated WebDevelopement tools like DreamWeaver and GoLive, it produces cleaner code and if you are not specifically a web developer you can use it for almost everything.

You can also let it sugest you which tags/attributes you can insert, depending on where is your cursor; BBEdit can also be used to write CSS and has facilities for templating and for authomatically update websites.

Of course BBEdit is enterely AppleScriptable.

Read the rest of this entry »


About myself

October 26, 2005

It’s always quite embarrassing to introduce myself.
I’m a student of Mathematics and Computer
Science
in Parma, Italy. I have many interests:
Mathematics, Computer Science, Information Technology , Jazz and
Rock Music, Literature.

Read the rest of this entry »


I never thought

October 25, 2005

OK. I never thought I would have had interest for a blog. I always thought they were kind of useless. This is a reason why I came this late, years after blog’s mania broke out.

In fact when I realized blog could be a wonderful mean to share knowledge (technical knowledge and other not strictly personal kind of knowledge) I understood their success.

I thought blogs as places where everybody told his life.

My first objection was: who cares? There is people who cares of course, still it’s not for me. Not that I do think people will be interested in this blog, still it can be a usefull way to put down quickly some pieces of information that can be shared among people who know me.

That is the same function of my website, that also failed in this sense. I never had time to improve it nor add content as frequently as I wanted. I also began writing a blog software by myself.

The point was I had to do it in PHP since altervista guys support only that language and unfortunately I just can’t stand PHP. So I  accepted the idea of using an external blog. Anyway, this is another story.

This blog will contain english and italian posts, depending on the subject (tech post tend to be in english).