C # code obfuscation

A few years ago, they were a competition to see who could create the most confusing C code, and some of the results were incredibly unreadable. C was like that. You really can damage the preprocessor in particular.

However, many of C #’s new features offer a tremendous opportunity to obfuscate code. I was wondering if anyone had an opinion on finding the right balance between a clear and precise wording of the code. Let me offer one example for discussion - the task of populating items in a ListView. (Yes, I know that you can do this with data binding, but come with me here.)

A control is two columns that must be filled with an array of struct Person {public row name; open string address; };

One clear and easy way:

private void Fill(Person[] people)
{
    foreach(Person person in people)
    {
        string[] columns = new string[2];
        columns[0] = person.name;
        columns[1] = person.address;            
        ListViewItem item = new ListViewItem(columns);
        listView1.items.Add(item);
    }
}

.

:

private void Fill(Person[] people)
{
    foreach(Person person in people)
    {
        string[] columns = new string[] { person.name, person.address };
        ListViewItem item = new ListViewItem(columns);
        listView1.items.Add(item);
    }
}

:

private void Fill(Person[] people)
{
    foreach(var person in people) // Note use implicit typing here
    {
        listView1.items.Add(new ListViewItem(
        new string[] { person.name, person.address }));
    }
}

, :

private void Fill(Person[] people)
{
    Array.ForEach(people, item =>
    listView1.items.Add(new ListViewItem(
    new string[] { person.name, person.address}));
}

. ? Obfuscated #?

+5
6

, ? , . , .

: .

Edit:

" , . , ".

     
  •   
  • , :   

roygbiv . ; , , , .

+24

"" - . , #, , , , .

+6

, , :

  • , . , . , - .

  • , , , , . , . , , , , , , .

, 1 - . 4 . , 2 3 , 3 , , :

private void Fill(Person[] people)
{
    foreach(var person in people)
    {
        listView1.items.Add(
            new ListViewItem(
                new string[] { person.name, person.address }
            )
         );
    }
}

: .

: , , .. var, . , - , , .

+2

, , , , Obfuscation , . , , . , , , C .

, # - "". C - A) / B) , .

, , , # , C, , , , , - .

+1

# VB.NET , , C. C. . - #, C.

" , . , ".

     
  •   
  • , :   
+1

.

Firstly, the intention is so painfully clear that a novice is more likely to find out what lambda is doing than not to understand the code. This is an ideal place to use more “advanced” techniques - where even someone who does not know what they are doing understands what they are “supposed to” do.

Secondly, all of the above is not only not confused, they are perfectly idiomatic C #. The latter, perhaps, is not so much due to the fact that Array.ForEach is not widely used, with which most people (with whom I worked) used LINQ.

0
source

All Articles