Even if it is a convenient function, there may be some disadvantages.
Therefore, the user needs to be able to judge the balance between advantages and disadvantages and implement it appropriately. I thought, I summarized it in an article.
In some cases, the difficulty of maintenance actually outweighs the difficulty, and is it necessary again? I hope it will be helpful for you to consider
ʻAttr_reader: name` defines the getter method with the name of the argument
def name
@name
end
ʻAttr_writer: name` defines the setter method with the name of the argument
def name=(val)
@name = val
end
ʻAttr_accessor: name` is a composite method of reader and writer
Normally, instance variables that can be accessed by @hoge
inside the instance are defined by public methods, so the value of the instance variable can be touched from the outside.
At this time, it is also possible to define the method privately by using private
.
private
attr_reader :hoge
It can be used from the outside because it is cut as the public
method, which is the original purpose.
As you all know here.
class Hoge
private
attr_accessor :hoge
def initialize(hoge:)
@hoge = hoge
end
def connect
Service.call(hoge: hoge) # <-Here
end
end
When it's implemented like this
def hoge
@hoge + 1
end
If you need to fix it like this, you can override it to make it easier to fix.
You need to think correctly about public
or private
, etc.
Inadvertent method definition can lead to method name conflicts
--If you can override it, is the method overridden? Need to check => Readability is reduced
class Hoge
include Hoge::XXXable
include Hoge::ZZZable
private
attr_accessor :hoge
def initialize(hoge:)
@hoge = hoge
end
def connect
Service.call(param: param)
end
end
module Hoge::XXXable
include ::YYYable
def param
{
hoge: hoge # <-Here
}
end
end
For the prerequisite module (cutout module) included in the target class in this way It just references an instance variable but can be a method call
This is
module Hoge::XXXable
include ::YYYable
def param
{
hoge: @hoge # <-Here
}
end
end
If it is, you can easily understand that "the instance variable of the class to be included and loaded is set" just by looking at the source in the module.
However, since this is an attr getter method, if you just look at the XXXable
module, where is the hoge
defined? I don't understand.
So somewhere below? The work of searching for will occur.
--Is it defined in XXXable
?
--In the module included or extended by XXXable
--Classes and modules that include XXXable
--The module loaded by the class or module that includes XXXable
** Easy to maintain ** mentioned in the merit is applicable in the sense that it is easy to overwrite. If the need is unpredictable at this stage, isn't it ** difficult to maintain **?
Isn't this a case where these disadvantages become greater when using it? I will consider whether to use it while thinking again I would like to write a better program