javafallback

Fallback Mechanism - Best approach?


I have three different types of server connection. These can be configured in properties file.

Say there are three servers:

Server1
Server2
Server3

In Properties file, I've configured as below:

ServerPref1 = Server1
ServerPref2 = Server2
ServerPref3 = Server3

In code level, my fall back mechanism is as below:

    private static void getServerAndConnect() {
        try {
            connect(Properties.ServerPref1);
        } catch (ServerException se1) {
            try {
                connect(Properties.ServerPref2);
            } catch (ServerException se2) {
                try {
                    connect(Properties.ServerPref3);
                } catch (ServerException se3) {
                    // Unable to connect
                }
            }
        }
    }

The connect() method will throw custom ServerException, if unable to connect to server.

Everything works as expected.

My question is: Is this the correct or best way to implement fallback mechanism?


Solution

  • I'd recommend a list of server connections then you can use a loop instead of nesting, this will let you add more servers without code changes.

    Since you have separate attributes for each connection the best I can offer without seeing the rest of your code is to put those fields into a temporary list and loop over that.

    Ideally make your properties parsing code write the connections into a List as well so you can have arbitrary number of servers without adding new fields to your Properties class.

    private static void getServerAndConnect() {
        List<ServerPref> serverPrefs = Arrays.asList(Properties.ServerPref1, Properties.ServerPref2, Properties.ServerPref3);
    
        for (ServerPref serverPref : serverPrefs) {
            try {
                connect(serverPref);
                // test success of connection? and break out of the loop
                break;
            } catch (ServerException se1) {
                // log error and go onto next one
            }
        }
    }