Melhoramento de Código

Gostaria de saber um modo de deixar esse código que fiz para ler o estoque de uma loja mais limpo e seco,o menor possivel com a mesma utilidade

package newexercise;

import java.util.Scanner;

public class Product {

    Scanner teclado = new Scanner(System.in);

    // Atributos

    String name;
    double Price;
    int Quantity;
    int N;
    int while1 = 1;
    int while2 = 1;

    // Métodos

    public double TotalValueInStock(){
        getPrice();
        getQuantity();

        System.out.println("Our value in stock is : " + getPrice()*getQuantity() + " Dollars in " + getName());

     return 0;   
    }

    public void AddProducts(){
        System.out.println("Name of the product: ");
        setName(teclado.nextLine());
        System.out.println("Price of the product: ");
        setPrice(teclado.nextDouble());
        System.out.println("Quantity of the products: ");
        setQuantity(teclado.nextInt());

        System.out.println("Entered " + getQuantity() + " " + getName() + " Whose prices are : " + getPrice() + " Dollars");
    }

    public void RemoveProducts(){
        getQuantity();

        while(while1==while2){
        System.out.println("Which product would you like to remove? : ");
        String Produte = teclado.next();
        if (Produte.equals(getName())){
            System.out.println("Type the quantity: ");
            setN(teclado.nextInt());
          }else{
                    System.out.println("There isn't any product with this name in our stock,sorry!");
                    while1++;
                    break;
                    }
        if (getN() > getQuantity()){
            System.out.println("Impossible to get,try another quantity smaller");
            while1++;
            break;
        }else{
            setQuantity(getQuantity()-getN());
            System.out.println(getN() + " " + getName() + " were removed from our stock");
            System.out.println("There are " + getQuantity() + " in our stock");
            while1++;
            break;
        }
        }
    }



     // Getter e Setters

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return Price;
    }

    public void setPrice(double Price) {
        this.Price = Price;
    }

    public int getQuantity() {
        return Quantity;
    }

    public void setQuantity(int Quantity) {
        this.Quantity = Quantity;
    }

    public int getN() {
        return N;
    }

    public void setN(int N) {
        this.N = N;
    }



}

Tu poderia limpar bem essa classe Product delegando algumas das funções dela para outras classes, por exemplo: O método AddProducts (deveria estar começando com letra minúscula, seguindo o padrão camel case) poderia apenas adicionar o produto de fato, deixando a parte de obter o nome, preço, etc., para outra classe.

Obs: É uma boa prática deixar os getters e setters logo após os construtores, e como essa sua classe não possui um, eles ficariam logo após os atributos.

1 curtida

Boa noite amigo.

Dá uma olhadinha nesse código:

public class Exercicio {

private static int menu = 0;
private static Scanner scan;
private static ProductUtil util;

public static void main(String[] args) {
    scan = new Scanner(System.in);
    util = new ProductUtil(scan);
    while(menu != 4){
        System.out.println("Menu\n" +
                "1- Add Product\n" +
                "2- Remove Product\n" +
                "3- Total Stock\n" +
                "4- Exit\n" +
                ">>>");
        menu = scan.nextInt();
        switch (menu){
            case 1:
                util.addProducts();
                break;
            case 2:
                util.removeProducts();
                break;
            case 3:
                util.totalValueInStock();
                break;
        }
    }
}

}

public class ProductUtil {

private Scanner scan;
private List<Product> products;

public ProductUtil(Scanner scan) {
    this.scan = scan;
    this.products = new ArrayList();
}

public void addProducts(){
    String[] messages = {"Name of the product: ", "Price of the product: ", "Quantity of the products: "};
    Product p = new Product();
    for(int m = 0; m < 3; m++){
        System.out.print(messages[m]);
        switch (m){
            case 0:
                p.setName(scan.next());
                break;
            case 1:
                p.setPrice(scan.nextDouble());
                break;
            case 2:
                p.setQuantity(scan.nextInt());
                break;
        }
    }
    products.add(p);
    System.out.println(p);
}

public void removeProducts() {
    System.out.println("Which product would you like to remove? (y/n): ");
    if(scan.next().toLowerCase().equals("y")){
        Product product = null;
        System.out.println("Select the product");
        for(int p = 0; p < products.size(); p++){
            System.out.println("\t" + p + " - " + products.get(p));
        }
        System.out.print(" > ");
        product = products.get(scan.nextInt());
        System.out.println("Type the quantity: ");
        int quant = scan.nextInt();
        if(product.getQuantity() < quant){
            System.out.println("Impossible to get,try another quantity smaller");
        } else {
            product.setQuantity(product.getQuantity() - quant);
            System.out.println(quant + " " + product.getName() + " were removed from our stock");
            System.out.println("There are " + product.getQuantity() + " in our stock");
        }
    }
}


public void totalValueInStock(){
    System.out.println("Our value in stock is : ");
    for(Product p : products){
        totalValueInStock(p);
    }
}

public void totalValueInStock(Product product){
    double total = product.getPrice() * product.getQuantity();
    System.out.println(product.getName() + " >  Quant: " + total + " - Value: " + product.getPrice() + " Dollars");
}

}

public class Product {

private String name;
private double price;
private int quantity;

public Product() {
}

public Product(String name, double price, int quantity) {
    this.name = name;
    this.price = price;
    this.quantity = quantity;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public double getPrice() {
    return price;
}

public void setPrice(double price) {
    this.price = price;
}

public int getQuantity() {
    return quantity;
}

public void setQuantity(int quantity) {
    this.quantity = quantity;
}

@Override
public String toString() {
    return "Product{" +
            "name='" + name + '\'' +
            ", price=" + price +
            ", quantity=" + quantity +
            '}';
}
}

Espero que isso te ajude. :metal::sunglasses::metal:

Uma das coisas que um Arquiteto de Software da empresa que trabalho diz em relação a limpeza de código é sobre nome das variáveis, uma variável deve possuir um nome que identifica o que ela faz corretamente.

No caso acima você utiliza nome de estrutura de repetição para definir nome de contador. No caso você poderia utilizar “i” e “j”, ou count1 e count2, tornaria o código mais legível.