-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 ?

2

1 Answer 1

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;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.