[webkit-dev] When to use "auto"? (I usually consider it harmful)

Geoffrey Garen ggaren at apple.com
Thu Jan 2 14:27:18 PST 2014


> We tend to avoid local write-once-read-once local variables, i.e. we tend to prefer
> 
> {
>    setSize(optimalSize());
> }
> 
> to
> 
> {
>    CGSize newSize = optimalSize();
>    setSize(newSize);
> }
> 
> But the up- and down-sides of this are the same as those of using auto.

I think I basically agree with Phil here, and slightly disagree with your premise that the upsides and downsides are truly the same:

(1) The downside to explicit declaration in this case is greater because it requires an extra line of code.

(2) The upside to explicit declaration in this case is lesser because the value is used only once, and in a guaranteed trivial way (just passing it somewhere else).

> Do you think we should also encourage use of write-once-read-once locals for the same reasons?

No, not in general.

However, in rare cases, I think the balance shifts, and I do prefer an extra line of code for write-once-read-once variables. For example:

int documentWidth = screenWidth(); // The size of the document is equal to the size of the screen because…
layout(documentWidth);

In this case, the caller of screenWidth() is changing its meaning, and I slightly prefer to call that out.

Geoff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.webkit.org/pipermail/webkit-dev/attachments/20140102/0c0e6df3/attachment.html>


More information about the webkit-dev mailing list