Articles about philosophy of programming

WTF Logo


A great and clever article: Soft Coding. There are great comments too. My favorites: "I'm not going to spend my life writing my own little framework for every possible business rule change. If business rules change, then so should the code.", "This article really gets to the heart of 'art of coding', that is finding the right balance between:  saving time and money now (hard coding) vs saving time and money later (soft coding)", "Always program as if the person who will be maintaining your program is a violent psychopath that knows where you live."



Another article: Programming Sucks! Or At Least, It Ought To.

Java: Autentificarse en Google (llamada HTTPS POST) / Google Authentication (HTTPS POST call)

El siguiente es código en Java para hacer un llamada HTTPS POST. Lo probé en JavaSE 6:

--

Next is Java code to do HTTP POST call. I tested it using JavaSE 6:

        try {
            // Parece no ser necesario / It seems innecessary:
            // System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
            // java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            URL url = new URL("https://www.google.com/accounts/ClientLogin");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            HttpURLConnection.setFollowRedirects(true);
            String query = URLEncoder.encode("accountType", "UTF-8") + "=" + URLEncoder.encode("GOOGLE", "UTF-8");
            query += "&" + URLEncoder.encode("Email", "UTF-8") + "=" + URLEncoder.encode("EMAIL@gmail.com", "UTF-8");
            query += "&" + URLEncoder.encode("Passwd", "UTF-8") + "=" + URLEncoder.encode("PASSWORD", "UTF-8");
            query += "&" + URLEncoder.encode("service", "UTF-8") + "=" + URLEncoder.encode("xapi", "UTF-8");
            query += "&" + URLEncoder.encode("source", "UTF-8") + "=" + URLEncoder.encode("COMPANY-PRODUCT-VERSION", "UTF-8");
            //connection.setRequestProperty("Accept-Encoding","gzip");
            connection.setRequestProperty("Content-length", String.valueOf(query.length()));
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)");
            // open up the output stream of the connection
            DataOutputStream output = new DataOutputStream(connection.getOutputStream());
            // write out the data
            int queryLength = query.length();
            output.writeBytes(query);
            //output.close();
            System.out.println("Resp Code:" + connection.getResponseCode());
            System.out.println("Resp Message:" + connection.getResponseMessage());
            // get ready to read the response from the cgi script
            DataInputStream input = new DataInputStream(connection.getInputStream());
            // read in each character until end-of-stream is detected
            for (int c = input.read(); c != -1; c = input.read()) {
                System.out.print((char) c);
            }
            input.close();
        } catch (Exception e) {
            System.out.println("Something bad just happened.");
            System.out.println(e);
            e.printStackTrace();
        }

Referencia / References:

Java 5: cuando el autoboxing se comporta mal / Java 5: When autoboxing behaves bad



En Java 5, apareció una característica nueva: el autoboxing. Esta característica permite tratar los tipos primitivos de Java como objetos de la clase correspondiente. Es decir, que una variable de tipo int puede tratarse como un objeto de tipo Integer. La ventaja del autoboxing es que es automático: el programador no tiene que hacer nada especial para usarlo, pues el compilador lo hace por él.

Sin embargo, el programador debe seguir teniendo cuidado al programar, pues pueden surgir errores sutiles, y difíciles de encontrar. Para muestra un ejemplo:

Yo tenía un ArrayList en una clase, y un método que recibe como parámetro un evento. El método debía borrar el elemento i-ésimo de la lista. La implementación parecía sencilla, pues la clase ArrayList define un método remove(int i). Esto, junto con el ingenuo uso  de autoboxing, resultó en la siguiente implementación:
public MiClase {
ArrayList lista = // ...
// ...
public void borra(PropertyChangeEvent evt) {
Integer i = evt.getNewValue();
lista.remove(i);
}

Pero el código anterior tiene un error, que sólo se manifiesta en tiempo de ejecución. El método que en realidad se ejecuta es ArrayList.remove(Object o), lo cual evidentemente es erróneo, pues el ArrayList buscará el objeto Integer y no lo encontrará.

Por supuesto, este error también pone de manifiesto un desconocimiento de mi parte del API de Java :-)

--

Starting with Java 5, there is a new feature: autoboxing. It allows to convert between primitive types and classes automatically. So, a int variable can be used as an Integer object. Autoboxing is automatic and the programmer does not must do anything special to use it: the compiler does the magic.

However, the programmer still must be careful, because it could lead to sutil bugs -the hard to find kind one. This is an example:

I had an ArrayList in a class. I had also a method with an event parameter, and the method should erase the i-nth element of the list. The implementation seemed easy, as ArrayList implements the remove(int i) method. This, with the naive use of autoboxing, lead in the following implementation:
public MyClass {
ArrayList list = // ...
// ...
public void erase(PropertyChangeEvent evt) {
Integer i = evt.getNewValue();
lista.remove(i);
}

But the code above has a bug -which will reveal itself only at execution time. Actually, the method which is called is ArrayList .remove(Object o). The ArrayList will search for the Integer object, and it will not find it.

Of course, this bug also shows my ignorance about the Java API :-)