copy-edit viget posts
This commit is contained in:
@@ -2,7 +2,6 @@
|
||||
title: "Multi-line Memoization"
|
||||
date: 2009-01-05T00:00:00+00:00
|
||||
draft: false
|
||||
needs_review: true
|
||||
canonical_url: https://www.viget.com/articles/multi-line-memoization/
|
||||
---
|
||||
|
||||
@@ -11,8 +10,10 @@ easy way to add caching to your Ruby app is to
|
||||
[memoize](https://en.wikipedia.org/wiki/Memoization) the results of
|
||||
computationally expensive methods:
|
||||
|
||||
``` {#code .ruby}
|
||||
def foo @foo ||= expensive_method end
|
||||
```ruby
|
||||
def foo
|
||||
@foo ||= expensive_method
|
||||
end
|
||||
```
|
||||
|
||||
The first time the method is called, `@foo` will be `nil`, so
|
||||
@@ -21,21 +22,39 @@ subsequent calls, `@foo` will have a value, so the call to
|
||||
`expensive_method` will be bypassed. This works well for one-liners, but
|
||||
what if our method requires multiple lines to determine its result?
|
||||
|
||||
``` {#code .ruby}
|
||||
def foo arg1 = expensive_method_1 arg2 = expensive_method_2 expensive_method_3(arg1, arg2) end
|
||||
```ruby
|
||||
def foo
|
||||
arg1 = expensive_method_1
|
||||
arg2 = expensive_method_2
|
||||
expensive_method_3(arg1, arg2)
|
||||
end
|
||||
```
|
||||
|
||||
A first attempt at memoization yields this:
|
||||
|
||||
``` {#code .ruby}
|
||||
def foo unless @foo arg1 = expensive_method_1 arg2 = expensive_method_2 @foo = expensive_method_3(arg1, arg2) end @foo end
|
||||
```ruby
|
||||
def foo
|
||||
unless @foo
|
||||
arg1 = expensive_method_1
|
||||
arg2 = expensive_method_2
|
||||
@foo = expensive_method_3(arg1, arg2)
|
||||
end
|
||||
|
||||
@foo
|
||||
end
|
||||
```
|
||||
|
||||
To me, using `@foo` three times obscures the intent of the method. Let's
|
||||
do this instead:
|
||||
|
||||
``` {#code .ruby}
|
||||
def foo @foo ||= begin arg1 = expensive_method_1 arg2 = expensive_method_2 expensive_method_3(arg1, arg2) end end
|
||||
```ruby
|
||||
def foo
|
||||
@foo ||= begin
|
||||
arg1 = expensive_method_1
|
||||
arg2 = expensive_method_2
|
||||
expensive_method_3(arg1, arg2)
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
This clarifies the role of `@foo` and reduces LOC. Of course, if you use
|
||||
|
||||
Reference in New Issue
Block a user