I have a database class with the following interface:
public Database {
//returns false if p (its ID) is already available
//otherwise adds p the the list and returns true
public boolean create(Person p);
//returns false if p (its ID) was not found in the list
//replaces the available Person q (q.ID == p.ID) with p and returns true
public boolean update(Person p);
//returns false if p (its ID) was not found in the list
//marks the available Person q (q.ID == p.ID) as inactive returns true
public boolean remove(Person p);
}
The Person
is immutable and can be identified by a unique id. I have a EditDialog
which looks like this:
I wanted to reuse my code and so the EditDialog
is used for create a Person
or update it. So this dialog is initialized either by a available Person
instance (Edit-Operation) or by a new one (Create-Operation).
Because I learned that there is always an evil user I wanted to avoid the following scenario:
- Click "Create Person" button
- New
Person
is created in Database EditDialog
for newPerson
is displayed
- New
- Click "Chancel" button
Person
has to be removed (= marked inactive) fromDatabase
EditDialog
is disposed
- repeat
Which would lead to many inactive Person
s in the Database
. So I decided to only create the Person
in the Database
, if the user clicks the "Save" button. Which leads to two possible scenarios for the Listener
of the "Save" button:
- New
Person
should be created inDatabase
Person
should be updaated inDatabase
So the code of the Listener looks like the following:
if(!database.create(p) {
database.update(p);
}
Which is not so pretty in my opinion. The Long and the short of it is, should the Database automatically
- update a
Person
if it's availabe at invokation ofcreate(Person)
? - create a
Person
if it's not yet available at invokation ofupdate(Person)
?
Or is there another solution/practice I didn't think about?
ORM
s (Object Relational Mapping) in generalnew person
so it is a new person then your save button knows what it have to do. Same for the Edit (in fact) because if the user already exists the user clicks on a user from a list (my guest) and you open the edit dialog knowing that the person already exists.database.persons.exists(p)