How to make data loosely coupled with application code?

63 Views Asked by At

I have inherited a project code base from a developer who worked on it. I have to make some changes in it.

Say I have a table "CARS" with 2 columns

ID | CARNAME

1 | HYUNDAI
2 | FORD
3 | BMW

bound to a Model class "Car":

public Class Car{

  @Id
  @Column(name="ID")
  private Long id;

  @Column(name="FORD")
  private String carName;

  //getters and setters...
}

and in my code snippet (say in some controller class) I have to see whether the given car is a FORD car, the conditional code would be something like

if(thisCar.getCarName()=="FORD")

or

if(thisCar.getId()==2L)

but this creates some dependency issues between DB and app. what if I flush the cars table or restructure it and as a result FORD car entry goes at primary-key 3 same goes for string "FORD". what if tomorrow it changes to "FORDspeed" or something. I would have to change my code accordingly.

how do I make my code loosely coupled in this sense from data.

1

There are 1 best solutions below

3
On

I think you should not rely on field ID, because this may has changed as you said. So, phrase if(thisCar.getId()==2L) may has different result later time, so you should avoid it. But I think if(thisCar.getCarName()=="FORD") always has a static result and I think it has not any problem based on object oriented design.