我有一些代码需要在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()
涉及分析、移动和隐藏文件。你知道吗
以上两个例子都很管用,但似乎并不是实现长期代码可维护性的最佳方法。你知道吗
为了使您的代码更易于维护,我建议您查看adapter design pattern。你知道吗
例如:您可以创建适配器类,而不是每次需要运行操作系统特定的函数时都调用if语句。在运行时,您将使用适当的特定于操作系统的实现创建适配器,并在需要时引用它。你知道吗
适配器设计示例:
我会把所有只适用于一个操作系统的东西放在一个文件中,但名称相同。然后可以在主文件的开头添加如下内容:
如果这两个文件具有相同的接口(例如顶级方法),则它们可以互换使用。你知道吗
在您的示例中,
linux_tools
和windows_tools
都将包含它们各自的sort_out_files
实现,但都命名为sort_out_files
,因此您可以将其与tools.sort_out_files
一起使用。你知道吗请记住,要尽可能避免这些模块中的常见代码。你知道吗
为了避免代码中的重复条件,可以在专用子模块(每个平台一个子模块)中定义所有特定于平台的函数,然后有条件地导入与主机匹配的函数
主文件
显然,您需要让两个子模块实现相同的函数(使用相同的名称)。 这是一种多态性,如果你想把所有的代码放在同一个文件中,你可以用类得到相同的结果。你知道吗
相关问题 更多 >
编程相关推荐