Pregunta

atajos del idioma a menudo puede ser utilizado para hacer el código más conciso.

Por ejemplo, ternario y nula operadores de coalescencia puede reducir la cantidad de código, pero posiblemente en detrimento de la legibilidad:

En C #:

Person newGuy = new Person();
if (boss == null) {
    newGuy.Boss = GetDefaultBoss();
} else {
    newGuy.Boss = boss;
}

es funcionalmente equivalente a:

Person newGuy = new Person();
newGuy.Boss = boss ?? GetDefaultBoss();

pero, obviamente, mucho más detallado.

¿Dónde se traza la línea cuando se trata de la concisión vs legibilidad?

¿Fue útil?

Solución

Ambos.

El primer ejemplo es sin duda más detallado, y sin duda más explícita ... pero también me obliga a escanear cinco líneas en lugar de uno. Peor aún, se pone menos énfasis en su propósito -. Asignar un valor a newGuy.Boss

Su segundo ejemplo puede me costó un segundo si estoy familiarizado con el operador coalescente nula, pero no puede haber ninguna duda en cuanto a su propósito, y si estoy exploración a través de una rutina más grande en busca de la fuente de un valor , será mucho más fácil para mí para recoger éste hacia fuera.

Ahora, en contraste esto:

if (boss == null) {
    newGuy.Boss = GetDefaultBoss();
    newGuy.IsTemp = true;
    newGuy.AddTask("orientation");
} else {
    newGuy.Boss = boss;
    newGuy.IsTemp = false;
}

... con:

newGuy.Boss = boss ?? GetDefaultBoss();
newGuy.IsTemp = boss == null;
if ( boss == null ) newGuy.AddTask("orientation");

El último ejemplo es de nuevo mucho más corto, pero ahora se oscurece su propósito al hacer tareas desencadenadas por la misma prueba parecen ser distintos. Aquí, siento el nivel de detalle de la primera es justificada.

Otros consejos

While both are good goals, I'll always side with Readability when forced to choose one.

I would argue that your example improves both readability and brevity. Consider, however:

if( a > b )
{
    foo = bar
}
else
{
    if( c.isThing() ){
        foo = somethingElse;
    }
    else{
        foo = someFurtherThing.GetFoo();
    }
}

as opposed to

foo = a > b ? bar ?? whatever.something : c.isThing() ? somethingElse : someFurtherThing.GetFoo();

The latter is concise, but is difficult to read through. The former is verbose, but the flow of logic is clear.

Ultimately, brevity doesn't serve much of a purpose, other than the ability to fit more on the screen. Readability makes it easier to debug, and so should generally be preferred.

I would say as a general rule never sacrifice readability because of conciseness, but never judge readability based on another programmers lack of knowledge on that subject.

Conciseness and readability are not opposites. Like this answer, sometimes shorter is more readable.

I would say I prefer readability, though that sometimes means using concise code. (I.e. ternary for relatively simple conditionals inside a larger conditional block.)

Basically, if it is unnecessarily difficult to understand, don't do it.

Readability comes first where it conflicts with conciseness, because code is modified more often than it is initially written. On the other hand:

  1. Syntactic noise and boilerplate code often obscure intentions and thus hurt readability. Sometimes the more concise code is also more readable. For example, think lambda functions or delegates/first-class functions versus single-method classes that implement a single-method interface.

  2. Readability should be assessed based on how easy the code is to read for a reasonably experienced programmer who knows the language and its unique/advanced features fairly well, not some barely competent code monkey who only knows the lowest common denominator.

One aspect that I don't think has been mentioned yet: what are your goals?

If all you care about is job security, go for conciseness & compactness over everything else. Skip commenting your code, too.

If you want to be able to easily hand your code off to someone else while you go work on a cool new project, go for readability, clarity, and lots of solid comments.

Note: the above isn't about you personally, @Damovisa; it's for anyone choosing between the two positions.

There is one thing that the verbose version has as an advantage.

It has more lines, and most debuggers are line-oriented! It is very hard to set a break point in the middle of an expression, but it is usually trivially simple to set it inside a block statement.

In other words, which one would you want to see in your editor if you want your debugger to kick in when boss == null ?

(That said I like the ??-operator)

Readability should come first, long-term most people spend most time modifying or extending existing code - readability is a big part of maintainability.

That said, conciseness is something which can contribute towards readability. For example, in your question the second snippet is both more readable and more concise.

Licenciado bajo: CC-BY-SA con atribución
scroll top