Skip to content

Commit c23be9a

Browse files
authored
Update style-guide with invalid constructor example (#53328)
1 parent 3e6ff3d commit c23be9a

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

doc/src/manual/style-guide.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,29 @@ Splicing function arguments can be addictive. Instead of `[a..., b...]`, use sim
262262
which already concatenates arrays. [`collect(a)`](@ref) is better than `[a...]`, but since `a`
263263
is already iterable it is often even better to leave it alone, and not convert it to an array.
264264

265+
## Ensure constructors return an instance of their own type
266+
267+
When a method `T(x)` is called on a type `T`, it is generally expected to return a value of type T.
268+
Defining a [constructor](@ref man-constructors) that returns an unexpected type can lead to confusing and unpredictable behavior:
269+
270+
```jldoctest
271+
julia> struct Foo{T}
272+
x::T
273+
end
274+
275+
julia> Base.Float64(foo::Foo) = Foo(Float64(foo.x)) # Do not define methods like this
276+
277+
julia> Float64(Foo(3)) # Should return `Float64`
278+
Foo{Float64}(3.0)
279+
280+
julia> Foo{Int}(x) = Foo{Float64}(x) # Do not define methods like this
281+
282+
julia> Foo{Int}(3) # Should return `Foo{Int}`
283+
Foo{Float64}(3.0)
284+
```
285+
286+
To maintain code clarity and ensure type consistency, always design constructors to return an instance of the type they are supposed to construct.
287+
265288
## Don't use unnecessary static parameters
266289

267290
A function signature:

0 commit comments

Comments
 (0)