How to communicate persistent content to developer working on consuming classes
Let's say we have a business object, let's call it a Foo
, which contains an ordered list of Bar
s. We pass this Foo
around as XML.
We have a class which deserializes a Foo
XML node (FooXMLDeserializer
) which itself uses a class which de开发者_如何学运维serializes the child Bar
XML nodes (BarXMLDeserializer
).
Now, I'm adding some functionality to the BarXMLDeserializer
that maintains some state such that if FooXMLDeserializer
is called on two separate Foo
nodes without reseting the BarXMLDeserializer
's state, the results may be invalid. BarXMLDeserializer
does not know when it has processed the final Bar
in a Foo
.
Is there some way that I can design the BarXMLDeserializer
class to communicate to developers working on consuming classes that it has state and must be reset for each Foo
?
Further info:
- My change solves a minor enough problem in our code that I won't be able to convince my manager to let me spend X days redesigning the whole system to nicely handle this case.
- If it matters,
BarXMLDeserializer
keeps is state in aBarStateTracker
class which is internal to it. - Programming in C#, but looking for a more general solution.
Thanks.
Expose your serializer only as a static method:
// no public constructor, etc
var deserializer = BarXMLDeserializer.CreateNew();
Then, when you have finished deserializing data, mark a field in your object. If the field is set, throw an exception if the same instance is used to deserialize more data when the deserialize method is called.
if(IsInstanceExhausted)
throw new InvalidOperationException("You must use a fresh instance.");
They'll figure it out after their first exception. In addition, mark your class as IDisposable so that code naturally uses using statements:
using(var deserializer = BarXMLDeserializer.CreateNew())
{
}
The list goes on of additional ways. ALTERNATIVELY, you could simply design your Deserializer to clear it's state or reset after a deserialization attempt, or to clear the state at the beginning of a deserialization attempt.
精彩评论