All Questions
Tagged with java coding-style
96
questions
1
vote
2answers
115 views
Granularity of a Method
I have a general design question. Suppose I have a List:
List<String> list = new ArrayList<>();
list.add("Str 1");
list.add("Str 2");
list.add("Str 3");
I ...
6
votes
1answer
247 views
How does Dependency Inversion solve switch cases?
I want to understand how Dependency Inversion gets rid of switch cases.
Consider a service that needs to communicate with several databases.
class StockUpdater {
private final DataStore datastore;
...
-1
votes
1answer
106 views
Is it bad to break out of a labelled block in Java?
I sometimes write Java code that looks like:
success: {
fail: {
if (...) break fail;
// some code
if (...) break fail;
// some code
if (...) break fail;
...
-4
votes
1answer
80 views
Java Class Structure
I have a problem during a project of mine using Java,
as usual my java classes have the structure:
import ...;
import ...;
...
private Type0 myVariable0;
private Type1 myVariable1;
...
...
private ...
5
votes
3answers
3k views
Significant difference between functional and procedural collection handling [closed]
I'm planning an empirical study on function passing - specifically lambdas aka anonymous functions aka arrow functions. Now, although functional or even object-oriented approaches are highly favored ...
2
votes
1answer
147 views
Better way to implement a feature with turn on/off based on a flag
I'm trying to implement a feature with option to turn it on/off based on a flag. I'm doing it in the following way which I feel like a overkill,
public interface Feature {
public interface ...
12
votes
5answers
1k views
How to introduce new language features in a legacy source code?
I have a coding style related question. In my example it is java, but I think this can be a generic question regarding languages that are changing rapidly.
I'm working on a java code base which was ...
2
votes
6answers
340 views
Java (or other Java-like languages): Best practice for many optional parameters?
Code design question for Java or Java-like languages (excluding languages which support default values for method parameters such as Javascript flavors):
You would like to implement a method with the ...
2
votes
2answers
251 views
Design pattern for static fields of a subclass
I'm creating a library, and I want there to be an abstract class called Optimizer. The user should be able to choose from a set of predefined Optimizers and if desired, use fluent methods to change ...
11
votes
4answers
2k views
Which is the better way to call a method that is only available to one class that implements an interface but not the other one?
Basically I need to execute different actions given a certain condition. The existing code is written this way
Base interface
// DoSomething.java
interface DoSomething {
void letDoIt(String info)...
8
votes
2answers
425 views
Is it a good practice to create new variable to see the output of a function?
Consider these 2 types of implementation:
public int add(int x, int y) {
return mysteriousAdd(x, y);
}
public int add(int x, int y) {
int output = mysteriousAdd(x, y);
return output;
}
...
0
votes
1answer
162 views
Is Java-like restrictiveness OK Python style?
Good Pythonic style is much looser than Java's uptight restrictiveness:
In Java, good style means private on methods wherever possible, all fields encapsulated, type declarations, defined ...
-2
votes
1answer
1k views
How to clean a refactor Java for-if-try-catch-else kind of messy code [duplicate]
Often I came across situations like this, how to write this code in a neat and clean way.
One more issue I find here is performance as I am iteration a list and then it's properties.
Edit : - while ...
0
votes
2answers
2k views
Using the same name for setter and gettter methods for a boolean member variable
Say I have class with a boolean member variable fancy:
public class MyClass {
private boolean fancy;
}
Case 1. I could the define the setter and getter as follows:
// getter
public boolean ...
3
votes
4answers
970 views
Is “Let more people able to review” a valid reason to “write c++ as if Java” at some degree?
According to Should we avoid language features that C++ has but Java doesn't?, I know it is horrible to write C++ as if Java, mostly because it drops the beneficial features of C++ languages.
But ...
0
votes
1answer
701 views
Representing Java Object Hierarchy With Nested Classes
I was working with some API which was used internally, and while looking at their code I found something like this:
public class Parent {
@Data
public static class Child {
private ...
-2
votes
1answer
327 views
What to name my config classes
What name should I give classes which are just for configuration? For example, when using JAX-RS, every application is required to have an Application class which extends the superclass javax.ws.rs....
0
votes
2answers
7k views
changing the value of String object in java
I have to set the value of a string object "result" depending on the results of different methods and different if/else conditions. In the end, there would be one (last value set) in the string that i ...
2
votes
5answers
1k views
What should a constructor contain?
What should a constructor contain?
In both cases, all three arguments are needed for the class to work.
Which approach is better and why?
1)
class Language {
LanguageRepository ...
7
votes
2answers
404 views
How should separated methods be used?
Among other things, the CQRS has a rule that each of the methods has one responsibility. So we can't have this in the model:
public class Store {
public Item getOrCreateItem(int id)
{
...
-1
votes
3answers
74 views
Is it good style that calling setters follow the same order as XSD elements? [closed]
In the project I work on we use XSD to generate some classes. XSD determines the order of elements, similar to this snippet:
<xs:element name="Customer_ID" type="com:Text6"/>
<xs:element ...
0
votes
5answers
737 views
Should I follow “dependency inversion principle” rule even if I need one type only and don't need polymorphism?
Consider I have classes as follows:
public class User{
private String name;
//other code
private String getName(){
return name;
}
}
public class ShowUserInfo{
public void ...
2
votes
3answers
2k views
Return array pointers vs. populating an array inserted as a parameter?
Which is better? I noticed the latter is used in a lot of C code. People will typically malloc an array, and then pass that as a parameter to a function, which will then populate it. Whereas in Java, ...
1
vote
3answers
342 views
Is it better practice to create a new variable solely for demonstrating something is final?
I recently encountered a situation in a Java project where I wrote a block like this:
String user = System.getProperty("user.home").toUpperCase();
user = user.substring(user.lastIndexOf(File....
16
votes
5answers
8k views
Boolean return of set.add() in if conditional?
The add operator of the set class returns a boolean which is true if the element (which is to be added) wasn't already there, and false otherwise. Is writing
if (set.add(entry)) {
//do some more ...
1
vote
2answers
2k views
Return array of multiple different objects?
I have code along the following lines:
public void processInput() {
List<String> input = readInput();
final Object[] returnObj = createInternalStructureFrom(input);
final Dictionary ...
3
votes
3answers
2k views
Tradeoff between clean code, duplicate code and code efficiency in java
I have a question on writing clean code. I’m trying to refactor the following method:
private static Map<String, String> createMapOfAttributes(
final String Id,
final String ...
2
votes
1answer
496 views
Package-by-feature confusion for libraries
As I understand it, it's generally recommended to package by feature rather than by layer. This promotes higher levels of abstraction and modularity between classes.
I can understand how this works ...
2
votes
2answers
703 views
Static per-enum data: constructor, set in initialiser or override getter?
I have an enum with > 10 items each having 8 static properties. Contrived example:
enum JavaTypes {
INTEGER,
BOOLEAN,
STRING,
...;
boolean isPrimitive() {
}
boolean ...
21
votes
5answers
3k views
Should non-trivial conditional statements be moved to the initialization section of loops?
I got this idea from this question on stackoverflow.com
The following pattern is common:
final x = 10;//whatever constant value
for(int i = 0; i < Math.floor(Math.sqrt(x)) + 1; i++) {
//...do ...
5
votes
2answers
168 views
Is avoiding having the fields representing the same object in different communicating classes reasonable?
I'm developing a program which does communication to different types of devices (with respective protocols). It should concurrently acquire messages from devices and write them to a file with specific ...
11
votes
3answers
3k views
In Java 8, is it stylistically better to use method reference expressions or methods returning an implementation of the functional interface?
Java 8 added the concept of functional interfaces, as well as numerous new methods that are designed to take functional interfaces. Instances of these interfaces can be succinctly created using ...
1
vote
2answers
3k views
SonarQube is complaining about: “Use isEmpty() to check whether the collection is empty or not.”
So as my the title says, SonarQube is complaining whenever you use
list.size() == 0
or
list.size > 0
However I started changing to isEmpty() and !is.Empty() and noticed the code becomes way ...
4
votes
3answers
4k views
When declaring an array in Java, what is the conventional location for the square brackets?
I've seen two methods of declaring an array, such as the String[] args portion of the main method:
public static void main(String args[]){
or
public static void main(String[] args){
The textbook ...
15
votes
2answers
2k views
Now that not all method declarations in a Java Interface are public abstract, should the methods be declared with these modifiers?
Starting with Java 8, default methods were introduced into interfaces. Effectively, this means that not all methods in an interface are abstract.
Starting with Java 9 (maybe), private methods will be ...
1
vote
1answer
767 views
Coding guidlines for Controller and Dao?
My Controller code:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ObjectReader objectReader = objectMapper.reader(...
2
votes
3answers
513 views
Why do assertions in Java need to get enabled?
I really like the concept of assertions in Java in the way how to use them. It's much easier than to write an if and then throw an Exception/Error.
But the thing I don't understand is, why do they ...
99
votes
10answers
14k views
Has / can anyone challenge Uncle Bob on his love of removing “useless braces”?
I hate referencing paywalled content, but this video shows exactly what I'm talking about. Precisely 12 minutes in Robert Martin looks at this:
And says "One of my favorite things to do is getting ...
9
votes
3answers
5k views
Is nesting try-catch statements still a code smell if nested within a loop?
I have heard that nesting try-catch statements can often be a code smell, so I'm wondering whether this situation is an exception. If not, what would be some good ways to refactor?
My code looks like ...
8
votes
3answers
332 views
OOP design problem. Two kinds of empty Optional
I'm writing a quite simple application that deals with hotel rooms reservation. I've got a problem at one stage.
I'm processing a queue of orders. For every order one of the receptionists should ...
36
votes
8answers
19k views
What Style is Better (Instance Variable vs. Return Value) in Java
I often find myself struggling to decide which of these two ways to use when I require to use common data across some methods in my classes. What would be a better choice?
In this option, I can ...
1
vote
3answers
533 views
Single exit point meets Java streams
We currently have a sensitive discussion going in the company that touches on a couple of old primary opinion based discussions. Nevertheless, I would like to discuss the case in this forum to ...
12
votes
3answers
43k views
How to deal with Classes having the same name (different packages)
Me and my R&D team maintain a large codebase. We've divided our business logic into multiple packages. some of which have classes with identical names.
As you can guess, the names conflict when ...
2
votes
1answer
436 views
Javascript Closure Style Similar to Java Class Structure
PROBLEM: There is a coding imperative (S. McConnel, Code Complete) that one shouldn't code on language, but by means of it, e.g. doing right style things even if language doesn't have some ...
0
votes
1answer
82 views
How confusing is `new SomeCollection(values…)::contains` as a Predicate? [closed]
Traditionally, a function that want to skip certain items during processing will accept a Collection or var-args argument, but in the Java 8 world I think I should switch to Predicates.
Now, since ...
1
vote
1answer
252 views
Sorting Array before looping : best practice
I was going through JBAKE code at
https://github.com/jbake-org/jbake/blob/master/src/main/java/org/jbake/app/Asset.java : 58
PFB the code.
Why are we sorting the array here?
if (assets != ...
46
votes
6answers
13k views
Is it better to check `c >= '0'` or `c >= 48`?
After a discussion with some my colleagues, I've a 'philosophical' question about how treat the char data type in Java, following the best practices.
Suppose a simple scenario (obviously this is only ...
3
votes
1answer
827 views
implementing an extended interface on a concrete class
I don't know if this is a best practices or not. If I have a interface that extends another interface such as :
public interface A extends B{
public void something();
};
and a concrete class ...
8
votes
4answers
767 views
Is this code structure beneficial in any way?
I was recently thrown into a Java web application project, and I’ve come across a number of classes that follow this type of format:
public class MyThingy {
private final int p1;
private final ...
5
votes
3answers
2k views
Creating a Java project without using any objects and just calling static methods on input?
I'm creating a program which takes a document, extracts it, and then moves this into a database. I've done most of this now and I've realised that I haven't made any instances of classes I've made (I ...