Question

On m'a demandé de travailler sur ce travail programmé back-end qui exporte certaines données sur les clients (à partir d'une base de données de commerce électronique) vers un fichier texte personnalisé. Le code qui suit est ce que j'ai trouvé.

Je voudrais juste tout supprimer, mais je ne peux pas. Serait-il possible pour moi d'améliorer cela sans le changer autant?

public class AConverter implements CustomerConverter {

    protected final Logger LOG = LoggerFactory.getLogger(AConverter.class);

    private final static String SEPARATOR = ";";
    private final static String CR = "\n";

    public String create(Customer customer) {

        if (customer == null)
            return null;

        LOG.info("Exporting customer, uidpk: {}, userid: {}", customer.getUidPk(), customer.getUserId());

        StringBuilder buf = new StringBuilder();

        buf.append("<HEAD>");
        buf.append(SEPARATOR);
        buf.append(String.valueOf(customer.getUidPk()));
        buf.append(SEPARATOR);
        byte[] fullName = null;
        try {
            fullName = customer.getFullName().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e1) {
            fullName = customer.getFullName().getBytes();
        }
        String name = null;
        try {
            name = new String(fullName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            name = customer.getFullName();
        }
        buf.append(limitString(name, 40));
        buf.append(SEPARATOR);
        final CustomerAddress preferredShippingAddress = customer.getPreferredShippingAddress();
        if (preferredShippingAddress != null) {
            final String street1 = preferredShippingAddress.getStreet1();
            if (street1 != null) {
                buf.append(limitString(street1, 40));
            }
        } else {
            buf.append(" ");
        }
        buf.append(SEPARATOR);

        final String addressStr = buildAddressString(customer);
        buf.append(limitString(addressStr, 40));
        buf.append(SEPARATOR);
        buf.append(limitString(customer.getEmail(), 80));
        buf.append(SEPARATOR);
        if (preferredShippingAddress!=null && preferredShippingAddress.getStreet2() != null) {
            buf.append(limitString(preferredShippingAddress.getStreet2(), 40));
        } else {
            buf.append(" ");
        }
        buf.append(SEPARATOR);
        buf.append(limitString(customer.getPhoneNumber(), 25));
        buf.append(SEPARATOR);
        if (preferredShippingAddress!=null) {
            if(preferredShippingAddress.getCountry()!=null) {
                buf.append(preferredShippingAddress.getCountry());
            } else {
                buf.append(" ");
            }
        } else {
            buf.append(" ");
        }
        buf.append(SEPARATOR);
        if (preferredShippingAddress!=null) {
            if(preferredShippingAddress.getCountry()!=null) {
                buf.append(preferredShippingAddress.getCountry());
            } else {
                buf.append(" ");
            }
        } else {
            buf.append(" ");
        }
        buf.append(SEPARATOR);

        String fodselsnummer = " ";
        try {
            Map<String, AttributeValue> profileValueMap = customer.getProfileValueMap();
            AttributeValue attributeValue = profileValueMap.get("CODE");
            fodselsnummer = attributeValue.getStringValue();
        } catch (Exception e) {
        }
        buf.append(fodselsnummer);
        buf.append(CR);
        final String string = buf.toString();

        return string;

    }

    private String buildAddressString(Customer customer) {
        final CustomerAddress preferredShippingAddress = customer.getPreferredShippingAddress();
        if (preferredShippingAddress != null) {
            final String zipOrPostalCode = preferredShippingAddress.getZipOrPostalCode();
            final String city = preferredShippingAddress.getCity();
            if (zipOrPostalCode != null && city != null) {
                return zipOrPostalCode + " " + city;
            } else if(zipOrPostalCode == null && city != null) {
                return city;
            } else if(zipOrPostalCode != null && city == null) {
                return zipOrPostalCode;
            }
        }
        return " ";
    }

    private String limitString(String value, int numOfChars) {
        if (value != null && value.length() > numOfChars)
            return value.substring(0, numOfChars);
        else
            return value;
    }

}
Était-ce utile?

La solution

Vous dites que vous voulez l'améliorer, vous aimeriez le supprimer, mais vous ne pouvez pas. Je ne sais pas pourquoi vous ne pouvez pas. Je ne comprends pas non plus pourquoi vous voudriez le supprimer. Mais cela me ressemble au genre d'attitude que j'avais avant de lire Refactorisation par Martin Fowler. Je vous suggère fortement de lire ce livre, si vous ne l'avez pas déjà fait.

Il est certainement possible d'améliorer ce code (ou n'importe quel code) sans tout réécrire. Les améliorations les plus évidentes consisteraient à éliminer une partie du code répétitif dans le create Méthode en créant des méthodes d'utilité, puis en brisant le create Méthode en plusieurs méthodes plus petites à la mathématiques.

De plus, il y a un peu de code douteux dans le create Méthode qui transforme le nom du client en flux d'octets UTF-8, puis de retour en chaîne. Je ne peux pas imaginer à quoi cela sert. Enfin, il renvoie NULL si le client est nul. Il est peu probable qu'il soit nécessaire ou sage.

Pour le plaisir, j'ai décidé de faire un peu de refactorisation sur ce code. (Notez que le refactorisation appropriée implique des tests unitaires; je n'ai pas de tests pour ce code et je n'ai même pas compilé le code ci-dessous, encore moins testé.) Voici un moyen possible de réécrire ce code:

public class AConverter implements CustomerConverter {
    protected final Logger LOG = LoggerFactory.getLogger(AConverter.class);

    private final static String SEPARATOR = ";";
    private final static String CR = "\n";

    public String create(Customer customer) {
        if (customer == null) throw new IllegalArgumentException("no cust");

        LOG.info("Exporting customer, uidpk: {}, userid: {}",
                customer.getUidPk(), customer.getUserId());

        StringBuilder buf = new StringBuilder();
        doHead(buf, customer);
        doAddress(buf, customer);
        doTail(buf, customer);
        return buf.toString();
    }

    private void doHead(StringBuilder buf, Customer customer) {
        append(buf, "<HEAD>");
        append(buf, String.valueOf(customer.getUidPk()));
        append(buf, limitTo(40, customer.getFullName()));
    }

    private void doAddress(StringBuilder buf, Customer customer) {
        append(buf, limitTo(40, street1of(customer)));
        append(buf, limitTo(40, addressOf(customer)));
        append(buf, limitTo(80, customer.getEmail()));
        append(buf, limitTo(40, street2of(customer)));
        append(buf, limitTo(25, customer.getPhoneNumber()));
        append(buf, countryOf(customer));
        append(buf, countryOf(customer));
    }

    private void doTail(StringBuilder buf, Customer customer) {
        buf.append(fodselsnummerOf(customer));
        buf.append(CR);
    }

    private void append(StringBuilder buf, String s) {
        buf.append(s).append(SEPARATOR);
    }

    private String street1of(Customer customer) {
        final CustomerAddress shipto = customer.getPreferredShippingAddress();
        if (shipto == null) return " ";
        if (shipto.getStreet1() != null) return shipto.getStreet1();
        return " ";
    }

    private String street2of(Customer customer) {
        final CustomerAddress shipto = customer.getPreferredShippingAddress();
        if (shipto == null) return " ";
        if (shipto.getStreet2() != null) return shipto.getStreet2();
        return " ";
    }

    private String addressOf(Customer customer) {
        final CustomerAddress shipto = customer.getPreferredShippingAddress();
        if (shipto == null) return " ";

        final String post = preferredShippingAddress.getZipOrPostalCode();
        final String city = preferredShippingAddress.getCity();

        if (post != null && city != null) return post + " " + city;
        if (post == null && city != null) return city;
        if (post != null && city == null) return post;
        return " ";
    }

    private String countryOf(Customer customer) {
        final CustomerAddress shipto = customer.getPreferredShippingAddress();
        if (shipto == null) return " ";
        if (shipto.getCountry() != null) return shipto.getCountry();
        return " ";
    }

    private String limitTo(int numOfChars, String value) {
        if (value != null && value.length() > numOfChars)
            return value.substring(0, numOfChars);
        return value;
    }

    private String fodelsnummerOf(Customer customer) {
        try {
            Map<String, AttributeValue> profileValueMap =
                customer.getProfileValueMap();
            AttributeValue attributeValue = profileValueMap.get("CODE");
            return attributeValue.getStringValue();
        } catch (Exception e) {
            return " ";
        }
    }
}

Je remarque également qu'il y a un problème avec votre format pour le fichier texte de format personnalisé si l'un des champs des données client (adresse e-mail, par exemple) a un demi-colon, car c'est votre caractère séparateur. J'espère que c'est un problème connu?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top