My problem consists of the following:
I have a JTextField that will receive the name of my entity, will pass pro controller, which will create the bean and finally call the DAO to insert into the bank. Simple thing is a basic CRUD.
The table field in the database is NOT NULL
because it would not make sense to be blank.
Thinking of: Make It Simple! I did the following in the method that will be responsible for the events in JDialog, I put the empty spaces at the beginning of the name and use a JOptionPane if the JTextField is empty.
However, we will also evaluate the elegance of the code, better ways to solve the problem, for example using Pattern. Following this logic in the controller method, responsible for instantiating the DAO and inserting a boolean return in the database only, to warn the method that called if the insert was succeeded or not. In this case, the method will check if the name of the entity is null, and if there is an equal name already registered in the database, instantiating an ArrayList with all names registered and using a ForEach for verification, if it already exists the name returns false.
But, as we say we will be evaluated by the elegance of the code, then imagine making an exception and treat it returning if the method returns false. looking for more information I've read:
How best to treat Exceptions in Java?
#
Exception vs. RuntimeException, when using one or the other?
And some other things to better my understanding that cleared up a bit, but, I'm still in doubt: In this way is it correct or would it be more, say "elegant", treat as an exception?
Codes:
Save button method:
public void setupEvents() {
btnSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
tfNameNewDiscipline.getText().trim();
ControllerDiscipline controller;
if(tfNameNewDiscipline.getText().isEmpty())
JOptionPane.showMessageDialog(null, "Digite um nome para a Disciplina", "Erro no cadastro da Disciplina", JOptionPane.ERROR_MESSAGE);
else {
controller = new ControllerDiscipline();
if(controller.addDiscipline(tfNameNewDiscipline.getText()) == false)
JOptionPane.showMessageDialog(null, "Disciplina já existe", "Erro no cadastro da Disciplina", JOptionPane.ERROR_MESSAGE);
}
}
});
Controller class method that adds to the bank:
public boolean addDiscipline(String name) {
DisciplineDAO dao = new DisciplineDAO();
Discipline entity = new Discipline();
entity.setName(name);
if (entity.getName().isEmpty()) {
return false;
}
ArrayList<Discipline> disciplines = new ArrayList<>();
disciplines.addAll(dao.searchData());
for(Discipline discipline : disciplines) {
if(entity.getName().equals(discipline.getName()))
return false;
}
dao.insert(entity);
return true;
}