0

I have an object retrieved from a form. It can contains some unwanted characters like "/n". I would like to remove them. I've found a way of doing it but I'm pretty sure it's possible to do it in a cleaner and shorter way?

List<Client> clients1 = pc.getClients();
List<Client> clients2 =new ArrayList<Client>();

if (clients1 != null) {
    for (Client tc : clients1) {    
        tc.setClientId(tc.getClientId().replaceAll("\\p{C}", ""));
        tc.setClientName(tc.getClientName().replaceAll("\\p{C}", ""));
        tc.setCallFirstName(tc.getClientFirstName().replaceAll("\\{C}",""));
        clients2.add(tc);
    }
}

pc.setClients(client2)

Any suggestions? The point of this question for me is to learn how to make better code.

deHaar
  • 17,687
  • 10
  • 38
  • 51
Jean
  • 601
  • 1
  • 10
  • 26

1 Answers1

4

The "clean code" answer would be framed around the Tell, don't ask principle.

In your case: you are first fetching (asking!) some attribute from a Client object, to make changes to that, to re-set the property.

Why not just go and tell the Client tc.normalizeFields() or something alike?!

Meaning: instead of having another class cleaning up fields of the Client class, put all of that code into the Client class itself! And have one method that internally works all fields that require "cleaning". So that when fields are added or removed, other classes do not need to be changed. The code you are showing needs to be updated each time you add/remove/change your fields.

When your Client class is more of a bean/data thing (that only carries around data, without any specific behavior, aka methods of its own), then you should consider to use a separate ClientNormalizerService class that encapsulates this work for you.

GhostCat
  • 137,827
  • 25
  • 176
  • 248