Could anybody tell me the example below violate LSP or not?
I have an example:
public class Person {
private String name;
private Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public void validate() {
if (age == null || age < 0) {
throw new IllegalArgumentException("Age can not be null");
}
}
}
and the subclass:
public class Employee extends Person {
private String employeeCode;
public Employee(String name, Integer age, String employeeCode) {
super(name, age);
this.employeeCode = employeeCode;
}
@Override
public void validate() {
super.validate();
if (employeeCode == null) {
throw new IllegalArgumentException("Employee code can not be null");
}
}
}
and the main class:
public class Main {
public static void main(String[] args) {
Person person = new Person("Person", 10);
validate(person); // will be ok. does not throw any exception
Person employee = new Employee("Employee", 30, null);
validate(employee); // will be throw IllegalArgumentException because subtype's employee code is null
}
public static void validate(Person p) {
p.validate();
}
}
In this example the subclass add new property called employeeCode
and override method validate
with additional check for it's own property employeeCode
.
In the main method I create 2 objects. The first one is object of type Person
and the second one is object of type Employee
.
When validate person it is ok because all precondition is ok
but for the employee it will throw an IllegalArgumentException
because it does not match precondition
- Does
Employee
violate LSP due to add new validation onemployeeCode
? - If 1 is yes, how can I refactor it to avoid violate LSP?
- If 1 is no, if I change exception from
IllegalArgumentException("Employee code can not be null")
to another exceptionNullPointerException
. So does it violate LSP due to introduce new exception type in subtype (which super type does not have)?