Nov 28, 2011

Internal knowledge

There is one way to introduce problems in the code, which I'd like to discuss today.

Suppose you have a module, which creates database records. The module has an integer field with a set of flags (each flag is a single bit in the integer). Flags 2 and 4 mean thing X. Flags 2 and 6 mean thing Y. Flag 1 must be used only together with flag 3 or flag 5. The module knows how to manage those flags and what to make of them. Let's name it “module 1”.

Now imagine another module (“module two”). It needs to get information from the first module, that matches certain criteria. Module one would be able to provide that information by matching flags.

Here is the tricky part. The most obvious solution would be simply to query the database directly from module two. Proper solution for module two would be to ask module one for the information. Querying module one's tables using a combination of flags is wrong. Such query uses the internal knowledge of module one outside of the module one. Thus, the implementation of module two becomes dependent on the implementation of module one.

Do you see potential problems here? If module one changes, module two breaks. This "solution spread" introduces unnecessary dependencies between logically separate modules, which is neither necessary, nor good.

A proper way would be to create an API in the module one that returns records, required by module two. If the internal implementation of module one changes, module two will work because all internal proceedings happen inside a single place.

Next time, when you are about to introduce cross-module dependencies, think of minimising them in favor of API usage.

This article was inspired by a in TYPO3.

No comments:

Post a Comment