Category Archives: programming

Scala trivia of the day: Traits can extend classes

A lot of people seem to not know this. In particular 90% of use of self types I’ve seen appear to exist solely because people do not know this.

Observe the following interpreter session:

scala> class Foo;
defined class Foo

scala> class Bar;
defined class Bar

scala> trait Stuff extends Foo;
defined trait Stuff

scala> new Foo with Stuff;     
res0: Foo with Stuff = [email protected]

scala> new Bar with Stuff;
<console>:8: error: illegal inheritance; superclass Bar
 is not a subclass of the superclass Foo
 of the mixin trait Stuff
       new Bar with Stuff;
                    ^

You can basically view this as putting a constraint on the trait, saying that all classes that implement this trait must extend this superclass. This can be particularly useful for adding various sorts of behaviour to classes. e.g. traits which add behaviours to GUI components.

Thus ends our public service announcement.

This entry was posted in programming and tagged on by .

A workaround for misbehaving X citizens

Some programs (most notably amongst those I use firefox and pidgin) don’t work properly with shift-insert for pasting from the primary X Selection. If you’re like me and virtually live in the command line, this is a real pain in the ass. It became more of a pain in the ass recently because I’ve started using a graphics tablet instead of a mouse, so no longer have a middle click. I could no longer paste from IRC into firefox.

After some hacking around, I settled on the following solution. “xsel -o -p | xsel -i -b” dumps the primary X selection into the clipboard (xsel is a nice little application. You should probably have it installed). So I’ve bound this to a shortcut in xmonad and now can at the press of a magic key combination take the current selection and make it pasteable. Hurray.

This entry was posted in programming, Uncategorized and tagged on by .

From Objects to Agents

I’ve been at the first day of barcamp london 6 today. It’s been fantastic so far. Apparently I gave a talk today titled “From Objects to Agents”, which is curious as it’s not a subject I know anything about. Also, those attending the talk might have noticed I looked a bit different than usual. Anyway, at the request of several of those attending (myself included), I have put the slides online

If this post seems needlessly cryptic, you’re probably not in the target audience. Just nod and smile.

This entry was posted in programming on by .

Exceptions for control flow considered perfectly acceptable, thanks very much

Apparently the fact that I use exceptions in my suggested control flow mechanism for collections makes me a bad person. This idiocy touches on a sore point for me. I have been invited to write a post on “Why exceptions for control flow are a good idea”. So. Here it is.

The thing is, I really can’t be bothered. I can give and have given useful use cases, but I’ll just be told that they’re evil because I use exceptions. So instead I will argue the converse: Why they are not a bad idea.

Let’s consider some common objections:

Exceptions are slow

No they’re not. Exceptions in C++ (and I believe .NET) may be slow, but many implementations of exceptions are in fact extremely fast. The various ML implementations have taken advantage of this for quite some time. The JVM too (with some mild tricks) has very fast exceptions.

Exceptions are for exceptional situations

This argument is pervasive. It’s also meaningless. Depending on the intent of the one claiming it, it is one or more of three different forms of fallacy:

  1. Assertion of the conclusion
  2. Argument by name. They’re called exceptions, therefore they must only be for exceptional conditions. If I called them kittens would it suddenly be ok to use them for control flow? (Next post: Kittens for control flow considered harmful. I look forward to seeing Josh Suereth’s rebuttal).
  3. Argument by meaningless blither. What distinguishes “exceptional conditions” from “control flow”? I have reached the end of a million element list. This happens one time in a million! That sounds pretty exceptional to me!

Writing exception safe code is hard

No it’s not. Be sure to clean up anything that could need cleaning up in a finally block. If you write decent code, and you’re using a language with automatic memory management so that this doesn’t apply to Joe Random Object, these tend to be small and relatively well isolated cases. Where possible you abstract this out entirely by using patterns like automatic resource blocks (remember: In decent languages it’s just a library).

Further, even if it were true, this would be an argument against using exceptions at all rather than using them for control flow: If you aren’t sure where exceptions may be thrown from (which is particularly true if you’re writing generic library code), you have to write exception safe code.

It’s confusing

Everything’s confusing when you first encounter it. Then you get used to it, you find where it does and doesn’t work, and then it becomes non confusing. As long as you continue to maintain that a technique is evil and should not be used it will remain confusing.

Debuggers will break on exceptions

Decent debuggers allow you to specify which exceptions you break on and which you don’t. It’s easy to provide a marker class that says “This exception is for control flow. Don’t worry about it”.

You might accidentally catch the exceptions you’re using for control flow with too broad exception handling

Consider the break/continue example. What happens if I do the following (and break is implemented with exceptions):

     for(thing <- myThings){
        try {
           doStuff;
           if(dieNow) break;
        } catch { case (e : Exception) => e.printStackTrace }
     }

We accidentally catch the break! This is bad.

There are a couple aspects to my response to this:

First off, given sensible library design it doesn’t happen at all. Control flow exceptions get moved outside the hierarchy of normal exceptions which it’s sensible to catch (in my quick hacked together version they were Errors. Really they should be subclasses of ControlFlow which extends Throwable).

Secondly, this is a problem with too broad exception handling: You’ve handled a generic exception where you probably just wanted to handle a specific one. This is always known to be bad.

Thirdly, this is a really really easy problem to spot. As soon as you even lightly test the code you will see a stack trace for Break being printed and will realise what you’ve done wrong. This might cost you a good 10 seconds of confusion tops. (If you simply swallow the exception silently this isn’t true. But if you do that I have no sympathy for you at all and your code deserves to break).

The problems with using exceptions for control flow are well documented

Actually, they’re not. If you don’t believe me, check google scholar.

Edit: It has been pointed out to me that if you add quotes to the search term then you do get a few hits. They all seem to be random Java best practices documents deriving from Rules for developing robust programs with java exceptions, which does not appear to present any arguments not already covered here. For completeness, here is the relevant section from it:

IM1: Do not use exceptions for control flow.
It is possible to use the exception handling mechanism for control flow also during normal
program flow. This makes the code harder to read, harder to analyze, significantly slower and
opens up for some horrible situations if an actual exception were to occur. Exception should,
as the name states, only be used in exceptional situations.

So we’ve got one count of “confusing”, one count of “performance”, one of what I can only imagine is a vague allusion to the problem of accidentally catching the exception and a chaser of “Exceptions should only be used in exceptional circumstances”. This, as far as I can tell, is the gold standard argument for the opposition in the Java realm.

Feel free to post additional arguments for or against in the comment. I’ll expand the article with any good ones posted.

This entry was posted in programming on by .

We don’t need anonymous inner classes? Bollocks to that.

Robert Fischer over at enfranchisedmind.com has a post about anonymous inner classes which I am forced to disagree with quite strongly.

He starts off with the example of a comparator, and shows that defining a lambda and then casting it to a Comparator is terser. I largely agree. I don’t agree with everything about that example, but it would be churlish to quibble over details. I concede the point: For one method anonymous inner classes, lambdas are better.

He then attempts to generalise this to anonymous inner classes with multiple methods.

Except he doesn’t really. He simply states that because Groovy lets you coerce maps to an interface, you don’t need anonymous inner classes.

This is an interesting point. Let’s take it further.

We can define the following function (in some sort of pseudo syntax because I don’t know Groovy):

defineClass("Kitten", {
  "meow" => () -> println("meow"),
  "play" => it -> ...
})

Hopefully it will be taken as uncontroversial that I don’t consider this to be the best idea I’ve ever heard. There’s certainly a place for things like this – e.g. if you’re starting from a prototype based language like Javascript and want to build a class system on top of it, something like the above makes sense. But with classes baked into the language, I much prefer

class Kitten{
   def meow = println("meow");
   def play(it) = ...
}

It’s cleaner and terser syntax, and it better expresses the meaning.

So. We now have two ways of expressing classes which map to our two ways of expressing anonymous inner classes. Except that for some reason we prefer one in the named class case and one in the anonymous inner class case. This is odd, to say the least.

Now I want to pick a bone with the claim that what we’re really doing when we create anonymous inner classes is passing multiple functions. It seems utterly contrary to reality. That may be true in some cases when you’re using them as an argument to some method, but most languages I know have this interesting feature called “returning values from functions”. I know you don’t see it getting used much what with the current fad for writing all your programs in continuation passing style, but it does happen occasionally.

Consider example the following implementation:

class Vector[T]{
   ...
   def elements = new Iterator[T]{
     var position = 0;
     def hasNext = position < length;
     def next = {val it = this(position); position += 1; it }
   }
}

This pretty unambiguously captures the intent: We’re creating a new iterator which captures the local scope. The alternative version (again, pseudo syntax):

class Vector[T]{
   ...
   def elements = {
     var position = 0;
     { 
       "hasNext" => () -> position < length;
        "next" => () -> {val it = this(position); position += 1; it }
     } as Iterator
   }
}

has absolutely no appeal to me. It muddies the intent and has worse syntax (if someone from the groovy world would like to tell me that the actual syntax for the above is better, please do, but I suspect I’ll still dislike even a slightly tider version of the above).

Iterators are one example, but there are plenty of others. e.g. in SBinary, formats have two methods read and write, and I return new ones as anonymous inner classes all the time. It would have been a maddening library to write without the capability to do that.

Anonymous inner classes get a bad reputation because so often their use is as a poor substitute for first class functions. But they really are a practically useful tool. I have plenty of other ideological reasons why I consider them vital to have, and this article was originally going to contain some of those, but I couldn’t be bothered. So I’m going to leave it at that: They’re useful, and they cleanly capture the intent in a way that I feel that coercing a map does not.

This entry was posted in programming on by .