Nur Main
| 🚧 | Diese Seite befindet sich in Bearbeitung | 🚧 |
| 🤓 | Diese Seite ist eine Bewertungsrichtlinie, die ab Blatt 1 annotiert und ab Blatt 2 abgezogen wird. | 🤓 |
Beschreibung
Die Main-Methode public static void main (String[] args) ist lediglich der Eingangspunkt für das Programm. Sie sollte deshalb so kurz wie möglich sein und keine weiteren Aspekte behandeln.
Besonders heißt das, dass nie das gesamte Programm in der Main-Methode sein sollte. Nutzen Sie mehrere Klassen und Methoden, um das Programm nach den Prinzipien der Objektorientierung und des Geheimnisverrats zu strukturieren.
Die Ausnahme dazu bildet das Validieren der Parameter, die für das Starten des Programms wichtig sind und demnach nicht an das Programm selbst übergeben werden können.
Negativbeispiel:
public class Main {
public static void main(String[] args) {
if (args.length < 2) {
return;
}
int first = Integer.parseInt(args[0]);
int second = Integer.parseInt(args[1]);
int result;
if (first < 0 || second < 0) {
System.out.println("Negative numbers are not allowed.");
result = 0;
} else {
result = first + second;
}
System.out.println("Result: " + result);
}
}
Positivbeispiel:
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
Parser parser = new Parser();
int first = parser.parseFirst(args);
int second = parser.parseSecond(args);
int result = calculator.add(first, second);
System.out.println("Result: " + result);
}
}
public class Calculator {
public int add(int x, int y) {
if (x < 0 || y < 0) {
System.out.println("Negative numbers are not allowed.");
return 0;
}
return x + y;
}
}
public class Parser {
public int parseFirst(String[] args) {
if (args.length < 1) {
// Throws exception
}
return Integer.parseInt(args[0]);
}
public int parseSecond(String[] args) {
// Parses the passed in args and checks if correct
}
}