Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
What is the most intrusive wart on your favourite programming language?
23 points by apgwoz on Dec 8, 2008 | hide | past | favorite | 70 comments


Java: The fact that I have to manually cast Arrays to a template. Everything else allows me to template nicely except arrays.

Python: The error message passed when you call a method with the wrong number of arguments. It's just off since the method "def apple(self, steve, new_product)" has three args, but you'll call it with two "apple(steve, new_product)". So, the message that gets passed back if I pass in one or three arguments is just wrong. I actually like the explicit self in the definition, but the error message needs to say something like "method given the wrong number of args. 1 argument passed when there are 2 arguments plus implicitly passed self."

Python: The functions that should be methods. len(list) just doesn't rub me as well as list.len(). It's such a stupid criticism that I'm hesitant to post it, but whatever, it bothers me. Likewise, Ruby's int.to_f seems much nicer than a built-in function float(int). Same with int and str.

PHP: The fact that 0 == "apple". Yeah, integer 0 is equal to any string. That means: $a = 0; $b = "apple" $c = "ms" $a == $b $b != $c $a == $c

Yeah, a == b, a == c and b != c. Um? Heck, integer 0 is equal to an uninitialized variable. It just makes bugs that are so hard to find. Yeah, it stops you from having to cast in certain situations, but for the little time it takes to cast, you end up with horrible bugs.

Java: The fact that I can't do if(a) { return true } else { return false } in a method. The Java compiler will say that I don't have a return in that method because all of my returns are within a conditional even though it will always hit one of the return statements. if the Java compiler is going to check that I have an appropriate return, be smart enough to figure out that I do.


Python: "Ruby's int.to_f seems much nicer than a built-in function float(int)."

    >>> print float.__class__.__name___
    type
See, "float" is a type. float(int) is a constructor for a floating point number. It's not a magic built-in function, it's just a constructor for type float. Same with int and str. I can't say there's anything wrong with Ruby's int.to_f, but I actually like the Python design better.

Now, as far as len() goes, I agree. It's easy to forget about such troubles, but I definitely wasted a good 10 minutes when I was learning Python trying to figure out what property or method of type list (or str--I don't remember) I should use to get its length.


The C code for Fixnum#to_f is quite literally

  fix_to_f(VALUE num) {
    double val;
    val = (double)FIX2LONG(num); //RSHIFTs sign
    return DBL2NUM(val); //Ruby float constructor of C double value
  }
It does the same thing. Ruby, by design, flows left to right instead of nested params. This way you don't have float(user.timestamp) but instead user.timestamp.to_f.


Your two Java points - the first one: Amen. The latter - not true:

public static String foo(final boolean b) { if( b ) { return "Yes"; } else { return "No"; } }

Compiles just fine.


> Ruby's int.to_f seems much nicer than a built-in function float(int)

I multiply by 1.0 to turn an int into a float:

   Python 2.5.1 (r251:54863, Jul 31 2008, 23:17:40)
   >>> 3/2
   1
   >>> 3*1.0/2
   1.5
   >>> float(3)/2
   1.5


About your last point: You can get around it by typing return (a);


I should have used a better example, but there are a good number of cases where the Java compiler complains about missing return statements that just don't need to be there. It's a wart in the language.


Can you cite a specific example where the condition is NOT ambiguous and the Java compiler WILL produce an error? The example you cite is incorrect (see my post later) - you can compile code of this form just fine.

I'm not aware of unambiguous situations where the compiler will complain; if you see an error it's usually pebkac!


It isn't always that straightforward. For example:

  if (a)
    return (some && complicated || boolean && calculation);
  else
    return (some || other && boolean || calculation);
edit: I suppose you can get rid of the "else", but you shouldn't have to sacrifice readability for a compiler shortcoming. I'm with mdasen; the compiler should figure it out.


Readability is improved by not having the else clause. It makes it clear that the return in the then-block is there and the code won't continue after the end-if.


You (and some posters below you) missed the point. It's just an example. Think of the more general case.


or...

if (a) { return true; } return false;


agreed, if (a) then just return a;

if (a) { return true; } is just as redundant as an if (a == true) statement.


Hmm... not sure what justified the -1 on this. Perhaps that in some languages if (a) can be used as a shortcut for if (a != null), where a is an object and not a boolean. So, as a correction to my previous comment. If (typeof a == "Boolean" || a instanceof boolean), I still stand by reducing redundancy, but if a is an object, then fine, if (a) return true;


About your last point: return (a ? ... : ... );


My favorite language is Javascript, so I've got plenty of warts to choose from.

I think that the most intrusive one is semicolon insertion. This is perfectly valid code that does not do what it looks like:

    return
      {
        a: "foo"
      };
That's quite different from:

    return {
      a: "foo"
    };


My favorite language is JavaScript too, and the most annoying wart for me is function scope instead of lexical scope. For example,

    var closures = [];
    for (var i = 0; i < 10; i++)
    {
        var j = i;
        closures[i] = function() { alert(j); }
    }
    closures[0](); // outputs 9, WTF?
How to fix it:

    var closures = [];
    for (var i = 0; i < 10; i++) (function()
    {
        var j = i*i;
        closures[i] = function() { alert(j); }
    })(i)
    closures[0](); // outputs 0 as it should


You could also do it like this:

    var closures = [];
    for (var i = 0; i < 10; i++)
    {
        var j = i;
        closures[i] = (function (k) { return function() { alert(k); })(j);
    }
    closures[0](); // outputs 0
The issue is that the var here is passed by reference. Ie, all 10 closures refer to the SAME "i" variable. So, when i is incremented, they see that it's been incremented.

Outputing 9 is actually correct in the first case. If you want to trap the current value, you need to copy the value to a new reference, ie, by making it the argument of a function with a new scope.


Yeah I know how this stuff works per spec.

The issue is that the var here is passed by reference. Ie, all 10 closures refer to the SAME "i" variable. So, when i is incremented, they see that it's been incremented.

No, closures refer to the j variable that doesn't get incremented, only assigned to. The assignment is by value - no vars get "passed by reference", whatever this means. The actual issue is that all invocations of the loop body alias the same var j, even though it's declared inside the block.

I usually wrap the whole loop body if it contains multiple variables and multiple closures closing over them - it's easier on the brain than fixing every closure creation spot. Kinda sad because JavaScript is almost the perfect language for my mind.


Yeah I know how this stuff works per spec.

You say that, and yet, you seem not to understand it. Perhaps you know how it works, but have not thought through the implications of it working any differently?

No, closures refer to the j variable that doesn't get incremented, only assigned to. ... The actual issue is that all invocations of the loop body alias the same var j, even though it's declared inside the block.

You're doing it wrong. Javascript doesn't have block-level scope. It only has functional scope.

In the process of parsing an execution context, all "var" statements (and named function declaration statements, which are a special sort of "var") are handled first, and only once. A var inside a loop still only creates the variable once, scoped to the function.

So, your code sample is actually equivalent to:

    var closures = [], j = undefined;
    for (var i = 0; i < 10; i++) {
        j = i;
        closures[i] = function() { alert(j); }
    }
    closures[0](); // outputs 9, duh ;)
You have one "j" variable that is shared by all 10 closures. When you set "j" in loop iteration 9, the closure created in iteration 0 faithfully sees that change.

Closures tracking changes to variables in the parent function is not a wart. Consider this code:

    var thing = (function () {
        var privateData = "foo";
        return {
            set : function (x) { privateData = x; },
            get : function () { return privateData; }
        };
    })();
If closures "trapped" outer values at their current state, then no matter how you called thing.set(), it would always return "foo" from thing.get(). Also, it would be much more expensive to keep track of completely independent contexts. (You could argue that these side effects make js a less pure functional language, and you'd be correct; another, less clear, argument could be made that this makes javascript less good, and I'd disagree.)

However, your complaint seems not to be about closures or shared activation objects per se, but rather about the lack of block-level scope. Since "j" is created inside a set of braces, you seem to suggest that there ought to be multiple "j" variables created, which are each forgotten at the end of the loop.

That's how C++ does it. But javascript is not C++. Javascript is javascript. And only functions create scope in javascript.

IMO, this is not a wart. Doing otherwise would mean that every "while", "for", "switch", "if", and "else" would have to create an activation object, which would get quite expensive and complicated.

If you find it confusing that a var inside a loop is only created once, then take Crockford's advice, and always put all "var" statements at the start of a function. Personally, I disagree with him on this point, because I find it more useful to "var" variables near their use so that moving code around doesn't accidentally result in leakage to the global scope.


I wrote about this too: http://scriptnode.com/article/the-last-in-a-loop-bug/

I like your reasoning for moving "var" further down where it's used in a function.


However, your complaint seems not to be about closures or shared activation objects per se, but rather about the lack of block-level scope.

Bingo, reread my first comment.

If closures "trapped" outer values at their current state, then no matter how you called thing.set(), it would always return "foo" from thing.get().

No I don't want hyper-static environments, this would preclude the very useful encoding of objects with mutable state as closures.

Since "j" is created inside a set of braces, you seem to suggest that there ought to be multiple "j" variables created... every "while", "for", "switch", "if", and "else" would have to create an activation object, which would get quite expensive and complicated.

Do you think Ocaml heap-allocates a frame for every scope entered? How is it about as fast as C++, then? :-) Activation frames would need to be created for only those blocks that directly construct closures, findable by simple static analysis. Almost all other languages with closures do precisely this.

As a rule, the introduction of lexical scope doesn't make languages perceptibly slower. For example, the historical transition of Lisps from dynamic to lexical scope was accompanied by fears very similar to yours, and Scheme played a major role in convincing people that lexical scope worked fast. Modern Scheme compilers are quite clever at eliminating unneeded activation frames and closures, sometimes even converting closures into inline code. It's a well-researched topic. (See http://www.paulgraham.com/thist.html, a great retrospective by one of the best implementers... search for "tied up" for an amusing paragraph about exactly this. The year was 1982, I was busy being born.)

And to reiterate my point from another comment, all code that relies on function scope could be converted to a hypothetical lexically-scoped-JavaScript by a trivial transformation: move every var declaration to the toplevel of the containing function (which coincides nicely with Crockford's advice). This demonstrates that function scope is not more useful than lexical in any practical sense.

In short, I know how JavaScript works, I know how it could work differently, and I consider the different way superior both in theory and in practice.


I guess it just seems much more elegant and simple to me to have only one kind of scope in the language. One is all you need.

No, closures refer to the j variable that doesn't get incremented, only assigned to.

"Doesn't get incremented, only assigned to." I don't know what that means. How is "i++;j=i;" any different, really, than "i++;j++"?

The assignment is by value - no vars get "passed by reference", whatever this means.

"Passed by reference" ==> all the closures reference the same "j" variable. The phrase "pass by reference" is, of course, a bit of a mixed metaphor, since it's not really "passed" as an argument to a function, but rather trapped by a closure. Same difference.

The actual issue is that all invocations of the loop body alias the same var j, even though it's declared inside the block.

"Even though"? There are no blocks in javascript; only functions create scope. That's what's so awesomely simple about this language. Eh, to each his own, I guess.

Lexical scope could be introduced in the new additions to ES3.1, but I'm pretty sure it won't be. A javascript engine would be crazy to try to shoehorn it into the language now, since it would, in fact, break a lot of code in the wild.

Time to man up. :)

Modern Scheme compilers are quite clever at eliminating unneeded activation frames and closures, sometimes even converting closures into inline code.

Isn't that roughly what tracemonkey does?


Isn't that roughly what tracemonkey does?

Yes. Nice to see implementations are growing up.

I guess it just seems much more elegant and simple to me to have only one kind of scope in the language... That's what's so awesomely simple about this language.

Block scope can be viewed as only one kind of scope. :-) If you try to define a language formally, function scope and lexical scope will be about equivalent on the simplicity scale: scopes will just be tied to code blocks instead of functions. (The scope nesting machinery is needed for closures anyway.) Implementation simplicity is also about equivalent: yes, blocks have to allocate activation frames only if they're needed, but same applies to functions once you get serious about speed.

The preference depends on your coding style. I find it intuitive to declare each variable in the outermost {} block that uses it, and not higher up; this intuition exactly corresponds to the formal concept of block scope. Many people naturally think like me, hence the huge number of Web articles complaining about the JS loop scope gotcha, calling it "weird", "unintuitive" and all manner of names. But as you say, to each his own.

A javascript engine would be crazy to try to shoehorn it into the language now, since it would, in fact, break a lot of code in the wild.

Yes. :-(


Function scope is the entire point of closures. If it was lexical scope it would not be a closure, it would just be a regular function.

Just pass in j when you call it and you can have lexical scope easily.

But if you changed that, a TON of code would be impossible, so I'm very happy with it working that way.


No.

Function scope is the entire point of closures. If it was lexical scope it would not be a closure, it would just be a regular function.

Many more languages with closures have lexical scope than function scope. Lexical scope is the entire point of closures in those languages, indeed everywhere except JavaScript.

Just pass in j when you call it and you can have lexical scope easily.

I don't know j when I call the closure. Give a code example.

But if you changed that, a TON of code would be impossible, so I'm very happy with it working that way.

I can't imagine any code that would become impossible, or even the slightest bit more difficult, if function scope were replaced with lexical. Indeed all code using function scope could be mechanically translated into a (hypothetical) lexically-scoped-JavaScript by moving every var declaration in every if/for/while/etc block up to the toplevel of the containing function. If you disagree, give a code example.


That's a pretty good argument to never use Allman, Whitesmiths, GNU, or Horstmann indent style. There can only be one and that's K&R.

Woho! I just won a religious war.


Absolutely! For Javascript at least, putting the { on the same line as the thing that caused it is pretty much the only rational policy.

The weird thing is just how the interpreter handles this:

    return;
    {
    a: "foo";
    }
That's a null return, a block (not that JS supports block-level scope, so blocks are pointless), a labeled line (line-labels aren't actually used for anything, since there's no GOTO), and on that labeled line, there's a string expression that does nothing.

So, this is really like 4 different warts working together, but semicolon insertion is by far the most insidious.

Also, liberal use of parens can help prevent semicolon insertion bugs.


Tcl's string quoting conventions also try to force you to use K&R style for procedure bodies. e.g

   proc foo {x} {
      # do stuff
   }
but if you really want to get around this you can abuse the continuation character

   proc foo {x} \
   {
      # do stuff
   }


Objective-C: @property requires duplication of the ivar type, and doesn't imply @synthesize. (To do either of these would stop it being a simple macro, but that elegance comes at the expense of a frustrating amount of unnecessary typing.)

Common Lisp: built-in functions aren't generic. Tedious verbosity of defclass. No literal syntax for hash tables. Debuggers so much worse than they should be.

Smalltalk: having to manually implement getters/setters. Awkwardness of code generation.

Ruby: gems not having a single canonical name (what you require != what you install).


I missed this thread, but I'll add another Common Lisp annoyance: the way DESTRUCTURING-BIND is inconsistent with destructuring lists in LOOP. Specifically, I want to bind to NIL for variables I don't care about (rather than having to explicitly ignore them) and bind to heads of lists rather than always the whole thing. I've been meaning to check out the open-source BIND macro and see if it does any better.


ObjC: You don't have to declare ivars for your @properties if you target 64bit. The 64bit runtime Does Magic. Also, @property cannot imply @synthesize because you might want to use @dynamic instead.


Haskell: people start talking behind my back when I mention implementing something on it


Python: "<br>".join(["string1","string2"])

Maybe it shouldn't but this pisses me off.


I would think a more natural approach of making join a method of any sequence would result in cleaner programs.

(a, b, c).join(',')

instead of: ','.join((a, b, c))


I agree. Join should word the same as split:

   >>> "abcbe".split("b")
   ['a', 'c', 'e']
So to get back the original string you should be able to say:

   ['a', 'c', 'e'].join("b")   #!!! WRONG !!!
but this doesn't work and instead you have to say:

   >>> "b".join(['a', 'c', 'e'])
   'abcbe'


You miss out on a nice side-effect of join being a method of string:

br = '<br>'.join

br((a, b, c))

Personally I think it makes more sense the ruby way but it's never bugged me.


Wow... This one is quite pretty. Really. A very nice side effect of the "everything is an object" concept.


There's not any reason you need objects for that, though. Python's join in the string module is called as join(list [,sep])*, and you could say

  def br(sl):
      return string.join(sl, "<br>")
or

  br = lambda sl: string.join(sl, "<br>")
for the same effect. It's actually due to first-class functions.


What don't you like about this?


The fact 'join' being a method of a string that accepts an array as an argument. I guess it isn't that bad, I just think I've been conditioned to expect it the other way around.


My string/sequence related annoyince is ''.split() -vs- ''.split(';').

The first returns [], but the second returns [''].


str.join("<br>", ["string1", "string2"])

I hate it too.


I like it.


Lua: array indexing starting at 1 (and interoperating with C is one of the main purposes of the language)


See also: (http://lua-users.org/wiki/CountingFromOne)

There are arguments for doing it either way, but making indexing incompatible with the language in which it is expected to embed in is just rude.


Which really is too bad, by the way - the language designers seem to have done a brilliant job of shrugging off potential design warts otherwise. It's a very clean language.


I use Lua a lot these days and coming from Python, it seems silly that I have to provide my own empty? function since standard Lua doesn't offer any way to get the number of elements in an arbitrary table other than to iterate over it:

    function empty_p(t)
        for k,v in pairs(t) do
            return true
        end
        return false
    end


    -- later on
    if not empty_p(t) then
        do_processing(t)
    end
This is because although Lua offers a #t operator, it's only guaranteed to be correct if you're careful about how the table is constructed. That and the weird ipairs() behavior for non-trivial tables drives me crazy sometimes. Here's an example:

    Lua 5.1.2  Copyright (C) 1994-2007 Lua.org, PUC-Rio
    > t = {1,2,3}
    > print(#t)
    3
    > for i,v in ipairs(t) do print(i,v) end
    1       1
    2       2
    3       3
 
Ok so all is good. But now what happens when the table contains a nil?

    > t = {1,nil,3}
    > print(#t)
    3
    > for i,v in ipairs(t) do print(i,v) end
    1       1
ipairs() stops at the first nil value even though Lua knows there is data past it. Things get more interesting for tables with non-integer keys:

    > t = {}
    > t['a'] = 1
    > t['b'] = 2
    > print(#t)
    0
    > t[1] = 1
    > print(#t)
    1
    > for i,v in ipairs(t) do print(i,v) end
    1       1
What's going on here is each Lua table has an array for integer valued keys and a separate hash table for non-integer keys and # and ipairs() only operate on the first array. To process all the keys you use pairs():

    > for k,v in pairs(t) do print(k,v) end
    1       1
    a       1
    b       2
While at first this doesn't seem to be such a big issue, it's easy to forget when it's safe to use the #t construct. I've made this error so often that now whenever my Lua code doesn't do what I expect the first thing I look for are places where I have something like:

    if #t > 0 then
        do_processing(t)
    end
or

    for i,v in ipairs(t)
        process(v)
    end
because chances are the real problem will turn out to be the particular way I initialized the table.


I suspect this is because a table may be used for an object (or some other abstract data type) which has a different data type. Adding another metatable hook for __empty might be another solution, though. (I agree it's a bit annoying.)

> Ok so all is good. But now what happens when the table contains a nil?

One of the invariants for the way Lua tables are implemented is that they won't contain nil as a value, IIRC. Using a multifaceted table type for both arrays and dicts is a mixed blessing. It is really convenient much of the time, but it does lead to some quirks.

NB: The i in "ipairs" means "integer (keyed) pairs".


The aliasing rules in C. Almost every single case I have found of performance-critical code being compiled suboptimally is due to redundant load/stores being emitted due to aliasing restrictions.

And no, the "restrict" keyword doesn't fix much of anything.

The most annoying rule is that char * pointers can alias anything... especially when one has to deal with enormous amounts of 8-bit image data.


I just did this in Ruby and got a syntax error:

    Time.now -1.day
Of course, what it should have been was:

    Time.now - 1.day


You mean Rails.

This works as expected, though:

  Time.now-1.day


submitted to reddit, here is the thread:http://www.reddit.com/r/programming/comments/7hv0j/ask_progg...

has some good responses


Actually, that's weird. I thought I attached that url to the post...


Note the helpful text on the submit page: http://skitch.com/isaacschlueter/76ee/the-helpful-text-it-is...


OCaml: can't split modules/packages/namespaces across files (I can't remember exactly, but that is the gist)


OCaml: no library compatibility between compiler versions -- recompile everything when you upgrade compiler.


Java - I love Javadoc Tool. Don't really get to use it much now, but still love it.

c# - Constraints on typed params.

public T AssignLiteItem<T>(ArchivingItem archivingItem ) where T : Item {

T myITem = (T)typeof(T).GetConstructor(new System.Type[] {}).Invoke(new Object[] { });

myITem.ItemReference = new ItemReference(archivingItem.Id);

return myITem;

}


Don't forget you can add an empty constructor constraint in c# generics.

public T AssignLiteItem<T>(ArchivingItem archivingItem ) where T : Item, new() {

T myITem = new T();

myITem.ItemReference = new ItemReference(archivingItem.Id);

return myITem;

}

I do wish the compiler handled constraints for arbitrary constructor signatures on generic types, however...


Nice, I guess I can get rid of the reflection invocation of the T Type constructor. Should speed things up a bit. Cheers.


Objective-C: lack of enforced constructors. Sure, by convention you're supposed to call the "init" function for the class, but you don't have to. There's really no good way to guarantee your object has been initialized correctly!


I don't get what the noise is about here. Millions of lines of objc code have been written without mass confusion of how to init objects. It might look good on paper, but in practice telling people "this is the designated initializer" seems to be more than sufficient to sort things out. And being able to initialize an object with anything (or, remember, to have anything initialize an object) only adds to the flexibility and dynamic character of the language.


It's objetive, but, after all, it's also C...

I find the Smalltalk-ishness of it a little weird when it intersperses with more traditional C code.


Python (prior to 3.0): 1/3 == 0

well, unless you do

    from __future__ import division


If your working with integers, 1 div 3 is indeed zero.


That makes sense in a language like C, but in Python there's no telling if you've got integers or floats at the point the division happens.

I'm very happy it's fixed in Python 3.


Wait, then how do you do integer division in Python 3?


1 // 3 == 0


Ruby: methods != lambdas != procs


the poor unicode support in ruby




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: