samedi 16 septembre 2017

Avoiding switch statements due to database types

I am currently working on a project with a database where i have several tables that contain only type enumerations. Things like:

OrderStatus:
ID | Description
1  | Open
2  | Shipped
3  | Canceled
...

When i get the types from the database and want to check them in code this usually results in a switch statement, which is somewhat hard to maintain especially when new items are added to the table.

switch(order.OrderStatus.ID) {
    case 1:
        handleOpenOrder();
        break;
    case 2:
        handleShippedOrder();
        break;
    case 3:
        handleCanceledOrder();
        break;
    default:
        break;
}

Normally one would use inheritance to solve this but in this case i have to check for the type of value returned from the database at some point.

I currently get the orderstatus as a normal orderstatus entity from the database. Is there a way for an ORM (NHibernate) to automatically cast the entity to a more specific obejct? Like for instance an OrderStatusOpen class?

Aucun commentaire:

Enregistrer un commentaire