Skip to content

Correcion de SRP en clases CustomerCheckIn, CustomerCheckOut y CustomerDetailsBill #5

@Eduidk28

Description

@Eduidk28

Corrección por violación del SRP en CustomerCheckIn, CustomerCheckOut y CustomerDetailsBill

Descripción del problema

Las clases combinan interfaz gráfica, lógica de negocio y acceso a datos (JDBC) en un mismo archivo.

Esto nos genera estos problemas:

  • Dificultad para probar la lógica sin ejecutar la UI.
  • Código duplicado en las operaciones con la base de datos.
  • Acoplamiento alto entre interfaz y persistencia.
    En pocas palabras, no cumple SRP al tener varias responsabilidades y no enfocarse en una cada clase.

Solución propuesta (aplicación del principio SRP)

Separar responsabilidades en capas distintas:

Clase Responsabilidad
Customer Modelo de datos
Room Entidad de habitación
CustomerRepository Acceso a base de datos
CustomerService Lógica de negocio
CustomerCheckInUI, CustomerCheckOutUI, CustomerDetailsBillUI Interfaz gráfica

Código refactorizado

Clase Customer

public class Customer {
    private String name;
    private String mobile;
    private String email;
    private String gender;
    private String nationality;
    private String address;
    private String id;
    private String checkInDate;
    private String checkOutDate;
    private String roomNumber;
    private String bedType;
    private String roomType;
    private double price;
    private int days;
    private double totalAmount;
    private String status;
    // Constructor, Getters, Setters
}

import java.sql.*;
import java.util.*;

public class CustomerRepository {
    private final DatabaseConnection db;

    public CustomerRepository(DatabaseConnection db) {
        this.db = db;
    }

    public void save(Customer customer) throws Exception {
        try (Connection con = db.getConnection()) {
            PreparedStatement pst = con.prepareStatement(
                "INSERT INTO customer(name, mobile, email, gender, address, id, nationality, date, roomnumber, bed, roomtype, price, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
            );
            pst.setString(1, customer.getName());
            pst.setString(2, customer.getMobile());
            pst.setString(3, customer.getEmail());
            pst.setString(4, customer.getGender());
            pst.setString(5, customer.getAddress());
            pst.setString(6, customer.getId());
            pst.setString(7, customer.getNationality());
            pst.setString(8, customer.getCheckInDate());
            pst.setString(9, customer.getRoomNumber());
            pst.setString(10, customer.getBedType());
            pst.setString(11, customer.getRoomType());
            pst.setDouble(12, customer.getPrice());
            pst.setString(13, "NULL");
            pst.executeUpdate();
        }
    }

    public List<Customer> findActiveCustomers() throws Exception {
        List<Customer> customers = new ArrayList<>();
        try (Connection con = db.getConnection()) {
            PreparedStatement pst = con.prepareStatement("SELECT * FROM customer WHERE status='NULL'");
            ResultSet rs = pst.executeQuery();
            while (rs.next()) {
                customers.add(mapCustomer(rs));
            }
        }
        return customers;
    }

    private Customer mapCustomer(ResultSet rs) throws SQLException {
        Customer c = new Customer();
        c.setName(rs.getString("name"));
        c.setMobile(rs.getString("mobile"));
        c.setEmail(rs.getString("email"));
        c.setGender(rs.getString("gender"));
        c.setRoomNumber(rs.getString("roomnumber"));
        c.setRoomType(rs.getString("roomtype"));
        c.setPrice(rs.getDouble("price"));
        c.setStatus(rs.getString("status"));
        return c;
    }
}
public class CustomerService {
    private final CustomerRepository repo;

    public CustomerService(CustomerRepository repo) {
        this.repo = repo;
    }

    public void register(Customer customer) throws Exception {
        if (customer.getMobile().length() != 10)
            throw new IllegalArgumentException("Número de móvil inválido.");
        if (customer.getEmail().isEmpty())
            throw new IllegalArgumentException("El correo no puede estar vacío.");
        repo.save(customer);
    }

    public List<Customer> getActiveCustomers() throws Exception {
        return repo.findActiveCustomers();
    }
}
public class CustomerCheckInUI extends JFrame {
    private final CustomerService service;

    public CustomerCheckInUI(CustomerService service) {
        this.service = service;
        initComponents();
    }

    private void onCheckInClicked() {
        try {
            Customer c = new Customer();
            c.setName(txtName.getText());
            c.setMobile(txtMobile.getText());
            c.setEmail(txtEmail.getText());
            c.setGender(comboGender.getSelectedItem().toString());
            c.setCheckInDate(txtDate.getText());
            c.setRoomNumber(comboRoom.getSelectedItem().toString());
            c.setRoomType(comboRoomType.getSelectedItem().toString());
            c.setPrice(Double.parseDouble(txtPrice.getText()));
            service.register(c);
            JOptionPane.showMessageDialog(this, "Check-in exitoso.");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, e.getMessage());
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions