Feeds:
Posts
Comments

Recentemente venho dedicando boa parte do meu tempo na implementação da minha dissertação de mestrado. O meu trabalho consiste em modelar/desenvolver um middleware para redes de sensores sem fio. Apesar de ser um pythonista de carteirinha não consegui achar nenhuma plataforma de sensores baseadas em python então a minha escolha para o mestrado ficou com o SunSPOT. Para os desavisados, o SunSPOT trabalha com j2me. Dessa forma, precisei deixar o python de lado e voltar a programar em “Java”.

O middleware que venho implementando tem como principal requisito ser extremamente flexível. O objetivo é tornar o middleware bastante customizável, permitindo que os interessados possam modificá-lo. Além disso, outra característica dele é permitir a troca on-the-fly de alguns componentes visando atender os requisitos da aplicação. No intuito de solucionar o problema da troca de componentes uma das escolhas realizadas foi a de utilizar o padrão proxy. Quando um componente é solicitado como requisito de outro componente, o middleware entrega um proxy para a  implementação real, assim um componente sempre tem uma referência opaca ao componente. Através da utilização de proxies, o middleware pode realizar a troca de componentes ajustando apenas a referencia do proxy e todos os objetos que fazem uso dele terão a referência ao novo componente automaticamente. Assim, o uso do padrão ajuda a controlar as referências para um determinado componente que precisa ser trocado.

No entanto, um “problema” da abordagem adotada é que eu necessito implementar um novo proxy para cada interface dos componentes. O middleware em questão possui vários componentes que podem ser modificados de acordo com a escolha da aplicação, por exemplo, gestores de bateria, roteamento e etc. Nesse cenário, para cada componente que é permitido a troca, é necessário ao programador desenvolver pelo menos 3 classes/interfaces. A interface do componente, a implementação real e o proxy.

Olhando a definição do padrão contida na wikipedia isso fica mais claro ao leitor. Podemos ver a definição da interface, da implementação real e do proxy.

import java.util.*;

interface Image {
    public void displayImage();
}

class RealImage implements Image {
    private String filename;
    public RealImage(String filename) {
        this.filename = filename;
        loadImageFromDisk();
    }

    private void loadImageFromDisk() {
        System.out.println("Loading   " + filename);
    }

    public void displayImage() {
        System.out.println("Displaying " + filename);
    }
}

class ProxyImage implements Image {
    private String filename;
    private Image image;

    public ProxyImage(String filename) {
        this.filename = filename;
    }
    public void displayImage() {
        if (image == null)
        {
           image = new RealImage(filename);
        }
        image.displayImage();
    }
}

Agora imagine que você tenha umas 15 interfaces para fazer isso ? Começa a ficar tedioso. Esse é o tipo de código em que um proxy em si não é código duplicado mas sua lógica sim, eles fazem sempre a mesma coisa, possuem uma referência ao objeto real e delegam todos os seus métodos para o objeto. Atualmente as IDEs for Java já permitem gerar esse tipo de código automaticamente, o que me facilitou muito o trabalho. Inicialmente eu passei mais tempo pedindo ao netbeans para produzir código do que de fato programando. Porém, apesar da IDE gerar o código, a sua manutenção ainda fica por conta do programador. O que acontece quando um método novo entra na interface? Outro precisa ser renomeado? Mudança de parâmetros e etc. Todos nós sabemos, mudanças na interface afetam todas as implementações, nesse caso os proxies também.

Como programador Python, pensei desde o princípio: “esse é o tipo de código que pode ser feito de forma muito mais inteligente em Python do que me Java”. Em Python eu posso definir um único proxy para todas as interfaces. Ou seja, onde eu teria 15, 20 implementações eu passo a ter só uma. Isso é redução de código válida, não estamos falando de one-liners. Dessa forma é menos código para manter, um único ponto para consertar, refatorar, testar. Quanta mágica se precisa para definir esse proxy genérico em Python?

class Proxy(object):
    def __init__(self, obj):
        self.obj = obj
    def __getattr__(self, attr):
        return getattr(self.obj, attr)

Pronto, ai está nosso “incrível” “super” proxy. Isso teria me poupado mais de uma centena de linhas de código. Como esse código funciona? Simples, em python nós temos um método, denominado de __getattr__, o qual é invocado quando não é encontrado um determinado atributo na instância. O nosso Proxy implementa o __getattr__ na linha 4, e na 5 nós definimos que quando um atributo não for encontrado dentro do proxy deve ser procurado na referência que o mesmo detém. Pequeno e elegante. Outro detalhe é que não estamos amarrados a nenhuma interface e não precisamos escrever vários métodos apenas delegando tarefas.

Os programadores rails vão achar semelhante ao method_missing do ruby. A idéia é a mesma, porém funciona também para atributos. Não sei dizer se ruby possui isso para acesso a atributos também, acredito que sim.

Twitter

The hype around Twitter has been growing enormously on the last weeks. Here in Brazil, writers from all around the web are writing and blogging about it everywhere. Almost everyone has a little blue bird on their blog side bar saying “follow me”.

Many bloggers and news corp have been using Twitter to broadcast news, which is very similar to what RSS already does. Check it out:

The Twitter way

  1. Blogger writes a new post;
  2. Blogger tweets about it and adds a tyniurl link to the post;
  3. Followers receive and read the tweet;
  4. If it’s interesting, they acess it.

The RSS way

  1. Blogger writes a new post;
  2. The post is automatically included on the blog RSS, no twitting needed;
  3. Signer accesses his RSS reader and gets the whole post, no clicking needed.

As I see it, to share news, RSS is simpler. No twitting nor clicking around.

So, why use Twitter then?

First of all, I don’t. I have an account, but rarely visit it. But, after reading and discussing a lot about it, I found out 2 interesting ways, one of which led to the recent hype.

  • Real time search. Using Twitter, everyone has access to everyone’s opinions about everything. It’s a soup of ideas about any topic you might imagine, and whenever new topics arise, people twitt about them. So, using tools like twitter search, it’s possible to learn what people are saying right now about some interesting topic. It’s unprecedent. And that’s why Sergei Brin and Larry Page are saying Twitter is ahead of Google on it.
  • Sharing comments. RSS exists to share news. Besides Google Reader recent advances on comment and sharing, RSS was not meant for it. Twitter wasn’ t also, but it does the job very efficiently. Whenever someone shares a link on twitter, they add a comment to it. They show their opinions to the world. So, you subscribe to a blog when you notice that blogger posts interesting stuff and you should follow someons when you see that someone posts interesting links and opinions.

Thinking about it, using twitter to share comments and news could kill RSS because people would only read news shared by their friends whom they trust. But, where would their friends find the news? From other twitts? It’s easy to see that this recursion would lead either to a news corp or blog twitt or to a RSS feed. So, the initial “sharers” will have to find the news somewhere and, as said, the best way is through rss.

So, calm down, RSS won’t die.

RSS

Mozilla Labs Bespin

A couple weeks ago, Magnun and I were trying to implement a new feature for CairoPlot 2.0, which will be called Series. At the time, we decided to create a draft of what we were doing before actually coding and versioning it.

Both of us were stunned to find that an online colaborative programming ide didn’t exist. So we opted for Google Docs which filled the gap but not without some problems (as no syntax highlight).

Today, Magnun just told me about the Mozilla Labs Bespin which aims to be exactly what I said before: an online colaborative programming ide right inside your browser. Check out the project link to see what has already been done.

I do hope these guys keep going with this, the interface looks great and their idea of reinventing the wheel (as they did for the scrollbars and text input areas) is not bad as they do it for great optimization.

Code Complete 2

Yeah, I finally gave up and decided to follow StackOverFlow users and Jeff Atwood advices and started to read Code Complete 2.

From the very first chapter, I’m starting to get why so much people love this book:

Software construction is the central activity in software development; construction is the only activity that’s guaranteed to happen on every project.

And yes, it’s true.

In the final analysis, your understanding of how to do construction determines how good a programmer you are, and that’s the subject of the rest of the book.

And this last one must be too as *SO* many people recommend this book.

What happens when a software enterpreneur and an offshore oil extractor come together?

Roger Green (the software enterpreneur) and David Cook (the offshore oil extractor) came together and decided to board the 600 best software engineers around the world to live on a boat 3 miles away from the US pacific coast. Right outside imigration range.

These guys will work 4 months and take 2 of vacations, which leads up to a pretty nice scenario of working just 2/3 of the year!

For more information, take a look at A plan to offshore . . . just 3 miles out or just go to the official page of the project.

Stack Overflow

Stack Overflow

One day, Jeff Atwood and Joel Spolsky decided to help the programming community. Along the way, other guys joined them (Jarrod Dixon, Geoff Dalgas, Jeremy Kratz and Brent Ozar) and they came with the absolutely fantabulous Stack Overflow.

From their About page

Stack Overflow is a programming Q & A site that’s free. Free to ask questions, free to answer questions, free to read, free to index, built with plain old HTML, no fake rot13 text on the home page, no scammy google-cloaking tactics, no salespeople, no JavaScript windows dropping down in front of the answer asking for $12.95 to go away. You can register if you want to collect karma and win valuable flair that will appear next to your name, but otherwise, it’s just free. And fast. Very, very fast.

It’s definitely that: fast. For the last weeks, I’ve been browsing a lot through the hot questions tab and I barely found unanswered questions. It’s amazing how fast you can get an answer and, for what I’ve seen, it’s usually the best.

The voting up and down associated with comments mechanism is also great, as you can learn through the answerer but also by everyone else’s knowledge. And they also have a badge system which rewards you depending on your attitudes (actually, by now I only have 8 bronze badges..).

This thing has been growing so fast that even the most famous programmers are getting into it. Alan Kay, for instance, is already one of them.

So, they have lots and lots of information there, go check it out!

Ah, and don’t forget to check these:

Hi there everyone.
Sorry for the long delay on posts and updates, lots of stuff happening.

So, CairoPlot now has a Mailing List as suggested by Yang. It’s actually a GoogleGroup named CairoPlot. Subscription is now open for anyone who’d like to discuss, question or suggest new features.

So… Join now!

Follow

Get every new post delivered to your Inbox.