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.
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 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 months ago.
The community reviewed whether to reopen this question 9 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
It occurred to me that interfaces cannot be instantiated and hence I could create an interface containing only a bunch of static utilities methods that I need as opposed to a regular class with a private constructor and public static methods. Any comments on that? Should I do it or does it not really matter?
A program is not just a set of instructions for a computer to obey. It's also a message to future developers. You should use the statements in your program to indicate to other developers (or even yourself a few months into the future), what you intend for the computer to do.
That's why we give variables, methods and classes clear names. It's why we lay out our programs in certain expected ways. It's why we use indentation consistently, and why we have naming conventions.
One of those conventions is that if you have a bunch of static methods that need to be organised together, they should be organised into a class, not an interface. Whether or not it's technically possible to put all your methods into an interface is not the question you should be asking. What matters is how to communicate most efficiently what you're actually intending to do.
To that end, please don't set up your program in strange, innovative ways. You're just going to confuse and annoy people.
Although this is possible interfaces should be used
when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts.
https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
Interfaces should be defined as an abstract type used to specify the behavior of a class; therefore they're meant to be later implemented.
What you're trying to do is not completely wrong (interfaces can offer static methods), but it's definitely not what they were designed for. If you want to offer a set of static utilities from a common "place", you could declare a final class with a private constructor, in order to prevent its extension (with possible methods overriding), and avoid its instantiation. The Math class is a perfect example of this.
Alternatively, if you want to declare instances of said class, you could declare your class normally, then declare its methods as final (to prevent their overriding) and offer a public constructor or a factory method.
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 6 years ago.
Improve this question
I'm looking for the best way to implement three-valued logic.
I googled and found three different approaches:
Use null value for Boolean variable as undefined
This variant looks to dangerous for me because it can unexpectedly cause NullPointerException
Use Optional<Boolean> type
This variant still is a bit dangerous. To avoid NoSuchElementException you should use constructions like this:
Optional<Boolean> amIRight = Optional.empty();
if (Optional.of(true).equals(amIRight ) {
doSome();
}
It looks too wordy for me
Implement your own enum
The last variant seems to be the best. Almost safe, very simple in undefstanding. But I haven't find any of such enums in widely spread java libriaries such as Apache, Google Guava and so on. It looks strange for me everybody avoids the simpler and safest implementation.
May be I missed something and there are serious reason not to implement three-valued logic enum.
If enum works for you, go for it.
Don't use that Boolean, it is ugly and destroy readability ... I also can't imagine how horrible it would be if you want it to support 4 values later...
Other cautions / advise :
Are you sure that you will use only 3 values?
In many situation, design tends to change, and enum will be no longer enough.
Using a class that encapsulate enum (or int) can provide better flexibility.
However, you can change from enum to class later.
In my program, I extensively use enum.
You shouldn't care much about what popular libraries do, just pick the best that work for you!
About the very interesting hypothesis :
... there are serious reason not to implement three-valued logic enum. ...
Suppose that I am Java language designer.
You ask for a 3-logic enum.
I accept you proposal.
Then, Mr.2D ask "We have 3-logic enum. Why don't you provide 4-logic enum to support +x -x +y -y?".
I give him what he want.
After that, Mr.LoveFive Mr.ObsessiveSick ..... I think you got the point.
There has to be a threshold (when to stop) and the demand for 3-enum is relatively very low compared to 2-enum (boolean).
I agree that enums is by far the safest and best solution to your problem. Perhaps enums are not widely used in projects like Apache because enums are relatively new in Java (I think they came along in Java 1.5).
If you want 3 valued logic, you are no longer talking about simple true/false conditions, you are talking about a state machine. Arguably state machines are among the most powerful paradigms in programming. If you aren't conversant with automata theory, look it up.
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 8 years ago.
Improve this question
I'm reading Martin Fowler's Refactoring book. In many of his refactoring examples, he is using variables that start with _varname. Why? Is this some old convention that is before my time? In the past year when I started learning Java, I have not seen anyone at work use this. Please advise as to where and why should this be used?
I'm already seeing differences in answers to this question...
Why does martin fowler do this in this code for extract method refactoring?
FROM:
void printOwing(double amount) {
printBanner();
//print details
System.out.println ("name:" + _name);
System.out.println ("amount" + amount);
}
TO:
void printOwing(double amount) {
printBanner();
printDetails(amount);
}
It is a convention to start the names of private fields of an object with an underscore in order to distinguish them from local variables in the code. This convention is not universal. Personally, I think that it is a bit superfluous when you have syntax highlighting that also shows the difference.
An alternative (although you could also use both) is to always reference members through this:
package org.foo.bar;
class Baz {
private String quux;
Baz (String quux) {
this.quux = quux;
}
String getQuux () {
return this.quux;
}
}
The convention is often used for private fields.
You don't have to use it, the most important is to be consistent, so if you are working on an existing code base, continue with that style.
Most likely, to distinguish local variables from class members.
EDIT: Now that you've added sample code, that is indeed the case.
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
Is it considered bad style to use long, but descriptive method names such as "adjacentLocationsByState()" and if so, would it be better to shorten it to something like "adjLocByState" which is definitely shorter, but also less readable in my opinion
Don't make me think.
When I read your code, if I have to stop and think about what the method name might mean, it usually means that the method name is wrong. Longer method names are preferable when it adds useful context to the method.
There are two rules I basically follow when writing code:
Must be readable as a normal text to which a human eye got used from books and mass media (so adjLocByState is not the case)
Maximize brevity, utilize programming techniques - code conventions and default states. These could be applied when some of the terms start appear to repeat too often.
So, adjacentLocationsByState() reads perfectly fine, but it could be shortened to just:
adjacentLocations()
which by default would return locations by their state and adjacentLocations(STATE) or chaining with fluent interface technique which allows more options for having the criteria: adjacentLocations().by(STATE). STATE here is a member of an enum LocationCriteria.
So in the end of the day it could look like:
adjacentLocations()
adjacentLocations().by(STATE)
adjacentLocations(STATE)
Of course, there is a time sacrifice which is spent on coding the 2nd and the 3rd forms.
Longer version is more readable and the the code is self documenting. So a good method name = method responsibility. Adj can be understand as adjust or adjacent, etc.
Keep in mind: Code is read 10 times more than it is written.!
You really write code that will often be read again and again. The more meaningful your names are, the more understandable is the code.
You are declaring classes, fields, methods, variables, and many more. You are thinking about them, you are developping a well-defined structure. All the time, you make hard decisions. The names that you give to your entities (classes, fields, ...) reflect all your thoughts on that. They reflect the intention of your code.
Conclusion: Names are the most important properties of your code. So, you always should think deeply about the names you give to your variables, methods, and so on. And you always should not abbreviate them in what way ever.
Its part of Documentation.
Usually everybody like to write Code in two phases before commit:
Implementation
Documentation
By example (phase 1):
ObjectOutputStream oos = ...
List a : ob.getSOE();
for(Object a: b){
oos.writeObject(a);
}
Then phase 2:
ObjectOutputStream stackOverflowElementOuputStream = ...
List stackOverflowElements : ob.getStackOverflowElement();
for(Object currentStackOverflowElement: stackOverflowElements){
stackOverflowElementOuputStream.writeObject(currentStackOverflowElement);
}