Should a DAO set the ID an return the instance on Save/Update operations?

  softwareengineering

Should a DAO save() method set the id/pk of the instance that is to be saved and return the instance or should it just return the PK?

// Example A: Return the instance
studentDAO = {
  save: function(student) {
    const id = db.query('INSERT INTO `students`...');
    student.setId(id);

    return student;
  }
}

// Example B: return the save id and it's up to me to set it 
// outside of the DAO
studentDAO = {
  save: function() {
    const id = db.query('INSERT INTO `students`...');

    return id;
  }
}

And usage of the above:

// Example A
student = new Student();
student = studentDao.save(student);

// Example B
student = new Student();
idStudent = studentDao.save(student);
student.setId(idStudent);

3

This bit is wrong:

    const id = db.query('INSERT INTO `students`...');

student.Id should already be set when the save function is called. The db should use that supplied Id. There should be no new Id to return.

eg.

public class Student
{
    public string Id {get;set;}
    public Student()
    {
        this.Id = Guid.NewGuid().ToString();
    }
}

Depending on knowledge of all students to be able to create a single new student adds a choke point to any system and will cause no end of issues.

9

The database is either going to use a ‘natural’ key or ‘artifical’ one. The primary key is important and it should be returned by the insert (DAO) if the database is generating it.

One should always strive for natural keys if possible. In some cases, this is not possible, but the key (Id) belongs to the object and thus should be returned.

If one is using a natural key, the save could return void as the object has not changed. If one is using an artificial key, then the save should return the PK value as part of the save operation.

2

LEAVE A COMMENT