【发布时间】:2019-11-02 11:44:43
【问题描述】:
我有一些代码需要在 Windows 和 Linux 上执行非常相似的操作。不幸的是,我需要几个特定于系统的功能(例如隐藏文件:Python cross platform hidden file)。编写代码以提高可读性和可维护性的最佳方式是什么?
当前代码使用许多if 语句在不同平台上表现不同。我考虑的另一种方法是将代码拆分为两个单独的函数,一个用于 Windows,一个用于 Linux,但这意味着在两个地方更新代码的主要部分。
请注意,代码的主要部分比这要长得多且复杂得多。
组合方法(最大的可维护性,但有很多 if 语句):
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()
单独的方法(需要更多的维护,但需要更少的if 语句):
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()
do_preparations() 和 do_tidying_up() 函数涉及复制文件、提取等。
is_correct_file() 检查文件是否具有正确的名称和正确的时间戳。
do_main_actions() 涉及分析、移动和隐藏文件。
以上示例都有效,但似乎不是最符合 Python 风格或实现代码长期可维护性的最佳方法。
【问题讨论】:
-
我给出了一个我认为应该对你有帮助的答案
-
感谢您的回复!很多代码都依赖于操作系统,例如隐藏文件的能力 (stackoverflow.com/questions/25432139/…)。该代码在两个系统上都运行良好,但它很长并且许多
if语句降低了可读性。