<h2>重构</h2>
<p>首先,我不会重复调用<code>props.getProperty("app.auth.idp.strategy")</code>。打一次电话,你马上就没有理由分线了。你知道吗</p>
<pre><code>strategy = props.getProperty("app.auth.idp.strategy")
if not strategy or strategy == 'saml/simpleSAMLphp' and PROXYING_MECHANISM == "ngrok":
IDP_STRATEGY = "saml/simpleSAMLphp"
elif strategy == 'saml/gsuite':
IDP_STRATEGY = "saml/gsuite"
elif strategy == 'saml/remote-simpleSAMLphp':
IDP_STRATEGY = "saml/remote-simpleSAMLphp"
else:
IDP_STRATEGY = "saml"
</code></pre>
<hr/>
<h2>行延拓</h2>
<p>对于第一个长行,您的选项是行继续,可以是显式的:</p>
<pre><code>if not strategy or \
strategy == 'saml/simpleSAMLphp' and \
PROXYING_MECHANISM == "ngrok":
</code></pre>
<p>或隐式括号内:</p>
<pre><code>if (not strategy or
strategy == 'saml/simpleSAMLphp' and
PROXYING_MECHANISM == "ngrok"):
</code></pre>
<hr/>
<h2>使用查找,而不是重复比较</h2>
<p>一个更好的选择是用<code>dict</code>查找替换一个长字符串:</p>
<pre><code>strategies = {
"saml/gsuite": "saml/gsuite",
"saml/remote-simpleSAMLphp": "saml/remote-simpleSAMLphp",
}
if PROXYING_MECHANISM == "ngrok":
strategies['saml/simpleSAMLphp'] = 'saml/simpleSAMLphp'
IDP_STRATEGY = strategies.get(props.getProperty("app.auth.idp.strategy"), "saml")
</code></pre>
<p>因为<code>dict</code>的每个键都映射到它自己,所以可以用一个简单的<code>set</code>查找来替换<em>。你知道吗</p>
<pre><code>strategies = {
"saml/gsuite",
"saml/remote-simpleSAMLphp",
}
if PROXYING_MECHANISM == "ngrok":
strategies.add('saml/simpleSAMLphp')
IDP_STRATEGY = "saml"
strategy = props.getProperty("app.auth.idp.strategy")
if strategy in strategies:
IDP_STRATEGY = strategy
</code></pre>
<p>从最后两个选项中选出你认为更具可读性的。<code>dict</code>在其定义中更为冗余,但允许对<code>IDP_STRATEGY</code>进行单个赋值。你知道吗</p>