I am doing some Java exercises, as you can see in the program I ask the user if he wants to continue or not and I evaluate the answer as you can see
/**
* ProbarLibro.java
* Programa para probar la clase Libro
* ==================================
*
* @author Luis Quesada Romero
*/
// Pertece al paquete tarea_libro
package tarea_libro;
import java.util.Scanner;
public class ProbarLibro { // Clase principal ProbarLibro
public static void main(String[] args) { // Método Main
// Varialbes
String comenzamos;
// Inicio del programa
System.out.println("BIENVENIDO\n");
System.out.println("Este programa guarda los datos de dos libros y nos dira cual tiene más paginas");
System.out.println("¿Comenzamos? s/n");
// Guardamos la respuesta y la evaluamos para empezar o salir del programa
Scanner entrada = new Scanner(System.in);
comenzamos = entrada.nextLine();
if ( "s".equals(comenzamos) ) {
System.out.println("Comenzamos!");
} else {
System.out.println("Otra vez sera, buena suerte!");
}
} // Fin del método main
} // Fin de la clase pirncipal ProbarLibro
My doubt comes in the If condition, you see how I directly evaluate "s" without creating a variable for example String respuesta = s
and then evaluate, my doubt is that I don't know if it is okay without creating a variable or it is better to create a variable and evaluate.
That has a programming name: "Magic values" (or in this case, "magic strings").
They are literal values that appear in the code and are used for its execution.
Sometimes they are problematic for several reasons:
What do they mean? If you see code that does
dias * 86400
this you may not realize that it is converting days to seconds. Instead,dias * SEGUNDOS_POR_DIA
it is clearer.dias * 24 * 60 * 60
is much more readable than the first form.are they variable? If your code to calculate VAT is
importe * 0.21
, when there is a change in the VAT percentage you will have to find the place (or places) of your code where the 0.21 is and change it. Maybe you leave some. Or maybe you change a 0.21 that was not used for VAT but for something else.So in general it is recommended to have those constant values defined as constants (eg an attribute
private static final String RESPUESTA_SI = "s";
). But having said what was said:Your program is very short and easy to read and modify.
It only asks one question, so there is no problem that for one question it expects "s" and for another "v" (true).
If you were to make the program in another language, you would still have to rewrite all the literals. It's not a program made with that idea, so you don't have to worry too much about that either.
In summary: I see the program as correct, but it is worth knowing that when you do more serious and complicated programs you have to be careful with the Magic Strings.