Conditions | 12 |
Total Lines | 28 |
Code Lines | 18 |
Lines | 0 |
Ratio | 0 % |
Changes | 2 | ||
Bugs | 0 | Features | 0 |
Complex classes like net.labymod.serverapi.Addon.getAddons(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.serverapi; |
||
32 | public static List<Addon> getAddons( JsonObject jsonObject ) { |
||
33 | if ( !jsonObject.has( "addons" ) || !jsonObject.get( "addons" ).isJsonArray() ) |
||
34 | return new ArrayList<>(); |
||
35 | |||
36 | List<Addon> addons = new ArrayList<>(); |
||
37 | |||
38 | for ( JsonElement arrayElement : jsonObject.get( "addons" ).getAsJsonArray() ) { |
||
39 | if ( !arrayElement.isJsonObject() ) |
||
40 | continue; |
||
41 | |||
42 | JsonObject arrayObject = arrayElement.getAsJsonObject(); |
||
43 | |||
44 | if ( !arrayObject.has( "uuid" ) || !arrayObject.get( "uuid" ).isJsonPrimitive() || !arrayObject.get( "uuid" ).getAsJsonPrimitive().isString() |
||
45 | || !arrayObject.has( "name" ) || !arrayObject.get( "name" ).isJsonPrimitive() || !arrayObject.get( "name" ).getAsJsonPrimitive().isString() ) |
||
46 | continue; |
||
47 | |||
48 | UUID uuid = null; |
||
|
|||
49 | |||
50 | try { |
||
51 | uuid = UUID.fromString( arrayObject.get( "uuid" ).getAsString() ); |
||
52 | } catch ( IllegalArgumentException ex ) { |
||
53 | continue; |
||
54 | } |
||
55 | |||
56 | addons.add( new Addon( uuid, arrayObject.get( "name" ).getAsString() ) ); |
||
57 | } |
||
58 | |||
59 | return addons; |
||
60 | } |
||
63 |
Even if your block only consists of one line right now, it is good practice to enclose it in curly braces. It makes your code much more readable.