What do you name a protocol abstracting over types that can encode another type?

i have an enum that looks like

enum State 
{
    case alabama 
    case arkansas 
    ...
}
enum Province 
{
    case ontario 
    case quebec 
    ...
}

and a super-enum that looks like

enum Region 
{
    case state(State)
    case province(Province)
}

now i need some protocol to abstract over types that can encode a State, e.g. State itself, and Region.

protocol TypeThatCanEncodeState
{
    static 
    func state(State) -> Self
}

extension Region:TypeThatCanEncodeState {}
extension State:TypeThatCanEncodeState 
{
    static 
    func state(_ state:Self) -> Self 
    {
        state
    }
}

what’s a better name for the “TypeThatCanEncodeState” protocol? ExpressibleByState, LosslessStateConvertible, StateStorage, etc. just don’t feel right.

StateEncoder” makes more sense semantically, but i don’t want to give the impression that the protocol has anything to do with Encoder or Encodable.

Maybe ConstructibleFromState? Though would this be that much more useful than say, abstracting over the constructed type T and then taking a (State) -> T function wherever you’d want to accept this protocol?

The semantics of the protocol seem a bit underspecified to be particularly useful.

2 Likes

to oversimplify, what i currently have are APIs that take States as input, and generate aggregates of either States or Regions:

func renderAsStates(states:[State]) -> HTML.Element<State>
func renderAsRegions(states:[State]) -> HTML.Element<Region>

and i would like to unify them as

func render<T>(states:[State], as _:T.Type = T.self) -> HTML.Element<T>

the closure-based approach doesn’t benefit from type inference, and there are a lot of call sites that would all receive the same closure.

overall, you’ve probably got a good point though, ConstructibleFromState probably is not pulling its weight here…

Yeah, point taken. This does feel like a bag-of-syntax protocol, but sometimes those can let you do some nice boilerplate reduction. Though without clear semantics, naming is definitely more difficult. :slightly_smiling_face:

i’ve come to recognize that 95% of time spent writing HTML rendering code is time spent on boilerplate reduction. but the boilerplate reduction just requires more boilerplate elsewhere… :frowning:

How about StateAlike or RegionAlike? :thinking: