Added Simple Arithmetic Methods to the BKTable
Thursday, October 30th, 2008Today a developer using BKit chatted me asking if it would be possible to add some simple arithmetic operations to the BKTable. Basically, adding, subtracting, multiplying and dividing the values in the table by simple external values without having to pull out the Object, get it's double value, do the math, create a new Double, and place it back in the table.
It seemed like a very reasonable suggestion. After all, because of the JEP parser, we had the ability to add complete tables, it only makes sense that we do the same for the contents of the individual cells in the table. Problem was, I didn't want to reproduce the code for the arithmetic operations themselves as I'd already written that once. I wanted to leverage that without making the code overly complex and include a JEP parser for each operation.
Thankfully, that wasn't necessary. The way JEP is structured, the operations are classes. I have sub-classed their Add, Subtract, Multiply, and Divide classes to make BKAdd, BKSubtract, BKMultiply, and BKDivide already to make the complex operations in the JEP parser work. Again, luck was on my side in that each of these had simple methods to really do the heavy lifing.
BKAdd used add(), BKSubtract used sub(), and so on. This meant that as long as the BKTable had an instance of BKAdd, it could add. So I make transient ivar of a BKAdd, BKSubtract, and so on to the class so they wouldn't be shipped around the universe, and then sent to work making the methods.
It was somewhat tedious work because I wanted to have forms that would take either integer or String indexing into the table - that's standard for the BKTable, and also have a version that took the generic Object, but also one that took a double for those times when it's just a bunch of numbers, and you don't need the added complexity.
Because it's possible to have nulls in the table before the operations happen, I took the logical stance that a null was the same as a zero for these operations. So, adding a number to a null gives you that something. Multiplying something by a null gives you the null - simple, but important, I think, if you're doing this to minimize the hassles of dealing with Objects when you want primitive values.
Took a while, but it was really nice to see it work. The ability to modify the individual cells in a BKTable now is really nice. It is going to make some of the work done with BKTables a lot cleaner.