1
\$\begingroup\$

I have been learning Java for approximately 3 weeks now and made 2 posts on code review. Learned quite a lot from people and learned a lot of Java at the same time as well. I made this Age Calculator program to mainly practice with splitting up code into methods and classes as well as using method parameters and return types.

As for the program itself, it takes user input of birth year, month, and day, and prints out the difference. It also has a prompt to allow you to restart the program or terminate it. I was wondering if there's anything I can do in a better and elegant way.

Main class:

public class Main {
    
    // Main method to run application.
    public static void main(String[] args) {
        Application application = new Application();
        application.printInstructions();
        application.loopProgram();
    }
}

Application class:

import java.time.LocalDate;
import java.time.Period;
import java.util.Scanner;

public class Application {
    Scanner scan = new Scanner(System.in);
    
    // Calculates the age of a user.
    public String calculateAge(int year, int month, int day) {
        LocalDate today = LocalDate.now(); // Today's date
        LocalDate birthday = LocalDate.of(year, month, day); // Birth date
        Period dateDifference = Period.between(birthday, today);

        return "You are " + dateDifference.getYears() + " year(s), " + dateDifference.getMonths() + " month(s), "
                + dateDifference.getDays() + " day(s) old.";
        
    }
    
    // Prints a brief description about the program.
    public void printInstructions() {
        System.out.println("—————————————————————————————————————");
        System.out.println("Age Calculator - Calculates your current age using your birthday.");
        
    }
    
    // Loops the program until the user exits with 'N'.
    public boolean loopProgram() {
        String commandPrompt = "";
        
        while (!commandPrompt.equals("N")) {
            System.out.print("Enter your birth year: ");
            int birthYear = scan.nextInt();
            System.out.print("Enter your birth month: ");
            int birthMonth = scan.nextInt();
            System.out.print("Enter your birth day: ");
            int birthDay = scan.nextInt();
            scan.nextLine();
            
            System.out.println(calculateAge(birthYear, birthMonth, birthDay));
            System.out.print("Restart? (Y/N): ");
            commandPrompt = scan.nextLine().toUpperCase();
            System.out.println("—————————————————————————————————————");
        }
        
        return false;
    }
}
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

I have a lot experience with Java, but still, code is a very subjective thing, so on many things there is no single universal truth.

  1. Rename Application to AgeCalculator
  2. Application implements Runnable
  3. Encapsulate(make private) methods printInstructions and loopProgram in the Application and call only run from main. You are forcing the user of Application to learn how to start it(By user I mean other developer that would want to reuse the Application).
  4. No point in having Main class separate. It would make more sense to split logical operations into different classes, I would opt for splitting if I get over 200-300 of lines, or see a clear reason for it. So you could create a class for reading and printing to terminal and a class for calculating.
  5. You should create a method log() which would hide the ugly System.out.print(". This is totally subjective.
  6. Create a special method for printing ------------- as it is used more than once
  7. In this case it makes total sense that you define strings where you use them, but it is more optimal to use constants, so the string does not have to be created a new every time you use it.
  8. Make calculateAge private. By default you wanna make everything private unless you really need to make it otherwise.
  9. You are providing the results of calculation already as a formatted string, so if you'd like to reuse it you would have to change this method.

New task: try creating also a calculator for how many days till next birthday. Create a new interface. Separate the logic for calculating the age and next birthday to new classes and make them both implement the Calculator interface.

\$\endgroup\$
3
  • \$\begingroup\$ Thank you for your input! I realized that code indeed is pretty subjective and there's really no right or wrong in most cases. You raised very good points but I was wondering what you meant by splitting the logic for calculating age and next birthday and have them implement the Calculator interface. \$\endgroup\$ Commented Jul 13, 2021 at 18:11
  • \$\begingroup\$ I was suggesting for you to do another exercise - to add also days till next birthday functionality. I was suggesting then to create a separate classes where 1 would be holding just a method for calculating the age, the other just for next birthday. Both would be implementing an interface. You can then play around with referring to the calculators in main app just through that interface. Try to do an UML diagram of it. This will help you better understand the principles of Object oriented programming. \$\endgroup\$
    – Javo
    Commented Jul 14, 2021 at 15:30
  • \$\begingroup\$ Ah, I see. Well, thank you for your input again. I will mark this as solved :). \$\endgroup\$ Commented Jul 14, 2021 at 16:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.