[webkit-dev] Should we recommend explicit constructors as part of WebKit style?

Maciej Stachowiak mjs at apple.com
Tue Sep 28 16:31:23 PDT 2010


On Sep 28, 2010, at 4:26 PM, David Levin wrote:

> This came up before: https://lists.webkit.org/pipermail/webkit-dev/2010-May/012873.html but I'd like to understand it a bit better.
> 
> It feels there were two points of view:
> Use explicit only when necessary to prevent an undesirable implicit conversion like int to vector.
> Use explicit except when it is desirable to allow an implicit conversion that makes the code simpler. For example, the String <-> AtomicString makes the bindings generator code simpler since it doesn't need to know which the underlying method takes.
> Are there any reasons beyond personal preference to select either of these?
> 
> Starting list:
> 
> Pro's for #1
>   It is a pain to remember to put explicit every time you have a constructor with one argument.
> 
> Pro's for #2
>    It would prevent accidental mistakes that happen with implicit constructors.

I think the rule should be something like:

  3. Do not explicit when the single-argument constructor can be thought of as a type conversion - the class will be in some sense an alternate form of its sole parameter. Do use explicit when the single-argument constructor is *not* reasonably thought of as a type conversion - the single argument just happens to be the sole initialization parameter. Or to put it another way - can you imagine having a type conversion operator overload that does the same thing as this constroctor?

Applying this rule to your two examples, Vector(int) should be explicit, because it doesn't convert the int to a vector, it uses the int as a size instead of the default one. But String(AtomicString) or AtomicString(String) need not be explicit, since they convert from one string type to another, carrying largely the same data.

I realize this rule requires some judgment, so it's worse than a purely mechanical rule, but I think it accurately captures the proper use of explicit.

Regards,
Maciej

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.webkit.org/pipermail/webkit-dev/attachments/20100928/48a1498d/attachment.html>


More information about the webkit-dev mailing list