Primary keys, IDs, references. The first attribute we add to our objects. They don't exist in the real-world.
TL;DR: Reference objects with objects, not ids.
-
Coupling
-
Accidental Implementation
-
Bijection Principle Violation.
-
Reference object to objects.
-
Build a MAPPER.
-
Only use keys if you need to provide an external (accidental) reference. Databases, APIs, Serializations.
-
Use dark keys or GUIDs when possible.
-
If you are afraid of getting a big relation graph use proxies or lazy loading.
-
Don't use DTOs.
class Teacher {
static getByID(id) {
// This is coupled to the database
// Thus violating separation of concerns
}
constructor(id, fullName) {
this.id = id;
this.fullName = fullName;
}
}
class School {
static getByID(id) {
// go to the coupled database
}
constructor(id, address) {
this.id = id;
this.address = address;
}
}
class Student {
constructor(firstName, lastName, id, teacherId, schoolId) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
this.teacherId = teacherId;
this.schoolId = schoolId;
}
school() {
return School.getById(this.schoolId);
}
teacher() {
return Teacher.getById(this.teacherId);
}
}
class Teacher {
constructor(fullName) {
this.fullName = fullName;
}
}
class School {
constructor(address) {
this.address = address;
}
}
class Student {
constructor(firstName, lastName, teacher, school) {
this.firstName = firstName;
this.lastName = lastName;
this.teacher = teacher;
this.school = school;
}
}
// The ids are no longer needed since they don’t exist in the real world.
// If you need to expose a School to an external API or a database,
// another object (not school)
// will keep the mapping externalId<->school and so on
This is a design policy.
We can enforce business objects to warn us if we define an attribute or function including the sequence id.
- Accidental
Ids are not necessary for OOP. You reference objects (essential) and never ids (accidental).
In case you need to provide a reference out of your system's scope (APIs, interfaces, Serializations) use dark and meaningless IDs (GUIDs).
Code Smell 20 - Premature Optimization
What is (wrong with) software?
The One and Only Software Design Principle
Coupling - The one and only software design problem
Photo by Maurice Williams on Unsplash
All problems in computer science can be solved by another level of indirection.
David Wheeler
Software Engineering Great Quotes
This article is part of the CodeSmell Series.