The interface is too general

In the Java code I'm working with, we have an interface for defining our data access objects (DAOs). Most methods accept a Data Transfer Object (DTO) parameter. The problem arises when a DAO implementation must reference a specific type of DTO. Then this method should execute (for me, completely unnecessary DTO selection for SpecificDTO. Not only that, but the compiler cannot apply any type of type checking for specific DAO implementations, which should only accept their specific DTOS types as parameters. My question : How do I fix this as little as possible?

+3
source share
2 answers

You can use generics:

DAO<SpecificDTO> dao = new SpecificDAO();
dao.save(new SpecificDTO());
etc.

Your DAO class will look like this:

interface DAO<T extends DTO> {
    void save(T);
}

class SpecificDAO implements DAO<SpecificDTO> {
    void save(SpecificDTO) {
        // implementation.
    }
    // etc.
}

SpecificDTO DTO.

+12

- ( , , ).

, DTO- :

DTO user = userDAO.getById(45);

((UserDTO)user).setEmail(newEmail)

userDAO.update(user);

( ).

:

public DeprecatedDAO implements DAO
{
    public void save(DTO dto)
    {
        logger.warn("Use type-specific calls from now on", new Exception());
    }
}

public UserDAO extends DeprecatedDAO
{
    @Deprecated
    public void save(DTO dto)
    {
        super.save(dto);
        save((UserDTO)dto);
    }

    public void save(UserDTO dto)
    {
        // do whatever you do to save the object
    }
}

, ; , , , .

0

Source: https://habr.com/ru/post/1698371/


All Articles