Replace Collections.unmodifiableList(Arrays.asList(....)); with List.of("...."); [closed] - java

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.

Related

Given a class, find out if it has been annotated with any annotation, yes or no [closed]

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).

Give a Java local the same name as a method? [closed]

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 4 years ago.
Improve this question
MyClassBuilder myClassBuilder = myClassBuilder()
A factory method to return a builder, assigned to a local of the same name as the method.
I've never seen this before today. Does it make sense or should it be avoided? It's not possible to meaningfully do this in Python or C++, so as I'm new to Java it feels wrong. IntelliJ doesn't give so much as a warning and it results in some (to me) confusing looking code.
Put simply: Is this considered idiomatic Java?
Edit: I don't feel this is purely opinion based. Major players in the Java community (possibly even the language creators themselves) may or may not be using this 'feature' of the language. If they did it would indicate that it's idiomatic. Answers would ideally cite references to where it's being used or specific problems that it solves. I don't think this is a good language feature, I've never used it but I'm open-minded and prepared to be convinced otherwise.
In java method and field names have their own name spaces, so they can be given the same name.
There are some code styles, that might use it:
public class Human {
private String opinion;
public Human opinion(String opinion) {
this.opinion = opinion;
return this;
}
public String opinion() {
return opinion;
}
Repetition due to field/method, field/parameter and method overloading.
Seen in fluent APIs, Builder patterns, from time to time getter-setter haters.
As you can see from the above it is kind of repetitive too. Verbal phrases for method names seems better (except we have size() and such).
Possible, but...
It is possible, and will compile, but it is really confusing. I think it is better to avoid such naming for your coworkers and/or your future self.
You can see this website for good practices, and I think you can even find better, official sources.

Why does java.util.Optional not have Some and None subclasses? [closed]

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
In Java 8, the Optional class is implemented as a final container class that defines isPresent depending on the value being null. That means that it is not possible to have an Optional(null), which although not commonly used, seems like a design flaw to me. In particular, this defeats the purpose of having an optional in the first place, because you can simply set a variable to null and do the usual if (x != null), without the overhead introduced by Optional. Furthermore, the Optional class has to check if the value == null for every single operation performed on it.
In Scala however, the Option trait is much more sophisticated: It has the Some subclass for existent values and the None subclass for non-existent values. This eliminates the need for null-checks inside the class and allows Some(null) values.
My question is why the Java designers chose not to follow this subclass principle as well.
Java has empty() and ofNullable(null). Other tool methods exist too. Scala uses subclassing, case classes where other languages (still) use other notions. Scala sees typing a bit more operational.
Java Optional is workable; come with code examples. Using a Stream for an Optional might be more in the character of Scala maybe, allowing fluent design with chaining calls in a bit more comfortable way.
It lives with null and is more a recommendation as you stated.

Alternatives to Assert [closed]

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 8 years ago.
Improve this question
The reasons I am dissatisfied with assert keyword in Java are
1) it's disabled by default, so it is a headache to make sure it's enabled when I want it to be
2) its behavior is rather rigid (I would want some inversion of control, ideally); but that's not terribly important.
Some of the alternatives I can think about:
JUnit's assertEquals() and such - good for tests, but can't use in main code
Guava's preconditions - great, but no assertion methods per se.
My own assertion library - I wrote it back in 1999, and back at the time it was great, but now I want to standardize.
Anything else?
So.. to sum it up.. how do I assert in production code in a way that is not disabled by default?
(And yes, this may be considered an anti-pattern by some, but I do want at least some assertions in Production, even if assertion failures are just silently logged. I see some room for that even in shrink-wraps, and definitely in websites).
I'd use Spring's Assert class, it includes a fairly extensive range of checks.
I am not sure if this is what you want, but I'm routinely using commons-lang Validate for many years already. Usually in public API methods/constructors to ensure that arguments are passed correctly. Not just notNull (see Lombok's #NotNull for this) but also noNullElements etc.
I especially like the <T> T notNull(T object) signature for immutables:
private final JSCodeModel codeModel;
private final String name;
public FunctionDeclarationImpl(JSCodeModel codeModel, String name,
String[] parameterNames, JSSourceElement[] sourceElements) {
this.codeModel = Validate.notNull(codeModel);
this.name = Validate.notNull(name);
...
}
What are your requirements, actually?
JUnit's assertEquals() and such - good for tests, but can't use in main code
Nothing technically prevents you from using JUnit assetions (and/or Hamcrest matchers) in your main code. Just include the Junit jar in your classpath. It's usually not done but that's more of a convention than any technical limitation.
Java 7 also introduced Objects.requireNotNull(obj, message) and similar methods although not as full featured as JUnit assertions.
but I think if you want to go with a more standardized approach Guava's preconditions is probably best.

Why Java utilizes both Collection and Collections classes to provide different things [closed]

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 years ago.
Improve this question
In many places Java utilizes the approach to have both, for example, Collection and Collections class.
Collection is interface, it defined some methods.
Collections class also provide some method.
Why didn't they choose to place all methods inside the interface?
because the names are too puzzled word. Collection is like Collections.
I know the historical reason. like interrupt() and interrupted() , because java must fit to old version, the methods' names are likely, make developer difficult to write and read.
But the collection framwork must have reason in this way.
For starters, an interface cannot have static methods. Note: until Java 8.
Arguably, some of the static methods of Collections should have been made instance methods of Collection, but that would create a lot of "clutter". Plus, extra work for implementations not derived from AbstractCollection etc.

Categories