Project

General

Profile

Actions

Feature #11911

open

Immutable method definitions and/or static dispatch

Added by mlarraz (Matt Larraz) over 5 years ago. Updated over 5 years ago.

Status:
Feedback
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:72563]

Description

One of Ruby's biggest strengths is the ability for anyone, at any time, to redefine (almost) any behavior. But this is also one of its biggest weaknesses.
Ruby has a very liberal dynamic dispatch, so any method can be redefined anywhere in the code, meaning we can never have any guarantees about behavior.

Other languages with dynamic dispatch (like C++ or Java) also allow for static dispatch. In particular, Java has dynamic dispatch by default, with the final keyword marking a method as immutable.

In Ruby, this might look something like:

def foo
 'foo'
end

final :foo

# Raises an exception
def foo
 'bar'
end

I see this as analogous to freezing a string.

Note that if somebody really needs to overwrite an immutable method, they can still do so, just in a more explicit way:

undef_method :foo

# Works as expected
def foo
 'bar'
end

This eliminates some ambiguity.

I'm not sure how feasible this is (or whether this is the ideal syntax), but I'd like to hear what the community thinks of such a concept in general.

Actions

Also available in: Atom PDF