0

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?

  • Never heard the term "primitive obsession" but to me it looks like you would introduce unnecessary classes. Especially defining a class Age looks utterly wrong. – Hans-Martin Mosner Jul 30 '18 at 6:49
  • No, it doesn't. I'm not sure it applies to these class fields, either. – Kilian Foth Jul 30 '18 at 6:59
  • @Hans-MartinMosner Primitive Obsession is defined at wiki.c2.com/?PrimitiveObsession – bdsl Jul 30 '18 at 12:08
4

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!)

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.