Google で働きたい ②

から、Google's R Style Guideに従おうと思う。

前回の続きである。

bioinfo.hatenablog.com

General Layout and Ordering

If everyone uses the same general ordering, we'll be able to read and understand each other's scripts faster and more easily.

組織でコードを共有する場合、書く順番は決まった並びになってたほうが速く簡単に読めていいよね。って話。
以下の順番で書きましょう。

  1. copyright
  2. 著者
  3. input、,output、プログラムの目的、を含む、ファイルに関する説明文
  4. source()による外部のRスクリプトの読み込み。library()によるライブラリの読み込み。
  5. 関数の列挙
  6. 必要に応じ、実行コマンド群

ユニットテストoriginalfilename_test.Rの形式にしましょう。

Commenting Guidelines

Comment your code. Entire commented lines should begin with # and one space.
Short comments can be placed after code preceded by two spaces, #, and then one space.

# とスペース1文字でコードに関するコメントを書きましょう。
行ごとに必要な短いコメントの場合、コードの後に2文字分スペースを空けてからその行に関するコメントを記述しましょう。
細かいな。。

# Create histogram of frequency of campaigns by pct budget spent.
hist(df$pct.spent,
     breaks = "scott",  # method for choosing number of buckets
     main   = "Histogram: fraction budget spent by campaignid",
     xlab   = "Fraction of budget spent",
     ylab   = "Frequency (count of campaignids)"

Function Definitions and Calls

Function definitions should first list arguments without default values, followed by those with default values.
In both function definitions and function calls, multiple arguments per line are allowed; line breaks are only allowed between assignments.

関数定義では、まずデフォルト値のない引数を並べましょう。その後にデフォルト値を持つ引数並べましょう。
関数定義のときも、関数呼び出しのときも、1行に複数の引数を持つことはよいが、改行は引数割り当ての間でのみ行いましょう。

PredictCTR <- function(query, property, num.days,
                       show.plot = TRUE)

こういうのはだめ。

PredictCTR <- function(query, property, num.days, show.plot =
                       TRUE)

自分は引数ごとに改行してました。1行に複数引数OKなんですね。

Function Documentation

Functions should contain a comments section immediately below the function definition line. These comments should consist of a one-sentence description of the function; a list of the function's arguments, denoted by Args:, with a description of each (including the data type); and a description of the return value, denoted by Returns:. The comments should be descriptive enough that a caller can use the function without reading any of the function's code.

関数定義の行のすぐ下にコメントのセクションを作りましょう。これらのコメントは、以下で構成しましょう。

  • 関数に関する1行のコメント
  • Args:と各引数に関する説明(データタイプも)で表される引数のリスト
  • Returns: から始まる返り値の説明。
CalculateSampleCovariance <- function(x, y, verbose = TRUE) {
  # Computes the sample covariance between two vectors.
  #
  # Args:
  #   x: One of two vectors whose sample covariance is to be calculated.
  #   y: The other vector. x and y must have the same length, greater than one,
  #      with no missing values.
  #   verbose: If TRUE, prints sample covariance; if not, not. Default is TRUE.
  #
  # Returns:
  #   The sample covariance between x and y.
  n <- length(x)
  # Error handling
  if (n <= 1 || n != length(y)) {
    stop("Arguments x and y have different lengths: ",
         length(x), " and ", length(y), ".")
  }
  if (TRUE %in% is.na(x) || TRUE %in% is.na(y)) {
    stop(" Arguments x and y must not have missing values.")
  }
  covariance <- var(x, y)
  if (verbose)
    cat("Covariance = ", round(covariance, 4), ".\n", sep = "")
  return(covariance)
}

TODO Style

Use a consistent style for TODOs throughout your code.

TODOを記述する場合は、一貫した形式で記述しましょう。

TODO(username): Explicit description of action to be taken

Functions

Errors should be raised using stop().

エラーはstop()関数で起こしましょう。

Objects and Methods

Use S3 objects and methods unless there is a strong reason to use S4 objects or methods. A primary justification for an S4 object would be to use objects directly in C++ code. A primary justification for an S4 generic/method would be to dispatch on two arguments.
Avoid mixing S3 and S4: S4 methods ignore S3 inheritance and vice-versa.

S3とS4メソッドが混雑したコードを書かないようにしましょう。
ものすごい大雑把に言うと、クラスの型を定義するのがS4、しないのがS3です。

Exceptions

The coding conventions described above should be followed, unless there is good reason to do otherwise. Exceptions include legacy code and modifying third-party code.

基本的にはこの規則に従いましょう。ただ、レガシーなコードやサードパーティーのコードをいじるときは別だよ。

Parting Words

Use common sense and BE CONSISTENT.
The point of having style guidelines is to have a common vocabulary of coding so people can concentrate on what you are saying, rather than on how you are saying it. We present global style rules here so people know the vocabulary. But local style is also important. If code you add to a file looks drastically different from the existing code around it, the discontinuity will throw readers out of their rhythm when they go to read it. Try to avoid this.

常識と一貫性をもってコードを書きましょう。
コードスタイルのガイドラインを規定することの目的はコードを書く人同士が「どう表現するか」でなく、「何を言うか」に集中することである。ここに書かれていることが、すでに存在するコードとあまりにもかけ離れている場合、読み手のリズムを崩してしまうことになりかねない。それは避けよう。

以上!

んーすばらしい。
コメントに関する規則とか、とっても面倒そうだけど、社内で習慣にしていけば共有しやすいコードになること間違いなしですね。
Rのコードを書くときにこういったことをほとんど意識してなかったので、積極的に取り込んでいきます。