Information Expert Principle

(1) Problems

What are the general principles for assigning responsibilities to objects?

(2) Scheme

Assign responsibilities to the class that has the information necessary to perform a responsibility, the information expert.

(3) Analysis

The principle of information expert is the most basic principle of object-oriented design. In plain English, a class does what it’s supposed to do. At system design time, responsibilities need to be assigned to classes that have the information needed to fulfill this responsibility. The information expert principle corresponds to the single responsibility principle in the object-oriented design principle.

The sample

public class AES {

    public string Decrypt(string ciphertext, string salt) {
        throw new NotImplementedException();
    }

    public void Post(string url, string cleartext, Dictionary<string.string> heads) {
        throw newNotImplementedException(); }}Copy the code

AES Decrypt class. The Decrypt method is a decryption method that needs to pass ciphertext and salt. This class contains another method Post to send plaintext data to a URL.

It is obvious that the Post method should not be in the AES class, because the responsibilities are not properly assigned. The decryption class should focus on the decryption action, and the Post method that sends the data should be wrapped in a separate class. Here are the solutions:

public class AES {

    public string Decrypt(string ciphertext, string salt) {
        throw newNotImplementedException(); }}Copy the code
public class PostUtil {
    public static void Post(string url, string content, 
        Dictionary<string.string> heads) {
        throw newNotImplementedException(); }}Copy the code

After a simple modification, the AES class becomes the information expert for AES decryption, and the PostUtil utility class becomes the information expert for sending data.