eclipse-jdt / eclipse-jdt/eclipse.jdt.ui

Extract Variable duplicates side-effecting expressions when extracting a partial string concatenation expression

Open
#3,182 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
59
Forks
127
Avg merge
21h 41m
Merged PRs (30d)
31

Description

## Steps to reproduce

1. Create a Java project.
2. Add the following Java class:

```java
import java.util.function.Supplier;

public class L01 {

static int count = 0;

static String get() {
count++;
return "V" + count;
}

public static void main(String[] args) {

Supplier s =
() -> "A" + get() + get();

System.out.println(s.get());
System.out.println(count);
}
}
```

3. Select the expression:

```java
get() + get()
```

inside:

```java
() -> "A" + get() + get();
```

4. Apply **Refactor → Extract Local Variable**.

---

## Code before refactoring

```java
import java.util.function.Supplier;

public class L01 {

static int count = 0;

static String get() {
count++;
return "V" + count;
}

public static void main(String[] args) {

Supplier s =
() -> "A" + get() + get();

System.out.println(s.get());
System.out.println(count);
}
}
```

Program output:

```
AV1V2
2
```

---

## Code after refactoring

Eclipse generates:

```java
import java.util.function.Supplier;

public class L01 {

static int count = 0;

static String get() {
count++;
return "V" + count;
}

public static void main(String[] args) {

Supplier s =
() -> {
String t = get() + get();
return "A" + get() + get();
};

System.out.println(s.get());
System.out.println(count);
}
}
```

Program output:

```
AV3V4
4
```

---

## Expected behavior

Extract Variable should replace the selected expression with the introduced variable.

The expected transformation is:

```java
Supplier s =
() -> {
String t = get() + get();
return "A" + t;
};
```

The extracted expression should be evaluated only once, and the program behavior should remain unchanged.

Contributor guide

Open the contributing guide

Research direction

Reproduce the Java example and run Extract Local Variable on the selected get() + get() expression inside the lambda. Trace the Extract Local Variable refactoring entry point and compare the generated code with the expected transformation. Done means the selected expression is evaluated once, replaced by the local variable, and the program output remains unchanged.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Clearly specified
Newbie friendliness
58/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.