Skip to main content

All Questions

Tagged with
Filter by
Sorted by
Tagged with
1 vote
1 answer
86 views

Diamond operator extends one or another [duplicate]

In my code I have two classes that are very similar (but still different), yet I want to map them both to a third class. I have it this way: class AToCMapper { public C from(A a) { // My ...
Adr4m's user avatar
  • 85
0 votes
1 answer
51 views

Reducing Java code-duplication when iteratively applying an operation on a list until stable

I am attempting to reduce code duplication in my java code. I am not a java expert, so I might be missing something basic. The goal is to operate on a list via several operators, foo1, foo2, ..., fooN....
Caleb's user avatar
  • 160
0 votes
1 answer
97 views

Refactoring in Java: The method setCode(int) in the type Refactor is not applicable for the arguments ()

I'm trying to reduce code duplication by creating a new class (Refactor.java) to accommodate the methods that are called in two other classes (A and B). This is what I came up with so far: public ...
Westrany's user avatar
1 vote
2 answers
96 views

How to use functional interface (perhaps) to pass comparison operator to a while loop?

I have two almost identical methods, the only difference is than one goes "left" and the second "right" from the spot in the array. Is there any way how to de-duplicate these tow ...
Jan Tibar's user avatar
3 votes
3 answers
287 views

How to avoid duplicate code with a helper-method for shared REST-operations like GET and DELETE

I have two methods methodOne (e.g. for a GET on questionaire) methodTwo (e.g. for a DELETE on questionaire) Both have almost same lines of code. IntelliJ also underlines the code and shows a warning:...
ma66ot's user avatar
  • 57
0 votes
0 answers
656 views

Getting "duplicate class" error in IntelliJ Idea Community edition, preventing complete compilation of workspace

I am trying to compile my entire workspace with about 200 modules in it. Using javac compiler with extra arguments -Xmaxerrs 1000 -Xmaxwarns 1000 However, the compilation is getting stopped due to the ...
ayaan604's user avatar
-3 votes
1 answer
85 views

Two classes with duplicates [closed]

I'm new to Java and object oriented programming. I've tried to find the solution myself, but couldn't manage to solve this problem. I have two duplicated pieces of code which I need to remove. As I ...
dgr379's user avatar
  • 345
0 votes
1 answer
217 views

How to generalize methods using functional Java

Can we reduce code duplication with these methods with the new java functional paradigm? I tried to pass the function as param. But one has Functional and the other BiFunctional. Unable to make it as ...
Forece85's user avatar
  • 498
0 votes
1 answer
257 views

Removing duplicate codes from if/else and try clause

Sonar has marked the below-mentioned code as duplicate, and I am not able to understand how to refactor the code as the fragments of the code exist in the if/else and try clause. First Method: private ...
Rishabh Prasad's user avatar
0 votes
2 answers
1k views

How to avoid duplicate code in Java when you require the same class in two separated applications?

For the sake of simplicity, let's say that I have a class named "Dog". Then I have two separated applications containing implementations of that class. Application "A" does ...
Jsh0s's user avatar
  • 599
1 vote
1 answer
129 views

How can I use one algorithm with audit logging and without, without duplication

I have this method. It is a simple example, a synthetic example: private int foo() { StringBuilder builder = new StringBuilder(); int result = 0; for (int i = 0; i < 10; i++) { ...
Pavel Petrashov's user avatar
0 votes
3 answers
108 views

How do I get rid of all this duplicate code?

private Optional<Player> playerWithMostCards() { Player scoringPlayer = null; int maxCount = 0; for(Player p : players) { final int count = p....
Picarrow's user avatar
-1 votes
2 answers
806 views

How to solve multiple "if return" statements being reported as duplicated code by sonarqube

Sonarqube reports duplicate code when having multiple if return statements. For example I have the following code: private static double computeGain(int rangeMax) { if (rangeMax <= 35) { ...
jfpatenaude's user avatar
2 votes
1 answer
162 views

How to avoid duplicate logic?

Given two methods that are somehow duplicate logic: default void method_one(int a, int b) { LOGGER.info("abc"); final long start = System.currentTimeMillis(); doMethod_A(a, b); ...
DerBenniAusA's user avatar
3 votes
3 answers
2k views

Map enum to another enum with less amount of code in java

I have two enum classes one is external and the other is internal. public enum ExternalEnum { EXTERNAL_CAR, EXTERNAL_VAN, EXTERNAL_BUS } public enum InternalEnum { CAR, VAN, BUS } I need to map ...
abo's user avatar
  • 378
0 votes
2 answers
389 views

Duplicate condition after loop when checking subsequences

When I check for subsequences I always duplicate the condition after the loop. For example, I want to find the maximum subsequence of numbers with a difference of no more than one. Here is my code ...
vszholobov's user avatar
  • 2,353
1 vote
1 answer
218 views

How to substitute @CsvSourceFile in parent AbstractTest to use different file sources in children tests?

JUnit 5 I have a lot of number properties in separate classes. They all implement Property interface and I would like to test them all. All test looks identical like this: @DisplayName("Given ...
Jegors Čemisovs's user avatar
1 vote
0 answers
249 views

How to avoid duplicate code inside constructors? Java

Often when writing objects, I end up creating rather lengthy constructors or constructors containing code that is already present in the object's instance methods (duplicate code). I know that I can ...
Picarrow's user avatar
0 votes
1 answer
343 views

Extract duplicated method which is used in many packages

I have a method: private Replace ReplaceType(final ReplaceTypeDao replaceTypeDao, final Long key) { final Optional<ReplaceType> replaceTypeEntry = replaceTypeDao.findById(key, true); ...
Michu93's user avatar
  • 5,689
0 votes
0 answers
73 views

How do I avoid code duplication in my case?

I am currently working on code that converts one data model to another. More precisely, it is a Hafas model, but it is not very important. The problem is that I have to support multiple versions of ...
Chuck Nuris's user avatar
0 votes
1 answer
67 views

Java join duplicate methods

I have two methods in service that are mostly the same, except for the entity and runnable type. Is there a way to join them? I think generics could be helpful but have no idea how to apply them here ...
hankuk's user avatar
  • 41
0 votes
2 answers
1k views

How to avoid duplication on similar classes and similar methods?

Context I am working with very similar classes like RechargeResponse or ConsultResponse. All of them (around 80) are generated from WSDL scheme has the same structure. (This scheme comes from 3PP ...
Edward's user avatar
  • 3
1 vote
1 answer
107 views

Reduce code duplicating in functional style java code [closed]

How to reduce code duplicating in the following snippet? Java 12. Thank you in advance public <V, RK> Map<RK, V> mapKeys(Map<String, V> input, Function<String, RK> ...
Žeka Koževin's user avatar
0 votes
2 answers
178 views

How to use an interface/something similar to clean up duplicate code in Java

I have output functions that output data from different objects to their corresponding files. Most of these functions follow the same pattern, the only differences are the objects being used and by ...
thePandasFriend's user avatar
0 votes
1 answer
123 views

Java class inheriting from multiple interfaces without code duplication

Imagine 5 interfaces: IAnimal ICanivore extends IAnimal IPet extends IAnimal IDog extends IPet, ICarnivore ICat extends IPet, ICarnivore I now want to create 2 new classes for dogs and cats, class ...
user avatar
4 votes
1 answer
945 views

How can I avoid duplicate code with the same method body but different return types in Java?

The Idea: When I was using hibernate I saw that everytime I had to write some sort of code. So I moved them to another method as wrapper. Where there will be functional interface as argument so that I ...
Farhat Shahir's user avatar
2 votes
2 answers
67 views

Avoiding code duplication when checking for default responses

I have a Java program that calls an external API (RealApi in the code below) and sometimes I want to avoid calling this API and instead return pre-constructed responses (generated by FakeApi). So, I ...
Schrute's user avatar
  • 729
1 vote
3 answers
2k views

How to use 2 classes having same methods but without a parent class?

Let's assume we have 2 classes in Java 8, ClassA and ClassB. ClassA is a dependency class which cannot be changed in any way. ClassB is kind of like a copy of ClassA but with some modifications. ...
Vineeth Chelur's user avatar
0 votes
1 answer
450 views

how do I check java code duplications from files [closed]

I am going through a project where I have to check the plagiarism between two files.In two files there have some java code.That means if there are two files named a.java and b.java and in two files ...
Sanzida Sultana's user avatar
2 votes
1 answer
296 views

Java | Using Generics to Reduce Code Duplication

I have been trying to write a simple but flexible class that holds some values of generic type T. T extends Number, which means I just want this class to deal with everything from bytes to longs. I am ...
antshekhter's user avatar
1 vote
1 answer
116 views

Template Method: How to use it when you want to be able to flexibly change primitive options?

The problem is best explained with the following code: public class TemplateClass { public void templateOne() { checkConditionA(); primitiveOp1(); checkConditionB(); } ...
Horyzon's user avatar
  • 33
0 votes
1 answer
2k views

Sonar 'Source files should not have any duplicated blocks' rule doesn't distinguish different literals

I have a simple two-level hierarchy made up of an abstract superclass named AbstractTable, and three specific subclasses, Table1, Table2 and Table3. Each subclass provide one different implementation ...
Gustavo Bartolomeo's user avatar
2 votes
1 answer
656 views

State Design Pattern: How to avoid code duplication when using entry() and exit()?

Situation: My States have an entry() and exit() method that needs to be called every time when a State transitions. To ensure that, I used a changeState() method in State that contains the necessary ...
Horyzon's user avatar
  • 33
0 votes
2 answers
63 views

Avoid duplicated code if the only diffence is a method call in a for loop

I have this two methods written in java: public void fillRect(float x, float y, float width, float height, Color color) { int xi = mapX(x); int yi = mapY(y); int heightf = ...
Meeresgott's user avatar
4 votes
2 answers
2k views

How can I avoid DTOs duplication without inheritance?

I am connecting with many social networks for login in my application. I have one DTO for each social network response. public class GoogleUserInfo { private String id; private String ...
Leandro Suarez's user avatar
2 votes
1 answer
111 views

Avoiding Dynamic Type Casting with Inheritance for Data Classes in Java

I have 3 Data Classes @Data class A { private int a; } @Data class B extends A { private int b; } @Data class C extends A { private int c; } Class B and C have some common fields ...
Daanish Sarguru's user avatar
0 votes
1 answer
70 views

How best to refactor variable instantiation duplication in Java?

I have two methods in Java that collect different information, but they both set up and run the same process which we then collect information from - and the collection of the data happens inside a ...
James's user avatar
  • 809
9 votes
2 answers
203 views

How to avoid duplication of code regarding primitive types?

Background A bit input stream is backed by an array of bytes. There are a handful of methods that read from that byte array into various coerced primitive arrays. Problem There is duplicated code. ...
Dave Jarvis's user avatar
  • 31.2k
0 votes
2 answers
178 views

Factory pattern with parameterized methods

These are a set of services which all follow the same algorithm. Consumers call these services and the services send the request for the consumers to some backend system. The service interface is ...
embarr's user avatar
  • 1
1 vote
2 answers
5k views

How to refactoring this duplicated code fragment of switch statement

I'm coding some CRUD application, a page show data from a database table and should join with two very similar table (These two very similar table cannot optimized to one table for history reason or ...
terrason's user avatar
0 votes
2 answers
62 views

Improving alghoritm to pair players - too much duplication code

I have got players. Players got preferred position. We have got 3 positions - DEFENDERS, ATTACKERS, BOTH (players who are good on both positions). I need to create teams of two. Pairing players should ...
mara122's user avatar
  • 313
-1 votes
1 answer
102 views

Pass a function with lamba expression to make a generic function

I am using google's AutoValue to generate some configs, but before generating the configs, I would like to make sure that the entries are sanitized and default values are added to the list. The ...
QuirkyBit's user avatar
  • 742
0 votes
2 answers
61 views

Is there a way to shorten code that is duplicated because of similiar properties of objects?

I have many Checkboxes all of whom are dependant on a certain box not being ticked, if however it does get ticked the boxes must be ticked and hidden. I know people keep saying ArrayList but, I have ...
theunie's user avatar
  • 83
1 vote
1 answer
766 views

How to prevent duplicate code in Exception

I have dozens of entities . And everytime I have to catch exceptions. Now I always have dupliate code. In this example all the catch blocks will be duplicate. How could I prevent this. try { ...
Steve Clever's user avatar
4 votes
4 answers
2k views

Avoid duplicate code with numerous Java classes sharing fields

I'm working on an application which writes on a NoSQL database (Elasticsearch to be precise) and I have to manage more than a dozen (the number grows with time) different document classes, that is ...
Ukitinu's user avatar
  • 53
0 votes
0 answers
57 views

how to "increment" variable names for loops [duplicate]

I'm reading through some coding books and am learning about classes and I want to increment the name of the class variable for months days and year. I just want to know how to increment date more ...
TFreight's user avatar
-16 votes
7 answers
1k views

Is there a more efficient way to write multiple if else? [duplicate]

I need to match the average score to a letter grade. That means if (90 < avg && avg < 100) { return 'A'; } and so on until 'F', with 5 if-else statements. That's a lot of ...
L C's user avatar
  • 65
1 vote
0 answers
155 views

refactor try-catch across class hierarchy

Suppose you have this code: class Base { void method() throws Exception { try { //Lots of code here } catch (Exception e) { //handle it (very little code ...
Mark VY's user avatar
  • 1,661
0 votes
0 answers
313 views

How to make sonar to show small code duplicates in java?

I want to see code duplication in sonar report, and I am more strict than sonar: I want to set limit to 5 tokens. As it turns out, the limit is not settable with the java analyzer of sonar. So I use ...
Árpád Magosányi's user avatar
1 vote
1 answer
676 views

IntelliJ IDEA Ultimate 2018.3.5 duplicate code not highlighted

IntelliJ IDEA Ultimate 2018.3.5 duplicate code not highlighted on the fly. I've checked the checkbox from Settings -> Inspections -> General but nothing is highlighted when I have duplicated ...
stefanbanu's user avatar