Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
down casting polimorphic objects

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.

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!