Hi

I needed some sort of polymorphism, but did not want to use inheritance and 
methods because it needs heap allocation and I have quite small objects which 
are created and destroyed frequently.

Finally I came out with setup which I was comfortable with, and here is example:

message.nim 
    
    
    type MessageType = enum msgHit, msgDeath, msgDayNight
    
    type Message* = object
        case messageType*: MessageType
        of msgHit:
            target*: string
            hp*: int
        of msgDeath:
            died*: string
        of msgDayNight:
            isDay*: bool
    
    # normally queue
    var messages*: Message
    
    proc hit*(target: string, hp: int): Message = Message(messageType: msgHit, 
target: target, hp: hp)
    
    proc death*(died: string): Message = Message(messageType: msgDeath, died: 
died)
    
    proc dayNight*(isDay: bool): Message = Message(messageType: msgDayNight, 
isDay: isDay)
    
    
    proc getTextHit(m: Message): string = "You hit " & m.target & " for " & 
$m.hp & " HP."
    
    proc getTextDeath(m: Message): string = m.died & " just died."
    
    proc getTextDayNight(m: Message): string =
        if m.isDay:
            result = "The day has just begun."
        else:
            result = "Beware! Night is coming."
    
    proc getText*(m: Message): string =
        case m.messageType:
        of msgHit:
            result = getTextHit(m)
        of msgDeath:
            result = getTextDeath(m)
        of msgDayNight:
            result = getTextDayNight(m)
        else:
            result = "UNKNOWN MESSAGE"
    

main.nim 
    
    
    from message import dayNight, messages, getText
    
    # game time system
    
    proc informAboutDay() =
        messages = dayNight(isDay = true)
    
    
    # player informer
    
    proc update() =
        echo( getText(messages) )
    
    when isMainModule:
        informAboutDay()
        update()
    

[snippet](https://glot.io/snippets/en6lyc2oyi)

It is simple, it is clear but it is very verbose. What would you suggest to 
preserve merits while allowing addition of new MessageTypes easier. Currently 
it consist in:

  1. Add message type in MessageType
  2. Add "of" condition in Message
  3. Add "of" in getText
  4. Provide constructor
  5. Provide handler



Also I would not like to solve this problem introducing another overly 
complicated layer (like not simple templates for instance).

All suggestions appreciated.

Regards  
Michal  
"Very bad coder." \- You have been warned!  

Reply via email to