格式化if语句以提高可读性 [英] Formatting an if statement for readability

查看:112
本文介绍了格式化if语句以提高可读性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  if(strpos($ file,'.jpg',1 )&& file_exists($ thumbsdir / $ file)== false || strpos($ file,'.gif',1)&& file_exists($ thumbsdir / $ file)== false | | strpos($ file,'.png',1)&& file_exists($ thumbsdir / $ file)== false){
createThumb($ gallerydir / $ file,$ thumbsdir / $文件,$ thumbsize);
fwrite($ log,date(Y-m-d)。@.date(H:i:s)。CREATED:$ thumbsdir / $ file \\\
);


解决方案

是一个图像的逻辑到自己的功能,这使得如果更具可读性,也允许您集中逻辑。

 函数is_image($ filename){
$ image_extensions = array('png','gif','jpg');
$ b foreach($ image_extensions as $ extension)
if(strrpos($ filename,。$ extension)!== FALSE)
return true;

返回false;


if(is_image($ file)&!file_exists($ thumbsdir / $ file)){
createThumb($ gallerydir / $ file ,$ thumbsdir / $ file,$ thumbsize);
fwrite($ log,date(Y-m-d)。@.date(H:i:s)。CREATED:$ thumbsdir / $ file \\\
);
}


What's the best way to format this for readability?

if (strpos($file, '.jpg',1) && file_exists("$thumbsdir/$file") == false || strpos($file, '.gif',1) && file_exists("$thumbsdir/$file") == false || strpos($file, '.png',1) && file_exists("$thumbsdir/$file") == false) {
  createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize);
  fwrite($log,date("Y-m-d")." @ ".date("H:i:s")."  CREATED: $thumbsdir/$file\n");
}

解决方案

I'd extract the "is an image" logic into its own function, which makes the if more readable and also allows you to centralize the logic.

function is_image($filename) {
    $image_extensions = array('png', 'gif', 'jpg');

    foreach ($image_extensions as $extension) 
        if (strrpos($filename, ".$extension") !== FALSE)
            return true;

    return false;
}

if (is_image($file) && !file_exists("$thumbsdir/$file")) {
    createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize);
    fwrite($log,date("Y-m-d")." @ ".date("H:i:s")."  CREATED: $thumbsdir/$file\n");
}

这篇关于格式化if语句以提高可读性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆