-2

I have tried this piece of code:

        String[] latitudesArray = latitudes.split(",");
        String[] longitudesArray = longitudes.split(",");

        Double startLat = StringUtils.isNotEmpty(latitudes) ?
                Double.valueOf(latitudes.split(",", 2)[0]) :
                null;

        Double endLat = StringUtils.isNotEmpty(latitudes) ?
                Double.valueOf(latitudes.split(",", 2)[1]) :
                null;

        Double startLong =  StringUtils.isNotEmpty(longitudes) ?
                Double.valueOf(longitudes.split(",", 2)[0]) :
                null;

        Double endLong =  StringUtils.isNotEmpty(longitudes) ?
                Double.valueOf(longitudes.split(",", 2)[1]) :
                null;

        Coordinate coordinate;
        if (latitudesArray.length == 1 && longitudesArray.length == 1 ) {
            coordinate = Coordinate.of(startLat, startLong);
        }   else {
            coordinate = centerOfRectangle(startLat, startLong, endLat, endLong);
        }

latitudes or longitudes can look like this:

String latitudes = "35.6701669,35.6968372"
String longitudes = "139.6891322,139.7003097" 

It can also be just a single latitude and longitude.

My question is: Can I improve my implementation ? Can I write it more elegant or efficient ?

lennon310
  • 3,132
  • 6
  • 16
  • 33
abc
  • 107
  • 3
  • Does this answer your question? [How would you know if you've written readable and easily maintainable code?](https://softwareengineering.stackexchange.com/questions/141005/how-would-you-know-if-youve-written-readable-and-easily-maintainable-code) – gnat Jan 06 '21 at 09:14
  • Why would you split latitudes and longitudes 3 times, instead of just once? You already split them. Just use that split version instead of splitting them again and again... – user253751 Jan 07 '21 at 02:29

1 Answers1

0

You could refactor some repeated code like this:

    String[] latitudesArray = latitudes.split(",");
    String[] longitudesArray = longitudes.split(",");

    Double startLat = getStart(latitudes);

    Double endLat = getEnd(latitudes);

    Double startLong = getStart(longitudes);

    Double endLong =   getEnd(longitudes);


    Coordinate coordinate;
    if (latitudesArray.length == 1 && longitudesArray.length == 1 ) {
        coordinate = Coordinate.of(startLat, startLong);
    }   else {
        coordinate = centerOfRectangle(startLat, startLong, endLat, endLong);
    }

    // somewhere else...
    private Double getStart(String[] arr)
    {
        return StringUtils.isNotEmpty(arr) ?
            Double.valueOf(arr.split(",", 2)[0]) :
            null;
    }

    private Double getEnd(String[] arr)
    {
        return StringUtils.isNotEmpty(arr) ?
            Double.valueOf(arr.split(",", 2)[1]) :
            null;
    }
FrustratedWithFormsDesigner
  • 46,105
  • 7
  • 126
  • 176