How can I create a new class variable in 100+ existing classes?

Viewed 129

I am building a Java program that checks whether or not a car has prior damage by inspecting each part individually. Each part is divided into it's own class.

UML Diagram of a selection of car part classes: enter image description here

My problem is that each part already exists and needs a Boolean value called 'damage'. Is there a faster way to assign a damage variable to each class rather than doing it one by one?

3 Answers

Can you create an EnginePartHealth with an boolean value, isHealthy, say, that you can then add to each part that needs it?

Go for composition over inheritance if you can.. seems to be what you're doing already. This will enable your design to be more flexible. Using a parent class with a health indicator in it may also work but tends to be less flexible... it may still work for you though and requires less coding.. you may want to add some intermediate class that acts as a parent to any parts you want to maintain engine health on... saying that if you make Mirror a subclass of CarPart and it automatically inherits health, you may end up with a mess of parent classes for grouping lots of items that just confuses things beyond comprehension... favour composition over inheritance where possible.

You can then create an interface along the lines of Healthiness which will enable you to carry out health related operations on all classes implementing the interface (which you'll store high up in your application somewhere to make measuring health easier - in a list/map depending on how you want to access those parts' health).

enter image description here

You can define an interface Inspectable with a method isDamaged(). Your program can reply on this Inspectable.isDamaged() but not the actual damage attribute. As you mention there are 100+ classes so car parts may have different forms. You can place business logic in a method and provide flexibility. For a boolean variable, it only has true or false which does not have much variety.

Define another class CarPart which implements Inspectable and have a private damage attribute. It serves an superclass of all car parts in your application. If CarPart.isDamaged() do not fit some subclass need, they can override it and implement their own version of isDamaged().

While both options - common parent class and interface implementation will technically work, common parent is more suitable for your case. Interface implementation is mainly to define common behavior, while in your case you need to define common state.

Related