开发者

C# constructor using a dynamic vs Interface as a parameter

开发者 https://www.devze.com 2023-03-08 19:38 出处:网络
In the benefit of creating clean decoupled code in c# I was hoping to get some feedback on using a dynamic parameter to construct objects.Typically I believe you\'d create an interface and use the int

In the benefit of creating clean decoupled code in c# I was hoping to get some feedback on using a dynamic parameter to construct objects. Typically I believe you'd create an interface and use the interface as the contract, but then you hav开发者_运维百科e to create interfaces for all your classes which I think is kind of icky...

So, my question is what are the pros and cons of doing something like this:

class Class1
{
    public string Description { get; set; }
    public string Name { get; set; }

    public Class1(dynamic obj)
    {
        Name = obj.Name;
        Description = obj.Description;
    }
}

vs

class Class1
{
    public string Description { get; set; }
    public string Name { get; set; }

    public Class1(IClass1 obj)
    {
        Name = obj.Name;
        Description = obj.Description;
    }
}


Pros of the interface:

  • The compiler will tell you if you're using the wrong kind of argument
  • The signature of the constructor tells you what's required from the parameter

Pros of dynamic:

  • You don't need to declare the interface or implement it
  • Existing classes with Name and Description properties can be used with no change
  • Anonymous types can be used within the same assembly if they have Name and Description properties

Personally I typically use C# as a statically typed language unless I'm interacting with something naturally dynamic (e.g. where I'd otherwise use reflection, or calling into COM or the DLR)... but I can see that in some cases this could be useful. Just don't over-do it :)


In both scenarios for the method to function properly as expected the objects being passed into the method must have your Name and Description properties.

My concern is that the best practice for using a dynamic as you have, you would need to provide additional method documentation to ensure other programmers or even yourself six months from now know the expected data contracts that must be present on the object being passed and even then you really should write error handling into your method to ensure it functions as expected when that contract is broken.

Does all these potential gotchas out weight the hypothetical gain of not writing an interface which in the example given would be literally only a 5 basic lines of code, which would then do everything your forcing yourself to do manually.

Assuming you want to follow best practices which lead to well documented and easy to read code. I would lean towards using an interface for this purpose.

0

精彩评论

暂无评论...
验证码 换一张
取 消