Question

For example, in a Student object, in order to avoid primitive obsession, I should change

public class Student{
    public String name;
    public int age;
}

into

public class Student{
    public Name name;
    public Age age;
}

so that name and age have their own object. However, in database, I usually stores Name and Age in plain text or int:

CREATE TABLE Students
  ID int NOT NULL,
  Name varchar(255),
  Age int,
  PRIMARY KEY (ID)

My question is, ideally, should I create one table for one field:

CREATE TABLE Students
  ID int NOT NULL,
  PRIMARY KEY (ID)

CREATE TABLE Names
  value varchar(255),
  CONSTRAINT student_id PRIMARY KEY (ID)

CREATE TABLE Ages
  value INT,
  CONSTRAINT student_id PRIMARY KEY (ID)

So that each field has its own tables?

Was it helpful?

Solution

You should not create unnecessary tables.

First, consider why "primitive obsession" is considered an antipattern in the first place. By encapsulating "Age" in its own class can apply constraints and validation specifically for this type - eg. ensuring it is not negative, add domain specific logic for calculating ages, and you can constrain what operations are valid on ages.

But you get none of these benefits by splitting the age field into a separate table. You can still perform exactly the same operations on age as before since the concept of encapsulation does not really apply to database tables. So creating a separate table have not benefit and will just complicate your code a lot.

What you can do (at least in same databases) is to create a distinct data type for Age, but still have it in the same table. Most databases allow you to create your own data types. Whether this is worth it is another question. If you have a simple CRUD application where all data manipulation happens in the application code, the benefit may not be big. If you have lots of SQL or have an enterprise system where multiple application access the same database, there may be a lot of benefits to creating custom types.

(By the way, you should probably store year of birth rather than age!)

Licensed under: CC-BY-SA with attribution
scroll top