Sequential coupling

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
m
m (Reverted edits by Ebybymic (Talk); changed back to last version by Bertrand Roussel)
 
(One intermediate revision by one user not shown)

Latest revision as of 03:23, 25 November 2010

This anti-pattern occurs when a class requires its methods to be called in a particular order. This can lead to problems especially if the contracts for these methods are not properly documented and do not tell clients the order in which methods should be called. Overall, it just makes a class a lot harder and more error-prone to use.

This kind of anti-pattern can often be spotted by looking at method names. Names which include the words start, begin or end may indicate sequential coupling.

Examples

Imagine we are writing a class to read data from a file line by line. We make a startRead() method that opens the file and makes it ready for reading. The readLine() method then allows clients to read from the file line by line but only works if the file has been opened; that is if the startRead() method has been called. When the client no longer wants to read from the file, it needs to call the endRead() method that closes the file. If this is not done, the file remains open, wasting resources.

The methods of our class need to be called in a very particular order. For example, we can't read from a file that's not open, we can't close a file that's not open and we can't open a file that's already open. Clearly, this is creating more work and confusion than necessary on the client side. It would be better if we encapsulated these conditions in the class itself rather than requiring clients to keep track of the state of the file.

Liabilities

  • Sequential coupling makes using a class harder and more error-prone for clients. It is easy to forget to call methods in the right order, potentially leading to bugs in the program.
  • The client using the class may need an understanding of how the class works internally and at the very least needs to know the protocol for using the methods of the class.
  • Clients are coupled to the class in that if the sequence of method calls changes in any way, clients will be affected by that change.

Related design heuristics


Personal tools