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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Alberto Chiesa
  • 7,022
  • 2
  • 26
  • 53
  • Will static fields/data inside that class be of relevance? – Corak Sep 05 '18 at 09: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 – Slava Utesinov Sep 05 '18 at 09:01
  • 1
    @Corak no. Static fields are generally evil ;) – Alberto Chiesa Sep 05 '18 at 09: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. – Alberto Chiesa Sep 05 '18 at 09: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 05 '18 at 09:06
  • @A.Chiesa - sure, they tend to be abused, but used as intended, i.e. as information of the *class* and not of *instances of that class*, it's not inherently evil. ^_^ -- point is: with generic classes, `Thing` and `Thing` do **not** share static data. – Corak Sep 05 '18 at 09:09

1 Answers1

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.

Haytam
  • 4,643
  • 2
  • 20
  • 43