3

I want to eliminate usage of magic strings in these:

BindingUtils.bindProperty(obj1, "propertyName", obj2, ["childObj", "anotherProperty"]);

or

var ddl:DropDownList = new DropDownList();
ddl.labelField = "propertyName";

it would be sweet to just type something like:

ddl.labelField = GetPropertyName(ComplexType.propertyName);

It would allow easy refactoring and would eliminate runtime errors when property name changes.

Any ideas?

mizi_sk
  • 1,007
  • 7
  • 33
  • I don't understand how your suggested change in nomenclature would eliminate runtime errors related to refactoring. – JeffryHouser Mar 18 '11 at 16:06
  • If I'd refactor property name "propertyName" with IDE's rename, say to "propertyName2", it would find in calls of function 'GetPropertyName' and would change it... however if I refactor/rename now, IDE wouldn't recognise this magic string as property of the class that I just changed property name in. Simply refactoring/renaming property creates runtime error. – mizi_sk Mar 18 '11 at 17:50

3 Answers3

4

Not sure whether I understand your problem correctly. You can easily define static constants in a separate class to eliminate all magic string.

// In class ConstantContainer

public static const PROPERTY_NAME:String = "propertyName";

// In anywhere else
ddl.labelField = ConstantContainer.PROPERTY_NAME;
taskinoor
  • 45,586
  • 12
  • 116
  • 142
  • I think it doesn't eliminate usage of magic string, it only moves it to another class :/ It breaks after refactoring of property name. – mizi_sk Mar 18 '11 at 15:29
  • 1
    It have some benefits. It prevents typo which may cause a run time crash. And if you need to use magic string, say in 20 place, then if that string require changing then you to need find all 20 places. But if you use a single class, then obviously you need changing in just one place, which is less less error prone. – taskinoor Mar 18 '11 at 15:31
1

'magic strings' are needed. Remember that this is a dynamic language that has pros and cons to everything. This is one of those cons.

There are a few things you can do to limit error like static properties.

J_A_X
  • 12,857
  • 1
  • 25
  • 31
0

The Stack Overflow discussion on the similar topic with some ideas that can be of interest to you:

Use of object vs string vs enum

Community
  • 1
  • 1
JabbyPanda
  • 872
  • 5
  • 13