I have some code which needs to do very similar things on both Windows and Linux. Unfortunately I require several system-specific functions (e.g. hidden files: Python cross platform hidden file). What is the best way of writing the code for readability and maintainability?
Currently the code uses many if
statements to behave differently on the different platforms. Another approach I have considered is to split the code into two separate functions, one for Windows and one for Linux, but this would mean updating the main part of the code in two places.
Note that the main part of the code is considerably longer and more complicated than this.
Combined approach (greatest maintainability but lots of if
statements):
import os
def sort_out_files():
if is_linux:
do_linux_preparations()
else:
do_windows_preparations()
# Main part of the code:
for file in os.listdir(folder):
if is_correct_file(file):
if is_linux:
do_main_actions_for_linux()
else:
do_main_actions_for_windows()
if is_linux:
do_linux_tidying_up()
else:
do_windows_tidying_up()
Separate approach (more maintenance needed but fewer if
statements required):
import os
def sort_out_files_linux():
do_linux_preparations()
# Main part of the code:
for file in os.listdir(folder):
if is_correct_file(file):
do_main_actions_for_linux()
do_linux_tidying_up()
def sort_out_files_windows():
do_windows_preparations()
# Main part of the code:
for file in os.listdir(folder):
if is_correct_file(file):
do_main_actions_for_windows()
do_windows_tidying_up()
def sort_out_files():
if is_linux:
sort_out_files_linux():
else:
sort_out_files_windows()
The do_preparations()
and do_tidying_up()
functions involves copying files, extracting, etc.
is_correct_file()
checks that the file has the right name and the right timestamp.
do_main_actions()
involves analysing, moving and hiding files.
The examples above both work but don't seem like the most Pythonic or best approach to long-term code maintainability.