Friday, 30 October 2020

OOP Object interfaces and decomposing the blob class

Introduction

The interface of the object should provide meaningful services to clients. A problem arises when too many jobs are assigned to one class of object for example a client object:

class Client {

public:

    void Authenticate();

    void SendMessageToChat();

    void JoinChatRoom();

    void LeaveChatRoom();

    void JoinGroup();

    // etc

}

Looks fine and useful but why does the client contain the information to manage groups and chat rooms?

Interface beauty and implementation blob

This object looks fine from the interface point of view and incredibly useful in that all the functions you need are in one place. But, it suggests a problem with the implementation behind the interface. The problem doesn't seem to be the interface semantically/syntactically but a problem in terms of information.

Since the Client's interface is the set of operations on the Client object, why does the client object contain the information to manage chat rooms, groups and all the other objects? The Client object holds way too much information about the rest of the system. This is known as a "God class" or "Blob".

Decomposing the blob

A solution for this would be to seperate the client object into further important concepts:

class Server;
class User;

class Client {

public:

    void Authenticate(Server& server);

}

class ChatRoom {

public:

    void Join(User& user);

    void Leave(User& user);

    void Post(User& user, string message);

}

class Group {

public:

    void Join(User& user);

    void Leave(User& user);

}

Here the information is spread across meaningful objects in the system which is more desireable since now each object can be thought of and maintained individually (for example assigning multiple people on each object instead of all on the client object).

Paraphrasing the collaboration, Subject not object

Additionally there error made in the design in the original client class is that the client object is not viewed as the subject of the methods calls. For example; the object method SendMessageToChat() could be paraphrased as "tell the client to send a message to the chat" or "the client can send a message to the chat" but in these phrases the subject is Chat not Client. This is a confusing notion however its simplifed if you remember that an object is the subject of its methods and wording the class collaboration appropriatly. The original client seems to be a functional decomposition instead of a data abstraction view.

Conclusion

When creating objects, always remember that the object is the subject and to carefully paraphrase the collaborations.

No comments:

Post a comment

Abstraction function, representation invariant

Abstraction Function & Rep invariant The abstraction functions map values in a class to the abstract concept's required values. The ...