Search code examples
javaunit-testingjunitassert

How to get one particular attribute from a class with several attributes?


I have this object. I want to access email attribute only in another class so I could check if the email is valid using assert in test directory. How do I access only email attribute from Person in another class to use it later to validate the email?

public  class Person {
String name;
int year;
int month;
int day;
String email;
String phonenr;

public Person(String name, int year, int month, int day, String email, String phonenr) {
    this.name = name;
    this.year = year;
    this.month = month;
    this.day = day;
    this.email = email;
    this.phonenr = phonenr;
}

This is the class I want to access email attribute from:

public class PersonValidator {
    public static boolean email(String email){
        Person onePerson = new Person();
        return false;
    }
}

This is test class to test if email is valid:

class PersonRegisterTest {

@Test
void checkValidEmail() {
 assertTrue(PersonValidator.email("[email protected]"));
 assertTrue(PersonValidator.email("[email protected]"));
 assertTrue(PersonValidator.email("[email protected]"));

}

Solution

  • Good practice in Java is to make all fields private, and create "getters and setters", i.e. functions to get and set values. For example:

    public class Person {
    
        private String email;
    
        public void setEmail(String email) {
            this.email = email;
        }
    
        public String getEmail() {
            return this.email;
        }
    }
    

    This way of doing things has several advantages:

    • If you you decide you want to change what values are allowed in a field, you can do that using the setter method. For example, if you want to impose a minimum length on emails, you can put if (email.length() < 10) return; in your method to prevent emails shorter than 10 characters

    • If you decide you want to retrieve emails over the internet or some other way, you do not have to change your code.

    • Many tools and frameworks expect Java objects to be in this format. Notable examples include Jackson for JSON serialization, and Spring/Spring Boot, for web application development, as well as many many more.

    P.S. if you are sick of writing getters and setters:

    1. Check if your IDE has a way of automatically generating them (most of them do)
    2. Look into a library called Lombok, it provides the @Data annotation which can generate these methods automatically at compile time. (https://projectlombok.org/)