Sophisticated Ways To Write A Function

Sophisticated Ways To Write A Function. Sticking to basics is first step to achieve success. So if any one struggling and trying hard to make his project better then he should first correct basics. Function is the most basic part of a class, which obviously most basic part of any project. I came up with following conclusions on writing a sophisticated function.

Calculate Variables

Suppose you need to cast and use a String as Integer on 4 different occasions in a function. Writing Integer.parseInt(string) on each occasion will hurt your function badly. You should define and use a local variable and calculate the value at one place only weather you need casting or arithmetic operation or any other little change that you think is not worthy for an extra variable. Extra variable may seem useless if it is only used at one place but it’s worthy if being used on more than one occasion.

Define Base Functions

Fetching a RecordSet, iterating it to get desired object and proceeding to actual operation is not a big deal. However doing the same thing in another function would be act of stupidity. It is the most common mistake usually coders make. I am sure getting an object from a RecordSet would not be main job of your function so why do it if it’s not?!?! Define base functions first which do petty tasks of your main function so that same petty tasks could be re-used by other functions. It is very useful to identify problems in functions as well.

Have Utility Functions

Utility tasks should be written separately. There is no proper way to define utility tasks but for me a simple definition is “a function which takes independent inputs and could be used project wide”. Usually these functions are static and used for conversions, casting, logging etc.

Make It Generic Yet Specific

Always write a generic function first and then make specific functions to call generic functions. It could easily be explained by “department base employees” example. Suppose you need to get employees of a specific department, define a generic method getEmployees(String department) which should return employee of all departments if null provided as argument and finally create a new function getDept1Employees() which simply calls getEmployees(“department1”). The more generic function you make at initial stage of project the more project will be expandable.