Re: Numeric constants vs enumerated strings

On Wednesday, February 15, 2012 at 3:15 PM, Dominique Hazael-Massieux wrote:

> Le mercredi 15 février 2012 à 15:08 +0100, Anne van Kesteren a écrit :
> > On Wed, 15 Feb 2012 14:57:00 +0100, Harald Alvestrand  
> > <harald@alvestrand.no (mailto:harald@alvestrand.no)> wrote:
> > > *This is a call for help from the WEBRTC working group.
> > > We are defining a new API
> > > (http://dev.w3.org/2011/webrtc/editor/webrtc.html) <about:blank>which
> > > has a number of cases where it needs to use arguments, or expose state
> > > variables, that can take only a limited set of values.
> >  
> >  
> >  
> > Unless there are strong ties to certain legacy APIs I would suggest using  
> > strings. They are easier for developers to author, easier for developers  
> > to maintain, easier in the future to extend, and have practically no  
> > drawbacks.
>  
>  
>  
> There are strong ties, in the sense that the said API would be exposing
> a readyState property (similar to XMLHttpRequest, HTMLMedia, etc).
>  

I'm not sure there is any relationship to the internal state of an object and using object.SOME_HARD_TO_REMEMBER_AND_TYPE_THING… specially when you can just type "thing".  

The ALL_IN_UPPER_CASE pattern is a bad legacy carry over from the old DOM specs, which have their ancestry in Java. It made sense in Java land, because Java land had some pretty intelligent IDE tools that could automatically do magic introspection into a class and work out what thing you were talking about… Javascript lack such tools (and java class-style hierarchies)… hence constants just end up being annoying and people just end up writing the constant's value itself.  

For instance, I've never seen an XHR tutorial that says:  

if (xhr.readystate === XMLHttpRequest.DONE){
    
}

Old java-style constants suck; please be kind and avoid them :)  

The WebIDL spec also says warms:

"Warning
Constants have in the past primarily been used to define named integer codes in the style of an enumeration. The Web platform is moving away from this design pattern in favor of the use of strings. Specification authors who wish to define constants are strongly advised to discuss this on the public-script-coord@w3.org mailing list before proceeding."  



--  
Marcos Caceres

Received on Wednesday, 15 February 2012 17:05:48 UTC