Home:ALL Converter>Cyclic dependencies between classes

Cyclic dependencies between classes

Ask Time:2013-04-04T22:16:08         Author:M0rgenstern

Json Formatter

I am having troubles with dependencies between two classes. The problem is the following:

I got two classes, Timestamp and Exception. Exception is abstract and all possible exceptions derive from this abstract class. Every exception has a timestamp to tell when the exception was thrown. So exceptions need to include (in the language i am using it is called import) the timestamp class. But wen working with timestamps errors can occur, so that exceptions are thrown. Therefor the timestamp class has to import the exception classes.

And there is my cyclic dependency. Now my actual question is (and this is why it is independent from the language): What would be a proper design in such a case to avoid cyclic dependencies? I fail to solve this problem as I cannot figure out a solution to have this classes as independent as they are now but without the cyclic dependency.

Author:M0rgenstern,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/15815780/cyclic-dependencies-between-classes
user932887 :

I'd drop the whole \"Exception-has-timestamp-property\" idea. Exceptions should indicate exceptional behavior and nothing else. Perhaps you want to do some logging? It makes more sense for the logger to keep track of the timestamps and pair them with their appropriate exceptions.\n\nAsk yourself what the job of an exception is. Obviously, an exception's job is to get thrown. Does this depend on when it gets thrown? Nope. Does the exception care about this at all? Nope. Does something else care? Yes, the exception logger. But, since the logger is the one who cares about timestamps, the logger should also get those timestamps, and do stuff with them. It's part of its job, after all. And, in a proper design, the logger does not outsource parts of his work to exceptions.\n\nCyclic dependency solved.",
2013-04-04T14:51:13
yy