PacktPublishing / Event-Driven-Architecture-in-Golang

Event-Driven Architecture in Golang, published by Packt
MIT License
336 stars 105 forks source link

feat: remove unnecessary switch statement #2

Closed kevin-vargas closed 1 year ago

kevin-vargas commented 1 year ago

Hi! the switch statement from the basket string method was unnecessary. The test cases I did were the following:

package domain

import (
    "testing"

    "github.com/stretchr/testify/assert"
)

func TestBasketString(t *testing.T) {
    // arrange
    cases := []struct {
        elem   BasketStatus
        expect string
    }{
        {
            BasketUnknown,
            "",
        },
        {
            BasketOpen,
            "open",
        },
        {
            BasketCancelled,
            "cancelled",
        },
        {
            BasketCheckedOut,
            "checked_out",
        },
    }
    for _, tt := range cases {
        // act
        actual := tt.elem.String()
        // assert
        assert.Equal(t, tt.expect, actual)
    }
}

p.d: Great Book!

stackus commented 1 year ago

Consider testing one more condition:

{
    BasketStatus("an_invalid_status"),
    ""
}

The two methods, using the switch with casting and using casting alone will give different results. The result from the method with the switch is the passing one.

The reason I use a switch before casting the value is because Go lacks an Enum type meaning we are forced to create our own mechanisms to ensure our Enum creations are correct. When strings are being Unmarshalled or written into a BasketStatus field Go is unfortunately more than happy to let any string in. The String() method provides some proper Enum value enforcement, but we are still able to read an invalid Enum value back out of we were to cast it back to its original type, for example with string(s).

How I have implemented string Enums is not the only way and it can be defeated by casting. Other approaches are suggested here: https://threedots.tech/post/safer-enums-in-go/

kevin-vargas commented 1 year ago

Perfect, thank you very much for the explanation.