Java – Return array of multiple different objects

clean codecoding-stylejava

I have code along the following lines:

public void processInput() {
    List<String> input = readInput();
    final Object[] returnObj = createInternalStructureFrom(input);
    final Dictionary dictionary = (Dictionary) returnObj[0];
    final List<Order> orderList = (List<Order>) returnObj[1];
    final List<String> invalidInput = (List<String>) returnObj[2];

    // some more code that processes the created objects
}

private Object[] createInternalStructureFrom(final List<String> input) {

    // here is some code that creates objects along the lines of

    // Dictionary dictionary = createDictionaryFrom(input);
    // List<Order> orderList = createOrderListFrom(input);
    // List<String> invalidInput = getInvalidInputFrom(input);

    // but actually these methods can not be seperated
    // and all objects are created simultaniously when the input is parsed

    final Object[] returnObj = new Object[3];
    returnObj[0] = dictionary;
    returnObj[1] = orderList;
    returnObj[2] = invalidInput;
    return returnObj;
}

So the 'createInternalStructureFrom' method returns an array of objects of different kinds which are then cast to the corresponding type in the caller method.

Is this considered good practice in terms of writing clean code? What would be the alternatives?

Best Answer

Is this considered good practice in terms of writing clean code?

Hell, no! It's horrible.

What would be the alternatives?

Create a class which has those things as fields and return an instance of that class. Furthermore, that class can have methods which use the data to do useful things. That's what OOP means: put the logic where the data is instead of ferrying around the data between procedures.

Related Topic