-1

I have a model and the model has several attributes. What I want to do is to turn one of the boolean attributes to true based on other attributes.

Let's say we have a model called User and user has attributes like..

  • id (int)
  • name (text)
  • birthday (date)
  • legal_age (boolean)

I was asked to change legal age attribute, based on birthday. (If user were 20 years old turn it true, if not, keep it false.) I named the function as check_legal_age, because it checks legal age column to true.

However, one of my colleagues advised me that the name is too vague and hard to figure out what the function does and what kind of value does the function returns.

After some conversation, I decided to name the function as make_legal_age_true, a wordy but straight-forward name. The colleague also suggested me to name trufy_legal_age

Is there a conventional way to name a method like this that makes the intentions clear to others reading the code?

m. simon borg
  • 2,515
  • 12
  • 20
  • 3
    I would reword your question a bit so it's less about opinion, or else it might be closed for being off-topic. Something more like "what is the naming convention for this type of method" would be an improvement. That said, I would make it a bang `!` method and call it `legal_age!` – m. simon borg Aug 15 '17 at 02:47
  • 1
    Agree with @m.simonborg, your method is modifying itself (its own attributes) so a simple bang `legal_age!` makes a lot of sense and will be easily understood generally by ruby programmers, take a look here at the ruby style guide for more naming conventions: https://github.com/bbatsov/ruby-style-guide#naming – John Hayes-Reed Aug 15 '17 at 03:07
  • https://stackoverflow.com/questions/612189/why-are-exclamation-marks-used-in-ruby-methods, see this, in ruby bang (!) mean to change the value of object its called. – buncis Aug 15 '17 at 09:33

2 Answers2

0

If it is a function it's best to use a question mark, and call it something like is_legal_age?

Shannon
  • 2,988
  • 10
  • 21
  • 1
    While correct for a method that checks some condition, the OP wanted to know a convention for naming a method that *changes* a value. – vijoc Aug 15 '17 at 05:57
0

Your colleague is right that check_legal_age is not a good name, not because it's vague, per se, but because it's misleading and therefore dangerous. It seems to imply that the object state is being checked or validated, when in fact it's being altered.

Convention is that a method that changes internal object state should be a "bang" ! method. Simply naming the method legal_age! gets the point across for setting a boolean attribute to true.

Better would be if the predicate method (the one that returns true or false) ended with ?. legal_age? and legal_age! seem crystal clear to me.

m. simon borg
  • 2,515
  • 12
  • 20