TechEd 2008

O TechEd está chegando aí (14 a 16/10) e contará com a presença de ninguém mais ninguém menos que Steve (Developers! Developers! Developers!) Balmer.

Os preparativos já estão a toda. Este ano estarei ministrando duas palestras:

  1. DEV301 – 300- 14/10/2008 14:00 – 15:15 – Sala 2 Melhores Práticas com a Linguagem C# 3.0
  2. WEB301 – 300 – 15/10/2008 09:15 – 10:30 – Sala 7 Internet Explorer 8 Para Desenvolvedores (junto com Miguel Ferreira)

Na palestra “Melhores Práticas com a Linguagem C# 3.0”, eu vou demonstrar os recursos que a linguagem ganhou na versão 3.0 e a melhor forma de usá-los. Também pretendo abordar os principais erros e gotchas que tenho encontrado por aí ao desenvolver o meu código e revisar código dos outros.

Na palestra “Internet Explorer 8 Para Desenvolvedores” eu e o Miguel Ferreira (PM do Windows) vamos mostrar o que o IE8 está trazendo de novidade para os desenvolvedores.

Além disto, estarei respondendo a perguntas no Ask The Experts. Para quem nunca participou de uma sessão destas, é uma chance de ter as suas dúvidas respondidas ali ao vivo e a cores. Imagina como um Fórum MSDN tête-à-tête. Imperdível!

Object creation with generics

Last week I was reviewing some code when I came across something that looked like.

class TypeTranslator<TOrigin, TDestination> {
    public TDestination Convert(TOrigin value) {
        Type typeOfTo = typeof(TDestination);
        TDestination to = (TDestination)typeOfTo.InvokeMember(null, BindingFlags.CreateInstance, null, null, null, CultureInfo.CurrentCulture);

        // goes on and copies the contents of each property from the TFrom object instance to the TTo object instance
        return to;
    }
}

 

The idea is to translate entity types to data transfer types. The class receives the origin and destination types upon instantiation and when Convert is called it creates a new instance of the destination type and populates its properties from the origin type enumerating through all its properties via reflection.

We all know that reflection is slow when compared to accessing the types and members directly, but the real problem on this code lays on the fact that it tries to instantiate a new object using a parameterless constructor, but there is no guarantee that the class has one.

It has all been working based on the convention assumed on the project that these types will all have a public parameterless constructor. What happens if a new developer comes in and unaware of the convention decides to create a constructor with parameters? The compiler seeing that there’s a constructor will not create the default parameterless constructor anymore. Since there’s nothing else checking it, it will only fail at runtime.

A runtime exception would be caught relatively early if they were using unit testing, but they aren’t using it, so it depends on trusting the developer to do the proper tests.

Well, I’m a developer, but I trust more on the compiler doing that job than on myself or whoever for that matter, so I proposed some changes:

class TypeTranslator<TOrigin, TDestination> where TDestination : new() {
    public TDestination Convert2(TOrigin value) {
        TDestination to = new TDestination();
        // goes on and copies the contents of each property from the TFrom object instance to the TTo object instance
        return to;
    }
}

This way, the compiler will guarantee that the type used has a parameterless constructor. Finding issues at compile time is much cheaper than at runtime.

Live Search – Se eu pudesse pelo menos experimentar…

Eu sou usuário do Google a vários anos.É realmente uma ferramenta de busca fantástica.

O Live Search deixava muito a desejar quando foi lançado. Eu ouvi dizer que melhorou muito, mas infelizemente já a alguns meses, eu não tinha como experimentar…

Tanto de casa quanto nos diversos projetos que passei nos últimos meses, o acesso à internet era provido pela Speedy. Coincidência ou não, em nenhum destes lugares o browser conseguia abrir a página de resultados de busca (http://search.live.com/results.aspx?q=mulher+pelada&form=QBRE, por exemplo).

Como usuário do Google, eu pensava… Ah.. Deixa pra lá, vou fazer a pesquisa no Google mesmo.

 

Hoje eu resolvi gastar um minutinhos nisso e consultei alguns camaradas daqui de São Paulo e de fora do estado e o resultado foi o seguinte:

Todo mundo que acessava via Speedy, não conseguia abrir o site.

O pessoal de outros estados conseguia.

Eu já desconfiava que fosse "sacanagem" do DNS da Telefônica, mas a experiência deixou isso mais claro.

Fazendo uma busca por "live search speedy telefônica dns" no Google eu acabei encontrando algumas páginas com pessoas descrevendo problemas parecidos finalmente uma relação de servidores DNS em http://www.abusar.org/dns.html

Configurei o meu DNS para o www.opendns.org (208.67.222.222 e 208.67.220.220) e Live Search voltou a funcionar.

Salvei a relação de servidores DNS aqui  na máquina para o caso de precisar novamente.

Tchau DNS da TelefoZica!

Keep it simple (and help to save the planet)

Today I came across a piece of code like the following.

Dim strSQL As New StringBuilder
strSQL.Append("SELECT ")
strSQL.Append(" ProductID, ")
strSQL.Append(" Name ")
strSQL.Append("FROM Production.Product")

Try
    cnnConn.Open()
    Dim cmd As New SqlCommand(strSQL.ToString, cnnConn)

When I encounter code I don’t agree with, I try to understand what made the developer code it that way.

Looking at this one I can only presume:

  1. He wanted to make his code more legible by separating the SQL Command to different lines.
  2. In doing that, he wanted to avoid string concatenation, because "string concatenation is performance wise evil"!

My answers to these points are:

  1. In this particular case, the code became harder to read than if it was stated in a single line.

    Dim strSQL As String = "SELECT ProductID, Name FROM Production.Product"

  2. That may be true in a lot of situations, but is not true in this particular one: concatenating small string constants, as the compiler is smart enough to generate one single string constant comprised of what we see in code as being multiple strings being concatenated

    Dim strSQL As String = _
    "SELECT " + _
        " ProductID, " + _
        " Name " + _
        "FROM Production.Product"

    Try
        cnnConn.Open()
        Dim cmd As New SqlCommand(strSQL, cnnConn)

    gets compiled to

    L_001f: ldstr "SELECT  ProductID,  Name FROM Production.Product"
    L_0024: stloc.1
    L_0025: nop
    L_0026: ldloc.2
    L_0027: callvirt instance void [System.Data]System.Data.SqlClient.SqlConnection::Open()
    L_002c: nop
    L_002d: ldloc.1
    L_002e: ldloc.2
    L_002f: newobj instance void [System.Data]System.Data.SqlClient.SqlCommand::.ctor(string, class [System.Data]System.Data.SqlClient.SqlConnection)

 

* Q: So what does this post has to do with saving the planet?

A: Keep it simple -> spend less processor cycles -> spend less energy -> … -> … ->…. Oooh… you get it!

Parlophone @ YouTube

A Parlophone, gravadora de bandas como Radiohead, Cold Play, Blur, The Verve, entre outros firmou parceria com o You Tube.

Já foram disponibilizados mais de 180 vídeo-clipes. Vários deles (se não todos, não fui atrás pra conferir) estão disponíveis em alta-resolução

Simplesmente imperdível!

http://www.youtube.com/parlophone

 

Growing software keeping things simple

Back in year 2000 I was running my own software development company and had a small kind of ERP system targeted at small companies.

Reading about all the advantages of interfaces such as the ability to switch implementations one for another at any time, I thought: "Wow! That’s amazing! I gotta do that!". So I went extracting the interfaces out of each class and making the classes refer to the interface. Soon I realized that in order to be really independent, I had also to change the methods and properties to point to the interfaces so I could change the object being passed to them.

Several weeks later I had it all done and working, but those were several weeks not adding new features. Only refactoring code at a time where we had no refactoring tools like today.

One could argue that I should have done interfaces from start and then I wouldn’t have had all that work. OK, I agree. The problem is that all that was new for me. Still, all the work would be compensated by the possibility of switching implementations whenever I needed!!!

The problem is that time never came! OK… To be fair, there were a couple of situations where I benefited from using interfaces. And that only became possible because I got a new insight, a new way of seeing the world – through interfaces. But for the most part, it was an overkill. When modifying a class, instead of having one place to change, now I had two!

It has been attributed to Albert Einstein that “Everything should be made as simple as possible, but no simpler

After so many years of developing software I came to appreciate simple designs.

I think about the ways the code might evolve in the future and instead of putting in things that pave the way to this predicted future, I tend to leave out the things that would otherwise make it more difficult to get there.

The reason for this is that the predicted future may never come to realization. So by putting in stuff now, I would eventually be throwing resources away. Resources that may be needed for something else.

It gets even worse when – driven by real needs – you find yourself having to accommodate changes that go in another direction that eventually are incompatible with what was initially predicted.

All of this has already been explained by people much better with words than I am. Take a look at YAGNI, KISS and DRY.

The bottom line is: Grow you software simple. Only add complexity when really needed. Even then, try to keep it as simple as possible, but no simpler. 🙂

Download gratuito de música – Legalizado e com remuneração do artista

Na semana passada eu descobri o Álbum Virtual da Trama.

Eles estão com uma idéia bem legal que é a de todo mês eles definem um orçamento e rateam a grana para os artistas que estão no site baseado no número de downloads.

Na semana passada haviam 3 bandas/artistas:

Cansei de Ser Sexy – Bem legalzinho

Tom Zé – Pura viagem. Provavelmente não escutarei novamente

Macaco Bong – Ainda não escutei.

Os álbuns ficam disponíveis por tempo limitado, então é bom estar checando o site de tempos em tempos para ver o que aparece de novo por lá.

Tem um videozinho lá no YouTube falando do projeto:

Preparing for Beta Exam 70-660: TS: Windows® Internals

Microsoft Advanced Windows Debugging and Troubleshooting team disclosed the exam preparation information for 70-660 (71-660 while in beta).

You’ll find what you need to know at: http://blogs.msdn.com/ntdebugging/pages/exam-preparation-information-for-exam-71-660.aspx

Since there currently is no prep material, I’ll recommend some books that I think will help prepare those who might want to take this exam.

First and foremost is Mark Russinovich’s Windows Internals currently in the 4th Edition. The 5th edition should be released later this year.

 

These books will give you the fundamentals of Windows internals.

For get a developer’s perspective on Windows internals reach out to Jeffrey Richter’s Windows via C/C++.

To get insight into debugging take a loot at John Robbin’s Debugging Applications for Microsoft .NET and Microsoft Windows :

  

I’ve read a few chapters from it – mostly the managed code debugging ones, but there’s a lot of information on native debugging.

Although I haven’t read Advanced Windows Debugging, is has been highly recommended, so I’ll list it here too.

That is a lot of stuff to read and study and it sure is not an exhaustive list. For just one exam! But what did you expected from an exam that caters:

     "Candidates for this exam are typically in the upper echelon of the technical staff at their companies."

So get prepared and good luck!