lundi 6 décembre 2021

How can I separate methods from a class which still requires some state in order to work

Suppose I have restaurant class(aggregate) which is responsible for managing orders and food details. It may look like this

data class Food(
  val foodId: String,
  val total: Int
)

data class Order(
  val orderId: String
)

class RestaurantAggregate {
  // aggregate identifier
  val restaurantId: String
  val foodLimit = 10
  val orderLimit = 30

  val foodList = listOf<Food>()
  val orderList = listOf<Order>()

  fun handle(cmd: CreateOrder){
    if (orderList.size >= 30) throw error
    if (!foodList.exist(cmd.foodId)) throw error
    // total of food > 0
    if (!foodList.isAvaible(cmd.foodId)) throw error
    // .. do
  }
  // .. too many commands managing order

  fun handle(cmd: CreateFood){
    if (foodList.size >= 10) throw error
    // .. do
  }
  // .. too many commands managing food
}

After a while of development, there are a lot of commands in a class and it looks like a god class so I want to separate these methods into its own class, but in order to make it works it still requires some state from aggregate root anyway.

// I want to separate management to antoher class
class Restaurant {
  // aggregate identifier
  val restaurantId: String
  val foodLimit = 10
  val orderLimit = 30

  val foodList = listOf<Food>()
  val orderList = listOf<Order>()
  // this will be aggregate member so it can handle commands/events
  val orderMgmt = OrderManagement()
  val foodMgmt = FoodManagement()
}

class OrderManagement {
  fun handle(cmd: CreateOrder){
    // but it will require some state from the aggregate root anyway
    if (orderList.size >= 30) throw error
    if (!foodList.exist(cmd.foodId)) throw error
    // .. do
  }
  // .. many of commands
}

class FoodManagement {
  // same as above
}

so I though I could use dependency injection and inject the state to the aggregate child, but is there any better way of doing it?. btw I use axonframework version 4.4.7

Aucun commentaire:

Enregistrer un commentaire