Best practices when writing glue code

1.4k Views Asked by At

I asked this question to get some opinions on the subject of glue code.

For example, imagine you have a class (pseudocode):

class MyClass
    int attribute a
    string attribute b

And to represent that data model, you have BOTH a slider and a text box to represent a, and a text box and say... the window label to represent b.

Obviously, when one of these view objects is changed, you want to update the others. However, updating the entire view is obviously inefficient.

method onSomethingHappened(uiObject)
    model.appropriateAttribute = uiObject.value

The question is, what is your opinion on what to do next? Should the model object implement a callback that notifies a listener when the value has been changed, allowing one to write glue code like:

method modelChangedCallback(model, attribute)
    uiObject1.value = model.a
    uiObject2.value = model.a

Where you might examine what the attribute that changed is, and respond accordingly? This is the model in Objective-C and Cocoa on Mac, for the most part.

OR, would you rather have the responsibility lie completely in the glue code?

method onSomethingHappened(uiObject)
    model.appropriateAttribute = uiObject.value
    self.updateForAttribute("appropriateAttribute")

Both of these approaches can get pretty hairy (as is the problem with glue code) when your project gets large. Maybe there are other approaches. What do you think?

Thanks for any input!

1

There are 1 best solutions below

0
On BEST ANSWER

For me I think it comes down to where the behavior is needed. In the situation you describe, the fact that you are binding multiple controls to a property is what is driving the requirement, so it doesn't make sense to add code to the model to support that.

In a web-based model I would probably put the logic in the web page since that can be done rather cheaply using Javascript. If I don't have that luxury (i.e. I'm dealing with a "dumb" view), then it would probably make sense to do it in the controller, or model glue code. If this sort of thing becomes common enough, I may go as far as creating some form of generic helper to reduce the amount of boiler-plate code I have to deal with.