package com.corejsf; import java.io.Serializable; import java.util.ArrayList; import javax.inject.Named; // or import javax.faces.bean.ManagedBean; import javax.enterprise.context.SessionScoped; // or import javax.faces.bean.SessionScoped; @Named // or @ManagedBean @SessionScoped public class QuizBean implements Serializable { private ArrayList<ProblemBean> problems = new ArrayList<ProblemBean>(); private int currentIndex; private int score; public QuizBean() { problems.add( new ProblemBean(new int[] { 3, 1, 4, 1, 5 }, 9)); // pi problems.add( new ProblemBean(new int[] { 1, 1, 2, 3, 5 }, 8)); // fibonacci problems.add( new ProblemBean(new int[] { 1, 4, 9, 16, 25 }, 36)); // squares problems.add( new ProblemBean(new int[] { 2, 3, 5, 7, 11 }, 13)); // primes problems.add( new ProblemBean(new int[] { 1, 2, 4, 8, 16 }, 32)); // powers of 2 } public void setProblems(ArrayList<ProblemBean> newValue) { problems = newValue; currentIndex = 0; score = 0; } public int getScore() { return score; } public ProblemBean getCurrent() { return problems.get(currentIndex); } public String getAnswer() { return ""; } public void setAnswer(String newValue) { try { int answer = Integer.parseInt(newValue.trim()); if (getCurrent().getSolution() == answer) score++; currentIndex = (currentIndex + 1) % problems.size(); } catch (NumberFormatException ex) { } } }
The QuizBean class defines a JSF managed bean named quizBean with session scope. The name "quizBean" is not specified explicitly; it is a default name derived from the class name. It has the following bean properties, which are not very well named:
The reason for making answer is read-write is that it is used in a text field. A text field can display an initial value as well as receive input from the user. In this application displaying an initial value is not desirable so the getter just returns an empty string.
There are two problems with naming of the quizBean properties:
Adjectives like "current" do not make good property names. A noun such as "problem" is much better. The name of a property should suggest what the property is, not just one of its characteristics.
A characteristic of a property may be useful as part of its name. For example, the name "currentProblem" may be desirable when the application needs to deal with, say, both the correct answer to the previous problem and the question for the current problem.
The name "answer" is ambiguous. It could have two possible meanings:
Here, the second meaning is intended. The name "response" would clarify the intention.