munificent / craftinginterpreters

Repository for the book "Crafting Interpreters"
http://www.craftinginterpreters.com/
Other
8.79k stars 1.03k forks source link

Redeclaring class methods #894

Closed invertego closed 3 years ago

invertego commented 3 years ago

I noticed that Lox allows redeclaring a method with the same name as a previous declaration in that class. For instance, the following code is perfectly legal:

class Foo {
  method() {}
  method() {}
}

I find this surprising! To me, this feels similar in spirit to redeclaration of a local variable - if not worse. The set of methods in a class is lexically/statically determined (though they can be shadowed by fields on an instance) and the reasoning provided for allowing global variables to be redeclared (for REPL convenience) doesn't really seem to apply here. Because only the last declaration wins, turning the previous ones into dead code, I would venture to guess that most of the time this would indicate programmer error.

I'm curious if this was an intentional design choice, and if so what the rationale behind it was.

munificent commented 3 years ago

It's intentional, but not particularly useful. :)

Making definition an error would mean tracking the list of method names in the compiler and it didn't feel particularly interesting or education to me to do that. It would be a decent amount of code for not much value, so I left it out. shrug

invertego commented 3 years ago

Yeah, I understand that the error detection code wouldn't really introduce any new concepts. Thanks for confirming.