答:
Well, what about O(N) for traversal, O(1) for reversal, but with a special O(N*P) for a calculation before doing any traversals?

In the above, N is the size of the array, P is the number of operations you've performed on the array?

Each operation - a reversal - would push into another array a pair, representing the first and last items to be swapped.

So, given an array ABCDE

we would represent the swap BACDE as

```<code>(1,2)
</code>```

Then we could represent the swap to EDCAB ( a full reversal ) as

```<code>(1,5)
</code>```

However, we won't worry about updating the original array for the transitive period, so we can represent the sequence of events as

```<code>[(1,2),(1,5)]
</code>```

And then a final swap to EDACB as

```<code>(3,4)
</code>```

to give us

```<code>[(1,2),(1,5),(3,4)]
</code>```

Obviously so far we've only had O(1) operations, because each is just an insertion of a tuple into our array. Or list, or whatever.

Finally, to produce the EDACB we get

```<code>[ABCDE] * [(1,2),(1,5),(3,4)]
</code>```

Where for each point in the initial array we determine its new position by

```<code>Xnew = [(1,2),(1,5),(3,4)].Xorig

 = ( (3,4).( (1,5).( (1,2).Xorig)))

 Where each element of our array, the tuple (defined as (α,β), actions like so:

 Xnew = α-Xorig+β
    where  α>Xorig>β (that is, don't do anything if Xorig isn't in (α,β) )
</code>```

So this  will take (all elements in our set) * (number of tuples we have to worry about)

However, you're always going to be dependent on the number of operations you've executed on the array...

There might be a way to break the array into "bits", so for each element in N you apply a discrete value to it (ie if N < 2, +3, if N >= 2 & N < 5 -1, +3) but right now i don't know how you'd do that.

Still, the above will be a lot simpler than writing a new collection, and for small P just as effective.

Title: Reverse subarray of an array with O(1)

Body:
I have an idea how to implement sub array reverse with O(1), not including precalculation such as reading the input. I will have many reverse operations, and I can't use the trivial solution of O(N).

Edit: To be more clear I want to build data structure behind the array with access layer that knows about reversing requests and inverts the indexing logic as necessary when someone wants to iterate over the array.

Edit 2: The data structure will only be used for iterations

I been reading this and this and even this questions but they aren't helping.

There are 3 cases that need to be taking care of:

Regular reverse operation

Reverse that including reversed area

Intersection between reverse and part of other reversed area in the array

Here is my implementation for the first two parts, I will need your help with the last one.

This is the rule class:

```<code>class Rule {
    public int startingIndex;
    public int weight;
}
</code>```

It is used in my basic data structure City:

```<code>public class City {
    Rule rule;
    private static AtomicInteger _counter = new AtomicInteger(-1);
    public final int id = _counter.incrementAndGet();

    @Override
    public String toString() {
        return "" + id;
    }
}
</code>```

This is the main class:

```<code>public class CitiesList implements Iterable<City>, Iterator<City> {

    private int position;
    private int direction = 1;
    private ArrayList<City> cities;
    private ArrayDeque<City> citiesQeque = new ArrayDeque<>();
    private LinkedList<Rule> rulesQeque = new LinkedList<>();

    public void init(ArrayList<City> cities) {
        this.cities = cities;
    }

    public void swap(int index1, int index2){
        Rule rule = new Rule();
        rule.weight = Math.abs(index2 - index1);
        cities.get(index1).rule = rule;
        cities.get(index2 + 1).rule = rule;
    }

    @Override
    public void remove() {
        throw new IllegalStateException("Not implemented");
    }

    @Override
    public City next() {
        City city = cities.get(position);
        if (citiesQeque.peek() == city){
            citiesQeque.pop();
            changeDirection();
            position += (city.rule.weight + 1) * direction;
            city = cities.get(position);
        }
        if(city.rule != null){
            if(city.rule != rulesQeque.peekLast()){
                rulesQeque.add(city.rule);
                position += city.rule.weight * direction;
                changeDirection();
                citiesQeque.push(city);
            }
            else{
                rulesQeque.removeLast();
                position += direction;
            }
        }
        else{
            position += direction;
        }
        return city;
    }

    private void changeDirection() {
        direction *= -1;
    }

    @Override
    public boolean hasNext() {
        return position < cities.size();
    }

    @Override
    public Iterator<City> iterator() {
        position = 0;
        return this;
    }

}
</code>```

And here is a sample program:

```<code>public static void main(String[] args) {
        ArrayList<City> list = new ArrayList<>();
        for(int i = 0 ; i < 20; i++){
            list.add(new City());
        }
        CitiesList citiesList = new CitiesList();
        citiesList.init(list);

        for (City city : citiesList) {
            System.out.print(city + " ");
        }
        System.out.println("\n******************");
        citiesList.swap(4, 8);

        for (City city : citiesList) {
            System.out.print(city + " ");
        }
        System.out.println("\n******************");
        citiesList.swap(2, 15);

        for (City city : citiesList) {
            System.out.print(city + " ");
        }
    }
</code>```

How do I handle reverse intersections?

Body:
Well, what about O(N) for traversal, O(1) for reversal, but with a special O(N*P) for a calculation before doing any traversals?

In the above, N is the size of the array, P is the number of operations you've performed on the array?

Each operation - a reversal - would push into another array a pair, representing the first and last items to be swapped.

So, given an array ABCDE

we would represent the swap BACDE as

(1,2)

Then we could represent the swap to EDCAB ( a full reversal ) as

(1,5)

However, we won't worry about updating the original array for the transitive period, so we can represent the sequence of events as

[(1,2),(1,5)]

And then a final swap to EDACB as

(3,4)

to give us

[(1,2),(1,5),(3,4)]

Obviously so far we've only had O(1) operations, because each is just an insertion of a tuple into our array. Or list, or whatever.

Finally, to produce the EDACB we get

[ABCDE] * [(1,2),(1,5),(3,4)]

Where for each point in the initial array we determine its new position by

Xnew = [(1,2),(1,5),(3,4)].Xorig

 = ( (3,4).( (1,5).( (1,2).Xorig)))

 Where each element of our array, the tuple (defined as (α,β), actions like so:

 Xnew = α-Xorig+β
    where  α>Xorig>β (that is, don't do anything if Xorig isn't in (α,β) )

So this  will take (all elements in our set) * (number of tuples we have to worry about)

However, you're always going to be dependent on the number of operations you've executed on the array...

There might be a way to break the array into "bits", so for each element in N you apply a discrete value to it (ie if N < 2, +3, if N >= 2 & N < 5 -1, +3) but right now i don't know how you'd do that.

Still, the above will be a lot simpler than writing a new collection, and for small P just as effective.


问:
How to improve skills in software architecture
What is the best way to improve your skills in software architecture? We were taught design patterns in university, and I see plenty of books with simple and straight forward examples, but aside from them, how can you learn good architecture? In other words, how does one evolve into a great architect? What are the prerequisites?</p>

答:
Personally, I'd say that I've learned more from sheer trial and error than I have from reading.  You might be surprised at how many of the crazy ideas you have turn out to be good and the number of brilliant ideas that turn out to be terrible.  But you never know that until you try.  This is just as true when you first start writing the code as when you're halfway through it.  Don't stick to an architecture that doesn't work just because it's what you've already decided on.

Lastly, spend the time to think your solution through.  Do your best not to listen to coworkers and managers who pressure you not to think things through and just start coding.

OwnerDisplayName: codetc

ContentLicense: CC BY-SA 2.5


问:
When is it appropriate to use colour in a command-line application?
Currently I have a command-line application in C called btcwatch. It has a -C option that it can receive as an argument that compares the current price of Bitcoin with a price that was stored beforehand with -S. Example output with this option is:

```<code>$ btcwatch -vC  # -v = verbose
buy: UP $ 32.000000 USD (100.000000 -> 132.000000)
sell: UP $ 16.000000 USD (100.000000 -> 116.000000)
</code>```

The dilemma is whether to use colour for the UP or DOWN string (green and red, respectively). Most command-line applications I know of (apart from git) stay away from colour in their output. In my desire for btcwatch to look and be quite "standard" (use of getopt, Makefiles, etc), I'm not sure if colour would look out of place in this situation.

答: The appropriate thing to do is to make the coloring optional, default to "off" and control it via a command-line flag. That way, people who don't like it or whose terminal doesn't support it aren't affected, people who like it can use it, and people who really, really like it can define an alias or shortcut to predefine the option. Everybody's happy.</p>

ContentLicense: CC BY-SA 3.0


问:
Why should I know concurrent programming?
Concurrent programming is quite difficult to me: even looking at a basic slide seems challenging to me. It seems so abstract. </p>

<p>What are the benefits to knowing Concurrent programming concepts well? Will it help me in regular, sequential programming? I know there is a satisfaction to understanding how our programs work, but what else? </p>

答:
I recently had a very interesting task to do in which multiprocessing saved me. I basically had to do a lot of requests to a few separate servers, dealing with very small amounts of data, but many requests.

Working with PHP, I did things the old fashioned way, and the best time I obtained after a few hours of work resulted in ~120 seconds to run a certain test (many requests + network delay + no async)

But that wasn't nearly enough compared to what I needed, and after failing miserably with PHPs multiprocessing, I switched to Python.

After a few hours, I had a running Python multiprocessing script that ran in 20 seconds, and after a bit of fiddling with the timeouts and no. of threads to be used, I got it down to ~10 seconds.

This was for a website written 100% in PHP, except a single, 100 line Python script. And the whole thing is working perfect.

My conclusion would be that even if it won't help you on a day to day basis, you may encounter situations where knowing at least the basics of concurrent programming will help you greatly.

Good luck, and happy coding!

PS: I'm not trying to bash PHP, but PHP simply wasn't the right tool for the job at hand.

PS2: Knowing a new technology, or a new way of doing things can open the door to a whole new world of possibilities.


问:
Find all lines segments intersections
I have a collection of lines segments, represented by an array.

Ex: [3,7,13,6,9] is 4 line segments: [(3,7)(7,13)] , [(7,13)(13,6)] , [(13,6)(6,9)] , ([6,9)(9,3)]

I want to find all the lines segments intersections(not including the common point), is there any better way of doing it rather than brute force(Checking all the options with O(N^2))?

答:
Create a grid, map all the lines to the that grid. For each cell that contains more than one line, validate intersection.

It have O(CN) efficiency, where C is depended by the size of the grid.

Title: Find all lines segments intersections


问:
Does the use of mongodb enhance extending/changing database driven applications?
When an application is created which need to store data, an SQL database is used very often.
So did I in a lot of asp.net applications. The resulting applications have often an ORM like the entity framework and maybe a business layer.

So when such an application needs to be extended(let's say you have to add a comment property to an object), you have to change/extend the database, then the ORM and the business layer and so on.
To deploy the changes you have to update the target database and the application. I know that things like code first and fluent can make this approach easier.

I tried mongodb, I only used the standard driver and I had to extend some objects and all I had to do was changing the code.

So it feels that such approaches are much easier to realize when using mongodb.
I don't have much experience with larger applications an mongodb. I know that a SQL database or mongodb doesn't fit for all needs and both have  their pros and cons.

I want to know if my feeling is right, if yes I would choose rather choose mongodb than SQL database.

答: I find it makes things easier in initial development, but once you get to supporting production it makes things more difficult.  Sure when the data model changes you just change your code, but what do you do with the data in Mongo that still uses the old format?  You either have to write a data model update script pretty much like your SQL schema change script, or your application has to handle every version of the data model that has ever existed.</p>


答:
I would consider it appropriate to use color when:

There are 'groups' of items and color groups will help visually group the items.

There are set(s) of 'label:value' fields and you want the labels (or values) to stand out.

There are items that would benefit from being shown in red/green, e.g. stop/go, good/bad, etc.

Most of the information is background but one key item should stand out.

Title: When is it appropriate to use colour in a command-line application?

Body:
Currently I have a command-line application in C called btcwatch. It has a -C option that it can receive as an argument that compares the current price of Bitcoin with a price that was stored beforehand with -S. Example output with this option is:

```<code>$ btcwatch -vC  # -v = verbose
buy: UP $ 32.000000 USD (100.000000 -> 132.000000)
sell: UP $ 16.000000 USD (100.000000 -> 116.000000)
</code>```

The dilemma is whether to use colour for the UP or DOWN string (green and red, respectively). Most command-line applications I know of (apart from git) stay away from colour in their output. In my desire for btcwatch to look and be quite "standard" (use of getopt, Makefiles, etc), I'm not sure if colour would look out of place in this situation.


答:
No, it is not easier to extend/change the application by choosing mongodb, because you still have a storage mechanism coupled to your logic.  The choice just shuffles the deck, some changes become easier than a RDBMS, some become harder.

Furthermore, it may not be wise to select any storage mechanism based on the ability to extend/change the application, as this road may lead to:

Making a decision on data storage without an evaluation of the storage concerns (the question only lists development concerns).

Coupling the application to this choice, making it more difficult to change if the choice is not correct.

If your feature is that: "A user should be able to comment on an object", then you may want to examine why the implementation would depend on where the object is stored.  Shouldn't this feature function the same way if the object is in memory, in a file, on the moon, or elsewhere?

All that is needed is a storage interface to the object and the comments.  At that point, you can store the objects in memory to run tests, then choose to implement a RDBMS adapter, a noSQL adapter, both, or neither, based on storage needs and not necessarily development time.

Title: Does the use of mongodb enhance extending/changing database driven applications?

Body:
When an application is created which need to store data, an SQL database is used very often.
So did I in a lot of asp.net applications. The resulting applications have often an ORM like the entity framework and maybe a business layer.

So when such an application needs to be extended(let's say you have to add a comment property to an object), you have to change/extend the database, then the ORM and the business layer and so on.
To deploy the changes you have to update the target database and the application. I know that things like code first and fluent can make this approach easier.

I tried mongodb, I only used the standard driver and I had to extend some objects and all I had to do was changing the code.

So it feels that such approaches are much easier to realize when using mongodb.
I don't have much experience with larger applications an mongodb. I know that a SQL database or mongodb doesn't fit for all needs and both have  their pros and cons.

I want to know if my feeling is right, if yes I would choose rather choose mongodb than SQL database.


问:
What is the right level of site blocking for you as a developer?
Almost all developers who work for a large corporation find themselves on the wrong side of site blocking software. It can be both frustrating ("Just let me read that damn blog!") and helpful ("Woah! Dodged a bullet with that site").

In your opinion, what is the right level of blocking to apply to developers and why?

答:
Have levels of privileges
In some cases, usefulness does not apply as criteria for monitoring internet activity.

From limited access upto unrestricted access.

EDIT: Say, Junior-most developers/trainess have no access and no file download rights.

One level up, maybe access to forums and QA sites related to field and/or restricted download bandwidth.

Another level up, no download restrictions but site monitoring.

And even higher, you can decide how much you want to relax for the top management.(most probably unrestricted)

EDIT:
If it were upto me I'd only put restrictions on file download rights. Site monitoring is somewhat self-imposed by the workplace environment, I feel.(Or you can even take a signed undertaking for such things and deal with cases that get extremely out of hand.)
I wouldn't waste time on that. But watching my bandwidth? Yes.


答:
sort the lines by the X of the leftmost point

then for each line look at the next lines and check each of them until the x of their leftmost point is further right than the current line's rightmost point

this will be n*log n best case (for the sorting) but will degenerate into the naive n^2 in bad data sets

Title: Find all lines segments intersections

Body:
I have a collection of lines segments, represented by an array.

Ex: [3,7,13,6,9] is 4 line segments: [(3,7)(7,13)] , [(7,13)(13,6)] , [(13,6)(6,9)] , ([6,9)(9,3)]

I want to find all the lines segments intersections(not including the common point), is there any better way of doing it rather than brute force(Checking all the options with O(N^2))?


答:
One other major factor to consider is that coloring, depending on platform, can add character escape sequences. For builds on those platforms, If the current/default mode is to output colour,  it is customary to detect if the program output is a PIPE and stripping colour if that is the case.

This is so that the color escape sequences do not throw off downstream programs that read it's output.


问:
How to know how much detailed requirements should be?
This doubt has to do with the requirements gathering phase of each iteration in one project based on agile methodologies. It arose because of the following situation: suppose I meet with my customer to gather the requirements and he says something like: "I need to be able to add, edit, remove and see details of my employees".

That's fine, but how should we register this requirement? Should we simply write something like "the system must allow the user to manage employees", or should we be more specific writing for points

The system must allow the user to add employees;

The system must allow the user to see details of employees;

The system must allow the user to edit employees;

The system must allow the user to delete employees;

Of course, this is just an example of a situation I was in doubt. The main point here is: how to know how much detailed I must be, and how to know what I should register? Are there strategies for dealing with these things?

Thanks very much in advance!

答:
The goal is to (1) deliver a system that satisfies the customer and (2) ensure the people using the requirements have everything they need. Provide the minimal detail level that performs both and you have answered your question.

More specifically, does your organization have any requirements standards? I assume not from your question but common templates or previous requirements documents may imply the level of detail required. Ask senior people in your organization, too.

Who will be using the requirements, such as developers, UX and QA? In your example, how much do they know about employees? Have they been working on similar systems for years and probably know it better than the customer or are they new to this type of system? For example, will they know what fields an employee has and their validation rules? If not, include these. See below for more examples.

What level of acceptance requirement detail does the customer require? Are they willing to experiment with several build/measure/learn cycles (less detail) or do they have detailed and strict compliance requirements (more detail)?

Capture when a requirement is not important (e.g. no system up time requirements) because the lack of a requirement can be just as important.

Requirements can be specified in different ways. Many prefer user stories or use cases. A UML sequence or activity diagram may be better for complex processes. Communicating requirements well is just as important as ensuring they are complete and consistent.

Not all requirements are suitable for all audiences. For example, customers confirming the system meets their requirements will likely want different information to developers doing the low level implementation. Consider splitting large lists into smaller ones for various audiences.

Beyond this and perhaps slightly off topic, requirements gathering is more than just specifying what the customer asks and to what level of detail. What requirements can you add? For example (hardly a definitive list):

Will employees be added in bulk? If so, does the UI need a bulk addition option (e.g. a table) instead of a form? Can they be imported form an HR system instead?

Who will enter the employee details? Who should not be allowed to see employee data? Who authorizes new users and removes old ones? If someone makes a change, does it need to be audited? How long should the audit logs be retained?  Do changes need to be approved by others?

How many employee records will there be? Ten? Ten thousand? Ten million? How will they be searched, sorted and filtered? How many people will be accessing the system simultaneously?

Where will the employee details be entered from? A web browser on a desktop computer in the organization's office or a mobile device used by the site foreman at a construction site?

What is the impact of the system going down? Can I patch the systems during business hours?

Are there reasons why I could not consider an "off the shelf" system instead of writing it ourselves?

Does the customer require I follow any standards, e.g. Common Criteria, FIPS 140, ISO 27001? Is there contractual or legal requirements for retention or privacy?

Organizations often impose implicit requirements. For example, can the project's costs and timeline be estimated from the requirements? If not, what is missing? How does this fit into my organizations technology strategy?

Are there any constraints on development, such as fixed deadlines, budget limits or technology constrains?

This really adds value, particularly when requirements gathering becomes a two-way conversation with customers.


答:
Lets take a slightly different set, one that has an intersection in it.

[3, 7, 13, 4, 11]

This generates the set of lines of:

```
{3,7}  {7,13}
{7,13} {13,4}
{13,4} {4,11}
{4,11} {11,3}
```

Lets assume a pre-existing function boolean intersect(x1, y1, x2, y2) (the math for this can be found on wikipedia, or various stack overflow questions - note that you want line segment intersection rather than a generic line intersection).

We are also going to take the set of lines and sort them by the left most X value and then rightmost X value ({4,11} {11,3} sorts before {4,11}, {13,4}).

```
{3,7}  {7,13}
{4,11} {11,3}
{4,11} {13,4}
{7,13} {13,4}
```

Now, adding line by line to a queue in sorted order.

Each time a line is to be added to the queue, check for intersections against all lines currently in the queue.

```
queue: empty
test:  none
add:   {3,7}  {7,13}
----
queue: (1) {3,7}  {7,13}
test:  1: intersects
add:   {4,11} {11,3}
---
queue: (1) {3,7}  {7,13}
       (2) {4,11} {11,3}
test:  1: intersects
       2: does not intersect
add:   {4,11} {13,4}
```

Furthermore, prior to running the tests, if the leftmost X value is equal to or greater than the rightmost X value of the first element in the queue, remove that element from the queue.

```
queue: (1) {3,7}  {7,13}
       (2) {4,11} {11,3}
       (3) {4,11} {13,4}

{7,13} >= {7,13} - drop #1

queue: (2) {4,11} {11,3}
       (3) {4,11} {13,4}

test:  2: does not intersect
       3: does not intersect
add:   {7,13} {13,4}
```

This is implementing a sweep line algorithm that is only concerning itself with the line segments that could possibly intersect with the list of line segments. Note the section on Applications that mentions Shamos and Hoey with an algorithm for  identifying line segment intersections on a plane (exactly this problem).  The full pseudo code is described at Intersections of a Set of Segments.  You can see code for this on CodeReview.SE - Is this implementation of Shamos-Hoey Algorithm OK? and Stack Overflow - Implementing Hoey Shamos algorithm with C#.  A handout on this from Tufts University
Line Segment Intersection Using a Sweep Line Algorithm goes into this and explains the various complexity and some further applications.

Note that the structures here can be simplified by using your own sorted list.  The queue is a useful visualization, but the sorted list itself can be used by maintaining two indexes which identify the window of line segments to test.  Instead of adding an element to the queue, the high end of the frame is incremented.  Instead of removing an element from the queue, the low end of the frame is incremented.

Title: Find all lines segments intersections

Body:
Lets take a slightly different set, one that has an intersection in it.

[3, 7, 13, 4, 11]

This generates the set of lines of:

{3,7}  {7,13}
{7,13} {13,4}
{13,4} {4,11}
{4,11} {11,3}

Lets assume a pre-existing function boolean intersect(x1, y1, x2, y2) (the math for this can be found on wikipedia, or various stack overflow questions - note that you want line segment intersection rather than a generic line intersection).

We are also going to take the set of lines and sort them by the left most X value and then rightmost X value ({4,11} {11,3} sorts before {4,11}, {13,4}).

{3,7}  {7,13}
{4,11} {11,3}
{4,11} {13,4}
{7,13} {13,4}

Now, adding line by line to a queue in sorted order.

Each time a line is to be added to the queue, check for intersections against all lines currently in the queue.

queue: empty
test:  none
add:   {3,7}  {7,13}
----
queue: (1) {3,7}  {7,13}
test:  1: intersects
add:   {4,11} {11,3}
---
queue: (1) {3,7}  {7,13}
       (2) {4,11} {11,3}
test:  1: intersects
       2: does not intersect
add:   {4,11} {13,4}

Furthermore, prior to running the tests, if the leftmost X value is equal to or greater than the rightmost X value of the first element in the queue, remove that element from the queue.

queue: (1) {3,7}  {7,13}
       (2) {4,11} {11,3}
       (3) {4,11} {13,4}

{7,13} >= {7,13} - drop #1

queue: (2) {4,11} {11,3}
       (3) {4,11} {13,4}

test:  2: does not intersect
       3: does not intersect
add:   {7,13} {13,4}

This is implementing a sweep line algorithm that is only concerning itself with the line segments that could possibly intersect with the list of line segments. Note the section on Applications that mentions Shamos and Hoey with an algorithm for  identifying line segment intersections on a plane (exactly this problem).  The full pseudo code is described at Intersections of a Set of Segments.  You can see code for this on CodeReview.SE - Is this implementation of Shamos-Hoey Algorithm OK? and Stack Overflow - Implementing Hoey Shamos algorithm with C#.  A handout on this from Tufts University
Line Segment Intersection Using a Sweep Line Algorithm goes into this and explains the various complexity and some further applications.

Note that the structures here can be simplified by using your own sorted list.  The queue is a useful visualization, but the sorted list itself can be used by maintaining two indexes which identify the window of line segments to test.  Instead of adding an element to the queue, the high end of the frame is incremented.  Instead of removing an element from the queue, the low end of the frame is incremented.


问:
How do I set up pairing email addresses?
Our team uses the Ruby gem hitch to manage pairing. You set it up with a group email address (e.g. dev@mycompany.com) and then tell it who is pairing:

```<code>$ hitch james tiffany
</code>```

Hitch then sets your Git author configuration so that our commits look like

```<code>commit 629dbd4739eaa91a720dd432c7a8e6e1a511cb2d
Author: James and Tiffany <dev+james+tiffany@mycompany.com>
Date:   Thu Oct 31 13:59:05 2013 -0700
</code>```

Unfortunately, we've only been able to come up with two options:

dev@mycompany.com doesn't exist. The downside is that if Travis CI tries to notify us that we broke the build, we don't see it.

Dev@mycompany.com does exist and forwards to all the developers. Now the downside is that everyone gets spammed with every broken build by every pair.

We have too many possible pair to do any of the following:

set up actual pair-james-tiffany@mycompany.com email addresses or groups (n^2 email addresses)

set up forwarding rules for dev+james+tiffany@mycompany.com (n^2 forwarding rules)

set up forwarding rules for james+tiffany@mycompany.com (n forwarding rules for each of n developers)

Does anyone have a system that works for them?

EDIT

I obviously missed a very important piece: we use GMail Business for all our company mail. We can add and remove users and groups, and users can create filters, but we don't have control over the MTA itself.

答:
Many sufficiently advanced mail processing applications (I'm looking at procmail at the moment, though I'm certain this can also be done with outlook email rules too) have the ability to do custom rules.  Or it could be as simple as using a .forward file with |program as the contents.

The approach is essentially set up dev as an account, but set up a program to receive and then resend email.

When the system sees the comment part of the email address of "+alice+bob" it would then split out the names, and then forward the mail appropriately to alice@company.com and bob@company.com.

Depending on the company and how tightly bound the mail server is to the IT department, Postfix or exim: Automated/Programmatic and forwarded email setup on ServerFault touches on using postfix to do the appropriate rules, or write some procmail rules, or outlook rules, or a program that takes the mail message and resends it to the appropriate people.

Noting the Ruby the following two bits may be of use in implementing the last part of the solution:

Net::IMAP

How to send email via smtp with Ruby's mail gem?

Also look at WebApps.StackExchange gmail and gmail-filters tags for the possibility of adding the appropriate filters in gmail itself.


问:
Why do many PHP Devs hate using isset() and/or any of PHP's similarly defensive functions like empty()?
Over on stackoverflow, I see this issue crop up all the time:

E_NOTICE ?== E_DEBUG, avoiding isset() and @ with more sophisticated error_handler

How to set PHP not to check undefind index for $_GET when E_NOTICE is on?

How to stop PHP from logging PHP Notice errors

How do I turn off such PHP 5.3 Notices ?

Even Pekka (who offers a lot of solid PHP advice) has bumped against the dreaded E_NOTICE monster and hoped for a better solution than using isset(): isset() and empty() make code ugly

Personally, I use isset() and empty() in many places to manage the flow of my applications.  For example:

```<code>public function do_something($optional_parameter = NULL) {
    if (!empty($optional_parameter)) {
        // do optional stuff with the contents of $optional_parameter
    }
    // do mandatory stuff
}
</code>```

Even a simple snippet like this:

```<code>if (!isset($_REQUEST['form_var'])) {
    // something's missing, do something about it.
}
</code>```

seems very logical to me.  It doesn't look like bloat, it looks like stable code.  But a lot of developers fire up their applications with E_NOTICE's enabled, discover a lot of frustrating "uninitialized array index" notices, and then grimace at the prospect of checking for defined variables and "littering" their code with isset().

I assume other languages handle things differently.  Speaking from experience, JavaScript isn't as polite as PHP.  An undefined variable will typically halt the execution of the script.  Also, (speaking from inexperience) I'm sure languages like C/C++ would simply refuse to compile.

So, are PHP devs just lazy?  (not talking about you, Pekka, I know you were refactoring an old application.)  Or do other languages handle undefined variables more gracefully than requiring the programmer to first check if they are defined?

(I know there are other E_NOTICE messages besides undefined variables, but those seem to be the ones that cause the most chagrin)

Addendum

From the answers so far, I'm not the only one who thinks isset() is not code bloat.  So, I'm wondering now, are there issues with programmers in other languages that echo this one?  Or is this solely a PHP culture issue?

答:
One of the questioned questions is mine, so let me reiterate.

Many developers mistake the presence of lot of isset() as quality sign. It gives an appearance of reliability and some people think of it even as security feature.

But you have to take into account that PHP is not a compiled language. It's a scripting language with a dynamic type system. E_NOTICE errors are only errors by name. And if lots of isset are used with the sole intention of suppressing the notices, then you are actually just coding against the language.

So, are PHP devs just lazy?

That is indeed the case if you see an abundance of notices and warnings thrown. Lot's of newbies don't care about notices, and it's usually the result of a completely disabled error_reporting(0).

You are however mistaken that other developers didn't recognize E_NOTICEs just because they weren't @ or isset-suppressed. At least that was my intention behind the retaining notices question. They aren't something to get rid of, but occasionally important debug info.

Like all generalizations, the inconsiderate use of isset doesn't lead to optimal code. It's important to differentiate where isset and empty are necessary and where they are syntactic salt.

Or is this solely a PHP culture issue?

No, undefined variable "errors" are not a PHP problem alone. Bash, TCL and Perl or JavaScript allow the use of undefined variables. This immanent language feature isn't seen as defect there however. There are similar language constructs to check for undefined values. However they aren't as constantly used as in PHP, due to undef values not being mischaracterized as "error".


答:
Email to user+param - passing param to scripts (Unix/Linux)

Your MTA may deliver dev+james+tiffany@mycompany.com via procmail (~dev/.procmailrc) with james+tiffany in $1.

~/dev/procmailrc may execute any program/script you like with $1 (james+tiffany as parameter) after some sanity checks.

AFAIK On most linuxes with sendmail as MTA and installed procmail all you need only to configure procmail (~dev/.procmailrc).

Do you use Linux/Unix mail server?  Which MTA do you use? (sendmail/postfix/exim/...)  Have you installed procmail?

Title: How do I set up pairing email addresses?

Body:
Our team uses the Ruby gem hitch to manage pairing. You set it up with a group email address (e.g. dev@mycompany.com) and then tell it who is pairing:

```<code>$ hitch james tiffany
</code>```

Hitch then sets your Git author configuration so that our commits look like

```<code>commit 629dbd4739eaa91a720dd432c7a8e6e1a511cb2d
Author: James and Tiffany <dev+james+tiffany@mycompany.com>
Date:   Thu Oct 31 13:59:05 2013 -0700
</code>```

Unfortunately, we've only been able to come up with two options:

dev@mycompany.com doesn't exist. The downside is that if Travis CI tries to notify us that we broke the build, we don't see it.

Dev@mycompany.com does exist and forwards to all the developers. Now the downside is that everyone gets spammed with every broken build by every pair.

We have too many possible pair to do any of the following:

set up actual pair-james-tiffany@mycompany.com email addresses or groups (n^2 email addresses)

set up forwarding rules for dev+james+tiffany@mycompany.com (n^2 forwarding rules)

set up forwarding rules for james+tiffany@mycompany.com (n forwarding rules for each of n developers)

Does anyone have a system that works for them?

EDIT

I obviously missed a very important piece: we use GMail Business for all our company mail. We can add and remove users and groups, and users can create filters, but we don't have control over the MTA itself.


问:
Parallel.For Inconsistency results
I am using VB.net to write a parallel based code. I use Parallel.For to generate pairs of 500 objects or in combination C(500,2) such as the following code; but I found that it didn't always generate all combinations which should be 124750 (shown from variable Counter). No other thread was runing when this code was run. I am using a Win-7 32 Bit desktop with Intel Core i5 CPU 650@3.2GHz, 3.33 GHz and RAM 2GB. What's wrong with the code and how to solve this problem? Thank You.

```<code>    Dim Counter As Integer = 0
    Parallel.For(0, 499, Sub(i)
                     For j As Integer = i + 1 To 499
                         Counter += 1
                         Console.Write(i & ":" & j)
                     Next
                 End Sub)
    Console.Writeline("Iteration number: " & Counter)
</code>```

答:
It is not that all were not generated, is it that the counter got broken. You encountered classic read/write race condition.

You should use atomic increment to solve the problem.

Also, printing is really slow and locks internally. So you are not going to gain any performance using parallelism this way.

But, this is basic knowledge. You should not, under any scenario, try to parallelize your code if you don't have this knowledge.

Title: Parallel.For Inconsistency results


答:
Parallel.For uses a thread pool to process your loop. As soon as one of its threads is free, it assigns it to the next element.

It's a common problem : calling something like count++ on a shared variable from multiple threads.

Thread #1 reads the value of count.

Thread #2 reads the value of count.

Thread #1 increments its local copy.

Thread #2 increments its local copy.

Thread #1 writes the incremented value back to count.

Thread #2 writes the incremented value back to count.

This way, the value written by thread #1 is overwritten by thread #2, so the value is actually incremented only once.

What you need to do is to "lock" count++ or use Interlocked class.

```<code>lock (lockObject)
{
     Counter += 1
}
</code>```

Title: Parallel.For Inconsistency results

Body:
I am using VB.net to write a parallel based code. I use Parallel.For to generate pairs of 500 objects or in combination C(500,2) such as the following code; but I found that it didn't always generate all combinations which should be 124750 (shown from variable Counter). No other thread was runing when this code was run. I am using a Win-7 32 Bit desktop with Intel Core i5 CPU 650@3.2GHz, 3.33 GHz and RAM 2GB. What's wrong with the code and how to solve this problem? Thank You.

```<code>    Dim Counter As Integer = 0
    Parallel.For(0, 499, Sub(i)
                     For j As Integer = i + 1 To 499
                         Counter += 1
                         Console.Write(i & ":" & j)
                     Next
                 End Sub)
    Console.Writeline("Iteration number: " & Counter)
</code>```

Body:
Parallel.For uses a thread pool to process your loop. As soon as one of its threads is free, it assigns it to the next element.

It's a common problem : calling something like count++ on a shared variable from multiple threads.

Thread #1 reads the value of count.

Thread #2 reads the value of count.

Thread #1 increments its local copy.

Thread #2 increments its local copy.

Thread #1 writes the incremented value back to count.

Thread #2 writes the incremented value back to count.

This way, the value written by thread #1 is overwritten by thread #2, so the value is actually incremented only once.

What you need to do is to "lock" count++ or use Interlocked class.

lock (lockObject)
{
     Counter += 1
}


问:
Calculating WPM given a variable stream of input
I'm creating an application that sits in the background and records all key presses (currently this is done and working; an event is fired every keydown/keyup).  I want to offer a feature for the user that will show them their WPM over the entire session the program has been running for.  This would be easy if I added a "Start" and "End" button to activate a timer, but I need to detect only when the user is typing continuously - ignoring all one-time keyboard shortcuts and breaks the user takes from typing.

How in the world do I approach this?  Is this even realistically & accurately possible?

答:
You could simply have a built-in in timer delay function which fires when a given time has passed since the last key-press. Once the user starts typing again, the timer un-pauses and continues. The given timer could be something like 2 seconds, which is a reasonable delay for most computer literate people. Once the timer starts again, just subtract that 2 seconds given time from the timer so the WPM isn't thrown off.

Keyboard shortcuts may be the harder issue. Something like every keypress event fires a lookup in a table somewhere checking to see if a keyboard shortcut was pressed do nothing, if not, increment the global character counter.


问:
What are the types of dynamically typed languages arrays?
For example, in JavaScript, I can do such things:

```<code>var arr = [1, "two", /three/, [4]];
</code>```

There is no way to do such a thing in C! Except by using a void*, which is not an efficient/safe way.

Is this how implementations do it? Using void* everywhere?

答:
It is overly naive to think that typing an array to void** will make your code less efficient, then say, int*. This is because the compiler today are often smart enough to manipulate the data behind the scenes in ways a programmer may not anticipate. Of course, some compilers are smarter then others, but it's getting incrementally better, and we are nowhere near the climax of art of compiler writing. We are probably somewhere in the very beginning of the road.

There also may be many other factors in play, such as how exactly the runtime allocates its objects (does it fragment them or not, how does it align them etc.). In what part of the memory do these objects land (memory may have all sorts of structures, hierarchies, different devices may have their own memory etc.) and most important of all: how your code handles them.

Now, from the perspective of type theory, "dynamically typed" is a misconception. There are untyped languages (even better named "languages where all data are of the same type") and there are languages where types are checked at various stages of the program creation cycle. The types can be often checked during compilation (if this is at all a step in the program livecycle), upon loading the program, "dynamically" (that is applying some heuristic after loading the program, based no the program's usage).

However, "dynamic language" is a terminology often found in special literature, different researchers assign different meanings to it, relating to different aspects of the program. By some standards, Java may be called a dynamic language (because it needs to take certain amount of decisions required for method dispatch at run time, for example). But some would not call Common Lisp a dynamic language because it verifies types during the compilation.

So, if anything, I'd avoid using "dynamic language" in an academic setting until further notice :)


答:
Network. Get to know some good architects. Talk to them. Learn from them, and bounce ideas off of them.

Read voraciously. There are hundreds of books on software architecture (several good ones even). Read on topic, and read related topics (building architecture, management structures, electrical engineering, operational architecture, etc.).

Study architecture.  There are thousands of platforms and products out there. Look at them. Dissect their parts. Some of my best learning early on was from looking at great architectures (look at the little languages, packed files, and simple structures in the original Doom source, for example).

Think, sketch, try. Practice your design skills on imaginary problems. Fun problems. Interesting problems.

Do. Work on real systems. Ship them. Feel the pain caused by your poor decisions, the pain you cause your developers, and learn from it.  Good architecture is in balancing what you get, how you get there, and how much it costs.

Title: How to improve skills in software architecture

Body: What is the best way to improve your skills in software architecture? We were taught design patterns in university, and I see plenty of books with simple and straight forward examples, but aside from them, how can you learn good architecture? In other words, how does one evolve into a great architect? What are the prerequisites?</p>


问:
Is it reasonable to null guard every single dereferenced pointer?
At a new job, I've been getting flagged in code reviews for code like this:

```<code>PowerManager::PowerManager(IMsgSender* msgSender)
  : msgSender_(msgSender) { }

void PowerManager::SignalShutdown()
{
    msgSender_->sendMsg("shutdown()");
}
</code>```

I'm told that last method should read:

```<code>void PowerManager::SignalShutdown()
{
    if (msgSender_) {
        msgSender_->sendMsg("shutdown()");
    }
}
</code>```

i.e., I must put a NULL guard around the msgSender_ variable, even though it is a private data member. It's difficult for me to restrain myself from using expletives to describe how I feel about this piece of 'wisdom'. When I ask for an explanation, I get a litany of horror stories about how some junior programmer, some-year, got confused about how a class was supposed to work and accidentally deleted a member he shouldn't have (and set it to NULL afterwards, apparently), and things blew up in the field right after a product release, and we've "learned the hard way, trust us" that it's better to just NULL check everything.

To me, this feels like cargo cult programming, plain and simple. A few well-meaning colleagues are earnestly trying to help me 'get it' and see how this will help me write more robust code, but... I can't help feeling like they're the ones who don't get it.

Is it reasonable for a coding standard to require that every single pointer dereferenced in a function be checked for NULL first—even private data members? (Note: To give some context, we make a consumer electronics device, not an air traffic control system or some other 'failure-equals-people-die' product.)

EDIT: In the above example, the msgSender_ collaborator isn't optional. If it's ever NULL, it indicates a bug. The only reason it is passed into the constructor is so PowerManager can be tested with a mock IMsgSender subclass.

SUMMARY: There were some really great answers to this question, thanks everyone. I accepted the one from @aaronps chiefly due to its brevity. There seems to be fairly broad general agreement that:

Mandating NULL guards for every single dereferenced pointer is overkill, but

You can side-step the whole debate by using a reference instead (if possible) or a const pointer, and

assert statements are a more enlightened alternative to NULL guards for verifying that a function's preconditions are met.

答:
I feel the code should read:

```<code>PowerManager::PowerManager(IMsgSender* msgSender)
  : msgSender_(msgSender)
{
    assert(msgSender);
}

void PowerManager::SignalShutdown()
{
    assert(msgSender_);
    msgSender_->sendMsg("shutdown()");
}
</code>```

This is actually better than guarding the NULL, because it makes it very clear that the function should never be called if msgSender_ is NULL. It also makes sure that you'll notice if this happens.

The shared "wisdom" of your colleagues will silently ignore this error, with unpredictable results.

In general bugs are easier to fix if they're detected closer to their cause. In this example the proposed NULL guard would lead to a shutdown message not getting set, which may or may not result in a noticeable bug. You'd have a harder time working backwards to the SignalShutdown function than if the entire application just died, producing a handy-dandy backtrace or core dump pointing directly to SignalShutdown().

It's a little counterintuitive, but crashing as soon as anything is wrong tends to make your code more robust. That's because you actually find the problems, and tends to have very obvious causes as well.

Body:
I feel the code should read:

PowerManager::PowerManager(IMsgSender* msgSender)
  : msgSender_(msgSender)
{
    assert(msgSender);
}

void PowerManager::SignalShutdown()
{
    assert(msgSender_);
    msgSender_->sendMsg("shutdown()");
}

This is actually better than guarding the NULL, because it makes it very clear that the function should never be called if msgSender_ is NULL. It also makes sure that you'll notice if this happens.

The shared "wisdom" of your colleagues will silently ignore this error, with unpredictable results.

In general bugs are easier to fix if they're detected closer to their cause. In this example the proposed NULL guard would lead to a shutdown message not getting set, which may or may not result in a noticeable bug. You'd have a harder time working backwards to the SignalShutdown function than if the entire application just died, producing a handy-dandy backtrace or core dump pointing directly to SignalShutdown().

It's a little counterintuitive, but crashing as soon as anything is wrong tends to make your code more robust. That's because you actually find the problems, and tends to have very obvious causes as well.


答:
It depends on the 'contract':

If PowerManager MUST have a valid IMsgSender, never check for null, let it die sooner.

If on the other hand, it MAY have a IMsgSender, then you need to check every time you use, as simple as that.

Final comment about the story of the junior programmer, the problem is actually the lack of testing procedures.

Title: Is it reasonable to null guard every single dereferenced pointer?

Body:
At a new job, I've been getting flagged in code reviews for code like this:

```<code>PowerManager::PowerManager(IMsgSender* msgSender)
  : msgSender_(msgSender) { }

void PowerManager::SignalShutdown()
{
    msgSender_->sendMsg("shutdown()");
}
</code>```

I'm told that last method should read:

```<code>void PowerManager::SignalShutdown()
{
    if (msgSender_) {
        msgSender_->sendMsg("shutdown()");
    }
}
</code>```

i.e., I must put a NULL guard around the msgSender_ variable, even though it is a private data member. It's difficult for me to restrain myself from using expletives to describe how I feel about this piece of 'wisdom'. When I ask for an explanation, I get a litany of horror stories about how some junior programmer, some-year, got confused about how a class was supposed to work and accidentally deleted a member he shouldn't have (and set it to NULL afterwards, apparently), and things blew up in the field right after a product release, and we've "learned the hard way, trust us" that it's better to just NULL check everything.

To me, this feels like cargo cult programming, plain and simple. A few well-meaning colleagues are earnestly trying to help me 'get it' and see how this will help me write more robust code, but... I can't help feeling like they're the ones who don't get it.

Is it reasonable for a coding standard to require that every single pointer dereferenced in a function be checked for NULL first—even private data members? (Note: To give some context, we make a consumer electronics device, not an air traffic control system or some other 'failure-equals-people-die' product.)

EDIT: In the above example, the msgSender_ collaborator isn't optional. If it's ever NULL, it indicates a bug. The only reason it is passed into the constructor is so PowerManager can be tested with a mock IMsgSender subclass.

SUMMARY: There were some really great answers to this question, thanks everyone. I accepted the one from @aaronps chiefly due to its brevity. There seems to be fairly broad general agreement that:

Mandating NULL guards for every single dereferenced pointer is overkill, but

You can side-step the whole debate by using a reference instead (if possible) or a const pointer, and

assert statements are a more enlightened alternative to NULL guards for verifying that a function's preconditions are met.


答:
No, it is not reasonable to check each and every pointer dereference for the pointer being NULL.

Null-pointer checks are valuable on function arguments (including constructor arguments) to ensure preconditions are met or to take appropriate action if an optional parameter is not provided, and they are valuable to check a class's invariant after you have exposed the class's internals. But if the only reason for a pointer to have become NULL is the existence of a bug, then there is no point in checking. That bug could just as easily have set the pointer to another invalid value.

If I were faced with a situation like yours, I would ask two questions:

Why was the mistake from that junior programmer not caught before the release? For example in a code review or in the testing phase? Bringing a faulty consumer electronics device to the market can be just as costly (if you take market share and goodwill into account) as releasing a faulty device used in a safety-critical application, so I would expect the company to be serious about testing and other QA activities.

If the null-check fails, what error handling do you expect me to put in place, or could I just write assert(msgSender_) instead of the null check? If you just put the null check in, you might have prevented a crash, but you might have created a worse situation because the software continues on the premise that an operation has taken place while in reality that operation was skipped. This might lead to other parts of the software becoming unstable.


答:
If msgSender must never be null, you should put the null check only in the constructor. This is also true for any other inputs into the class - put the integrity check at the point of entry into the 'module' - class, function etc.

My rule of thumb is to perform integrity checks between module boundaries - the class in this case. In addition, a class should be small enough that it is possible to quickly mentally verify the integrity of the lifetimes of the class members - ensuring that such mistakes as improper deletes / null assignments are prevented. The null check that is performed in the code in your post assumes that any invalid usage actually assigns null to the pointer - which is not always the case. Since 'invalid usage' inherently implies that any assumptions about regular code does not apply, we cannot be sure to catch all types of pointer errors - for example an invalid delete, increment etc.

In addition - if you are certain the argument can never be null, consider using references, depending on your usage of the class. Otherwise, consider using std::unique_ptr or std::shared_ptr in lieu of a raw pointer.


问:
Class diagrams - do aggregated/composed classes automatically see each other?
Let's say that in the game, a player has a pet:

Player<>------Pet

Obviously player can access Pet's fields and methods, but I assume Pet does not know about the player?
I need that Pet can access the player as well, how should I model that?

答:
In UML, an aggregation relationship has a directionality, which can be

uni-directional, where the Player knows about the Pet, but not the other way around. This is usually indicated with an arrow on the end of the line:

Player <>------> Pet

bidirectional, where both the Player and the Pet can access each other. This is usually indicated by the absence of an arrow (like you used in the question):

Player <>------- Pet

In most programming languages, there is no real equivalent of the bidirectional relation, so it is usually emulated by using two uni-directional relations (pointers/references) and a bit of logic to ensure that if you follow both links, you end up back in the same object.


答:
The reason that you're asked to avoid null dereferences is to ensure that your code is robust.  Examples of junior programmers long long ago are just examples.  Anyone can break the code by accident and cause a null dereference - especially for globals and class globals.  In C and C++ it's even more possible accidentally, with the direct memory management capability.  You might be surprised, but this kind of thing happens very often. Even by very knowledgeable, very experienced, and very senior developers.

You don't need to null check everything,  but you do need to protect against dereferences that have decent likelihood of being null.  This is commonly when they are allocated, used and dereferenced in different functions.  It is possible that one of the other functions will be modified and break your function.  It is also possible that one of the other functions may be called out of order (like if you have a deallocator that can be called separately from the destructor).

I prefer the approach your coworkers are telling you in combination with using assert.  Crash in the test environment so it's more obvious that there's a problem to fix and fail gracefully in production.

You should also be using a robust code correctness tool like coverity or fortify. And you should be addressing all compiler warnings.

Edit: as others have mentioned, silently failing, as in several of the code examples, is generally the wrong thing, as well.  If your function cannot recover from the value being null, it should return an error (or throw an exception) to its caller.  The caller is responsible for then either fixing its call order, recovering, or returning an error (or throwing an exception) to its caller, and so on.  Eventually, either a function is able to gracefully recover and move on, gracefully recover and fail (such as a database failing a transaction because of an internal error for one user but not acutally exiting), or the function determines that the application state is corrupt and unrecoverable and the application exits.


问:
Why do large IT projects tend to fail or have big cost/schedule overruns?
I always read about large scale transformation or integration project that are total or almost total disaster. Even if they somehow manage to succeed  the cost and schedule blow out is enormous. What is the real reason behind large projects being more prone to failure. Can agile be used in these sort of projects or traditional approach is still the best.

One example from Australia is the Queensland Payroll project where they changed test success criteria to deliver the project.

See some more failed projects in this SO question (on Wayback Machine)

Have you got any personal experience to share?

答:
Software projects of all sizes "tend to fail" or "have cost overruns." You don't hear about the cost overrun at the business around the corner, but you do hear about things like the FBI Virtual Case system, or the Denver Airport baggage handling system. So I will make the claim that not all large systems fail, nor do all large systems have cost/schedule overruns.

I've come across large systems that came in on time (the schedule moved once and only once during the project) and on spec (I had no access to budgetary information as we were just 1 of many suppliers). One that impresses me still (and I've written a bit about it on this site) was a large integrated customer management system for a large (in the first 100 of the fortune 500) financial client. I estimate that they blew about $100k/day (for more than a year) on peoples' salaries during conference calls.

In the case of the baggage handling system, the software managers said "based on projects of this size and complexity, it will take 4 years to build and debug this system." The sales and executive managers said "the airport opens in 2 years, we told the client it will take 2 years, so you have 2 years to do it." The test to see if you are a programmer or a mismanager is a simple answer to the following question: "was the baggage handling system late or on time?"

If the customer knows exactly what they want (and very few do), they will be very far along the path to keeping costs and time under control (and these are the folks who tend to do quite well offshoring). If your project has to meet every single possible feature that your customers can possibly dream up, and every single department has veto power over when their pet goldbricks get added to the project, then you are doomed to abject failure from the start (like the FBI's VCF project).


问:
Python scripts link to GUI using an IDE
I am studying python. Now I can write python scripts(codes) to some extent.
I am interested in making GUI to those written programs.I like to do it using an IDE rather than using PyGTK or Tkinter.
Can anyone help me how to start with this and link my scripts to a GUI.
I downloaded a IDE called "glade". But I don't know how to use this IDE.
I need some tutorial guide also. Can anyone help me.Please.Thank you!</p>

答:
Glade is not an IDE it's a GUI builder/designer. Glade just helps you create the interface of your application, Coding comes later.

If you're not comfortable with PyGTK you should try PySide, the Python binding of Qt.

Title: Python scripts link to GUI using an IDE


答:
It depends on what you want to happen.

You wrote that you are working on "a consumer electronics device". If, somehow, a bug is introduced by setting msgSender_ to NULL, do you want

the device to carry on, skipping SignalShutdown but continuing the rest of its operation, or

the device to crash, forcing the user to restart it?

Depending on the impact of the shutdown signal not being sent, option 1 might be a viable choice. If the user can continue to listen to his music, but the display still shows the title of the previous track, that might be preferable to a complete crash of the device.

Of course, if you choose option 1, an assert (as recommended by others) is vital to reduce the likelihood of such a bug creeping in unnoticed during development. The if null guard is just there for failure mitigation in production use.

Personally, I also prefer the "crash early" approach for production builds, but I am developing business software that can be fixed and updated easily in case of a bug. For consumer electronics devices, this might not be so easy.


答:
As other have noted, this depends on whether or not msgSender can be legitimately NULL. The following assumes that it should never be NULL.

```<code>void PowerManager::SignalShutdown()
{
    if (!msgSender_)
    {
       throw SignalException("Shut down failed because message sender is not set.");
    }

    msgSender_->sendMsg("shutdown()");
}
</code>```

The proposed "fix" by the others on your team violates the Dead Programs Tell No Lies principle. Bugs are really hard to find as it is. A method that silently changes its behavior based on an earlier problem, not only makes it hard to find the first bug but also adds a 2nd bug of its own.

The junior wreaked havoc by not checking for a null. What if this piece of code wreaks havoc by continuing to run in an undefined state (device is on but the program "thinks" it's off)? Perhaps another part of the program will do something that is only safe when the device is off.

Either of these approaches will avoid silent failures:

Use asserts as suggested by this answer, but make sure they are turned on in production code. This, of course, could cause problems if other asserts were written with the assumption that they would be off in production.

Throw an exception if it is null.

Body:
As other have noted, this depends on whether or not msgSender can be legitimately NULL. The following assumes that it should never be NULL.

void PowerManager::SignalShutdown()
{
    if (!msgSender_)
    {
       throw SignalException("Shut down failed because message sender is not set.");
    }

    msgSender_->sendMsg("shutdown()");
}

The proposed "fix" by the others on your team violates the Dead Programs Tell No Lies principle. Bugs are really hard to find as it is. A method that silently changes its behavior based on an earlier problem, not only makes it hard to find the first bug but also adds a 2nd bug of its own.

The junior wreaked havoc by not checking for a null. What if this piece of code wreaks havoc by continuing to run in an undefined state (device is on but the program "thinks" it's off)? Perhaps another part of the program will do something that is only safe when the device is off.

Either of these approaches will avoid silent failures:

Use asserts as suggested by this answer, but make sure they are turned on in production code. This, of course, could cause problems if other asserts were written with the assumption that they would be off in production.

Throw an exception if it is null.


问:
What Is The Relationship Between Software Architect and Team Member
I work for a small company which has less than 100 persons. Several months ago, this company offered me position of SA and I accepted. There are three teams in this company, and I work for one of them. This is the first time I work as a SA.

During the past months, I find I don't have any power of management, I even can't let the team member do things (coding-related) in the way which is correct and more efficient. The team members argue with me on very very basic technical questions and I have to explain to them again and again. Though some members did take my advice, other members stubbornly program in their way which frequently proved wrong finally.

Recently I feel a little tired and confused. I wonder what is correct relationship between a Software Architect and team members including the team leader? Besides, is software architect also leaded by the Team Leader?

答:
Software architect has no power of management. This is explained in the question I referred in comments:

What should you bring to the table as a Software Architect?

Stuff architect does is explained in top answer:

The SA should have the last word on all design, technology and coding style decisions... for the most part... developers get to decide, at their level, how problems are to be solved... the SA keeps the pointy-haired bosses out of the developers' cubicles.

A good explanation for how they do their job is provided in another answer:

A thick skin. Good negotiation skills.

I've been an architect myself and I can confirm that answers match my experience.

Now, I would like to get a bit deeper on what you feel like a problem, disagreements with team members and the need to obey to team lead.

I think that disagreement with someone who you have no power to order is the most valuable and interesting part of architect job. If you continuously feel bad about it, seriously consider whether this job is indeed for you.

Disagreements that can not be resolved by brainless "shut up and follow my orders" provide unique opportunity for one to progress as an architect. These are the way to learn how to discuss complicated problems, how to negotiate and resolve conflicts, how to explain things, communicate your knowledge and learn new things. These are the only way to practice a skill to convince and influence team members.

If you're especially lucky, you'll happen to get into disagreement about things where your initial understanding is wrong.

Being free of thought-blocking "follow my orders" escape hatch, you will be able to find out how to improve your understanding, figure your mistakes, accept them and how to discover, share and lead the right way.

At architect position, one would rather strive to gain from failures like that, by analyzing what went wrong, what could have been done better and how to efficiently "re-use" acquired experience. These bits of knowledge may be invaluable if learned right, the very successful career at senior positions may depend on how well these are learned, as explained in this brilliant answer at WP:

Judgement comes not from success, but from failures. Most companies want to hire people that have had their failures paid for by previous companies...


问:
How to handle lookup data in a C# ASP.Net MVC4 application?
I am writing an MVC4 application to track documents we have on file for our clients. I'm using code first, and have created models for my objects (Company, Document, etc...). I am now faced with the topic of document expiration.

Business logic dictates certain documents will expire a set number of days past the document date. For example, Document A might expire in 180 days, Document 2 in 365 days, etc... I have a class for my documents as shown below (simplified for this example).

What is the best way for me to create a lookup for expiration values? I want to specify documents of type DocumentA expire in 30 days, type DocumentB expire in 75 days, etc... I can think of a few ways to do this:

Lookup table in the database I can query

New property in my class (DaysValidFor) which has a custom getter that returns different values based on the DocumentType

A method that takes in the document type and returns the number of days

and I'm sure there are other ways I'm not even thinking of. My main concern is a) not violating any best practices and b) maintainability. Are there any pros/cons I need to be aware of for the above options, or is this a case of "just pick one and run with it"?

One last thought, right now the number of days is a value that does not need to be stored anywhere on a per-document basis -- however, it is possible that business logic will change this (i.e., DocumentA's are 30 days expiration by default, but this DocumentA associated with Company XYZ will be 60 days because we like them). In that case, is a property in the Document class the best way to go, seeing as I need to add that field to the DB?

```<code>namespace Models
{
    // Types of documents to track
    public enum DocumentType
    {
        DocumentA,
        DocumentB,
        DocumentC // etc...
    }

    // Document model
    public class Document
    {
        public int DocumentID { get; set; }

        // Foreign key to companies
        public int CompanyID { get; set; }

        public DocumentType DocumentType { get; set; }

        // Helper to translate enum's value to an integer for DB storage
        [Column("DocumentType")]
        public int DocumentTypeInt
        {
            get { return (int)this.DocumentType; }
            set { this.DocumentType = (DocumentType)value; }
        }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
        public DateTime DocumentDate { get; set; }

        // Navigation properties
        public virtual Company Company { get; set; }
    }
}
</code>```

答:
Hum, to each one his own way to see things, but to me this has nothing to do with C# MVC 4, and everything to do with the database itself, as this is linked to the data, not the way they are accessed.

I think I would create a View (SQL View, not MVC...) with a calculated column for the expiration date. This way you can use any criteria you want, check if documents are linked, the company, the type of document, just anything you need, and change those criterias as many time as needed, without any change in the MVC application.

I know you can create stored procedures with Code First, I am not too sure bout Views, but really from my point of view this belongs into the database, so that's what I would be looking to do.


问:
Are there any formalized/mathematical theories of software testing?
Googling "software testing theory" only seems to give theories in the soft sense of the word; I have not been able to find anything that would classify as a theory in the mathematical, information theoretical or some other scientific field's sense.

What I'm looking for is something that formalizes what testing is, the notions used, what a test case is, the feasibility of testing something, the practicality of testing something, the extent to which something should be tested, formal definition/explanation of code coverage, etc.

UPDATE: Also, I'm not sure, intuitively, about the connection between formal verification and what I asked, but there's clearly some sort of connection.

答:
I can't point to a good online resource (the English Wikipedia articles on these topics tend to be improvable), but I can summarize a lecture I heard which also covered basic testing theory.

Testing modes

There are different classes of tests, like unit tests or integration tests. An unit test asserts that a coherent piece of code (function, class, module) taken on its own works as expected, whereas an integration test asserts that multiple such pieces correctly work together.

A test case is a known environment in which a piece of code is executed, e.g. by using specific test input, or by mocking other classes. The behavior of the code is then compared to expected behavior, e.g. a specific return value.

A test can only prove the presence of a bug, never the absence of all bugs. Tests put an upper bound on program correctness.

Code Coverage

To define code coverage metrics, the source code can be translated to a control flow graph where each node contains a linear segment of the code. Control flows between these nodes only at the end of each block, and is always conditional (if condition, then goto node A, else goto node B). The graph has one start node and one end node.

With this graph, statement coverage is the ratio of all visited nodes to all nodes. Full statement coverage isn't sufficient for thorough testing.

Branch coverage is the ratio of all visited edges between nodes in the CFG to all edges. This insufficiently tests loops.

Path coverage is the ratio of all visited paths to all paths, where a path is any sequence of edges from the start to the end node. The problem is that with loops, there can be an infinite number of paths, so full path coverage can't be practically tested.

It is therefore often useful to check condition coverage.

In simple condition coverage, each atomic condition is once true and once false – but this doesn't guarantee full statement coverage.

In multiple condition coverage, the atomic conditions have taken on all combinations of true and false. This implies full branch coverage, but is rather expensive. The program may have additional constraints that exclude certain combinations. This technique is good for obtaining branch coverage, can find dead code, but cannot find bugs stemming from the wrong condition.

In Minimal multiple condition coverage, each atomic and composite condition is once true and false. It still implies full branch coverage. It is a subset of multiple condition coverage, but requires fewer test cases.

When constructing test input using condition coverage, then short-circuiting should be taken into account. For example,

```<code>function foo(A, B) {
  if (A && B) x()
  else        y()
}
</code>```

needs to be tested with foo(false, whatever), foo(true, false), and foo(true, true) for full minimal multiple condition coverage.

If you have objects that can be in multiple states, then testing all state transitions analogous to control flows seems sensible.

There are some more complex coverage metrics, but they are generally similar to the metrics presented here.

These are white box testing methods, and can be partially automated. Note that an unit test suite should aim to have a high code coverage by any chosen metric, but 100% isn't always possible. It is especially difficult to test exception handling, where faults have to be injected into specific locations.

Functional tests

Then there are functional tests which assert that the code adheres to the spec by viewing the implementation as a black box. Such tests are useful for unit tests and integration tests alike. Because it is impossible to test with all possible input data (e.g. testing string length with all possible strings), it is useful to group the input (and output) into equivalent classes - if length("foo") is correct, foo("bar") is likely to work as well. For each possible combination between input and output equivalence classes, at least one representative input is chosen and tested.

One should additionally test

edge cases length(""), foo("x"), length(longer_than_INT_MAX),

values that are permitted by the language, but not by the contract of the function length(null), and

possible junk data length("null byte in \x00 the middle")…

With numerics, this means testing 0, ±1, ±x, MAX, MIN, ±∞, NaN, and with floating point comparisons testing two neighboring floats. As another addition, random test values can be picked from the equivalence classes. To ease debugging, it is worth recording the seed used…

Non-functional tests: Load tests, Stress tests

A piece of software has non-functional requirements, which have to be tested as well. These include testing at the defined boundaries (load tests), and beyond them (stress tests). For a computer game, this could be asserting a minimum number of frames per second in a load test. A website may be stress-tested to observe response times when twice as many visitors as anticipated are battering the servers. Such tests are not only relevant for whole systems but also for single entities – how does a hash table degrade with a million entries?

Other kinds of tests are whole system tests where scenarios are simulated, or acceptance tests to prove that the development contract was fulfilled.

Non-testing methods

Reviews

There are non-testing techniques that can be used for quality assurance. Examples are walkthroughs, formal code reviews, or pair programming. While some parts can be automated (e.g. by using linters), these are generally time intensive. However, code reviews by experienced programmers have a high rate of bug discovery, and are especially valuable during design, where no automated testing is possible.

When code reviews are so great, why do we still write tests? The big advantage of test suites is that they can run (mostly) automatically, and are as such very useful for regression tests.

Formal verification

Formal verification goes and proves certain properties of the code. Manual verification is mostly viable for critical parts, less so for whole programs. Proofs put a lower bound on program correctness. Proofs can be automated to a certain degree, e.g. via a static type checker.

Certain invariants can be explicitly checked by using assert statements.

All of these techniques have their place, and are complementary. TDD writes the functional tests up front, but the tests can be judged by their coverage metrics once the code is implemented.

Writing testable code means writing small code units that can be tested separately (helper functions with suitable granularity, single responsibility principle). The fewer arguments each function takes, the better. Such code also lends itself for insertion of mock objects, e.g. via dependency injection.

Body:
I can't point to a good online resource (the English Wikipedia articles on these topics tend to be improvable), but I can summarize a lecture I heard which also covered basic testing theory.

Testing modes

There are different classes of tests, like unit tests or integration tests. An unit test asserts that a coherent piece of code (function, class, module) taken on its own works as expected, whereas an integration test asserts that multiple such pieces correctly work together.

A test case is a known environment in which a piece of code is executed, e.g. by using specific test input, or by mocking other classes. The behavior of the code is then compared to expected behavior, e.g. a specific return value.

A test can only prove the presence of a bug, never the absence of all bugs. Tests put an upper bound on program correctness.

Code Coverage

To define code coverage metrics, the source code can be translated to a control flow graph where each node contains a linear segment of the code. Control flows between these nodes only at the end of each block, and is always conditional (if condition, then goto node A, else goto node B). The graph has one start node and one end node.

With this graph, statement coverage is the ratio of all visited nodes to all nodes. Full statement coverage isn't sufficient for thorough testing.

Branch coverage is the ratio of all visited edges between nodes in the CFG to all edges. This insufficiently tests loops.

Path coverage is the ratio of all visited paths to all paths, where a path is any sequence of edges from the start to the end node. The problem is that with loops, there can be an infinite number of paths, so full path coverage can't be practically tested.

It is therefore often useful to check condition coverage.

In simple condition coverage, each atomic condition is once true and once false – but this doesn't guarantee full statement coverage.

In multiple condition coverage, the atomic conditions have taken on all combinations of true and false. This implies full branch coverage, but is rather expensive. The program may have additional constraints that exclude certain combinations. This technique is good for obtaining branch coverage, can find dead code, but cannot find bugs stemming from the wrong condition.

In Minimal multiple condition coverage, each atomic and composite condition is once true and false. It still implies full branch coverage. It is a subset of multiple condition coverage, but requires fewer test cases.

When constructing test input using condition coverage, then short-circuiting should be taken into account. For example,

function foo(A, B) {
  if (A && B) x()
  else        y()
}

needs to be tested with foo(false, whatever), foo(true, false), and foo(true, true) for full minimal multiple condition coverage.

If you have objects that can be in multiple states, then testing all state transitions analogous to control flows seems sensible.

There are some more complex coverage metrics, but they are generally similar to the metrics presented here.

These are white box testing methods, and can be partially automated. Note that an unit test suite should aim to have a high code coverage by any chosen metric, but 100% isn't always possible. It is especially difficult to test exception handling, where faults have to be injected into specific locations.

Functional tests

Then there are functional tests which assert that the code adheres to the spec by viewing the implementation as a black box. Such tests are useful for unit tests and integration tests alike. Because it is impossible to test with all possible input data (e.g. testing string length with all possible strings), it is useful to group the input (and output) into equivalent classes - if length("foo") is correct, foo("bar") is likely to work as well. For each possible combination between input and output equivalence classes, at least one representative input is chosen and tested.

One should additionally test

edge cases length(""), foo("x"), length(longer_than_INT_MAX),

values that are permitted by the language, but not by the contract of the function length(null), and

possible junk data length("null byte in \x00 the middle")…

With numerics, this means testing 0, ±1, ±x, MAX, MIN, ±∞, NaN, and with floating point comparisons testing two neighboring floats. As another addition, random test values can be picked from the equivalence classes. To ease debugging, it is worth recording the seed used…

Non-functional tests: Load tests, Stress tests

A piece of software has non-functional requirements, which have to be tested as well. These include testing at the defined boundaries (load tests), and beyond them (stress tests). For a computer game, this could be asserting a minimum number of frames per second in a load test. A website may be stress-tested to observe response times when twice as many visitors as anticipated are battering the servers. Such tests are not only relevant for whole systems but also for single entities – how does a hash table degrade with a million entries?

Other kinds of tests are whole system tests where scenarios are simulated, or acceptance tests to prove that the development contract was fulfilled.

Non-testing methods

Reviews

There are non-testing techniques that can be used for quality assurance. Examples are walkthroughs, formal code reviews, or pair programming. While some parts can be automated (e.g. by using linters), these are generally time intensive. However, code reviews by experienced programmers have a high rate of bug discovery, and are especially valuable during design, where no automated testing is possible.

When code reviews are so great, why do we still write tests? The big advantage of test suites is that they can run (mostly) automatically, and are as such very useful for regression tests.

Formal verification

Formal verification goes and proves certain properties of the code. Manual verification is mostly viable for critical parts, less so for whole programs. Proofs put a lower bound on program correctness. Proofs can be automated to a certain degree, e.g. via a static type checker.

Certain invariants can be explicitly checked by using assert statements.

All of these techniques have their place, and are complementary. TDD writes the functional tests up front, but the tests can be judged by their coverage metrics once the code is implemented.

Writing testable code means writing small code units that can be tested separately (helper functions with suitable granularity, single responsibility principle). The fewer arguments each function takes, the better. Such code also lends itself for insertion of mock objects, e.g. via dependency injection.


问:
Utility Classes in MVC - ASP.NET
So I was wondering today, where would you put utility classes in an ASP.NET MVC app? By utility classes I mean classes that can be static and are just used to perform a function. Like a class to send an email that takes email address , subject, and body as arguments.

I would assume maybe creating a separate folder and namespace would be good enough, but wanted to get everyone opinions

答:
The question is a valid one, even if the example given is not. The answer given by Maina is perfect, in a very specific context, which is not to me, the proper context for said "utility" classes.

Personally, I create a folder Helpers in which I put simple functions to be called from about anywhere, like extensions, in which case, yes, they are static.

Now, if there is a better way, I will be glad to learn, but so far:

I see nothing wrong with Extensions.

I see nothing wrong with grouping them in a specific Folder.

Now, an extension is just syntaxic sugar, it could as well be a classic function.

Title: Utility Classes in MVC - ASP.NET

ContentLicense: CC BY-SA 4.0


问:
Who designed exceptions?
Where did exceptions and exception handling come from?

I like how .NET uses it, I like how C++ supports it (but libraries unfortunately use return code or is written in C instead). I know its pretty much standard in all new languages, but who designed it first or where did it come from?

Is C++ the first language to use it? I don't know of any other that is older.

答:
Hof, Mössenböck and Pirkelbauer (in their 1997 paper Zero-Overhead Exception Handling using Metaprogramming) affirm that the concept of exceptions was suggested in the seventies, referring to John B. Goodenough's 1975 Exception handling: Issues and a proposed notation paper in the Communications of the ACM.  In it he conflates modern exception handling with the general idea of registering callbacks, and his proposed notation looks more like modern Attribute metadata specifications than try/catch, but it (or at least its section 2) is a great overview of the state of exception handling in the mid-seventies.

Perhaps of note is also the raise/rescue mechanism in Alef, which one can view as a primitive form of catch blocks, lest we think they sprang fully-formed from Stroustroup's brow like Athena from Zeus's.

Title: Who designed exceptions?


答:
Like exceptions, guard conditions are only useful if you know what to do to recover from the error or if you want to give a more meaningful exception message.

Swallowing an error (whether caught as an exception or a guard-check), is only the right thing to do when the error doesn't matter.  The most common place for me to see errors being swallowed is in error logging code -- you don't want to crash an app because you were unable to log a status message.

Anytime a function is called, and it's not optional behavior, it should fail loudly, not silently.

Edit: on thinking about your junior programmer story it sounds like what happened was that a private member was set to null when that was never supposed to be allowed to happen.  They had a problem with inappropriate writing and are attempting to fix it by validating upon reading. This is backwards.  By the time you identify it, the error has already happened. The code-review/compiler enforceable solution for that isn't guard conditions, but instead getters and setters or const members.


问:
How to slowly release a web application to more and more users so that too many concurrent users don't crash your site?
I have a web application that I expect to go viral pretty quickly.

How can I control traffic to it so that it doesn't crash under too much load?

This application doesn't require user login.
It will be properly load tested, but I am not really sure what kind of traffic to expect until I make it live.

答:
It is harder to control without a login.

Another option is to protect the site with an "access key" that you can then give out to your beta users.  I personally don't like these and they will inhibit initial expansion of your site since all users will need this key and the site won't be indexed by Google etc.

Your best be is to do some load testing.  Address the bottlenecks in your code and have a scale out plan if you think it will expand quickly.  You need to have this plan ready so you can just click a button and add another load balanced server etc.


答:
What is your bottleneck?

Assuming that bandwith is your problem, e.g. by serving high-res images, then using a CDN will be beneficial.

If your site is computationally expensive, then load-balancing between multiple servers sounds like the way to go. Hosting your webapp in a cloud will make this scaling easier, and you can always scale down or move to a conservative solution when you can accurately estimate the number of users. Scaling across multiple servers can get difficult if the users interact with each other using your site. In that case, peer-to-peer communication between users, or a message queue between your servers sounds like a good idea.

You might want to tweak your technology stack towards better performance. Static content can be cached. If you are running an interpreted language on the server, an alternative implementation may have a better performance profile (possibly trading start-up time or memory for overall faster execution). There is no excuse for using CGI scripts in this day and age for a modern webapp.

I don't know how you will roll out your site. If you are targeting an international audience, one possibility would be to release the site at a certain local time for each user. A variation of this would be to display the site as closed to a certain percentage of IPs when load is high. However, requiring an email address to log in would actually be preferable. If load is high, tell the user he'll get the activation email in about ten minutes (but then, give him priority). You could also give out URLs with an access token to specific individuals before officially opening the site. You can then try to estimate public interest from various metrics like percentage of people that used their tokens, number of tweets, ….

A controlled launch can be achieved by giving each pre-opening user a number of further tokens, which he can give away. This allows you to adjust the rate of expansion, until you open to the general public. Be careful with such tactics: while artificial scarcity can increase interest, this also makes it harder to your product to “go viral”.

If there are few fixed slots for users available, you could display their position in a waiting queue and perhaps give a clue on the remaining waiting time. How you can reduce the perceived waiting time is an interesting UX question.

In the end, this is not only an interesting technical question, but also a matter of marketing.

Title: How to slowly release a web application to more and more users so that too many concurrent users don't crash your site?

Body:
I have a web application that I expect to go viral pretty quickly.

How can I control traffic to it so that it doesn't crash under too much load?

This application doesn't require user login.
It will be properly load tested, but I am not really sure what kind of traffic to expect until I make it live.


问:
Should my colleagues review each others code from source control system?
So that's my story: one of my colleagues uses to review all the code, hosted to revision system. I'm not speaking about adequate review of changes in parts that he belongs to. He watches the code file to file, line to line. Every new file and every modified. I feel just like being spied on!

My guess is that if code was already hosted to control system, you should trust it as workable at least. My question is, maybe I'm just too paranoiac and practice of reviewing each others code is good?

P.S: We're team of only three developers, and I fear that if there will be more of us, colleague just won't have time to review all the the code we'll write.

答:
You feel it as being spied on(!)? But from your colleague perspective I would say he is doing the right things for his career development. Read others code and find how do they design and implement the logic, this will gain you a lot!

IMHO if some one point out something wrong in your code, you must accept it and learn from them about how to write a good code


问:
What are some efficient ways to set up my environment when working on a remote site?
Hello fellow Programmers,

I am still a relatively new programmer and have recently gotten my first on-campus programming position. I am the sole dev responsible for 8 domains as well as 3 small sized PHP web apps.

The campus has its web environment divided into staging and live servers -- we develop on the staging via SFTP and then push the updates to the live server through a web GUI.

I use Sublime Text 2 and the Sublime SFTP plugin currently for all my dev work (its my preferred editor). If I am just making an edit to a page I'll open that individual file via the ftp browser. If I am working on the PHP web app projects, I have the app directory mapped to a local folder so that when I save locally the file is auto-uploaded through Sublime SFTP.

I feel like this workflow is slow and sub-optimal. How can I improve my workflow for working with remote content? I'd love to set up a local environment on my machine as that would eliminate the constant SFTP upload/download, but as I said there are many sites and the space required for a local copy of the entire domain would be quite large and complex; not to mention keeping it updated with whatever the latest on the staging server is would be a nightmare.

Anyone know how I can improve my general web dev workflow from what I've described? I'd really like to cut out constantly editing over FTP but I'm not sure where to start other than ripping the entire directory and dumping it into XAMP.

答:
keeping it updated with whatever the latest on the staging server is would be a nightmare.

It's shouldn't be a nightmare, it should be trivial. At a minimum you should be using version control to automate much of this. These days I would start with either git or mercurial.

Any professional programmer should run away screaming in horror from a job that does not use version control in some fashion. It's something you need in your toolbox "RIGHT NOW". Distributed version control makes it very easy to just set up on your own and even if you can't get buy in from the group at least you can keep yourself sane.

Mercurial (hg) is easier to get started with IMHO than git, but git is probably the defacto standard. Create a github account for yourself and play around with some simple boring stuff to get a feel for it. Or try hg at bitbucket.com.

You don't need either site to use these programs effectively, but they do make it easier to get started.

Once you have version control in your toolbox, the next thing is to have a portable development environment. If you have anything like a reasonably powered laptop or workstation you should be able to completely duplicate the production environment of most web applications.

Using a tool like Vagrant can make this a simple as a single command to get a complete test environment up and running. It does take a fair amount of work, but this is the world many people are working in these days. The more you can learn about these tools, the more employable you'll be in the future.