Refactorized code to avoid problems with nulls and ensure uniqueness
with some classes.