Rubocop: Idea: Cop for unnecessary `||=` operator in the initializer

Created on 19 Dec 2018  路  3Comments  路  Source: rubocop-hq/rubocop

Is your feature request related to a problem? Please describe.

I often stumble across code like this:

class Person
  def initialize(full_name)
    @full_name ||= full_name
  end

  # ...
end

Describe the solution you'd like

In this case, I find the ||= usage unnecessary as the #initialize method is called just once.

I believe that this is an offence and deserves a dedicated cop.

Thank you for your time and consideration. Would be happy to hear back from you.

Describe alternatives you've considered

Blank

Additional context

Blank

feature request

Most helpful comment

馃憤 but, consider a constructor that calls super:

def initialize
  super
  @x ||= 1
end

The location of the super matters. Consider also:

include MaybeSetIvars
def initialize
  maybe_set_ivars # from MaybeSetIvars
  @x ||= 1
end

We could write an imperfect implementation that only registers obvious offenses. There's still some value in that.

All 3 comments

I recently reviewed some code and recommended changing ||= to = in an initialize method. 馃憤

馃憤 but, consider a constructor that calls super:

def initialize
  super
  @x ||= 1
end

The location of the super matters. Consider also:

include MaybeSetIvars
def initialize
  maybe_set_ivars # from MaybeSetIvars
  @x ||= 1
end

We could write an imperfect implementation that only registers obvious offenses. There's still some value in that.

Was this page helpful?
0 / 5 - 0 ratings