Suppose I have a private method inside my main class that performs a repeatedly used process:
The design problem is that the FontStyle that I will always pass to this method will be the same FontStyle object, but I don't want to create it inside the method because it will be re-created unnecessarily every time the method is called. It just seems like bad design to always pass the same object to a method. Is there a better way?
More typical would be to make doSomething() a method of ExpensiveObject. Is there a reason you can't do that?
Joined: Aug 20, 2008
3rd party library. Apache POI, actually. I changed the code around because it helps me work through the problem and usually find a solution, but not this time unfortunately. Here is the actual code I'm using:
I always use the same CellStyle object "gothic10error" to pass to it, but it seems like it would be a unnecessary performance hit to do all that CellStyle creation code every time I call the method.
Not to mention that the Workbook has a limited number of fonts it can hold. You might consider some sort of factory method which:
1) First tries workbook#findFont(...) to see if the font you want already exists.
2) If the font does not exist, create a new one
3) Use the font to create the style.
Now, you can lookup a previously defined style using the style's index, but other than iterating through the list of styles I don't see a way of finding one. I also don't know if there is a limited number of styles.
Another option would be to pre-populate the workbook with the fonts and styles you want, and keep track of the indices for the Styles you want to use. Then you could use Workbook#getCellStyleAt(index) to re-use the predefined styles.
What is copy? Is it the workbook? If you want to always have one font associated with a workbook, you can always wrap the workbook in your own class that implements workbook. Inthe constructor create the font. All other methods delegate to the real workbook