How to implement custom type safety

66 views Asked by At

I have 3 SpringBoot projects:

  • Producer (producer of messages)
  • Consumer (consumer of messages)
  • Commons (Domain objects shared b/w Producer and Consumer)

Message class is as below:

public class Message {
  private String eventType;
  private String Payload; //serialized
}

Payload class is as below:

public class Payload {
    private DomainObjectA a;
    private DomainObjectB b;
    private DomainObjectC c;
    private DomainObjectD d;
}

There are 2 type of events CREATE and UPDATE, and the Producer application can produce 2 types of Messages(to ActiveMQ) depending on type of event.
I need to maintain a single queue in Consumer project which will accept Messages for both kind of events.

For CREATE event I need to build all domain objects, while for UPDATE event need to build DomainObjectA and DomainObjectB only.

    if("CREATE".equals(eventType)
    {
         build DomainObjectA;
         build DomainObjectB;
         build DomainObjectC;
         build DomainObjectD;
         set above objects in Payload object  
    
         set Payload from above in Message object
         set CREATE as eventType in Message object
    }
    else if("UPDATE".equals(eventType)
    {
         build DomainObjectA;
         build DomainObjectB;
         set above objects in Payload object
      
         set Payload from above in Message object
         set UPDATE as eventType in Message object
    }

Currently, the producer need to know which domain objects to build in Payload depending on type of event, so this is not TypeSafe (as producer might try to set unwanted domain objects).

How can I make this typesafe and have a solution as shown below:

public class Message {
      private String eventType;

     //want to make Payload dynamic depending on the eventType
     // for CREATE eventType i want CreatePayload while for UPDATE i want UpdatePayload 
      private String Payload;
    }


    public class CreatePayload implements Serializable {
        private DomainObjectA a;
        private DomainObjectB b;
        private DomainObjectC c;
        private DomainObjectD d;
    }

    public class UpdatePayload implements Serializable {
        private DomainObjectA a;
        private DomainObjectB b;
    }

Any pointers are appreciated.Thank you.

0

There are 0 answers