I disagree. This code should be improved.
try
{
String autor = "SomeAuthor";
String texto = null;
Comentari newComentari = new Comentari(autor, texto);
}
catch {RedProfesionalException ex)
{
// React to catched exception here...
}
That is not how object orientation works.
It is a bad habit to throw exceptions in a constructor:
public class Comentari extends Object {
private String autor, texto;
public Comentari(String autor, String texto) throws RedProfesionalException{
this.autor = autor;
this.texto = texto;
if (texto==null || texto.equals(""))
throw new RedProfesionalException("You have written nothing");
}
}
One reason to choose OOP is the advantage of creating an object in a predefined state. What you wanted is: you wanted to create a valid Comentari object. What you did is: in case the state of your object would be invalid, your object would be created and just break in to pieces because of your exception.
It would be much cleaner to wrap this into a factory function like:
public Comentari createComentariWithAuthorAndText(String autor, String texto){
if (texto==null || texto.equals(""))
throw new RedProfesionalException("You have written nothing");
return new Comentari(author, texto);
}
So there is nerver an inconsistent object created and no objects were harmed ;)
Another solution would be to allow the creation of an empty commentary, but check later, if comentari.getTexto() is empty and handle that fact later.
So the try/catch looks like:
try
{
String autor = "SomeAuthor";
String texto = null;
Comentari newComentari = createComentariWithAuthorAndText(autor, texto);
}
catch {RedProfesionalException ex)
{
// React to catched exception here...
}
Comentari
class has an ID field not shown here? Does it have setters/getters (especially setters) forautor
andtexto
also not shown here? – abuzittin gillifirca May 27 '13 at 10:41