My program is working properly but I'm unconfortable with code repetition.
class Movimentacao(models.Model):
data = models.DateField() # complete datetime field from 2019->2022
movimentacao = models.CharField(max_length=200) # text field
valor_da_operacao = models.DecimalField(max_digits=19, decimal_places=2) # decimal field
# get all objects filtered by `movimentacao` field
proventos = Movimentacao.objects.filter(movimentacao__in=('Dividendo', 'Juros Sobre Capital Próprio', 'Rendimento', 'Reembolso')).order_by('data', 'id')
currentDate = proventos[0].data # get date from the first record
lastRecord = proventos.last().id # get ID from the last record
assets = []
stockSum = 0
fiiSum = 0
for m in proventos:
if(m.data.month != currentDate.month or lastRecord == m.id):
dataFormatada = f'{currentDate.strftime("%y")}-{currentDate.strftime("%b")}'
if(lastRecord == m.id):
# first if-else block (necessary but I'd like to 'remove')
if(m.movimentacao == 'Dividendo'):
stockSum += m.valor_da_operacao
if(m.movimentacao == 'Rendimento'):
fiiSum += m.valor_da_operacao
assets.append([dataFormatada, 'FIIs', fiiSum])
assets.append([dataFormatada, 'Stocks', stockSum])
stockSum = 0
fiiSum = 0
currentDate = m.data
# second if-else block (this one I can't remove)
if(m.movimentacao == 'Dividendo'):
stockSum += m.valor_da_operacao
if(m.movimentacao == 'Rendimento'):
fiiSum += m.valor_da_operacao
As you can see, the code below is being repeteaded:
if(m.movimentacao == 'Dividendo'):
stockSum += m.valor_da_operacao
if(m.movimentacao == 'Rendimento'):
fiiSum += m.valor_da_operacao
The goal of this code is to build the assets
list formatted accordingly below:
[
["19-Nov", "FII", 411.97], ["19-Nov", "Stocks", 0],
["19-Dec", "FII", 368.21], ["19-Dec", "Stocks", 1542.08],
["20-Jan", "FII", 0], ["20-Jan", "Stocks", 401.06],
]
In this way, I'd like to see if it's possible to "remove" the first if-else statement, keeping the code working properly (this would be my first choice).
The issue is: if I remove the first if-else statement, the variable m.movimentacao
from the last object is not added inside stockSum
or fiiSum
variables - that was the reason I need to insert the first if-else statement. The last object can't reach the last if-else statement to be checked either m.movimentacao
is a 'Dividendo' or 'Rendimento'.
If not, what is the best way to avoid code repetition in this case (function use)?
stockSum
orfiiSum
twice when processing a record that whose ID is equal tolastRecord
- once before writing toassets
and once after. Is that the correct behaviour? \$\endgroup\$assets
as the result? Wouldn't you also want to do another twoassets.append(…)
statements at the end? \$\endgroup\$