satcfdi.render.helpers.format_address_raw()   D
last analyzed

Complexity

Conditions 12

Size

Total Lines 32
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 12.0135

Importance

Changes 0
Metric Value
cc 12
eloc 22
nop 10
dl 0
loc 32
ccs 21
cts 22
cp 0.9545
crap 12.0135
rs 4.8
c 0
b 0
f 0

How to fix   Complexity    Many Parameters   

Complexity

Complex classes like satcfdi.render.helpers.format_address_raw() 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.

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1 1
from ..models import Code
2
3
4 1
def format_address_raw(calle, num_exterior, num_interior, referencia, colonia, municipio, localidad, estado, pais, codigo_postal):
5 1
    parts = []
6
7 1
    calle_num = None
8 1
    if calle or num_exterior or num_interior:
9 1
        if num_exterior:
10 1
            calle_num = f"{calle} #{num_exterior}"
11
        else:
12 1
            calle_num = f"{calle}"
13
14 1
        if num_interior:
15 1
            calle_num = f"{calle_num}, int. #{num_interior}"
16
17 1
    if colonia:
18 1
        if calle_num:
19 1
            parts.append(f"{calle_num}, {colonia}")
20
        else:
21
            parts.append(f"{colonia}")
22
23 1
    if referencia:
24 1
        parts.append(f"{referencia}")
25
26 1
    if localidad and localidad != municipio:
27 1
        parts.append(f"{localidad}")
28
29 1
    if municipio:
30 1
        parts.append(f"{municipio}, {estado} {codigo_postal}")
31
    else:
32 1
        parts.append(f"{estado} {codigo_postal}")
33
34 1
    parts.append(f"{pais}")
35 1
    return "\n".join(parts)
36
37
38 1
def format_address(k):
39 1
    return format_address_raw(
40
        calle=k["Calle"],
41
        num_exterior=k.get("NumeroExterior"),
42
        num_interior=k.get("NumeroInterior"),
43
        referencia=desc(k.get("Referencia")),
44
        colonia=desc(k.get("Colonia")),
45
        municipio=desc(k.get("Municipio")),
46
        localidad=desc(k.get("Localidad")),
47
        estado=desc(k["Estado"]),
48
        pais=desc(k["Pais"]),
49
        codigo_postal=k["CodigoPostal"]
50
    )
51
52
53 1
def desc(s):
54 1
    if isinstance(s, Code):
55 1
        return s.description
56
    return s
57