For a fun project I'm trying to implement the BitTorrent spec, and right now I'm working on the BEncoding portion of it.
The encoding basically can encode from int/string/dictionary -> string for transmission. I've got all of the different encodings written/tested/working as overloaded Encode(...) methods and I've got the individual decode methods written/tested/working as DecodeString(...), DecodeInt(...) etc.
I can't figure out a way to have 1 Decode method for all decodings, in order to keep the API for the encoding/decoding as clean as possible (2 public methods, tops, for the time being).
Note that I have a method that can get the type of result that the decoded string will have.
Client code, right now would have to look something like this every time they want to decode a message:
string s = ...; // Encoded string
Type t = Encoder.GetDecodedType(s);
if (t == typeof(int))
process(Encoder.DecodeInt(s));
else if (t == typeof(string))
process(Encoder.DecodeString(s));
else if (t == typeof(Dictionary<string, string>))
process(Encoder.DecodeStringDictionary(s));
else if (t == typeof(Dictionary<string, int>))
process(Encoder.DecodeIntDictionary(s)):
and I'd like to be able to clean that up to be more like:
string s = ...; // Encoded string
process(Encoder.Decode(s));
where, in both cases the process(...) would likely be overloaded functions at the client end taking the 4 types of decoded values.