samedi 18 juin 2016

Is it better to add all the properties you might need in a map beforehand?

I am writing a small piece of code in Groovy where I have a bunch of methods which I call actions, each doing something specific. Most of them can be combined in a sequence to achieve an overall purpose, e.g. book a facility for a game of football. Some specific scenarios have their own actions suited for them but in general a lot of them are reusable (e.g. find available slots, prepare book form, prepare payment, send payment, create response to client....)

So I made a class that has just one method that loops over a list of actions and returns a response.

What I am having trouble deciding is the following: Each action takes a map I call context as an argument and the idea is that the action takes what it needs from it and then puts something new (or enhance something already there) and pass it to the next action until the context returns with a response property that has details of the transaction.

class Procedure {
        List chain
        boolean execute(Map context) {
                for (action in chain) {
                    boolean keepGoing = action.execute(context)
                    if (!keepGoing) {
                        return false
                    }
                }

                true
            }
}

So, the map I pass, should it have all the possible properties depending on the purpose. I am calling this from a higher level so I could prepare the map there to at least have the properties with null values and just update them as I go through the actions. That way, inside the actions I can just assume that the stuff I need will be on the context and if not an excpetion will be thrown (pro a NPE). Or should I just put just what I have just before when the purpose is called and then inside the actions start them by first checking if what I need is on the map. That way there would be a lot of checking and some of it might be duplicated or triplicated. Let's say for instance I have a customer id and use it to get his account, then to find payments and then to add in the booking. In all three commands I would have to check that there is a property that has this. It seems superfluous.

It's been bothering me because I am using Groovy and I have to use maps. In my mind if I was writing in Java, I would probably have an interface for the basic context and then for each purpose I would have another interface that would have the accessors for the fields and would pass the interface that i need in the actions... or something like that.

However, the idea is to use Groovy and Maps.

Aucun commentaire:

Enregistrer un commentaire