[RUBY] About naming Rails model methods

Introduction

Regarding Rails naming, there are many names for Model, Controller and tables, but it seems that method names, variable names and scope names are not written much.

Good or bad naming has a big impact on the readability of the code, but on the other hand, we who are not good at English often give a bloody naming and often accumulate technical debt.

In the first place, ruby has a language specification that is conscious of English-like writing taste ("poi" to the last), so I think that method names, variable names, and scope names should follow this etiquette to some extent. Therefore, I reconsidered the guidelines that these names should follow.

I'll write it in various ways, so I'd like to subdivide it. This time, I thought about naming the model method, scope, and (a little) variable, but I'll think about the controller at a later date.

TL; DR (model edition)

Name target format
scope "Adjective phrase","preposition_noun","Verb ing","Past participle form of verb"
Method with action "Transitive verb" → The object of the transitive verb should be the receiver object!
Judgment method "Adjective (phrase)?」,"preposition_noun?」,"Verb ing?」,"Past participle form of the verb?」
Method that has no effect "Noun (phrase)" → Can be used as a property
Method to transform the object itself 「to_noun"
variable "Noun (phrase)"
Variable (exception) "Past participle form of the verb_preposition(_Noun) ”→ Avoid if you can avoid it

Pay attention to the part of speech of the word you use. And the most important thing is to read and understand the meaning.

Details

Scope name

Should be an adjective or an adjective phrase. The scope name post-qualifies the model name. Use the "what" part of "what OO" as the scope name. The model name is entered in 〇〇.

If you name the scope so that it is post-modified with an adjective phrase, it will not break in English grammar even when the scope is chained. Book.in_sale.published_by("O'Reilly") ← Book (which is) in sale published by O'Reilly

Typical example

Model name. Verb + ing or model name. Past participle form of verb

Shop.selling_books #Stores selling books
Task.not_running #Negative form
Book.published #Past participle form
Book.published_by("O'Reilly") #Scope that also takes arguments

Book (which is) published by O'Reilly

It's a good name to look like a noun phrase with the (which is) omitted.

Model name. Preposition + noun

Shop.without_blue_roof
Devil.in_the_prada
Man.with_the_machine_gun

Model name. Adjective

Mission.impossible
Daemon.alive
Picture.not_displayable
Tower.taller_than(100)
Session.expired #Supplement)expired can be regarded as an adjective or a past participle form of an intransitive verb (there is no big difference).

Useless pattern

Sometimes I see scope names in the style : filtered_xxxx, but these names are redundant because the scope functions are narrowed down in the first place.

We also deprecate : can_xxxx. The judgment of whether or not the name is good is whether or not which is, which was omitted as "Model (which is) scope name", is revived and grammatically collapsed.

Method name

The way of thinking differs greatly depending on whether the method involves an action (change of variables, etc.) or a method that does not have an action.

Methods with action

"What to do" with "subject (caller object)" as "object (receiver)". The "what to do" part is the method name. As a result of somehow, it changes the state of internal variables, acts on external objects, and accesses external services.

cow.grow # <=  I grow up the cow.As a result cow.Age is incremented, and so on.
file.delete # <= I delete the file.As a result, the file disappears on the external file system (for the program).
job.perform # <= I perform the job.

Sometimes I see methods where the receiver (object) is the subject, but it's not good. It may look good for a moment, but in the long run it's no longer object-oriented and begins to collapse.

#bad example
manager.evaluate(member) # <=Word order as it is A manager evaluates his member.

Method without action

Predicate methods

Judgment-based (non-acting) methods that return true or false have a distinctly different naming approach than normal (acting) methods. Only in this case, the receiver is treated as the subject.

For example, the Statement that determines if Shop is in the ʻopen` state

shop.open? # <= Is the shop open?

In other languages, we often make judgment methods with the glue with the be verb shop.is_open. In Ruby / Rails, the be verb is usually omitted and a ? Is added at the end. I think that it is a culture peculiar to the language specification that ? Can be used, and in the first place, "S + V + C" becomes "V + S + C?", So ʻis between the subject and the complement. `Does not enter.

Only in the case of a judgment method, the method name needs to be "complementary". (S = object, V = omitted, C = method name) → Similar to the naming of scopes, the basics are "adjective?", "Preposition + noun?", "Verb + ing?", Or "past participle form of verb?".

Is there or not can_xxx, can_be_yyy? I think it's best to avoid it as much as possible. I will think about it later.

Negation method of judgment system

Do not create a method called shop.not_open? as much as possible. All you have to do is write ! shop.open?. If the judgment conditions become complicated, the readability of the method will also decrease, so I think it is good to design it so that it does not include the meaning of negation in the first place.

A method that has no effect but does not determine

For methods that do not return true / false, it seems better to define those that can be used as properties from the outside as properties. The naming at this time is the same style as the "variable name" described later.

Or, if you want to convert the object itself to another format, you should name it to_xxx. Do not use convert_to_xxx.

For example

class Sylinder
  attr_accessor :bore, :stroke

  def initializer(bore, stroke)
    @bore = bore
    @stroke = stroke
  end

  def displacement # <=Because it does not affect the internal state of the object:calculate_Do not use method names like displacement
    (@bore/2) * (@bore/2) * Math::PI * @stroke
  end
end

Variable name

Basically, I want to use a noun phrase as a variable name. Variables are attributes owned by an object (or class). The attribute name is a noun. You may narrow down the meaning by adding an adjective or possessive case before the noun.

user.email
user.first_name

Exceptionally, a variable that holds ancillary information about an action on an object may have a variable name in the form of the past participle of the verb + the preposition (+ noun). If you can express it without using such variable names, I think it is easier to read later if you avoid it.

article.created_at
article.published_by
article.referenced_in_indices

Consideration

Ruby language specification

automator.call bob if not bob.awake?

From the place where you can call the method argument without parentheses like, and the place where the not, ʻand` keywords are defined Originally, it is possible to write in natural language ** like ** with less symbolic description. The stress of code reading can be reduced by devising the naming of scopes, methods, and variables so that the expression looks like natural language when called.

Basics of English grammar

It is known that English grammar is basically categorized into the following five sentence patterns.

  1. S+V
  2. S+V+C
  3. S+V+O
  4. S+V+O+O
  5. S+V+O+C

I think the sentence pattern components and the corresponding Rails programming concepts are as follows.

S: Subject (main part) → Caller (subject) V: Verb → Method O: Object (noun) → Receiver (object that has the method) and method argument (in the case of the 4th sentence pattern) C: Complement (adjective / adverb / adjective phrase / adverb phrase) → Substitution value

The "O" in S + V + O is an Object-oriented "O".

Expressiveness that object-oriented languages should cover

Basically, it seems good to think that the method call expresses the sentence of the third sentence pattern. Other than that, will it be implemented as an assignment or property change, or will it be implemented by converting it to the third sentence pattern?

First sentence pattern: S + V

Not so much. This is because object-oriented programming is a paradigm in which the caller acts on the receiver to implement the process. I think the simple file.delete () is actually the third sentence pattern.

file.delete # <= I deletes the file.

Second sentence pattern: S + V + C

Since O (Object) does not appear, this is also a rare case as a method form. If so, I think the calling object will assign something to its property, or something like that.

The variations of V (verb) that take this sentence pattern are as follows.

State type: be, look, seem, appear, keep, remain, lie Variants: become, get, turn, grow, make, come, go, fall Sensory type: smell, taste, feel, sound Source: https://www.eng-builder.jp/learning/sentence-pattern2/

In other words, although these verbs differ in whether they are accompanied by changes or not, they all express that S is in the state of C (S = C) as a result. When writing this expression by programming, it seems that it can be realized by assigning a value to the property that represents the state of the object in most cases.

alice.health = :fine # <= Alice becomes fine.

Third sentence pattern: S + V + O

This is easy to understand. It seems to be the most.

file.delete # <= I delete the file.
window.move_to(100, 300) # <= I move the window to (100, 300).

I feel that the given arguments are often used as adverbial phrases to modify the entire sentence. In short, the argument is a parameter that adjusts the action on the object. I feel that the parameter should be const in the called method, but I haven't thought about it yet.

Fourth sentence pattern: S + V + O1 + O2

The variations of V (verb) that take this sentence pattern are as follows.

give, show, offer, hand, pass, send, teach, tell, pay, lend, do

As a tendency, it can be seen that S means giving O2 to O1. When writing in object-oriented programming, I feel that it can often be expressed by assigning / adding to properties.

alice.belongings.push book # <= I give Alice a book
alice.give book # <= I give Alice a book

Fifth sentence pattern: S + V + O + C

The variations of V (verb) that take this sentence pattern are as follows.

make, get, keep, leave, think, believe, find, call, name

It can be seen that all of them are verbs that express the state that O = C. A verb that means to recognize that "some state of O is C" or "some state of O is C" as a result, although there is a difference whether S works on O or not. This could be rewritten into a simpler SVC representation using only C and O if you try to implement it object-oriented.

Room.tidiness = :clean # <= I make the room clean.
cat.name = "Tom" # <= I name the cat "Tom."

Summary

I don't know because it's complicated. The text has become uncoordinated.

Referenced page

Object is the object How To Name Variables And Methods In Ruby

Recommended Posts

About naming Rails model methods
About Rails 6
Rails model and table naming conventions
About Rails routing
[Rails] Naming convention
About singular methods
About HttpServlet () methods
[Rails] About ActiveJob ,!
[Rails] Model Association (Association)
About Rails controller
About Ruby methods
About RSpec (Rails)
[Rails] About migration files
[Rails 6] About main gems
About rails application server
About rails kaminari pagination
About rails version specification
About Ruby instance methods
MEMO about Rails 6 series
About calling instance methods
[Rails] About Slim notation
[rails] About devise defaults
Rails: About partial templates
About rails strong parameters
[Beginner] About Rails Session
Find out about class methods
About validation methods in JUnit
about the where method (rails)
rails path and url methods
rails g model Overall flow
[Ruby on Rails] about has_secure_password
[Rails] About scss folder structure
About pluck and ids methods
[Rails] Japaneseize model attribute names
About Java class variables class methods
[Rails] About Rspec response test
About Ruby and object model
About Rails scraping method Mechanize
Naming convention when creating a new controller or model with rails
About methods often used in devise
About Java static and non-static methods
About the equals () and hashcode () methods
About the symbol <%%> in Rails erb
[Rails] About implementation of like function
[For our newcomers] About isXXX methods
[Rails] About helper method form_with [Basic]
Consideration about Rails and Clean Architecture
Ruby methods often used in Rails
[Ruby] About variable naming rules. Also naming conventions for constants, classes, and methods.