5

I'm designing a class capable of deserializing some file, and I'm wondering what would be the implications of this two options:

// option 1 - generic class
public class XmlConfigurationManager<T>
{
    public T ReadConfigurationAndWriteDefault(string configurationPath, Func<T> defaultConfiguration)
    {
        ...
    }

    public T Deserialize(string configurationPath)
    {
        ...
    }
}

// option 2 - generic methods in non generic class
public class XmlConfigurationManager
{
    public T ReadConfigurationAndWriteDefault<T>(string configurationPath, Func<T> defaultConfiguration)
    {
        ...
    }

    public T Deserialize<T>(string configurationPath)
    {
        ...
    }
}

I can't seem to find any hint on the differences between the two.

How do this two options compare? There would be any difference? Are there any notable points to keep in mind when evaluating the design?

6
  • Will static fields/data inside that class be of relevance?
    – Corak
    Sep 5, 2018 at 9:01
  • 3
    At first variant, type parameters for both methods always will be equal and are determined at instance creation, for second one - they can be different and are determined at calling Sep 5, 2018 at 9:01
  • 1
    @Corak no. Static fields are generally evil ;) Sep 5, 2018 at 9:03
  • 1
    @Slava Utesinov. Yep, but I'm expecting to have them called by the ReadConfigurationAndWriteDefault entry point. I'm mainly interested in JIT differences, performance (I don't expect this to be a thing) or design considerations. Sep 5, 2018 at 9:05
  • It depends. If you want Manager to be related with Type, then you use 1 option. If you want more flexible, helper-like methods, then you use option 2.
    – Renatas M.
    Sep 5, 2018 at 9:06

1 Answer 1

6

I can think of one difference right away:

  • Generic class: You'll have to instanciate an object with a certain type for every type of file you want to deserialize to. Although you'll be able to hold type-specific parameters in case you use the instance long term.
  • Generic method: You'll instanciate the class once and use the generic method for as much types as you want (assuming you'll handle the difference of types, if any).

For example, if you want to simply deserialize the content of a file (json) to an object, a generic method would be enough as the needed type doesn't change anything.

Not the answer you're looking for? Browse other questions tagged or ask your own question.