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?
id = null
make the state invalid? The linked question does not say that and the accepted answer seems to imply that it should be considered valid.id = null
makes the state invalid? Anyway the answer to your question is obviously yes, what you describe are not properly encapsulated objects. But you already know that don't you?id = null
state is in valid