Thursday, September 01, 2005

Only do it once...

When it comes to programming, one of my most recent mantras is to "only do it once".

Whenever I solve a problem, whatever that problem might be, I must only solve the problem once and then re-use that solution in future. By doing this you programs become many mini programs.

I can remember one of the first things I learnt, even when I still at school, about computer programs is that it's input, process, output. By employing this approach you are configuring alreaday written components, supplying them with input data and then firing them off.

A naive example would be, you have a square root to solve, you write a square route method, make it statically available (it is a stateless algorithm) and you never have to solve the square route problem again.

It has input - the input parameter you want to find the square root, it has processing, calculate the square root and it has result, the calculated square root.

Now on my current project, we receive data from a back end stored in a Map. We have to move that data into a data object. The populate mechanism for doing this would be to write something like...

Now, as you can see, for every different data object I receive from the back end, I have to do something similar to this.

However, that means I have to solve the same problem many times. If I apply the "only do it once, input process output" paradigm then I write a re-usable utility that will do the work for me. I supply it input parameters and configuration parameters, and it does the work of copying the data from the map to the data object.

In this case the input parameter is the map. The configuration parameter (this is a kind of input parameter) is the mapping between the key names in the map and the property names in the data object. The other input parameter would be the data object.

funkyMechanism(map, <ObjecToMapMapper> , dataObject)
So map to data object would contain...
START_DATE = startDate
AMOUNT = amount
In order to solve this problem in this way, reflection was used. There are ways to solve it using a similar input processing output paradigm, they're just not as elegant.

When programming try your best to only ever solve a problem once, and then re-use that solution. Think of instances where you can encapsulate a solution into input - processing - output. You'll find you code a lot less, your programs will be more robust and will have more of a Wow factor!

1 comment:

Anonymous said...

i agree, i personally think that "laziness" makes for good creative programming :D - Wendy

How important is the programming language?

  Python, typescript, java, kotlin, C#, .net… Which is your technology of choice? Which one are you currently working in and which do you wa...