提问人:Don Cheadle 提问时间:11/17/2023 最后编辑:Don Cheadle 更新时间:11/17/2023 访问量:29
何时应重构以避免全局变量?[关闭]
When should you refactor to avoid global variables? [closed]
问:
据我了解,在简单程序中有选择地使用全局变量是可以的——但作为初学者,我不知道究竟什么是“选择性”或“简单”。
我的 Notepad++ 脚本遍历每个打开的文件,检查可用于打开其相关文件的正则表达式模式。然后检查此打开的文件是否存在正则表达式模式,这些模式可用于相应地调整原始文件,从而允许用户在需要时手动识别文件。它在 2-3 个函数中使用 5 个全局变量。
是否应该重构代码以避免这种情况?如果是这样,最好的方法是什么?
# encoding=utf-8
import os
import re
from Npp import *
history_files = 'C:/Program Files (x86)/Steam/steamapps/common/Europa Universalis IV/history/countries'
options = '1 - Eastern European\n2 - Anatolian\n3 - Muslim\n4 - Indian\n' + (
'5 - East African\n6 - Central African\n7 - Chinese\n8 - Nomad\n' +
'9 - West African\n10 - North American\n11 - Mesoamerican\n' +
'12 - South American\n13 - Andean\n14 - Aboriginal\n15 - Polynesian\n')
maluses = {
'eastern': (20, 1),
'ottoman': (25, 2),
'muslim': (37.5, 3),
'indian': (40, 4),
'east_african': (45, 5),
'central_african': (55, 6),
'chinese': (50, 7),
'nomad_group': (62.5, 8),
'sub_saharan': (50, 9),
'mesoamerican': (75, 11),
'andean': (75, 13),
'north_american': (92.5, 10),
'south_american': (92.5, 12),
'aboriginal_tech': (92.5, 14),
'polynesian_tech': (92.5, 15),
}
def message(text, style):
current_file = re.compile(r'[^\\]*\.txt').search(filename).group(0)
console.editor.setReadOnly(False)
console.editor.addStyledText(Cell('\n"' + current_file + '" ' + text, [style]))
def replace(percentage):
percentage_as_factor = float((100 - float(percentage)) * 0.01)
base_tech = 3
editor.rereplace(r'(?<=adm_tech = )(\d+)|(?<=dip_tech = )(\d+)|(?<=mil_tech = )(\d+)', (
str(int(round(base_tech * ((((float(value.group(0)) / base_tech) - 1) * percentage_as_factor) + 1))))));
notepad.save()
def adjust(tag):
if tag in ('mission_tag', 'decision_tag'):
message(tag + ' matched to "' + matched_file + '"', 0)
notepad.open(history_files + '\\' + matched_file)
tech = (re.search(r'(?<=technology_group = )(\w+)', editor.getText())).group(0)
notepad.close()
elif tag == 'manual':
raw_tech = str([key for key, dict_value in maluses.items() if int(prompt) in dict_value])
tech = re.search(r"[^[\]']+", raw_tech).group(0)
message('manually matched to "' + tech + '"', 0)
else:
raise Exception()
if tech in maluses:
replace(maluses[tech][0])
message('- "' + tech + '" matched to key in dictionary - value adjusted\n', 0)
elif tech == 'western':
message('is "western"\n', 5)
else:
message('"' + tech + '" not found in dictionary', 1)
return
def adjust_tech_patterns():
editor.beginUndoAction()
global filename
for (filename, bufferID, index, view) in notepad.getFiles():
notepad.activateBufferID(bufferID)
global value
value = re.search(r'(?<=adm_tech = )(\d+)|(?<=dip_tech = )(\d+)|(?<=mil_tech = )(\d+)', editor.getText())
if not value:
message('exited the loop because of "no value"\n', 5)
continue
mission_tag = re.search(r'\s*potential = \{[\s\S]*?(?<=tag = )((?!ROOT)\w+)', editor.getText())
decision_tag = re.search(r'(?<=NOT = { exists = )((?!ROOT)\w+)', editor.getText())
if mission_tag:
mission_tag_compiled = (re.compile(mission_tag.group(1)))
global matched_file
(matched_file,) = filter(mission_tag_compiled.match, os.listdir(history_files))
adjust('mission_tag')
continue
elif decision_tag:
decision_tag_compiled = (re.compile(decision_tag.group(1)))
global matched_file
(matched_file,) = filter(decision_tag_compiled.match, os.listdir(history_files))
adjust('decision_tag')
continue
else:
message('has no identifiers', 4)
notepad.new()
editor.addText(options)
editor.setSavePoint()
current_file = re.compile(r'[^\\]*\.txt').search(filename).group(0)
global prompt
prompt = notepad.prompt('What tech group is "' + current_file[:-4] + '"?', '','')
notepad.close()
if prompt in (None, ''):
continue
adjust('manual')
editor.endUndoAction()
adjust_tech_patterns()
答: 暂无答案
评论