I am designing a class that stores (caches) a set of data. I want to lookup a value, if the class contains the value then use it and modify a property of the class. I am concerned about the design of the public interface.
Here is how the class is going to be used:
ClassItem *pClassItem = myClass.Lookup(value); if (pClassItem) { // item is found in class so modify and use it pClassItem->SetAttribute(something); ... // use myClass } else { // value doesn't exist in the class so add it myClass.Add(value, something); }
However I don't want to have to expose ClassItem to this client (ClassItem is an implementation detail of MyClass). To get round that the following could be considered:
bool found = myClass.Lookup(value); if (found) { // item is found in class so modify and use it myClass.ModifyAttribute(value, something); ... // use myClass } else { // value doesn't exist in the class so add it myClass.Add(value, something); }
However this is inefficient as Modify will have to do the lookup again. This would suggest a lookupAndModify type of method:
bool found = myClass.LookupAndModify(value, something); if (found) { // item is found in class ... // use myClass } else { // value doesn't exist in the class so add it myClass.Add(value, something); }
But rolling LookupAndModify into one method seems like very poor design. It also only modifies if value is found and so the name is not only cumbersome but misleading as well.
Is there another better design that gets round this issue? Any design patterns for this (I couldn't find anything through google)?