8.1.  Anti-patterns

[ fromfile: antipatterns.xml id: antipatterns ]

Anti-pattern is a term first coined by [Gamma95] to mean a common design pitfall. An anti-pattern is called that because many design patterns are designed to avoid such pitfalls.

In other words, design patterns are commonly used solutions to anti-patterns, which are commonly faced problems. Some examples of anti-patterns are:

Figure 8.1.  Anti-pattern

Anti-pattern

In Figure 8.1, Customer includes member functions for importing and exporting its individual data members in XML format.

getWidget() provides a special a GUI widget which the user can use to enter data from a graphical application. In addition, there are custom methods for input/output via iostream.

This class is a model, because it holds onto data and represents some abstract entity. However, this class also contains view code, because of the createWidget() method. In addition, it contains serialization code specific to the data type. That is too much responsibility for a data model.

This is an example of the Interface Bloat anti-pattern (and perhaps a few others also).

The problems that interface bloat can lead to become immediately apparent when we implement other data model classes: Address, ShoppingCart, Catalog, CatalogItem, etc. Each of them also would need these methods:

This could lead to the use of Copy-and-Paste programming, another anti-pattern.

If we ever change the data structure, corresponding changes would need to be made to all presentation and I/O methods. Bugs introduced when maintaining this code are very likely. If Customer were reflective, meaning that it had the ability to determine useful things about its own members (e.g., How many properties? What are their names? What are their types? How do I load/store them? What are the child objects?), then we could define a generic way to read and write objects that would work for Customer and any other similarly reflective class. We will see an example of how to write more general-purpose code with reflection, in Chapter 16.