I have a method like this:
void method(int number){some code}
and i will call it like this:
method(-1)
is there a way in java to only allow passing positive integers to number parameter other than checking in the method body or making a checked exception?
Declaring a checked exception doesn't make method parameters automatically validated somehow, it just means that the caller is obligated to check whether it was thrown, even if the code calls a literal method(1).
If your application is complex enough, you can use Bean Validation and put a constraint on the method parameter:
void method(#Min(1) int number) { }
This is only worthwhile if you're already using a system complex enough to provide support for it, such as Spring or CDI. Otherwise, just stick to checking in the method body and throwing IllegalArgumentException if the requirements fail. Guava's Preconditions utility can be helpful here.
(Additionally, your code will be much easier to read if you follow the universal Java code standards. Type names start with capitals, but member and parameters names start with lowercase.)
Related
I come from a C++ background and I am currently learning Java. One question arose when I have tried using some third party libraries. How do I determine if the call to a method taking an object reference as parameter modifies the object?
In C++ this is clear thanks to the use of the const keyword. If the method signature is:
void foo(Boo& boo);
I know that the referenced object might be modified, while if the method signature is:
void foo(const Boo& boo);
The compiler guarantees that the referenced object is not modified.
I haven't seen something analogous in Java, as only the reference itself can be declared final, not the referenced object, and a final argument doesn't make much sense in the first place since it is passed by value anyway. Therefore, when I see a method such as:
void foo(Boo boo) {...}
How do I determine if the object referenced by boo is modified inside the body of the function (maybe using annotations)? If there is no way to know, is there some widely used convention or some best practices to avoid confusion and bugs?
how do I determine if the object referenced by boo is modified inside the body of the function (maybe using annotations)?
The only way is to read the code unfortunately.
If there is no way to know, is there some widely used convention or some best practices to avoid confusion and bugs?
The common convention is to pass an object which cannot be modified, using a wrapper if needed. This ensure the class cannot modify the object.
List<String> readOnly = Collections.unmodifiableList(list);
If the object is Cloneable, you can also use clone() but another common approach is to use a copy.
List<String> readOnly = new ArrayList<>(list);
If you care about such behaviour, unit tests can show whether a method modifies an object or not. If you have unit tests already, it is usually one or two lines extra to check for this.
There's no such facility built in to the language, unfortunately. A good defensive practice is to define the data objects you pass around as immutable (i.e., without any public method that allows modifying their state). If you are really concerned about this, you could copy/clone an object before passing it to a method you don't trust, but this is usually a redundant precaution.
NOTE: this answer is a more detailed version of
You can also write purity or side-effect annotations in your code — mernst
There exists the Checker Framework among the various things it can check at compile-time via annotations is the IJG Immutablity checker. This checker allows you to annotate object references with #Immutable or #ReadOnly.
The problem is that you often would have to annotate the library yourself. To ease your task the Checker Framework can automatically infer part of the annotations; you will still have to do much yourself.
A side effect analysis is not built into the Java language.
You can perform side effect analysis via manual inspection, but several tools exist to automate the process.
You can use an inference tool (1, 2, 3) to detect whether your code side-effects a parameter.
You can also write purity or side-effect annotations in your code and then use a checking/verification tool (1, 2) to ensure that your code conforms to the annotations you have written.
All of the above-linked tools have limitations, but you might find them useful. If you know of other tools, mention them in comments.
How do I determine if the object referenced by boo is modified inside
the body of the function (maybe using annotations)?
I must agree with other answers that there is no direct way to determine that method will modify your object or not and yes to make sure that method can not modify your Object you all have to do it is from your side.
If there is no way to know, is there some widely used convention or
some best practices to avoid confusion and bugs?
Here the method name comes to the scene. Moving ahead with the naming convention of method we have to take a look at some method declarations which clearly convince you that your Object will not be changed at all.
For example, You know that Arrays.copyOf will not change your actual array, System.out.println(boo) will not change your boo
Method names are real weapons to provide as much information as possible to the method user.(Yes! it's always not possible but quite a good practice to follow.)
Let's consider it in your case that say printBoo will only print, copyBoo will only copy, clearBoo will reset all attributes, checkAndCreateNewBoo will check your boo Object and create new if required.
So, ultimately if we can use them in a proper way caller can be assured with the fact that Object will remain the same after calling the method.
As everyone says, prefer using immutable objects and also avoid void methods
The available purposes of methods like this
void foo(Boo boo) {...}
are to change the state of the object itself or change the object passed as a parameter
void completOrder(Order order) { ... }
//or
void parserTokenEnded(String str) { ... }
There is a way , that the method developer should mark parameter as final , if it is not going to modify the parameter.
public void test(final Object param)
However very few people follow this , so it is difficult to know. However good programmer follow this rule , especially writing the api. If you want to write method and expose it. Make param final to indicate that passed object is not going to be modified.
Is it possible to convert a method reference (e.g. SomeClass::someMethod) to a MethodHandle instance? I want the benefits of compile-time checking (ensuring that the class and method exists) as well as the ability to introspect the method using the MethodHandle API.
Use-case: I've got code that needs to execute if and only if the request was not triggered by a specific method (to avoid endless recursion). I want a compile-time check to ensure the class/method exists but a runtime check to compare the caller to the method.
So to recap: Is it possible to convert a method reference to a MethodHandle?
Well, if you can afford the additional overhead and security implications, you can use a Serializable functional interface and decode the serialized form of the method reference instance to find the target like demonstrated in this answer or brought up again with this question and its answers.
However, you should really rethink your software design. “Avoiding endless recursion” shouldn’t be fixed by decoding some kind of parameter object, especially not if your assumption is, that this actual argument value represents the caller of your method. How would you ever enforce this strange relationship?
Even a simple code change like referencing a method which delegates to the other method would break your check. Here is a simple example showing the subtle problems with your approach:
public class SimpleTest {
public static void main(String... arg) {
run(SimpleTest::process);
}
static void run(BiConsumer<Object,Object> c) {
c.accept("foo", "bar");
}
static void process(Object... arg) {
Thread.dumpStack();
}
}
When running this program it will print something like:
java.lang.Exception: Stack trace
at java.lang.Thread.dumpStack(Thread.java:1329)
at SimpleTest.process(SimpleTest.java:16)
at SimpleTest.lambda$MR$main$process$a9318f35$1(SimpleTest.java:10)
at SimpleTest$$Lambda$1/26852690.accept(Unknown Source)
at SimpleTest.run(SimpleTest.java:13)
at SimpleTest.main(SimpleTest.java:10)
showing that the method reference within the generated instance is not the expected SimpleTest::process but instead SimpleTest::lambda$MR$main$process$a9318f35$1 which will eventually invoke process. The reason is that some operations (here varargs processing) are not performed by the generated interface instance but a synthetic method instead, just like you had written run((a,b)-> SimpleTest.process(a,b)). The only difference is the name of the synthetic method.
You shouldn’t design software relying on such fragile introspection. If you want to avoid recursion, a simple ThreadLocal flag telling whether you are already inside your specific method would do the job. But it might be worth asking yourself why your API is provoking endless recursion in the first place; there seems to be something fundamentally wrong…
I am trying to create an API for an open source project I am working on, and I have hit a speed bump in trying to extend the API while keeping the semantics consistent with the current API. What I desire is to be able to define a method signature with a generic parameter that accepts the result of calling any method signature. By "any", that is meant to include void methods. I already know that you cannot directly define parameter types of void -- please do not repeat the obvious fact. What is not obvious is whether there is any trick by which a void method call can be provided as an argument to a method (i.e., and ignored).
Back story so this makes a little more sense why I would want to do such a thing, and what my design goal and constraints are, in case the above is impossible (as I fear it is):
My current API defines a very repeatable pattern of methods like this:
public <T,V> Function<T,V> functionFor(V ignoredRetVal) {...}
public <T> Predicate<T> predicateFor(V ignoredRetVal) {...}
public <T> Filter<T> filterFor(V ignoredRetVal) {...}
As the names imply, the parameters are ignored and are not even used in the implementation. In usage, ignoredRetVal is replaced with a method call to a dynamic proxy. Since parameters are evaluated before the method is invoked, this dynamic proxy method is invoked before the outer function (functionFor or predicateFor, etc.). The dynamic proxy invocation records the Method (or method chain) called, and converts this into a Function object (Guava) or other function-like object from multiple functional libraries.
What I am trying to do now is create a similar semantic that captures method invocations that are used for side-effects only without any need for a return type (such as Functional Java's Effect. If a non-void return type is provided, it is ignored. If a void return type is provided, it too is ignored and accepted. The key is that the semantics must somehow force the proxy method to be invoked before another method that extracts the intercepted proxied method calls. And since we are only interested in side effects, candidate methods are likely to include void methods. Ideally it would look something like:
public <T, V> Effect<T> effectFor(V ignoredRetVal) {...}
(which already works for non-void return types) and it could be used as follows:
Effect<MyClass> effect1 = effectFor (proxyOfMyClass.nonVoidMethod());// OK :-)
Effect<MyClass> effect2 = effectFor (proxyOfMyClass.orVoidMethod()); // Problem!!
As I have said, I'm afraid the semantic I am looking for is not directly supportable. If not, then any alternative should be close in spirit to the pattern I have established. Also, the whole goal of my API was to reduce "vertical noise" of inner class implementations, and I am not a fan of Double Brace Initializers. Whatever suggestions are offered, I am looking for a semantic that supports brevity, especially a single-statement semantic.
I don't think you'll ever be able to coerce a void into an expression, particularly if you don't like the double-brace hack.
You could follow Mockito's example in your API design. Normally, you set up an mock like this:
when(mockedInstance.someMethod()).thenThrow(new IllegalArgumentException());
But for a void, you do this:
doThrow(new IllegalArgumentException()).when(mockedInstance).someMethod();
Similarly, you can enumerate the methods of Effect<T> to make them static methods of your library.
E.g. if Effect<T> has doSomething() then you would invert it, like
doSomething().onEffectFor(proxyInstanceOfA).methodA();
But this assumes that the relevant methods of Effect<T> don't return a value themselves.
If that's not an option, and you need the Effect<T>, you could make it stateful, something like this:
VoidEffect<MyType> effect = effectForVoid(proxyOfMyClass);
effect.on().myVoidMethod();
Where VoidEffect<T> implements Effect<Void>, and on() returns the proxy passed in (or a different proxy). Then you would want to throw an IllegalStateException if on() wasn't called before you otherwise interact with effect.
I am writing a Java method with the following signature.
void Logger(Method method, Object[] args);
If a method (e.g. ABC() ) calls this method Logger, it should retrieve the Method object that encapsulates data about itself (ABC()) and pass it as an argument.
How can a method retrieve the Method object that is storing all the information about that method?
A simple way is that I use
Method[] methods = ExampleClass.Class.getMethods();
and search the whole array for the Method with the correct name. (Which is quite inefficient). Also, if two or more methods have the same names, then I will have to retrieve their parameter types too (to distinguish them) and have different code for each method. This would be inefficient as well as painful.
Is there a better way?
Thanks for the help.
Don't do it. Rather obtain the method name from the stack.
public void log(Object object) {
String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
// ...
}
This is however pretty expensive and that's why most self-respected logging frameworks offer an option to turn it on/off (which I would recommend to use instead of homegrowing one).
Even better, don't implement this method at all. Use logback, or some other modern logging framework.
If you are writing a wrapper over existing logger frameworks then the already provide a way to print the method name in the log message - if that's what you are trying to implement.
You can read from the log4j documentation, for example, that this extraction (as the other answer suggests) is done from the stack trace and is expensive : http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html
I have a method that takes an enum as a parameter and returns some information dependent on that parameter. However, that enum contains some values which should not be handled, and should raise an error condition. Currently the method throws an IllegalArgumentException but I would like this to be a checked exception to force callers to catch it (and return gracefully, logging an error). Is there something suitable or should I create my own Exception subclass?
I'm open to other patterns as well. A reasonable reaction would be that all values of the enum should be handled, but that isn't the case. When a new value is added to the enum, I want to make sure that this method does the right thing - alerting a human is preferable to using some default return value in this case.
Thanks for any advice.
You can certainly create a checked exception of your own (such as UnhandledEnumType), or you could catch and handle the IllegalArgumentException. It sounds a little fishy that only some values of the enum should be handled. One of the purposes of an enum is to bind values to a certain set of values, and I would expect all to be handled. If you're worried about new ones being added, you should have a test that tests that all values are properly handled (by using the values() method of the enum to ensure they are all tested).
The questions are:
how "normal" are cases when the method is called with an unsuitable enum parameter?
can you handle these cases gracefully and then continue processing?
From what you describe, it is not "normal" (happens only when a new enum value is added and the method is not updated properly - i.e. when a bug was introduced). So to me this sounds more like a case for RuntimeException (i.e. unchecked). Callers of this method can still catch an unchecked exception if they really want to, but they are not forced to.
OTOH I would try to eliminate the case you describe, by moving the data your method is returning right inside the enum. This way whenever a new enum value is added, there is no way the relevant data could be forgotten.
If you are interested, you may want to check out this tutorial.
How about InstantiationException?
Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated. The instantiation can fail for a variety of reasons including but not limited to:
the class object represents an abstract class, an interface, an array class, a primitive type, or void
the class has no nullary constructor