Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 997
rocat Avatar asked Nov 10 '22 06:11

rocat


1 Answers

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.

like image 116
beautifulcoder Avatar answered Nov 14 '22 22:11

beautifulcoder