问:
Sharing knowledge in activity-based working
My workplace will soon be shifting to the concept of 'activity based working', which moves from the idea of IT teams, BA teams, PM teams, etc to project-based work where people from across all facets of IT and the business involved on a project sit and work together. As a result, you wouldn't be sitting with your normal team colleagues on a day-to-day basis and sharing knowledge in that sort of organic way with the rest of your dev team won't really be happening.

What ways would you recommend to help preserve that team collaboration and knowledge sharing when people will not physically be co-existing alongside their teammates any longer? Not to mention preserving that 'geek spirit' (bad term perhaps) that sees devs encouraging and coaching each other to find better designs and solutions.

I've already thought about online collaboration tools such as Trello or Mingle, plus wikis or software such as Confluence to help collaboration and discussion. But I'd be interested to hear peoples opinions on what else could be done, or their own experiences with this approach to day-to-day work.

答: Nothing beats getting together face to face. Why can't IT have a pizza lunch and general sharing session one day a week where you and all your old colleagues get together and share ideas and keep in touch?</p>


问:
Assembly instructions execution time
Where can I find the x86 instructions execution time? How to find out which instruction is faster or smaller?</p>

答:
Daniel already summed up the answer, +1 to that.  Bottom line is that on modern CPUs with over 2 billion transistors, they do such crazy things that you can't look at assembly instructions and expect to guess timing.  The only thing you can really do is write code and measure its performance.

On that note, if you are curious about learning more, take a look at http://www.flounder.com/exceptions.htm. The guy who wrote that article is a PhD and actually has a lot of cool things to say about many things. I've spent some time going through all his articles.  The one I'm linking talks about measuring performance of exception handling and he goes right down to assembly instruction level.

ContentLicense: CC BY-SA 3.0

Title: Assembly instructions execution time


问:
How can we avoid creating duplicate or conflicting functionality when working on an agile team?
I'm working in a team where each member is working on an user story. How can we avoid creating duplicate or conflicting functionality?

For example, if my user story requires the creation of class A and my team member needs the same functionality and creates a similar class (maybe with a slightly different name), how should we plan our work so that we both move smoothly?

答:
Communications.

Large part of working as agile team is knowing what your team is working on. You have planning meetings and you should have design discussions prior to going off and coding solo.

On our teams we always know what other developers are working on and as soon as the thought arises that there's a potential for reuse or for overstepping bounds, you get up and walk over to the other person's desk (or if remote, pick up the phone).

UPDATE (response to comment):

At the beginning of every sprint, the team decides which stories are to deliver and which tasks are to be completed. We have a standard template (kinda like a checklist to make sure nothing is forgotten) and one of the things, is design task.

Almost every story has a design task, but generally it is 10 min to 1 hour discussion among team members to discuss the general approach of completing the work ahead.  This not only serves as a heads-up for other people, but it is also useful because sometimes other people will offer a different solution that is better than what you were considering doing. In planning meeting, we decide which developers should participate in the discussion based on a) complexity and b) other people's familiarity of existing code that's involved.

If two people know they will be working in similar area, they will most likely participate in the same discussion.  Our agile teams also have a technical lead, who typically participates in larger portion of design/code reviews and one of the responsibilities of that person is to spread knowledge through out the team, but I have a feeling this is a temporary position we will get rid off (or maybe scale back) once other team members get more familiar with the product (currently lots of fresh members).

Also during daily stand ups we generally talk about what we've been working on and what's ahead and if I mention that i started writing a utility class to help with feature X, and that class is useful to another developer, then the other developer would talk to me after the meeting and we would discuss how to make sure we are not repeating work and the class is generic enough to satisfy everyone's needs.

Finally, all code written is code reviewed, and we rotate through who reviews what, so in general the team has good familiarity with the whole code base. Even if two duplicate classes slip through (and I can't think of that ever actually happening), 95% chance this would be brought up in a code review and the two classes would be merged into one at that point.


问:
Why should I prefer composition over inheritance?
I always read that composition is to be preferred over inheritance. A blog post on unlike kinds, for example, advocates using composition over inheritance, but I can't see how polymorphism is achieved.

But I have a feeling that when people say prefer composition, they really mean prefer a combination of composition and interface implementation. How are you going to get polymorphism without inheritance?

Here is a concrete example where I use inheritance. How would this be changed to use composition, and what would I gain?

Class Shape
{
    string name;
  public:
    void getName();
    virtual void draw()=0;
}

Class Circle: public Shape
{
    void draw(/*draw circle*/);
}
```

答:
Preferring composition isn't just about polymorphism.  Although that is part of it, and
you are right that (at least in nominally typed languages) what people really mean is "prefer a combination of composition and interface implementation."  But, the reasons to prefer composition (in many circumstances) are profound.

Polymorphism is about one thing behaving multiple ways.  So, generics/templates are a "polymorphic" feature in so far as they allow a single piece of code to vary its behavior with  types.  In-fact, this type of polymorphism is really the best behaved and is generally referred to as parametric polymorphism because the variation is defined by a parameter.

Many languages provide a form of polymorphism called "overloading" or ad hoc polymorphism where multiple procedures with the same name are defined in an ad hoc manner, and where one is chosen by the language (perhaps the most specific).  This is the least well behaved kind of polymorphism, since nothing connects the behavior of the two procedures except developed convention.

A third kind of polymorphism is subtype polymorphism.  Here a procedure defined on a given type, can also work on a whole family of "subtypes" of that type.  When you implement an interface or extend a class you are generally declaring your intention to create a subtype.  True subtypes are governed by Liskov's Substitution Principle, which says that if you can prove something about all objects in a supertype you can prove it about all instances in a subtype.  Life gets dangerous though, since in languages like C++ and Java, people generally have unenforced, and often undocumented assumptions about classes which may or may not be true about their subclasses.  That is, code is written as if more is provable than it really is, which produces a whole host of issues when you subtype carelessly.

Inheritance is actually independent of polymorphism.  Given some thing "T" which has a reference to itself, inheritance happens when you create a new thing "S" from "T" replacing "T"s reference to itself with a reference to "S".  That definition is intentionally vague, since inheritance can happen in many situations, but the most common is subclassing an object which has the effect of replacing the this pointer called by virtual functions with  the this pointer to the subtype.

Inheritance is a dangerous like all very powerful things inheritance has the power to cause havoc.  For example, suppose you override a method when inheriting from some class: all is well and good until some other method of that class assumes the method you inherit to behave a certain way, after all that is how the author of the original class designed it.  You can partially protect against this by declaring all methods called by another of your methods private or non-virtual (final), unless they are designed to be overridden.  Even this though isn't always good enough.  Sometimes you might see something like this (in pseudo Java, hopefully readable to C++ and C# users)

interface UsefulThingsInterface {
    void doThings();
    void doMoreThings();
}

...

class WayOfDoingUsefulThings implements UsefulThingsInterface{
     private foo stuff;
     public final int getStuff();
     void doThings(){
       //modifies stuff, such that ...
       ...
     }
     ...
     void doMoreThings(){
       //ignores stuff
       ...
     }
 }
```

<p>you think this is lovely, and have your own way of doing "things", but you use inheritance to acquire the ability to do "moreThings", </p>

<pre class="lang-java prettyprint-override"><code>class MyUsefulThings extends WayOfDoingUsefulThings{
     void doThings {
        //my way
     }
}
</code>```

And all is well and good. WayOfDoingUsefulThings was designed in such a way that replacing one method doesn't change the semantics of any other... except wait, no it wasn't.  It just looks like it was, but doThings changed mutable state that mattered. So, even though it didn't call any override-able functions,

 void dealWithStuff(WayOfDoingUsefulThings bar){
     bar.doThings()
     use(bar.getStuff());
 }
```

<p>now does something different than expected when you pass it a <code>MyUsefulThings</code>.  Whats worse, you might not even know that <code>WayOfDoingUsefulThings</code> made those promises.  Maybe <code>dealWithStuff</code> comes from the same library as <code>WayOfDoingUsefulThings</code> and <code>getStuff()</code> isn't even exported by the library (think of <em>friend classes</em> in C++).  Worse still, you have defeated the static checks of the language without realizing it: <code>dealWithStuff</code> took a <code>WayOfDoingUsefulThings</code> just to make sure that it would have a <code>getStuff()</code> function that behaved a certain way.</p>

<p>Using composition</p>

<pre class="lang-java prettyprint-override"><code>class MyUsefulThings implements UsefulThingsInterface{
     private way = new WayOfDoingUsefulThings()
     void doThings() {
        //my way
     }
     void doMoreThings() {
        this.way.doMoreThings();
     }
}
</code>```

brings back static type safety.  In general composition is easier to use and safer than inheritance when implementing subtyping.  It also lets you override final methods which means that you should feel free to declare everything final/non-virtual except in interfaces the vast majority of the time.

In a better world languages would automatically insert the boilerplate with a delegation keyword.  Most don't, so a downside is bigger classes.  Although, you can get your IDE to write the delegating instance for you.

Now, life isn't just about polymorphism.  You can don't need to subtype all the time.  The goal of polymorphism is generally code reuse but it isn't the only way to achieve that goal.  Often time, it makes sense to use composition, without subtype polymorphism, as a way of managing functionality.

Also, behavioral inheritance does have its uses.  It is one of the most powerful ideas in computer science.  Its just that, most of the time, good OOP applications can be written using only using interface inheritance and compositions.  The two principles

Ban inheritance or design for it

Prefer composition

are a good guide for the reasons above, and don't incur any substantial costs.

Body:
Preferring composition isn't just about polymorphism.  Although that is part of it, and
you are right that (at least in nominally typed languages) what people really mean is "prefer a combination of composition and interface implementation."  But, the reasons to prefer composition (in many circumstances) are profound.

Polymorphism is about one thing behaving multiple ways.  So, generics/templates are a "polymorphic" feature in so far as they allow a single piece of code to vary its behavior with  types.  In-fact, this type of polymorphism is really the best behaved and is generally referred to as parametric polymorphism because the variation is defined by a parameter.

Many languages provide a form of polymorphism called "overloading" or ad hoc polymorphism where multiple procedures with the same name are defined in an ad hoc manner, and where one is chosen by the language (perhaps the most specific).  This is the least well behaved kind of polymorphism, since nothing connects the behavior of the two procedures except developed convention.

A third kind of polymorphism is subtype polymorphism.  Here a procedure defined on a given type, can also work on a whole family of "subtypes" of that type.  When you implement an interface or extend a class you are generally declaring your intention to create a subtype.  True subtypes are governed by Liskov's Substitution Principle, which says that if you can prove something about all objects in a supertype you can prove it about all instances in a subtype.  Life gets dangerous though, since in languages like C++ and Java, people generally have unenforced, and often undocumented assumptions about classes which may or may not be true about their subclasses.  That is, code is written as if more is provable than it really is, which produces a whole host of issues when you subtype carelessly.

Inheritance is actually independent of polymorphism.  Given some thing "T" which has a reference to itself, inheritance happens when you create a new thing "S" from "T" replacing "T"s reference to itself with a reference to "S".  That definition is intentionally vague, since inheritance can happen in many situations, but the most common is subclassing an object which has the effect of replacing the this pointer called by virtual functions with  the this pointer to the subtype.

Inheritance is a dangerous like all very powerful things inheritance has the power to cause havoc.  For example, suppose you override a method when inheriting from some class: all is well and good until some other method of that class assumes the method you inherit to behave a certain way, after all that is how the author of the original class designed it.  You can partially protect against this by declaring all methods called by another of your methods private or non-virtual (final), unless they are designed to be overridden.  Even this though isn't always good enough.  Sometimes you might see something like this (in pseudo Java, hopefully readable to C++ and C# users)

interface UsefulThingsInterface {
    void doThings();
    void doMoreThings();
}

...

class WayOfDoingUsefulThings implements UsefulThingsInterface{
     private foo stuff;
     public final int getStuff();
     void doThings(){
       //modifies stuff, such that ...
       ...
     }
     ...
     void doMoreThings(){
       //ignores stuff
       ...
     }
 }

you think this is lovely, and have your own way of doing "things", but you use inheritance to acquire the ability to do "moreThings",

class MyUsefulThings extends WayOfDoingUsefulThings{
     void doThings {
        //my way
     }
}

And all is well and good. WayOfDoingUsefulThings was designed in such a way that replacing one method doesn't change the semantics of any other... except wait, no it wasn't.  It just looks like it was, but doThings changed mutable state that mattered. So, even though it didn't call any override-able functions,

 void dealWithStuff(WayOfDoingUsefulThings bar){
     bar.doThings()
     use(bar.getStuff());
 }

now does something different than expected when you pass it a MyUsefulThings.  Whats worse, you might not even know that WayOfDoingUsefulThings made those promises.  Maybe dealWithStuff comes from the same library as WayOfDoingUsefulThings and getStuff() isn't even exported by the library (think of friend classes in C++).  Worse still, you have defeated the static checks of the language without realizing it: dealWithStuff took a WayOfDoingUsefulThings just to make sure that it would have a getStuff() function that behaved a certain way.

Using composition

class MyUsefulThings implements UsefulThingsInterface{
     private way = new WayOfDoingUsefulThings()
     void doThings() {
        //my way
     }
     void doMoreThings() {
        this.way.doMoreThings();
     }
}

brings back static type safety.  In general composition is easier to use and safer than inheritance when implementing subtyping.  It also lets you override final methods which means that you should feel free to declare everything final/non-virtual except in interfaces the vast majority of the time.

In a better world languages would automatically insert the boilerplate with a delegation keyword.  Most don't, so a downside is bigger classes.  Although, you can get your IDE to write the delegating instance for you.

Now, life isn't just about polymorphism.  You can don't need to subtype all the time.  The goal of polymorphism is generally code reuse but it isn't the only way to achieve that goal.  Often time, it makes sense to use composition, without subtype polymorphism, as a way of managing functionality.

Also, behavioral inheritance does have its uses.  It is one of the most powerful ideas in computer science.  Its just that, most of the time, good OOP applications can be written using only using interface inheritance and compositions.  The two principles

Ban inheritance or design for it

Prefer composition

are a good guide for the reasons above, and don't incur any substantial costs.


问:
Why are shortcuts like x += y considered good practice?
I have no idea what these are actually called, but I see them all the time. The Python implementation is something like:

x += 5 as a shorthand notation for x = x + 5.

But why is this considered good practice? I've run across it in nearly every book or programming tutorial I've read for Python, C, R so on and so forth. I get that it's convenient, saving three keystrokes including spaces. But they always seem to trip me up when I'm reading code, and at least to my mind, make it less readable, not more.

Am I missing some clear and obvious reason these are used all over the place?

答:
Depending on how you think about it, it's actually easier to understand because it's more straightforward. Take, for example:

x = x + 5 invokes the mental processing of "take x, add five to it, and then assign that new value back to x"

x += 5 can be thought of as "increase x by 5"

So, it's not just shorthand, it actually describes the functionality much more directly. When reading through gobs of code, it's much easier to grasp.


答:
It is called an idiom. Programming idioms are useful because they are a consistent way of writing a particular programming construct.

Whenever someone writes x += y you know that x is being incremented by y and not some more complex operation (as a best practice, typically I wouldn't mix more complicated operations and these syntax shorthands). This makes the most sense when incrementing by 1.

Title: Why are shortcuts like x += y considered good practice?

Body:
I have no idea what these are actually called, but I see them all the time. The Python implementation is something like:

x += 5 as a shorthand notation for x = x + 5.

But why is this considered good practice? I've run across it in nearly every book or programming tutorial I've read for Python, C, R so on and so forth. I get that it's convenient, saving three keystrokes including spaces. But they always seem to trip me up when I'm reading code, and at least to my mind, make it less readable, not more.

Am I missing some clear and obvious reason these are used all over the place?


问:
What should I do when I find sensitive information in version control?
Today I found what looked to be my supervisor's password in some code in version control. The password is to a database. He is very experienced and has explained before how to avoid having passwords in the source code.

How should I handle this situation? Is there a best practice about preserving evidence of a security flaw, or should I remove such data as soon as I see it?

Even if I remove the data in the current revision, there's still the revision history. Should I just alert my supervisor instead?

答:
All version control systems I am aware of have some form of "obliterate" capability that allows you to remove data permanently. This is normally not something you want to do lightly as it inevitably involves rewriting history. Most version control systems in fact restrict this ability to administrators or at least to users with direct access to the central repository. In a distributed version control system like git, this is complicated by the fact that many people may have clones of the repository and therefore copies of the sensitive data. If you cannot guarantee that all copies are destroyed, you have a problem.

Some general advice from an SCM pro: As a matter of policy I won't use any "obliterate" equivalent unless requested to do so by the company's legal department. This is because, as I said, you are rewriting history, and the history of the code in your repository can be considered legal evidence in some cases. I probably would recommend not removing a password as a password can be changed.

In your particular instance, I would strongly recommend that you not do anything without talking to your supervisor, even if you do have the access or the knowledge to remove the password. Messing around with the history in your repository is not something you should be doing on your own authority.


答:
It's concise.

It's much shorter to type. It involves fewer operators. It has less surface area and less opportunity for confusion.

It uses a more specific operator.

This is a contrived example, and I'm not sure if actual compilers implement this. x += y actually uses one argument and one operator and modifies x in place. x = x + y could have an intermediate representation of x = z where z is x + y. The latter uses two operators, addition and assignment, and a temporary variable. The single operator makes it super clear that the value side can't be anything other than y and doesn't need to be interpreted. And there could theoretically be some fancy CPU that has a plus-equals operator that runs faster than a plus operator and an assignment operator in series.


答:
While the += notation is idiomatic and shorter, these are not the reasons why it is easier to read. The most important part of reading code is mapping syntax to meaning, and so the closer the syntax matches the programmer's thought processes, the more readable it will be (this is also the reason why boilerplate code is bad: it is not part of the thought process, but still necessary to make the code function). In this case, the thought is "increment variable x by 5", not "let x be the value of x plus 5".

There are other cases where a shorter notation is bad for readability, for example when you use a ternary operator where an if statement would be more appropriate.


答:
Besides readability, they actually do different things:+= doesn't have to evaluate its left operand twice.

For instance, expr = expr + 5 would evalaute expr twice (assuming expr is impure).


问:
What are the practical uses of Windows Services?
I am new to working with Windows Services. Although I have learnt to create  Windows Services in VS2010  I would like to know some practical ways in which windows services could be used?

I tried Googling with the current context in mind only to find more tutorials on how to create Windows Services.

EDIT on Bounty Offer:

All the answers are great but I was looking for more practical examples on windows services and their implications? This will help developers know when it is appropriate to use them with the case study.

答:
Examples of candidate programs:

Systems that must monitor resources/other applications and send
reports (user activity, particular kinds of file traffic,
notifications of application misbehaviour)

Systems that offer services to other local applications
(translations, file conversion, inter-system messaging)

Anti-virus software.

I think these are the big examples that can't easily be done using scheduled tasks.


答:
Remove the reference from the code, as it's not safe.

Communicate to him that his current password has become compromised listing the reason.

Have him change it and tell everyone coding this should never happen again.

Title: What should I do when I find sensitive information in version control?

Body:
Today I found what looked to be my supervisor's password in some code in version control. The password is to a database. He is very experienced and has explained before how to avoid having passwords in the source code.

How should I handle this situation? Is there a best practice about preserving evidence of a security flaw, or should I remove such data as soon as I see it?

Even if I remove the data in the current revision, there's still the revision history. Should I just alert my supervisor instead?


答:
To put @Pubby's point a little clearer, consider someObj.foo.bar.func(x, y, z).baz += 5

Without the += operator, there are two ways to go:

someObj.foo.bar.func(x, y, z).baz = someObj.foo.bar.func(x, y, z).baz + 5. This is not only awfully redundant and long, it's also slower. Therefore one would have to

Use a temporary variable: tmp := someObj.foo.bar.func(x, y, z); tmp.baz = tmp.bar + 5. This is ok, but it's a lot of noise for a simple thing. This is actually really close to what happens at runtime, but it's tedious to write and just using += will shift the work to the compiler/interpreter.

The advantage of += and other such operators is undeniable, while getting used to them is only a matter of time.


问:
Is it a must for every programmer to learn regular expressions?
I am new to programming, and at an interview I got a question on regular expressions; needless to say I couldn't answer. So I was wondering whether I should learn regular expression? Is it a must for every programmer of all fields? Or it is a must for programming for some particular fields?

Related questions:

Why are regular expressions so morbidly attractive?

When you should NOT use Regular Expressions?

答: Is it a must? You already know what you MUST know: that they exist, what they are, and what they are used for.  Your job as a programmer is to solve problems.  You now know enough to begin factoring them into your solution for solving your problem.  Should you learn regexs?  Absolutely.  Priority is up to you...there are jobs where they will be used everyday, and jobs where they will never be used. Simple guide would be how much pattern matching the problems you expect to encounter will require.</p>


问:
Should I Prefer Session Timeouts Based off of Prime Numbers?
While researching some information regarding managing state and session in web applications, I stumbled across this nugget of information:

67 is the first useful prime number after 60. (Yes, 61 is a prime,
  too, but it's too close to 60 to be of use.) Setting timeouts in
  durations of primes is common because it lessens the likelihood that
  two timeout sessions will overlap.

Of course, that's completely anecdotal and may not in any way be the
  reason why they chose 67 minutes, but that's always made sense to me.

At first glance, this seems to make perfect sense to me, and traditionally, I've never given a lot of thought to the variance of sessions timing out, but I wonder how much (if any) this strategy has been put into place in practice? Would making a change to timeouts ending on prime numbers really have that much of an effect long-term in a large scale application? Or would a change like this go mostly unnoticed?

In other words, is this really anecdotal? Or is it something that should be strongly considered as a best practice?

答:
This sounds like cargo cult programming. Session timeouts occur based on user action and while some patterns for that can be seen on a large enough time scale, they only become relevant at time scales orders of magnitude larger (eg. most session time-outs happen at lunch or closing hours).

In practice session time-out periods are set around the 15-20 minute mark. There are deviations because the end user may want them, but anything above that is kind of a security risk and anything below is an inconvenience to the user.


问:
Are we always supposed to create a setup to deploy or application?
I have recently developed an application in C# which is supposed to run within the environment of the company i work for.

I could technically generate a Setup or use ClickOnce to handle the deployment of the application, but I am considering basically copying the EXE file into a public directory and have everybody execute it from there.

The program recovers data from a database, makes some computations and displays the results.

I was wondering what the downfalls of this idea were. So far, I came up with the following:

I have to make sure that the prerequisites are installed on each machine (for example, .Net Framework 4.0)

I will not be able to "automatically" create a shortcut and the entries in the "Start Menu" (not a problem, user can do it manually).

In particular, I was wondering if the fact that several user actually run the same application at the same time could result in a problem (cocurrency, efficiency)?

答: Running the application concurrently is unlikely to be a problem (does it write to itself?).  Resource access might be a problem if it requires exclusive access to something.  As for the framework, that depends upon your organization, and how it handles system updates.  Its certainly viable in some cases, whether it is in your case or not, well, you'll have to decide that,</p>


答:
I do this for simple in-house apps too. It works fine.

Actually you have the same pre-requists as before - you would still need .Net on the clients machine if you used ClickOnce or an installer (you cannot distribute the parts of the .Net framework you use with your app unfortunatly). Windows makes of temporary local copy of the exe then runs it - which means they all users run an independent copy.

Title: Are we always supposed to create a setup to deploy or application?

Body:
I have recently developed an application in C# which is supposed to run within the environment of the company i work for.

I could technically generate a Setup or use ClickOnce to handle the deployment of the application, but I am considering basically copying the EXE file into a public directory and have everybody execute it from there.

The program recovers data from a database, makes some computations and displays the results.

I was wondering what the downfalls of this idea were. So far, I came up with the following:

I have to make sure that the prerequisites are installed on each machine (for example, .Net Framework 4.0)

I will not be able to "automatically" create a shortcut and the entries in the "Start Menu" (not a problem, user can do it manually).

In particular, I was wondering if the fact that several user actually run the same application at the same time could result in a problem (cocurrency, efficiency)?


答:
It's not shorthand.

The += symbol appeared in the C language in the 1970s, and - with the C idea of "smart assembler" correspond to a clearly different machine instruction and adressing mode:

Things like "i=i+1", "i+=1" and "++i", although at an abstract level produce the same effect, correspond at low level to a different way of working of the processor.

In particular those three expressions, assuming the i variable resides in the memory address stored in a CPU register (let's name it D - think of it as a "pointer to int") and the ALU of the processor takes a parameter and return a result in an "accumulator" (let's call it A - think to it as an int).

With these constraints (very common in all microprocessors from that period), the translation will most likely be

```<code>;i = i+1;
MOV A,(D); //Move in A the content of the memory whose address is in D
ADD A, 1;  //The addition of an inlined constant
MOV (D) A; //Move the result back to i (this is the '=' of the expression)

;i+=1;
ADD (D),1; //Add an inlined constant to a memory address stored value

;++i;
INC (D); //Just "tick" a memory located counter
</code>```

The first way of doing it is disoptimal, but it is more general when operating with variables instead of constant (ADD A, B or ADD A, (D+x)) or when translating more complex expressions (they all boil down in push low priority operation in a stack, call the high priority, pop and repeat until all the arguments had been eliminated).

The second is more typical of "state machine": we are no longer "evaluating an expression", but "operating a value": we still use the ALU, but avoid moving values around being the result allowed to replace the parameter. These kind of instruction cannot be used where more complicated expression are required: i = 3*i + i-2 cannot be operated in place, since i is required more times.

The third -even simpler- does not even consider the idea of "addition", but uses a more "primitive" (in computational sense) circuitry for a counter. The instruction is shorted, load faster and executes immediately, since the combinatorial network required to retrofit a register to make it a counter is smaller, and hence faster than the one of a full-adder.

With contemporary compilers (refer to C, by now), enabling compiler optimization, the correspondence can be swapped based on convenience, but there is still a conceptual difference in the semantics.

x += 5 means

Find the place identified by x

Add 5 to it

But x = x + 5 means:

Evaluate x+5

Find the place identified by x

Copy x into an accumulator

Add 5 to the accumulator

Store the result in x

Find the place identified by x

Copy the accumulator to it

Of course, optimization can

if "finding x" has no side effects, the two "finding" can be done once (and x become an address stored in a pointer register)

the two copies can be elided if the ADD is applied to &x instead to the accumulator

thus making the optimized code to coincide the x += 5 one.

But this can be done only if "finding x" has no side effects, otherwise

```<code>*(x()) = *(x()) + 5;
</code>```

and

```<code>*(x()) += 5;
</code>```

are semantically different, since x() side effects (admitting x() is a function doing weird things around and returning an int*) will be produced twice or once.

The equivalence between x = x + y and x += y is hence due to the particular case where += and = are applied to a direct l-value.

To move to Python, it inherited the syntax from C, but since there is no translation / optimization BEFORE the execution in interpreted languages, things are not necessarily so intimately related (since there is one less parsing step). However, an interpreter can refer to different execution routines for the three types of expression, taking advantage of different machine code depending on how the expression is formed and on the evaluation context.

For who likes more detail...

Every CPU has an ALU (arithmetic-logical unit) that is, in its very essence, a combinatorial network whose inputs and output are "plugged" to the registers and / or memory depending on the opcode of the instruction.

Binary operations are typically implemented as "modifier of an accumulator register with an input taken "somewhere", where somewhere can be
 - inside the instruction flow itself (typical for manifest contant: ADD A 5)
 - inside another registry (typical for expression computation with temporaries: e.g. ADD A B)
 - inside the memory, at an address given by a register (typical of data fetching e.g.: ADD A (H)) - H, in this case, work like a dereferencing pointer.

With this pseudocode, x += 5 is

```<code>ADD (X) 5
</code>```

while x = x+5 is

```<code>MOVE A (X)
ADD A 5
MOVE (X) A
</code>```

That is, x+5 gives a temporary that is later assigned. x += 5 operates directly on x.

The actual implementation depends on the real instruction set of the processor:
If there is no ADD (.) c opcode, the first code becomes the second: no way.

If there is such an opcode, and optimization are enabled, the second expression, after eliminating the reverse moves and adjusted the registers opcode, become the first.

Body:
It's not shorthand.

The += symbol appeared in the C language in the 1970s, and - with the C idea of "smart assembler" correspond to a clearly different machine instruction and adressing mode:

Things like "i=i+1", "i+=1" and "++i", although at an abstract level produce the same effect, correspond at low level to a different way of working of the processor.

In particular those three expressions, assuming the i variable resides in the memory address stored in a CPU register (let's name it D - think of it as a "pointer to int") and the ALU of the processor takes a parameter and return a result in an "accumulator" (let's call it A - think to it as an int).

With these constraints (very common in all microprocessors from that period), the translation will most likely be

;i = i+1;
MOV A,(D); //Move in A the content of the memory whose address is in D
ADD A, 1;  //The addition of an inlined constant
MOV (D) A; //Move the result back to i (this is the '=' of the expression)

;i+=1;
ADD (D),1; //Add an inlined constant to a memory address stored value

;++i;
INC (D); //Just "tick" a memory located counter

The first way of doing it is disoptimal, but it is more general when operating with variables instead of constant (ADD A, B or ADD A, (D+x)) or when translating more complex expressions (they all boil down in push low priority operation in a stack, call the high priority, pop and repeat until all the arguments had been eliminated).

The second is more typical of "state machine": we are no longer "evaluating an expression", but "operating a value": we still use the ALU, but avoid moving values around being the result allowed to replace the parameter. These kind of instruction cannot be used where more complicated expression are required: i = 3*i + i-2 cannot be operated in place, since i is required more times.

The third -even simpler- does not even consider the idea of "addition", but uses a more "primitive" (in computational sense) circuitry for a counter. The instruction is shorted, load faster and executes immediately, since the combinatorial network required to retrofit a register to make it a counter is smaller, and hence faster than the one of a full-adder.

With contemporary compilers (refer to C, by now), enabling compiler optimization, the correspondence can be swapped based on convenience, but there is still a conceptual difference in the semantics.

x += 5 means

Find the place identified by x

Add 5 to it

But x = x + 5 means:

Evaluate x+5

Find the place identified by x

Copy x into an accumulator

Add 5 to the accumulator

Store the result in x

Find the place identified by x

Copy the accumulator to it

Of course, optimization can

if "finding x" has no side effects, the two "finding" can be done once (and x become an address stored in a pointer register)

the two copies can be elided if the ADD is applied to &x instead to the accumulator

thus making the optimized code to coincide the x += 5 one.

But this can be done only if "finding x" has no side effects, otherwise

*(x()) = *(x()) + 5;

and

*(x()) += 5;

are semantically different, since x() side effects (admitting x() is a function doing weird things around and returning an int*) will be produced twice or once.

The equivalence between x = x + y and x += y is hence due to the particular case where += and = are applied to a direct l-value.

To move to Python, it inherited the syntax from C, but since there is no translation / optimization BEFORE the execution in interpreted languages, things are not necessarily so intimately related (since there is one less parsing step). However, an interpreter can refer to different execution routines for the three types of expression, taking advantage of different machine code depending on how the expression is formed and on the evaluation context.

For who likes more detail...

Every CPU has an ALU (arithmetic-logical unit) that is, in its very essence, a combinatorial network whose inputs and output are "plugged" to the registers and / or memory depending on the opcode of the instruction.

Binary operations are typically implemented as "modifier of an accumulator register with an input taken "somewhere", where somewhere can be
 - inside the instruction flow itself (typical for manifest contant: ADD A 5)
 - inside another registry (typical for expression computation with temporaries: e.g. ADD A B)
 - inside the memory, at an address given by a register (typical of data fetching e.g.: ADD A (H)) - H, in this case, work like a dereferencing pointer.

With this pseudocode, x += 5 is

ADD (X) 5

while x = x+5 is

MOVE A (X)
ADD A 5
MOVE (X) A

That is, x+5 gives a temporary that is later assigned. x += 5 operates directly on x.

The actual implementation depends on the real instruction set of the processor:
If there is no ADD (.) c opcode, the first code becomes the second: no way.

If there is such an opcode, and optimization are enabled, the second expression, after eliminating the reverse moves and adjusted the registers opcode, become the first.


答:
Operators such as += are very useful when you're using a variable as an accumulator, i.e. a running total:

```<code>x += 2;
x += 5;
x -= 3;
</code>```

Is a lot easier to read than:

```<code>x = x + 2;
x = x + 5;
x = x - 3;
</code>```

In the first case, conceptually, you're modifying the value in x. In the second case, you're computing a new value and assigning it to x each time. And while you'd probably never write code that's quite that simple, the idea remains the same... the focus is on what you're doing to an existing value instead of creating some new value.

Body:
Operators such as += are very useful when you're using a variable as an accumulator, i.e. a running total:

x += 2;
x += 5;
x -= 3;

Is a lot easier to read than:

x = x + 2;
x = x + 5;
x = x - 3;

In the first case, conceptually, you're modifying the value in x. In the second case, you're computing a new value and assigning it to x each time. And while you'd probably never write code that's quite that simple, the idea remains the same... the focus is on what you're doing to an existing value instead of creating some new value.


问:
How do people doing TDD handle loss of work when doing major refactoring
For a while I have been trying to learn to write unit tests for my code.

Initially I started out doing true TDD, where I wouldn't write any code until I'd written a failing test first.

However, I recently had a thorny problem to solve which involved a lot of code. After spending a good couple of weeks writing tests and then code, I came to the unfortunate conclusion that my entire approach was not going to work, and I would have to throw out two weeks work and start again.

This is a bad enough decision to come to when you've just written the code, but when you've also written several hundred unit tests it becomes even more emotionally difficult to just throw it all away.

I can't help thinking that I've wasted 3 or 4 days of effort writing those tests when I could have just put the code together for proof of concept and then written the tests afterwards once I was happy with my approach.

How do people who practice TDD properly handle such situations? Is there a case for bending the rules in some cases or do you always slavishly write the tests first, even when that code may turn out to be useless?

答: The point of TDD is that it forces you to write small increments of code in small functions, precisely to avoid this problem. If you have spent weeks writing code on one domain, and every single utility method you wrote becomes useless when you rethink the architecture, then your methods are almost certainly way too large in the first place. (Yes, I'm aware this isn't exactly comforting rght now...)


答:
You should keep in mind that TDD is an iterative process. Write a small test (in most cases a few lines should be sufficient) and run it. The test should fail, now directly work on your main source and try to implement the tested functionality so that the test passes. Now start over again.

You should not try to write all the tests in one go, because, as you have noticed, this is not going to work out. This reduces the risk of wasting your time writing tests that aren't going to be used.

Title: How do people doing TDD handle loss of work when doing major refactoring

Body:
For a while I have been trying to learn to write unit tests for my code.

Initially I started out doing true TDD, where I wouldn't write any code until I'd written a failing test first.

However, I recently had a thorny problem to solve which involved a lot of code. After spending a good couple of weeks writing tests and then code, I came to the unfortunate conclusion that my entire approach was not going to work, and I would have to throw out two weeks work and start again.

This is a bad enough decision to come to when you've just written the code, but when you've also written several hundred unit tests it becomes even more emotionally difficult to just throw it all away.

I can't help thinking that I've wasted 3 or 4 days of effort writing those tests when I could have just put the code together for proof of concept and then written the tests afterwards once I was happy with my approach.

How do people who practice TDD properly handle such situations? Is there a case for bending the rules in some cases or do you always slavishly write the tests first, even when that code may turn out to be useless?


答:
Brooks said "plan to throw one away; you will, anyhow".  It seems to me that you are doing just that.  That said, you should write your unit tests to test unit of code and not large swath of code.  Those are more functional tests and therefore should it over any internal implementation.

For example, if I want to write a PDE (partial differential equations) solver, I would write a few tests trying to solve things that I can solve mathematically. Those are my first "unit" tests -- read: functional tests run as part of a xUnit framework.  Those will not change depending on what algorithm I use to solve the PDE.  All I care about is the result.  The second unit tests will focus on the functions used to code the algorithm and thus would be algorithm specific -- say Runge-Kutta.  If I were to find out that Runge-Kutta was not suitable, then I would still have those top level tests (including the ones that showed that Runge-Kutta was not suitable).  Thus the second iteration would still have many of the same tests as the first.

Your problem maybe on of design and not necessarily of code.  But without more details, it is difficult to say.


答:
I feel there are two issues here. The first is that you didn't realize in advance that your original design may not be the best approach. Had you known this in advance, you may have chosen to develop a quick throw-away prototype or two, to explore the possible design options and to assess which is the most promising way to follow. In prototyping, you need not write production quality code and need not unit test every nook and cranny (or at all), as your sole focus is on learning, not on polishing the code.

Now, realizing that you need prototyping and experiments rather than starting the development of production code right away, is not always easy, and not even always possible. Armed with the knowledge just gained, you may be able to recognize the need for prototyping next time. Or may not. But at least you know now that this option is to be considered. And this in itself is important knowledge.

The other issue is IMHO with your perception. We all make mistakes, and it is so easy to see in retrospect what we should have done differently. This is just the way we learn. Write down your investment into unit tests as the price of learning that prototyping may be important, and get over it. Just strive not to make the same mistake twice :-)


答:
Test-driven development is meant to drive your development. The tests you write help you assert the correctness of the code you're currently writing and increase the development speed from the first line onward.

You seem to believe the tests are a burden and only meant for incremental development later on. This line of thinking is not in line with TDD.

Maybe you can compare it with static typing: although one can write code using no static type information, adding static type to code helps in asserting certain properties of the code, freeing the mind and allowing focus on important structure instead, thus increasing the velocity and efficacy.


问:
How long do programmers generally stay in industry?
One thing that I've heard a lot over the years is that those working in the IT world generally don't make life time careers out of it, but tend to "burn out" and start a new career doing something else unrelated (e.g. going from software development to being an accountant).

Have you found this to be generally true in your experience and if so, what is the general impression on how long people work as developers before starting a new career?

答:
The following is my personal opinion - All figures are based on my own experience and may not be scientifically correct. Observations are geographically biased.

Your observation is correct. Many people will either burn out or will have obsolete experiences within 15 years or so unless:

A) They have very good IQ and

B) Work very hard

C) Maintain an excellent track record

D) Gain marketable skills with experience

E) Have good network

The reason many leave the career may be (not an ordered list)

There is not a continuous demand on old technologies

Many technologies become old fast and rarely used outside of the maintenance work

The 90s made lots of older technologies near obsolete (with the exception of few golden years near Y2K)

Most companies don't train people in core techs. They can get any skill in 1 phone call

Training path in core technologies takes too long and too much

Many jobs are contracting jobs, the older you get the more secure you want to be

Even if you learn the next technology, it will last you only 5 years or so (on the average)

Recruiters can't appreciate old experience almost at all

Recruiters are the front end for many employers

It takes a higher IQ to understand today's tech.

Most employers want a CS degree or the likes - Older folks did not use to require those

If you are 50 chances are you don't want an arrogant 25 years old to boss you just because he knows CSS 3.0 and you don't!

Outsourcing affected local demand

Competition is tough

Most worthwhile applications have already been built (SAP, etc.) - Ready made software is everywhere

Moving to other related disciplines is not that easy. Certification and demand of very good experience is a barrier in many cases. For example, those who can't do HTML/CSS can't become DBAs overnight.


答: I am hovering with over 14 years now from graduate developer to lead developer and solution architect. I have always found projects that are no just maintenance but new development/migration in new technology and I absolutely love it. There are couple guys in my team whom we recently recruited and are 40+ years and they are up to date on new technology. But yes you have to be passionate, read voraciously, see videos, follow blogs, go to user groups and conferences to keep on with continuous learning.</p>

Title: How long do programmers generally stay in industry?

Body:
One thing that I've heard a lot over the years is that those working in the IT world generally don't make life time careers out of it, but tend to "burn out" and start a new career doing something else unrelated (e.g. going from software development to being an accountant).

Have you found this to be generally true in your experience and if so, what is the general impression on how long people work as developers before starting a new career?


问:
communication, realistic approach
I work for a mid sized Architecture and Engineering firm, our sub group focuses on developing tech solutions for engineers, mappers and technical managers. So we're heavy on desktop based apps for GIS and Civil/Env Engineering (some web). The company sells the services that our Engineers and mappers produce and our team develops tools that aids in them being more productive, efficient and help in adding value to their decisions and products, we DO NOT sell the technology.

We are going through growing pains where initially we used to be extremely responsive and could rapidly prototype apps for engineers which immediately brought budgetary savings. That mindset has worked for us in the past. But this year we won a huge contract and our client base has basically quintupled (5 times?). What we are finding is that this rapid prototyping culture is hurting us, where project managers have started to expect short response times for tool development and robust production ready tools for all our engineers and GIS analysts. We've grown organically and now it seems that we are running into these issues were it appears we have to scale back our speed for more stability.

Is this a legitimate tradeoff? Is there a win-win? How does one push back the engineer, project manager and analyst when they are our clients, they fund us and yet we need to be able to push back and tell them that if they want stability they have to be realistic about time frames?

This isn't Microsoft Word, these are specialized GIS software and Engineering models with a ton of interop components for other industry standard models, they aren't idiot proof tools, they need informed inputs and we can only test things so much.

Has anyone dealt with similar growing pains? Recommendations/advice on a communication stance, books, blogs?

答:
This is basically a management problem, not a software problem. You will need to hire some more people to handle the new demand. You will probably also start having to build a QA team, at least informally.
Depending on your product line, continuous integration & continuous unit testing might be feasible.</p>

Title: communication, realistic approach

ContentLicense: CC BY-SA 2.5


答:
The reason people say this is that beginning OOP programmers, fresh out of their polymorphism-through-inheritance lectures, tend to write large classes with lots of polymorphic methods, and then somewhere down the road, they end up with an unmaintainable mess.

A typical example comes from the world of game development. Suppose you have a base class for all your game entities - the player's spaceship, monsters, bullets, etc.; each entity type has its own subclass. The inheritance approach would use a few polymorphic methods, e.g. update_controls(), update_physics(), draw(), etc., and implement them for each subclass. However, this means you're coupling unrelated functionality: it is irrelevant what an object looks like for moving it, and you don't need to know anything about its AI to draw it. The compositional approach instead defines several base classes (or interfaces), e.g. EntityBrain (subclasses implement AI or player input), EntityPhysics (subclasses implement movement physics) and EntityPainter (subclasses take care of drawing), and a non-polymorphic class Entity that holds one instance of each. This way, you can combine any appearance with any physics model and any AI, and since you keep them separate, your code will be much cleaner too. Also, problems such as "I want a monster that looks like the balloon monster in level 1, but behaves like the crazy clown in level 15" go away: you simply take the suitable components and glue them together.

Note that the compositional approach still uses inheritance within each component; although ideally you'd use just interfaces and their implementations here.

"Separation of concerns" is the key phrase here: representing physics, implementing an AI, and drawing an entity, are three concerns, combining them into an entity is a fourth. With the compositional approach, each concern is modelled as one class.

Title: Why should I prefer composition over inheritance?

Body:
I always read that composition is to be preferred over inheritance. A blog post on unlike kinds, for example, advocates using composition over inheritance, but I can't see how polymorphism is achieved.

But I have a feeling that when people say prefer composition, they really mean prefer a combination of composition and interface implementation. How are you going to get polymorphism without inheritance?

Here is a concrete example where I use inheritance. How would this be changed to use composition, and what would I gain?

Class Shape
{
    string name;
  public:
    void getName();
    virtual void draw()=0;
}

Class Circle: public Shape
{
    void draw(/*draw circle*/);
}
```


问:
Software to organize and maintain project documentation, specification?
I'm looking for software to organize and maintain projects internal documentation, specification, requirements, etc. Currently we store all documentation as lots of MS Word DOC files in a source control repository, which gives us version control, and that's nice. But you can't search this information, create links between them, categorize, collaborate.

Requirements, preferences:

Zero install on client side (WEB based).

Document version control.

Document annotations.

Document linking.

Full search (all documentation).

MS Word (*.doc) import\export.

WYSIWYG text editor.

Systems I have discovered and tried so far:

MediaWiki

XWiki

Confluence

答:
We recently started using the Alfresco DMS which has a lot of interesting properties:

Very simple install

Has a built-in indexer for quick searching through heaps of documents

Allows work-flows, groups and if necessary, specific access to documents by customers

Open-source

Active community

LDAP/AD/SSO integration

Handles many different documents

There are also some disadvantages:

User interface is not always intuitive

It's not really a wiki, so simultaneous collaborative work on one document might be a bit fragile

If you decide to give it a swing, please contact me with your opinions.


答:
I see many answers to this already, but they all seem to be about the merits of knowing regular expressions as a tool in the programmer's toolbox.

I much prefer to think of regular expressions as the kind of knowledge that expands one's understanding of how computers work. Once someone truly gets what a regular language is, and that you can express it with three simple operations, I believe it gives them something beyond simply a tool for validating simple strings.

They become able to better understand parsing in general, which is useful to just about every kind of programming, and better understand how the tools we use on a regular basis (compiler, editor, browser, etc.) work.

The practical benefits of using regular expressions is of course enormous. Even if you don't "program" with them - I use regular expressions doing find/replace in my editor all the time, and measure how much more productive they make me.

So, while it is not necessary, I think it is one of the first tools a programmer should learn.

Title: Is it a must for every programmer to learn regular expressions?

Body:
I am new to programming, and at an interview I got a question on regular expressions; needless to say I couldn't answer. So I was wondering whether I should learn regular expression? Is it a must for every programmer of all fields? Or it is a must for programming for some particular fields?

Related questions:

Why are regular expressions so morbidly attractive?

When you should NOT use Regular Expressions?


问:
Do GUI programmers have an undue advantage over others?
It is easy for managers and customers to appreciate what they can see.

I have seen many GUI developers who are average programmers with minimal knowledge of design principles or other programming idioms. However, these shortcomings often go unnoticed, specially by management and customers, if the programmer can create an impressive looking user interface. So much so that many GUI developers I know spend hours beautifying the GUI at the expense of writing bad, unmaintainable code.

On the other hand, middle tier programmers who develop APIs or business functionality or database code (SQLs etc.) are at a disadvantage as there is nothing tangible to showcase. Perhaps a code reviewer or an architect may appreciate the elegance, good design, scalability etc. of code but it means nothing to the outside world. Your code may run for years without breaking, may be very easy to maintain and have good performance, yet it never elicits the 'wow' that a slick looking GUI does.

In my opinion, a corollary to this is (and I am going to get heavily downvoted for this, I know) that there is less motivation for a GUI programmer to write good clean code.

EDIT: I must explain here that by GUI programmer, I don't mean a full-fledged web/GUI designer but a front-end programmer e.g., a java-swing programmer.

Does the rest of the community agree ?

答: You can get away with all sorts of hackery and shortcuts in the internal systems. When dealing with the GUI you do not have that freedom. Your internal api may have inconsistency and you just expect the coders to deal with it because its too hard to fix. You cannot trying and make your customers do the same thing. So in some sense, the people who have to deal with the user visible components have to actually follow a higher standard. </p>


答:
Consider this

```<code>(some_object[index])->some_other_object[more] += 5
</code>```

D0 you really want to write

```<code>(some_object[index])->some_other_object[more] = (some_object[index])->some_other_object[more] + 5
</code>```

Body:
Consider this

(some_object[index])->some_other_object[more] += 5

D0 you really want to write

(some_object[index])->some_other_object[more] = (some_object[index])->some_other_object[more] + 5


答: It is not a must. You just need to be aware of their existence and when to use them. Syntax specifics are easy to find and get right using google and online tools.</p>


答:
Hmm, I need to comma-separate and output this list of strings, let me write function containing a for loop that takes a separator argument, and keep appending them together...or I could just use this existing 'join' command.

I need sort to these complex objects based on a couple of attributes that each object has, let me remind myself how to write a sort function that does that, oh no wait, I can just use the existing standard sort function that this language supports. I'll have to learn how to write a custom comparator but it shouldn't be too hard, it's obviously better than maintaining my own sort function.

I'm a bit scared by the idea of virtual methods, but it should help me reduce these lists, each one for a different type of item, down to a single list. Then I don't have to write half a dozen similar statements processing each list in a different way. Guess I ought to study hard and learn those things because my code will be a lot simpler and cleaner if I do that.

I need to extract from this text file these pairs of words and values amongst all this other noise, let me write a fifty-line parser to read the characters one by one and if one of the characters look like the start of what I'm looking for I'll set this state variable and start parsing it differently and so on etc... of course my case is obviously so special no-one else has come across an issue like this before and invented a generic solution that takes one line of code to do it. That reminds me I ought to take those programming books I never read to the second-hand book store.


答:
I think you said it yourself: you were not sure about your approach before you started writing all your unit tests.

The thing I learned comparing the real-life TDD projects I worked with (not that many in fact, only 3 covering 2 years of work) with what I had learned theoretically, is that Automated Testing != Unit Testing (without of course being mutually exclusive).

In other words, the T in TDD doesn't have to have a U with it... It is automated, but is less a unit test (as in testing classes and methods) than an automated functional test: it's at the same level of functional granularity as the architecture you are presently working on. You start high-level, with few tests and only the functional big picture, and only eventually you end up with thousands of UTs, and all your classes well-defined in a beautiful architecture...

Unit tests give you a great deal of help when you work in team, to avoid code changes creating endless cycles of bugs. But I never wrote anything so precise when starting to work on a project, before having at least a global working POC for each user story.

Maybe it's just my personal way of doing this. I don't have the sufficient experience to decide from scratch what patterns or structure my project will have, so indeed I won't waste my time writing 100s of UTs from the beginning...

More generally, the idea of breaking everything and throwing it all will always be there. As "continuous" as we can try to be with our tools and methods, sometimes the only way there is to fight entropy is to start over. But the goal is that when that happens, the automated and unit testing you implemented will have made your project already less costly than if there were not there - and it will, if you find the equilibrium.


答:
I'm not sure about the reason why your approach turned out flawed after 3 days.
Depending on your uncertainties in your architecture, you could consider changing your testing strategy:

If you are uncertain about performance, You might want to start with a few integration tests that assert performance?

When API complexity is what you are investigating, write some real bare, small unit tests to figure out what would be the best way to go about it. Don't bother implementing anything, just make your classes return hard coded values or make them throw NotImplementedExceptions.


答:
Besides the obvious merits which other people described very well, when you have very long names it is more compact.

```<code>  MyVeryVeryVeryVeryVeryLongName += 1;
</code>```

or

```<code>  MyVeryVeryVeryVeryVeryLongName =  MyVeryVeryVeryVeryVeryLongName + 1;
</code>```

Body:
Besides the obvious merits which other people described very well, when you have very long names it is more compact.

  MyVeryVeryVeryVeryVeryLongName += 1;

or

  MyVeryVeryVeryVeryVeryLongName =  MyVeryVeryVeryVeryVeryLongName + 1;


问:
Synchronizing local and remote cache in distributed caching
With a distributed cache, a subset of the cache is kept locally while the rest is held remotely.

In a get operation, if the entry is not available locally, the remote cache will be used and and the entry is added to local cache.

In a put operation, both the local cache and remote cache are updated. Other nodes in the cluster also need to be notified to invalidate their local cache as well.

What's a simplest way to achieve this if you implemented it yourself, assuming that nodes are not aware of each other.

Edit
My current implementation goes like this:

Each cache entry contains a time stamp.

Put operation will update local cache and remote cache

Get operation will try local cache then remote cache

A background thread on each node will check remote cache periodically for each entry in local cache. If the timestamp on remote is newer overwrite the local.  If entry is not found in remote, delete it from local.

答:
The problem you may want to focus is when to send local caches messages carrying updates of remote caches. On one hand, you could send a message for each changed item, to all other caches. This ensure timely updates but there can be lots of update messages. On the other hand, the local cache can check whether an item is valid just before using it (and after a given timeframe from the same request), asking the remote cache. As another option, you could send updates on several changed items periodically.

The best strategy depends on the system you are going to build. The strategy could be a balance of several factors, such as frequency of updates, traffic generated by update messages, overhead of updating, criticality of missing updates, etc.

Do items of the cache vary frequently with respect to their access? How many local caches do you have? Does the change come from each local cache, a few of these, all, or from the remote cache?


问:
What tools do you use to manage requests from users?
I'm drowning in user emails and I'd like to implement a better way to manage all these requests I get and put them in a queue where those people on a team, as well as users, have access to them and can make common notes. I'm thinking about some sort of task management tool that would allow multiple tasks to be created under a project where emails, comments, ideas, etc. could be dropped/entered and easily accessible.

I need something that all parties can be involved in - users, managers, team leaders, developers. I'm looking for a tool that can allow:

Users to just drag/drop an email to submit a request for maintenance or enhancement.

Developers to just see their queue and the weighted priority of each task/project.

A team of developers to see what everyone is working on in real-time.

Management to keep a a log of time spent on each task.

I I am starting to look in more of a Agile/Scrum direction for solving this problem. I found list of scrum agile sofware project management open source tools. Since I am limited on time, has anyone used these? Which one should I test to see if it will meet my needs? TeamPulse is a good direction, but think it is a little too bloated. I need something simple for all parties.

答:
TestTrackPro worked for us in my last job.  I don't know how it has changed in the last 3 years.

At the time it was on a server, so everyone could add and access issues.  I'm pretty sure it allowed files to be added to an issue.  You could query by a lot of different parameters, so you could see just your tasks.  Tasks had a status that you could change as you worked on them.  It was a standard bug tracker.

If I were looking for a tool to manage requests from users, I would look at it (although I'd look first at the tools that got the most votes) to see how it compared to others based on my needs.  I certainly wouldn't just use emails to track my tasks!


答:
It is a nice idiom. Whether it is faster or not depends on the language. In C, it is faster because it translates to an instruction to increase the variable by the right hand side. Modern languages, including Python, Ruby, C, C++ and Java all support the op= syntax. It's compact, and you get used to it quickly. Since you will see it a whole lot in other peoples' code (OPC), you may as well get used to it and use it. Here is what happens in a couple of other languages.

In Python, typing x += 5 still causes the creation of the integer object 1 (although it may be drawn from a pool) and the orphaning of the integer object containing 5.

In Java, it causes a tacit cast to occur. Try typing

```<code>int x = 4;
x = x + 5.2  // This causes a compiler error
x += 5.2     // This is not an error; an implicit cast is done.
</code>```

Body:
It is a nice idiom. Whether it is faster or not depends on the language. In C, it is faster because it translates to an instruction to increase the variable by the right hand side. Modern languages, including Python, Ruby, C, C++ and Java all support the op= syntax. It's compact, and you get used to it quickly. Since you will see it a whole lot in other peoples' code (OPC), you may as well get used to it and use it. Here is what happens in a couple of other languages.

In Python, typing x += 5 still causes the creation of the integer object 1 (although it may be drawn from a pool) and the orphaning of the integer object containing 5.

In Java, it causes a tacit cast to occur. Try typing

int x = 4;
x = x + 5.2  // This causes a compiler error
x += 5.2     // This is not an error; an implicit cast is done.


问:
How should standards and process improvements be introduced to an organization without them?
I've been tasked with improving the software development process through the implementation of process improvements, of which we will most likely be using CMMI for Development, Version 1.3 as a guideline and adopting the best practices in whole or in part. What is the best way to introduce standards and process improvements so that the degree of push back and resistance from developers is minimized?</p>

答:
Basing your efforts on the CMMI is probably a good idea, even if you don't undergo the appraisals and get formally audited and rated. There's plenty of literature available about the CMMI, CMMI and other process improvement techniques such as Lean and Six Sigma, and CMMI and agile software development. The SEI has an entire collection of resources, some available for free, about different aspects of CMMI and guidance for different types of organizations.

I'd recommend looking in great depth at the continuous approach to implementing CMMI, rather than the staged approach. It strikes me as a much more efficient way to determine exactly where your organization stands now and improve in areas that add the most business value. This will allow you to not only align your improvement efforts with business objectives, but quickly achieve progress milestones and demonstrate the effects of improvement, increasing buy-in from all levels.

Something to keep in mind, though, is that process improvement is generally more successful when it's a grassroots effort. When process changes are dictated from above - by people the developers "in the trenches" might see as being out of touch with how things are done in the trenches - there is probably going to be pushback, even if the idea is a good one. Be prepared for this.

Some type of engineering process group might also be beneficial. Bring together representatives of the various organizational components and teams impacted by the improvement so that everyone's voice is heard. This would include not just representatives of each role, but perhaps various product development teams. Without knowing how your organization is structured, I can't say exactly who you might want to look at, but include people from every level of the organization in the group. Also, make the discussions and decisions made by this group available to the organization for comments and raising of any problems.


问:
Can I share data between two users in an ASP.NET Application?
I have an issue with Roles.IsUserInRole function. It take hell amount of time to just check if the logged-in user is in particular role(typ 3-9 sec). I searched to find a solution and arrived on this but I am not sure If I have fully grasped it.

What I got from the above, A new derived class is created. Inside that class, there is a list which retrieves all user at once. The next time you check IsUserInRole, you do not use the actual IsUserInRole method but rather use the one you overrode in your class. Is this the correct description? Am I on track?

My question is, can data be share between two different users in ASP.NET application? If yes, will the shared data exist only if there is at least one user logged in. If all users logs out, that shared data is destroyed? My point is this data will be created only one time whenever a user logs in. For all subsequent users they can use this data and check their roles against the list? I need a detailed answer.

My application has users and different roles. We are using ASP.NET roles.

答:
Yes data can be shared between two different users.  There are many ways to do this the quickest and dirtiest would be a static field.  Other options include a shared DB, file, etc.

As far as your speed issue, my suggestion would be to create a role provider that derives from your current role provider.  Then modify the role provider to cache the user's roles somewhere, probably in [Session][2] the first time it tries to check the user's roles.  Any subsequent check would hit the cache and not incur the cost of getting the roles.  To be honest I would probably actually cause the roles cache to be populated when the user was initially authenticated since the user will have an expectation that logging in will take some period of time that isn't expected when just requesting a page.

Updated response due to comment

How you do your caching is going to depend on your requirements, design, and architecture.  So without specifics on your implementation it'll be difficult to answer your question with regard to how you expire the cached roles.  Personally my first cut would be to do an individual cache for each user, which is why I referenced Session above.  Assuming that the standard first this process goes something like

GET some page

REDIRECT to Login page

POST Login page

REDIRECT to originally requested page

You might be able to asynchronously populate the cache in step 3 which would limit the delay when processing the request from step 4.  This would require some coordination work that might delay the rendering of the page in step 4 if the caching has completed yet.

A quick google search for "WindowsTokenRoleProvider slow" revealed some results for others that have had this issue.  This article describes at least one cause and offers a reasonable solution.


问:
What types of positions might involve improving processes using CMMI and Scrum?
I'm an IT student and have been working on team based projects for several years. I've read some papers about CMMI and Scrum; this is really interesting to me and I would like to know what kind of jobs involve improving processes inside an organization.

What kind of studies can lead someone towards these jobs? Management? I doubt it's only that, as CMMI/Scrum affect management as well, I think it's something above it all, that will hold together the organization.

答:
One development job that may involve CMMI and Scrum is likely going to be Release Engineering or Release Management either as a Release Engineer that is coming at things from a software development career path or coming at it from other directions, likely project management.

Depending upon the organization Release Engineering is going to have a fairly significant influence over software development as ultimately they are the group that is going to be signing off on the final version of software to be released, either as a Gold Master, binaries that are available to the public, or as part of a code migration pathway for continuous deployment as part of an SaaS model.

The other option is that you might want to look around for a company that has a formal standards implementation and compliance group of which the group name can pretty much be anything, I've seen at least one that was simply called "Software Engineering" with groups that did the actual product development having other names.

In terms of moving into such a position, it's really hard to say as to what the best way to go about doing it is as each company is going to view such a group differently. With proper education you might find your way into such groups fresh out of school (assuming that there are even open positions at that level) or it might take you a couple years of getting software development experience before you can make the move over. Having experience writing software does help if you are in such a group though so you might want to look into spending some time as a developer and then making a move to release engineering by building up any professional credentials that you may need to apply for such jobs (e.g. formal CMMI training, background in managing build systems or refactoring a build script for a major project, etc).

Or course, the disclaimer that needs to be applied to this is that different organizations approach problems differently and as a result things might be different depending upon where you are. I've seen some companies have the internal Release Engineering group be responsible for the development standards as they are responsible for what goes out the door where as others will have a formal standards group that does nothing but standards compliance.

OwnerDisplayName: Aki


问:
Indexing a database
I am not so familiar with databases and now I am trying to understand the indexing mechanism.

From what I know, in a RDBMS, indexing on a column makes searching by that column faster. This is also true for the triple stores, only there indices assume you will search(for example) mostly by the subject, then by object and so on.

I am not sure about RDBMS, but on triple stores you can define more than one index, letting the store choose the best index for each query(hopefully I understood this right). Naturally, the following question appears:

Why shouldn't I add all the possible indexes to a triple store, and extending to a RDBMS, why not make indexes on each column(assuming I am not too lazy)?

答:
The indexes are basically additional data structures which have to be built and stored. Building inde wastes CPU power (during writing operations) and storing it wastes disk capacity.

Why would you want to build and store indexes which you never use?

Title: Indexing a database


答:
You have to Implement basepage and all page needs to be derived from baseage.

```<code>public class BasePage : System.Web.UI.Page
{

}

public partial class LoginScreen: BasePage
{

}
</code>```

Or  you can use session variable.
set

```<code>HttpContext.Current.Session["IsUserInRole"] = true;
</code>```

get

```<code>bool IsUserInRole = Convert.ToBoolean(HttpContext.Current.Session["IsUserInRole"])
</code>```

Title: Can I share data between two users in an ASP.NET Application?

Body:
I have an issue with Roles.IsUserInRole function. It take hell amount of time to just check if the logged-in user is in particular role(typ 3-9 sec). I searched to find a solution and arrived on this but I am not sure If I have fully grasped it.

What I got from the above, A new derived class is created. Inside that class, there is a list which retrieves all user at once. The next time you check IsUserInRole, you do not use the actual IsUserInRole method but rather use the one you overrode in your class. Is this the correct description? Am I on track?

My question is, can data be share between two different users in ASP.NET application? If yes, will the shared data exist only if there is at least one user logged in. If all users logs out, that shared data is destroyed? My point is this data will be created only one time whenever a user logs in. For all subsequent users they can use this data and check their roles against the list? I need a detailed answer.

My application has users and different roles. We are using ASP.NET roles.

Body:
You have to Implement basepage and all page needs to be derived from baseage.

public class BasePage : System.Web.UI.Page
{

}

public partial class LoginScreen: BasePage
{

}

Or  you can use session variable.
set

HttpContext.Current.Session["IsUserInRole"] = true;

get

bool IsUserInRole = Convert.ToBoolean(HttpContext.Current.Session["IsUserInRole"])


答:
Because, essentially, an index is an extra table, where the primary key is the field you're indexing and the only content is the primary key of your main table. So every update has to be replicated in every index that uses the field you update.

This is particularly noticable on Inserts. Imagine if every insert you did to a table had to be replicated on 20 other tables. It's going to be painfully slow.

Note that this gets even worse with compound, clustered and full-text indexes, but I don't want to complicate the issue for you yet.

Title: Indexing a database

Body:
I am not so familiar with databases and now I am trying to understand the indexing mechanism.

From what I know, in a RDBMS, indexing on a column makes searching by that column faster. This is also true for the triple stores, only there indices assume you will search(for example) mostly by the subject, then by object and so on.

I am not sure about RDBMS, but on triple stores you can define more than one index, letting the store choose the best index for each query(hopefully I understood this right). Naturally, the following question appears:

Why shouldn't I add all the possible indexes to a triple store, and extending to a RDBMS, why not make indexes on each column(assuming I am not too lazy)?


答: I'm going to say yes, for one simple reason: The iPhone. Everyone I've ever spoken to thinks it's fantastic because of the slick interface, but I can only imagine the work underneath to make that all possible.</p>

Title: Do GUI programmers have an undue advantage over others?

Body:
It is easy for managers and customers to appreciate what they can see.

I have seen many GUI developers who are average programmers with minimal knowledge of design principles or other programming idioms. However, these shortcomings often go unnoticed, specially by management and customers, if the programmer can create an impressive looking user interface. So much so that many GUI developers I know spend hours beautifying the GUI at the expense of writing bad, unmaintainable code.

On the other hand, middle tier programmers who develop APIs or business functionality or database code (SQLs etc.) are at a disadvantage as there is nothing tangible to showcase. Perhaps a code reviewer or an architect may appreciate the elegance, good design, scalability etc. of code but it means nothing to the outside world. Your code may run for years without breaking, may be very easy to maintain and have good performance, yet it never elicits the 'wow' that a slick looking GUI does.

In my opinion, a corollary to this is (and I am going to get heavily downvoted for this, I know) that there is less motivation for a GUI programmer to write good clean code.

EDIT: I must explain here that by GUI programmer, I don't mean a full-fledged web/GUI designer but a front-end programmer e.g., a java-swing programmer.

Does the rest of the community agree ?


答:
Creating an index for every column in a table is usually a waste of space, and as others have mentioned, it can slow down insert/update operations. An index is used to speed up queries. I'd only recommend adding an index to a column if you notice poor performance when querying for values in that column.

Some databases may require an index for a table's primary key so you might not have a choice about that one. Also, if you have a very large text columns, there are specific technologies that are designed for full-text search and index, but they are not always the same kinds of index you'd use for a small numeric column.

Title: Indexing a database


答:
Only place indexes when needed.  As a rule of thumb when I am developing a database schema, every table gets a PK Primary Key Clustered Index to start with.  This will be the unique identifier for data in that table.  In can be on 1 column or many.

After that, I usually just add Non-Clustered Unique Indexes on column(s) which I want to enforce uniqueness on.

This is the base schema.  As the application gets developed and matures, we add indexes as needed based on performance concerns and how we are querying the data.

Every index added increases spaced used as well as adding additionally maintenance.  So choose your indexes wisely.

Title: Indexing a database


问:
Why are shortcuts like x += y considered good practice?
I have no idea what these are actually called, but I see them all the time. The Python implementation is something like:

x += 5 as a shorthand notation for x = x + 5.

But why is this considered good practice? I've run across it in nearly every book or programming tutorial I've read for Python, C, R so on and so forth. I get that it's convenient, saving three keystrokes including spaces. But they always seem to trip me up when I'm reading code, and at least to my mind, make it less readable, not more.

Am I missing some clear and obvious reason these are used all over the place?

答:
Say it once and only once: in x = x + 1, I say 'x' twice.

But do not ever write, 'a = b +=1' or we will have to kill 10 kittens, 27 mice, a dog and a hamster.

You should never change the value of a variable, as it makes it easier to prove the code is correct — see functional programming. However if you do, then it is better no say things only once.


答:
The strength of Indexes is that they are 1) a data structure that can be quickly searched through and 2) more compact than the actual tables, allowing more of the index to fit into memory instead of being paged to disk.

If you have an index on every column, then the indexes themselves will take more space than the table they represent. If the database really does use all of the indexes, it will require more time just to swap them in and out of memory. In addition, every index has to be updated on an inert, update, or delete.

Beyond that, indexes on a single column are not even the best you can do. Most relation databases actually allow an index on multiple columns, and the order of these columns matter. For example, if I want to search a database for all people who went to Duke from classes between 1980 and 1984, then what I want is an index on (School, ClassYear). The query would not be able to use an index with the same columns, but reversed.

So to create every possible index, there are at least n! ways to arrange columns in an index. With only 5 columns, there are 120 possible indexes.

Since there are so many possible indexes, you really do have to determine what indexes are useful for your application and create only those.

Title: Indexing a database


答:
As @Quagmire said, yes you can share data between your users, and the best choice would be to use the Application scope (see How To Store Data in the Application Scope).

That way, you don't need to cache anything.

However, I have a remark. I don't know enough about the application you are writing, but be careful about storing user roles, and never refreshing that information. If the user roles change in your database (or place where you are storing these information), your application would need to be restarted for these changes to be known... Not very pretty.

If the user roles never change, Application is good enough. However, if they change, there is a better solution, use ASP.NET's caching infrastructure. You can even define sliding and absolute expiration that will effectively remove the user roles information from the cache at some point.

I checked out the article linked by @KenHenderson, and he basically does that except that he sets no sliding/absolute expiration which means the cache never gets refreshed.

What I would do is attempt to improve his nice solution by setting a sliding expiration time of 30 minutes. After thirty minutes without activity, the information is removed from the cache, and the next time the user connects to your application, the user roles are refreshed.


答:
It's true that it's shorter and easier, and it's true that it was probably inspired by the underlying assembly language, but the reason it's best practice is that it prevents a whole class of errors, and it makes it easier to review the code and be sure what it does.

With

```<code>RidiculouslyComplexName += 1;
</code>```

Since there's only one variable name involved, you're sure what the statement does.

With RidiculouslyComplexName = RidiculosulyComplexName + 1;

There's always doubt that the two sides are exactly the same. Did you see the bug? It gets even worse when subscripts and qualifiers are present.

Body:
It's true that it's shorter and easier, and it's true that it was probably inspired by the underlying assembly language, but the reason it's best practice is that it prevents a whole class of errors, and it makes it easier to review the code and be sure what it does.

With

RidiculouslyComplexName += 1;

Since there's only one variable name involved, you're sure what the statement does.

With RidiculouslyComplexName = RidiculosulyComplexName + 1;

There's always doubt that the two sides are exactly the same. Did you see the bug? It gets even worse when subscripts and qualifiers are present.


答:
In my experience, you're hosed. The point of no return was when you let someone send you an e-mail in the first place.

In all seriousness, OnTime is nice and has the customer portal (the whole thing is wicked easy to setup and they have free online seminars that are pretty good) where users can create tickets, vote on things, etc.

No amount of software you put in place will be easier than your users clicking "send" though. I wish you good tidings trying to convert them!

Title: What tools do you use to manage requests from users?

Body:
I'm drowning in user emails and I'd like to implement a better way to manage all these requests I get and put them in a queue where those people on a team, as well as users, have access to them and can make common notes. I'm thinking about some sort of task management tool that would allow multiple tasks to be created under a project where emails, comments, ideas, etc. could be dropped/entered and easily accessible.

I need something that all parties can be involved in - users, managers, team leaders, developers. I'm looking for a tool that can allow:

Users to just drag/drop an email to submit a request for maintenance or enhancement.

Developers to just see their queue and the weighted priority of each task/project.

A team of developers to see what everyone is working on in real-time.

Management to keep a a log of time spent on each task.

I I am starting to look in more of a Agile/Scrum direction for solving this problem. I found list of scrum agile sofware project management open source tools. Since I am limited on time, has anyone used these? Which one should I test to see if it will meet my needs? TeamPulse is a good direction, but think it is a little too bloated. I need something simple for all parties.


答:
At least in Python, x += y and x = x + y can do completely different things.

For example, if we do

```<code>a = []
b = a
</code>```

then a += [3] will result in a == b == [3], while a = a + [3] will result in a == [3] and b == [].  That is, += modifies the object in-place (well, it might do, you can define the __iadd__ method to do pretty much anything you like), while = creates a new object and binds the variable to it.

This is very important when doing numerical work with NumPy, as you frequently end up with multiple references to different parts of an array, and it is important to make sure you don't inadvertently modify part of an array that there are other references to, or needlessly copy arrays (which can be very expensive).

Body:
I have no idea what these are actually called, but I see them all the time. The Python implementation is something like:

x += 5 as a shorthand notation for x = x + 5.

But why is this considered good practice? I've run across it in nearly every book or programming tutorial I've read for Python, C, R so on and so forth. I get that it's convenient, saving three keystrokes including spaces. But they always seem to trip me up when I'm reading code, and at least to my mind, make it less readable, not more.

Am I missing some clear and obvious reason these are used all over the place?

Body:
At least in Python, x += y and x = x + y can do completely different things.

For example, if we do

a = []
b = a

then a += [3] will result in a == b == [3], while a = a + [3] will result in a == [3] and b == [].  That is, += modifies the object in-place (well, it might do, you can define the __iadd__ method to do pretty much anything you like), while = creates a new object and binds the variable to it.

This is very important when doing numerical work with NumPy, as you frequently end up with multiple references to different parts of an array, and it is important to make sure you don't inadvertently modify part of an array that there are other references to, or needlessly copy arrays (which can be very expensive).


答:
How do people who practice TDD properly handle such situations?

by considering when to prototype vs when to code

by realizing that unit testing is not the same as TDD

by writings TDD tests to verify a feature/story, not a functional unit

The conflation of unit testing with test-driven development is the source of much anguish and woe. So let's review it once more:

unit testing is concerned with verifying each individual module and function in the implementation; in UT you'll see an emphasis on things like code coverage metrics and tests that execute very quickly

test-driven development is concerned with verifying each feature/story in the requirements; in TDD you'll see an emphasis on things like writing the test first, ensuring that the code written does not exceed the intended scope, and refactoring for quality

In summary: unit testing has an implementation focus, TDD has a requirements focus. They are not the same thing.


问:
What are graph datastores better at doing than other datastores and why?
Where previously there was only relational databases, the data store world is now rife with options like Key-Value, Document, and Graph datastores. Unfortunately, every datastore likes to show how it can be used for anything, but none of them really help people figure out when to use one model over another.

So, the question is: What "things" are graph datastores better at than relational datastores? (ie. faster, simpler, more flexible, more powerful) What makes them better at doing those things?

答:
Highly connected graphs are not easy to model or query using relational databases.

Think about social graphs - Bob is a friend to Alice, Alice is a friend to Carol.

How many friends of friends does Bob have?

Modelling and querying this kind of data is what graph datastores are good at.

Another example - think about Dr Who episodes and a corpus of data about all the actors, characters and sets used in them. In a graph datastore you could query all the episodes an actor was in a specific set with a specific character - this is not easy to model or query in relational database.