Wednesday, December 19, 2012

Tackling Hard-Coded Values in Code and Example of 'Metadata as Data'


Many times we have to hard code values in our code to implement a business scenario to handle several comparisons. The most frequent case is when we compare master records' name field to implement a use case. 

In many cases the key business user may chose to change the name of a master record. 

What happens to the hard-coded part in the code then ? 
If you have made a comparison using a if-else statement then it fails to qualify the condition.

How to overcome this ? 

One way this problem can be solved is as follows.
Instead a creating a number of master entities, create two 'User or Team Owned' entities.

  1. A master entity, say A, to store the names of master entity types/tables that you want to maintain.
  2. A master entity, say B, to store the actual master records.


(This is an example related to one of the topics in my previous post where I discussed implementing 'storing metadata as data')

Entity A will contain the following mandatory attributes (apart from primary key, say 'A_id', which is auto-generated):

  • Name field
  • Key field (auto-generated;read-only for everyone)
  • Other necessary fields required by IT or business


Entity B will contain the following mandatory fields (apart from primary key, say 'B_id', which is auto-generated):

  • Name field
  • Key field (auto-generated;read-only for everyone)
  • Other necessary fields required by IT or business


There will be a 1:N relationship between A:B
There will be a parental relationship in B to create a hierarchy if needed (again this is as per requirement)

Advantages

1. Reduced overhead of creating multiple master entities in initial or later stage of maintenance.
2. One generic query to retrieve all master records.
3. Since key is auto-generated and read-only the comparison in code should be through keys rather than by names of master records.
4. In case the number of master records is more and keys may seem cryptic for developer then you can maintain a mapping entity where you can again generate a friendly name for each key to compare. You can also store the primary key guid of the record in the mapping entity.
5. For already present master entities (OOB), you can create a attribute for 'key' field and
 then opt to map the same in mapping entity.
6. One stop view for all master records.
7. writing sql queries becomes easy since you just have to remember a set of master entities' 
 names and also no hard-coded values required.
8. Since the entities are "User or Team Owned' you can limit the view of the master records 
 to various Business Unit levels by adjusting ownership.

There may be many more advantages which you will discover when you implement.

The underlying idea is that "to make something flexible, you have to make something else rigid" in nature.

Cheerios till my next post !