There is a data block containing continuous packed data of structures of different types. It is necessary to read this data into an array. It was programmed like this:
class Handler{
//...
public List<MyStruct> getMyStructs(){
// when processing, some subsequent data depends on the
// processing of the previous ones
}
//...
}
abstract class MyStruct{
// Common method implementations for all structs
}
class ImpulsOne extends MyStruct{
// declaring and init fields
// methods
}
class ImpulsTwo extends MyStruct{
// declaring and init fields
// methods
}
//and etc...
After we have received the List, we live and enjoy life using the common methods that are in MyStruct.But this happens as long as there is no task to pull out and display or process several fields from several structures of certain types. There can be many such processing, and, unfortunately, each depends on the results of the previous processing.
The only thing I came up with is to do a downcast with each processing:
//...
SomeResult processing1(List<MyStruct> structs){
//...
for(var struct: structs){
if(struct instanceof ImpulsOne){
ImpulsOne impuls = (ImpulsOne) struct
// extracting fields and processing
}else if(struct instanceof ImpulsTwo){
ImpulsTwo = (ImpulsTwo) struct
// extracting fields and processing
}
// and many many else-if
}
}
//...
I don't like this approach and I'm sure it can be made easier.
I hope I have clearly explained the whole essence of the problem. Have you faced a similar problem? What ideas do you have to simplify the code?
Thanks.