简体   繁体   中英

Java Class: I need to add a new field of type String to a class. Should I extend (create a new derived class) or simply add the new field?

I am trying to know about best practice regarding this. I have a class with some fields. Now I need to add a new field of type String.

Most of the instances of that class don't need this new String field and hence it won't be set for those instances. Some instances will have this field set.

So should I create a new subclass and create the latter instances to be of this subclass? Please specify reason.

The case: you want to add String color to a Car , but it will not be in use for many of the usages.

I would not make a subclass here, but add:

Optional<String> color = Optional.empty();

The reason:

  • (Formal) It is a has-a relation, not a is-a.
  • It will not change business logic in existing parts.
  • It will have the least impact.

As I do not like null either init on "" , or use Optional .

The answer of your question depends on many things (is the system at production state, how much complexity the system has etc) and so there is not only one answer.

But while i was reading your question I mentioned something that seems to be a common mistake "Most of the instances of that class don't need this new String field" .

Keep in mind that this statement is a code smell. Because you "add" extra knowledge to objects that dont need. More abstractions upon this class is the only way to solve this problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM