B
B
Bogdan Khvalko2019-02-17 17:19:34
Java
Bogdan Khvalko, 2019-02-17 17:19:34

How to avoid code duplication in java?

private int getCountLines ()
    {
        int countLines = 0;

        try {
            String query = "SELECT  COUNT(*) FROM " + tableName + this.where;

            Statement stmt = connection.createStatement();
            ResultSet resultSet = stmt.executeQuery(query);
            resultSet.next();
            countLines = resultSet.getInt(1);

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return countLines;
    }

There is a method which considers an amount of records at the given request. The request is formed based on the data passed to the constructor. I need to count the number of all records in a table and the number of selected records. How to make a function flexible so that it alone performs these two tasks?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Bogdan Khvalko, 2019-02-17
@quitting

Perhaps bydlokod (if yes, write down), but washed down just such garbage.

private int getCountLines (boolean allElements)
    {
        int countLines = 0;

        try {
            String query = "SELECT  COUNT(*) FROM " + tableName;
            if (allElements) {
                query += this.where;
            }

            Statement stmt = connection.createStatement();
            ResultSet resultSet = stmt.executeQuery(query);
            resultSet.next();
            countLines = resultSet.getInt(1);

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return countLines;
    }


    private int getCountLines ()
    {
        return getCountLines(true);
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question