Estilo de Código

Advertencia

This documentation refers to an outdated SpongeAPI version and is no longer actively maintained. While the code examples still work for that API version, the policies, guidelines, and some links may have changed. Please refer to the latest version of the documentation for those.

Seguimos las Directrices de Estilo de Java de Google <https://google.github.io/styleguide/javaguide.html>`_ con unas pocas adiciones y modificaciones, aquí descritas.

Truco

Puedes utilizar nuestros estilos de código para Eclipse o IntelliJ IDEA para dejar que tu IDE dé formato al código correctamente por ti. Ve Preparación del Desarrollo para obtener más información.

  • Finales de línea

    • Use finales de línea de Unix al asignar (\n)

      • Los usuarios de Windows de Git pueden ejecutar ``git config –global core.autocrlf true` para permitirle a Git convertirlos automáticamente

  • Ancho de columna

    • 80 para documentos de Java

    • 150 para código

    • Jangan ragu untuk membungkusnya saat akan membantu keterbacaan

  • Sangría

    • Usa 4 espacios para las sangrías, no uses 2 espacios

  • Espacio en blanco vertical

    • Deja una linea en blanco antes del primer miembro de una clase, interfaz, enumeración, etc. (es decir después de``class Ejemplo {``) al igual que después del ultimo miembro

  • Cabeceras de fichero

    • Las cabeceras de los ficheros deben contener las cabeceras de las licencias para el proyecto. Usa el comando Gradle licenseFormat para añadirlas automáticamente.

  • Importaciones

    • Las importaciones deben estar agrupadas en el siguiente orden, donde cada grupo es separado por una linea en blanco

      • Importaciones estaticas

      • Todas las otras importaciones

      • Importaciones java

      • Importaciones javax

    • Esto difiere del estilo de Google en que las importaciones no son agrupadas por paquetes de primer nivel, son todas agrupadas como una.

  • Excepciones

    • Para excepciones que deben ser ignoradas, nombra la variable de excepción ignored

  • Accesos de campo

    • Califica todos los campos de acceso con this

  • Javadocs

    • No uses @author

    • Pon los parrafos adicionales entre las etiquetas <p> y </p>

    • Ponga en mayúscula la primera letra en las descripciones dentro de cada «at clause», p.ej @param name Player to affect, sin puntos

Convenciones de Código

  • Usa Opcionales en lugar de devolver null en la API

  • Los parámetros de los métodos que admitan null deben ser anotados con @Nullable (from javax.*), todos los métodos y parámetros son @Nonnull por defecto.

  • Usa Precondiciones de Google para null- y comprobación de argumentos.

La Razón

Aunque insistimos particularmente en que leas las convenciones de Google sobre Java, ambos son documentos bastante largos. Para que empieces rápidamente, aquí tienes un ejemplo de un código correctamente formateado:

/*
 * This file is part of Sponge, licensed under the MIT License (MIT).
 *
 * Copyright (c) SpongePowered.org <https://www.spongepowered.org>
 * Copyright (c) contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.example.java;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;
import java.util.Optional;

public class Example {

    private static final Logger log = LoggerFactory.getLogger(Example.class);
    private static final Random random = new Random();
    private final String id = "test";

    /**
     * Returns an identifier approximately half of the time.
     *
     * <p>A static instance of {@link Random} is used to calculate the
     * outcome with a 50% chance.</p>
     *
     * @return The ID, if available
     */
    public Optional<String> resolveId() {
        log.info("ID requested");

        if (random.nextBoolean()) {
            return Optional.of(this.id);
        } else {
            return Optional.empty();
        }
    }

    /**
     * Returns an identifier approximately half of the time.
     *
     * <p>A static instance of {@link Random} is used to calculate the
     * outcome with a 50% chance. If the outcome is to not return the ID,
     * the given fallback ID is returned.</p>
     *
     * @param fallback A fallback name to return
     * @return The ID half of the time, the given fallback the other half
     */
    public String resolveId(String fallback) {
        return resolveId().orElse(fallback);
    }

}