yanom blog

様々な技術について書きます

Actorクラスのメソッドをprivateにする必要があるか?

Akkaでテストコードを書いていて、privateメソッドの呼び出しに困ったので、そもそもprivateにする必要があるか調べてました。

その答えは以下にありました。
Unit testing private methods in Akka

There's really no good reason to make that method private. 

One generally makes a method on a class private to prevent someone who has a direct reference to an instance of that class from calling that method. With an actor instance, no one will have a direct reference to an instance of that actor class. 

All you can get to communicate with an instance of that actor class is an ActorRef which is a light weight proxy that only allows you to communicate by sending messages to be handled by onReceive via the mailbox. An ActorRef does not expose any internal state or methods of that actor class. 

That's sort of one of the big selling points of an actor system. 

An actor instance completely encapsulates its internal state and methods, protecting them from the outside world and only allows those internal things to change in response to receiving messages. 

That's why it does not seem necessary to mark that method as private.

---
そのメソッドを非公開にする正当な理由はありません。

あるクラスのインスタンスを直接参照している人がそのメソッドを呼び出せないようにするために、クラスのメソッドをプライベートにするのが一般的です。 
アクターインスタンスでは、そのアクタークラスのインスタンスを直接参照することはできません。

そのアクタークラスのインスタンスと通信するために取得できるのは、メールボックス経由でonReceiveによって処理されるメッセージを送信することによってのみ通信を可能にする軽量プロキシであるActorRefだけです。 
ActorRefは、そのアクタークラスの内部状態やメソッドを公開しません。

これは、俳優システムの大きなセールスポイントの1つです。

アクターインスタンスは、その内部の状態とメソッドを完全にカプセル化し、
それらを外部から保護し、メッセージの受信に応じてそれらの内部のものを変更できるようにします。

そのため、そのメソッドをプライベートとしてマークする必要はないようです。

これによるとActorクラスのメソッドは簡単には呼び出せないため、privateにする必要がないとされています。
このため、心置きなくメソッドをpublicにすることでテストコードが書くことができました。