View Full Version : How to avoid store hardcoded field names?

30 Jul 2012, 9:16 AM
I'm looking for feedback on best practices for avoiding hardcoding store field names.

I'll use http://docs.sencha.com/ext-js/4-1/#!/guide/application_architecture as an example:

Ext.define('AM.model.User', {
extend: 'Ext.data.Model',
fields: ['name', 'email']

editUser: function(grid, record) {
var email = record.get( 'email' ); // hardcoded field usage

I have devised one scheme, among others that seems to work:

Ext.define('AM.model.UserModelNames', {
FIELD: { NAME: 'name', EMAIL: 'email' },
singleton: true

// The model becomes:
Ext.define('AM.model.User', {
extend: 'Ext.data.Model',
fields: [ AM.model.UserModelNames.FIELD.NAME, AM.model.UserModelNames.FIELD.EMAIL ]

// The editUser becomes:
editUser: function(grid, record) {
var email = record.get( AM.model.UserModelNames.FIELD.NAME );

What do you think?

Thanks. Thierry.

Tim Toady
30 Jul 2012, 10:05 AM
I see what you are trying to do, but I think it is an unnecessary level of complexity. While it is great to be able to redefine a field name by changing it in one place, hopefully a name was chosen that makes sense in the first place so you don't have to. Typically you will only have that string in a few places in different scopes, so I don't think the tradeoff with readability is worth it. When I read record.get( 'email' ) I immediately know what is happening. When I see a long namespaced variable, I have to think about it for a second. If the need for the redefinition is just for clarity, then you would want to change the property name in your singleton bringing you back to where you started. If the the issue is with data coming in from the backend changing, you can just define a mapping on your field so it knows where to get the new value and the front end won't care that it changed. Just my thoughts on the idea. Others may disagree.

31 Jul 2012, 12:57 PM
Thanks for you answer.

I was looking for how to avoid hardcoding these names for several reasons:

1) be able to uniquely search where specific fields are used. This is difficult on larger projects with fields that have generic names like "name", or "id". And in particular when there are several stores with identical names.

2) Be able to leverage refactoring capability in the IDE

3) Trying to emulate what I have been doing when programming in other languages where hardcoding is bad practice. Hardcoding, somehow ends up biting back at a later point in time, particularly when one needs to maintain someone else code