rocat
rocat

Reputation: 109

What is the advantage of using an Dynamic object over creating a class of that object?

I would like to preface that I have not used Dynamic Objects very often, and only recently came across this problem. I have a specific scenario that I will explain below, but I was wondering what exactly were the advantages of implementing a dynamic object compared to creating a class for that object.

I have a method that takes a dynamic object as a parameter. For the sake of length I will not post much code just enough to get the point across:

public static Tax GetEmployeeTax(string Id, Employee employee, dynamic inputObject)
{
var temp = new Employee();
//use the dynamic object properties
return temp;
}

In this case, inputObject will have properties that help identify the employee taxes without directly being related to the employee class. Primarily I have given the inputObject the following properties:

dynamic dynamicEmployeeTax = new ExpandoObject();
dynamicEmployeeTax.FederalTaxInfo = "Some information";
dynamicEmployeeTax.StateTaxInfo = "Some other information";

Are there any advantages to making this it's own class versus using a dynamic object? Are there any benefits one way or the other?

Upvotes: 5

Views: 1501

Answers (1)

beautifulcoder
beautifulcoder

Reputation: 11340

There are several reasons why you want to create a class:

  • Strong typing leverages the compiler to ensure correctness.
  • Every class that encapsulates data is like a contract. You can imagine how's used by examining the class.
  • You force the guy after you to read how it works. It is simpler to read class properties and image its utility.
  • It is a sign a bad planning and engineering. You are creating blobs of data instead of structured data sets that solve a specific problem. Think mud pits versus Lego blocks.

The list goes on ad infinitum. I think the consensus here is to avoid it. There are extreme rare cases where this is useful. For most, stick to contracts and coding to abstractions not implementation details.

Upvotes: 1

Related Questions