What would be the best type of class to use for a module representation?

51 views Asked by At

To clarify the title: I've got a multi-module app that has 5 feature-modules, I've set up navigation etc. but currently for my bottom navigation bar everything is hard-coded, the paths to graphs + icons + titles, I'm trying to find a way to create a class / object of some sort that would let me to just do something like:

val nestedGraphsRoutes = listOf(
    ProductModuleInfo,
    CategoriesModuleInfo,
    SearchModuleInfo,
    ProfileModuleInfo,
    CartModuleInfo
)
BottomNavigation() {
    nestedGraphsRoutes.forEach { graph ->
        BottomNavigationItem(
            label = {Text(graph.title)},
            icon = {Icon(painterResource(graph.icon, null)},
            selected = {...},
            onClick = {navController.navigate(graph.routes.nestedGraphRoute)} // I want the "routes" to contain other strings as well
    }
}

however I currently cannot think what wound fit well here, I'm currently using simple objects and that's... not pleasant to work with

Thanks in advance, cheers

1

There are 1 answers

0
VonC On BEST ANSWER

Holding module representation is like holding data: why not a "Data class"?

Data classes are a concise way of creating classes used mainly for holding data. They implicitly declare component functions, equals(), hashCode(), toString(), and others based on the properties declared in the primary constructor.

For example, in the context of your use case:

data class ModuleInfo(
    val title: String,
    val icon: Int,
    val routes: Routes
) {
    data class Routes(
        val nestedGraphRoute: String,
        // Add other strings as needed
    )
}

You can then create your instances like so:

val ProductModuleInfo = ModuleInfo(
    title = "Product",
    icon = R.drawable.ic_product,
    routes = ModuleInfo.Routes(
        nestedGraphRoute = "ProductNestedGraphRoute",
        // other strings...
    )
)

// Repeat for other modules

And then you can use these instances in your BottomNavigation() call:

val nestedGraphsRoutes = listOf(
    ProductModuleInfo,
    CategoriesModuleInfo,
    SearchModuleInfo,
    ProfileModuleInfo,
    CartModuleInfo
)

BottomNavigation() {
    nestedGraphsRoutes.forEach { graph ->
        BottomNavigationItem(
            label = { Text(graph.title) },
            icon = { Icon(painterResource(graph.icon), contentDescription = null) },
            selected = { /*...*/ },
            onClick = { navController.navigate(graph.routes.nestedGraphRoute) }
        )
    }
}

That way, the ModuleInfo instances are effectively replacing the hard-coded data in your BottomNavigation() call. Each module is represented by an instance of ModuleInfo and that instance carries all the necessary information (title, icon, routes) for the BottomNavigationItem.

That should give you a more flexible and clean way to organize your module information.