55502f40dc8b7c769880b10874abc9d0

At work I was told to optimize a part of an application, looking into the code I found this beast method and I am sick of looking at it and not finding what is going on, can some one please refactor this for me... Thanks in advance

/**
     * Retrives the student line items for the reports, calculates avg and grades
     * @param team the team line item object
     * @param howIwasRated if true retrives the information about "how I was rated by my team" if not "how I rated my team"
     * @param includeComments boolean to include comments or not
     * @param summaryReport checks if it is a summary report
     * @return  a list of student Line Items
     */
    @Transactional(readOnly = false)
    public List<StudentLineItem> getStudentLineItems(TeamLineItem team, boolean howIwasRated, boolean includeComments, boolean summaryReport) {

        List<StudentLineItem> studentList = new ArrayList<StudentLineItem>();
        double teamTaskAvg = 0;
        double teamProcessAvg = 0;
        double teamTaskAvgWithOut = 0;
        double teamProcessAvgWithOut = 0;
        Boolean isPosted = false;
        StudentUser su;

        try {
            su = userManager.findStudentUserByPrimaryKey((Integer) FacesHelper.sessionFind(UserConstants.USER_ID));
            su.getId(); //this throws an exception if it's not a student....
        } catch (Exception e) {
            //It's an instructor!
            if (log.isErrorEnabled()) {
                log.error("IT'S AN INSTRUCTOR");
            }
            su = null;
        }

        //With this I only get the enrollments from this team.
        List<StudentEnrollment> enrollments = getCourseStudentEnrollmentsByTeamNumber(team.getTeamNo(), su, summaryReport);


        Boolean checkPosted = (task.getName().equals(CourseContext.PEER_EVALUATION) ||
                task.getName().equals(CourseContext.PEER_FEEDBACK)) &&
                su != null && howIwasRated;//only how I was rated by my team checks for posted


        if (checkPosted) {
            int teamNumber = 0;

            for (StudentEnrollment se : enrollments) {
                if (se.getStudentUser() != null) {
                    if (se.getStudentUser().getId().equals(su.getId())) {
                        teamNumber = se.getTeamNumber();
                        break;
                    }
                }
            }
            PostedTask pt = taskManager.findPostedTask(task.getId(), teamNumber);
            boolean isPostable = task.evaluatePostedDate();
            if (pt == null && !isPostable) {
                //we aren't posted, so remove all but this student
                for (StudentEnrollment se : course.getStudentEnrollments()) {
                    if (se.getStudentUser() != null) {
                        if (!se.getStudentUser().getId().equals(su.getId())) {
                            //is not this user, remove.
                            enrollments.remove(se);
                        }
                    } else {
                        //it is not this user because is a discrepancy.
                        enrollments.remove(se);
                    }
                }
            } else {
                isPosted = true;
            }
        }

        for (StudentEnrollment enrollment : enrollments) {
            StudentUser studentUser = (enrollment.isMatched()) ? enrollment.getStudentUser() : getStudentFromDiscrepancy(enrollment.getDiscrepancy());
            List<FeedBackAnswer> answers;
            StudentLineItem studentLineItem = buildLineItem(studentUser, enrollment, team);

            // Get the question about the comments (We only need the answers for this specific question)
            for (Question question : task.getTaskType().getQuestions()) {
                if (includeComments || !question.isCommentable()) {
                    EventQuestion eventQuestion = new EventQuestion();
                    EventQuestion teamQuestionAverages = team.getQuestion(question.getId());

                    eventQuestion.setId(question.getId());
                    eventQuestion.setDescription(question.getLabel() + ". " + question.getText());
                    eventQuestion.setCommentable(question.isCommentable());
                    
                    // Adds the EventQuestionItem object in the list of questions for the team averages.
                    if (teamQuestionAverages == null) {
                        teamQuestionAverages = new EventQuestion();
                        teamQuestionAverages.setId(question.getId());
                        teamQuestionAverages.setDescription(question.getText());
                        team.addQuestion(teamQuestionAverages);
                    }

                    List<FeedBackAnswer> feedbackAnswers = getFeedbackAnswers(enrollment, question, howIwasRated);
                    answers = getAnswersForSubmittedAssessments(feedbackAnswers, howIwasRated);
                    //answers = feedbackAnswers;
                    
                    // SELF ANSWER
                    if (enrollment.isRegistered()) {
                        for (FeedBackAnswer answer : answers) {
                            boolean selfAnswer = isSelfAnswer(studentUser, answer, howIwasRated);
                            if (selfAnswer) {
                                if (question.getType() != null) {
                                    if (question.isProcessType()) {
                                        studentLineItem.setLeadershipEvaluation(doubleFromString(answer.getAnswer()));
                                    } else if (question.isTaskType()) {
                                        studentLineItem.setTaskEvaluation(doubleFromString(answer.getAnswer()));
                                    }
                                }
                                eventQuestion.setEvaluation(doubleFromString(answer.getAnswer()));
                                eventQuestion.setComments(answer.getAnswerText());
                                break;
                            }
                        }
                    }

                    // PEER ANSWER ! ME
                    double taskAverage = 0;
                    int totalStudentsTasks = 0;
                    double processAverage = 0;
                    int totalStudentsProcess = 0;
                    double taskAverageWithOut = 0;
                    int totalStudentsTasksWithOut = 0;
                    double processAverageWithOut = 0;
                    int totalStudentsProcessWithOut = 0;

                    double questionAverage = 0;
                    int totalStudentsAnswers = 0;
                    double questionAverageWithoutSelf = 0;
                    int totalStudentsAnswersWithoutSelf = 0;

                    if (su == null || isPosted || !howIwasRated) {
                        //ONLY SHOW MY PEER EVALUATIONS IF THE TASK HAS BEEN POSTED for howIwasRated
                        //OR IS NOT A TASK THAT NEEDS TO BE POSTED

                        for (FeedBackAnswer answer : answers) {
                            boolean selfAnswer = (enrollment.isRegistered() &&
                                    isSelfAnswer(studentUser, answer, howIwasRated));

                            StudentUser evaluatedStudent = getEvaluatedStudent(answer, howIwasRated);

                            double answerValue = doubleFromString(answer.getAnswer());

                            StudentLineItem studentSubLineItem = new StudentLineItem();
                            studentSubLineItem.setTeamNo(enrollment.getTeamNumber());
                            studentSubLineItem.setFirstName(evaluatedStudent.getFirstName());
                            studentSubLineItem.setLastName(evaluatedStudent.getLastName());
                            studentSubLineItem.setId(evaluatedStudent.getId());
                            studentSubLineItem.setEvaluation(answerValue);
                            studentSubLineItem.setComments(answer.getAnswerText());    
                            questionAverage += answerValue;
                            totalStudentsAnswers++;
                            questionAverageWithoutSelf += selfAnswer ? 0 : answerValue;
                            totalStudentsAnswersWithoutSelf += selfAnswer ? 0 : 1;

                            if (question.getType() != null) {
                                if (question.isTaskType()) {
                                    studentSubLineItem.setTaskEvaluation(answerValue);
                                    taskAverage += answerValue;//task
                                    totalStudentsTasks++;
                                    taskAverageWithOut += selfAnswer ? 0 : answerValue;
                                    totalStudentsTasksWithOut += selfAnswer ? 0 : 1;
                                } else if (question.isProcessType()) {
                                    studentSubLineItem.setLeadershipEvaluation(answerValue);
                                    processAverage += answerValue;//process
                                    totalStudentsProcess++;
                                    processAverageWithOut += selfAnswer ? 0 : answerValue;
                                    totalStudentsProcessWithOut += selfAnswer ? 0 : 1;
                                }
                            }

                            if (!selfAnswer) {
                                eventQuestion.addStudentEvaluation(studentSubLineItem);
                                studentLineItem.addStudentLineItem(studentSubLineItem);
                            }

                        }

                    }

                    //Check if only the self student answered the question.
                    if (totalStudentsAnswersWithoutSelf == 0) {
                        totalStudentsAnswersWithoutSelf = 1;
                    }
                    if (totalStudentsTasksWithOut == 0) {
                        totalStudentsTasksWithOut = 1;
                    }
                    if (totalStudentsProcessWithOut == 0) {
                        totalStudentsProcessWithOut = 1;
                    }
                    if (totalStudentsAnswers > 0 && totalStudentsAnswersWithoutSelf > 0) {
                        // Calculates the average for the current question
                        eventQuestion.setAverage(questionAverage / totalStudentsAnswers);
                        eventQuestion.setAverageWithoutSelf(questionAverageWithoutSelf / totalStudentsAnswersWithoutSelf);
                        // Calculates the team average for the current question
                        teamQuestionAverages.setAverage(teamQuestionAverages.getAverage() + eventQuestion.getAverage());
                        teamQuestionAverages.setAverageWithoutSelf(teamQuestionAverages.getAverageWithoutSelf() + eventQuestion.getAverageWithoutSelf());

                        if (question.getType() != null) {
                            if (question.isTaskType()) {
                                studentLineItem.setTaskAverage(taskAverage / totalStudentsTasks);//task
                                studentLineItem.setTaskAverageWithoutSelf(taskAverageWithOut / totalStudentsTasksWithOut);
                                teamTaskAvg += studentLineItem.getTaskAverage();
                                teamTaskAvgWithOut += studentLineItem.getTaskAverageWithoutSelf();
                            } else if (question.isProcessType()) {
                                studentLineItem.setLeadershipAverage(processAverage / totalStudentsProcess);//process
                                studentLineItem.setLeadershipAverageWithoutSelf(processAverageWithOut / totalStudentsProcessWithOut);
                                teamProcessAvg += studentLineItem.getLeadershipAverage();
                                teamProcessAvgWithOut += studentLineItem.getLeadershipAverageWithoutSelf();
                            }
                        }
                    }

                    studentLineItem.addEventQuestion(eventQuestion);
                }
            }
            studentList.add(studentLineItem);
        }

        // Calculates the TEAM AVERAGES
        for (EventQuestion questionItem : team.getEventQuestionItems()) {
            double questionItemIndex = 0;
            questionItem.setAverage(questionItem.getAverage() / studentList.size());
            questionItem.setAverageWithoutSelf(questionItem.getAverageWithoutSelf() / studentList.size());
            for (StudentLineItem studentItem : studentList) {
                for (EventQuestion studentQuestionItem : studentItem.getEventQuestionItems()) {
                    if (studentQuestionItem.getId().equals(questionItem.getId())) {
                        if (questionItem.getAverageWithoutSelf() > 0) {
                            studentQuestionItem.setIndex(studentQuestionItem.getAverageWithoutSelf() / questionItem.getAverageWithoutSelf());
                        }
                        questionItemIndex += studentQuestionItem.getIndex();
                        break;
                    }
                }
            }
            questionItem.setIndex(questionItemIndex / studentList.size());
        }


        team.setTeamLeadershipTotalAverage(teamProcessAvg / studentList.size());
        team.setTeamLeadershipTotalAverageWithoutSelf(teamProcessAvgWithOut / studentList.size());
        team.setTeamTaskTotalAverage(teamTaskAvg / studentList.size());
        team.setTeamTaskTotalAverageWithoutSelf(teamTaskAvgWithOut / studentList.size());

        //put the dataset std dev here.

        return studentList;
    }

Refactorings

No refactoring yet !

220a1ce7a99b513ece2aca0f6d4688c7

zetafish

October 6, 2009, October 06, 2009 07:37, permalink

1 rating. Login to rate!

This method is too big, it tries to do too many things. I would start by splitting the huge method into managable parts. I aim to keep my bigger methods no longer than a single page. Also right at the start you catch an exception and set the su to null and continue with the method but checking everywhere if su is not null. Seems simpler to not catch at all and let the exception be handled somewhere higher.

Your refactoring





Format Copy from initial code

or Cancel