Coding Guidelines: Instance variables in views

Matt Wagner matt.wagner at redhat.com
Fri Aug 17 19:55:35 UTC 2012


On Fri, Aug 17, 2012 at 04:05:24PM +0200, Maros Zatko wrote:
> All magic in programming is magic at wrong place.

I was referring to mostly the Rails pattern of convention over
configuration. If you don't explicitly call render in a controller
method, Rails knows where to look. If you have a Cat model, Rails
assumes it's backed by "cats" in the table. And if you define an
instance variable in a controller, Rails makes it available to the
views.

> Relying on autovivified variables for passing values is
> 1) unsafe
> 2) unreadable
> 3) unmaintainable
> 4) spaghetti
> This can cause hell especially when refactoring so you lose track of
> which data comes from where. Then your variables became automagically
> initialised to nil, and then kaboom.

But if you lose track of what you're doing during a refactor, isn't it
_good_ if things blow up?

> Generally, you want to have variables of only one type.
> Since types in ruby are not lifted with nil, then
> by autovivification you have broken contract of returning correct data type.

I'm not sure what you follow by only one type. Do you mean that having
one variable that's an Array and another that's a Hash is bad?

> Nice example of this missbehavior might be returning nil instead of [] when
> method can't find any items in database (this is just an illustrative
> example).
> 
> So you have to check first if there is a nil in variable and only then you
> can use it (for example call 'each' method on that).

Yes, this can be annoying.

> When using locals, interpreter can much easier identify real source
> of problem,
> so you get error message stating that variable does not exist,
> instead of confusing
> error stating that you can't call something on nil, including much
> worse problem
> when that 'something' called on nil passes without problems but produces
> completely undesired result (i.e. hidden runtime bug & data corruption).

But with all due respect, "If you carelessly refactor code, the errors
you cause might be confusing" doesn't strike me as a compelling argument
to do something differently from most other projects and from the Rails
documentation.

> Convenience or (at least partial) correctness and safety?

I wouldn't use any of those terms to describe any of this, personally.
I'd say it's more a question of whether doing things our own unique way
that requires explicitly passing variables along into views is any safer
than using the Rails way that makes them automatically available.

> PS: If this sounds rude, I apologise, it was not meant like that.

Likewise -- I hope our difference of opinions on this doesn't seem rude.

-- Matt



More information about the aeolus-devel mailing list