Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

186
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda