Anti-for-if programming mode

Source: Internet
Author: User

Over the years, I have seen a lot of anti-programming models. I feel I should share some with you.

Today, I want to introduce the anti-pattern I call the anti-for-if programming mode. "If you are interested, check this article: Why is a for loop hateful ?」, That is what people call "we sell you the entire seat, but all you need is one side ."

This is a special anti-case mode, in which only one of all cases will be null.

  1. For (INT I = 0; I <100; I ++ ){
  2. If (I = 42) {do_something (I );}
  3. }

In this case, you can simply write

  1. Do_something (42 );

This reverse-If mode can be represented in various forms. For example:

  1. Foreach (string filename in directory. getfiles ("."))
  2. {
  3. If (filename. Equals ("desktop. ini", stringcomparison. ordinalignorecase ))
  4. {
  5. Return new streamreader (filename );
  6. }
  7. }

It is used to traverse a specified file in a directory. If a specified file is found, the data stream of the file is returned. One way to write this code is

  1. If (file. exists ("desktop. ini "))
  2. {
  3. Return new streamreader ("desktop. ini ");
  4. }

Note that the code snippets of the two versions have the same competition condition: If this desktop. INI already exists, but it is deleted before you create streamreader, and you will get a filenotfoundexception error.

Another example:

  1. Foreach (Object o in hashtable. Keys)
  2. {
  3. If (O = "target") return hashtable ["target"];
  4. }

Equivalent

  1. Return hashtable ["target"];

I guess these guys don't like to find a book by name in the library, because their approach is so tedious:

They came to the library and said, "Give me all your books." Then they sat down in the corner and said to themselves, carrying baskets full of thousands of books:

"No, the title of this book is incorrect ",

"No, this is not ",

"The title is still incorrect ."

"What about this book ?"

"No, neither. "

"My God, when will I need such a copy... "

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.