Home » Blog » Object Cesspool Anti-Pattern

Object Cesspool Anti-Pattern

Object pools are a common pattern in development. The canonical example is probably a database connection pool.

If objects returning to the pool are not validated, the pool can gradually fill with garbage objects, turning it into a cesspool of unusable objects.

How to Identify

The two easiest ways to identify if your object pool may become a cesspool:

  • Object pool does not have a “release object” method.
  • Overly simple “release object” method, which does not check object validity.

Both of these symptoms indicate that the object consumers are responsible for ensuring that the objects are valid.

Example

This is a pretty simple anti-pattern, but as a coder, I want to make sure I speak your language.

public class ConfigWriterPool {
	private Queue<configwriter> pool = new Queue<configwriter>();
 
	public ConfigWriter Get() {
		if (pool.Count &gt; 0) {
			return pool.Dequeue();
		} else {
			return BuildNewConfigWriter();
		}
	}
 
	public void Release(ConfigWriter writer) {
		pool.Queue(writer);
	}
}
</configwriter></configwriter>

Notice that the released config writers are not validated. Now everywhere the pool is used must test that the writer is open, etc., when this could be easily handled in one place.

Here is a better solution:

public class ConfigWriterPool {
	private Queue<configwriter> pool = new Queue<configwriter>();
 
	public ConfigWriter Get() {
		if (pool.Count &gt; 0) {
			return pool.Dequeue();
		} else {
			return BuildNewConfigWriter();
		}
	}
 
	public void Release(ConfigWriter writer) {
		if (IsReadyForUse(writer))
			pool.Queue(writer);
		else
			DestroyWriter(writer);
	}
 
	private bool IsReadyForUse(ConfigWriter writer) {
		/* check that the writer is not null, open, in the correct position, etc. */
	}
	private void DestroyWriter(ConfigWriter writer) {
		/* cleanup and dispose of the writer, it will not be used again */
	}
}
</configwriter></configwriter>