Kodestil

Advarsel

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.

We follow Google’s Java Style Guidelines with a few additions and modifications, which are described herein.

Tips

You can use our code styles for Eclipse or IntelliJ IDEA to let your IDE format the code correctly for you. See Å gjøre seg klar til utvikling for more information.

  • Linjeslutt

    • Use Unix line endings when committing (\n)

      • Windows-brukere av Git kan bruke git config --global core.autocrlf true for å la Git konvertere dem automatisk.

  • Kolonnebredde

    • 80 for Javadocs

    • 150 for kode

    • Du må gjerne la teksten gå over flere linjer dersom det gjør det mer lesbart.

  • Innrykk

    • Bruk 4 mellomrom for innrykk, ikke bruk 2 mellomrom

  • Vertikalt mellomrom

    • Plasser en tom linje før det første medlemmet av en klasse, et grensesnit, enum, osv. (altså etter class Example {), samt etter det siste medlemmet

  • Filoverskrifter

    • Filoverskriftene må inneholde prosjektets lisesoverskrifter. Bruk licenseFormat-Gradle-jobben for å legge dem til automatisk.

  • Importer

    • Imports must be grouped in the following order, where each group is separated by an empty line

      • Static imports

      • All other imports

      • java imports

      • javax imports

    • This differs from Google’s style in that imports are not grouped by top-level package, they are all grouped as one.

  • Unntak

    • For unntak som skal ignoreres, gi unntaksvariabelen navnet ignored

  • Field accesses

    • Qualify all field accesses with this

  • Javadocs

    • Ikke bruk @author

    • Pakk inn nye avsnitt i <p> og </p>

    • Den første bokstaven i beskrivelsene i hver @-klause bør være stor, altså @param navn Spilleren som affiseres. Ingen punktum.

Kodekonvensjoner

  • Use Optionals instead of returning null in the API

  • Metodeparametere som godtar null må annoteres med @Nullable (fra javax.*), alle metoder og parametere er @Nonnull som standard.

  • Bruk Google Preconditions til null- og argumentsjekking.

Kjernen

Selv om vi oppfordrer deg til å lese Google sine Java-konvensjoner godt, er de to ganske lange dokumenter. For å få deg fort i gang, her er et eksempel på riktig formatert kode:

/*
 * 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);
    }

}