Home > Software design >  Refactor nested ifs with internal if and final else have the same statement
Refactor nested ifs with internal if and final else have the same statement

Time:11-15

I would like to refactor a code similar to this one:

import os

init_val = 1

existing_file = "test.txt"

if os.path.isfile(existing_file)
    saved_val = read_file(existing_file)

    if saved_val != init_val
        create_file()
else:
    create_file()

I want to create the file when it doesn't exist or if the content is different to the initialized value, but I don't want to repeat the create_file function twice.

Any advice?

CodePudding user response:

This would work, just set the saved_val as the init value

Then do you're check if it matches just the once.

import os

init_val = 1
saved_val = init_val
exists = False
existing_file = "test.txt"


if os.path.isfile(existing_file)
    saved_val = read_file(existing_file)
    exists = True

if saved_val != init_val or not exists:
    create_file()

  • Related