如何编写无法维护PHP代码[2009]

Originally published at http://phpadvent.org/ in 2009. The site is no more, but I found a copy on my hard drive. I'm not sure but I do hope it's the final version because Sean Coates (@coates) and Chris Shiflett (@shiflett) did a really nice job editing the pice.

最初于2009年发布在http://phpadvent.org/ 。该站点不再存在,但我在硬盘上找到了一个副本。 我不确定,但我希望它是最终版本,因为Sean Coates ( @coates )和Chris Shiflett ( @shiflett )在编辑价格方面做得非常好。

Also hope it's still funny...

也希望它仍然很有趣...

With the unemployment rates lately being at the levels that they are, everybody realizes that job security is important. And what's the best way to keep a job but to be irreplaceable, one way or another. The simple truth is that if no one can maintain the code you write, you have a job for life. Writing unmaintainable code is a special skill that, strangely enough, seem to come quite naturally to certain developers. But for the rest of you, here are some tips and hints to get you started.

鉴于最近的失业率处于这样的水平,每个人都意识到工作安全很重要。 保持一份工作却又不可替代的最好方法是一种或另一种。 一个简单的事实是,如果没有人可以维护您编写的代码,那么您就可以终生工作。 编写不可维护的代码是一项特殊技能,很奇怪,对于某些开发人员来说,这似乎是很自然的事情。 但是对于其余的人,这里有一些提示和提示可以帮助您入门。

第一件事 (First things first)

It all starts with the job posting. You should look for the right company, where you can spread your wings and achieve your unmaintainable potential. You don't necessarily need to be the PHP guru in the company but it sure helps. Look for job descriptions where they mention migrating to PHP from something else (so you know you'll be calling the shots). Or maybe search misguided jobs posts that require for example 10 years of PHP5 experience. Plus fluency in FrontPage and Netscape Composer.

这一切都始于职位发布。 您应该寻找合适的公司,在这里您可以展开翅膀并实现无法维持的潜力。 您不一定需要成为公司PHP专家,但这肯定会有所帮助。 在他们提到从其他地方迁移到PHP的地方寻找工作说明(因此,您会做主)。 或者,可能是需要10年PHP5经验的搜索错误的职位发布。 加上流利的FrontPage和Netscape Composer。

Once you land the golden opportunity, be vocal from day one. Speak up at meetings, let your opinion be heard. Talk about object-oriented design architectures, enterprise, shifting paradigms, how "good enough" is not good enough, and, of course, your personal commitment to excellence. Make sure everyone consults your opinion on the important coding initiatives.

一旦获得了千载难逢的机会,请从第一天开始发声。 在会议上大声疾呼,让您发表自己的意见。 谈论面向对象的设计架构,企业,不断变化的范例,“足够好”还不够好,当然还有您个人对卓越的承诺。 确保每个人都对重要的编码计划征询您的意见。

不可维护的Struts (The pillars of unmaintainability)

Inspired by the most excellent piece "Writing unmaintainable code" (must-read for anyone interested in keeping their job), here are the two important concepts you need to grasp and master:

受到最出色的文章“编写无法维护的代码”的启发(对保持工作有兴趣的任何人都必须阅读),这是您需要掌握和掌握的两个重要概念:

  1. You should make it impossible for someone to change something easily without breaking something else.

    您应该使某人不可能轻易更改某些内容而不破坏其他内容。

    Understand that the maintainer doesn't have time to understand your code. Maintainable code means being able to quickly locate a specific piece in the mountains of code, understand how it works right away and change it without breaking stuff. You can't have that. No one should be able to simply search for something and just find it where they expect.

    了解维护者没有时间理解您的代码。 可维护的代码意味着能够快速找到大量代码中的特定部分,了解其工作原理并立即对其进行修改而不会破坏代码。 你不能那样没有人应该能够简单地搜索某些东西,而只是在他们期望的地方找到它。

  2. Your code shouldn't look unmaintainable (because someone will suspect something), it just has to be unmaintainable.

    您的代码不应看起来不可维护(因为有人会怀疑某些东西),而只是不可维护。

    The code should look normal to the maintainers, but take them by surprise when they least expect.

    该代码对于维护人员而言应该看起来是正常的,但是在他们最不期望的时候会感到惊讶。

最佳实践 (Best practices)

  1. Ban coding conventions. Endless flamewars have been fought over coding and naming conventions. You can't have that in your fine organization. You have awesome projects to build and you can't afford to spend countless hours in discussion of tabs vs. spaces. Plus, conventions are restrictive. If a new hire comes and is not used to your conventions, they'll be miserable. Unhappy programmer is unproductive programmer. Explain that to anyone who asks. Let everybody write in their favorite style-du-jour. As for your own code - rotate your conventions. Go camelCase on Monday, all_lowercase on Tuesday, mix-and-match Friday and Hungarian on every February 29th.

    禁止编码约定。 在编码和命名约定方面进行了无休止的斗争。 您不能在优秀的组织中拥有这种能力。 您要构建的项目很棒,而且您无法花无数小时来讨论制表符和空格。 另外,约定是限制性的。 如果新来的员工不习惯您的惯例,他们将很痛苦。 不快乐的程序员是没有生产力的程序员。 向任何要求的人解释。 让每个人都按自己喜欢的风格写文章。 至于您自己的代码-旋转约定。 星期一进入camelCase all_lowercase ,星期二进入all_lowercase ,星期五进入混合搭配比赛,每年2月29日进入匈牙利比赛。

  2. No comments. Your code is beautiful, it doesn't need comments. If someone can't understand it, well maybe they are not so good programmers after all. If, by any chance, you're forced to write comments, then simply overdo it. Elaborately describe the most obvious and trivial code, skip the rest.

    没意见。 您的代码很漂亮,不需要注释。 如果有人听不懂,也许他们毕竟不是那么好的程序员。 如果碰巧您被迫发表评论,那就简单地改掉它。 精心描述最明显和最简单的代码,跳过其余部分。

        // in the following block
        // we add two variables:
        // named variable a and variable b
        // both of them integers
        
        // declare variable a
        // and assign integer 1 to it 
        $a = 1;
        // declare variable b
        $b = 2;
        // sum the two variables a and b
        // declared and initialized above
        // and assign the result to 
        // a new variable c
        $c = $a + $b;
        
    
  3. Standardize on Notepad. Or any other editor without source highlighting. Let the others suffer and eventually leave the team. You don't need to listen to them complaining all the time. And if someone asks why Notepad, be ready to explain: it comes with Windows (the only OS for today's productive programmer), no training is necessary, it doesn't cost anything. I'm sure you'll find references on the web how you can use any program, including Word, to write code for web pages, but Notepad is for real gurus. And, after all, your company hires no one but the gurus.

    在记事本上标准化。 或任何其他未突出显示源代码的编辑器。 让其他人受苦并最终离开团队。 您无需一直听他们抱怨。 而且,如果有人问为什么记事本,请随时说明:Windows附带了Windows(当今高效程序员使用的唯一操作系统),无需培训,也不需要花任何钱。 我相信您会在网上找到参考资料,介绍如何使用任何程序(包括Word)编写网页代码,但记事本是真正的专家。 而且,毕竟,您的公司只雇用专家,而不雇用任何人。

  4. No unit testing. Explain to anyone who asks that you are hired to write high-quality code that doesn't have bugs (ergo, needs no testing). Why would anyone in their right mind spend any time writing useless tests that confirm the obvious - that the code works? Some things in life just are - the sky is blue, the sun rises from the East and your code works, thank you very much. Move on. (Like with comments, if forced to do tests, be prepared to overtest the obvious and skip the rest)

    没有单元测试。 向任何要求您被雇用编写没有错误的高质量代码的人解释(错误,不需要测试)。 为什么任何有主见的人都花时间编写无用的测试来确认显而易见的代码(代码有效)? 生活中有些事情-天空是蓝色的,太阳从东方升起,您的代码有效,非常感谢。 继续。 (与评论一样,如果被迫进行测试,请准备对显而易见的内容进行过度测试,并跳过其余部分)

  5. No templating engine. Templating engines help separate business logic from presentation. It may make the code maintainable and you cannot allow that. Quote Rasmus Lerdorf: "PHP is a templating engine". Even if you're forced to use a templating engine, find a way to misuse it and put little pieces of business logic in the template, as well as carefully crafted mix of HTML (and CSS and JavaScript) into the database access layer for example.

    没有模板引擎。 模板引擎有助于将业务逻辑与表示分离。 它可能使代码可维护,您不能这样做。 引用Rasmus Lerdorf:“ PHP一个模板引擎”。 即使您被迫使用模板引擎,也要找到一种方法来滥用它,并将少量业务逻辑放入模板中,以及将精心制作HTML(以及CSS和JavaScript)混合到例如数据库访问层中。

    In general, strive for a healthy mix of PHP, HTML, CSS and JavaScript, possibly on the same line of code. Write PHP that creates JavaScript that creates HTML with inline styles. If asked, call this pattern "encapsulation" - your code is just fully responsible for itself.

    通常,尽可能在同一行代码中争取健康地组合PHP,HTML,CSS和JavaScript。 编写可创建JavaScriptPHP,该JavaScript可创建具有内联样式HTML。 如果要求,请将该模式称为“封装”-您的代码仅对自身负责。

  6. Version control. It's hard to avoid it, but it's worth to try talking yourself out of any form or shape of version control. Demonstrate how it improves communication between team members if you talk about stuff, instead of relying on cold-blooded version control software to resolve conflicts. When you fail convincing anybody, do not despair. You don't have to commit it all to source control. Keep some code to yourself. Small but deadly pieces, which will break the project if someone other than you tries to build and deploy. If caught, explain how this code was not yet fit-to-print, after all, you only commit code that can educate junior team members on exceptional quality and clever solutions. These boys and girls look up to you and expect nothing but the best!

    版本控制。 很难避免,但是值得尝试摆脱任何形式或形式的版本控制。 演示有关内容时如何改善团队成员之间的沟通,而不是依靠冷血的版本控制软件来解决冲突。 当您无法说服任何人时,请不要绝望。 您不必将所有内容都提交给源代码管理。 给自己保留一些代码。 微小但致命的片段,如果您以外的其他人尝试构建和部署,则会破坏项目。 如果发现了问题,请说明该代码尚不适合印刷,毕竟,您只提交可以对初级团队成员进行卓越质量和巧妙解决方案教育的代码。 这些男孩和女孩仰望你,期望最好的!

  7. Build a framework. Then you inevitably become The Architect and your authority is unquestionable. Plus it lets you add secret conventions (and lots of them, sometimes contradicting ones) that will trip even the most experienced maintainer. Your framework will take care of everything, no one should bother understanding it, they should be happy you're single-handedly making development easier and more productive for the whole company. Never release the framework as open-source because a) the framework is an asset to the company and the company have invested heavily, and b) the open-source community will poke fun at you and that will be the end of your bluff.

    建立一个框架。 然后,您不可避免地成为建筑师,而您的权威无疑。 此外,它还允许您添加秘密约定(很多约定,有时甚至是相互矛盾的约定),即使是最有经验的维护人员也可以使用。 您的框架将处理所有问题,没有人会费心去理解它,他们应该为您的一臂之力使整个公司的开发变得更加容易和高效而感到高兴。 永远不要将框架发布为开源的,因为a)框架是公司的资产,并且公司已投入大量资金,并且b)开源社区会取笑您,这将是您虚张声势的终结。

命名的东西 (Naming stuff)

Your variables should be named mysteriously, often with one letter only. The goal is to make it impossible for anyone to find anything with a simple search.

您的变量应该被神秘地命名,通常只有一个字母。 目的是使任何人都无法通过简单的搜索找到任何东西。

Class names and functions could be one character names too. When you do actually decide to use a normal name for a change, use it all the time - remember sometimes the best way to hide information is to have too much of it. When reusing the same name (call it "subject matter-oriented programming"), it also helps if you place parentheses and curly braces on new lines - to claim you improve readability and also to make your teammates brush up on their regexp if they want to find anything in your code. Consider this:

类名和函数也可以是一个字符名。 当您确实决定使用常规名称进行更改时,请始终使用它-请记住,有时隐藏信息的最佳方法是存储太多信息。 当重用相同的名称(称为“面向主题的程序设计”)时,如果在新行上放置括号和花括号也很有帮助-声称可以提高可读性,还可以使队友在需要时重新使用正则表达式在您的代码中找到任何东西。 考虑一下:

    $noodles = 1;
    class 
    noodles
    {
        var $noodles = 2;
        function 
            noodles
            ()
        {
            $noodles['noodles'] = 'noodles';
        }
    }
    function 
        noodles() {
            return new noodles;
        }
    $noodles = noodles();
    var_dump($noodles);

You can also use strange charsets when naming variable. Cyrillic letters are quite appropriate, because some letters look just like the roman letters, but they aren't (all of these: xopekacMEBCTAKXOPH). So what will the following echo:

命名变量时,您也可以使用奇怪的字符集。 西里尔字母非常合适,因为有些字母看起来像罗马字母,但并非全部(所有这些:xopekacMEBCTAKXOPH)。 那么以下内容会产生什么回响:

    $alert = 1;
    $аlert = 2;
    echo $alert;

2? Not if the second alert starts with a Cyrillic "a"!

2? 如果第二个alert以西里尔字母“ a”开头,则不会!

引用东西 (Referencing stuff)

Even if you define something normally, doesn't mean you cannot use it in interesting ways. The weapons to master include:

即使您正常定义某些内容,也不意味着您不能以有趣的方式使用它。 掌握的武器包括:

  • eval()

    eval()

  • variable variables

    可变变量
  • variable class names, e.g. $strudels = "noodles"; $noo = new $strudels;

    可变的类名,例如$strudels = "noodles"; $noo = new $strudels; $strudels = "noodles"; $noo = new $strudels;

  • call_user_func()

    call_user_func()

Basically any language construct that allows you to treat code as strings is your friend.

基本上,任何允许您将代码视为字符串的语言构造都是您的朋友。

    // calling abc();
    $z = 'A';
    call_user_func($z .'bC');

大写(Capitalization)

Master letter cases. Function names are case insensitive. Abuse this.

掌握信件的情况。 函数名称不区分大小写。 虐待这个。

function abc(){
    echo "abc";
}
AbC();

On the other hand array keys are sensitive. Abuse this as well.

另一方面,数组键是敏感的。 也要滥用这个。

$a['UseConvetionsOnlyTobreakThem'] = 1;
if (isset($a['UseConvetionsOnlyToBreakThem'])) {
    // ?? capital B !!1!
}

覆写(Overwrite)

Overwrite globals where least expected. Especially superglobals. Overwrite elements in the $_GET array early, overwrite them often. Same for $_POST. Sprinkle that with some quiet $_REQUEST overwrites. If WTF-ed, explain you're sanitizing user input to prevent XSS, injections, infections, and other diseases.

覆盖最不期望的全局变量。 尤其是超全局变量。 尽早覆盖$_GET数组中的元素,经常覆盖它们。 与$_POST相同。 撒上一些安静的$_REQUEST覆盖。 如果是WTF版本,请说明您正在清除用户输入内容,以防止XSS,注射,感染和其他疾病。

控制结构 (Control structures)

Use, mix and match all the alternative if, while, for, foreach, switch syntax. If asked why, explain that you're training the new hires to really learn the language, all of it.

使用,混合和匹配ifwhileforforeachswitch语法的所有替代项。 如果被问到原因,请说明您正在培训新员工,以真正学习该语言。

if ($a > 5):
  if ($a > 4) {
      while ($a > 0):
        echo --$a;
      endwhile;
  }
endif;

Nest ternary operators, nothing like nice concise code:

嵌套三元运算符,不像简洁的代码:

// guess the output
echo true ? 'true' : false ? 't' : 'f';

Inside of the body of for loops, increment the $i once again to keep everybody alert. Alternatively, surprise folks by not using $i for loop increment. Never.

for循环的主体内for再次增加$i以使所有人保持警觉。 另外,不要用$i来增加循环次数,这会给人们带来惊喜。 决不。

Nest loops. Deeply. Then suddenly break out of them. Statements like break 2 and break 3 are a pure joy to figure out, especially when mixed with strangely indented code.

嵌套循环。 深。 然后突然爆发出来。 像break 2break 3这样的语句很容易找出来,特别是当它与缩进的代码混合在一起时。

那是一个开始! (That's a start!)

And that's all for today. I hope by now you're convinced that you can do it, you too can write unmaintainable code. Now your future is in your hands! Can you take the chance of being replaceable by writing predictable code?

今天就这些。 我希望现在您已经确信可以做到,也可以编写无法维护的代码。 现在,您的未来就在您手中! 您可以通过编写可预测的代码来抓住机会被替换吗?

Tell your friends about this post on Facebook and Twitter

FacebookTwitter上告诉您的朋友有关此帖子的信息

翻译自: https://www.phpied.com/how-to-write-unmaintainable-php-code-2009/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值