2017-10-16 39 views
0

私がもし/ else文に2つのまったく同じロジックがあります。if/else文で重複したコードを避ける方法は?

if alert.get('comment_time_created') is None: 
here-> args = {'is_comment_visible': 1, 'comment_time_created': current_comment_time} 
     await self._db_alert.update_alert(alert['alert_id'], **args) 
    else: 
     first_comment_time_creation = datetime.strptime(alert['comment_time_created'], '%Y-%m-%dT%H:%M:%SZ') 
     current_comment_time = datetime.strptime(current_comment_time, '%Y-%m-%dT%H:%M:%SZ') 
     if current_comment_time > first_comment_time_creation: 
      await self._db_alert.update_alert(alert['alert_id'], is_comment_visible=1) 
     else: 
here->  args = {'is_comment_visible': 1, 'comment_time_created': current_comment_time} 
      await self._db_alert.update_alert(alert['alert_id'], **args) 

は、かつてこのロジックを実行する方法はありますか?

+0

上記の変数に上記の辞書を保存することはできませんか? – Carcigenicate

+0

これはhttp://codereview.stackexchange.com/にもっと適しているかもしれません。 – kfx

+0

@Carcigenicate説明する方法を教えてください。 –

答えて

2

あなたはすべての条件で待っているようです。ちょうどあなたのkwargsはあなたが特定の条件のためにcomment_time_created argを持っていない場所を変更しています。これは以下のように減らすことができます:

args = {'is_comment_visible': 1} 
if alert.get('comment_time_created') is None: 
    args['comment_time_created'] = current_comment_time 
else: 
    first_comment_time_creation = datetime.strptime(alert['comment_time_created'], '%Y-%m-%dT%H:%M:%SZ') 
    current_comment_time = datetime.strptime(current_comment_time, '%Y-%m-%dT%H:%M:%SZ') 
    if current_comment_time <= first_comment_time_creation: 
     args['comment_time_created']= current_comment_time 

await self._db_alert.update_alert(alert['alert_id'], **args) 
1

外側のifの終わりの後にのみメソッドを呼び出します。すべてのブランチに共通する式をリッピングしてブロックを簡略化します。 このようなもの:

if alert.get('comment_time_created') is not None:  
    first_comment_time_creation = datetime.strptime(alert['comment_time_created'], '%Y-%m-%dT%H:%M:%SZ') 
    current_comment_time = datetime.strptime(current_comment_time, '%Y-%m-%dT%H:%M:%SZ') 
    if current_comment_time <= first_comment_time_creation: 
     comment_time_created = current_comment_time 

await self._db_alert.update_alert(alert['alert_id'], is_comment_visible = 1, comment_time_created = comment_time_created) 
+1

が間違っている。彼は最初のcondtionの前に定義された 'current_comment_time'を持っているようですが、argsの彼の最初の初期化を確認します – MohitC

+0

よく目撃されました。最初の宣言を削除するだけです。 – Daniel

+1

ローカル変数 'comment_time_created'が割り当て前に参照される可能性があります。 –

関連する問題