renno
renno

Reputation: 2827

Why insert the type when using DS.attr(type) in Ember

In ember documentation it says the following for the method DS.attr():

By default, attributes are passed through as-is, however you can specify an optional type to have the value automatically transformed

If you go to the transform method documentation it says the following:

You can specify that you would like a transform to run for an attribute by providing the transform name as the first argument to the attr method. Ember Data supports attribute types of string, number, boolean, and date, which coerce the value to the JavaScript type that matches its name.

So my question is: is it bad to explicitly insert the type of the attribute? It seems it forces some kind of cast as mentioned after (quoted below). So it could have some performance decrease (almost nothing).

The boolean transform can handle values other than true or false. The strings "true" or "t" in any casing, "1", and the number 1 will all coerce to true, and false otherwise.

The only reason I see to insert the type is to make it easier to read in your model, but that can be done in a comment as well...

Upvotes: 0

Views: 167

Answers (2)

pbanka
pbanka

Reputation: 726

I tend to believe this is a bad practice unless you have an API that is very buggy that you do not control and will sometimes deliver an attribute with varying types for the same field. In general, an API should be reliable in how it delivers types. Setting the type in Ember causes it to do type-coercion which is never a good idea in JavaScript because JavaScript is surprisingly terrible at type-coercion.

As for the fact that this documents your types, I agree that's a good idea. However, in modern Ember TypeScript is a far better tool to document types because the documentation is actually enforced.

Upvotes: 0

Justin Niessner
Justin Niessner

Reputation: 245399

No, it's not bad to insert the type of the attribute. It's actually good.

While there may be some negligible performance decrease when loading data into the Store, you get the added benefit of consistent types when working with your models regardless of what your API may return.

If you were to only use comments to specify types, you may be telling other developers what type is expected to be in the model, but the API could return anything it wants. In that case the expected type and the actual type may not match.

Upvotes: 1

Related Questions