Abstraction Rules
Rule of Three
If same code is used in three distinct locations, hoist it
- If not, then don't abstract away the code and leave them separately
How to think about correct abstraction layer
In order to abstract it away from your React code. Wrap it in a hook (or use a state manager) so that it only exposes state / actions. Then it won't matter anymore whether the data is transferred via WebSockets, REST API calls, or any other technology.
When designing this abstraction layer, make sure the application isn't aware of the underlying data storage/transfer technology. Perform a mental exercise by asking yourself, "Can I replace WebSockets with a regular REST API call without needing to make any changes in the rest of the app?" If the answer is "yes," then your abstraction layer is solid.
Never leak internals
Example 1: When you are using a vendor "nice messenger" to power your chat system, don't expose that nice messenger
is powering your chat system by including it in names
- Instead, name your chat system service
instant messenger
orsocial
to make it generic so any vendor or system can substitutenice messenger
when the underlying implementation needs to change
Example 2: exposing __typename
GQL metadata field onto the schema as a data type shape
What is __typename
__typename
is a reserved field in GraphQL that returns the name of the object type for a particular GraphQL object
- It is used to determine the type of any object in a GraphQL schema
Every object type in your schema automatically has a field named __typename
(you don't need to define it)
__typename
is useful is for instance for Apollo client since it uses it for client side cache entries and polymorphism. But should not be used for anything else
Rules
Customization if the enemy of abstraction
- One customization requirement may break the whole abstraction that exists