Skip to content

Commit

Permalink
Mention Nullable in Style Guide section about type Unions
Browse files Browse the repository at this point in the history
With Nullable, the main drawback of this kind of field (type
instability) goes away, so mention it as a last resort solution.
Make the title more imperative since type Unions can always be
avoided by using a Nullable field.

[av skip]
  • Loading branch information
nalimilan committed Mar 18, 2015
1 parent 17abcd9 commit ef532f5
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
18 changes: 14 additions & 4 deletions doc/manual/style-guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -121,18 +121,28 @@ Avoid strange type Unions
Types such as ``Union(Function,AbstractString)`` are often a sign that some design
could be cleaner.

Try to avoid nullable fields
----------------------------
Avoid type Unions in fields
---------------------------

When using ``x::Union(Nothing,T)``, ask whether the option for ``x`` to be
``nothing`` is really necessary. Here are some alternatives to consider:
When creating a type such as::

type MyType
...
x::Union(Void,T)
end

ask whether the option for ``x`` to be ``nothing`` (of type ``Void``)
is really necessary. Here are some alternatives to consider:

- Find a safe default value to initialize ``x`` with
- Introduce another type that lacks ``x``
- If there are many fields like ``x``, store them in a dictionary
- Determine whether there is a simple rule for when ``x`` is ``nothing``.
For example, often the field will start as ``nothing`` but get initialized at
some well-defined point. In that case, consider leaving it undefined at first.
- If ``x`` really needs to hold no value at some times, define it as
``::Nullable{T}`` instead, as this guarantees type-stability in the code
accessing this field (see :ref:`Nullable types <man-nullable-types>`)

Avoid elaborate container types
-------------------------------
Expand Down
2 changes: 2 additions & 0 deletions doc/manual/types.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1276,6 +1276,8 @@ For consistency across Julia, the call site should always pass a
``Val`` type rather than creating an instance, i.e., use
``foo(Val{:bar})`` rather than ``foo(Val{:bar}())``.

.. _man-nullable-types:

Nullable Types: Representing Missing Values
-------------------------------------------

Expand Down

0 comments on commit ef532f5

Please sign in to comment.