Java – Does a Null Object ID Violate Encapsulation?

class-designencapsulationjavaobject-orientedobject-oriented-design

This question is related to How should an `Employee` class be designed?

In the above question, to uniquely identify an employee, each Employee object has an id field as shown below

class Employee
{
    private int id // id is given by the database
    // Employee data (let's say, dozens of properties).


    //methods.....

}

The id of an employee object is given by the database.

So if I use the object for describing a new employee, there will be no id to store yet. But an object representing an existing employee will have an id. So I have a property that sometimes describes the object and sometimes doesn't.

Also, id = null makes the Employee object's state invalid but

[A] properly encapsulated object cannot be brought into an invalid state
via the public interface […]

https://softwareengineering.stackexchange.com/a/258281/234665

Does this design violate encapsulation because id = null at the start?

Best Answer

The simplest method is to just ignore your perceived problem. Items that are in the database have an id, provided by the database. Items not in the database have no id. Both are valid states. “Insert” is not a valid operation if the item has an I’d that is not null. And “update” is an invalid operation if the item is not in the database.

You can decide whether id should be immutable - in that case adding an item to the database leads to the creation of a new item with the id changed.