Passed
Pull Request — master (#5)
by Manuel
04:01
created

collectAddons(JsonObject)   D

Complexity

Conditions 12

Size

Total Lines 33
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 22
c 0
b 0
f 0
dl 0
loc 33
rs 4.8

How to fix   Complexity   

Complexity

Complex classes like net.labymod.server.common.addon.StandardAddonCollector.collectAddons(JsonObject) often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
package net.labymod.server.common.addon;
2
3
import com.google.gson.JsonElement;
4
import com.google.gson.JsonObject;
5
import edu.umd.cs.findbugs.annotations.NonNull;
6
import net.labymod.server.common.addon.model.AddonModel;
7
8
import java.util.ArrayList;
9
import java.util.Collections;
10
import java.util.List;
11
import java.util.UUID;
12
13
/**
14
 * The {@link StandardAddonCollector} implement the {@link AddonCollector} to collect
15
 * all {@link AddonModel} as {@link List} from {@link JsonObject}.
16
 *
17
 * @author Manuel Kollus
18
 * @version 2.0
19
 * @since 2.0
20
 */
21
final class StandardAddonCollector implements AddonCollector {
22
23
    @Override
24
    public List<AddonModel> collectAddons( @NonNull JsonObject jsonObject ) {
25
        if ( !jsonObject.has( "addons" ) || !jsonObject.get( "addons" ).isJsonArray() ) {
26
            return Collections.emptyList();
27
        }
28
29
        List<AddonModel> addons = new ArrayList<>();
30
31
        for ( JsonElement arrayElement : jsonObject.get( "addons" ).getAsJsonArray() ) {
32
            if ( !arrayElement.isJsonObject() )
33
                continue;
34
35
            JsonObject arrayObject = arrayElement.getAsJsonObject();
36
37
            if ( !arrayObject.has( "uuid" ) || !arrayObject.get( "uuid" ).isJsonPrimitive() || !arrayObject.get( "uuid" ).getAsJsonPrimitive().isString()
38
                    || !arrayObject.has( "name" ) || !arrayObject.get( "name" ).isJsonPrimitive() || !arrayObject.get( "name" ).getAsJsonPrimitive().isString() )
39
                continue;
40
41
            UUID uuid;
42
43
            try {
44
                uuid = UUID.fromString( arrayObject.get( "uuid" ).getAsString() );
45
            } catch ( IllegalArgumentException ignored ) {
46
                continue;
47
            }
48
49
            addons.add( AddonModel.newBuilder()
50
                    .withName( arrayObject.get( "name" ).getAsString() )
51
                    .withUniqueId( uuid )
52
                    .create() );
53
        }
54
55
        return addons;
56
    }
57
}
58