I hope this is a very simple question, what is the Android equivalent to doing this in PHP:
PHP:
function BlahBlah ($first_var,$second_var,$optional_var_1=null,$optional_var_2=null) {
}
In Android it appears everything I feed into a function must have a non-null value for all variables. While I can add logic such as if statements to check for null values, why can’t I simply pass through null values and have them be ignored?
My problem revolves around a function which enters a book into my sql database for my app. If I enter all of the book’s information such as author, title, copyright, ISBN, etc. there is no problem as I am not supplying any null values. If however, I were to leave the copyright or ISBN as Null and try to pass these through to the function I get a nullpointerexception. Sometimes I don’t need to record the ISBN or the copyright (this is an example and not the real app) so instead of making multiple functions such as addBook(…) addBookWithNoISBN(…) addBookWithNoCopyright(…) … what is the better way to do this?
I believe I should be sending all of my variables to the function as a string array and perhaps do some processing in the function itself? Is there a better way?
I hope people get what I’m trying to say, thanks a lot!
Java supports something called method overloading, which lets you define multiple methods having the same exact name, but with different numbers/types of parameters: http://download.oracle.com/javase/tutorial/java/javaOO/methods.html
So you would end up coding a separate method for each possible combination. They would then pass in null values where needed, and call the main method that does the core logic:
With this, it doesn’t matter if you pass in 2, 3, or 4 variables as the same function is ultimately called with ‘null’ values for things you didn’t pass.
Here’s another example, where you have a single method name that can accept all sorts of input types:
Hope that helps!