When and how to use attribute based programming

584 views Asked by At

I have seen many ORM mapping tables/columns to corresponding classes in C# using Custom Attributes. Even entity framework do in a similar way. I am trying to figure out when and how to use Attributes to make my solution more manageable efficient and scalable.

Some of the problem statements I assume it might be useful are 1. Mapping Tables/Views to Classes

Table Employee{ Name, Age, salary, height}...
class Employee{Name, Age, Salary, Height}...
  1. Mapping KeyValue pair/dictionary to class

Table

PersonAttributes{
Column1, Column2
"Age", "25"
"Salary", "3000"
"Weight", "80"
...
}

Class Person{
string Name;

[MapToTable(TableName="PersonAttributes", Key="Column1", Value="Column2",DataType="Int", Field="Age", )]
int Age;

[MapToTable(TableName="PersonAttributes", Key="Column1", Value="Column2",DataType="Int", Field="Weight", )]
int Weight;

[MapToTable(TableName="PersonAttributes", Key="Column1", Value="Column2",DataType="Int", Field="Salary", )]
int Salary;
}
1

There are 1 answers

0
Matías Fidemraizer On

Metaprogramming is useful to decorate your assembly members (i.e. assemblies, types...) and type members to provide hints on which your system can do assumptions to perform certain actions or behave in some specific way.

Actually, in .NET, attributes are a way to provide more semantics than what modifiers already do. For example:

  • public, private, internal, protected...
  • implicit, operator, overrides...

Later, using reflection, you can introspect your assembly and assembly members to set up an enviornment based on them.

For example, there's the [Required] data annotation to tell a validation framework, OR/M or serializers that a given class property should mandatorily contain a value.

In conclusion, I wouldn't say that attributes are just there to describe mapping semantics, but they're a powerful tool to implement conventions or a declarative approach to provide hints about how your system should work.