Last active
March 28, 2017 01:22
-
-
Save kenji-andoh/57c30164044db5ceb94a3cc89cdee2f7 to your computer and use it in GitHub Desktop.
immutable 解説のためのコード断片
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// クラスの内部状態が Mutable だったら | |
// あるクラスの"設定" を示す | |
class SomeSettings | |
{ | |
//あるクラスの何らかの動作モード | |
public enum BehaviourMode { A,B }; | |
//設定のモードの値 | |
public BehaviourMode Mode{ get;set;} | |
} | |
// SomeSettings を内部的に使用するクラス | |
class SomeClass | |
{ | |
// Mutable な内部状態を public にしちゃった | |
public SomeSettings Settings{ get; private set;} | |
public SomeClass( SomeSettings settings ) | |
{ | |
Settings = settings; | |
} | |
//設定のモードによって振る舞いが変わる。 | |
public void someMethod(){ /*...*/} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SomeClassUser | |
{ | |
// おやここでも mutable な内部状態を公開しちゃってる | |
public readonly SomeClass impl = new SomeClass( new SomeSettings{ Mode = SoumeSettings.BehaviourMode.A } ); | |
public void someMethod() | |
{ | |
// impl.someMethod() はモードAで実行するはずだ。 | |
// なにしろ自分で A モードとして初期化したんだからな。 | |
// 絶対だ。 | |
impl.someMethod(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
System.String str = "string"; | |
str.ToUpper(); //str の内容は変化しない | |
str = str.ToUpper(); //( str == "STRING" ) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
System.String s1 = "apple" + "pen"; | |
System.String s2 = String.Concat("apple","pen"); //2項の + 演算と同じ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
MyString s1 = new MyString("apple"); | |
MyString s2 = s1; | |
s2.Append("pen"); //あれ? s1 も s2 も "applepen" だ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment