I was recently tasked with thinking about returning optional tracing information about the execution of a complex algorithm. It's the kind of data you need to analyse the inner workings - a bit like logging of intermediate results but being programmatically available to the caller and optional.

I only had rather bad ideas that involve too many changes to the core algorithm, like passing additional parameters all the way through. Also I couldn't find anything on the web.

  • 2
    I'd just "log" normally, but to a String or StringBuffer or whatever your system supports, then make that available. – user949300 Jun 16 at 19:47
  • What precisely is your idea about "additional parameters"? What kind of parameters? Why? – Doc Brown Jun 16 at 19:53
  • 2
    Write unit tests and use log levels appropriately. – svidgen Jun 16 at 19:54
  • Svidgen since the unit is the complex algorithm you may write tests but they wouldn’t be unit tests. – gnasher729 Jun 17 at 5:19
  • thanks - I like the logging to StringBuffer. So I guess I'll try making them ThreadLocals to be able to use them in production with appropriate log-levels. I thought about logging but it never occurred to me to simply use a thread local string-appender. :facepalm – fricke Jun 17 at 8:38

Adding a parameter is not changing an algorithm.

An example: Your complex algorithm is Quicksort. Usual call:

Quicksort (array, size)

As the caller I want to know for some reason in which order you created partitions. So I declare

Class partition { int left; int right; int pivot; }

I change the prototype to

Quicksort (array, size, vector <partition> *partitions = nil)

You add code that adds information to the partitions vector if it is not nil. And I call your code, optionally passing a partitions vector, and if I do so I can then examine the results at runtime. That’s what you were asked to do.

If your algorithm works by creating an object describing the problem and then calling a method that solves the problem described, then the logging / feedback parameter can be stored as an instance variable and doesn’t need passing around.

| improve this answer | |
  • 1
    Hi, right it's not changing the algorithm, but making it more difficult to read - differentiate what's essential and what's a cross-concern. It also adds overhead, since it needs to be forwarded to all parts. – fricke Jun 17 at 8:33
  • Well, that’s life. – gnasher729 Jul 17 at 21:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.