Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 days ago.
Improve this question
The pattern-matching switch available as a preview feature in Java 18+, is a great feature. It does seem to have a limit that you cannot specify multiple cases while using it. This is understandable, but raises a question about intended use. The following is actual code from my current project:
#SuppressWarnings("DuplicateBranchesInSwitch")
static boolean numeric(Type type) {
return switch (type) {
case IntType ignored -> true;
case IntegerType ignored -> true;
case RationalType ignored -> true;
case RealType ignored -> true;
default -> false;
};
}
There is not actually an issue with duplicate code here; it's just a matter of true being written four times, which is fine. However, Intellij IDEA thinks duplicate branches are bad on principle (and in other forms of switch, indeed they are, which is why I leave that warning enabled; a couple of times, it has caught incipient bugs), so I ended up using the annotation to suppress the warning for this method.
Is that the best practice here, use the annotation to suppress the warning in specific cases for now, until a later version of IDEA will likely disable it for pattern-matching switch? Or is there an idiom in the use of this language feature that I am missing?
it seems to be a bug. IntelliJ IDEA 2023.1, which is currently in early access, will have a fix.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
I want to migrate old Java code to Java 17. Is it a good idea to replace:
Collections.unmodifiableList(Arrays.asList(....)); to List.of("....");
Should I expect code execution error or there should be no impact?
specific answer
Obviously, the best way to figure this out is to try it yourself.
If you want some certainty before you attack this challenge, it is usually a good idea to look at the method signatures in the java API documentation for the different versions.
Java 7 spec of Collections.unmodifiableList: https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#unmodifiableList(java.util.List)
Java 17 spec of List.of: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/List.html#of()
As you can see, both return an unmodifiable List<E>. So I would say your update is quite safe.
general approach
In general, if you are going to refactor a common part of your codebase, it is a good practice to first extract all occurrences of this construct in your codebase onto a utility method.
For your case, you could create a simple utility class, like so:
public final class ListUtilWrapper {
public static <E> List<E> listOf(E... elements) {
return Collections.unmodifiableList(Arrays.asList(elements));
}
}
After each call is replaced by ListUtilWrapper.listOf(....), you compile and test your code.
Next up, you replace the implementation of ListUtilWrapper.listOf to be List.of(elements) and rebuild your codebase.
If all works well: inline the utility method after some manual testing. If it fails, you can easily roll back to a stable state.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
My tutor has given me this task to write a Boolean method that checks whether a class has been annotated at all. Don't want to bother you guys with further details, but it was actually a package, so at first I used the Google reflections library to collect all classes from my project. Unfortunately, this library, along with others doesn't answer my question, they all require me to provide annotation class, which I yet to find out with my method I am struggling with.
Edit: this is a Spring project
a Boolean method
I doubt that. I think they want you to write a boolean method. Boolean is the wrapper type. It's a tri-state thing you don't want (it can be null, true, or false. Yich).
so at first I used the Google reflections library to collect all classes from my project.
That seems completely unrelated to the question.
All you need is:
Class<?> toCheck = ...;
return toCheck.getAnnotations().length > 0;
Note that annotations need to mention whether they are visible at runtime or not. If they aren't, that won't work, but the point is, nothing will (the 'point' of an annotation that doesn't have a retention level of source is that you can't tell at runtime whether it is there, after all).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Android Studio is, apart from other things, a fairly fancy Java IDE, and it has a bunch of built-in language specific edit features that can perform various code transformations. One of these that surprised me is "Expand Boolean", and its partner "Expand Boolean to multiple ifs". The documentation says that the first will transform this:
public class X {
boolean f(boolean a) {
return a;
}
}
into this:
public class X {
boolean f(boolean a) {
if(a) {
return true;
}
else {
return false;
}
}
}
My question is why you might want to? Is there a performance advantage to be had in Java? The original version seems to be superior in terms of clarity and conciseness.
Intentions are not necessarily quick fixes, sometimes they are just warnings or available macros for micro-refactoring.
The one in question doesn't assume any error with your code since this one also appears with
boolean f(boolean a, boolean b) {
return b&&a;
}
What is trying to provide is a way to move from boolean expression to conditional alternative. Sometimes your condition becomes complex and doesn't fit into a single expression any more and you end up writing an if. So, instead of writing it by hand, it offers you to do so automatically.
Note that, once you apply the intention, other intentions like clean code and simplify appear, and applying them will undo the expansion. And this time they appear as quick fixes, since now it's actually seeing a problem with your code.
In other words, this is just a macro useful as a first step for further changes and probably wasn't created to use it alone.
It doesn't actually suggest you to do the change, but just letting you know that it can be handled automatically if you intend to do it.
On a side note, the user documentation reference this kind of intentions as suggestions, but I find that name misleading for the reasons I stated above.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Im trying to use a assert stmt to check if a value is greater than 1 but its not working as expected.
public class asserttest {
static void methoda(int i){
assert (i > 1);
System.out.println("This is methoda");
}
public static void main(String[] args){
methoda(-1);
}
}
Output:
This is methoda
Expected output:-
assertionerror
I was able to fix it by enabling the assertions.
My guess is that you're getting confused by assertions not being enabled by default. Use the -enableassertions command line option:
java -enableassertions asserttest
You can also limit assertions to specific packages, and specify packages to disable using -disableassertions too.
Personally I prefer to unconditionally validate parameter values, precisely because of this - I don't like the idea of running the code in a "safe" mode in test, but then letting it loose in production with the safety off. It's like learning to drive with a seatbelt on, but then entering an F1 race without any protection...
You should never use assertions on parameters or any input value in general.
Assertions are meant to describe invariants that ought to be always true. Therefore they can be switched off for performance reasons. You have to enable them, e.g. by using the -ea JVM option.
But inputs to a method should always be checked so use
if(i<=1) throw new IllegalArgumentException("i must be >1");
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
This question has bogged me quite a while. During programming there is regularly the question whether there is something in an object or not. For this reason was the isEmpty method invented. Great, but in practice we use it like !isEmpty almost all the time.
As a consequence, notEmpty would be a much more appreciated addition to a language like Java. The question is: why don't language designers think of this before defining the API? At least give a counterpart for isEmpty
EDIT: I meant there should be a notEmpty as well as isEmpty. Depending on the domain, both of them may be used but in most cases when a UI is not involved, I think notEmpty applies better.
EDIT2: To close the discussion, here is an example:
!metadata.isEmpty() == metadata.notEmpty()
I'd prefer we had the right side of the equation as well.
isEmpty follows the naming convention of other syntactically positive isXXX methods such as isVisible and isEnabled
I think it follows the convention of using is[Something]() for booleans in place of get[Something]().
Also, having to use !notEmpty() might get a bit confusing!
My opinion is, it is more logical because like == and !=. Logically It is better to have isEmpty and !isEmpty, It is easy to understand.