Skip to content

Commit

Permalink
Update style-guide with invalid constructor example (#53328)
Browse files Browse the repository at this point in the history
  • Loading branch information
hyrodium authored Feb 15, 2024
1 parent 3e6ff3d commit c23be9a
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions doc/src/manual/style-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,29 @@ Splicing function arguments can be addictive. Instead of `[a..., b...]`, use sim
which already concatenates arrays. [`collect(a)`](@ref) is better than `[a...]`, but since `a`
is already iterable it is often even better to leave it alone, and not convert it to an array.

## Ensure constructors return an instance of their own type

When a method `T(x)` is called on a type `T`, it is generally expected to return a value of type T.
Defining a [constructor](@ref man-constructors) that returns an unexpected type can lead to confusing and unpredictable behavior:

```jldoctest
julia> struct Foo{T}
x::T
end
julia> Base.Float64(foo::Foo) = Foo(Float64(foo.x)) # Do not define methods like this
julia> Float64(Foo(3)) # Should return `Float64`
Foo{Float64}(3.0)
julia> Foo{Int}(x) = Foo{Float64}(x) # Do not define methods like this
julia> Foo{Int}(3) # Should return `Foo{Int}`
Foo{Float64}(3.0)
```

To maintain code clarity and ensure type consistency, always design constructors to return an instance of the type they are supposed to construct.

## Don't use unnecessary static parameters

A function signature:
Expand Down

0 comments on commit c23be9a

Please sign in to comment.