I have used the technique I described in self-registering methods in several of my classes, and it has found its way into some of my libraries – all is good.
Then I hit upon a situation where I had a new method to add to a library containing self-registering methods, but this method was an odd case – one that I would only ever use in the class I was writing. I didn’t want to clutter up my library with methods that would only ever be used by one class. What to do?
Fortunately, the code is easy enough to extend to handle one-offs. Going back to the example given in my previous post, the library would contain something like this
Public int Parse(string id, LetterInfo parms) { if (_functionMappings.ContainsKey(id)) { var result = _functionMappings[id](this, parms); } ... return result }
And would be called by an outside class with
Note: the g in the code below should be quoted (“g”), but, for some reason, WordPress does not like that.
var parseResult = MyLibrary.Parse(g, someLetterInfoData);
Now I need to have my outside class deal with a special case: where the letter to parse is “8” – but I will never do this in any other code: this is only time I ever foresee parsing a numeric value. This is kind of one-off situation can be handled by adding a little code to the Parse method in MyLibrary:
public int Parse(string id, LetterInfo parms, Func callBack = null) { if (_functionMappings.ContainsKey(id)) { var result = _functionMappings[id](this, parms); } else if (callBack != null) { result = callBack(id, parms); } ... return result }
So, when we find a reference to a method that is not registered, execute the function provided as the callback parameter to see if it can deal with the reference.
The call to Parse would look like
var parseResult = MyLibrary.Parse(g, someLetterInfoData, (i, p) => { return LocalParse(i, p); });
and the callback method would be
private int LocalParse(string id, LetterInfo parms) { if (id == "8") {...} ... return result; }
This way, the processing for the odd-ball case of “8” remains in the code that uses it. All the other “common” functions remain, undisturbed, in the MyLibrary library object.
Even better, though, is to include the callback method in the parms object so you don’t have an extra parameter hanging about in the code:
public class LetterInfo() { ... Func Callback { get; set; } ... } public int Parse(string id, LetterInfo parms) { if (_functionMappings.ContainsKey(id)) { var result = _functionMappings[id](this, parms); } else if (parms.CallBack != null) { result = parms.CallBack(id, parms); } ... return result }
and call with
someLetterInfoData.CallBack = (i, p) => { return LocalParse(i, p); }; ... var parseResult = MyLibrary.Parse(g, someLetterInfoData);
(again, the g should be quoted.)