Recently I had an assignment in a computer science course to create a class with two objects built from said class.
The professor's criticism through email was the following: "sysouts in constructor, getters, and setters these should be in the main method."
He doesn't speak English very well so that doesn't help much. Does anybody know what exactly he's talking about in reference to my code? This is the code I submitted:
public class Book {
int currentPage;
int nextPage;
int lastPage;
public Book(int pageNumber) {
currentPage = pageNumber;
System.out.println("You've opened the book to page " + currentPage + ".");
}
public void turnForward(int numTurned) {
nextPage = numTurned + currentPage;
System.out.println("You've turned forward to page " + nextPage + ".");
}
public void turnBack(int numTurned) {
lastPage = nextPage - numTurned;
if (lastPage <= 1) {
lastPage = 1;
System.out.println("You've turned back to the first page.");
}else {
System.out.println("You've turned back to page " + lastPage + ".");
}
}
public static void main(String[] args) {
Book bigJava = new Book(5);
bigJava.turnForward(2);
bigJava.turnBack(8);
Book earlyObjects = new Book(22);
earlyObjects.turnForward(12);
earlyObjects.turnBack(17);
}
}
Is it mandatory to put getters/setters in the main method? The code doesn't actually run if I do.
He's referring to the reusability of your class. He wants you to expose getters so you'll be able to put your print statements in the main method.
If someone else wanted to use your class, or maybe you want to reuse it for a different project, stuff should not print to the console. Not every situation where Book
may be used should print stuff to the console.
Thus it's best to keep the logging in the main method, so Book
can be reused for other tasks.
Getters allow you to access the values while still keep your fields private
, ensuring the only way they can be modified is through the behaviors you exposed: turnForward
, turnBack
, etc..
When you turn a page, the current page should change. It doesn't make sense for it to stay the same.
Your behavioral methods should instead be mutating the currentPage
variable:
public void turnForward(int pages) {
currentPage += numOfPages;
}
public void turnBack(int numOfPages) {
currentPage -= numOfPages;
}
public int getCurrentPage() {
return currentPage;
}
Your main method could then turn the pages, logging every time it does:
public static void main(String[] args) {
Book book = new Book(25);
int startPage = book.getCurrentPage();
book.turnForward(5);
int endPage = book.getCurrentPage();
System.out.println("The book was turned " + endPage - startPage + " pages forward.");
}