答:
Requirements for a bridge are probably much less prone to changes from users. I imagine that unless it's a very complex bridge, your users will want it to do the same thing, the whole way through the project.

I suppose that in some way, the more detailed requirements for a bridge could change (such as change to maximum load capacity, number of lanes and sidewalks, height of bridge, endpoints of bridge) but I would imagine that those some of those things are much harder to change after construction on a bridge has begun. And ultimately, a bridge is still a bridge - it gets you from one side of a geographic feature to another. I don't think anyone would decide halfway through a bridge project that it should now be a radio tower or chicken farm.

Another thought: In software, competition with similar markets can drive timelines and requirements. I don't usually see bridges built all right beside each other competing with each other for access (that and where I live they're built by government agencies in charge of infrastructure).

Also: I don't know how many bridges are given release dates and then told to stick with them. I'd like to think that a bridge won't be open for traffic until it has been thoroughly tested so that it is known to not collapse when people use it. I wish the same could be said about software, but for most software (mission-critical systems excluded, of course) the cost in lives of "bugs" and defects is much lower.

Disclaimer: I'm not an engineer and I've never built a bridge

Title: What is a good analogy to explain how software development is different than building a bridge?

Body:
If you had a manager, a couple of levels above you, tell you that building software is like building a bridge, how would you respond to that?

If this manager truly believes that we should be able to accurately estimate and build a system, what good metaphors are out there to explain why this isn't the case?


问:
What is a good analogy to explain how software development is different than building a bridge?
If you had a manager, a couple of levels above you, tell you that building software is like building a bridge, how would you respond to that?

If this manager truly believes that we should be able to accurately estimate and build a system, what good metaphors are out there to explain why this isn't the case?

答:
One of my teacher once talk about this, but the comparison was with a house. One of the main things that is different is the "invisible waste". Now that I have almost 10 years in the software industry, I think it was the best argument ever!

For example, when you build a house, if you make a mistake or the requirements change in the building process, you will need to destroy a wall or even tear the house down. All the wasted material will be there, in a big pile.

In software, we do the same (sometimes) but there is no "pile of wasted material". It's invisible, and managers don't care about invisible waste of money and time.

Since software is supposed to embrace change and that manager seems to know this (they always tell us that software is easy to change, so do it), this example show the difference between a bridge and a software.

ContentLicense: CC BY-SA 3.0


问:
Is there a factory pattern to prevent multiple instances for same object (instance that is Equal) good design?
I have a number of objects storing state.  There are essentially two types of fields.  The ones that uniquely define what the object is (what node, what edge etc), and the others that store state describing how these things are connected (this node is connected to these edges, this edge is part of these paths) etc.  My model is updating the state variables using package methods, so all these objects act as immutable to anyone not in Model scope.  All Objects extend one base type.

I've toyed with the idea of a Factory approach which accepts a Builder object and constructs the applicable object.  However, if an instance of the object already exists (ie would return true if I created the object defined by the builder and passed it to the equal method for the existing instance) the factory returns the current object instead of creating a new instance.  Because the Equal method would only compare what uniquely defines the type of object (this is node A to node B) but won't check the dynamic state stuff (node A is currently connected to nodes C and E) this would be a way of ensuring anyone that wants my Node A automatically knows its state connections.  More importantly it would prevent aliasing nightmares of someone trying to pass an instance of node A with different state then the node A in my model has.

I've never heard of this pattern before, and it's a bit odd.  I would have to do some overriding of serialization methods to make it work (ensure that when I read in a serilized object I add it to my facotry list of known instances, and/or return an existing factory in its place), as well as using a weakHashMap as if it was a weakHashSet to know whether an instance exists without worrying about a quasi-memory leak occuring.  I don't know if this is too confusing or prone to its own obscure bugs.

One thing I know is that plugins interface with lowest level hardware.  The plugins have to be able to return state that is different than my memory; to tell my memory when its own state is inconsistent.  I believe this is possible despite their fetching objects that exist in my memory; we allow building of objects without checking their consistency with the model until the addToModel is called anyways; and the existing plugins design was written before all this extra state existed and worked fine without ever being aware of it.

Should I just be using some other design to avoid this crazyness?  (I have another question to that affect that I'm posting).

答:
The pattern you are conceptualizing is called memoization, and is much more common in functional programming but is also used heavily in games programming.

As long as you encapsulate your implementation, and don't have special cases that will drive other programmers crazy, you should be in the clear.

http://en.wikipedia.org/wiki/Memoization


答:
I'd embrace the metaphor and simply point out where normal bridge building practices differ from normal software development practices.

The requirements of the bridge are defined well in advance and do not change during construction.  No one thinks about moving the starting or ending point of the bridge midway through construction.  No one expects a road bridge to magically support a train or to go from supporting a two lane rural road to an eight lane superhighway.  It's much easier to make accurate projections when you know in advance exactly what you're being asked to project rather than making guesses and dealing with constant changes.

The vast majority of bridges are using extremely tried and true materials, architectures, and techniques.  A Roman engineer could be transported two thousand years into the future and generally recognize what was going on at a modern construction site.  There would be differences, of course, but you're still building arches for load balancing, you're still using many of the same materials, etc.  Most software that is being built, on the other hand, involves lots of novelty.  If you wanted a "standard" piece of software, you'd be buying it rather than building it so if you've made the choice to build something, that strongly implies that it is novel in some way.  Novelty introduces risk but that novelty is also, presumably, what's delivering value.

It's also a bit of a myth that civil engineering projects are always accurately estimated.  Most construction projects end up taking longer and costing more than the initial projections.  The Big Dig in Boston, for example, was more than a decade over schedule and cost well more than twice the initial amount (more if you don't adjust for inflation). And very, very few people that have ever built a house will tell you about how they were pleasantly surprised that everything was completed on time and on budget.


答:
Essentially you're asking what the difference is between an engineering process and a software development process.  And there are a number of significant differences.

The top difference is the degree of constraints or requirements applied against the end product.

A bridge has fixed constraints.  "The gap to bridge is ### meters wide."

Software projects are notorious for the fluidity of their constraints.  Last week passwords needed to be 4 characters long. This week it's now 12.

The next difference is the body of knowledge surrounding the materials used to construct the end product.

Concrete, steel, and wood are all well researched and understood materials.  An 18" concrete slab reinforced with 3/4" steel rebar at ### intervals will have distinct, fixed properties.

With software and because you happened to have just blinked, your preferred framework has a new major version released. The language you are using has introduced a new concept or programming approach. The properties of software tools are significantly more fluid.

Then consider the degree of specificity surrounding the requirements.

In addition to being fixed, the requirements are easier to dictate with an engineering process.  The length of the bridge can be specified.  The minimum tonnage it has to support can (and will!) be specified.  These specifications have fixed, numeric values associated with them.  Verification of the requirement is simpler to perform in the engineering process.

Now consider a software user interface and just how fluid the terminology is with specifying how it should look and feel and be "responsive."

Next consider the repeatability of the process.

The carry-through knowledge of engineering processes is much higher than it is with software processes.  By and large, building any given bridge is pretty dang similar to building any other bridge.  It's a pretty well fixed domain.

Software ... not so much.  While we have patterns to simplify and reduce the complexity of repeated tasks, patterns remain at a much more abstract level than what an engineering design process is.

Finally, consider the level of documentation and review.

Building a bridge requires an incredible number of blueprints, schematics, and associated drawings.  Heck, there's designs just to show specific elements (such as steel) for the structure.

When was the last time you saw that degree of documentation on a software product?  If you ever have, it was a waterfall methodology which is often portrayed as "slow" and "unworkable."  How many times have your software design documents been reviewed by an external 3rd party prior to your beginning construction? How would you react towards having to wait on receiving a permit before you could begin coding?

There is value in the metaphor behind construction projects and software construction.  But it's important to not take that metaphor too far.

You asked specifically about estimating and building systems.

Estimation on the software side is more complicated due to the lack of specificity regarding the project.  Lack of repeatability also also hampers the estimate because software projects are almost always the first time you've built something like that.  Estimates on your first-of-that-kind project are always going to suffer a degree of error.

Build estimates suffer from the changing nature of the constraints / requirements.  Because it's apparently so easy to change software specifications, we fail to realize the impact of that change request.  From an engineering perspective, software construction can tolerate an amazing degree of change requests and still survive.  Not so with a traditional engineering project - you'd have to reject the change request or start the project over.

Build estimates also suffer from the changing nature of the body of knowledge.  Constantly having to hunt down why XYZ feature isn't working impedes development time and the ability to make accurate estimates.  Concrete cures in a consistently predictable manner.  Putting together a set of UI panels is nowhere near as predictable.

Disclaimers:

While I am an engineer, none of my response should be construed as a professional, engineering opinion.

While I work for an engineering firm, my comments do not necessarily represent those of my employer.

My background is in software development, not engineering process.  Apply a healthy dose of skepticism and moderation to my comments regarding engineering process.


答:
There are a lot of ways they are the same:  both are built to spec, not mass produced, both require a degree of planning, estimation, and technical expertise, and both require the application of simple principles on a larger scale.  That makes the comparison more apt than, say, assembly line manufacturing.

To me, the biggest differences are the degree of precision required in software engineering, and how easy it is to change the finished product.  That creates a vast difference in how design and implementation errors are accounted for.

As for precision, if a beam rated at 3 tons actually can only support 5999 pounds, your bridge will still stand.  If you get one bit wrong out of gigabytes, it can bring an entire software application down.  You can't just make that bit twice as strong as necessary.  It's either right or wrong.

Fortunately, when that one incorrect bit is discovered, it is relatively easy to change.  If you don't discover a flaw in your bridge design until after it's built, it can be extremely expensive to fix.

That's what makes the processes so different.  If you tested bridges the way you tested software, you would build it, then cause hurricanes, tsunamis, earthquakes, and extreme heat and cold to see if it still stands.  After rebuilding it and retesting it several times, it would finally pass the tests, and you would start letting people drive on it.  Then you would find out that blue cars cause the bridge to collapse, and you would rebuild it again.  Then a customer would complain that the Golden Gate Bridge design doesn't work when he tries to copy it for a bridge to Hawaii, and marketing would expect you to make it work for the same cost because to them it seems like the problem is exactly the same.


问:
How did they debug segmentation faults before protected memory?
Now, when I make a programming mistake with pointers in C, I get a nice segmentation fault, my program crashes and the debugger can even tell me where it went wrong.

How did they do that in the time when memory protection wasn't available? I can see a DOS programmer fiddling away and crashing the entire OS when he made a mistake. Virtualization wasn't available, so all he could do was restart and retry. Did it really go like that?

答: On the IBM 360, running Fortran batch jobs, we used to get hex core dumps. Such a dump could be as much as an inch thick of fan-fold green-and-white printer paper. It would tell what the registers were, and from there we could backtrack and figure out what the program was doing. We could find each subroutine and figure out where it stored its return address, so we could see the context. It would help to have an assembler listing of the program.</p>


问:
How can I test parts of my application against the output of third party application?
I have a fairly new C# application, approximately 6 months old, that we are now trying to incorporate testing into. (Should have been done from the start but I can't change the past)

Parts of this application involve pushing some documents out to a folder. A third party application then picks these up, does its own work on them, and drops output files in another folder.

My application waits for this to be done, picks up the outputs, then continues its work.

This poses a problem when testing as I can't really install another version of the third party just for testing, nor can I mock it without ending up fully rewriting the third party application.

How can I test these parts of my application? (Preferably with NUnit)

Specifically, I'm asking about how to unit test my code against the output of the 3rd party tool. So it's a little bit different than another similar question, which involves isolating how code interfaces with a third party.

答:
You do unit testing by mocking the third-party component, so that you're not checking the behavior of that component but rather just yours, and you do integration testing by including the third party component in the tests and checking that the whole ensemble works together. Neither precludes the need to do the other; while you want to carefully check that your part passes information around correctly, you still need to make sure that you're not doing something daft that the other component doesn't like (e.g., passing the wrong options or a badly encrypted password).

Be aware that integration testing is considerably more difficult than unit testing, as you need to check with an environment that is at least partially equivalent to a real deployment. (At the moment, I'm working with an application that is very difficult to automatically deploy, so our integration testing is an utter PITA as it can't be tied in with our CI system…)


问:
File storage for a blog component: database or filesystem?
I'm going to develop a fairly basic re-usable blog component, with simple CRUD operations using ASP.Net.

Which method of storing blog posts would be best suited to the situation in terms of performance/maintainability?

Create an XML file and store data in filesystem, filesize will not likely be any more than 50kb in size

Store blog post data in DB, retrieve as needed

Am I right in assuming that the asp.net runtime will cache the .xml files and only clear them/request a fresh copy when their contents are changed? Or do you have to explicitly add the file to the cache? If this is the case would this offer the best performance over storing the data in the database?

答: Use a database, thats what they are for.  File storage has its place, but I wouldnt use it for this kind of scenario.  Consider, for example, getting a list of blog posts containing a certain tag.  Doing that with a database is trivial - likely just a single SQL statement.  Doing it with files will involve a lot of file manipulation.</p>


问:
AGPL License - does it apply in this scenario?
There is an AGPLv3 based software (Client) that makes web service calls (using SOAP) to another software (Server - commercial, cloud based). There is no common code or any connection whatsoever between these two except for the web service calls being made.

My questions -

Does the Server need to be AGPL too?  I guess not - but would like to confirm.

Let us say the end point URL for the Server can be configured on the Client side (by editing an XML file) to connect it to different Servers (again, there is no connection other than the webservice calls being made) does it require any of these Servers being AGPL?

Are there any issues in running the Client as a DLL that is loaded by other commercial applications on users' desktops? Does it require these other applications also to be AGPL?

答:
tl;dr: Using AGPL this way might not have the effects expected.

Does the Server need to be AGPL too? I guess not - but would like to confirm.

There is no way for the license on the client to force the server to change its license, whatever the license on the client. There is no way to force that legal restriction; the commercial company simply cannot be bound that way. If this conflicts with the license of the client, then it is the client that is incorrectly licensed (and which hence should not be distributed by anyone other than its copyright holder; standard copyright rules apply).

Persuading any organization to pick a license based on what people (or organizations) that are “downstream” of them do is a hard sell at the best of times. Telling them that, because of some random third party that is totally beyond their control, they have to switch to a license that is objectionable to them (for whatever reason) is just not going to work. They simply do not have such an obligation to you.

Let us say the end point URL for the Server can be configured on the Client side (by editing an XML file) to connect it to different Servers (again, there is no connection other than the webservice calls being made) does it require any of these Servers being AGPL?

That's even more ridiculous. Suppose you edited that URL in that file to point at an installation of Microsoft Sharepoint; would that force MS to license one of their key commercial products under the AGPL? That's totally laughable.

No, what you'd actually be doing is breaking the terms of use of the client software. Strictly, if it is AGPL then it should only ever be pointed at AGPL services (excepting where the copyright holder grants an explicit exception).

Are there any issues in running the Client as a DLL that is loaded by other commercial applications on users' desktops? Does it require these other applications also to be AGPL?

It should require that in order for everything to be properly correct, though there's a strong chance that that's not what will actually happen. Instead, what you'll actually get is users breaking the license agreement. Unless the AGPL client is promiscuously offering itself to other programs to load (there at least used to be ways to do this in Windows, though it is now much rarer except for a few parts of the OS itself) in which case it could be argued that the software was trying entrap users into breaking the license. Not a good idea if you want to actually enforce the license!

But you won't persuade the commercial software authors to change (unless they're deliberately searching out the AGPL software for loading despite knowing that it is AGPL). That the commercial software is able, at the prompting of the user, to load an arbitrary DLL and use some sort of introspection to invoke a function within it (such code exists) would not in itself be enough to force a dependency; it would again be the user who is the party causing the problem, not the commercial firm. (Understanding the API presented by the AGPL-ed DLL would not in itself cause a link; there have been fairly recent court decisions to the effect that APIs are not subject to license restrictions at all. This irritated Oracle a lot IIRC.)


答:
Am I right in assuming that the asp.net runtime will cache the .xml files and only clear them/request a fresh copy when their contents are changed?  Or do you have to explicitly add the file to the cache?

No, that isn't a valid assumption. You must opt in to caching and come up with a system for invalidation.

If this is the case would this offer the best performance over storing the data in the database?

It's all about the memory vs bandwidth vs processing time tradeoff. You'll need to define what you value in performance before anyone could tell you whether it'll be the best. If you value CPU and bandwidth more than memory, then definitely.

Title: File storage for a blog component: database or filesystem?

Body:
I'm going to develop a fairly basic re-usable blog component, with simple CRUD operations using ASP.Net.

Which method of storing blog posts would be best suited to the situation in terms of performance/maintainability?

Create an XML file and store data in filesystem, filesize will not likely be any more than 50kb in size

Store blog post data in DB, retrieve as needed

Am I right in assuming that the asp.net runtime will cache the .xml files and only clear them/request a fresh copy when their contents are changed? Or do you have to explicitly add the file to the cache? If this is the case would this offer the best performance over storing the data in the database?


答: You could adopt a hybrid approach, by storing the structured, metadata of each blog post in a database, and then store the raw text on your file-system (or in a blob-store). Storing the metadata in a database allows you to perform queries for blogs by title, date, tag, user, etc. in a very straightforward way, while allowing the text size of your blog posts to be unbounded. This may be of interest since you stated that this was intended to be part of a reusable blog component.</p>


问:
Building one way chat?
I'm implementing a Windows 8 app using C#, part of it is One Way Chat. It will be for multiple users such as teacher and student. We want to use a chat room for every course.

Teachers teach different courses that include many students and students study different courses, so when the teacher and student open the course page, they will find a chat page specific for this course.

How can I build such a thing?

答: I would recommend skinning the IRC protocol. This will save you a ton of time, give you a lot of flexibility, and it already supports one-way chat using the voice privilege.</p>

Title: Building one way chat?


问:
Are Intel compilers really better than the Microsoft ones?
Years ago, I was surprised when I discovered that Intel sells Visual Studio compatible compilers. I tried it in particular for C/C++ as well as fantastic diagnostic tools. But the code was simply not that computationally intensive to notice the difference. The only impression was: did Intel really do it for me just now, wow, amazing tools with nanoseconds resolution, unbelievable. But the trial ended and the team never seriously considered a purchase.

From your experience, if license cost does not matter, which vendor is the winner?

It is not a broad or vague question or attemt to spark a holy war. This sort of question is about two very visible tools. Nobody likes when tools have any mysteries or surprises. And choices between best and best are always the pain. I also understand the grass is always greener argument. I want to hear all "what ifs" stories.

What if Intel just locally optimizes it for the chip stepping of the month, and not every hardware target will actually work as well as Microsoft compiled? What if AMD hardware is the target and everything will slow down for no reason? Or on the other hand, what if Intel's hardware has so many unnoticable opportunities, that Microsoft compiler writers are too slow to adopt and never implement it in the compiler? What if both are the same exactly, actually a single codebase just wrapped into two different boxes and licensed to both vendors by some third-party shop?

And so on. But someone knows some answers.

答:
Check this benchmark page. In short, intel wins. </p>

<p>But the margin may not be that big: if you compile to 32 bit, and your build system cant support profile guided optimization, the gain is of the order of 10%. Is such an improvement worth the trouble and the longer compile times? </p>

Body:
Check this benchmark page. In short, intel wins.

But the margin may not be that big: if you compile to 32 bit, and your build system cant support profile guided optimization, the gain is of the order of 10%. Is such an improvement worth the trouble and the longer compile times?


问:
Where to put details about the acceptance criteria of a user story?
In this blog post about acceptance criteria the author explains that good acceptance criteria should:

State an intent not a solution (e.g. “The user can choose an account”
rather than “The user can select the account from a drop-down”)

Are independent of implementation (ideally the phrasing would be the
same regardless whether this feature/story would be implemented on
e.g. web, mobile or a voice activated system)

Are relatively high level (not every detail needs to be in writing)

And further details such as:

The column heading is “Balance”

The rolling balance format is 99,999,999,999.9 D/CR

We should use a dropdown rather than checkboxes

should be moved to either a Team internal documentation or Automated acceptance tests

However,
I often hear people frowning about using Cucumber or similar frameworks for doing GUI tests.
Moreover, using an internal documentation could generate lots of problems due to failure to update the documentation regularly.

I'm still struggling to find an effective way to capture such details during the conversation with the customer.

答:
I have two places (as the product owner)

New feedback from customers can translate in more stories, a change of story priorities or some new details about a story. In the back log I take notes of these details for future stories that I might forget otherwise. These are notes for myself.

Shortly before the planning meeting, I translate what is in my head + these notes into something the team can review. This document (we use a wiki page per user epic) is further refined & completed during sprint planning as a part of  discussing the story with the team.


问:
Are error codes wrong in SQL queries too?
I have an SQL query which does several things at once¹: it does multiple checks and then, if the checks pass, updates some data. Without entering in the domain-specific details, here's an imaginary example:

-- The user password should be updated only if the user account is not removed and
-- not locked, and the threshold was not exceeded.
if exists (select * from [People].[User] where [UserId] = @UserId)
begin
    if exists (select * from [People].[User] where [UserId] = @UserId and [IsLocked] = 0)
    begin
        if exists (select * from [People].[User]
                   where [UserId] = @UserId and [IsRemoved] = 0)
        begin
            update [People].[User] set [PasswordHash] = @Hash where [UserId] = @UserId
            select 0 -- Success.
        end
        else
        begin
            select 3 -- The account doesn't exist any longer.
        end
    end
    else
    begin
        select 2 -- The account is locked.
    end
end
else
begin
    select 1 -- The user cannot be found.
end
```

<p>The query is then used like this:</p>

<pre class="lang-cs prettyprint-override"><code>var errorCode = new SqlDataQuery(query, Program.ConnectionString)
    .With(new { UserId = this.Id, Hash = this.ComputeHash() })
    .ReadValue<int>();

// Error codes are used only between the database and code, and transformed into exceptions
// as soon as possible.
switch (errorCode)
{
    case 1: throw new UserNotFoundException();
    case 2: throw new AccountPermissionException();
    case 3: throw new AccountRemovedException();
}
</code>```

In general programming, error codes are considered bad and should be replaced by conventional error handling procedures, including exceptions.

Is it also bad to use them in SQL queries? If yes, how should I rewrite the query to follow best practices?

¹ Given the non-functional requirements related to the load and performance, there is no way to make several consecutive queries. All the checks and the update should be done in a single query.

答: Depending on your SQL implementation, you may have a RAISE, RAISERROR, or similar statement you can use in your query to fail the operation with an exception-like result.  That's the best answer.


答:
If this is only one-way, implement a little embedded web server or xmlrpc server in the teacher's app. Then, each student can post a message or call an xmlrpc function to send a message to the teacher. All they need to know is the IP address of the teacher's machine.

You could also try searching the internet for "simple echo server". This is a common thing to build if you're new to network programming so there are lots of tutorials and example code. Typically it's a few dozen lines of code that simply echoes back whatever it receives. You can then modify the code to update the teacher's GUI rather than echo the data back.

Title: Building one way chat?

Body:
I'm implementing a Windows 8 app using C#, part of it is One Way Chat. It will be for multiple users such as teacher and student. We want to use a chat room for every course.

Teachers teach different courses that include many students and students study different courses, so when the teacher and student open the course page, they will find a chat page specific for this course.

How can I build such a thing?


问:
Is Oberon really "a better Pascal"?
Reading Niklaus Wirth, one can notice that despite some popularity of Pascal, he is not glad that Oberon (as a "polished" successor of Pascal and Modula) didn't get much popularity. I never did anything in Oberon, but reading the page Oberon For Pascal Developers I really did not like many of the changes as a Delphi/pascal developer, for example

forcing the reserved words to be always uppercase

making the language case-sensitive

getting rid of enumeration types

What do you think about Oberon, is it really "a better Pascal" from your point of view?

答:
Yes, I would call Oberon a better Pascal. With Oberon, Professor Wirth got to the core of object oriented programming with type extension and procedure variables. I find it elegant that Oberon is a smaller language than Pascal with much more power.

Oberon 2 took the language a step further by binding methods to records.

I do dislike the upper case reserved words. I find the syntax an improvement with the elimination of many begins and ends.

Oberon was used to write a very interesting operating system described in Project Oberon: The Design of an Operating System and Compiler.

Title: Is Oberon really "a better Pascal"?

ContentLicense: CC BY-SA 2.5


答:
I like defining acceptance tests for each Story BDD-style as part of the high-level documentation (Features - Stories - Tests)

```<code>WHEN [preconditions]
GIVEN [trigger action/condition/event/situation]
THEN [expected outcome]
</code>```

Specific details such as those mentioned above would be part of a screen mockup that the client signs off on; such details are not always known in advance, but in any event they fall under 'design constraints'. I do, when the mockups are known in advance, include the mockups and agreed-upon design constraints in the high-level documentation, because the client must sign off on it before work begins.

So, while conceptually separate, I see no harm in including it in the same document. Even if it's not required for client sign-off, it is convenient to have all of the requirements for a feature/story in one place.

Title: Where to put details about the acceptance criteria of a user story?

Body:
In this blog post about acceptance criteria the author explains that good acceptance criteria should:

State an intent not a solution (e.g. “The user can choose an account”
rather than “The user can select the account from a drop-down”)

Are independent of implementation (ideally the phrasing would be the
same regardless whether this feature/story would be implemented on
e.g. web, mobile or a voice activated system)

Are relatively high level (not every detail needs to be in writing)

And further details such as:

The column heading is “Balance”

The rolling balance format is 99,999,999,999.9 D/CR

We should use a dropdown rather than checkboxes

should be moved to either a Team internal documentation or Automated acceptance tests

However,
I often hear people frowning about using Cucumber or similar frameworks for doing GUI tests.
Moreover, using an internal documentation could generate lots of problems due to failure to update the documentation regularly.

I'm still struggling to find an effective way to capture such details during the conversation with the customer.

Body:
I like defining acceptance tests for each Story BDD-style as part of the high-level documentation (Features - Stories - Tests)

WHEN [preconditions]
GIVEN [trigger action/condition/event/situation]
THEN [expected outcome]

Specific details such as those mentioned above would be part of a screen mockup that the client signs off on; such details are not always known in advance, but in any event they fall under 'design constraints'. I do, when the mockups are known in advance, include the mockups and agreed-upon design constraints in the high-level documentation, because the client must sign off on it before work begins.

So, while conceptually separate, I see no harm in including it in the same document. Even if it's not required for client sign-off, it is convenient to have all of the requirements for a feature/story in one place.


问:
Storing data in code
A few times in my past I've wanted to store data in code. This would be data that seldom changes and is used in places where access to a database isn't possible, practical, or desirable. A small example would be storing a list of countries. For that you could do something like:

```<code>public class Country
{
    public string Code { get; set; }
    public string EnglishName {get;set;}
}

public static class CountryHelper
{
    public static List<Country> Countries = new List<Country>
        {
            new Country {Code = "AU", EnglishName = "Australia"},
            ...
            new Country {Code = "SE", EnglishName = "Sweden"},
            ...
        };

    public static Country GetByCode(string code)
    {
        return Countries.Single(c => c.Code == code);
    }
}
</code>```

I've got away with doing this in the past because the data sets were relatively small and the objects pretty simple. Now I'm working with something that will have more complex objects (5 - 10 properties each, some properties being dictionaries) and around 200 objects total.

The data itself changes very rarely and when it does change it's really not even that important. So rolling it into the next release version is perfectly fine.

I'm planning to use T4 or ERB or some other templating solution to turn my data source into something that is stored statically in the assembly.

It seems my options are

Store the data in XML. Compile the XML file as an assembly resource. Load data as needed, store loaded data into a Dictionary for repeat-use performance.

Generate some kind of static object or objects that are initialized at startup.

I'm pretty sure I understand the performance implications of option 1. At least, my hunch is that it wouldn't have stellar performance.

As for option 2, I don't know what to do. I don't know enough about the internals of the .NET framework to know the best way to actually store this data in C# code and the best ways to initialize it. I poked around using .NET reflector to see how System.Globalization.CultureInfo.GetCulture(name) works, since this is actually a very similar workflow to what I want. Unfortunately that trail ended at an extern, so no hints there. Is initializing a static property with all the data, as in my example, the way to go? Or would it be better to create the objects on demand and then cache them, like this?

```<code>    private static readonly Dictionary<string, Country> Cache = new Dictionary<string,Country>();

    public static Country GetByCode(string code)
    {
        if (!Cache.ContainsKey(code))
            return Cache[code];

        return (Cache[code] = CreateCountry(code));
    }

    internal static Country CreateCountry(string code)
    {
        if (code == "AU")
            return new Country {Code = "AU", EnglishName = "Australia"};
        ...
        if (code == "SE")
            return new Country {Code = "SE", EnglishName = "Sweden"};
        ...
        throw new CountryNotFoundException();
    }
</code>```

The advantage to creating them at once in a static member is that you can use LINQ or whatever else to look at all the objects and query them if you want. Though I suspect doing this has a startup performance penalty. I'm hoping someone has experience with this and can share their opinions!

答:
Given that these are essentially key-value pairs, I recommend storing these strings as a resource file embedded in your assembly at compile time. You can then read them out using a ResourceManger. Your code would look something like this:

```<code>private static class CountryHelper
{
    private static ResourceManager rm;

    static CountryHelper()
    {
        rm = new ResourceManager("Countries",  typeof(CountryHelper).Assembly);
    }

    public static Country GetByCode(string code)
    {
        string countryName = rm.GetString(code + ".EnglishName");
        return new Country { Code = code, EnglishName = countryName };
    }
}
</code>```

To make it a bit more efficient you can load them all at once, like this:

```<code>private static class CountryHelper
{
    private static Dictionary<string, Country> countries;

    static CountryHelper()
    {
        ResourceManager rm = new ResourceManager("Countries",  typeof(CountryHelper).Assembly);
        string[] codes = rm.GetString("AllCodes").Split("|"); // AU|SE|...
        countries = countryCodes.ToDictionary(c => c, c => CreateCountry(rm, c));
    }

    public static Country GetByCode(string code)
    {
        return countries[code];
    }

    private static Country CreateCountry(ResourceManager rm, string code)
    {
        string countryName = rm.GetString(code + ".EnglishName");
        return new Country { Code = "SE", EnglishName = countryName };
    }
}
</code>```

This will help you out a lot if you ever need to make your application support multiple languages.

If this happens to be a WPF application, a resource dictionary is a much more obvious solution.

Title: Storing data in code

Body:
Given that these are essentially key-value pairs, I recommend storing these strings as a resource file embedded in your assembly at compile time. You can then read them out using a ResourceManger. Your code would look something like this:

private static class CountryHelper
{
    private static ResourceManager rm;

    static CountryHelper()
    {
        rm = new ResourceManager("Countries",  typeof(CountryHelper).Assembly);
    }

    public static Country GetByCode(string code)
    {
        string countryName = rm.GetString(code + ".EnglishName");
        return new Country { Code = code, EnglishName = countryName };
    }
}

To make it a bit more efficient you can load them all at once, like this:

private static class CountryHelper
{
    private static Dictionary<string, Country> countries;

    static CountryHelper()
    {
        ResourceManager rm = new ResourceManager("Countries",  typeof(CountryHelper).Assembly);
        string[] codes = rm.GetString("AllCodes").Split("|"); // AU|SE|...
        countries = countryCodes.ToDictionary(c => c, c => CreateCountry(rm, c));
    }

    public static Country GetByCode(string code)
    {
        return countries[code];
    }

    private static Country CreateCountry(ResourceManager rm, string code)
    {
        string countryName = rm.GetString(code + ".EnglishName");
        return new Country { Code = "SE", EnglishName = countryName };
    }
}

This will help you out a lot if you ever need to make your application support multiple languages.

If this happens to be a WPF application, a resource dictionary is a much more obvious solution.


答:
The best example of this that exists is probably WPF... Your forms are written in XAML, which is basically XML, except that .NET is able to rehydrate it into an object representation very quickly. The XAML file is compiled into a BAML file, and squeezed into ".resources" file, which is then embedded within the assembly (the latest version of .NET reflector can show you these files).

Although there isn't any great documentation to support it, MSBuild should in-fact be able to take a XAML file, convert it to BAML, and embed it for you (it does it for forms right?).

So, my approach would be: Store your data in XAML (it's just an XML representation of an object graph), stuff that XAML into a resources file, and embed it in the assembly. At runtime grab the XAML, and use XamlServices to rehydrate it. Then either wrap it in a static member, or use Dependency Injection if you want it to be more testable, to consume it from the rest of your code.

A few links that are useful reference material:

AL.exe (for embedding resources in assemblies)

Resgen.exe (for converting .resx files to resources)

XamlServices class

On a side note, you can actually use the app.config, or web.config files to load up reasonably complex objects through the settings mechanism if you want the data to be changed more easily. And you can also load XAML from the file system.

Title: Storing data in code

Body:
A few times in my past I've wanted to store data in code. This would be data that seldom changes and is used in places where access to a database isn't possible, practical, or desirable. A small example would be storing a list of countries. For that you could do something like:

```<code>public class Country
{
    public string Code { get; set; }
    public string EnglishName {get;set;}
}

public static class CountryHelper
{
    public static List<Country> Countries = new List<Country>
        {
            new Country {Code = "AU", EnglishName = "Australia"},
            ...
            new Country {Code = "SE", EnglishName = "Sweden"},
            ...
        };

    public static Country GetByCode(string code)
    {
        return Countries.Single(c => c.Code == code);
    }
}
</code>```

I've got away with doing this in the past because the data sets were relatively small and the objects pretty simple. Now I'm working with something that will have more complex objects (5 - 10 properties each, some properties being dictionaries) and around 200 objects total.

The data itself changes very rarely and when it does change it's really not even that important. So rolling it into the next release version is perfectly fine.

I'm planning to use T4 or ERB or some other templating solution to turn my data source into something that is stored statically in the assembly.

It seems my options are

Store the data in XML. Compile the XML file as an assembly resource. Load data as needed, store loaded data into a Dictionary for repeat-use performance.

Generate some kind of static object or objects that are initialized at startup.

I'm pretty sure I understand the performance implications of option 1. At least, my hunch is that it wouldn't have stellar performance.

As for option 2, I don't know what to do. I don't know enough about the internals of the .NET framework to know the best way to actually store this data in C# code and the best ways to initialize it. I poked around using .NET reflector to see how System.Globalization.CultureInfo.GetCulture(name) works, since this is actually a very similar workflow to what I want. Unfortunately that trail ended at an extern, so no hints there. Is initializing a static property with all the data, as in my example, the way to go? Or would it be better to create the objects on demand and then cache them, like this?

```<code>    private static readonly Dictionary<string, Country> Cache = new Dictionary<string,Country>();

    public static Country GetByCode(string code)
    {
        if (!Cache.ContainsKey(code))
            return Cache[code];

        return (Cache[code] = CreateCountry(code));
    }

    internal static Country CreateCountry(string code)
    {
        if (code == "AU")
            return new Country {Code = "AU", EnglishName = "Australia"};
        ...
        if (code == "SE")
            return new Country {Code = "SE", EnglishName = "Sweden"};
        ...
        throw new CountryNotFoundException();
    }
</code>```

The advantage to creating them at once in a static member is that you can use LINQ or whatever else to look at all the objects and query them if you want. Though I suspect doing this has a startup performance penalty. I'm hoping someone has experience with this and can share their opinions!


问:
better method to revert state if failure occures during add/delete
So I have a generic framework with a concept of children and parent objects, the objects don't have to be the same type, and I can add or remove any of them.  Adding calls add on all the children, and informs the parents, inverse for remove.

the concept of Parent is generic enough that there can be a loop across classes.  A may be a parent of B which is a parent of C which is a parent of A.  This still works, since I mark an object as added or removed as the first step in the abstract class; so even if a circular dependency calls Add a second time on the same object the second time through the add will return without doing anything (because the added boolean is already set) and we halt our recursion.

If some unexpected exception occurs I want to revert my state back to what it was before the exception occurs.  I was doing this with exception handling, if I catch a run time connection I remove objects I added and update parents before throwing the exception.  This is where my logic can fail.  As of now I 'revert' the AddObject method by calling removeObject and vice versa.  If my state somehow ended up in a truly bizarre state I could keep throwing exceptions, add throws and calls remove, remove throws and calls add, etc etc.  I think this still has a chance for infinite recursion; though admittedly something would already have to be pretty messed up in my state for it to happen.

Is there a cleaner way to do my rollback logic to avoid this potential?  At a point like this what should I say my state should be once I recover anyways?

答:
If you can afford the memory, you could take a snapshot before making any changes. If everything goes fine, delete the snapshot. If anythong goes wrong, drop the new version and just revert to the snapshot.

If this is too expensive, you could first compute which parts could possibly be affected (DFS or something) and only take a snapshot of those parts.


问:
UML communication diagrams, implementation details or not?
After reading Applying UML and Patterns (Larman) and looking around on the Internet it still seems ambiguous to me if a UML communication diagram should depict implementation details (such as GUI related function calls) or be more bound to the analysis. What is the correct answer? Does UML even specify it?</p>

答:
Well, it depends on the view the diagram belongs too.

If the diagram is part of the Logical View or the Use Case View, it should not dive into the very details of the implementation because this view is concerned with the functionality provided to end users and may be used communicate the architecture to end users, domain experts and others who do not care much about the internal functions.

On the other hand if the diagram is part of the Development View, it's your call. The development view is used to communicate the architecture to the developers. So if you believe the details of GUI function calls and so on will help the developer understand what you want then it's Ok.


问:
Copyright notices/disclaimers in source files
It's a common practice to place copyright notices, various legal disclaimers and sometimes even full license agreements in each source file of an open-source project. Is this really necessary for a (1) open-source project and (2) closed-source project? What are you trying to achieve or prevent by putting these notices in source files?

I understand it's a legal question and I doubt we can get a fully competent answer here at programmers.SO (it's for programmers, isn't it?) What would also be interesting to hear is, when you put legal stuff in your source files, is it because "everyone does it" or you got legal advice? What was the reasoning?

答:
For any open-source project

You are defining the conditions under which the code is to be used and redistributed (or not, depending on those conditions).

At the very least, a license can answer questions such as:

Appropriation: Can someone take the code and evolve it into a different project? A good example of such a phenomenon is Google Chrome, which is based upon the open-source Chromium project.

Do they need to give you credit, seek permission, etc...

Commercial Use: Can your code be used commercially, such as within Photoshop as a third-party DLL? If so do different conditions apply?

Redistribution: Do any uses of your code have to be in software with a similar/identical license? Licenses such as the GPL which require this are called viral licenses (and I don't know if that's a negative term, or just a statement of fact).

Etc. That's by no means a comprehensive list, it's just to give you an idea of the questions a license would state clearly.


答:
I guess the System.Globalization.CultureInfo.GetCulture(name) would call Windows APIs to get the data from a system file.

For loading the data in code, just like @svick had said, if you're about to load 200 objects, it won't be a problem in most cases, unless your code running on some low memory devices.

If your data never changes, my experience is simply using a list/dictionary like:

```<code>private static readonly Dictionary<string, Country> _countries = new Dictionary<string,Country>();
</code>```

But problem is that you need to find a way to initialise your dictionary.
I guess this is the pain point.

So the problem is changed to "How to generate your data?".
But this relates to what you need.

If you want to generate data for the countries, you could use the

```<code>System.Globalization.CultureInfo.GetCultures()
</code>```

get the CultrueInfo array, and you could initialise your dictionary with your needs.

And of course you could put the code in a static class, and initialise the dictionary in the static constructor like:

```<code>public static class CountryHelper
{
    private static readonly Dictionary<string, Country> _countries;
    static CountryHelper()
    {
        _countries = new Dictionary<string,Country>();
        // initialization code for your dictionary
        System.Globalization.CultureInfo[] cts = System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures);
        for(int i=0; i < cts.Length; i++)
        {
            _countries.Add(cts[i].Name, new Country(cts[i]));
        }
    }

    public static Country GetCountry(string code)
    {
        Country ct = null;
        if(this._countries.TryGet(code, out ct))
        {
            return ct;
        } else
        {
            Log.WriteDebug("Cannot find country with code '{0}' in the list.", code);
            return null;
        }
    }
}
</code>```

Title: Storing data in code

Body:
I guess the System.Globalization.CultureInfo.GetCulture(name) would call Windows APIs to get the data from a system file.

For loading the data in code, just like @svick had said, if you're about to load 200 objects, it won't be a problem in most cases, unless your code running on some low memory devices.

If your data never changes, my experience is simply using a list/dictionary like:

private static readonly Dictionary<string, Country> _countries = new Dictionary<string,Country>();

But problem is that you need to find a way to initialise your dictionary.
I guess this is the pain point.

So the problem is changed to "How to generate your data?".
But this relates to what you need.

If you want to generate data for the countries, you could use the

System.Globalization.CultureInfo.GetCultures()

get the CultrueInfo array, and you could initialise your dictionary with your needs.

And of course you could put the code in a static class, and initialise the dictionary in the static constructor like:

public static class CountryHelper
{
    private static readonly Dictionary<string, Country> _countries;
    static CountryHelper()
    {
        _countries = new Dictionary<string,Country>();
        // initialization code for your dictionary
        System.Globalization.CultureInfo[] cts = System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures);
        for(int i=0; i < cts.Length; i++)
        {
            _countries.Add(cts[i].Name, new Country(cts[i]));
        }
    }

    public static Country GetCountry(string code)
    {
        Country ct = null;
        if(this._countries.TryGet(code, out ct))
        {
            return ct;
        } else
        {
            Log.WriteDebug("Cannot find country with code '{0}' in the list.", code);
            return null;
        }
    }
}


问:
Should I not try to emulate private class data in javascript?
So I have been building this ORM style library for AngularJS (JavaScript) and since I come from a C++/PHP/C# background, I always try to make sure that private things stay private.  While this can be accomplished in JavaScript, I keep running into issues that I have to work around probably because JavaScript really does not have the transitional class system that I am used to.

Should I just take the python approach and allow people to access private methods/data if they think they know what they are doing?  Is this type of approach common in the JavaScript world?

答:
Use a well-established convention, such as а leading underscore, or a pattern such as the Revealing Module Pattern.

One advantage to using a pattern that enforces visibility at the language level rather than just using a naming convention is intellisense support. Developers that are working in a IDE may not want to see the private methods and data.

The most important thing, though, is that you communicate your intent to other programmers, whether they are working on the library itself or simply using it. This way it is clear which methods and variables are considered implementation details that are subject to change. It will also help you as a developer to minimize your dependencies in the code.

The question you have to decide, then, is whether you want to enforce it at the language level, such that attempting to access it is an error that would require changing the source code to get around. The naming convention is simpler and less strict, but requires more discipline.


答:
I would go with option one. It's simple & easy to read. Someone else looking at your code will understand it straight away. It'll also be easier to update your XML data if needs be. (Plus you could let the user update them if you have a nice front end and stored the files separately)

Only optimise it if you need to - premature optimisation is evil :)

Title: Storing data in code


问:
parallel computing list of objects
I have a list of objects that all require the exact same filtering, basically a set of conditionals in a function which outputs if the object is "good" or "bad".  I want to keep all of my "good" objects in the list.  Lets say I have 1000 objects in this list and the function I want to filter on in written.  What languages/functionality would maximize how parallel this operation could be?  I have played with python's multiprocessing, which does improve performance, but still left me unsatisfied.  I suppose this is an "embarrassingly parallel" problem as no state needs to be shared.  </p>

答:
I'm not entirely sure as to what to answer to this question, but two immediate possibilities come to my mind:

Scala

As you are already describing the problem in a functional way and explicitly state that you have no shared state, the parallel collection API of Scala seems like a perfect match for the problem. It may not provide top performance though (see below for that), but will certainly require only a tiny amount of effort to setup. Something like the following is all you need really:

```<code>myList.par.filter(goodBadCondition)
</code>```

The .par turns any collection into a parallelized one, which executes operations like filter in parallel using the JVM's fork/join-support. Note that the parallel collection operations are stable, i.e. the order of the original list elements remains the same in the result (for those elements that passed the condition).

GPU based

If you really want to squeeze out a maximum of performance, then letting the GPU perform the filtering seems the perfect way to go. In this case, most of your speed loss comes from having to send data to/from the GPU. While the operation you want to perform is a perfect match for something like Cuda, I am not entirely sure that it is worthwhile. For example, if your condition is very simple and extremely fast to check, then the overhead of having to transfer the whole list to the GPU may not pay off against a quad core CPU which can process the whole list in its memory.

On the other hand, if your filter condition is costly to check, then you can check way more elements at the same time as compared to a CPU. Depending on the card you use, you can get from several dozens up to hundreds of GPU cores to perform the work.

However, the implementational effort of this approach is far higher than the one above. You also need to have a lot more knowledge about GPU programming and you will need a lot of code for such a supposedly trivial task (newer frameworks to simplify this are starting to appear though).

Title: parallel computing list of objects

Body:
I'm not entirely sure as to what to answer to this question, but two immediate possibilities come to my mind:

Scala

As you are already describing the problem in a functional way and explicitly state that you have no shared state, the parallel collection API of Scala seems like a perfect match for the problem. It may not provide top performance though (see below for that), but will certainly require only a tiny amount of effort to setup. Something like the following is all you need really:

myList.par.filter(goodBadCondition)

The .par turns any collection into a parallelized one, which executes operations like filter in parallel using the JVM's fork/join-support. Note that the parallel collection operations are stable, i.e. the order of the original list elements remains the same in the result (for those elements that passed the condition).

GPU based

If you really want to squeeze out a maximum of performance, then letting the GPU perform the filtering seems the perfect way to go. In this case, most of your speed loss comes from having to send data to/from the GPU. While the operation you want to perform is a perfect match for something like Cuda, I am not entirely sure that it is worthwhile. For example, if your condition is very simple and extremely fast to check, then the overhead of having to transfer the whole list to the GPU may not pay off against a quad core CPU which can process the whole list in its memory.

On the other hand, if your filter condition is costly to check, then you can check way more elements at the same time as compared to a CPU. Depending on the card you use, you can get from several dozens up to hundreds of GPU cores to perform the work.

However, the implementational effort of this approach is far higher than the one above. You also need to have a lot more knowledge about GPU programming and you will need a lot of code for such a supposedly trivial task (newer frameworks to simplify this are starting to appear though).


问:
What should I do when waiting for a review?
Before asking my question, I must explain the situation.

I'm working for a company as a junior software engineer. One of the seniors always stops me when I have finished my development and want to commit.

He always wants me to wait for him to review it. This is ok, because usually he finds some bugs, and does some optimizations.

However I must commit my code before the deadline. When I finished, I call him and say it is finished. He usually comes late. So my code is late too.

My question is, what should I do? Should I wait him for a review?

EDIT: Addition to the question. I'm curious about one more issue.

I want to be free when coding. How could I gain the trust for freedom of development?

Some explanations:
I've talked with him about this. But it didn't help. We use an issue tracker already, but there isn't any task for reviews. There are just development and test tasks.

答:
So my code is late too.

No, it is not your code, it is the code of you and the senior. You are working as a team, you have a shared responsibility, and when you two miss a deadline, it is the fault of both of you. So make sure the one who makes the deadlines notices that. If that person sees that as a problem, too, he will surely talk to both of you together - that may help more than a single talk with you coworker.

And to your EDIT:

I want to be free when coding. How could I gain the trust for development freedom?

Reviewing code is one of the most important quality savers. It is virtually impossible to write excellent code without a second pair of eyes, even when you have >20 years of programming experience. So in a good team, everyones code should be constantly reviewed - your senior's code as well as your code. This has nothing to do with distrust against you in person (or, at least, it should not). As long as you believe that "free coding" without a second pair of eyes is better, you are still a junior programmer.


答:
In a good team, you should have a queue of development tasks assigned to you in an issue tracker.

That way, while you are waiting for a reviewer, you could (should) work on next task waiting in that queue. Once you get used to work in that fashion, this will open an opportunity to have your changes reviewed in "batches", thus decreasing delays.

If you don't have such a "queue", discuss this with your manager, or better yet, with reviewer. If your team doesn't have reasonably convenient issue tracker for stuff like that, consider studying job boards or company internal job opportunities to find a better team (you might also discuss this with manager / reviewer but don't expect this to help - lack of a good issue tracker is often a symptom of something being severely broken in a team).

I want to be free when coding. How could I gain the trust for development freedom?

To find out, you need first to understand the purpose of code reviews. You mentioned trust - that's a good "approximation", but not entirely accurate one.

For example, in one of my recent projects development has been done by a mini-team of me and my colleague. We fully mutually trusted and respected each other - but despite this we reviewed 100% of code. We were doing it because this allowed us to find and quickly fix some bugs and, which is also very important, because reviews didn't take much time and didn't block our work.

You see, it would be more accurate to think of code reviews in terms of efforts invested in order to prevent certain risks. In a good team, you can expect sort of shared understanding of how to "properly balance" this. Note there is no one-size-fits-all proper balance, it heavily depends on a project - risk and impact of bugs in a mission critical software naturally differs from that in a non-critical application.

Using your example, you can expect "blocking reviews" as long as efforts invested by your reviewer are justified by finding bugs and improvements that are better be fixed prior to committing your code.

They likely expect that with practice and with guidance received at reviews you will get better at coding, so that they will find less and less issues worth fixing prior to commit. As soon as they discover that your code got "safe enough" to allow less cumbersome "risk prevention measures", you could expect the process to change, for example to reviews after commit.

Depending on a project, at some point your code may be even considered safe enough to skip reviews at all, leaving discovery of the bugs to testers (but that not necessarily will happen, see my example above).

Title: What should I do when waiting for a review?

Body:
Before asking my question, I must explain the situation.

I'm working for a company as a junior software engineer. One of the seniors always stops me when I have finished my development and want to commit.

He always wants me to wait for him to review it. This is ok, because usually he finds some bugs, and does some optimizations.

However I must commit my code before the deadline. When I finished, I call him and say it is finished. He usually comes late. So my code is late too.

My question is, what should I do? Should I wait him for a review?

EDIT: Addition to the question. I'm curious about one more issue.

I want to be free when coding. How could I gain the trust for freedom of development?

Some explanations:
I've talked with him about this. But it didn't help. We use an issue tracker already, but there isn't any task for reviews. There are just development and test tasks.


问:
Why is Flags Enumeration considered an intermediate skill?
I was reading this article: Designing Flags Enumerations @ msdn and it says

Combining flags enumeration values is an intermediate skill that should not be required for developers implementing common scenarios.

I think flags enumeration are awesome - something I learned about during my experience with C.

Why does it seem like this article is cautioning developers away from what I consider to be a useful (and not complex) skill?

答:
As with many computing concepts, those who understand them don't find them difficult. You're among those people; congratulations!

That doesn't change the fact that bitwise arithmetic seems strange and hard to understand to many people, because it uses a language element (numbers) that they are used to handle in one way (for absolute magnitude) in a very different way (with different meanings for each bit, regardless of their 'value' in the normal number system.)

Yes, there are people to whom this is difficult, and yes, there are a lot of positions that can be filled by people who can't be bothered to learn bit arithmetic. That's what "intermediate" means here.


问:
Randomness in Acceptance-Tests
I've got a simple authentication solution, where a user can log in with either email or username.

Since I want to show the little feature in the acceptance tests but don't want to pollute them, I thought I'll introduce some randomness. Do you think this is bad or good?

```<code>step "Fill in my credentials" do
    fill_in :user_login, with: [@user.email, @user.name].sample
    fill_in :user_password, with: @user.password
end
</code>```

答:
I won't state randomness is a bad idea.

[Sav07] tested his algorithm implementation for binary search by writing a group of test which included some "theories" (hypotheses) about how the search algorithm should perform.

He then ran the "thorough" group of tests with a lot of random fixtures.

In Ruby:

```<code>require "test/unit"
require "binary_search" # binary_search gem:
                        # <https://github.com/tyler/binary_search>

class BinarySearchTestTheories < Test::Unit::TestCase
    def before_all
       @rand = Random.new()
    end

    def test_theories
        experiments = 1000
        max_value = 1073741824 # Fixnum max value

        while (experiments-- > 0) do
            test_array = generateRandomSortedArray

            target_must_exist = [true, false].sample
            if target_must_exist
                target = test_array[@rand.rand(test_array.length)]
            elsif
                target = @rand.integer(max_value)
            end

            return_value = test_array.binary_search { |v| target <=> v }

            assert_theory1(test_array, target, return_value)
            assert_theory2(test_array, target, return_value)
            assert_theory3(test_array, target, return_value)
            assert_theory4(test_array, target, return_value)
        end
    end

    # Theories
    def assert_theory1(arr, target, expectation) ... end
    def assert_theory2(arr, target, expectation) ... end
    def assert_theory3(arr, target, expectation) ... end
    def assert_theory4(arr, target, expectation) ... end

    # Helper
    def does_array_contain_target?(arr, target) ... end
    def target_position(arr, target) ... end
end
</code>```

I'm not certain his "test theories" qualify as acceptance tests---but they clearly are beyond unit or "boundary" tests.

My conclusion:  random acceptance tests are useful for predictable algorithms.  Sampling email and user name fixtures seems trivial enough.

[Sav07]  Alberto Savoia:  "Beautiful Tests", in: Andy Oram and Greg Wilson (eds.):  Beautiful Code, Beijing: O'Reilly, 2007.

See the full article at: http://cdn.ttgtmedia.com/searchSoftwareQuality/downloads/BeautifulTests.pdf

Title: Randomness in Acceptance-Tests

Body:
I won't state randomness is a bad idea.

[Sav07] tested his algorithm implementation for binary search by writing a group of test which included some "theories" (hypotheses) about how the search algorithm should perform.

He then ran the "thorough" group of tests with a lot of random fixtures.

In Ruby:

require "test/unit"
require "binary_search" # binary_search gem:
                        # <https://github.com/tyler/binary_search>

class BinarySearchTestTheories < Test::Unit::TestCase
    def before_all
       @rand = Random.new()
    end

    def test_theories
        experiments = 1000
        max_value = 1073741824 # Fixnum max value

        while (experiments-- > 0) do
            test_array = generateRandomSortedArray

            target_must_exist = [true, false].sample
            if target_must_exist
                target = test_array[@rand.rand(test_array.length)]
            elsif
                target = @rand.integer(max_value)
            end

            return_value = test_array.binary_search { |v| target <=> v }

            assert_theory1(test_array, target, return_value)
            assert_theory2(test_array, target, return_value)
            assert_theory3(test_array, target, return_value)
            assert_theory4(test_array, target, return_value)
        end
    end

    # Theories
    def assert_theory1(arr, target, expectation) ... end
    def assert_theory2(arr, target, expectation) ... end
    def assert_theory3(arr, target, expectation) ... end
    def assert_theory4(arr, target, expectation) ... end

    # Helper
    def does_array_contain_target?(arr, target) ... end
    def target_position(arr, target) ... end
end

I'm not certain his "test theories" qualify as acceptance tests---but they clearly are beyond unit or "boundary" tests.

My conclusion:  random acceptance tests are useful for predictable algorithms.  Sampling email and user name fixtures seems trivial enough.

[Sav07]  Alberto Savoia:  "Beautiful Tests", in: Andy Oram and Greg Wilson (eds.):  Beautiful Code, Beijing: O'Reilly, 2007.

See the full article at: http://cdn.ttgtmedia.com/searchSoftwareQuality/downloads/BeautifulTests.pdf


答:
My question is, what should I do? Should I wait him for a review?

No, you shouldn't just sit idle. There is always something to do. As Gnat suggested, there should be a queue of tasks. Or, in an agile way of development, list of tasks assigned to you for the current iteration. If you sit idle, there is something wrong in the organization of your company or your team.

Another thing is : is your senior supervisor really checking every piece of code you do? If yes, you could also do pair programming.

I want to be free when coding. How could I gain the trust for development freedom?

There are some regulations which require that senior checks the work of junior (I think medical iso 62304 requires this). If it is so, you can not do anything.

What you can change is to ask senior not to check literally everything. You can set code review process, and check important things.


问:
Refactoring an existing abstract class and its parameters
I have an abstract class A which declares an abstract method doStuff.  Currently there are many classes that inherit from A and implement doStuff.

The class' instances are initialized at run-time via AFactory based on user input.
Originally all the classes had the same single parameter (the user input). But now I have an additional parameter that only a new class that inherits A needs.

So breaking it down I though of the following logic:

The interpreter class that generates instances based on user input(using AFactory of course) was not aware of this extra parameter.

Trying to push it into the class interpreter class would be really awkward because then I would have to know when to pass it to the factory which defeats the whole purpose of having a factory in the first place.

Sending it blindly into the Factory hoping it might do something with it seems quite ugly as well.

My current solution: Meanwhile I've decided to refactor A.doStuff(Param param) into A.doStuff(AParams params).

AParams can hold what ever parameters needed and doStuff can ignore then if they're not interested in them. This also seems a bit awkward to me , and remids me of sending structs in WIN32API that can hold a lot of ugly useless parameters and I'm not fond of it.

Is there a more elegant way to approach this problem ? Or some design pattern that I've overlooked and solves this?

Notes :

We're using Java 1.7

The class' names are silly in order to emphasize the theoretical design issue they do have normal indicative, meaningful names in reality :)

I did search quite a lot but having figured out that it's quite hard to search the web for specific abstract theoretical issues (as opposed to why is X throwing Exception in this code) I've decided to ask anyway so I'm sorry if this is a duplicate.

Edit 1:

Clarification: I need to pass a subclass-specific argument to the doStuff method.

EDIT 2:

I did not fully understand Kilian Foth's intention so I've written some Java-pseudo-code to help me better explain the problem/understand your solution. So:

This is a skeleton of my problem.

This is a skeleton of my solution.

This is what I think  might be Kilian Foth's solution, but I'm not sure.

答:
The point of a factory is to hide the fact that you may get objects from slightly different classes. Therefore, if some of these objects need certain data and others don't...

Either they aren't similar enough to be produced by the same factory. Then you need to have more than one factory and make the decision way earlier than you are currently doing.

Or they are similar enough that the client isn't supposed to care which one they get. Then you can't expect the client to care about whether to send the extra data or not. It follows that they must always be passed, but the factory will sometimes ignore them without bothering the client with that implementation detail. Anything else would burden the client with the very distinction that the factory was supposed to conceal.


答:
There are multiple possible answers here, depending on exactly what your problem is.

If your major concern is "I am missing deadlines", no. The two of you are jointly missing deadlines. Can you (with confidence) say "I will be done in an hour, can we do the code review then"? That might be enough. Can you complete the code the day before the deadline? That should be a plentiful buffer. Are you completing your code, with plenty of buffer between "please review" and the deadline? If the latter, it's not even a joint fault, I'd say.

Code should always be reviewed. I can't check anything in without (at least) a second set of eyes and another human going "that's OK". That goes for projects where I am the lead programmer as well as for projects where I don't normally contribute (but have managed to find a bug impacting me that I want fixed). However, the strictness of a review is very much based on trust. If I trust that the person wanting to submit code knows the code-base well, I will not be as strict as if I don't know how well the person knows the code-base.


问:
I should have used a factory method instead of a constructor. Can I change that and still be backwards-compatible?
The problem

Let's say I have a class called DataSource which provides a ReadData method (and maybe others, but let's keep things simple) to read data from an .mdb file:

```<code>var source = new DataSource("myFile.mdb");
var data = source.ReadData();
</code>```

A few years later, I decide that I want to be able to support .xml files in addition to .mdb files as data sources. The implementation for "reading data" is quite different for .xml and .mdb files; thus, if I were to design the system from scratch, I'd define it like this:

```<code>abstract class DataSource {
    abstract Data ReadData();
    static DataSource OpenDataSource(string fileName) {
        // return MdbDataSource or XmlDataSource, as appropriate
    }
}

class MdbDataSource : DataSource {
    override Data ReadData() { /* implementation 1 */ }
}

class XmlDataSource : DataSource {
    override Data ReadData() { /* implementation 2 */ }
}
</code>```

Great, a perfect implementation of the Factory method pattern. Unfortunately, DataSource is located in a library and refactoring the code like this would break all existing calls of

```<code>var source = new DataSource("myFile.mdb");
</code>```

in the various clients using the library. Woe is me, why didn't I use a factory method in the first place?

Solutions

These are the solutions I could come up with:

Make the DataSource constructor return a subtype (MdbDataSource or XmlDataSource). That would solve all my problems. Unfortunately, C# does not support that.

Use different names:

```<code>abstract class DataSourceBase { ... }    // corresponds to DataSource in the example above

class DataSource : DataSourceBase {      // corresponds to MdbDataSource in the example above
    [Obsolete("New code should use DataSourceBase.OpenDataSource instead")]
    DataSource(string fileName) { ... }
    ...
}

class XmlDataSource : DataSourceBase { ... }
</code>```

That's what I ended up using since it keeps the code backwards-compatible (i.e. calls to new DataSource("myFile.mdb") still work). Drawback: The names are not as descriptive as they should be.

Make DataSource a "wrapper" for the real implementation:

```<code>class DataSource {
    private DataSourceImpl impl;

    DataSource(string fileName) {
        impl = ... ? new MdbDataSourceImpl(fileName) : new XmlDataSourceImpl(fileName);
    }

    Data ReadData() {
        return impl.ReadData();
    }

    abstract private class DataSourceImpl { ... }
    private class MdbDataSourceImpl : DataSourceImpl { ... }
    private class XmlDataSourceImpl : DataSourceImpl { ... }
}
</code>```

Drawback: Every data source method (such as ReadData) must be routed by boilerplate code. I don't like boilerplate code. It's redundant and clutters the code.

Is there any elegant solution that I have missed?

答:
The best solution will be something close to your option #3. Keep the DataSource mostly as it is now, and extract just the reader part into its own class.

```<code>class DataSource {
    private Reader reader;

    DataSource(string fileName) {
        reader = ... ? new MdbReader(fileName) : new XmlReader(fileName);
    }

    Data ReadData() {
        return reader.next();
    }

    abstract private class Reader { ... }
    private class MdbReader : Reader { ... }
    private class XmlReader : Reader { ... }
}
</code>```

This way, you avoid duplicate code, and are open to further extensions.

Body:
The best solution will be something close to your option #3. Keep the DataSource mostly as it is now, and extract just the reader part into its own class.

class DataSource {
    private Reader reader;

    DataSource(string fileName) {
        reader = ... ? new MdbReader(fileName) : new XmlReader(fileName);
    }

    Data ReadData() {
        return reader.next();
    }

    abstract private class Reader { ... }
    private class MdbReader : Reader { ... }
    private class XmlReader : Reader { ... }
}

This way, you avoid duplicate code, and are open to further extensions.


问:
How to manage large scale project in node.js keeping everything Asynchronous?
I have a large module which have to process more than 10k request/ response per second.
Every request has a json and need to process it and verify it on the database and generate the response on the basis of the db query.
Here is an example

```<code> Function 1

 function  ('/get' , fucntion (req1 , res1 , next ){

  //to process the req data
  processData(req1 , res1 );

 });

 Function 2

     processData(req1 , res1 ){

      var J = JSON.parse (req1.body)
     //it has to read db three times
     //process the json build the response and return

           condtionCheck(J , res1){

                    var a = someVlaue(){
                    //select a value from a collection set of nosql which have
                    //more than 1000 document and
                    //i have to itrate a for loop to check the condition .....etc
                    //...........

                      }
                    ........

                      dataRead(var a , res1){
             // is it possible to send response for the req1 object here
                         res1.send({value b: abcd123})
                    }

              }

      }

     Function 3 ..... and so on
</code>```

The major problem is all the code i have written inside the process data is synchronous. Bacaue each code depends upon the previous call back and there are so many condition check are used in several times.

So It is good to put such a large processing in synchronous way inside node ?
If i write the code using async some times all scenario got in a deadlock condition How to avoid such behavior?
Does async or function like step have affect on performance ?
On such a series of function how can  we reduce latency ?

答:
Short answer:

No, synchronous processing in node.js WILL cause performance problems.

Long answer:

You want to avoid synchronous processing in node as much as possible. Obviously, sometimes you're going to need it, but that may be a point at which you move the relevant synchronous code out of node and into something more suitable.

Basically, as node follows an evented model of concurrency, where a single thread runs a stack of events one at a time, any long-running events are going to block the execution of anything else. So, what you'll be looking to do is to scythe off as much functionality as possible into small, asynchronous, function calls.

What you'll want to do is look to use a library, such as async or Step, which allows you to avoid the "callback hell" approach to node programming. JQuery has a similar thing in the browser that you may have used, which is its promise() method and Deferred objects. This will make it much quicker to write, and maintain, your node source.

If you really do need to put a large synchronous procedure in your web app, then node is not the right tool for that job. Try looking at having another API that node can call out to when it needs to accomplish a long-running task, whether that's a command-line C++ app or a web API in a more standard-concurrency model language.


问:
Naming a class that does Importing and exporting of data
I've been thinking about creating a class that handles importing and exporting of data, and I feel that naming it FooImporterExporter might look too long, I wan't to see if there's a name convention that I could use to name it.

These are some of the names I think would be appropriate:

FooProcessor

FooPorter / FooPort - ( as Import/Export comes from trading goods in a Port )

FooTrader

答:
The name of the class should make the responsibility of that class obvious. FooProcessor is ambiguous; FooPorter and FooTrader are each a cute play on words.

FooImporterExporter tells the reader exactly what the class does, it imports and exports Foos.

Having said that, you really should split it into two class, FooImporter and FooExporter. The reason it is a pattern that Java and other languages follow is because they are respecting Single Responsibility Principle.


问:
Organizing Git repositories with common nested sub-modules
I'm a big fan of Git sub-modules.  I like to be able to track a dependency along with its version, so that you can roll-back to a previous version of your project and have the corresponding version of the dependency to build safely and cleanly.  Moreover, it's easier to release our libraries as open source projects as the history for libraries is separate from that of the applications that depend on them (and which are not going to be open sourced).

I'm setting up workflow for multiple projects at work, and I was wondering how it would be if we took this approach a bit of an extreme instead of having a single monolithic project.  I quickly realized there is a potential can of worms in really using sub-modules.

Supposing a pair of applications: studio and player, and dependent libraries core, graph and network, where dependencies are as follows:

core is standalone

graph depends on core (sub-module at ./libs/core)

network depdends on core (sub-module at ./libs/core)

studio depends on graph and network (sub-modules at ./libs/graph and ./libs/network)

player depends on graph and network (sub-modules at ./libs/graph and ./libs/network)

Suppose that we're using CMake and that each of these projects has unit tests and all the works.  Each project (including studio and player) must be able to be compiled standalone to perform code metrics, unit testing, etc.

The thing is, a recursive git submodule fetch, then you get the following directory structure:

```<code>studio/
studio/libs/                    (sub-module depth: 1)
studio/libs/graph/
studio/libs/graph/libs/         (sub-module depth: 2)
studio/libs/graph/libs/core/
studio/libs/network/
studio/libs/network/libs/       (sub-module depth: 2)
studio/libs/network/libs/core/
</code>```

Notice that core is cloned twice in the studio project.  Aside from this wasting disk space, I have a build system problem because I'm building core twice and I potentially get two different versions of core.

Question

How do I organize sub-modules so that I get the versioned dependency and standalone build without getting multiple copies of common nested sub-modules?

Possible solution

If the the library dependency is somewhat of a suggestion (i.e. in a "known to work with version X" or "only version X is officially supported" fashion) and potential dependent applications or libraries are responsible for building with whatever version they like, then I could imagine the following scenario:

Have the build system for graph and network tell them where to find core (e.g. via a compiler include path).  Define two build targets, "standalone" and "dependency", where "standalone" is based on "dependency" and adds the include path to point to the local core sub-module.

Introduce an extra dependency: studio on core.  Then, studio builds core, sets the include path to its own copy of the core sub-module, then builds graph and network in "dependency" mode.

The resulting folder structure looks like:

```<code>studio/
studio/libs/                    (sub-module depth: 1)
studio/libs/core/
studio/libs/graph/
studio/libs/graph/libs/         (empty folder, sub-modules not fetched)
studio/libs/network/
studio/libs/network/libs/       (empty folder, sub-modules not fetched)
</code>```

However, this requires some build system magic (I'm pretty confident this can be done with CMake) and a bit of manual work on the part of version updates (updating graph might also require updating core and network to get a compatible version of core in all projects).

Any thoughts on this?

答:
I would not use submodules.

It's tempting, same as used to be the case with svn-externals. However, can you be sure all of those projects you link are still at the same place in a year? What about in five?

Therefore, I am simply copying all required dependencies into my project. This means that as long as my repo is valid, I can checkout the exact state.

Basically, I have a folder structure as follows:

```<code>myproject/... [sources etc]
ext/ [third-party dependencies]

e.g. ext/boost, ext/cppunit
</code>```

While this is not very nice from a disk-space perspective, I value the guarantee that I can check out every state recorded as long as the repo is available much higher.

In addition, there are a bunch of problems with submodules as described here

Body:
I would not use submodules.

It's tempting, same as used to be the case with svn-externals. However, can you be sure all of those projects you link are still at the same place in a year? What about in five?

Therefore, I am simply copying all required dependencies into my project. This means that as long as my repo is valid, I can checkout the exact state.

Basically, I have a folder structure as follows:

myproject/... [sources etc]
ext/ [third-party dependencies]

e.g. ext/boost, ext/cppunit

While this is not very nice from a disk-space perspective, I value the guarantee that I can check out every state recorded as long as the repo is available much higher.

In addition, there are a bunch of problems with submodules as described here


答:
The article says

Consider providing special enumeration values for commonly used combinations of flags.

Of course, it is not really hard to combine different flags using the "|" operator, but providing special enumeration values has the following advantage:

easier to read:

MyEnumeration.MyFlag1 | MyEnumeration.MyFlag2 | MyEnumeration.MyFlag3

tends to get much more lengthy than

MyEnumeration.MyCombinedFlags123

it makes immediately clear that the specific combination of flags is a legal combination (which may or may not be the case for every other combination)

Nevertheless, I read this sentence from the article not like "don't do this, never ever", only like "make it easier for the common case". There's nothing to say against having no special enum value for a rarely used combination.

Title: Why is Flags Enumeration considered an intermediate skill?

Body:
I was reading this article: Designing Flags Enumerations @ msdn and it says

Combining flags enumeration values is an intermediate skill that should not be required for developers implementing common scenarios.

I think flags enumeration are awesome - something I learned about during my experience with C.

Why does it seem like this article is cautioning developers away from what I consider to be a useful (and not complex) skill?


答:
There is a cleaner way and it is to use immutable/persistent data structures. This is an idea from functional programming but there's really no reason that you couldn't do it in an object-oriented paradigm also.

You construct the data in such a way that it is never deleted or mutated. Updates create a new structure without changing the data of the old structure. If an update goes awry, you revert to the previous version. If it is successful you can discard the previous version depending on your needs.

https://en.wikipedia.org/wiki/Persistent_data_structure

Title: better method to revert state if failure occures during add/delete

Body:
So I have a generic framework with a concept of children and parent objects, the objects don't have to be the same type, and I can add or remove any of them.  Adding calls add on all the children, and informs the parents, inverse for remove.

the concept of Parent is generic enough that there can be a loop across classes.  A may be a parent of B which is a parent of C which is a parent of A.  This still works, since I mark an object as added or removed as the first step in the abstract class; so even if a circular dependency calls Add a second time on the same object the second time through the add will return without doing anything (because the added boolean is already set) and we halt our recursion.

If some unexpected exception occurs I want to revert my state back to what it was before the exception occurs.  I was doing this with exception handling, if I catch a run time connection I remove objects I added and update parents before throwing the exception.  This is where my logic can fail.  As of now I 'revert' the AddObject method by calling removeObject and vice versa.  If my state somehow ended up in a truly bizarre state I could keep throwing exceptions, add throws and calls remove, remove throws and calls add, etc etc.  I think this still has a chance for infinite recursion; though admittedly something would already have to be pretty messed up in my state for it to happen.

Is there a cleaner way to do my rollback logic to avoid this potential?  At a point like this what should I say my state should be once I recover anyways?


问:
How do you keep track of what classes and functions your team has written?
When working on code, I face many of the same challenges that my teammates do, and I have written some helpful functions and classes, and so have they. If there is good communication, I'll hear about some great thing someone put together, and six months later when I need it I may remember it and call that function, saving myself time. If I don't remember it, or never knew about it, I will probably re-invent the wheel.

Is there a particular practice of documenting these kinds of things? How do you make them easy to find?

If your team has no such documentation, how do you find out if your wheel already exists?

EDIT:

All but one of the answers so far deals with an ideal situation, so let me sum up those solutions: documentation & communication; wikis, stand-up meetings, etc. Those are all great things, but they rely on programmers having the time (and skills) to write up the documentation and attend the meetings and take notes and remember everything.

The most popular answer so far (Caleb's) is the only one that could be used by a programmer who is incapable of documentation and meetings, and does only one thing: programming. Programming is what a programmer does, and yes, a great programmer can write up documentation, unit tests, etc., but let's face it - most of us prefer programming to documenting. His solution is one where the programmer recognizes re-usable code and pulls it out to its own class or repository or whatever, and by the fact that it is isolated, it becomes find-able and eases the learning curve for using it.... and this was accomplished by programming.

In a way I see it like this: I've just written three functions, and it occurs to me that someone else should know about them. I could document them, write them up, announce them at a meeting, etc. - which I can do, but it's not my strength - or .... I can extract them to a class, name it well, make them function like a black box, and stick it where other class files go. Then a short email announcing it is easy. Other developers can scan the code and understand it better than they could an isolated function used in code they don't fully understand - that context is removed.

I like this because it means having a set of well-named class files, with well-named methods, is a good solution that is accomplished by good programming. It does not require meetings, and it softens the need for detailed documentation.

Are there any more ideas in this vein ... for isolated and time-pressed developers?

答:
One approach for that is setting up a Wiki for that purpose, and write some high-level docs on what reusable components you have, how you solved a problem etc.

The hard part is to get every one in your team to constantly maintain that Wiki. But any other kind of documentation suffers from the same problem.

Some of your code may also be good enough to be put into a reusable library. This makes it also easier to find the code again later.