Pergunta

Imagine scenario: need to strip out spaces from a string to be used lets say in url.

Now would it be smart to do this once before saving in DB, and than use raw db results when outputting. Or would it be smart to write helper function and just do space removal when outputting and keep data saved raw in DB?

Foi útil?

Solução

It makes more sense to cleanup the data and store it into the database instead of storing it "raw" and then cleaning it up on reads.

It's like with every other piece of information you store in a database:

  • you validate the data;
  • sanitize it if needed (in this case removing unnecessary spaces);
  • persist it;
  • if needed, assert it has the format you expect when you read it back.

So clean it up before saving it to the DB.

Outras dicas

Try as much as you can not to store garbage in your database. If you can trim off leading or trailing spaces from a URL before inserting it into a database table, do it.

In the other hand, you could write a trigger in the table that does that before inserting the value.

Any solution can potentially be comprised of more that just one front end (one web front-end, one Android front-end, one iPhone front-end, etc.). So relying in "the app", assumming that no other front-end will ever, never exist to the same back-end is something we should not assume.

So my recommendation is try not to insert garbage into tables only to clean it before outputing it to the user. You could potentially end up writing space-stripping code in a whole lot of places when you output that value from DB instead of doing it in just before inserting.

Licenciado em: CC-BY-SA com atribuição
scroll top