Skip to content

Commit 2a50dfa

Browse files
jaredbeckbbatsov
authored andcommitted
Disjunctive assignment in constructor
See discussion in: - rubocop/rubocop#6608 - rubocop/rubocop#6586
1 parent d721dd2 commit 2a50dfa

File tree

1 file changed

+33
-13
lines changed

1 file changed

+33
-13
lines changed

README.md

Lines changed: 33 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3018,19 +3018,6 @@ condition](#safe-assignment-in-condition).
30183018
Person = Struct.new(:first_name, :last_name)
30193019
```
30203020
3021-
* <a name="factory-methods"></a>
3022-
Consider adding factory methods to provide additional sensible ways to
3023-
create instances of a particular class.
3024-
<sup>[[link](#factory-methods)]</sup>
3025-
3026-
```ruby
3027-
class Person
3028-
def self.create(options_hash)
3029-
# body omitted
3030-
end
3031-
end
3032-
```
3033-
30343021
* <a name="duck-typing"></a>
30353022
Prefer [duck-typing](https://en.wikipedia.org/wiki/Duck_typing) over
30363023
inheritance.
@@ -3254,6 +3241,39 @@ condition](#safe-assignment-in-condition).
32543241
end
32553242
```
32563243

3244+
### Constructors
3245+
3246+
* <a name="factory-methods"></a>
3247+
Consider adding factory methods to provide additional sensible ways to
3248+
create instances of a particular class.
3249+
<sup>[[link](#factory-methods)]</sup>
3250+
3251+
```ruby
3252+
class Person
3253+
def self.create(options_hash)
3254+
# body omitted
3255+
end
3256+
end
3257+
```
3258+
3259+
* <a name="disjunctive-assignment-in-constructor"></a>
3260+
In constructors, avoid unnecessary disjunctive assignment (`||=`) of
3261+
instance variables. Prefer plain assignment. In ruby, instance variables
3262+
(beginning with an `@`) are nil until assigned a value, so in most cases the
3263+
disjunction is unnecessary.
3264+
3265+
```ruby
3266+
# bad
3267+
def initialize
3268+
@x ||= 1
3269+
end
3270+
3271+
# good
3272+
def initialize
3273+
@x = 1
3274+
end
3275+
```
3276+
32573277
## Exceptions
32583278

32593279
* <a name="prefer-raise-over-fail"></a>

0 commit comments

Comments
 (0)