logoalt Hacker News

matharmin • today at 11:43 AM • 1 reply • view on HN

It's an interesting trick, but for a setter method you really need to use `def cloaking=(value)` instead of overloading the same method. It would help to give a more realistic example for where this technique can be useful.


Replies

shevy-java • today at 1:05 PM

I somewhat agree with you here. I find it easier to read when a '=' is used.

At the same time I also understand the idea behind:

    def colour(xyz = :green)
The idea would be to use something in a toggle state.

I sometimes use a similar, but simpler pattern, though I also tend to use explicit method names. But for instance:

    enable(:colours)
    enable :colours
    enable_colours
    disable_colours # etcc
Personally I prefer the longer variants, e. g. enable_colours and disable_colours (without trailing (); if people prefer US spelling the method names could be enable_colors etc.. it is really the very same point anyway). I do, however had, also sometimes use a more generic top-level entry point such as enable. I use that for my pseudo-shell replacement for bash, written in ruby too. For instance:

    enable :windows_configuration
    enable :colours
    enable :systemd # and so on and so forth.
I mostly do this so I have an easier time remembering things; and finding a simple, ideally as simple as possible, entry point.

Of course it is not exactly the same as the rails-idiom shown here, since I'd also have to use:

    colours :green
    colours :disable
    colours false
But I am also fine with set_colours :false. But in general I tend to prefer disable_colours in this case.

Personally, since I know my brain is rather weak, I try to not use "cloaked" methods and just use oldschool setters and getters, where I treat set_foobar to be the same as foobar =.

foobar= is a bit more elegant, but I also like set_xyz in general. Oddly enough I don't really use get_xyz; but I, to my shame, must admit that I like this:

   def return_base_directory
Most will omit "return_", but I kind of like stupid code where I don't have to think. In particular in bigger projects.

I don't really see a need for overloading methods though. I dislike having too many instance variables however had; I noticed that when I have like more than 10 @ variables, I often find it easier to just group them into a Hash instead, with Symbols as key. So for instance:

    @internal_hash[:use_colours] = false
It's not that elegant compared to:

    @use_colours = false
but I found a Hash to just be a lot more convenient to use here. And pp hash is super-userful. (We can easily get all instance variables programmatically, of course, but I still find a Hash structure so much more logical and convenient to use and read than many different instance variables.)