0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PGスタイルシリーズ:変数を初期化するタイミング

Posted at
1 / 7

スタイルを選ぶ理由

以下の事項を重視しての選択

  • ミスが起きにくい
  • インデントが深くならない(読みやすさに寄与)

基本姿勢:宣言的に書く

  • 宣言的に書く:どうやるか、ではなく何をやるか
  • 関数型に倣う:関数(値をもらって値を返す、副作用を極力減らす)の組み合わせで実装する

以降、便宜上C#を例にして話を進めます。


変数の扱い

  • 大原則:再代入しない
  • 宣言即初期化
  • インスタンス変数はreadonlyを付ける
  • そもそも、変数は少ない方がいい!

サンプル

public class MessageDisplayer
{
    string name;

    public Hoge(string name)
    {
        this.name = name;
    }

    public void DisplayMessage()
    {
        Console.WriteLine(GetProcessedMessage());
    }

    string GetProccessedMessage()
    {
        string ret = null;
        if (DateTime.Now.Minutes % 2 == 0)
        {
            ret = "Hello, " + this.name;
        }
        else
        {
            ret = "Hello, " + this.name + "!!";
        }
        return ret;
    }
}

改善版

public class MessageDisplayer
{
    readonly string name;

    public Hoge(string name)
    {
        this.name = name;
    }

    public void DisplayMessage()
    {
        Console.WriteLine(GetProcessedMessage());
    }

    string GetProccessedMessage()
    {
        string ret;
        if (DateTime.Now.Minutes % 2 == 0)
        {
            ret = "Hello, " + this.name;
        }
        else
        {
            ret = "Hello, " + this.name + "!!";
        }
        return ret;
    }
}

妥協なき改善版

public class MessageDisplayer
{
    readonly string name;

    public Hoge(string name)
    {
        this.name = name;
    }

    public void DisplayMessage()
    {
        Console.WriteLine(GetProcessedMessage());
    }

    string GetProccessedMessage()
    {
        return
            DateTime.Now.Minutes % 2 == 0
            ? "Hello, " + this.name
            : "Hello, " + this.name + "!!"
            ;
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?