Julia – 114 – guida allo stile – 2

Continuo da qui, copio qui.

Continuo con i consigli, ce ne sono che mi piacciono, altri li considero miei, usati da sempre 😊

Non abusare try-catch
It is better to avoid errors than to rely on catching them.

Non mettere le condizioni tra parentesi
Julia doesn’t require parens around conditions in if and while. Write:

if a == b

instead of:

if (a == b)

Non abusare di ...
Splicing function arguments can be addictive. Instead of [a..., b...], use simply [a; b], which already concatenates arrays. collect(a) 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.

Non usare parametri statici non necessari
A function signature:

foo(x::T) where {T<:Real} = ...

should be written as:

foo(x::Real) = ...

instead, especially if T is not used in the function body. Even if T is used, it can be replaced with typeof(x) if convenient. There is no performance difference. Note that this is not a general caution against static parameters, just against uses where they are not needed.

Note also that container types, specifically may need type parameters in function calls.

Evitare confusioni tra istanze e tipi
Sets of definitions like the following are confusing:

foo(::Type{MyType}) = ...
foo(::MyType) = foo(MyType)

Decide whether the concept in question will be written as MyType or MyType(), and stick to it.

The preferred style is to use instances by default, and only add methods involving Type{MyType} later if they become necessary to solve some problem.

If a type is effectively an enumeration, it should be defined as a single (ideally immutable struct or primitive) type, with the enumeration values being instances of it. Constructors and conversions can check whether values are valid. This design is preferred over making the enumeration an abstract type, with the “values” as subtypes.

Non abusare delle macros
Be aware of when a macro could really be a function instead.

Calling eval() inside a macro is a particularly dangerous warning sign; it means the macro will only work when called at the top level. If such a macro is written as a function instead, it will naturally have access to the run-time values it needs.

Non usare operazioni non sicure (unsafe) nell’interfaccia
If you have a type that uses a native pointer:

mutable struct NativeType

don’t write definitions like the following:

getindex(x::NativeType, i) = unsafe_load(x.p, i)

The problem is that users of this type can write x[i] without realizing that the operation is unsafe, and then be susceptible to memory bugs.

Such a function should either check the operation to ensure it is safe, or have unsafe somewhere in its name to alert callers.

Non sovraccaricare (overload) metodi di tipo container di base
It is possible to write definitions like the following:

show(io::IO, v::Vector{MyType}) = ...

This would provide custom showing of vectors with a specific new element type. While tempting, this should be avoided. The trouble is that users will expect a well-known type like Vector() to behave in a certain way, and overly customizing its behavior can make it harder to work with.

Evitare “piracy type”
“Type piracy” refers to the practice of extending or redefining methods in Base or other packages on types that you have not defined. In some cases, you can get away with type piracy with little ill effect. In extreme cases, however, you can even crash Julia (e.g. if your method extension or redefinition causes invalid input to be passed to a ccall). Type piracy can complicate reasoning about code, and may introduce incompatibilities that are hard to predict and diagnose.

As an example, suppose you wanted to define multiplication on symbols in a module:

module A
import Base.*
*(x::Symbol, y::Symbol) = Symbol(x,y)

The problem is that now any other module that uses Base.* will also see this definition. Since Symbol is defined in Base and is used by other modules, this can change the behavior of unrelated code unexpectedly. There are several alternatives here, including using a different function name, or wrapping the Symbols in another type that you define.

Sometimes, coupled packages may engage in type piracy to separate features from definitions, especially when the packages were designed by collaborating authors, and when the definitions are reusable. For example, one package might provide some types useful for working with colors; another package could define methods for those types that enable conversions between color spaces. Another example might be a package that acts as a thin wrapper for some C code, which another package might then pirate to implement a higher-level, Julia-friendly API.

OK, cosa molto specifica, non credo di arrivare a tanto 😊

Attenzione ai tipi di ugualianza
You generally want to use isa() and <: (issubtype()) for testing types, not ==. Checking types for exact equality typically only makes sense when comparing to a known concrete type (e.g. T == Float64), or if you really, really know what you’re doing.

Non scrivere x->f(x)
Since higher-order functions are often called with anonymous functions, it is easy to conclude that this is desirable or even necessary. But any function can be passed directly, without being “wrapped” in an anonymous function. Instead of writing map(x->f(x), a), write map(f, a).

Evitare, quando possibile, di usare float in costanti numeriche
If you write generic code which handles numbers, and which can be expected to run with many different numeric type arguments, try using literals of a numeric type that will affect the arguments as little as possible through promotion.

For example,


Questa la considero una mia vittoria (molto tardiva) 😁

As you can see, the second version, where we used an Int literal, preserved the type of the input argument, while the first didn’t. This is because e.g. promote_type(Int, Float64) == Float64, and promotion happens with the multiplication. Similarly, Rational literals are less type disruptive than Float64 literals, but more disruptive than Ints:

Thus, use Int literals when possible, with Rational{Int} for literal non-integer numbers, in order to make it easier to use your code.


Posta un commento o usa questo indirizzo per il trackback.



Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo di WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione /  Modifica )

Google photo

Stai commentando usando il tuo account Google. Chiudi sessione /  Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione /  Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione /  Modifica )

Connessione a %s...

Questo sito utilizza Akismet per ridurre lo spam. Scopri come vengono elaborati i dati derivati dai commenti.

%d blogger hanno fatto clic su Mi Piace per questo: