In c++, I'd usually pass a byRef variable as a parameter to the function to get the information that I need returned, and I'd return a boolean or int value from the function to determine if the function was executed successfully (no errors occurred at any point).
I can't do that in Java since you can only pass byVal, and can get one thing returned.
I guess you can return some array or list, but I feel like that's bad coding practice.
What are some proper ways to deal with this problem?
If you want to do it exactly like in c++, you can pass a primitive by reference via its wrapper-class (e.g. class Integer for primitive int). But I agree with the comments below the question that the 'proper way' of doing this in Java is to throw an exception in case of failure. In case you do not like both ideas, you can still use static variables in the class that implements the method you are executing, let them be set by that method and read by the invoking method/class, but this is no good coding practice either and should not be done unless there is no other option for whatever reasons.
Related
I am looking for a way where I can structure java enums in an efficient / elegant way. These enums hold return results.
there are functions like "delete item" (enums: OK, DOESNT_EXIST, ACCESS_DENIED..) or create item (OK, ALREADY_EXISTS, ACCESS_DENIED..), changeItem (OK, INVALID_PARAMETER, INVALID_CLASS, ACCESS_DENIED)
As you see they have both own and shared enums. therefore some enums should be implemented in every return function (OK, ACCESS_DENIED), while others are exclusive (DOESNT_EXIST, ALREADY_EXISTS...).
also, there are complex functions like changeOrCreate where an item may be created if it does not exist and changed elsewise (enums: all createItem enums, all changeItem enums).
Basically I can
build different enums for every function (createItemResult, changeItemResult..) or
put them all into one RESULT enum class.
But whatever I choose I can never accomplish all of these
When a complex function like "changeOrCreate" fails, I want to know whether the returned enum "ACCESS_DENIED" was caused by the creation or the change.
I would highly prefer the caller of any function getting the same enumType
(I would prefer the functions no to be able to return illegal enums. e.g.: createUser shouldnt have DOESNT_EXIST)
Any ideas? Or is there any convention for return type enums?
Update:
The reason I cannot use (Non-Standard-)Exceptions is that I have to provide an API and it was a requirement that no Exceptions can be thrown.
When a complex function like "changeOrCreate" fails, I want to know whether the returned enum "ACCESS_DENIED" was caused by the creation or the change.
Then name them CREATE_DENIED and CHANGE_DENIED, or something like that.
I would highly prefer the caller of any function getting the same enumType
So do the one RESULT enum class you suggested.
I would prefer the functions no to be able to return illegal enums.
Since you're writing the functions, you control which of the enums it returns, i.e. you make sure createUser never returns DOESNT_EXIST.
It seems you're using HTTP status codes in Java, and while this can work well for your program, is not an elegant way to write Java programs.
Java has exceptions for two reasons (that I know of):
Something unexpected happened, and the program doesn't know how to handle it. What you do: Throw it to the next layer~!
Something expected happened, so you catch it, and resolve it.
Since you are expecting an exception, what this means for you is:
Create some classes for your enum-cases, like UserNotAuthorizedException, (or just use the built-in AuthenticationException), and throw those to your program.
If you want to know who didn't get access you can either select it with an argument to your exception (an ID for each use-case, the instance that failed (which can include a static type), or even a string. It's up to you), you can create a subclass...
At the end of the day, Java likes classes.
I'm new to the java language. I'm a php developer. There exist a lot of Variable handling Functions in the php language.
But I find it hard to imagine there aren't any built in functions that check whether value is numeric, is null, etc...
Can anyone explain why this is? Why does java not provide simple functions such as these?
PHP lets you store almost any value in any variable, and converts between types as necessary. Java does not automatically convert between most types - if you want a conversion, you have to do it yourself.
All of the is_something functions would be pointless - you know the type of a variable since you declared it!
If you have a reference to an object, you can determine the type of the object (not the variable) that it refers to using instanceof or reflection:
Object x = "hello";
// the variable x is of type Object, but it refers to a String. How can we tell?
System.out.println(x instanceof Integer); // prints "false"
System.out.println(x instanceof String); // prints "true"
System.out.println(x.getClass().getName()); // prints "java.lang.String"
However, most of the time, this simply isn't something you need to do.
So, all of the is_something functions are unnecessary, and all of the somethingval functions wouldn't fit well in the language (although there's no technical reason they couldn't exist). What else is there?
get_defined_vars - again, redundant. You know what variables are defined because you defined them!
empty (returns true if a variable doesn't exist or contains false). Using a variable that doesn't exist is a compile-time error, so you can just use thing == false (or !thing if it's a boolean) instead of empty(thing).
get_resource_type - the closest match in Java is thing.getClass().getName() instead of get_resource_type(thing).
gettype - useless for the same reason the is_something functions are useless.
import_request_variables - The language Java has no built-in concept of GET variables, POST variables or cookies. Even if it did, this wouldn't work very well, because you'd have to declare all the variables anyway.
is_null - use thing == null instead of is_null(thing).
isset - again, you can't use variables that don't exist. So just use thing != null instead of isset(thing).
serialize and unserialize - Java has a serialization system, which is more complex but more flexible. Look up ObjectOutputStream and ObjectInputStream.
settype - makes no sense, as the type of a variable cannot be changed.
strval - use String.valueOf.
unset - makes no sense. Variables exist until the end of their scope.
print_r and var_dump and var_export - the only ones that might actually be useful and don't already exist. Sadly, it just doesn't exist, though you can get something similar if you override toString in all of your classes.
But i imagine any in build function is not check a value is numeric, is null, etc...
Why java is not provide simple functions such like this?
First reason: Java supports method overloading.
In Java, you typically don't write a single method that handle all sorts of arguments with all sorts of different types. Instead, you can write multiple overloads of the same method: same method name with different declared argument types, and/or different numbers of declared arguments.
The compiler sorts out at compile time which overloaded method to call based on the static types of the argument expressions.
In this model, there is no need to a bunch of functions for sorting out whether values are numeric, null, etcetera.
Second reason: Java does not allow primitive types and object types to be used interchangeably.
For example you cannot declare an argument type that would accept both an int value and a String value. And an int argument type can never accept a null.
(Actually, the primitive wrapper classes like Integer and Java 5's addition of autoboxing / unboxing tend to blur the distinction. But the underlying hard distinction between primitive and reference types remains. Autoboxing is syntactic sugar.)
Third reason: There is instanceof and testing for == null.
As #Malik points out, in the cases where the tests do make sense in Java, they can be implemented with built-in constructs, without resorting to library "functions". The functions are unnecessary.
(AFAIK, no mainstream 3rd-party utility library has implemented the equivalent of the PHP functions you are talking about ... which supports the view that they are unnecessary. If enough people thought the functions were necessary, there would be a library and we would know about it.)
It is also worth noting that most of the "variable handling functions" are to do with dynamically declared variables in PHP. Java doesn't support that. If you want to implement a dynamic binding between names (strings) and values in Java, use a Map class.
PHP as you are aware doesn't tend to care what you store in a variable, you declare a name, give it a value and it will try and interpret it itself. In Java, you explicitly declare the type of variable you would like.
Something like an integer (whole number) can be presented by the primitive data type int, so you could use
int myNumber = 7;
And the code would know for sure that this is an integer, as you have explicitly stated that this is the case. Refer to this page for other java primitives.
If you are using a String (which is an object) in Java, you can use the function isEmpty() to determine if there are any characters in it. You can do a check on objects in Java to see if they have been instantiated by using object == null.
Some compilers will actually give you warnings if you have not initialised variables before you check them, whether these are objects or primitives.
To get a good feel of how data types work in Java, refer to the Oracle documentation I linked, it is very useful, and ill contain a lot of information of other aspects of Java you may have questions with.
First of all why check variable type when you explicitly define a variable with a type. Secondly, you can check the type in Java although you should already know the type.
Integer x = 3;
if (x instanceof Integer) {
System.out.println("Integer");
}
String s = "test";
if (s instanceof String) {
System.out.println("String");
}
So Java 8 introduces method references and the docs describe the four types.
My question is what's the difference between the two instance types?
Reference to an instance method of a particular object.
Reference to an instance method of an arbitrary object of a particular type.
Both refer to references but what's significantly different? Is it that the type inference used to resolve them is different? Is it significant that (in their examples) one is a closure and the other is a lambda? Is it something to do with the number of arguments on a method?
myString::charAt would take an int and return a char, and might be used for any lambda that works that way. It translates, essentially, to index -> myString.charAt(index).
String::length would take a String and return an int. It translates, essentially, to string -> string.length().
String::charAt would translate to (string, index) -> string.charAt(index).
With this they mean that you have the following:
1) Can be for example this::someFunction;, this will return the someFunction reference of the current object.
2) Can be for example String::toUpperCase, this will return the toUpperCase method of String in general.
I am not sure if there is an actual difference in behaviour, I think it is just like you can also call static methods on instance variables.
I wrote up the conclusion I came to here, the following is a summary.
Oracle describe the four kinds of method reference as follows.
What they should have written is:
I found their description of the first two confusing ("reference to a static method" and "reference to an instance method of a particular objects"), I think its really the difference between a class static and an object.
I prefer to think of the first as an instance method of a specific object known ahead of time and the second as an instance method of an arbitrary object that will be supplied later. Interestingly, this means the first is a closure and the second is a lambda. One is bound and the other unbound.
The distinction between a method reference that closes over something (a closure) and one that doesn’t (a lambda) may be a bit academic but at least it’s a more formal definition than Oracle’s unhelpful description. If you’re interested in the difference between a closure and a lambda, check out this post.
Summary
The difference between the two types of instance method reference is interesting but basically academic. Sometimes, you’ll need to pass something in, other times, the usage of the lambda will supply it for you. My gripe is with Oracle’s documentation. They make a big deal out of the distinction but fail to describe it in an easily understandable way. It’s the canonical reference material but it’s just plain confusing.
There's one or two more subtleties to it that I wrote up.
I used to write a very strong type language, for example, java. I need to tell the complier what type of variable I will put in... for example...
public static void sayHello(String aName)
I can ensure that the user will pass a string to me...
But if I use php, I can do that...
function sayHello($aName)
I still can call the sayHello, but I don't know what the param type......I can let the name more informative like this:
function sayHelloWithString($aName)
But I can't stop the user pass in a int to me..... the user can still pass the int to me... ...it may cause lot of errors....How can I stop it? any ideas or experience shared? Thank you.
How about not stopping the user from passing in an int?
In php, you could check is_string, but of course, you'll miss out on objects that have __toString set, or the implicit conversion of numbers to strings.
If you must make your program cry in pain when a developer tries something different, you could specify a type in the later versions of PHP (i.e. function foo(ObjectType $bar)...)*
In most loosely typed languages, you want to set up fall-backs for the major types:
number
array
string
generic object
Be liberal in what you accept, be strict in what you send.
* Primitive types are not supported for type hinting
There's a few ways to deal with this...
Use an IDE that supports docblocks. This deals with the pre-runtime type checking when writing code.
Use type checking within your function This only helps with the runtime type checking, and you won't know when writing your code.
Depending on the type you can use built-in type hinting. This however only works for non-scalar values, specifically array and a class name.
1 - To implement #1 using a good IDE, you can docblock your function as such:
/**
* Say hello to someone.
*
* #param string $aName
**/
public function sayHello($aName) {
2 - To implement #2 use the is_ methods..
public function sayHello($aName) {
if (!is_string($aName)) {
throw new ArgumentException("Type not correct.");
}
// Normal execution
3 - You can't do this with your method above, but something like this.. Kindof the same as #2 apart from will throw a catchable fatal error rather than ArgumentException.
public function manipulateArray(array $anArray) {
It's worth noting that most of this is pretty irrelevant unless you're writing publicly usable library code.. You should know what your methods accept, and if you're trying to write good quality code in the first place, you should be checking this before hand.
Using a good IDE (I recommend phpStorm a thousand times over) you can and should utilise DocBlocks everywhere you can for all of your classes. Not only will it help when writing APIs and normal code, but you can use it to document your code, what if you need to look at the code 6 months later, chances are you're not going to remember it 100% :-)
Additionally, there's a lot more you can do with docblocks than just define parameter types, look it up.
You can check if what they passed is a string using:
http://php.net/manual/en/function.is-string.php
Then provide appropriate error handling.
function sayHello($aName) {
if (is_string($aName)) {
//string OK!
} else {
echo "sayHello() only takes strings!";
}
}
In PHP you can check whether the variable that has been passes is a string by using the is_string function:
<?php
if (is_string($aName)) {
echo "Yes";
} else {
echo "No";
}
?>
Hope that helps.
Or alternatively /additionally use Type Casting to convert the variable to the required type
http://us3.php.net/manual/en/language.types.type-juggling.php
You have the option of checking to make sure the parameter is of the right type. However, it's worth considering what you'd do if it isn't. If you're just going to throw an exception, you might be better off just assuming it's the right type and the the exception be thrown when something you do isn't allowed. If you're not going to add any more useful information to the exception/error that would already be thrown, then there's not much point in checking it in the first place.
As to giving the user an indication of what type you want, I generally stick with including it in the variable name:
function sayHello($aNameStr)
function addItems($itemList)
...etc...
That, plus reasonable documentation, will mean the user can look at the function and figure out what they should be passing in in the first place.
Some scripting languages have tools that can help you. For example use strict in perl requires declaration of each variable before using. But still the language is weakly typed by definition.
Sometimes naming conventions help. For example we inherited from good old Fortran tradition that int variables' names should start from i, j, k, l, m, n. And this convention is used now at least for indexes.
A co-worker asked me to change a signature from using a primitive "boolean" to using a classed "Boolean". He didn't offer a very good explanation why?
Have any of you heard of this and can any of you explain why it matters or doesn't matter?
Edit: He mentioned that it was good practice for public methods.
The use of the field is just a flag that tells me whether to call one flow or another depending on whether it's true or false.
Is it database-related? If you have a boolean value in a database, it can hold one of THREE values -- true, false, and null. The Boolean object would let you mimic that behavior.
Basically, it's a matter of whether you want to deal with "null" as a potential input value.
Actually I tend to err on the side of passing small-b boolean instead, because I know that a primitive boolean is never going to be null. I'm sure there are valid reasons for using the Boolean type, but I'd want to think about its use in each case.
Actually, in general, it's good practice to use regular primitives unless there's a specific reason not to. It will be slightly faster/less wasteful, though you'd need to be moving a lot of objects around for that to really matter.
In response to your edit, I've never heard of it being good practice for public methods. In the often-cited Effective Java by Josh Bloch, there's an entire item "Prefer primitive types to boxed primitives" (item 49, if you can get your hands on a copy). It sounds like your specific case has no reason to favor of using a big-b Boolean, and using objects creates pitfalls like poor interaction with old code that, for example, uses == rather than equals() (which isn't even possible for a primitive).
The main advantage of Boolean over primitive booleans is that they allow you to have a null value. This is particularly effective for return values but can sometimes be used for an "optional" argument in Java.
Make sure your JavaDocs (and code) can deal with the null
Never heard of any valid reason to prefer Boolean over boolean.
Given a chance, always stick with primitives. Boolean variables can be null; and thus can introduce an unexpected behavior in your method. Your co-worker may have some specific reasons based on program implementation/logic.
I typically try to make use of the primitive boolean wherever possible.
The only possibility that I can think for a developer to want the Boolean class is boxing/unboxing (but I would think you'd want to prevent boxing/unboxing whenever possible rather than encourage it everywhere) and the possibility for null values.
If you control both sides of the interface (i.e. the calling code and the called method) then you should simply be consistent. You actually incur a bit of overhead if you force the compiler to autobox the variable for you.
If the method in question is one of a set of methods with similar signatures, and all others pass an object of some kind in the position where your boolean goes, then using an object rather than a primitive might simply be a matter of being a bit more consistent.
EDIT: Re-reading the question, if that boolean parameter is really just there to control an if (which is exactly what the primitive is there for), then using the object form is simply a waste of CPU time and memory. I can't think of a sensible reason why it should be an object rather than a primitive.
Keep it simple. Using Boolean:
adds an extra layer of complexity
takes a true/false state boolean and converts it to a true/false/null state variable
offers no advantages if used as a logic flag (assuming there is no database interaction as mentioned by BlairHippo)
potentially requires additional lines of code to box/unbox booleans in Java 1.4
Are you using any kind of data-binding framework in your app? I recently had to deal with a case where a boolean in a model object needed to be bound to a form. The field in the form was required, but we didn't want to default the value to true or false (because it was important for the user to choose the correct value for the specific case, if there was a default, you'd easily get a lot of incorrect values.) However, before the object could be validated, values from the form had to be bound to it. Of course, if the user hadn't selected a value, it would attempt to bind null to the field, and an exception would be thrown during the bind. So we changed it to a Boolean so that null could be bound to the field temporarily, and then validation could report that the field was required.
If you use Boolean, then you can either pass a boolean or a Boolean to the method
public void setX(boolean b) //only takes boolean
public void setX(Boolean b) //takes Boolean or boolean
This is due to the autoboxing of the booleans into the function.
EDIT: The autoboxing only works in 1.5+