Altering Execution Flow

Dengan menggunakan mekanisme try catch sebuah exception, kita bisa bikin eksekusi code kita melompat – lompat sesuai keinginan kita. Ini biasanya kita gunakan untuk sanity check dari variable yang kita punya.

Contohnya adalah code berikut ini (penjelasannya ada di comment dari method berikut ini):

protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object, BindException bindException) throws Exception {
    // user must be authenticated (avoids auth errors)
    if (Context.isAuthenticated()) {
        HttpSession httpSession = request.getSession();
        httpSession.setMaxInactiveInterval(-1); // don't let the session expire

        String password = ServletRequestUtils.getStringParameter(request, "password");
        String passphrase = ServletRequestUtils.getStringParameter(request, "passphrase");

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        byte[] iv = new byte[IV_SIZE];
        try {
            MultipartFile secretFile = multipartRequest.getFile("secretFile");
            // sanity check
            if (secretFile == null || secretFile.isEmpty())
                throw new IOException("Unable to read secret file.");
            InputStream secretFileInputStream = secretFile.getInputStream();
            int ivSize = secretFileInputStream.read(iv);
            // make sure the iv is 16 byte
            if (ivSize != IV_SIZE)
                throw new IOException("Secret file is corrupted or invalid secret file are being used.");
            secretFileInputStream.close();

            MultipartFile returnedData = multipartRequest.getFile("summaries");
            // sanity check
            if (returnedData == null || returnedData.isEmpty())
                throw new IOException("Unable to read collection of summaries file.");
            InputStream summariesInputStream = returnedData.getInputStream();

            FileUtils.inflateSummaries(summariesInputStream, SummaryConstants.OUTPUT_LOCATION, password, passphrase, iv);
            FileUtils.loadIndexFile("summaryindex.sql");

            summariesInputStream.close();

            String message = "Inflating collection of summary files completed successfully. Please check if files are decrypted succesfully.";
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, message);
        }
        catch (Exception e) {
            log.error("Inflating collection of summary files failed", e);
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, e.getMessage());
        }
        return new ModelAndView(new RedirectView(getSuccessView()));
    }
    return showForm(request, response, bindException);
}

Inti dari tips kali ini adalah throwing exception didalam try catch block. Dengan mekanisme ini, flow dari program kita akan berubah sesuai dengan exception yang terjadi. Contohnya saat ivSize yang dibaca tidak sesuai dengan minimum yang kita inginkan, kita bisa men-throw exception disana dan exception ini akan di-catch kemudian sebuah error message akan ditampilkan di halaman web yang sedang dibuka oleh user.

            if (ivSize != IV_SIZE)
                throw new IOException("Secret file is corrupted or invalid secret file are being used.");

Dengan mekanisme ini, kita bisa mengatur flow eksekusi program kita tanpa if-then-else dan tanpa explicit goto.

9 thoughts on “Altering Execution Flow

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s