Skip to content

Instantly share code, notes, and snippets.

@booch booch/gist:8411351
Last active Jan 3, 2016

Embed
What would you like to do?
What If We Could Mark Methods As Pure?

What If We Could Mark Pure Methods?

Me

  • Craig Buchek
  • @CraigBuchek
  • github.com/booch

What is a pure method?

  • No side-effects
  • Does not mutate state
  • Idempotent - can run multiple times, always getting same result
def method1
  1 + 1
end

def add1(x)
  x + 1
end

def not_pure1
  Random.rand
end

def not_pure2(x)
  self.x = x
end

def not_pure3
  puts "Hello!"
end

Why?

  • Could automatically memoize pure methods
  • Could be run in parallel, theoretically
  • Functional Programming

Marking pure methods

def method1(options)
  # ...
end
pure :method1
# Ruby 2.1+
pure def method2(options)
  # ...
end
@pure
def method2(self, options):
  # ...

But

  • C++ allows marking pure methods
  • C++ has const everywhere

Marking impure methods

  • We'd be encouraged to default to pure methods

Inference

  • Could we infer purity via static analysis?

But

  • We'd really have to do it in the interpreter
  • Fairly dramatic change to the language semantics
  • Considering trying to add it to Rubinius or Crystal

Going even further

  • Marking classes as mutable/immutable
    • More value objects!
  • Marking instances as mutable/immutable:
x = User.new('Craig')   # immutable
y = User.new!('Craig')  # mutable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.