Skip to content

Commit fa77b2f

Browse files
mlimbermatthew-limbinar
authored andcommitted
Clarify wording re: explicit ctors
1 parent fa05f6d commit fa77b2f

File tree

1 file changed

+20
-12
lines changed

1 file changed

+20
-12
lines changed

_posts/2018-02-15-totw-142.md

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -81,18 +81,26 @@ object, no confusion arises from this affordance.
8181

8282
## Constructors That Do More
8383

84-
Implicitly calling a constructor isn’t such a good idea if its output is a
85-
different value than its input, or if it might have preconditions.
86-
87-
Consider a `Request` class with a constructor `Request(Server*, Connection*)`.
88-
There’s no sense in which the value of the request object “is” the server and
89-
connection — it’s just that we can create a request that uses them. There could
90-
be many semantically different types that can be constructed from `{server,
91-
connection}`, such as a `Response`. Such a constructor should be `explicit`, so
92-
that we can’t pass `{server, connection}` to a function that accepts a `Request`
93-
(or `Response`) parameter. In such cases marking the constructor as `explicit`
94-
makes the code clearer for readers by requiring the target type to be named when
95-
it’s instantiated and helps to avoid bugs caused by unintended conversions.
84+
The constructor should be `explicit` when it may have preconditions or when
85+
the new object is a different kind of thing than its inputs (that is,
86+
when the inputs do not uniquely define the object but are used to build
87+
a new thing that has additional semantic meaning or state beyond these
88+
inputs).
89+
90+
Consider a `Request` class with a constructor `Request(Server*,
91+
Connection*)`. The server and connection are not converted into a
92+
request object. Rather, we use this constructor to create a new object
93+
that uses the inputs and has an implied direction of information flow.
94+
There could be many semantically different types that can be constructed
95+
from `{server, connection}`, such as a `Response` going in the opposite
96+
direction from a `Request`.
97+
98+
Such a constructor should be `explicit` so that we can’t pass
99+
`{server, connection}` to a function that accepts a `Request` or
100+
`Response` parameter. Marking the constructor as `explicit` makes the
101+
code clearer for readers by requiring the target type (and thus the
102+
intended direction) to be named when it’s instantiated. This
103+
explicitness helps to avoids bugs caused by unintended conversions.
96104

97105
<pre class="prettyprint lang-cpp code">
98106
// A line is defined by two distinct points.

0 commit comments

Comments
 (0)