Skip to content

Enhance tea.Msg handling using a polymorphic approach #12

@allisoneer

Description

@allisoneer

I've noticed that the Update function in the tableModel struct uses a switch statement to check for message types and handle them accordingly. Since tea.Msg is an interface, I was pondering a more Go-native, polymorphic approach that provides better separation of responsibilities and makes the code more organized and maintainable.

I have no idea the upstream bubbletea reasons for creating an interface nor do I know the codebase very well yet, it's just something I noticed. In the spirit of over engineering - Here is a recommendation that AI helped me create with my thoughts - just putting it here for reference.

The idea is to create a MsgHandler interface that all message handlers should implement:

type MsgHandler interface {
	Handle(msg tea.Msg) (tea.Model, tea.Cmd)
}

Then, separate structs can be created for each message type to handle, and the Handle method can be implemented for each of them:

type WindowSizeHandler struct {
	model *tableModel
}

func (h WindowSizeHandler) Handle(msg tea.Msg) (tea.Model, tea.Cmd) {
	// Handle WindowSizeMsg here
}

type KeyHandler struct {
	model *tableModel
}

func (h KeyHandler) Handle(msg tea.Msg) (tea.Model, tea.Cmd) {
	// Handle KeyMsg here
}

// Add more handlers for other message types if needed

Finally, the Update function can use a map to map message types to their respective handlers:

func (m tableModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	handlers := map[reflect.Type]MsgHandler{
		reflect.TypeOf(tea.WindowSizeMsg{}): WindowSizeHandler{model: &m},
		reflect.TypeOf(tea.KeyMsg{}):         KeyHandler{model: &m},
		// Add more handlers for other message types if needed
	}

	handler, ok := handlers[reflect.TypeOf(msg)]
	if ok {
		return handler.Handle(msg)
	}

	// If no handler is found for the given message type, update the table as before
	m.table, cmd := m.table.Update(msg)
	return m, cmd
}

This approach would make it easier to add new message handlers without modifying the Update function, just by adding new structs that implement the MsgHandler interface and updating the handlers map.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions