Dear KaVE committers,
Sven and I realized that the project currently contains many different approaches to implement a ToString method and some are more helpful than others. Many classes do not contain a ToString implementation at all.
There was consensus that a ToString implementation is generally helpful for debugging, so we discussed pros and cons of the different approaches. Today, I'd like to announce the result of this discussion: the policy for new ToString methods in the KaVE project.
There are four general rules:
1) ToString is to be used for debugging purposes only, never rely on it to access information. Consider it to be in a preliminary format that can change anytime.
2) The output of ToString should allow the developer to decide if two objects are equal. Make sure that all relevant information is contained. Good candidates for inclusion are also the (runtime) type name and the computed hash code. -- If you override ToString and decide to leave out information available for an object, make sure that this information is really irrelevant for the developer. (*)
3) The output of the ToString method should be formatted in multiple lines. Different views exist on this so this is no strict rule. Just consider that the output is easier to read when printed and that even the debugger can display formatted strings (by clicking the magnifying glass).
To make it easier for you, I prepared a generic ToString extension method that is based on reflection. It generates output that complies to all rules. You can use it by simply invoking "ToStringReflection()" on the object in question.
ToString methods don't need to be tested, but if you prefer to do it anyways then a custom assert exists exactly for that purpose (AssertToString.Reflection(sut)). It checks that the output of ToString conforms to the expected output of the reflection approach.
I'd like to encourage a discussion about this policy. State your doubts if you disagree or if you would like to extend these rules!
best
Sebastian
(*) An example in our codebase is the naming classes, which implement the flyweight pattern. Each class contains a static factory that is only used for instantiation and -therefore- left out in the ToString implementation.
--
Email:
pro...@st.informatik.tu-darmstadt.de
Phone:
+49 (0) 6151-16-21367
Fax:
+49 (0) 6151-16-22361
Software Technology Group
Technische Universität Darmstadt
Hochschulstr. 10, S202|A202
64289 Darmstadt, Germany
http://www.stg.tu-darmstadt.de/staff/sebastian_proksch