Posts Tagged programming

Are dynamic languages just a temporary workaround?

This can unleash so much hate mail, but here it goes, my inbox is ready!

Are dynamic languages just a temporary workaround? I’m not sure! I’m switching between the two types of languages all the time: Java, Python, C#, JavaScript. I’ll try to make the long story short.

Statically typed languages, like Java and C#, are nice because when you do

blah.bleh()

you know that blah’s class has a bleh method, at compile time. But better than that, when you typed “blah.” you get a list of methods, and you already know whether there’s a bleh method or not, and if you typed bleh and it doesn’t exist, the IDE lets you know, no need to wait for the compiler. Also you can do very deterministic refactoring, renaming all “bleh” for “bluh” for example.

Statically typed languages are not nice because they are very verbose and require a lot of boilerplate (if you’ve used Haskell, just bear with me for now please), so you end up with things like:

List[Car] cars = new List[Cars]();
foreach (Car car in cars) {
    car.Crash();
}

How many “cars” do you read there? And that’s a nice example. There are worse. So come dynamically typed languages and you can write:

cars = []
for car in cars:
    car.crash()

You have less cars, and less (no) lists. That means you are more productive. You start chunking out code faster without having to stop and think “What type of object will this or that method return?”. But crash() can crash your application instead of just the car because you can’t know if it exists until run-time. That might be OK or not, testing and whatnot.

Then comes C# 3.0 where you can do:

var cars = new List[Car]();
foreach (var car in cars) {
    car.crash();
}

And you can see that syntactically it got closer to Python, which is what gives you the productivity. Don’t know the type? type “var”. But semantically, it’s still statically typed, like the previous statically typed example. You know that car is going to be of some class that has a crash method. You can actually know car’s class at compile time, no need to run it.

That’s called type inference. You don’t have to specify the type where the compiler is capable of inferring it for you. C# type inference system is still very limited (but better than Java’s). Let’s see an example in another language

cars = []
map crash cars

That means, create a list called cars, call the function crash on each car. Would you say that that is a statically typed language? or a dynamic one? I’d say it is dynamic, but it is static. Very static. It’s Haskell. Haskell’s compiler will infer all the types for you. It’s amazing, you’ll write code as robust as with C#, but as terse as Python’s (Monads will then kill your productivity, but that’s another story).

In Python 3 you can define types for arguments. They are mostly useless, but it’s an interesting direction. I think the best it can do is that when a program crashes it’ll tell you: “function blah expected an int, but got a float, not sure if that was the problem, but you might want to look into that”.

Now, my question is, are dynamically typed languages just a temporary workaround? As our compilers get better, our computers faster, will statically typed languages keep giving us as many or more reassurances about our code and utilities while at the same time they become as simple and terse as dynamically typed languages? Or will dynamically typed languages start to gain types and over time be more static without the programmers that use them ever noticing?

My question is, will we in the future, 50 or 100 years, look back and said “Dynamically typed languages where a temporary workaround to statically languages being painful to use when human beings and their toy computers were so primitive?” in the same way we can say today that “non-lexical scope was a limitation we had and have due to the limitations of computer hardware 30 years ago”.

Reviewed by Daniel Magliola. Thank you!

, , , , , , , , , ,

10 Comments

Formating strings in C#, like in Python

I like Python’s way to format strings because you can use it everywhere, it’s part of the strings. You can do

print("Welcome %s!" % user.name)

as you can do

Console.Writeln("Welcome {0}!", user.Name)

But then in Python you can also do

randomMethodThatTakesAString("Welcome %s!" % user.name)

In C# it gets trickier, because the call to Console.Writeln takes extra arguments for the string arguments, while RandomMethodThatTakesAString doesn’t. It just takes a string. So the only way to go is

RandomMethodThatTakesAString(String.Format("Welcome {0}!", user.Name))

which is ugly.

Thanfully C# 3.0 has extension methods, so I quickly wrote this method:

blah blah

and now I can write:

RandomMethodThatTakesAString("Welcome {0}".Args(user.Name))

which is more verbose that Python’s version, but equally nice in my eyes.

If you can understand why allowing the language to be extendable in one aspect was a win here, then you can understand why so many, me included, love Lisp that is extendable in every possible way.

Reviewed by Daniel Magliola. Thank you!

Update 2009-09-17: For those complaining that I didn’t show how I did it, here is the Args method:

public static class StringExtensions {
    public static string Args(this string str, params object[] args) {
        return String.Format(str, args);
    }
}

, , , , , , ,

No Comments

Complexity of writing software

Broken bridge, picture by Ghost V

There seems to be a lot of discussion about software complexity, and although I think many people are talking about different stuff, here’s my take on it. We often compare writing software with other professional disciplines, like civil engineering and medicine, which allows us to pick at possible futures of writing software.

I believe writing software is hard, very hard, extremely hard. Probably one of the hardest thing to do. Any non trivial piece of code has an amazing amount of moving pieces. I bet the average software project is more complex than a car or a bridge. But how do we reconcile that with the fact that we have children programming and not children building cars or bridges?

Well, we do have children building cars and bridges, just that they are toy cars and toy bridges. Toy cars and bridges are very different from real cars and bridges. Toy software is not much different from real software. The path for going from toy to real in software, unlike in medicine, motor and civil engineering, is smooth. You don’t jump from building toy software into building real software, you just build better and bigger software until it’s real or professional.

That makes sense because software is abstract. Software is like ideas. There’s no jump between having toy ideas and having real ideas. If you don’t buy it, let’s do the analogy with math. There’s no jump between doing toy math and real math. You learn more math, more operations, more tools, but the sums and multiplication you learned when you were 5 years old are the same you use in civil engineering. There’s no toy sums vs real sums.

At some point in time, ages ago, math was primitive. A 12 year old could discover something new in math. We are at that period in the world of software writing. We are young and there’s not a lot out there. That’s why even though it’s extremely complex, a kid can still do something meaningful.

There’s something special about software. Even though it is abstract like math, it has a concrete impact, like civil engineering. So the 12 year old kid can do something new and it’s not just a piece of paper with a couple of numbers on it. It’s a real usable thing that other people can start, well, using. And that’s why I believe programming is so wonderful.

There’s another very important property of software that makes it so complex and still approachable. Imagine the world ages ago when 12 years old where doing math discoveries. Probably 99.9% were wrong in what they discovered as 99.9% of the software written by kids is wrong in the way it has bugs. But buggy software is still software and it’s still usable. Buggy math is wrong and should be discarded, buggy bridges kill people. Buggy software is a nuisance, but usable.

There’s some code in which only very smart and professional people put their hands on. Code written at NASA has something like 10 times more code to test it. Code put in a machine that can kill people, like a robot at a factory or a radiotherapy machine is written quite differently than the latest web toy or even the operating system you are using (last time I checked my analytics, nobody was using QNX to access this web site).

Rocket picture by SWP Moblog

As software becomes more important in our lives, more of it has to be written rigorously. You can accept the latest web toy to crash, but you cannot accept your phone to crash. And then, the latest web toy becomes very important, like Twitter, and you cannot accept it to crash. The way code is written at NASA is more similar to the way a civil engineer makes a bridge: accounting for all possible variables.

It’s a real possibility that in 20 or 30 years all code will have to be written very rigorously. That means that you probably won’t be able to get a job working as a programmer in many, many places unless you have a proper degree, certification and license. I know it sounds crazy, but extrapolate about who was building bridges ages ago (anybody) and who are building them now (civil engineers) to who is building software now and who is going to be building software tomorrow.

For me, that sounds very depressing. I like the chaos of innovation that software is today. I probably couldn’t live in a rigorous software environment. One aspect that I haven’t analyzed is that, unlike civil engineers, software programmers will most likely always be able to build software by themselves, put it out there and be out of the loop of rigorous working. Anyone can build a bridge in their back-yard and nobody will use it, because it doesn’t stand a chance of being useful. But the back-yard of a programmer is the Internet. The only question is whether people will use that crapy web toy built by a 12-year old 20 years from now. I honestly hope so because that will keep the thriving environment of chaotic innovation that programming is today.

Reviewed by Daniel Magliola. Thank you! Broken bridge picture by Ghost V, rocket picture by SWP Moblog.

, ,

No Comments

File input for forms in ASP.NET MVC

fileI’m not sure why ASP.NET MVC was shipped without a file input type for forms. Maybe it’ll come in MVC 2.0 or 3.0. Meanwhile, I created one. I spent two or three hours trying to figure out how to go from Object to IDictionary<String, Object> to follow the same ASP.NET MVC style where you have methods like:

TextBox(HtmlHelper, String, Object, IDictionary);
TextBox(HtmlHelper, String, Object, Object);

which are essentially the same. The last argument is a dictionary of extra HTML attributes, like style=”float: left;”. The good thing about accepting Object Is that you can call it this way:

Html.TextBox("email", new { style="float: left;" })

which is very handy for forms. The bad thing is that it is a pain in the ass to do that hocus pocus in C# using reflection. Thankfully ASP.NET MVC is open source. I downloaded the source and after 15 minutes I got it working nicely (and without manually using reflection). Use the source Luke!

In a recent episode of Hansel Minutes podcast someone argued what was the value of releasing the code of ASP.NET MVC at all. Well, this is the value. You help developers, you build a better developing community.

Without further ado, here’s the code:

public static class HtmlHelperExtensions {
   /// <summary>
   /// Returns a file input element by using the specified HTML helper and the name of the form field.
   /// </summary>
   /// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
   /// <param name="name">The name of the form field and the <see cref="member">System.Web.Mvc.ViewDataDictionary</see> key that is used to look up the validation errors.</param>
   /// <returns>An input element that has its type attribute set to "file".</returns>
   public static string FileBox(this HtmlHelper htmlHelper, string name) {
       return htmlHelper.FileBox(name, (object)null);
   }
 
    /// <summary>
    /// Returns a file input element by using the specified HTML helper, the name of the form field, and the HTML attributes.
    /// </summary>
    /// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
    /// <param name="name">The name of the form field and the <see cref="member">System.Web.Mvc.ViewDataDictionary</see> key that is used to look up the validation errors.</param>
    /// <param name="htmlAttributes">An object that contains the HTML attributes for the element. The attributes are retrieved through reflection by examining the properties of the object. The object is typically created by using object initializer syntax.</param>
    /// <returns>An input element that has its type attribute set to "file".</returns>
    public static string FileBox(this HtmlHelper htmlHelper, string name, object htmlAttributes) {
        return htmlHelper.FileBox(name, new RouteValueDictionary(htmlAttributes));
    }
 
    /// <summary>
    /// Returns a file input element by using the specified HTML helper, the name of the form field, and the HTML attributes.
    /// </summary>
    /// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
    /// <param name="name">The name of the form field and the <see cref="member">System.Web.Mvc.ViewDataDictionary</see> key that is used to look up the validation errors.</param>
    /// <param name="htmlAttributes">An object that contains the HTML attributes for the element. The attributes are retrieved through reflection by examining the properties of the object. The object is typically created by using object initializer syntax.</param>
    /// <returns>An input element that has its type attribute set to "file".</returns>
    public static string FileBox(this HtmlHelper htmlHelper, string name, IDictionary<String, Object> htmlAttributes) {
        var tagBuilder = new TagBuilder("input");
        tagBuilder.MergeAttributes(htmlAttributes);
        tagBuilder.MergeAttribute("type", "file", true);
        tagBuilder.MergeAttribute("name", name, true);
        tagBuilder.GenerateId(name);
 
        ModelState modelState;
        if (htmlHelper.ViewData.ModelState.TryGetValue(name, out modelState)) {
            if (modelState.Errors.Count > 0) {
                tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
            }
        }
 
        return tagBuilder.ToString(TagRenderMode.SelfClosing);
    }
}

Reviewed by Daniel Magliola. Thank you!

, , , , , , , , ,

6 Comments

Music for coding

Back to the FutureI’ve been looking for ages for the perfect music for coding. I’ve asked around and tried new age, Mozart, Bach, and other academic music. I’ve tried instrumental soothing music and instrumental electronic music. Nothing worked until I started to expand my original coding music: Indiana Jones and the Last Crusade.

Yes, I used to code to the music of Indiana Jones and the Last Crusade and I loved it. I started to try others and I’ve found I like coding to these albums:

I’m looking for more. There’s a clear pattern: instrumental and fast. It has to be of movies I’ve seen. When I listened repeatedly to Indiana Jones and the Last Crusade when I was a teenager I would recreate the whole movie in my head. I don’t do that anymore but the music still carries some subconscious meaning. I’ve tried with music of movies that I haven’t seen and it doesn’t work. And some don’t work and I don’t know why. These songs work as isolated songs, but not the whole album:

All by Vangelis of course. Star Wars music kind of works, but only some songs. I still have to sit down and select them (6 albums, lot of work). I remember other music like Apollo 13 also worked, but I don’t have it anymore.

What do I mean by work? It seems that music speeds me up. It makes me work faster, concentrate more and enjoy myself more. It makes me not want to stop, like watching a good movie. What do you listen to? Any other movies with great coding music?

Reviewed by Daniel Magliola. Thank you!

, , , ,

4 Comments

Converting the ASP.NET MVC project into OpenID

When you create an ASP.NET MVC project it comes with a controller called AccountController that manages logging in, logging out, registering, changing password and so on. Since usernames and passwords are dead I converted it into OpenID and I’m just pasting it here for everybody to use.

I’m using the DotNetOpenAuth library which you have to download, put in your project and refer. The difference between what I’m pasting and the example provided by DotNetOpenAuth is that I’m actually storing the user in the membership database, like the original AccountController.

My work is based on the on the blog post Adding OpenID to your web site in conjunction with ASP.NET Membership. I really had to put a couple of hours on top of that, so I consider it worth it to post it. Scott Hanselman also provides useful information for integrating OpenID. I’m using the jQuery OpenID plug-in but I’m not going to post my views. They are really trivial and left as an exercise to the reader.

I’m not using any extra tables, I’m storing the OpenID identifier (the URI) in the field for the username. This has the advantage of not requiring any other fields but the disadvantage that you can have only one identifier per user. There are some unfinished parts but since you are likely to customize them anyway, I don’t feel too guilty about not finishing yet. If you find a bug, please, let me know.

Read the rest of this entry »

, , , ,

5 Comments

How to create a Clojure application

This is one of those posts that I publish partly for myself. And partly so people can criticize my way, which is also for myself, and only incidentally for others to learn from it.

It seems Maven is popular in the Clojure world. Clojure itself uses it, Webjure uses and its demo application uses it as well, there’s a branch for Compojure that uses too. So after building all those components using Maven I’ve decided to use it myself when building Clojure applications.
Read the rest of this entry »

, , , , , ,

5 Comments

Printing emails in Django

When developing applications in Django, it may be nice to print emails instead of sending them. If you send them you have to be careful which addresses you use. Just being on the safe side and always using @example.{com,org,net} is not enough, you have to use an address you can actually retrieve emails for. And you have to configure your development environment to actually deliver mails. And then wait for the whole thing in each code-try iteration.

So, basing myself on the testing code, I’ve added this to settings.py and mails are now printed:

if DEBUG:
 from utils import BogusSMTPConnection
 from django.core import mail
 mail.SMTPConnection = BogusSMTPConnection

Of course you’ll also need the BogusSMTPConnection class, I’ve defined it as following:

from textwrap import wrap
class BogusSMTPConnection(object):
  """Instead of sending emails, print them to the console."""
 
  def __init__(*args, **kwargs):
    print("Initialized bogus SMTP connection")
 
  def open(self):
    print("Open bogus SMTP connection")
 
  def close(self):
    print("Close bogus SMTP connection")
 
  def send_messages(self, messages):
    print("Sending through bogus SMTP connection:")
    for message in messages:
      print("tFrom: %s" % message.from_email)
      print("tTo: %s" % ", ".join(message.to))
      print("tSubject: %s" % message.subject)
      print("t%s" % "nt".join(wrap(message.body)))
      print(messages)
      return len(messages)

And that’s it.

, , ,

3 Comments

Pylons or Django?

I am trying to decide whether to use Pylons or Django. Both are frameworks for building Python web applications, but with opposing philosophies.

Django tries to be everything. It comes with its own ORM, its own template engine, its own everything. That gives you a nice developing experience because everything fits together and because very nice applications can be built on top of all those components, like the admin tool, which is amazing. Read the rest of this entry »

, , , , ,

3 Comments

“Programming Languages: Application and Interpretation” now in paperback

Programming Languages: Application and Interpretation, the best book I’ve found on creating your own programming language is now available in paperback.

You can still get a free-of-cost copy of Programming Languages: Application and Interpretation at its original site. Actually, the book is now released under a Creative Common license, thank you Shriram!

This is, actually, old news. The book has been in paperback for quite a while, but I neglected to publish the post at that time. Today, a chat at the Esperanto meeting about Lulu (and how useful it is for Esperantists, that make books nobody wants to publish) reminded me about the post and I’m now publishing it.

,

No Comments