问:
Is this XOR value swap algorithm still in use or useful
When I first started working a mainframe assembler programmer showed me how they swap to values without using the traditional algorithm of:

```<code>a = 0xBABE
b = 0xFADE

temp = a
a = b
b = temp
</code>```

What they used to swap two values - from a bit to a large buffer - was:

```<code>a = 0xBABE
b = 0xFADE

a = a XOR b
b = b XOR a
a = a XOR b
</code>```

now

```<code>b == 0xBABE
a == 0xFADE
</code>```

which swapped the contents of 2 objects without the need for a third temp holding space.

My question is: Is this XOR swap algorithm still in use and where is it still applicable.

答:
My colleague reported that this is a base trick he has taught in university studying for a programmer of automated systems. Many such systems are embedded ones with limited resources and they could lack a free register to keep the temporary value; in that case, such tricky exchange (or its analog with adding and subtracting) is getting vital so still being used.

But one shall care using it that these two locations can't be identical because in the latter case it will effectively zero both values. So usually it's being limited to obvious cases like exchanging a register and a memory location.

With x86, the xchg and cmpxchg instructions satisfy the need in most cases, but RISCs generally aren't covered with them (except Sparc).


问:
Should I create a "placeholder" parent case, or set up Areas?
I'm using FogBugz for Project Management, and I'm unsure how to structure my cases.

I have different features which require implementing as part of this project.

For example, if I have a new feature to include autocomplete on a search text box, this would have cases such as:

Method for returning search terms

Front-end changes to request method

Front-end changes to display search terms

Should I create these as subcases under a "Autocomplete" case, or should they be created as top-level cases under an area called "Autocomplete"?

答:
This is an appropriate place to use a parent case and sub-cases.

The reason areas are not a good fit for this is that they are permanent, whereas a given new feature is, if not exactly ephemeral, of limited scope. Once the feature is complete, you can close all related cases and forget about it, but if you associate them using an area, you have to keep the area around forever to maintain the association, and I can't see this as being much use (since you don't gain anything by it).

ContentLicense: CC BY-SA 3.0


答:
I guess ultimately it is down to user preference as to how you choose to use Areas, however I would strongly suggest that in this instance you should create a parent case, NOT an area.

The reason for this is that you do not want to clutter your areas list with each feature, if you create one for each "large" case (that requires sub-cases) then you would end up with a lot of unmanageable areas, and you don't have all the features with an area that you get the a case - such as being able to close an area, for whatever reason.

In my opinion, areas should be used to divide up a project as a whole. For example, you might have an area for "Design" and one for "Development". Or you might go even deeper and have areas like "Development - Database" and "Development - Application". Or perhaps if it is primarily focused on coding, you could create areas for each part of the system, such as "Admin", "Users", "Customers" etc.

As a side note, I have actually used parent cases in this way before and they work well. One extra benefit of the parent case approach is when it comes to recording time spent on a case. Any time spend on sub-cases is also visible (as a total) on the parent case. This is useful for reporting where you can easily see the overall time taken for a feature without having to worry about the time taken for each sub-case, which in some cases there can be many - even sub-sub-cases!

Title: Should I create a "placeholder" parent case, or set up Areas?

Body:
I'm using FogBugz for Project Management, and I'm unsure how to structure my cases.

I have different features which require implementing as part of this project.

For example, if I have a new feature to include autocomplete on a search text box, this would have cases such as:

Method for returning search terms

Front-end changes to request method

Front-end changes to display search terms

Should I create these as subcases under a "Autocomplete" case, or should they be created as top-level cases under an area called "Autocomplete"?


问:
Is online freelance work viable by American standards?
I've always been curious about trying out online freelance sites... it would be nice to work from home, feel independent, get to choose what I want to work on, get to work on different technologies, lose the PHB, etc.

However I never really gave them a chance because I'm used to American rates and assumed that I would be competing with people from India, Russia, China, etc. that would severely undercut me, and it wouldn't be viable for me.

Am I correct in this assumption or should I give it a shot?  What kind of hourly rate would I be able to expect on short-term programming work?

答: I've been freelancing online for over 5 years now and have learned from experience, you get paid what you're worth. Others undercutting you becomes a moot point when you know what you're doing, so just concentrate on providing top quality. That's what gets you the rates you deserve (and sometimes some pretty bonuses too!). Try appealing to clients in Canada, the UK, and other well-developed countries. In my experience, they sometimes pay better than Americans. :-o</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Just Outsourcing


问:
Keeping track of all objects of a class
I'm new to object-oriented programming, and I keep running into this issue. (I'm programming in Java) I've been a bit reluctant to ask about this, since it seems like such a basic issue, but I can't find any information on it, or questions about it here, and none of the textbooks I have read (on a quite basic level of course) have touched on this issue:

Often I need to keep track of all objects of a class that have been created, to iterate through them for various purposes. They way I currently write programs, many objects are only referenced from other objects, meaning I have no array or collection with which to reference them all.

I imagine that, as this seems like such a very basic necessity in OOP, there should be a quite institutionalized, and simple, way to go about this? Is it usual practice to keep a separate list of all the objects of a class?

I thought about a static array or collection, to which through its constructor, every new object created would be added. This however would not work with subclasses, since constructors are not inherited?

I realize this question might not have one easy answer; I just hope someone can enlighten me a bit on this subject. I feel like if I'm lacking a central piece of knowledge here.

答:
Try to think context. When you create an object, you do so in a certain context. For example, if your game is about shooting aliens, your app will be creating new Alien objects all the time. They will be displayed in a field called Space (which could be the class that represents the main UI).

It is perfectly natural for Space to have a property named currentAliens, which would be an array, to which you add each new alien you create. If you want to allow your user to rip apart the fabric of spacetime and destroy all aliens at once, you would iterate through that collection and destroy each object.

If you wanted to have access to this collection of aliens from within other parts of your app (say, from a Settings page, where you might want to allow users to wipe out certain types of alien in one fell swoop), your Settings context would need to be given access to the Space object.

Title: Keeping track of all objects of a class


问:
Should methods that return boolean be named after a question or an assertion?
Many naming conventions recommend that methods returning a boolean (also called predicate methods) should be named after a question. My question is: don't they really mean the methods should be named after an assertion?

The difference may be subtle, but you end up with different names in some cases:

question: is_pixel_transparent(...)

assertion: pixel_is_transparent(...)

Sometimes, this makes no difference and the phrasing is the same:

question: end_of_file(...)

assertion: end_of_file(...)

Besides, it seems like most of the time, what people call "questions" are actually assertions.

key_exists(...) --> this is not a question, this is an assertion.

Example usage: if (key_exists(...)) ...

array_contains_element(...) --> this is not a question, this is an assertion.
Example usage:
if (array_contains_element(...)) ...

So, to restate the question, is everyone meaning assertion when they say question?

答:
The point of naming conventions is not to make your code read like English, so you might be over-analyzing a bit. In many languages, it is customary to prefix a method or function returning a boolean result or a boolean variable with is, when it makes sense. There are other traditions (e.g. Lisp, Ruby), where a suffix ? is used instead. (An older Lisp tradition is the suffix -p for predicate).

In your pixel transparency example, is_transparent should be a method of a pixel object. If you are in a language that does not have objects, but want to simulate an OOP style, then the type would usually be the prefix: Pixel_is_transparent. Note that the prefix is is only used to highlight the boolean nature of this method; it is already implied by the method call (pixel.transparent works as well, but this can become too ambiguous with other property names).

To test for EOF, a method could be named at_eof. This interprets the end of file as a location in the stream, whereas stream.is_eof would work as well: here, the EOF is a specific state.

To tests whether an entry exists, collection.exists(key) would be better.

array_contains_element isn't a good method name, as it contains a type, and the unecessary element. Better: array.contains(elem).

All of the names I suggest are assertions, or more precisely: predicates. Using questions does not make any linguistic sense when these predicates are used in an if-then-else contex. The word “assertion” is probably not optimal here, as it is used to describe the testing of invariants in many languages. The word “predicate” would be better: a statement that is either true or false. A statement is phrased as if it were true, not as a question. The statement 1 ∈ {} – “1 is element of the empty set” or “the empty set contains 1” is a false statement. The question “does the empty set contain the number 1?” can be answered with yes or no, but it isn't true or false.


问:
Does Open Source lead to bad coding?
I have a thought that I tried asking at SO, but didnt seem like the appropriate place. I think that source sites like Google Code, GitHub, SourceForge... have played a major role in the history of programming. However, I found that there is another bad thing to these kind of sites and that is you may just "copy" code from almost anyone, not knowing if it is good(tested) source or not.

This line of thought has taken me to believe that source code websites tend to lead many developers (most likely unexperienced) to copy/paste massive amounts of code, which I find just wrong.

I really dont know how to focus the question well, but basic thought would be:

Is this ok? Is Open Source contributing to that or I'm just seeing ghosts...

Hope people get interested because I think this is an important theme.

答:
Isn't one of the big principles of coding "don't re-invent the wheel"?

If you copy bad code and doesn't learn from it, then it's your bad.  If you copy great code and learn from it, then you're a good programmer going on great.

Title: Does Open Source lead to bad coding?


问:
Why can data sent from the server be in a variety of formats, but sent to the server it can only be a string
I recently ran into an error, I guess caused by my lack of understanding of how HTTP works, where I was sending a JSON object to the server to be stored in session data, and then sent back to the client at a later time.

When I was sending the data to the server all of my booleans were enclosed in quotes and so when they were later sent back to the client and parsed, all of my false values were evaluated as true - obviously quite a nooby error but it took me  ages to debug because I was being stupid and seeing the "false" values in chrome dev tools and thought everything was fine with the response from the server and was looking for the problem elsewhere.

So I was wondering, is there a way to set a content-type header when sending data to the server, that would cause data types to be maintained, as you can when sending a response from the server to the client?

答:
JSON is a string.  Unless you had a server-side re-processing of the data, you should have gotten back exactly what you sent, plus or minus some line breaks.  If your JSON parser on the client doesn't correctly interpret a serialized file back to a shallow-copy of the same object, you've got a bad JSON parser. (true, false, and null are valid according to the standard.)

If you need to explicitly state the type of a field, you should consider a format with that information in the string.  XML with an XSD (or DTD) can achieve that, or you could just include a flag in your JSON denoting the value type.


问:
What format is the data going to Windows print drivers?
I have been tasked with writing a print driver.  I have no experience with this and have been researching it for a few days.  The goal of this is to essentially write the data coming to the driver to a file and then do some additional processing of it.

If I understand it correctly, I can start other processes to do most of the work, but I'll need the driver itself to generate the initial file/data.  I am confused about what state the data is in when it comes to the driver from an application.  Is this something that is determined by the application, or is there a standard of some kind?

答:
Go to the Windows DDK website and start from their print and imaging examples. What the driver actually does inside itself is entirely up to you, but the framework for a driver is clearly defined. The text-only driver should get you going.

Spend some time reading those examples and surrounding documentation before going off and inventing your own wheels - there's nothing worse than a shitty printer driver implementation, we have plenty of those already. Write one that integrates like its supposed to.


问:
UML sequence diagrams - include
I'm currently doing my OCPJEA assignment.

I have to draw several sequence diagrams for the use cases presented in the documentation. One of the use cases (A) state that after some interaction, the system executes another use case (B).

I've already drawn the diagram for B, is there any way in UML2 to show inclusion, or do I have to duplicate all those interactions into A?

答:
It looks like an official notation for this kind of referencing was introduced with UML v.2 and is called ref

Usually, all your sequence diagrams will contain a label in the upper left corner to identify your diagram. For example: sd:login-verification. Using this label, you can then reference this sequence diagram from within another one by drawing a simple box onto the concerned lifeline.

This box must mention ref in its upper left corner together with the name of the referenced diagram in the middle of the box. In addition, you have to pass those instance(s) that are used within the referenced diagram.

```<code>                        |
                        |
  -----------------------------------------------
  |  ref  /                                     |
  |-------                                      |
  |   login-verification(user, token) : bool    |
  |                                             |
  -----------------------------------------------
                        |
                        |
</code>```

I think that the following article might be quite helpful as it gives a concrete example. Have a look at the section called "Beyond the basics" where they talk about "Referencing another sequence diagram".

Article: UML basics : The sequence diagram

Title: UML sequence diagrams - include

Body:
It looks like an official notation for this kind of referencing was introduced with UML v.2 and is called ref

Usually, all your sequence diagrams will contain a label in the upper left corner to identify your diagram. For example: sd:login-verification. Using this label, you can then reference this sequence diagram from within another one by drawing a simple box onto the concerned lifeline.

This box must mention ref in its upper left corner together with the name of the referenced diagram in the middle of the box. In addition, you have to pass those instance(s) that are used within the referenced diagram.

                        |
                        |
  -----------------------------------------------
  |  ref  /                                     |
  |-------                                      |
  |   login-verification(user, token) : bool    |
  |                                             |
  -----------------------------------------------
                        |
                        |

I think that the following article might be quite helpful as it gives a concrete example. Have a look at the section called "Beyond the basics" where they talk about "Referencing another sequence diagram".

Article: UML basics : The sequence diagram


答:
My opinion is that there are good open source projects and bad open source projects. The availability of good open source projects that can be found on sites like Git Hub allow the sort of beginner programmer that will one day end up as a good programmer to have an almost endless source of good code to look at and study and (if desired) copy. The thing is that the sort of person that ends up as a good programmer is almost incapable of just copy and pasting code. They want to look at it and take it apart and modify and understand what makes it good and what could make it better and what would make it worse. By the time they're done, it's their code and they understand how it works.

It does make it more convenient for bad programmers to be bad programmers but so what? It's sort of like the flaw in javascript where

```<code>i = 1
</code>```

creates a global variable i and

```<code>var i = 1
</code>```

creates a proper local variable. This makes it possible to spot crap code in a second by all of the inadvertent global variables laying out all over the place1. The fact that it's easier to copy and paste projects together means that it's easier to spot crap code because it will be littered with the sort of vestigial limbs that were adapted to the conditions that it came from and not the conditions it's currently living in.

1 The lack of global variables doesn't of course imply that the code is good but it's a promising sign

Title: Does Open Source lead to bad coding?

Body:
I have a thought that I tried asking at SO, but didnt seem like the appropriate place. I think that source sites like Google Code, GitHub, SourceForge... have played a major role in the history of programming. However, I found that there is another bad thing to these kind of sites and that is you may just "copy" code from almost anyone, not knowing if it is good(tested) source or not.

This line of thought has taken me to believe that source code websites tend to lead many developers (most likely unexperienced) to copy/paste massive amounts of code, which I find just wrong.

I really dont know how to focus the question well, but basic thought would be:

Is this ok? Is Open Source contributing to that or I'm just seeing ghosts...

Hope people get interested because I think this is an important theme.

Body:
My opinion is that there are good open source projects and bad open source projects. The availability of good open source projects that can be found on sites like Git Hub allow the sort of beginner programmer that will one day end up as a good programmer to have an almost endless source of good code to look at and study and (if desired) copy. The thing is that the sort of person that ends up as a good programmer is almost incapable of just copy and pasting code. They want to look at it and take it apart and modify and understand what makes it good and what could make it better and what would make it worse. By the time they're done, it's their code and they understand how it works.

It does make it more convenient for bad programmers to be bad programmers but so what? It's sort of like the flaw in javascript where

i = 1

creates a global variable i and

var i = 1

creates a proper local variable. This makes it possible to spot crap code in a second by all of the inadvertent global variables laying out all over the place1. The fact that it's easier to copy and paste projects together means that it's easier to spot crap code because it will be littered with the sort of vestigial limbs that were adapted to the conditions that it came from and not the conditions it's currently living in.

1 The lack of global variables doesn't of course imply that the code is good but it's a promising sign


问:
Is lucene.net/solrnet a good solution for searching a list of names with fuzzy matching?
At the moment, we're using sql server full text search, but it's too inflexible.

The main thing we do is look up names of people from a database based on a search query. The searches need to be fast, and they need to be fuzzy. SQL Full Text Search doesn't really support fuzzy matching especially when combined with the thesaurus option. Therefore I need a better solution.

My research suggests that lucene and solr are widely used enterprise solutions, but my searching suggests these are more designed for indexing things like documents and webpages, or what it refers to as 'unstructured data'.

Our data is very well structured, and therefore I'm unsure if it's suitable for this type of work or if I should be investigating another product. According to the book I have Solr 1.4 Enterprise Search Server it supports all of the above except for prefix matching out of the box, however it states there are performance issues with substring searches.

Do you think that solr/lucene is a good technology to investigate for solving my problem? If not, do you have an alternative?

Any advice is welcome. I am a .NET developer, hence solrnet rather than solr.

答:
I have only experience with Solr and Sphinx, so can't really compare too much. And we don't use much 'fuzzy' search. But I worked with Solr a lot and think I know the docs quite well.

First of all, the term 'document' is to be understood in a very technical way. By no means does this limit your search to typical text documents. We use Solr to search products from our database and in this context a document is just a denormalized data stream representing a single product with all the text information normally in related tables directly attached to the product document. So whatever you want to search for, if it has some kind of unique id and textual descriptions (tags, category, assortment, brand...) it qualifies as document.

Ok, back to fuzzy. This kind of search is difficult, because you can't really make much use of indexes here. You would have to compare a string against every single indexed string and calculate some kind of 'distance' value and then select against a maximum distance. Solr offers Fuzzy Search and Proximity Search, but since we don't use it, I can't say how good they perform. But as one can read on the internet from version 4.0 Lucene uses something called Levenshtein Automata which should enable fuzzy search on very large indexes.

Maybe interesting here too us the way Solr builds the index. Before indexing every string goes through filters and tokenizers. There some of the magic happens and you can strongly influence how good the index will be for your kind of data. There are already a lot of default Filters and Tokenizers, but you can even write your own. So maybe there would be ways to improve performance here a bit.

Beyond that there are a few things in which Solr is really great. Mainly facetted search, where you search and count for example how many products are in a given assortment. Just make a list of all assortments and counts, then go on and make the same list in near real time together with a search term. Or select another facet (say brand=CocaCola), a search term (q=light) and again get a list with all assortments and number of products. This cross referencing came out so nice and fast that we actually replaced nearly every single SQL product listing or searching on our web site with Solr queries.


问:
Should I use a list or an array?
I'm working on a windows form to calculate UPC for item numbers.

I successfully create one that will handle one item number/UPC at a time, now I want to expand and do it for multiple item numbers/UPCs.

I have started and tried using a list, but I keep getting stuck. I created a helper class:

```<code>public class Codes
{
    private string incrementedNumber;
    private string checkDigit;
    private string wholeNumber;
    private string wholeCodeNumber;
    private string itemNumber;

    public Codes(string itemNumber, string incrementedNumber, string checkDigit, string wholeNumber, string wholeCodeNumber)
    {
        this.incrementedNumber = incrementedNumber;
        this.checkDigit = checkDigit;
        this.wholeNumber = wholeNumber;
        this.wholeCodeNumber = wholeCodeNumber;
        this.itemNumber = itemNumber;
    }

    public string ItemNumber
    {
        get { return itemNumber; }
        set { itemNumber = value; }
    }

    public string IncrementedNumber
    {
        get { return incrementedNumber; }
        set { incrementedNumber = value; }
    }

    public string CheckDigit
    {
        get { return checkDigit; }
        set { checkDigit = value; }
    }

    public string WholeNumber
    {
        get { return wholeNumber; }
        set { wholeNumber = value; }
    }

    public string WholeCodeNumber
    {
        get { return wholeCodeNumber; }
        set { wholeCodeNumber = value; }
    }

}
</code>```

Then I got started on my code, but the issue is that the process is incremental, meaning I get the item number from a gridview via checkboxes and put them in the list. Then I get the last UPC from the database, strip the checkdigit, then increment the number by one and put it in the list. Then I calculate the checkdigit for the new number and put that in the list. And here I already get an  Out of Memory Exception.
Here is the code I have so far:

```<code>List<Codes> ItemNumberList = new List<Codes>();

    private void buttonSearch2_Click(object sender, EventArgs e)
    {
        //Fill the datasets
        this.immasterTableAdapter.FillByWildcard(this.alereDataSet.immaster, (textBox5.Text));
        this.upccodeTableAdapter.FillByWildcard(this.hangtagDataSet.upccode, (textBox5.Text));
        this.uPCTableAdapter.Fill(this.uPCDataSet.UPC);
        string searchFor = textBox5.Text;
        int results = 0;
        DataRow[] returnedRows;
        returnedRows = uPCDataSet.Tables["UPC"].Select("ItemNumber = '" + searchFor + "2'");
        results = returnedRows.Length;
        if (results > 0)
        {
            MessageBox.Show("This item number already exists!");
            textBox5.Clear();
            //clearGrids();
        }
        else
        {
            //textBox4.Text = dataGridView1.Rows[0].Cells[1].Value.ToString();
            MessageBox.Show("Item number is unique.");
        }
    }

    public void checkMarks()
    {

        for (int i = 0; i < dataGridView7.Rows.Count; i++)
        {
            if ((bool)dataGridView7.Rows[i].Cells[3].FormattedValue)
            {
                {
                    ItemNumberList.Add(new Codes(dataGridView7.Rows[i].Cells[0].Value.ToString(), "", "", "", ""));
                }
            }
        }
    }

    public void multiValue1()
    {
        _value = uPCDataSet.UPC.Rows[uPCDataSet.UPC.Rows.Count - 1]["UPCNumber"].ToString();//get last UPC from database
        _UPCNumber = _value.Substring(0, 11);//strip out the check-digit
        _UPCNumberInc = Convert.ToInt64(_UPCNumber);//convert the value to a number

        for (int i = 0; i < ItemNumberList.Count; i++)
        {
            _UPCNumberInc = _UPCNumberInc + 1;
            _UPCNumberIncrement = Convert.ToString(_UPCNumberInc);//assign the incremented value to a new variable
            ItemNumberList.Add(new Codes("", _UPCNumberIncrement, "", "", ""));//**here I get the OutOfMemoreyException**
        }

        for (int i = 0; i < ItemNumberList.Count; i++)
        {
            long chkDigitOdd;
            long chkDigitEven;
            long chkDigitSubtotal;
            chkDigitOdd = Convert.ToInt64(_UPCNumberIncrement.Substring(0, 1)) + Convert.ToInt64(_UPCNumberIncrement.Substring(2, 1)) + Convert.ToInt64(_UPCNumberIncrement.Substring(4, 1)) + Convert.ToInt64(_UPCNumberIncrement.Substring(6, 1)) + Convert.ToInt64(_UPCNumberIncrement.Substring(8, 1)) + Convert.ToInt64(_UPCNumberIncrement.Substring(10, 1));
            chkDigitOdd = (3 * chkDigitOdd);
            chkDigitEven = Convert.ToInt64(_UPCNumberIncrement.Substring(1, 1)) + Convert.ToInt64(_UPCNumberIncrement.Substring(3, 1)) + Convert.ToInt64(_UPCNumberIncrement.Substring(5, 1)) + Convert.ToInt64(_UPCNumberIncrement.Substring(7, 1)) + Convert.ToInt64(_UPCNumberIncrement.Substring(9, 1));
            chkDigitSubtotal = (300 - (chkDigitEven + chkDigitOdd));
            _chkDigit = chkDigitSubtotal.ToString();
            _chkDigit = _chkDigit.Substring(_chkDigit.Length - 1, 1);
            ItemNumberList.Add(new Codes("", "",_chkDigit, "", ""));
        }
</code>```

Is this the right way to go about it, using a list, or should I be looking at a different way?

答:
I'll expand my comment:

... if you're adding or removing elements, you want a list (or other flexible data structure). Arrays are only really good when you know exactly how many elements you need at the start.

A Quick Breakdown

Arrays are good when you have a fixed number of elements that is unlikely to change, and you wish to access it in a non-sequential fashion.

Fixed Size

Fast Access - O(1)

Slow Resize - O(n) - needs to copy every element to a new array!

Linked-Lists are optimized for quick additions and removals at either end, but are slow to access in the middle.

Variable Size

Slow Access at middle - O(n)

Needs to traverse each element starting from the head in order to reach the desired index

Fast Access at Head - O(1)

Potentially fast access at Tail

O(1) if a reference is stored at the tail end (as with a doubly-linked list)

O(n) if no reference is stored (same complexity as accessing a node in the middle)

Array Lists (such as List<T> in C#!) are a mixture of the two, with fairly fast additions and random access. List<T> will often be your go-to collection when you're not sure what to use.

Uses an array as a backing structure

Is smart about its resizing - allocates the double of its current space when it runs out of it.

This leads to O(log n) resizes, which is better than resizing every time we add/remove

Fast Access - O(1)

How Arrays Work

Most languages model arrays as contiguous data in memory, of which each element is the same size. Let's say we had an array of ints (shown as [address: value], using decimal addresses because I'm lazy)

```<code>[0: 10][32: 20][64: 30][96: 40][128: 50][160: 60]
</code>```

Each of these elements is a 32-bit integer, so we know how much space it takes up in memory (32 bits!). And we know the memory address of the pointer to the first element.

It's trivially easy to get to the value of any other element in that array:

Take the address of the first element

Take the offset of each element (its size in memory)

Multiply the offset by the desired index

Add your result to the address of the first element

Let's say our first element is at '0'. We know our second element is at '32' (0 + (32 * 1)), and our third element is at 64 (0 + (32 * 2)).

The fact that we can store all these values next to each other in memory means our array is as compact as it can possibly be. It also means that all our elements need to stay together for things to continue working!

As soon as we add or remove an element, we need to pick up everything else, and copy them over to some new place in memory, to make sure there are no gaps between elements, and everything has enough room. This can be very slow, especially if you're doing it every time you want to add a single element.

Linked Lists

Unlike arrays, Linked Lists don't need all their elements to be next to each other in memory. They are composed of nodes, that store the following info:

```<code>Node<T> {
    Value : T      // Value of this element in the list
    Next : Node<T> // Reference to the node that comes next
}
</code>```

The list itself keeps a reference to the head and tail (first and last nodes) in most cases, and sometimes keeps track of its size.

If you want to add an element to the end of the list, all you need to do is get the tail, and change its Next to reference a new Node containing your value. Removing from the end is equally simple - just dereference the Next value of the preceding node.

Unfortunately, if you have a LinkedList<T> with 1000 elements, and you want element 500, there's no easy way to jump right to the 500th element like there is with an array. You need to start at the head, and keep going to the Next node, until you've done it 500 times.

This is why adding and removing from a LinkedList<T> is fast (when working at the ends), but accessing the middle is slow.

Edit: Brian points out in the comments that Linked Lists have a risk of causing a page fault, due to not being stored in contiguous memory. This can be hard to benchmark, and can make Linked Lists even a bit slower than you might expect given just their time complexities.

Best of Both Worlds

List<T> compromises for both T[] and LinkedList<T> and comes up with a solution that's reasonably fast and easy to use in most situations.

Internally, List<T> is an array! It still has to jump through the hoops of copying its elements when resizing, but it pulls some neat tricks.

For starters, adding a single element doesn't usually cause the array to copy. List<T> makes sure there's always enough room for more elements. When it runs out, instead of allocating a new internal array with just one new element, it will allocate a new array with several new elements (often twice as many as it currently holds!).

Copy operations are expensive, so List<T> cuts down on them as much as possible, while still allowing fast random access. As a side effect, it may end up wasting slightly more space than a straight-up array or linked list, but it's usually worth the tradeoff.

TL;DR

Use List<T>. It's normally what you want, and it seems to be correct for you in this situation (where you're calling .Add()). If you're unsure of what you need, List<T> is a good place to start.

Arrays are good for high-performance, "I know I need exactly X elements" things. Alternatively, they're useful for quick, one-off "I need to group these X things I've already defined together so I can loop over them" structures.

There are a number of other collection classes. Stack<T> is like a linked list that only operates from the top. Queue<T> works as a first-in-first-out list. Dictionary<T, U> is an unordered, associative mapping between keys and values. Play with them and get to know the strengths and weaknesses of each. They can make or break your algorithms.

Title: Should I use a list or an array?

Body:
I'll expand my comment:

... if you're adding or removing elements, you want a list (or other flexible data structure). Arrays are only really good when you know exactly how many elements you need at the start.

A Quick Breakdown

Arrays are good when you have a fixed number of elements that is unlikely to change, and you wish to access it in a non-sequential fashion.

Fixed Size

Fast Access - O(1)

Slow Resize - O(n) - needs to copy every element to a new array!

Linked-Lists are optimized for quick additions and removals at either end, but are slow to access in the middle.

Variable Size

Slow Access at middle - O(n)

Needs to traverse each element starting from the head in order to reach the desired index

Fast Access at Head - O(1)

Potentially fast access at Tail

O(1) if a reference is stored at the tail end (as with a doubly-linked list)

O(n) if no reference is stored (same complexity as accessing a node in the middle)

Array Lists (such as List<T> in C#!) are a mixture of the two, with fairly fast additions and random access. List<T> will often be your go-to collection when you're not sure what to use.

Uses an array as a backing structure

Is smart about its resizing - allocates the double of its current space when it runs out of it.

This leads to O(log n) resizes, which is better than resizing every time we add/remove

Fast Access - O(1)

How Arrays Work

Most languages model arrays as contiguous data in memory, of which each element is the same size. Let's say we had an array of ints (shown as [address: value], using decimal addresses because I'm lazy)

[0: 10][32: 20][64: 30][96: 40][128: 50][160: 60]

Each of these elements is a 32-bit integer, so we know how much space it takes up in memory (32 bits!). And we know the memory address of the pointer to the first element.

It's trivially easy to get to the value of any other element in that array:

Take the address of the first element

Take the offset of each element (its size in memory)

Multiply the offset by the desired index

Add your result to the address of the first element

Let's say our first element is at '0'. We know our second element is at '32' (0 + (32 * 1)), and our third element is at 64 (0 + (32 * 2)).

The fact that we can store all these values next to each other in memory means our array is as compact as it can possibly be. It also means that all our elements need to stay together for things to continue working!

As soon as we add or remove an element, we need to pick up everything else, and copy them over to some new place in memory, to make sure there are no gaps between elements, and everything has enough room. This can be very slow, especially if you're doing it every time you want to add a single element.

Linked Lists

Unlike arrays, Linked Lists don't need all their elements to be next to each other in memory. They are composed of nodes, that store the following info:

Node<T> {
    Value : T      // Value of this element in the list
    Next : Node<T> // Reference to the node that comes next
}

The list itself keeps a reference to the head and tail (first and last nodes) in most cases, and sometimes keeps track of its size.

If you want to add an element to the end of the list, all you need to do is get the tail, and change its Next to reference a new Node containing your value. Removing from the end is equally simple - just dereference the Next value of the preceding node.

Unfortunately, if you have a LinkedList<T> with 1000 elements, and you want element 500, there's no easy way to jump right to the 500th element like there is with an array. You need to start at the head, and keep going to the Next node, until you've done it 500 times.

This is why adding and removing from a LinkedList<T> is fast (when working at the ends), but accessing the middle is slow.

Edit: Brian points out in the comments that Linked Lists have a risk of causing a page fault, due to not being stored in contiguous memory. This can be hard to benchmark, and can make Linked Lists even a bit slower than you might expect given just their time complexities.

Best of Both Worlds

List<T> compromises for both T[] and LinkedList<T> and comes up with a solution that's reasonably fast and easy to use in most situations.

Internally, List<T> is an array! It still has to jump through the hoops of copying its elements when resizing, but it pulls some neat tricks.

For starters, adding a single element doesn't usually cause the array to copy. List<T> makes sure there's always enough room for more elements. When it runs out, instead of allocating a new internal array with just one new element, it will allocate a new array with several new elements (often twice as many as it currently holds!).

Copy operations are expensive, so List<T> cuts down on them as much as possible, while still allowing fast random access. As a side effect, it may end up wasting slightly more space than a straight-up array or linked list, but it's usually worth the tradeoff.

TL;DR

Use List<T>. It's normally what you want, and it seems to be correct for you in this situation (where you're calling .Add()). If you're unsure of what you need, List<T> is a good place to start.

Arrays are good for high-performance, "I know I need exactly X elements" things. Alternatively, they're useful for quick, one-off "I need to group these X things I've already defined together so I can loop over them" structures.

There are a number of other collection classes. Stack<T> is like a linked list that only operates from the top. Queue<T> works as a first-in-first-out list. Dictionary<T, U> is an unordered, associative mapping between keys and values. Play with them and get to know the strengths and weaknesses of each. They can make or break your algorithms.


问:
Is TDD viable in collaborative open source projects
Let's say I wanted to start an open source project that I hope/expect to have many people submit patches and whatnot. Is it viable to take a strict TDD approach? Can/should I expect/trust collaborators to write quality tests whenever they submit a patch?

One thing I've been thinking about is writing test suites for individual bug reports and feature requests and requiring that all patches/pull requests make the tests pass, but at that point it seems like it would be better just to write the feature/bugfix myself.

As far as I can tell, most of the major open source projects that use TDD (or at least write tests) seem to be mostly written purely by an individual or team, where it's easy to enforce practices such as TDD.

答:
You could ask people to submit test-only patches before they're allowed to work on the code; this would provide an additional opportunity to review the planned design before the code itself is written.

In practice, this may kill any enthusiasm people have for contributing to the project--or it might kindle a fire in those who agree with your methodology.

Reviewers would have to be very good about turning around the design reviews quickly, however, so as not to stall out development.


答: I don't think too many developers copy-paste from large open-source projects. It's just too much work to find the right spot in thousands of lines of codes, and it could be difficult (at least for a bad developer) to find out which part to copy. They rather copy-paste small snipplets found on forums, articles, examples etc., where everything is nicely put together.</p>

Title: Does Open Source lead to bad coding?

ContentLicense: CC BY-SA 4.0


问:
Why is the following naming guideline different between OO and non-OO languages?
I am working with a non-OO language and I'm trying to name my routines consistently. I came acrross the following guideline from Steve McConnell's Code Complete:

To name a procedure, use a strong verb followed by an object

McConnell gives the following good and bad examples:

good, non-OO --> PrintDocument(doc)

good, OO -->       doc.Print()

bad, OO -->          doc.PrintDocument()

For an OO language, doc.PrintDocument() is non-recommended on the basis that it is redundant.

I'm having a hard time wrapping my head around this guideline. Why is PrintDocument(doc)recommended, and doc.PrintDocument() non-recommended?

Also, what would be the problem with the simpler name Print(doc) in a non-OO language?

Am I missing something very basic here?

答:
For the non-OO situation PrintDocument():  The suffix Document gives you the context required to know the method is to be called with a Document parameter.

For the OO situation doc.Print():  The doc object already gives you some context.  Namely, that its methods will perform actions on a Document.  Because the context is nearly explicit it would be redundant to specify "Document" in the method name.

And wrt your second question:  I'm assuming Print(doc) isn't recommend because it's more difficult to discover exactly what Print does.  I guess it's all about presenting as much information as possible as early as possible.  Self documenting code!


问:
Why does the backing store of an array bind to the smallest type?
In C# it is legal to write

```<code>Animal[] a = new Giraffe[4]; //with obvious relationships
</code>```

Because arrays are covariant.  However, this is a breaking relationship.  It's a runtime exception to then apply a different type of Animal to this array because the backing store is a Giraffe.

```<code>a[0] = new Cat(); //KABOOM
</code>```

Why doesn't the language create a covariant backing store?  This doesn't appear to be a limitation of the language because I can create this type of data structure myself:

```<code>class Program
{
    static void Main(string[] args)
    {
        A[] a = new B[2];
        a[0] = new B();
        a[1] = new C();//runtime exception

        var containerLegal = new Container<B, A>();
        containerLegal.Add(new B());
        containerLegal.Add(new C());//works fine
    }
}

class A { }

class B : A { }

class C : A { }

class Container<T,S> where T: class, S
{
    S[] s = new S[4];
    int currentIndex = 0;

    public void Add(S t)
    {
        s[currentIndex] = t;
        currentIndex++;
    }
}
</code>```

I'm cheating a little bit cause I'm not using T in Container<>...but I think its a fair relationship anyhow.

答:
As noted, arrays bind to whatever type is specified when they are created.  The fact that even mutable arrays may be passed covariantly is a consequence of a few things:

Arrays predate generics, and until covariant generics were added to .NET there was no immutable type which could behave covariantly, so the arrays (which were all mutable) were the only thing that could be covariant.

To efficiently sort an array, one must be able to read items out of the array and write them back to it.  If one has a reference of type Animal[], even if it points to a Cat[], one may without any possibility of run-time error read out any item of that array into a reference of type Animal and later store it back to the array from which it came.  The ability to read out items might not be totally necessary if Array contained some methods like CopyItem and SwapItem, but being able to read out an item and write it back after performing many other changes to an array is more efficient than would be having to decompose every sort into a sequence of swaps.  While one could design a covariant interface which would allow an array or other collection to be efficiently sorted without requiring the sorting code to directly write anything into the collection itself, it's much easier to simply allow array covariance.

An array knows the type of element it's supposed to contain.  This allows it to enforce type-safety at runtime.  Although the generic collections added in .NET 2.0 also know their element type, most generic collections in Java don't.  If one tried to pass an ArrayList<Cat> to code expecting an ArrayList<Animal>, and if the latter code tried to add a Dog to it, there would be no way the ArrayList<Cat> could know that it was created as an ArrayList<Cat> and should reject the request.

If one declared arrays using syntax like Array<Dog> myDogs = new Array<Dog>(34); rather than Dog[] myDogs = new Dog[34];, then it might be possible to have multiple kinds of array references, so that e.g. Array<Animal> myDogs = new Array<Dog>(34); wouldn't compile, but SortableArray<Animal> myDogs = new Array<Dog>(34); would.  Neither Java nor .NET supports multiple array types, however.


问:
How can I automate the process of code review
I have a team that works on multiple technologies. I want to know how can I automate the process of code review for .Net, .Net MVC, Python, PHP, Drupal and HTML5/CSS with JavaScript.

I have read about and have used some tools like StyleCop/FxCop for .Net and PHP Code Sniffer and likes for PHP and pyLint for Python.

I understand that automated code reviews do not fully replace the manual ones, but I want to setup a process to support manual code reviews.

Any suggestions?
Thanks

答:
Well you can rely on some best Code Analysis Tools specific to your language. This tools will be like plugins to your IDEs. you will get code review comments to some decent extent while you code.You can also manually run the tool. I don't have any idea on PHP but we use PMD, check styles for the same purpose in java development.

Hope this will be helpful.

OwnerDisplayName: theghostofc

OwnerDisplayName: Balaji Reddy


答: In projects where it's available it can be a good idea to implement unit testing. On smaller builds you could set it up (in Visual Studio at least) to have your tests run on build and compile (on large projects with large tests this will increase your compile time by a lot though...)

Title: How can I automate the process of code review

Body:
I have a team that works on multiple technologies. I want to know how can I automate the process of code review for .Net, .Net MVC, Python, PHP, Drupal and HTML5/CSS with JavaScript.

I have read about and have used some tools like StyleCop/FxCop for .Net and PHP Code Sniffer and likes for PHP and pyLint for Python.

I understand that automated code reviews do not fully replace the manual ones, but I want to setup a process to support manual code reviews.

Any suggestions?
Thanks

OwnerDisplayName: Max


问:
Writing simple executable script on Windows
I'm a Mac user, but I need to write a script on Windows, and I'm not sure how I should go about that.

Here's the scenario:

Someone adds photos to a USB drive. The drive is then inserted into a digital picture frame.

In order for the photos to autoplay, a 'playlist.asb' file must be present on the drive. I want to create a script that can be clicked on and executed to auto create the playlist file based on the image files added to the USB. The script would do something like this:

Check if there are images in the 'slideshow' folder.

Check if file called 'playlist.alb' exists, if not create it. If so, overwrite it.

Loop through available images.

Add each image name and extension on a new line.

Save (and overwrite any existing playlist file) and exit.

I'm comfortable with AppleScript for Macs, but I'm not sure if a Windows equivalent would make sense, or if some kind of command line script would work better.

Any help is greatly appreciated.

答:
Assuming flashdrive will allways be mapped to, e.g., G: letter, and all images are jpgs, then this should work:

```<code>echo. > g:\slideshow\playlist.alb
dir /b g:\slideshow\*.jpg >> g:\slideshow\playlist.alb
</code>```

Create a file with the .bat extension with that instruction in it.

If no jpg file is found, an empty playlist will be created which should yield the same result as having no playlist at all.

The /b switch is to prevent boilerplate text, file sizes, dates, etc, from being dumped into the file. The echo command with a dot at the end (no space) is not a typo.

Update:

First line generates a file with a blank line in it. In the second line, ">" is changed to ">>" to append at the end of such a file rather than overwriting it.

Body:
Assuming flashdrive will allways be mapped to, e.g., G: letter, and all images are jpgs, then this should work:

echo. > g:\slideshow\playlist.alb
dir /b g:\slideshow\*.jpg >> g:\slideshow\playlist.alb

Create a file with the .bat extension with that instruction in it.

If no jpg file is found, an empty playlist will be created which should yield the same result as having no playlist at all.

The /b switch is to prevent boilerplate text, file sizes, dates, etc, from being dumped into the file. The echo command with a dot at the end (no space) is not a typo.

Update:

First line generates a file with a blank line in it. In the second line, ">" is changed to ">>" to append at the end of such a file rather than overwriting it.


问:
Comparison of route formats
I'm developing a new application and I'm trying to come up with a convention for defining routes. Ideally, I would like it to be simple, flexible, and reversible.

Here are some from popular frameworks:

Backbone

```<code>route                           matches
-----------------------------------------------------
help                            help
search/:query                   search/kiwis
search/:query/p:page            search/kiwis/p7
file/*path                      file/nested/folder/file.txt
docs/:section(/:subsection)     docs/faq, docs/faq/installing
</code>```

Django

Uses regexes, but comes with a complex regex reverser

```<code>route                                                           matches
-------------------------------------------------------------------------------------
^articles/2003/$                                                /articles/2003/
^articles/(\d{4})/(\d{2})/$                                     /articles/2005/03/
^articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$     /articles/2003/03/03/
</code>```

Ruby on Rails

```<code>:controller/:action/:id/with_user/:user_id
books/*section/:title
</code>```

ASP.NET / MVC 5

```<code>{controller}/{action}/{id}           /Products/show/beverages
{resource}.axd/{*pathInfo}           /WebResource.axd?d=...
{productId:int}/{productTitle}       /5/asp-net-mvc
books/{isbn?}                        /books, /books/1430210079
</code>```

Django's is probably the most flexible, and it's already familiar to people that know regexes, but it's also the most difficult to read and reverse.

Backbone, RoR and ASP.NET all allow optional and wildcard/splat parts, with various syntaxes. MVC 5 has some options for restricting the parameters inline ala :int.

Where might these schemes fall short, and how could they be fixed?

答:
How about manipulating you routes using Angular.js and js functions and conditionals?
 http://scotch.io/tutorials/javascript/single-page-apps-with-angularjs-routing-and-templating</p>

Title: Comparison of route formats


问:
What are common code review processes and what is considered bad?
My company recently started doing formalized code reviews. The process goes like this: you submit into a github, request a pull request, code gets reviewed by approximately three people, then if all passes, your code goes in.

The process seems fair, however the three people who do the code reviews don't seem to be fair. I notice that when I put my code in for review, I get anywhere between 100-200 comments. The top number for me was 300 comments once. Of course you'd think it is big changes, but this can be very small changes as well with less than 50 lines of code (which includes unit tests). All comments are considered "must do" and without argument.

With that in mind, my main problem here is that it seems a bit excessive. I talked to the group and they told me basically that just because I had so many years of development in php doesn't mean I am an "developer." Of course this seems more hurtful than not. Also I notice that within the group, they don't appear to produce as much comments and most of the time they ignore or otherwise disregard other comments or suggestions rarely accepting it as a valid point even if something is broken.

So my question is if this is fair? Or common?

答:
Code reviews can be a divisive process.

You are at an important junction, though.  Do a thoughtful analysis on their review.  Are they identifying nit-picking issues, or highlighting serious flaws in your style and logic?

If it's the former, I'd recommend working towards a resolution ( new job, or new code review processes ).

If it's the latter, I recommend doing a lot of code-reading and studying to try to bring your code up to professional quality.


答:
The scope and scale here isn't well defined in the question, so I'm answering this assuming the USB drive is being shipped with the photo frame, and the whole thing is meant for the end user to use.

If thats the case, the route I'd take would be to make an executable that runs automatically when the USB drive is plugged in (as set in an autorun.inf file).  That program would provide an interface prompting the user to drag/drop files into it.  As the files are added, that program would create the .asb file automatically.  If the user adds files to the USB drive manually, you can have them launch the program which will generate the .asb file.

I would not rely on the customer knowing what a batch file is, or even rely on them reading instructions.

The technology you'd use for creating this would essentially be any programming language capable of generating a stand-alone Windows executable.

Title: Writing simple executable script on Windows

Body:
I'm a Mac user, but I need to write a script on Windows, and I'm not sure how I should go about that.

Here's the scenario:

Someone adds photos to a USB drive. The drive is then inserted into a digital picture frame.

In order for the photos to autoplay, a 'playlist.asb' file must be present on the drive. I want to create a script that can be clicked on and executed to auto create the playlist file based on the image files added to the USB. The script would do something like this:

Check if there are images in the 'slideshow' folder.

Check if file called 'playlist.alb' exists, if not create it. If so, overwrite it.

Loop through available images.

Add each image name and extension on a new line.

Save (and overwrite any existing playlist file) and exit.

I'm comfortable with AppleScript for Macs, but I'm not sure if a Windows equivalent would make sense, or if some kind of command line script would work better.

Any help is greatly appreciated.


答:
@user61852 is on the right track, but his solution has the drawback that it will not work with a different drive letter. And you don't know the drive letter beforehand. Everytime you insert the usb stick, it may get a different drive letter assigned to.

As a solution, one should put the script directly in the main folder of the usb stick itself, and add cd /d %~d0%~p0 to the first line. This makes the usb home directory the current directory. Then, you can leave out the letter afterwards. So the script should look like this:

```<code>cd /d %~d0%~p0
dir /b \slideshow\*.jpg >\slideshow\playlist.alb
</code>```

Body:
@user61852 is on the right track, but his solution has the drawback that it will not work with a different drive letter. And you don't know the drive letter beforehand. Everytime you insert the usb stick, it may get a different drive letter assigned to.

As a solution, one should put the script directly in the main folder of the usb stick itself, and add cd /d %~d0%~p0 to the first line. This makes the usb home directory the current directory. Then, you can leave out the letter afterwards. So the script should look like this:

cd /d %~d0%~p0
dir /b \slideshow\*.jpg >\slideshow\playlist.alb


答:
Is it common for anyone to get 100+ comments in their code reviews on a routine basis? I would say not. Is it common for people whose code quality "leaves a lot to be desired" to get a lot of comments, absolutely.

However, it also depends on the "rules" of the code review process. EVERYBODY has their own ideas on how something should have been done. If your code review process allows comments to be of the form "You should do it this way instead of that way", then you'll likely get LOTS of comments even for adequate code. If your process is intended to find "defects" then the number of comments should be much smaller.

In my experience, reviews that allow "suggestions" for alternative methods are time wasters. Those "suggestions" should be handled one on one outside the review process. Defect reviews are more useful as they get people to focus on bugs instead of "why didn't you do it like I would have done it?".  It also is more useful because there's no denying a bug if someone finds one. Thus, there's no hurt feelings but likely gratitude instead.

UPDATE: With all that said, some code is just plain bad, even if defect free. In that case, the review comment should be a single comment that says something like. "This code needs to be cleaned up. Please postpone the review until the code is discussed with [your name here]."  In that case, further review of the code should stop until the comment is rectified.

UPDATE2: @User:Do you discuss your code/design with one of them while you are developing it so you can implement what they are looking for before you get to far doing it your way? Are you changing anything about how you are developing code based on their suggestions or keep thinking your way is fine? Are you learning anything from their comments?

When I am the sw lead on a project, it is my job to be responsible for ALL work products. If I approve a work product then I am claiming the product is acceptable. I want to have a reputation for building quality products. Thus, I have expectations and won't accept less than satisfactory. At the same time I try to teach and explain the reasons for my preferences. Those preferences may not always be ideal (particularly in the eyes of others), but most of those preferences have come from experience. Usually a reaction to avoid repeating the bad ones. Thus, there are a few of my personal "sticklers" that are necessary to get my approval, regardless of pushback.

On the other side, you need to learn the expectations that are necessary to get your work products approved. You can disagree, but since you don't appear to have the authority to over-rule then learn what is expected. I doubt that the team is trying to make you fail. As that makes them look bad also. In that regard, just demonstrate that you are eager to learn (even if you aren't), take what they say and do your best to adapt to their preferences and you'll likely see them back off quite a bit. Maybe find the one that you can at least tolerate and see if they'll do a bit of hand-holding to teach you their ways. Who knows, in the process you may learn something that really could take your skills to the next level.

Title: What are common code review processes and what is considered bad?

Body:
My company recently started doing formalized code reviews. The process goes like this: you submit into a github, request a pull request, code gets reviewed by approximately three people, then if all passes, your code goes in.

The process seems fair, however the three people who do the code reviews don't seem to be fair. I notice that when I put my code in for review, I get anywhere between 100-200 comments. The top number for me was 300 comments once. Of course you'd think it is big changes, but this can be very small changes as well with less than 50 lines of code (which includes unit tests). All comments are considered "must do" and without argument.

With that in mind, my main problem here is that it seems a bit excessive. I talked to the group and they told me basically that just because I had so many years of development in php doesn't mean I am an "developer." Of course this seems more hurtful than not. Also I notice that within the group, they don't appear to produce as much comments and most of the time they ignore or otherwise disregard other comments or suggestions rarely accepting it as a valid point even if something is broken.

So my question is if this is fair? Or common?


答:
From what you are saying, it seems to me that they might have a bias against php developers, and thus they are trying to find every single thing that is wrong with your code in order to prove their point.¹

Regarding the code review itself, I believe as you said already, that such a huge amount of minor comments is less helpful than a few good and valid criticisms. And although I have limited experience with respect to code reviews, the following technique has worked well for the teams I worked-in in the past.

First of all, a static code analyser should be used to identify most of the issues before the code review takes place. E.g.: running your code through Sonar, Lint or any other good code analyser should help you to get rid of most minor issues. Especially since your reviewers can define custom profiles to ensure everything from bracket placing, white-spaces, comments, proper variable naming and much more...

Second, I seems to work well if you divide the comments into different categories. For example two categories where one group includes small things that are you should take note of and apply in the future. And a second group for those comments that require an immediate modification of your code which would require another commit and subsequent review. Of course, the number of comments in latter group should be smaller.

Furthermore, I have to say that my first real code reviews also contained more comments than I originally expected. However I never regarded this as a bad thing. If you continue to learn from their comments² and are willing to apply those newly learned techniques / best practices in your future code submissions, the comments should become less. It sure was the case for me ;-)

¹ In my experience, this happens a lot as many programmers claim that php is the most evil programming language, having the most inexperienced programmers using it. I distance myself from this statement as I believe that great software can be written in any language!

² Assuming that although the comments are excessive, some value is in them


问:
Building proprietary software over haskell compiler
Is it perfectly legal to use GHC as base and build some commercial application over its top ? Are there such examples I can can interact with ?</p>

答:
(IANAL)

AFAIK by default GHC is linked with the GMP for integer arithmetics. And the library is licensed under LGPL, which requires that users of a program that uses the library can replace the library with a different one. This is hardly possible with GHC static builds and strong optimizations.

This problem is described in tichet #601 and on GHC's wiki page Replacing GMP: Bignum libraries, Licensing and Implementation. A link at the end of the ticket says that now you can select a native numeric library, when compiling GHC, thus avoiding the problem.

So be sure that whatever you build on top of GHC, you opt out of using GMP when compiling GHC. As long as you're using only BSD3 (or similar permissive licenses), there are very few restrictions you have to obey.


答:
All comments are considered "must do" and without argument.

IMHO that's the real issue, since there is no priorization in that. When you get 100-300 comments, there must be some of them having a priority A (real bugs), some of them prio B (likely to lead to bugs later) and some of them prio C (everything else). Tell your colleagues that you are willing to respect all their wishes, but to make changes effective, and your time is limited, insist on a priorization. Then, start with fixing prio A comment first, and if you really have time for more after that, you can start with B (if you are lucky, your boss will understand that fixing prio B and C is not so important, and give you some more important tasks instead of wasting your time).


答:
Everyone has some sort of motivation for releasing their code in a manner that allows other people to use, modify and re-distribute it.

Some of the reasons:

You feel the code is useful, and would be useful to others

You feel the idea is useful, and hope more experienced people will refine the implementation

You are obligated by a license to release the code for modified binary executables that you distributed

You hope the availability of the code will help boost your business

Other reasons, of course come into play, or perhaps a combination of reasons. Your question seems to hinge on an assumption that code released into the wild should be of a minimum quality, which I think is overly idealistic.

Additionally, I think more 'copy and paste' coding results from reading a 'tutorial' that someone posted on a blog with snippets, not from someone who took the time to mine through github to find something that might solve a problem. Yet, using examples from a five year old 'quick start' guide you bought at a used book store might be equally dangerous.

Good programmers avoid the mistakes that inexperienced programmers tend to make, that will always be the case. You often learn how to avoid these traps by falling into them.

Title: Does Open Source lead to bad coding?


问:
What does Scrum say about tech demos?
I'm sometimes suppsed to demo work and I wonder if the Scrum methods have specified something about how demos should be done? I've done quick demos and I've been asked to demo on-the fly while it's not realistic to expect that programming always moves only forward. SO I'd like to know if you can tell me since I follow Scrum, if there is anything there that can improve my technical demos? For instance how often and when a demo should be done?</p>

答:
Since you're using Agile, you're expected to have a working version at regular intervals. The intervals depend on your precise approach: it can be as long as a few weeks (the duration of your sprints), or as short as a few minutes if you use continuous integration.

Having constantly a working version makes it easy for your stakeholders to test themselves the product. In the same way, it's easy to make a demo to your stakeholders if they want to.

The fact that the project doesn't always move forward doesn't change anything: the demo is done on a working product in a given amount of time, not on the progress. If your stakeholders want to see the progress, in order, for example, to have a clear idea about what was done since the last sprint, they shouldn't ask for a demo, but rather go and see the backlog.

It's usually better to do the demos not at the regular intervals, but when you release a major feature. Indeed, making a demo after you spend two weeks doing major refactoring will give a bad impression on the stakeholders, which may reflect in their attitude towards refactoring, Agile methods, your team, your credibility, etc.

Remember that Agile encourages nearly-constant interaction between the team and the stakeholders, especially to quickly obtain feedback about what's just done and what is expected to be done soon. If this interaction is correctly done, stakeholders are already informed well about the current state of the product, the features and the progress. This makes demos much less useful compared to Waterfall projects, where the customer may remain blind during development, and discovers the project months later.

Title: What does Scrum say about tech demos?


答:
It seems by your comments that your colleagues are using the code review process to agree a methodology or polish the code. I have just started to do code reviews like you and I notice that sometimes we discuss a lot over things that are just implementation approaches or improvements. This is not bad at all as far as its reasonable (300 comments look too many for me, that must look like a reddit thread)

Maybe you need to agree some architectural decisions about the code before start implementing it or maybe is just agree about naming conventions, patterns and good practices so you all know what it is considered "good code".

If you are complying with your code standards as you say and the code works as intended, there shouldn't be so many comments, so either they are using your code as a forum or they are trolling you as it seems that you are pointing.

I would try to be critic with myself, would try to take part in the conversations and see the reason of all this comments and maybe talk with them about it in a constructive way to see why are they so unhappy with your code and if you can code in a way that makes everyone happy and the work don't get stuck in code review.

I just read your last comments, sometimes when you don't agree with the code you can go over it a hundred times and propose changes everywhere that don't make you happy because the real reason its that you would have done a different architectural decision and you just don't like that code, no matter how many times you refactor it. As I say above, maybe you need to agree the approach to the code beforehand so when you write it you know what they expect from it and therefore your code would be more reasonable to them.


问:
Why is there a gap between JBoss EAP and the JBoss AS/Community edition?
Admittedly new to this but I wanted to understand why there is a gap between Red Hat's JBoss EAP project (their enterprise version) and JBoss AS/Wildfly/community project.

Looking at this post from Red Hat, it seems that they don't withhold the source/patches. Makes sense since withholding the source would be a GPL violation, which in spirit wants source distributions so end users can recreate/reuse the binaries.

So if the sources are identical, then why isn't the AS/community version exactly at par with the EAP version? Shouldn't they be bit-exact, like having the same SHA256 value? It appears that the AS/community version usually lags by several hundred patches (from here, "Intro" section)

Talking about the latest JBoss Application Server is always tricky.
  Red Hat simultaneously offers two versions of JBoss: community
  edition, the current release where is 7.1.1-Final, and Enterprise
  Application Platform, EAP, edition where JBoss AS component version is
  7.1.3-Final. The difference between these is actually a few hundred bug-fixes, which is enormous ...

Since EAP binary distribution is controlled by Red Hat, surely there is enough community interest that the community itself rebuilds and redistributes AS/Wildfly binaries that are at-par with the EAP binaries, right? (a single Maven server should suffice).

I mean look at the popularity of CentOS (the community version of Red Hat Enterprise Linux) - the community IS interested in using software in production without RedHat's blessings/support.

So, what am I missing here?

答:
It looks like all boils down to the differences mentioned on this page

While the community version is mainly used for prototyping and testing, the enterprise version is intended for commercial production use. Due to the service level agreements (SLAs) that are mentioned for the jboss enterprise edition (which centers around the EAP), it is no wonder that commercial customers might require fixes that are not of particular interest for the community edition as the target audience is different.

As the development process is different for both versions, such fixes could be integrated at a later stage into the community edition where the focus lies on different aspects. (e.g. innovating)


问:
Single responsibility vs procedural programming
Single responsibility (from SOLID) is like making me create classes with only one public method. But if it's so, it would be possible use static methods, and go back to procedural programming. What's the difference?</p>

答:
Single responsibility (from SOLID) is like making me create classes with only one public method.

Then you're doing it wrong or need to use a language with good delegate/functor/function object support. Very few responsibilities can be represented with a single pure function.

In languages like Java this can happen because you need to use interfaces to provide different implementations to a single function interface, but in general this should not happen. Certainly you can make everything static functions that just pass data around, and if that's easier, by all means do procedural or functional programming.

But for many problems, having some shared state or some protected invariants make your life easier, and OO does that work well.


答:
The problem with questions like these is in regards to the fact that you're talking about coding style and NOT about code itself; there's nothing inherently wrong with this type of question (I've had debates with colleagues on 'proper' style for years), but it gets into the realm of 'how should I name my functions to best clarify to the user what they do' .. THAT is completely up to you the programmer. It's completely possible to have an object (in the OO realm) that makes since to have both a Print and PrintDocument (maybe the Print function handles some simple stuff for you that PrintDocument does not, or maybe Print prints something to the screen instead of printer). The point is that naming guidelines are just that, guidelines.

Where these kind of naming conventions really make a difference is in the procedural world (non-OO) and more specifically the C language, which, as one user already pointed out, does not support function overloads (i.e. having 2 functions named the same but with different parameters, ex: void Print(void) and void Print(int) would fail in C). In this case where the language itself inhibits you from doing such things it make since to follow some sort of convention. Also, when you're dealing with object oriented programming, you're usually talking about objects with state, at which point functions usually become verbs to the object (i.e. I have an Image object, I would like to print it, so I call img.Print() which acts on the Image object I have .. OO and non-OO aren't that different because the same could be said for PrintImage(Image)), style guidelines are more about HOW the code you're writing is conveyed to the user and that's usually part of the 'design' process in the SDLC.

I've been in both the Linux/Unix kernels, embedded and cloud environments, Java and .NET and I have NEVER seen a single style that makes since. It ALWAYS depends on the scope of project, the team, the language, the intent and IMHO if the developer had enough sleep the night before :) And while you can't always rely on documentation, I do find that if it's available it can give a better understanding of what a function is supposed to do than the function name itself (kernel code and API names can be VERY confusing if you're only going off of the names).

I hope that can help

Title: Why is the following naming guideline different between OO and non-OO languages?

Body:
I am working with a non-OO language and I'm trying to name my routines consistently. I came acrross the following guideline from Steve McConnell's Code Complete:

To name a procedure, use a strong verb followed by an object

McConnell gives the following good and bad examples:

good, non-OO --> PrintDocument(doc)

good, OO -->       doc.Print()

bad, OO -->          doc.PrintDocument()

For an OO language, doc.PrintDocument() is non-recommended on the basis that it is redundant.

I'm having a hard time wrapping my head around this guideline. Why is PrintDocument(doc)recommended, and doc.PrintDocument() non-recommended?

Also, what would be the problem with the simpler name Print(doc) in a non-OO language?

Am I missing something very basic here?


答:
The single responsibility principle doesn't force you to have classes with only one public method. It just states that a class should do one thing, and it should do it well.

For example, a GraphNode could contain public functions to print a description, to rename the node or to rearrange it within its canvas... However, everything related to the edges would be better placed in its own GraphEdge class, even though it might seems that a "few additional edge methods shouldn't disturb anyone."

Another good indicator for classes that commonly violate the SRP are XYZHelpers or ABCManagers classes which oftentimes implement a bunch of different methods that are only remotely related to each other. In most cases, these methods should be re-factored and belong to a specific class, (or a new classes) depending on the scenario.

However, I believe that all patterns, principles and best practices should always be taken with a grain of salt. Although they are unbelievably helpful, blindly applying them without using common sense might do you more harm than good.

Title: Single responsibility vs procedural programming

Body: Single responsibility (from SOLID) is like making me create classes with only one public method. But if it's so, it would be possible use static methods, and go back to procedural programming. What's the difference?</p>


问:
Is it possible to protect json api scraping using random tokens?
I have built a restful json api for an online store using Laravel.

I now wish to create an AngularJS app to run the front-end web application. Product prices for my store need to update every second, so Angular needs to get the product json from the server once per second to update the html.

I wish to somehow do something to protect this publicly accessible json data from being stolen by scrapers / bots repetitively hitting my api to steal my product and pricing data.

My thoughts:

Each json api response contains a random use-once token (i am aware about doing stuff to stop collisions).

This random token is injected via AngularJS into a hidden field within the html page. Angularjs reads the hidden token prior to re-requesting the api and uses this in the header of the next get request.

A json response is only provided with the correct token in the header. Once the token is used, it expires, and any attempt to re-use the expired token, results in that IP address being locked out for a period of time or flagged to administrator to investigate.

Is there a better way of doing the above? Are there any kind of actual available solutions to my problem? Considering that I am paying for the product pricing feed in the first place, I really don't want some schmuck getting it from me for free just because I exposed an api!

Whilst I understand that there is probably no way of being 99% certain that somebody could find a way of scraping my json, there must be something relatively simple I can do to protect my json feed from dumb bots / scrapers simply using curl to steal data.

答:
The short answer is: there is no adequate way to fully protect publicly accessible data from copying.

Cheap loss-less copy is one of main advantages of digital data. Anyone who can access your data is able copy it. And it's not easy to get rid of this ability.

The trick with nonce suggested by you makes scraping a little bit more complex, but not impossible, and even not much harder. A bot can evaluate anything that can be evaluated by a web browser. And in fact, modern bots usually do it. They may run a headless web browser  (like PhantomJS) and "see" pages exactly as user sees. The most advanced bots emulate mouse clicks and randomize delays between actions, so it is very hard to distinguish them from humans.

And if your data is really public (there is no authentication) then there is no strong way to protect it from bots, although you can make their life a little bit harder. it is always a confrontation between a shop’s owner and a bot’s owner. The shop’s owner tries to make the bot more complex and expensive by making data harder to extract. The bot’s developer tries to make the bot more sophisticated. It continues until the bot or protection mechanisms become too costly for someone’s business.

You can use several tricks like data obfuscation, captcha, nonce, some heuristics to detect human activity. It will filter-out most of mass spiders that aren’t developed specially for your web site. If someone is aimed to your shop and develops a scraper specially for it then it is likely that you can’t protect from him.

So I think you should go to the light side and minimize costs by making your JSON API  as simple and straightforward as possible.


问:
Should I pass an object or values?
Let's say I have a model that has 'purchase' method. The purchase method should take care of purchasing a product.

Signature of purchase

```<code>public function purchase($token, Model_Member $member, Model_Product $product, Model_Recipient $recipient);
</code>```

To call this method, I need to make $member, $product, and $recipient in my controller. Is it considered a better approach to pass an array of values to the purchase so that purchase can make those required objects like below?

```<code>public function purchase($token, $member_id, $product_id, array $recipient);
</code>```

in this case, purchase should pull up a member record from the database and make a model of it.

What's the better approach?

答:
Is it considered a better approach to pass an array of values to the
  purchase so that purchase can make those required objects like below?

In general, I would say, no.  But, like everything it depends.

If your domain doing the purchasing is significantly complex, IMHO, it is better to map all data into structures that the domain understands (so in your case, the entities) and then call purchase.

This does a couple of beneficial things.

First, it means that the core business logic (purchasing) does not need the concern of how to hydrate data into objects.  In other words, the domain entities do not need references to repositories.

Second, it means that you can map from many sources (database, web services, file systems) before calling the business domain.  So, this sets up a nice separation of concerns around the core logic of your application.

For more on this.  I recommend reading through the Onion Architecture series of blog posts.

Now, for the "It depends" part:

Every time that you add a logical layer to your application, you add complexity.  In this case, you add the necessity to map into these domain objects before calling purchase.  So, if you are performing simple CRUD operations or forwarding on calls to some web service, then you probably don't need to incur that cost.

OwnerDisplayName: Moon

Title: Should I pass an object or values?


问:
Does Implementing a New Function Imply A New Major Version?
I am currently developing a new library for RESTful web requests in Puredata, and am about to release version 1.0.0. This version will not implement all HTTP verbs, only GET, PUT, POST and DELETE.

In the next version, this library will most likely include the other HTTP verbs for RESTful requests, PATCH, HEAD, OPTIONS, CONNECT, TRACE.

I am using Semantic Versioning for the version numbers.

In the specs it says:

Minor version Y (x.Y.z | x > 0) MUST be incremented if new, backwards compatible functionality is introduced to the public API. It MUST be incremented if any public API functionality is marked as deprecated. It MAY be incremented if substantial new functionality or improvements are introduced within the private code. It MAY include patch level changes. Patch version MUST be reset to 0 when minor version is incremented.

Major version X (X.y.z | X > 0) MUST be incremented if any backwards incompatible changes are introduced to the public API. It MAY include minor and patch level changes. Patch and minor version MUST be reset to 0 when major version is incremented.

Now, I am unsure what to after implementing the remaining verbs: On the one hand, the functionality is backwards compatible, as the already implemented functionality does not change. On the other hand, the functionality is changing, as issuing a HEAD request will not result in an error message on the console, but in an output. In the first case, only an increase to the minor version is needed, in the second case, the major version must be increased.

What is the correct interpretation in this case?

答:
That's mostly a matter of what you consider a minor or major change. If you consider this to be only a minor improvement, you bump the minor version.
If it's a big step you bump the major version.

In this case, (mind that I don't know the library), you probably want to bump the major version number. It looks like a big step when you start supporting different verbs.


问:
What is the difference between 'code readability' and 'language conventions' used within a community?
When I'm looking at questions asked on sites like stackoverflow on how to make a particular piece of code "more pythonic" there are usually suggestions offered to use complex list comprehensions or generators or other python features that aren't available in, say, Java.

I am a casual Python programmer, and sometimes I can't follow what's going on without carefully unwrapping the logic in my head. Sometimes the list comprehensions are nested in ways that I'm thinking "you probably should just write it out using loops".

Of course, veteran Python users probably won't have an issue with this, but I'm increasingly getting the impression that "pythonic code" is preferred over writing code that would be readable for the "average programmer" that may not be very proficient in Python.

In general, what are some guidelines and heuristics to follow when choosing between the readability of the code and following the conventions used in a specific programming language community?

答:
If you're 'carefully unwrapping the logic' to make sense of a line of code, the author missed the boat on being Pythonic.  Being Pythonic isn't about using obscure language features to pack as much code as possible into a line - that's what Perl's for.  Being Pythonic is about keeping code simple, readable and efficient.

>>> import this

The Zen of Python, by Tim Peters

Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

Complex is better than complicated.

Flat is better than nested.

Sparse is better than dense.

Readability counts.

Special cases aren't special enough to break the rules.

Although practicality beats purity.

Errors should never pass silently.

Unless explicitly silenced.

In the face of ambiguity, refuse the temptation to guess.

There should be one-- and preferably only one --obvious way to do it.

Although that way may not be obvious at first unless you're Dutch.

Now is better than never.

Although never is often better than right now.

If the implementation is hard to explain, it's a bad idea.

If the implementation is easy to explain, it may be a good idea.

Namespaces are one honking great idea -- let's do more of those!


问:
Selecting the (right?) application design
While working to build software products for early stage startups, I have seen two very common schools of thought that define an approach to application design.

Those 2 paradigms typically include designing an application predicated on an "extendible codebase” or a "throw away codebase".

What factors should one consider/measure to identify their approach to application design?  What are alternatively ways to think about application design?

Some factors suggested to date include:

the amount of time available to build the product.

the total amount of budget available.

the level of quality.

答:
It depends on how easy it will be to convince the powers that be to throw away the live prototype.

You see as soon as prototype / proof of concept, goes live, it becomes a real live system.  And the "powers that be" will want you to make modifications and changes, and whilst this happens it will gain real world use, and then it is not so easy to replace.

And you make these modifications and fixes, the user base will grow,  and the external quality of the system will improve, and the internal quality will reduce.  And the updates will become harder and harder, and slower and slower, and technical debt will grow and grow.

And you will say,  we need to replace the system, it was only ever supposed to be a proof of concept, and they will say, but it works, and we have spent so much time and money on it,  surely we can continue, and if you fold to the demands,  you will continue, and internal quality will sink and sink, and 1 year from start, they will not even acknowledge that it was a throw away prototype, and you will be lumped with maintenance nightmares, and questions about the quality of your implementation.

I have learned the hard way,  do it right first time.  Some turds are hard to sink.


问:
Examples of Java APIs that demand an action sequence
As part of a research I'm working on, I'm looking for public APIs that only work correctly when you apply a certain sequence of actions on them.

For example, the java.nio.channels.SocketChannel class, from the Java standard library, only works correctly with sequences such as open() -> connect() -> read() -> read() -> close(). A more complete demonstration if how it may be used may be represented in the following graph:

Additional examples of Java standard library APIs that require certain sequences are java.io.PrintStream (very similar to the one above) and java.util.Iterator (which requires a next() call between every two remove() calls, thus enforcing a certain sequence).

So, does you favorite API for doing X also behave that way? I would very much like to know about additional APIs that require a certain method sequence for correct usage; especially classes that are not part of the Java standard library. The more complex the sequence(s) required, the better.

Some APIs require a sequence that spans across multiple classes, for example:

```<code>X x = new X();
x.setup();
Y y = x.createNewY();
Z z = new Z(y);
z.doSomething();
</code>```

These examples are also interesting, but I'm mostly looking for sequences that all appear in the same class.

EDIT added bounty for greater visibility. I'm sure many of you have encountered many APIs that will match this description - I would really appreciate some good examples.

答:
java.sql.ResultSet

contains operations which require a certain order:

move commands (absolute(int row) or next()),

read/write commands (getInt(int columnIndex) or updateInt(int columnIndex, int x)),

write-back-to-datasource commands (updateRow()),

release commands (close()).


问:
Why do programmers use `Acme` as a package, namespace or directory name
This may or may not be a silly question, but I really would like to know the answer to something which has been bothering me for a while.

I quite often see programming examples/conventions where the programmer has created a directory called acme to put stuff in.

What does Acme mean? Why Acme and not Emca or other?

Is Acme like a generic folder name to group miscellaneous OOP classes?

Where did the term come from in terms of the programming convention. As far as I can see, it has nothing to do with a programmer UI http://plan9.bell-labs.com/sys/doc/acme.html

答: It's from Road Runner. The Coyote always orders his traps/weapons from Acme and they all mysteriously backfire. It's since become the defacto namespace for gag packages.


答:
I think this matter only come to client relationship, sometime major mean pay more if you want to update

When come to Developer breaking API should mean changing to major version,

if you really want to implement all verb in one go, then use major version but if you want to push it slowly one verb at a time then minor should be enough

Title: Does Implementing a New Function Imply A New Major Version?

Body:
I am currently developing a new library for RESTful web requests in Puredata, and am about to release version 1.0.0. This version will not implement all HTTP verbs, only GET, PUT, POST and DELETE.

In the next version, this library will most likely include the other HTTP verbs for RESTful requests, PATCH, HEAD, OPTIONS, CONNECT, TRACE.

I am using Semantic Versioning for the version numbers.

In the specs it says:

Minor version Y (x.Y.z | x > 0) MUST be incremented if new, backwards compatible functionality is introduced to the public API. It MUST be incremented if any public API functionality is marked as deprecated. It MAY be incremented if substantial new functionality or improvements are introduced within the private code. It MAY include patch level changes. Patch version MUST be reset to 0 when minor version is incremented.

Major version X (X.y.z | X > 0) MUST be incremented if any backwards incompatible changes are introduced to the public API. It MAY include minor and patch level changes. Patch and minor version MUST be reset to 0 when major version is incremented.

Now, I am unsure what to after implementing the remaining verbs: On the one hand, the functionality is backwards compatible, as the already implemented functionality does not change. On the other hand, the functionality is changing, as issuing a HEAD request will not result in an error message on the console, but in an output. In the first case, only an increase to the minor version is needed, in the second case, the major version must be increased.

What is the correct interpretation in this case?


答:
Some important differences with our team inspection process:

the basis of an inspection is a checklist, compiled by the whole team.

Focus is defects (present and future), not style for the sake of style.

the 3 inspectors (including the author) sit together to run over the comments. Only comments with majority vote remain.