答:
Since you refer them as basically "CRUD" developers, we'll assume you don't think they are very good. We don't know if this means they also don't understand your business domain. If they understand the domain, the classes should make sense to them. Knowing several classes have been built, they should take a look first, ask second, consider building from scratch as a third option.

As far as knowing how to automatically know how to use/reuse a class just by looking at it shouldn't be expected the first time. You're going to need to document and possibly provide additional explanation either through training or possibly during code review.

Many API's and open source projects provide documentation, code examples and other explanations. Yours may not need to be as user friendly, but there's no getting around it. Teach them well.

Title: Is discoverability for developers a problem when using SOLID principles?

Body:
I do line of business apps where the all the other developers are used to doing basic CRUD apps or are focused solely on making pretty/functional interfaces and I am getting the following a lot.

"With the way we use to do it Employee would have all the things you could possibly do with an employee." And it was true. That one "Class" had thousands of lines of code and anything you could do with an employee was there. Or, even worse, there was a table of employee data and each developer figured out how to do what they wanted to do in the event handler.

All the bad things about that approach was true but at least the developer using employee could, without going to other documents, figure out how to enroll the employee in a health plan, give a pay raise, fire, hire, transfer etc. Same goes for Manager and all the other major ideas. Or, if they used the employee other needed data tables, could just do what they wanted.

Yes, there was much duplicated code. Yes it was very brittle code. Yes testing it was way more difficult than necessary. Yes changing functionality was fear inducing and Copy Paste was a natural due to the approach.

But they could at least discover what was available by creating one class or they could do what they need to get done without having to understand the difference between interfaces, abstract classes, concrete classes etc. And they didn't have to search anything other than the methods returned by intellisense or know the tables where the data resided.

I have googled/binged and even yahoo!d but I haven't found any acknowledgement of this problem.

So maybe there isn't a problem and I am just missing something. I have racked my brain trying to figure out a solution where the developer(s) that do not work the actual behavior/design can easily discover how to do something without having to reference any external documents or scan the class names in the various components/projects to find the one that sounds like it will work.

The only thing I have been able to come up with is have these, for lack of a better name, "Table of Content Class" that does nothing more that return the actual classes (and really most of them are interfaces but they don't know the difference or even care) that other developers can use to perform the actual tasks desired. Still end up with really big classes but there is almost no behavior in them.

Is there a better way that doesn't require intimate knowledge of the middle tier where the actual implementation of SOLID takes place?

Basically what I am asking is there a way to allow CRUD type developers continue to be CRUD developers in a very complex system


问:
Becoming a "maintenance developer"
So I've kind of been getting angry about the current position I'm in, and I'd love to get other developers' input on this.

I've been at my current place of employment for about 11 months now. When I began, I was working on all new features. I basically worked on an entire new web project for the first 5-6 months I was here. After this, I was moved to more of a service oriented role (which was still great, all new stuff for me), and I was in this role for about the past 5-6 months. Here's where the problem comes in.

Basically, a couple of days ago I was made the support/maintenance guy. Now, we have an IT support team, so I'm not talking that kind of support, I'm talking more of a second level support guy (when the guys on the surface can't really get to the root of the issue), coupled with working on maintenance issues that have been lingering in the backlog for a while. To me, a developer with about 3 years of experience, this is kind of disheartening.

With the type of work place this is, I wouldn't be surprised if these support issues take up most of my days, and I barely make it to working on maintenance issues. Also, most of these support issues aren't even related to code, they are more or less just knowing the system architecture, working with making sure services are running/getting started properly, handling/fixing bad data, etc. I'm a developer, so this part sucks. Also, even when I do have time to work maintenance, these are basically just bug fixes/improving bad code, so this sucks as well, however at least it's related to coding.

Am I wrong for getting angry here? I don't want to really complain about it, but to be honest, I wasn't spoken to about this or anything, I was kind of just sent an e-mail letting me know I'm the guy for this type of thing, and that was that. The entire team took a few minutes to give me their "that sucks" talk, because they know how annoying it is to be on support for the type of work we do, so I know I'm not the only guy that knows it's not that great of an opportunity.

I'm just kind of on the fence about how to move forward. Obviously I'm just going to continue working for the time being, no point making a bad impression on anybody, but I'd like to know how you guys would approach this situation, or how you think I should be feeling about it/how you guys would feel.

答: You need to ask why you were put in a role everyone thinks sucks. If your manager has half a brain, he'll know no one likes it and if he thought there are those that do, he could of at least asked. Find out how long this situation will last and if there are opportunities to move back to new development. You never know, you may walk into the office the next day and be given a brand new project. Stranger things have happened.</p>

OwnerDisplayName: anon

ContentLicense: CC BY-SA 3.0

Title: Becoming a "maintenance developer"


问:
When to use C over C++, and C++ over C?
I've been introduced to Computer Science for a little over a year now, and from my experience it seems that C and C++ are both considered to be "ultrafast" languages, whereas others such as Python and such scripting languages are usually deemed somewhat slower.

But I've also seen many cases where a software project or even a small one would interleave files where a certain number n of those files would be written in C, and a certain number m of those files would be written in C++.

(I also noticed that C++ files almost always have corresponding headers, while C files not so much). But my main point of inquiry is to get a general sense of intuition on when it is appropriate to use C over C++, and when it is better to use C++ over C. Other than the facts that (1) C++ is object-oriented whereas C is not, and (2) the syntaxes are very similar, and C++ was intentionally created to resemble C in many ways, I am not sure what their differences are. It seems to me that they are (almost) perfectly interchangeable in many domains.

So it would be appreciated if someone could clear up the situation! Thanks

答:
I would say that the main reason why I would choose C over C++, is only when I would have to resort to "It this HAS TO BE 1000% stable" NASA kind of stuff.

C++ is ~99% C when we look at the performance, and it's a lot more productive. So even while in C you can write code that will be faster than C++ (you can use a subset of C++ without exceptions, virtual, streaming, abstractions, etc. as well, but that's basically C), the time to optimize every damn thing while STL is tested and does that already, would cost you more than the tiny performance gain you might achieve, or sacrifice because STL algorithms have been written by groups of experts, and you're probably not an expert in everything.

On the other hand C++ has a ton of abstractions. When under circumstance they leak, this gets you into trouble. And there are few people who know 100% of C++ gotchas, while, I guess, there are more that know all C gotchas, so writing a solution where every step is fully understood by all members of a team is a lot easier in C.

Example: Do you know when shared_ptr<smthn> will overflow its reference count, will it throw an exception? Things like these are not cool when Shuttle has to reenter the atmosphere, at least I guess so.

Also, exception handling is very, very hard compared to error codes. It's hard to see if the class is 100% exception safe, and easy to get into leaks. A lot of high rep people have expressed this opinion.

Title: When to use C over C++, and C++ over C?


问:
Why there is no ISO hardware query interface?
I'm currently reading a book, chapter about I/O, and one question came to my mind.

Basically, when you program in C/C++, you have an amazing opportunity to optimize for hardware behavior. Using buffering for block devices, use streaming and async I/O for high latency network devices and so on.

And if you're writing a server application that is targeted at high load applications, and you can optimize for I/O devices, that can actually change the hardware requirements tremendously. Say, you know that HDD cache is around 32MB, and it likes to stream data in 8MB blocks, and you have 16GB of RAM that's cheap and sitting idle, you could just use low level _read with a 8MB buffer and be done with it. Which would remove ton of locking and user->kernel->user transitions that's caused by smaller reads, say 64KB each.

The problem is, you basically have to run the program on target platform to get the actual performance data, and optimize for it. And if you port that application to say ARM, the optimizations can even backfire.

So why is there no API to get the sweet-spot values for architecture you're running on.

Say QueryOptimalHddReadBuffer, QueryOptimalHddWriteBuffer, QueryHddSeekTimeCharacteristics, QueryOptimalNetworkCardReadBuffer, etc.

答:
I'd guess there are basically two reasons. First and foremost, I'd guess nobody's even attempted to submit a proposal for anything similar in a form that the committee could even hope to accept if they wanted to.

Second (and probably secondarily), I suspect there's an attitude that the implementation can and should do most such optimization more or less automatically. To use your example, there's a reason _read isn't standardized by C or C++, and fread is standardized instead -- it allows the implementation to do buffering, so instead of querying for the optimal read size for the system, it should just do the optimal read size automatically. I realize that what it chooses isn't optimal for every purpose, but I doubt a QueryOptimalHDDReadBuffer (etc.) would necessarily be any better.


问:
What do you consider to be the prime cause of software defects (and how to minimize them)
I define defect as :

"something within the application design or code which prevents it functioning as per requirements."

I'm looking for ideas about the causes of defects, eg the human factor, lack of testing, lack of prototyping, and possible ideas to mitigate these.

答:
Schedule Pressure is certianly a strong source.

Rushed developers don't take the time to fully specify the requirements, or fully understand the intent behind requirements, or fully investigate alternates to find the best solution, or fully think through all the edge cases and interactions of the changes they are making, or develop a full set of test cases, or fully perform all the unit test, or perform a full integration test, or fully consider platform dependencies, or fully test out the installer, or fully document what they've done so the next developer can understand....

ContentLicense: CC BY-SA 2.5


问:
When to update jQuery?
When you recommend updating jQuery/jQuery UI? Or in other words: what are the best practices for updating jQuery/jQuery UI?

I’m working on a long project that will take at least one more year. In that time span, I’m sure that jQuery/jQuery UI will be updated many times.

Do you recommend update my jQuery/jQuery UI files every time an update is released? Or is better to stick with a particular version until the end of the project?

I’m afraid of “breaking” code changes, and every time an update is released, I have to test everything. That takes too much time. But on the other hand, if I didn’t update, I’m afraid of bugs that later will bite me in the rear.

The project is an ASP.MVC and I use jQuery a lot.

Any thoughts?

答:
Update your version of jQuery if and only if you need some new feature that's included in the new version. Simple as that.

If you frequently develop using jQuery, keep an eye on the official blog to know when updates are released and what they offer. Wait a couple of weeks or so before upgrading to the latest version to make sure any unexpected bugs get shaken out.

OwnerDisplayName: epaulk

Title: When to update jQuery?


答:
You should upgrade with each release of jQuery -- just take a peek at the update logs before updating.

The jQuery team is very good about documenting API changes and deprecated calls. At this point, the vast majority of the API is quite stable and probably won't change. Most changes are behind-the-scenes bug fixes that do not affect the outward API. This is especially true with the latest releases (1.8+).

Another great reason to update is because regardless of whether or not you remain on a project, that project will be maintained by somebody after you're done with it. Upgrading to latest version is beneficial for you, future developers and users -- because the newer versions of jQuery blow the older ones out of the water... so go ahead and update the thang.

Title: When to update jQuery?

Body:
When you recommend updating jQuery/jQuery UI? Or in other words: what are the best practices for updating jQuery/jQuery UI?

I’m working on a long project that will take at least one more year. In that time span, I’m sure that jQuery/jQuery UI will be updated many times.

Do you recommend update my jQuery/jQuery UI files every time an update is released? Or is better to stick with a particular version until the end of the project?

I’m afraid of “breaking” code changes, and every time an update is released, I have to test everything. That takes too much time. But on the other hand, if I didn’t update, I’m afraid of bugs that later will bite me in the rear.

The project is an ASP.MVC and I use jQuery a lot.

Any thoughts?

OwnerDisplayName: ImportedNoob


答:
Do you need any of the new features included in a newer version of JQuery?
Does your site work as expected today?

If you answered "no" to the first and "yes" to the second question, then don't upgrade jQuery.

If you DO need new functionality, then you have to balance this against the cost of increased testing and possible introduction of new issues.

If you have issues with your current version of JQuery, then a newer version may have fixed your issue, but you still have an increased test burden because you have to ensure the new version doesn't break anything else.

This is why having a good suite of unit, functional and feature tests is so essential.

Title: When to update jQuery?

OwnerDisplayName: Richard Turner


答:
Only you can decide if the risks are worth it.  Personally, I like to stay up to date.  However, i have had a few bugs introduced when upgrading that broke something (or caused odd behavior).  Since you have a year of development ahead of you, chances are it will have to go through a final QA anyways.

I say keep up to date.  It's much easier to do continuous small integrations than large ones all at once.

Title: When to update jQuery?

OwnerDisplayName: Mystere Man


答:
Upgrade as soon as you can without breaking anything. New functionalities, bug fix, new features are introduced in every iterations.

You might not need the latest features but when you do, you'll need to validate every new version in between what you have to make sure it doesn't break anything.

Small increment will allow you to keep everything up to date without having to upgrade 5 major releases and spend 5 hours testing everything at once.

Title: When to update jQuery?

OwnerDisplayName: Maxime Rouiller


问:
Does your company have a written policy about contributing to open-source projects?
Does your company have a written policy about contributing to open-source projects?

We've been contributing "don't ask don't tell" style, but it's time to write something down. I'd appreciate both full written policy text and bits and pieces.

Update: we've made some progress since I asked this question and now have such a policy - read this.

答:
We do not have a direct policy regarding this.  Long story short: work created at the university is owned by university unless declared prior to start of coding.

I have discussed with my boss from time to time about this and we have not gone far with it as it becomes a political nightmare as the people who need to approve this do not quite understand open source software aside from the "it is usually free" idea.

/me eagerly awaits others responses!

Update: This topic surfaced at work recently, we met with our legal team and all appears well.  My understanding (from my employer) is this is a case by case basis but they are willing to work with employee's interested.


问:
Is discoverability for developers a problem when using SOLID principles?
I do line of business apps where the all the other developers are used to doing basic CRUD apps or are focused solely on making pretty/functional interfaces and I am getting the following a lot.

"With the way we use to do it Employee would have all the things you could possibly do with an employee." And it was true. That one "Class" had thousands of lines of code and anything you could do with an employee was there. Or, even worse, there was a table of employee data and each developer figured out how to do what they wanted to do in the event handler.

All the bad things about that approach was true but at least the developer using employee could, without going to other documents, figure out how to enroll the employee in a health plan, give a pay raise, fire, hire, transfer etc. Same goes for Manager and all the other major ideas. Or, if they used the employee other needed data tables, could just do what they wanted.

Yes, there was much duplicated code. Yes it was very brittle code. Yes testing it was way more difficult than necessary. Yes changing functionality was fear inducing and Copy Paste was a natural due to the approach.

But they could at least discover what was available by creating one class or they could do what they need to get done without having to understand the difference between interfaces, abstract classes, concrete classes etc. And they didn't have to search anything other than the methods returned by intellisense or know the tables where the data resided.

I have googled/binged and even yahoo!d but I haven't found any acknowledgement of this problem.

So maybe there isn't a problem and I am just missing something. I have racked my brain trying to figure out a solution where the developer(s) that do not work the actual behavior/design can easily discover how to do something without having to reference any external documents or scan the class names in the various components/projects to find the one that sounds like it will work.

The only thing I have been able to come up with is have these, for lack of a better name, "Table of Content Class" that does nothing more that return the actual classes (and really most of them are interfaces but they don't know the difference or even care) that other developers can use to perform the actual tasks desired. Still end up with really big classes but there is almost no behavior in them.

Is there a better way that doesn't require intimate knowledge of the middle tier where the actual implementation of SOLID takes place?

Basically what I am asking is there a way to allow CRUD type developers continue to be CRUD developers in a very complex system

答:
It seems that what you've described (i.e. Employee class having ALL possible code that you could do with an employee) is an extremely common pattern that I've personally seen quite a lot.  Some of that code I've written myself before I knew any better.

What starts off as a class that is supposed to represent a single entity with manageable set of methods, morphs into something that is a nightmare to maintain because each feature and each release keep adding more and more to the same class.  This does go against SOLID principles that say you should write a class once and resist the urge to modify it over and over again.

A while ago (before I discovered design patterns or SOLID as promoted by others), I decided for my next project to flip things around a bit. I was working on a server that served as an interface between two very large platforms. At first, only synchronization of configuration was required, but I could see that this would be a logical place for many other features.

So instead of writing a class that exposed methods, I wrote classes that represented methods (turned out to be "Command" pattern from GoF). Instead of doing the work for the client, all my main application classes became persistent state holders and they became much shorter in length.  Every time I had to add a new interface method to the service itself, I would simply create a new class that had Execute() method that started everything.  If multiple commands had something in common, they derived from the common base class.  Eventually the thing had 70+ different command classes and the entire project was still very manageable and was actually a pleasure to work on.

Your "TOC class" is not too far off from what I did. I had an abstract factory (GoF) that was responsible for instantiating commands. Inside the factory class, I hid most of the details behind the base class and ATL-style macros, so when a programmer had to add or look up a request, they went in there and all they saw was:

```<code>BEGIN_COMMAND_MAP()
    COMMAND_ENTRY( CChangeDeviceState )
    COMMAND_ENTRY( CSetConfiguration )
    ....
END_COMMAND_MAP()
</code>```

Alternatively (or in addition to), you could put all your actual command classes into a separate namespace so when people are coding and need to run something, they just type namespace name and Intellisense lists all the commands that you've defined.  Then each command includes all get get/set methods that determine exactly what input and output parameters.

You can also explore the use of Facade (GoF) pattern. Instead of exposing 1000+ classes to your CRUD engineers.  Hide all of them behind a single class that exposes only what is needed.  I would still stick to having each "action" be its own class, but your Facade class can have methods that would instantiate each of your actions and again, with Intellisense they'd see immediately what is available. Or have Facade have actual methods, but internally make them instantiate commands, queue them up and wait for responses.  Then return as if a regular method call was made.

(*) I didn't want to get into too many details, but I actually had "Command" and "CommandHandler" set of classes. This separated responsibility of managing/queuing/serializing in/out parameters from classes that actually "handled" those commands.

Body:
It seems that what you've described (i.e. Employee class having ALL possible code that you could do with an employee) is an extremely common pattern that I've personally seen quite a lot.  Some of that code I've written myself before I knew any better.

What starts off as a class that is supposed to represent a single entity with manageable set of methods, morphs into something that is a nightmare to maintain because each feature and each release keep adding more and more to the same class.  This does go against SOLID principles that say you should write a class once and resist the urge to modify it over and over again.

A while ago (before I discovered design patterns or SOLID as promoted by others), I decided for my next project to flip things around a bit. I was working on a server that served as an interface between two very large platforms. At first, only synchronization of configuration was required, but I could see that this would be a logical place for many other features.

So instead of writing a class that exposed methods, I wrote classes that represented methods (turned out to be "Command" pattern from GoF). Instead of doing the work for the client, all my main application classes became persistent state holders and they became much shorter in length.  Every time I had to add a new interface method to the service itself, I would simply create a new class that had Execute() method that started everything.  If multiple commands had something in common, they derived from the common base class.  Eventually the thing had 70+ different command classes and the entire project was still very manageable and was actually a pleasure to work on.

Your "TOC class" is not too far off from what I did. I had an abstract factory (GoF) that was responsible for instantiating commands. Inside the factory class, I hid most of the details behind the base class and ATL-style macros, so when a programmer had to add or look up a request, they went in there and all they saw was:

BEGIN_COMMAND_MAP()
    COMMAND_ENTRY( CChangeDeviceState )
    COMMAND_ENTRY( CSetConfiguration )
    ....
END_COMMAND_MAP()

Alternatively (or in addition to), you could put all your actual command classes into a separate namespace so when people are coding and need to run something, they just type namespace name and Intellisense lists all the commands that you've defined.  Then each command includes all get get/set methods that determine exactly what input and output parameters.

You can also explore the use of Facade (GoF) pattern. Instead of exposing 1000+ classes to your CRUD engineers.  Hide all of them behind a single class that exposes only what is needed.  I would still stick to having each "action" be its own class, but your Facade class can have methods that would instantiate each of your actions and again, with Intellisense they'd see immediately what is available. Or have Facade have actual methods, but internally make them instantiate commands, queue them up and wait for responses.  Then return as if a regular method call was made.

(*) I didn't want to get into too many details, but I actually had "Command" and "CommandHandler" set of classes. This separated responsibility of managing/queuing/serializing in/out parameters from classes that actually "handled" those commands.


问:
What factors should be evaluated when determining a desktop software price?
What factors should be evaluated when determining a desktop software price?</p>

答: Try to estimate approximate productivity gain of customers with the software in terms of currency. And also how much post-sale support you are offering. Combine that with your development, marketing and all other cost. You can also consider your reputation. Then you should get a reasonable price. Consider price points for different versions and number of user per licences.</p>


问:
Why are there so many competing filesystem designs?
Just a quick question, but why are there so many file systems still competing and in use today? (ntfs, fat32, ext3(ffs), etc)

It seems that file system designers could agree upon the best aspects of each type of system and implement a "best" filesystem, no? Just a thought, since these filesystems have been around for a while now, and it should be at least somewhat apparent which ones have good qualities over others, and we could just combine the good in each and create an ultimate system that is much better

答:
Short answer: One size does not fit all.

There are trade-offs. For example if you want a journaled FS, you pay (efficiency, complexity, etc.) for it but get something out of it. Some don't feel the need for a journaled FS and don't want to pay for it, some do. Same with other "features" of the FS.


答:
Too much depends on what you want to optimize.

Consider FAT for a moment: its support for long file names is kludgy (to put it nicely), and searching through files in a directory is linear so it gets slow very quickly if a directory contains a lot of files. At the same time, it has a bare minimum of metadata to raw write speed is very good, and since it's so simple over all, code to implement it can be quite small.

Something like ext2 or ext3 adds a lot of features and capabilities that are simply absent from FAT. Searching for files is also quite a lot faster. At the same time, raw writing speed is probably a bit slower, and the code to implement the file system is undoubtedly quite a lot larger.

Title: Why are there so many competing filesystem designs?

Body:
Just a quick question, but why are there so many file systems still competing and in use today? (ntfs, fat32, ext3(ffs), etc)

It seems that file system designers could agree upon the best aspects of each type of system and implement a "best" filesystem, no? Just a thought, since these filesystems have been around for a while now, and it should be at least somewhat apparent which ones have good qualities over others, and we could just combine the good in each and create an ultimate system that is much better


答:
Let's think about the specifics here for a moment, using examples you've cited:

ntfs - Proprietary to Microsoft.  Anyone who is not Microsoft cannot use this, therefore would have to use/create something different.  Now, if you are Microsoft, you want to use this over FAT because of the issues of the next bullet point.

fat32 - Not sufficiently modern.  The maximum file size is 4GB.  Directory entry lookup is O(n).  The allocation table is a linked list, rather than something more efficient like an allocation bitmap (where it's really quick to find contiguous free space).  Does not support permissions.  Does not support hard links or symbolic links.  Does not support journaling.

ext3 - This was an extension of ext2 mainly to support journaling.

So, it seems there are a few reasons:

An earlier filesystem lacks something.  In the case of FAT it is lacking a lot: both in terms of (1) features and (2) performance.  In the case of ext2 it did not have journalled updates, so recovering from a crash took more time.

An existing filesystem would probably do, but it is not yours.  (eg. NTFS if you're not Microsoft).  In this case you don't really have much choice but to come up with your own.


答: I don't have any situation that I can directly cite, However I imagine that top Engineers and Programmers at major companies are forbidden from writing any other code for any other reason thats not beneficial to the company they work for. Of course this is purely speculative on my part.</p>

Body:
Does your company have a written policy about contributing to open-source projects?

We've been contributing "don't ask don't tell" style, but it's time to write something down. I'd appreciate both full written policy text and bits and pieces.

Update: we've made some progress since I asked this question and now have such a policy - read this.


问:
Whether to put the business logic in Stored Procedure or Not?
There is always a debate over the topic - "Whether to put the business logic in Stored Procedure or Not?". If we decide not to use the ORM Tool and not to put the Business Logic in Stored Procedure then where would we put the Business Logic?

In my previous applications I have always preferred putting all of the Business Logic in Stored Procedures only. Then from .NET code I call these Stored Procedures using Data Access Application Blocks. SQLHelper etc. But this can not be the scenario all the time. So I did some googling but ended up in confusion.......

Any suggestionss...?

答:
Our team have a soft rule here. Sometimes it's better to solve the Business Logic in T-SQL, sometimes it's easier to do it in c# (Business Layer).

So we have a pragmatic solution: Put where it fits better.
I know the theory is sometimes very strict about it... but that's theory :-)

OwnerDisplayName: Pravin Patil

OwnerDisplayName: gsharp


问:
What's the difference between "use case", "User Story" and "Usage Scenario"?
Is there an exact, but simple and understandable defintion of the distinction between "use case",  "User Story" and "Usage Scenario"?

there are quite a bunch of explanation, but right now, I see no one that explains the differences in a single sentence, or two...

(e.g. http://c2.com/cgi-bin/wiki?UserStoryAndUseCaseComparison very long and hard to get, full of discussion)

答:
A User Story is a more informal, friendlier and smaller version of a Use Case, minus the UML diagram; it is typically used in iterative scenarios.

A Usage Scenario is a Use Case drawn out into a step-by-step procedure, sometimes accompanied by a flowchart.

OwnerDisplayName: Henning

OwnerDisplayName: Robert Harvey


答:
There isn't an exact definition of any of this stuff.  It all varies a little bit (or a lot) from company to company and from system to system.

Your best bet is to find an example already in place for your current project and follow it.

If you are creating a new system, you can find definitions of different types of use cases for whatever system you prefer--Just pick the pattern that seems to communicate your intentions best.

Don't get hung up on names.

Title: What's the difference between "use case", "User Story" and "Usage Scenario"?

Body:
Is there an exact, but simple and understandable defintion of the distinction between "use case",  "User Story" and "Usage Scenario"?

there are quite a bunch of explanation, but right now, I see no one that explains the differences in a single sentence, or two...

(e.g. http://c2.com/cgi-bin/wiki?UserStoryAndUseCaseComparison very long and hard to get, full of discussion)

OwnerDisplayName: Bill K


答:
To me, the biggest differences between a User Story and a Use Case are:

A user story is a lightweight document that can be written on a card (In order to , as a , I want ). A User Story doesn't capture all the details, it's an informal support for the discussion.

A use case is an heavyweight document that needs a word document. It describes a "Normal Flow" of steps and/or actions and "Alternative Flows" which are detailed. A Use Case captures all the details, it's a formal specification.

According to Scott W. Ambler on Usage Scenarios, these artifacts look like a Use Case's flow:

A usage scenario, or scenario for short, describes a real-world example of how one or more people or organizations interact with a system.  They describe the steps, events, and/or actions which occur during the interaction. Usage scenarios can be  very detailed, indicating exactly how someone works with the user interface, or reasonably  high-level describing the critical business actions but not the indicating how they’re performed.

Honestly, the differences with a Use Case's flow is not crystal clear, even after reading this paragraph (the last sentence being maybe the most important):

As you can imagine, there are several differences between  use cases and scenarios.  First, a use case typically refers to generic actors, such as Customer, whereas scenarios typically refer to examples of the actors such as John Smith and Sally Jones.  There’s nothing stopping you from writing a generic scenario, but it’s usually better to personalize the scenarios to increase their understandability.  Second, usage scenarios describe a single path of logic whereas use cases typically describe several paths (the basic course plus any appropriate alternate paths).   Third, in UP-based processes use cases are often retained as official documentation whereas scenarios are often discarded after they’re no longer needed.

I may be wrong, but Usage Scenario really sounds like Use Case flow but rebranded with an Agile touch.

OwnerDisplayName: Pascal Thivent


答:
I am not familiar with User Story, but when I looked into this several years ago:

A Use Case is a major task.

     User Scenarios are the various ways that task can play out.  So, Every Use Case has one or more scenarios.  The Use Case is the abstract, the User Scenarios are a catalog of all possible instances of that abstract task.

So:

Use Case A:
    User authenticates with id and password.

Scenarios:

1.  ID is recognized, password is correct.  ("sunny day" scenario)

2.  ID is recognized, password is incorrect.

3.  ID is recognized, password is incorrect for third time.

4.  ID is not recognized.

I have always thought of use cases as a way of defining requirements in a narrative way for the client in their terms.   w/r/t the above, if the client says "But what if they try to log in in between midnight and one when the system is down?", we have discovered another scenario for the authentication task, and some additional requirements.

OwnerDisplayName: cvsdave


答:
A user story is from a customer's point of view, sometime it's incorrect or incomplete. It may have no consideration on performance, on error handling, or nothing on the backend.

A use case is from dev's point of view. It's accurate and complete. It should answer all the requirements from customers.

OwnerDisplayName: Dan


答: We always put our Business Logic in Business Logic Layer. If you put it in Stored Procedure, it will be lost once you change your RDBMS.</p>

Body:
There is always a debate over the topic - "Whether to put the business logic in Stored Procedure or Not?". If we decide not to use the ORM Tool and not to put the Business Logic in Stored Procedure then where would we put the Business Logic?

In my previous applications I have always preferred putting all of the Business Logic in Stored Procedures only. Then from .NET code I call these Stored Procedures using Data Access Application Blocks. SQLHelper etc. But this can not be the scenario all the time. So I did some googling but ended up in confusion.......

Any suggestionss...?


答:
I would adopt a pragmatic approach - historically the primary 'benefit' of keeping business logic in stored procs is for performance reasons (2.5 tier architecture), whereas separating the business logic into a BLL tier (3/N tier) is generally cleaner from a maintenance perspective, and easier to test (Mock / Stub out the data access).

However, given that LINQ-enabled .NET ORMS such as LINQ2SQL, EF and NHibernate now create parameterised SQL queries, where query plans can be cached, are escaped for SQL Injection etc, I would guess that the move toward 3/N tier architecture is more compelling than ever, and most of the SPROCs (especially query-centric ones) can be avoided altogether. Repository patterns in .NET commonly expose IQueryable / accept Expression tree parameters, allowing for a type safe, yet flexible access to your tables. (Personally in SOA type architectures, I wouldn't expose IQueryable beyond the BLL, i.e. your Service and Presentation tiers should work with a well defined set of methods. Reason is that otherwise you can never fully test your system, and you won't sleep well at night knowing that some arbitrary query issued by a client could hit your DB without hitting indexes etc)

However, in a decent sized system, there will always be a few exceptions, where a really data intensitive piece of code might still need to be written as a Stored Proc for performance reasons. In these instances I would keep the SPROC, and expose the SPROC through the ORM, but still expose the function as a pass-through method on your BLL.

Title: Whether to put the business logic in Stored Procedure or Not?


答:
Just a quick question, but why are there so many file systems still competing and in use today? (ntfs, fat32, ext3(ffs), etc)

It seems that file system designers could agree upon the best aspects of each type of system and implement a "best" filesystem, no?

Let's suppose that there weren't tradeoffs, and file system designers did implement a "best" filesystem, free from patent worries, and released as dual-licence BSD/GPL so that it would be acceptable to MS and Debian alike. What makes you think that the other file systems would vanish overnight?

I don't think anyone's used FAT32 on a new hard drive for 10 years, but it still persists as the de facto standard for formatting USB drives, SD cards, etc. Camera and mobile phone manufacturers have tried and tested firmware for using it. Arduino hobbyists have stable libraries for using it. They're all going to need big incentives to change.

And then you have the issues of backwards compatibility with older OSes (especially Windows, whose users won't want to install new filesystem drivers).


问:
What is the name for this variation to Adapter Pattern?

Introduction

An Adapter normally wraps another object, so that it can be used in an interface it wasn't designed for, e.g., when you want to use

```<code>interface Node {
    Node parent();
    Iterable<Node> children();
}
</code>```

together with

```<code>class TreeModel {
    private Node root;
    // example method (stupid)
    Node grandparent(Node node) {
        return node.parent().parent();
    }
}
</code>```

and you're given a class like

```<code>class File {
    File getParent() {...}
    File[] listFiles() {...}
}
</code>```

you need to write some FileToNodeAdapter.

Unfortunately, it means that you need to wrap each single object and you also need both a way to get from FileToNodeAdapter to File (which is trivial, since it's embedded), but also from File to FileToNodeAdapter, which leads either to creating a new object each time or to using some Map, which must be either globally accessible or referenced in each FileToNodeAdapter.

The Pattern

Replace the interface Node by

```<code>interface NodeWorker<T> {
    T parentOf(T node);
    Iterable<T> childrenOf(T node);
}
</code>```

and modify the TreeModel like

```<code>class TreeModel<T> {
    private NodeWorker<T> nodeWorker;
    private T root;
    // example method (stupid)
    T grandparent(T node) {
        return nodeWorker.parentOf(nodeWorker.parentOf(node));
    }
    ...
}
</code>```

Does this pattern have a name?

Are there any disadvantages, besides the fact that it is little bit more verbose and only applicable when you are in charge of the TreeModel code?

答:
tl;dr

It is the strategy pattern as mentioned earlier by Cameron MacFarland.
But I also have a few problems with your question.

Your node interface is not using generics. Therefore, to use a Node you need to know what type of Node you were trying to use (File in your example).
So if we fix this by adding Node then your two example becomes more clear.

Now what we see is that both are very similar with the exception that the Node one is stateful vs stateless as in the NodeWorker one.

You can see this clearly by adding a very quick:
T getAdapted() to your Node interface.

Now you basically have the same code as the NodeWorker with one extra line of code  but a slightly (arguably) cleaner grandParent method.

As far as the number of classes you need to implement using this new Node vs your NodeWorker? It's exactly the same now.

So now the question becomes a multi part question.
If you want an adapter then you should never really know what the adapter was adapting (ideally). Because the adapter is your 'standard' way to interact with multiple subsystems that you don't want to have to manage.
This mean you shouldn't ever KNOW what type of object was actually adapted. What did you want to do with the File? Would what you want to do with the File change if you were using some other type of Node? If not then add the interaction methods that you need to the Node interface.

What is the advantage of that? The advantage of that is that Node does NOT need generic types and can actually return other Node types WITHOUT having to let the clients know or even care.

For example suppose that we have File types Directory types and Disc types.

the grandParent call could conceivably return Directory as the parent of a file and Disc as the parent of the Directory which in essence would return DirectoryNodeAdapter and DiscNodeAdapter all under the interface of Node without the client having to worry about it!

Common methods (let's say delete) could be added to the interface instead and again you never have to worry about the fact that it was a Directory or Disc or File to delete as you Node adaptors will abstract that away from you.

Your strategy NodeWorker will not have this ability as is now typed to the first type File and the grandparent call assumes that this same type will be returned
(This can be changed in your strategy interface of course).

Basically what it boils down to is your use case.
I personally like to use the strategy pattern when working with the SAME set of items but the specifics of how I want to deal with it while performing the SAME tasks will vary.

A good example of this would be the Comparator interface in java where I know I'm dealing with a set of objects and know that I need to vary (or may change) how I compare them.

I personally use adapter patterns when I want to hide the underlying system should I want to swap out the underlying system at some point.

A good example of this is java jdbc and eclipse's plugin architecture.


答:
There can't ever be one "best" of anything because there are so many opinions about what "best" is. The decision is specific to the needs and limitations of the user. Designs are always based on their ability to fit within constraints.

A basic mobile phone needs to store a few hundred contacts, text message history, and a few small apps. Does its filesystem need to support a hierarchical directory structure on multi-terabyte drives in a RAID configuration? Is there sufficient RAM on the device to run such a filesystem? Does the filesystem need complex ACLs? Probably not -- for all of these questions -- so a simple, resource-sipping filesystem would suffice.

Companies will also develop different products to maintain a competitive advantage. For instance, Apple touts the ability of its HFS+ filesystem to track which files have changed recently so that backups are quick. On the flip side, the drivers for a floppy disk filesystem (FAT) can fit in just a few KB of memory.


问:
Recommended content for layers
As an expansion from my previous question about using separate projects for seperate layers - Good practice on Visual Studio Solutions

I now wish to know if I am putting the right functionality in the correct layers.

Background

I'm building a WPF application from scratch, that contains business logic and business objects. The database itself sits on another server on the web with access to it, restricted to web API calls using OAuth authentication.

I think the following content should be in these layers. The idea being, you go from layer 1 to layer 4, you are only depending on the layers below you. To prevent circular dependencies.

1. Presentation

WPF View (what the user will see)

WPF ViewModel (how the program responds to user interaction)

No WPF Model, as it will just be the business object

2. Application/Services

Repository (class used by ViewModel to load/save business objects)

Utility classes to assist in saving objects, by selecting the correct API calls.

3. Business layer

Business objects/Entities/DTO (whichever name is preferred)

Factories (Used by the repositories in the creation of business objects)

Other misc business class (i.e. storage of currently logged in user)

4. Infrastructure/Data Access

OAuth client (makes authenticated calls against the web server, used by repository classes)

答:
Just a couple of suggestions:

Infrastructure and Data Access should be two separate layers. Their concerns are different enough for that.

Maybe "storage of currently logged in user" is better suited for the infrastructure class, as this data probably relies on a system dependant authentication/authorization system.

Repository implementations should go in the Data Access layer, but repository contracts should go in the Business layer (since the business objects know what are the persistence requirements).

Title: Recommended content for layers


答:
Being a maintenance developer != being left on the bench. Maintenance dev work can be some of the most frustrating, painful and annoying work in the world as you fix the weird issues the original developer missed.

It can also be some of the most rewarding, both personally and professionally, and educational work you can do. If you can take out a bug that's existed in the system for 6 months+ and has a direct knock on effect to 10% of the customer base your bosses will love you, 10% of the customer base will love you as well. By improving software incrementally and fixing bugs that take a week to track down effectively you'll be increasing your knowledge of not just that system, but what bugs that you can potentially see under specific conditions, and then you take it on board and become a better developer.

I love creating systems anew, but most of the tricks in my programming bag came from doing maintenance work and come in handy more times than I care to think.

Title: Becoming a "maintenance developer"

Body:
So I've kind of been getting angry about the current position I'm in, and I'd love to get other developers' input on this.

I've been at my current place of employment for about 11 months now. When I began, I was working on all new features. I basically worked on an entire new web project for the first 5-6 months I was here. After this, I was moved to more of a service oriented role (which was still great, all new stuff for me), and I was in this role for about the past 5-6 months. Here's where the problem comes in.

Basically, a couple of days ago I was made the support/maintenance guy. Now, we have an IT support team, so I'm not talking that kind of support, I'm talking more of a second level support guy (when the guys on the surface can't really get to the root of the issue), coupled with working on maintenance issues that have been lingering in the backlog for a while. To me, a developer with about 3 years of experience, this is kind of disheartening.

With the type of work place this is, I wouldn't be surprised if these support issues take up most of my days, and I barely make it to working on maintenance issues. Also, most of these support issues aren't even related to code, they are more or less just knowing the system architecture, working with making sure services are running/getting started properly, handling/fixing bad data, etc. I'm a developer, so this part sucks. Also, even when I do have time to work maintenance, these are basically just bug fixes/improving bad code, so this sucks as well, however at least it's related to coding.

Am I wrong for getting angry here? I don't want to really complain about it, but to be honest, I wasn't spoken to about this or anything, I was kind of just sent an e-mail letting me know I'm the guy for this type of thing, and that was that. The entire team took a few minutes to give me their "that sucks" talk, because they know how annoying it is to be on support for the type of work we do, so I know I'm not the only guy that knows it's not that great of an opportunity.

I'm just kind of on the fence about how to move forward. Obviously I'm just going to continue working for the time being, no point making a bad impression on anybody, but I'd like to know how you guys would approach this situation, or how you think I should be feeling about it/how you guys would feel.


答:
The main problem missing from the existing answers (as of the time of this posting) is the choice.

It's simple. If, for some utterly irrational reason, you feel that exceptions aren't worth the overhead, then you don't have to use them. You can still have templates, and RAII, and the Standard library, and never write a single "throw". The same goes for templates. If, for some reason, you feel they cause irrevocable (and actually important, which it is only on embedded) executable bloat, then surprise- you can use void* and sizeof(T) all day too. Nothing forces you to use any of the C++ features over C.

That's why C++ is an inherently superior language- you can cherry pick the features you want, and fall back to C-style programming when you dislike a given feature. Therefore, given that C++ is everything C is and more, it's an obvious fact that C++ is a superior language. Suggesting otherwise is like trying to suggest that 4 is greater than 5.

Title: When to use C over C++, and C++ over C?

Body:
I've been introduced to Computer Science for a little over a year now, and from my experience it seems that C and C++ are both considered to be "ultrafast" languages, whereas others such as Python and such scripting languages are usually deemed somewhat slower.

But I've also seen many cases where a software project or even a small one would interleave files where a certain number n of those files would be written in C, and a certain number m of those files would be written in C++.

(I also noticed that C++ files almost always have corresponding headers, while C files not so much). But my main point of inquiry is to get a general sense of intuition on when it is appropriate to use C over C++, and when it is better to use C++ over C. Other than the facts that (1) C++ is object-oriented whereas C is not, and (2) the syntaxes are very similar, and C++ was intentionally created to resemble C in many ways, I am not sure what their differences are. It seems to me that they are (almost) perfectly interchangeable in many domains.

So it would be appreciated if someone could clear up the situation! Thanks


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
In theory, there is no difference
  between theory and practice. But, in
  practice, there is.

— Jan L. A. van de Snepscheut

LastEditorDisplayName: Roger Pate


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答: A decent chair. (If you can afford it, a Herman Miller Mirra is absolutely wonderful for someone sitting in a chair for many hours a day.)


答:
In addition to what have been said:

A- Calculate your cost accurately (documentation, web site, licensing software, support) this is of course in addition to programming cost so that you set your break even price.

B- Make different license costs based on how many users are using your software. If you don't do that mid-size corp. users will not be tempted to buy the software.

C- Consider the total cost of ownership to the user. For example, factor in the cost of database, and any other costs the user is required to pay to make the solution work. Compare that with similar products (if any) on the Net.

Body: What factors should be evaluated when determining a desktop software price?</p>


答: Talk to you manager about rotating developers into the position (say on a monthly cycle or something). If everyone knows that it sucks then everyone will understand why the work is being distributed around the whole team. Maybe in talking to your manager you'll find out that this is already the case, and you've just gotten rotated in. </p>

Title: Becoming a "maintenance developer"


问:
What is the equivalent of functions and methods in SQL?
In language like C or Java, there are things like functions/methods to modularize and abstract stuff.

What is there in SQL, specifically for Oracle?

I've seen people talking about using views to reduce the complexity in various blogs but there is only so much that can be done with a view. (For example, a bind variable cannot be passed as a runtime parameter to a view). In tools like Oracle Reports the query sometimes gets very awkward running several hundreds of lines.

I was wondering what sort of techniques people use to manage the complexity of their SQL? What are the equivalents of functions and methods in SQL to keep SQL from becoming extremely complex?

答:
PL-SQL supports user defined functions. You can use this to re-use some common logic with queries. However, there are significant performance penalties for doing this, as UDFs hide indexes from the query. Most of the time, you're better off writing out your query logic again.

Another option is to use a computed column. This let's you do some (not all) of the same things as a scalar user defined function, but is more index-friendly.

OwnerDisplayName: toddlermenot

OwnerDisplayName: Joel Coehoorn


答: I have found common table expressions (cte's) helpful for both reducing the size and complexity as well as making the query more readable.  Temporary results (temp tables and so forth) can be a mixed blessing, as can user defined functions.  They can certainly make the code more readable, but may have a performance impact (not that the impact is always negative, but it is something to watch out for).</p>

Title: What is the equivalent of functions and methods in SQL?

Body:
In language like C or Java, there are things like functions/methods to modularize and abstract stuff.

What is there in SQL, specifically for Oracle?

I've seen people talking about using views to reduce the complexity in various blogs but there is only so much that can be done with a view. (For example, a bind variable cannot be passed as a runtime parameter to a view). In tools like Oracle Reports the query sometimes gets very awkward running several hundreds of lines.

I was wondering what sort of techniques people use to manage the complexity of their SQL? What are the equivalents of functions and methods in SQL to keep SQL from becoming extremely complex?

OwnerDisplayName: jmoreno


答:
There are advantages and disadvantages to both (in my opinion):

Stored procedures can become a nightmare if you are not using some sort of SQL source control (which a lot of places don't) and you have multiple developers working on them. Someone can change a stored procedure and forget to update the code that calls that procedure and before you know it you've just built and deployed a site that is going to throw unhandled exceptions (parameter count mismatch etc).

On the other hand, stored procedures allow for quicker bug fixes in certain situations. If there is a bug with a stored procedure you just fix it and you're done. A bug fix in an ORM requires a rebuild. Depending on your build process this could be lengthy / annoying.


问:
How to specify WIP limits in Kanban?
Consider a typical Kanban board:

Input, Analysis, Dev Ready, Development, Build Ready, Test, Release Ready

How to specify WIP limits for each column? any formula?

答:
I'd start with a number of "slots" in each column that is equal to the number of people that would pick up work in the associated column. That will reveal bottlenecks or pain points. Address the pain point until it is gone.

Over time experiment with reducing the number of slots in each column.

OwnerDisplayName: The Legend of 1982

Title: How to specify WIP limits in Kanban?

OwnerDisplayName: John


答:
No, no formula. There isn't one.

Much depends on the way your team works, practices you use, etc. If you pair program you will have lower limits in development column than a number of developers.

If you introduce Kanban in existing team you can try to map all the work which is currently in progress into MMFs, and then see how many features you do have in different columns. It would give you some insight what limits you really have at the moment and this is a good starting point to set Kanban limits.

Another advice you get is go with your/your team's gut feeling. Do what you feel is right. Then monitor whether your limits aren't too tight or too loose and adjust. Some people say "the board will tell you" and that's basically true. If you hit the bottleneck every single week you probably have you limits set too low. If one or two blockers aren't a problem limits are too high.

I wrote a post how we set our limits when we were crafting our Kanban board: http://blog.brodzinski.com/2009/11/kanban-story-kanban-board.html

Title: How to specify WIP limits in Kanban?

Body:
Consider a typical Kanban board:

Input, Analysis, Dev Ready, Development, Build Ready, Test, Release Ready

How to specify WIP limits for each column? any formula?

OwnerDisplayName: pawelbrodzinski


答:
I use two techniques for specifying WIP limit when we start a new project or a team.

In case of a development project: we are working in pairs (we are doing XP), which means that two members can work on one element at a time. If the team consisted of 6 people, the WIP would be 3, based on the previous sentence. However pair programming is an exhausting job, and sometimes colleagues would like to work a bit alone, I give a plus one, so the WIP limit for 6 members would be 4.

When we are talking about a maintenance, verification test or support project, then I check how much parallel work the different colleagues can do, I sum this number and I subtract it with one. For example everybody from the previously mentioned team can take care of 2 parallel issues, it would make the WIP limit 12, but with the -1, it is 11. The -1 ensures me that the team stays focused, and works together. If in this case the WIP limit were 12, everybody would work on his/her maximum two cards, and no collaboration would happen.

I want to empathize that I use these techniques only at the beginning when the project/team starts. Afterwards the adjustment of the WIP limit is the duty of the team based on their feelings, load, goal etc.

Title: How to specify WIP limits in Kanban?

OwnerDisplayName: Zsolt


答: I've tried two extremes, both suggested by different people. One is to use high limits and tweak them down until it hurts, and the other is the opposite, to start with n-1 where n is the number of people who could pull a task to that column. The latter is more painful for teams new to kanban, but it helped us to arrive at a flow maximizing point faster than the first option because when we felt pain (bottlenecks) our first instinct was to examine the problem with raising the WIP limit as a last resort and as a result, we uncovered and solved several process issues that might have been invisible otherwise.</p>

Title: How to specify WIP limits in Kanban?

OwnerDisplayName: Paul


问:
Loading XML File
I'm using xml to store cross-program information. This information is used in some webpages and in C# programs. When the information is altered, these alterations are not displayed right away in the webpages, they keep on displaying the information saved in cache, it takes a few refreshes for the webpage to show these alterations. Is there any way I can force the webpages to show the actual file and not the cached one?</p>

答: Your pages are cached.  Put a meta line in the header saying that they expire very soon, and they should get reloaded.</p>

Title: Loading XML File


问:
Coding to interfaces
I understand why it is a good idea to code to an interface rather than to a concrete class. I find it hard to implement though as other methods generally need to use properties of the given object. Have I got the wrong end of the stick?</p>

答:
I don't see why needing properties matters. Don't focus on what you need to perform the operation, but rather what operations are needed. The data needed to perform said operations will be determined by the implementing classes.

For example, you have a Shape interface. One of the methods in this interface is getArea(). You say that anything that is a Shape must be able to calculate its area - that implies that it must have the appropriate properties and members to do so. If a Circle class implements the shape interface and needs a getArea() method, that implies that (since getArea() doesn't take any parameters), that the Circle instance must be aware of it's radius. If a Rectangle class implements the Shape interface, that implies that it must somehow maintain its length and width.

Title: Coding to interfaces


答:
In the case where you need external access to a property of an object you should make it part of the interface.  The usual convention is to add set_foo() and get_foo() methods to provide this access.

It is fairly common to need a few getter and setter functions, but you should think about the interface before adding too many.  In particular you should make sure that the property is a property of the class, not of the implementation.  Don't expose implementation details outside of the class, only properties which will always be a part of any reasonable implementation of that class.

Title: Coding to interfaces

Body: I understand why it is a good idea to code to an interface rather than to a concrete class. I find it hard to implement though as other methods generally need to use properties of the given object. Have I got the wrong end of the stick?</p>


问:
Why do we need a Heap if everything can be done much more efficiently on the Stack?
This is actually somewhat related to the question I asked yesterday about why both a Stack and a Heap are necessary in the applications we use today (and why we can't just go with a Heap instead of both, in order to have a simple & singular standard to go by).

However, many of the responses indicated that a Stack is irreplaceable due to the fact that is many hundreds (or thousands) of times faster than trying to allocate/reference the Heap. I know there is a problem with dynamic storage allocation if we do away with the Heap, but isn't there a way around this, or perhaps, a way to improve on the Stack so that it can handle dynamic memory allocation?

答:
Stack is per-thread, Heap is process-wide

If have 100 threads all processing work items I put into a queue, exactly where do I allocate the work items such that any of the 100 threads could see them?

There are other types of memory, too

E.g. memory-mapped files, shared memory, I/O mapped (kernel mode). The efficiency argument is kind of moot in these situations.


答:
Think of interface conformance as a step beyond type safety. Identify things that are changed  and ways they can be changed, define interface that provides them all and then while writing to interface assures you don't worry you'll confuse parameters or mess up units.

You can always assign special meta-values for "Do not affect" or "Not applicable", stubs that discard unnecessary information or provide blanket "default" values if your interface is "on the large side". But you're better off if you use more granular, smaller interfaces to cover smaller chunks of functionality. It will be better to separately implement "work data" and "configuration" interfaces, than requiring implementation of one huge "input data" interface, or even split "work data" further for various sources/types, like Activation and Status being separate interfaces - classes that need both, implement both.

Title: Coding to interfaces


问:
Solutions to C# 5 async re-entrancy
So, something's been bugging me about the new async support in C# 5:

The user presses a button which starts an async operation. The call returns immediately and the message pump starts running again - that's the whole point.

So the user can press the button again - causing re-entrancy. What if this is a problem?

In the demos I've seen, they disable the button before the await call and enable it again afterwards. This seems to me like a very fragile solution in a real-world app.

Should we code some sort of state machine that specifies which controls must be disabled for a given set of running operations? Or is there a better way?

I'm tempted to just show a modal dialog for the duration of the operation, but this feels a bit like using a sledgehammer.

Anyone got any bright ideas, please?

EDIT:

I think disabling the controls that shouldn't be used while an operation is running is fragile because I think it will quickly become complex when you have a window with many controls on it. I like to keep things simple because it reduces the chance of bugs, both during the initial coding and the subsequent maintenance.

What if there is a collection of controls that should be disabled for a particular operation? And what if multiple operations are running concurrently?

答:
Why do you think disabling the button before the await and then re-enabling it when the call completes is fragile? Is it because you are worried that the button will never get re-enabled?

Well, if the call doesn't return then you can't make the call again, so it seems that this is the behaviour you want. This indicates an error state that you should be fixing. If your async call times out then this could still leave your application in an indeterminate state - again one in which having a button enabled could be dangerous.

The only time this might get messy is if there are several operations that affect the state of a button, but I think those situations should be very rare.

Title: Solutions to C# 5 async re-entrancy


答:
We create a services layer that contains all of our business logic implemented in the chosen language and only use the database for queries. This approach is sort of mandated by us because our goal is to create COTS solutions to deliver applications with various database implementations. Hibernate has proven to be a lifesaver for us in these circumstances.

I think the greatest advantage of this approach, aside from database portability, is that you can find all of your answers in one search.

Also, despite some of the answers to a forum, I have a friend working for a fortune 100 insurance company who's done 2 database conversions in three years because the database of choice for the company changed.


问:
When to update jQuery?
When you recommend updating jQuery/jQuery UI? Or in other words: what are the best practices for updating jQuery/jQuery UI?

I’m working on a long project that will take at least one more year. In that time span, I’m sure that jQuery/jQuery UI will be updated many times.

Do you recommend update my jQuery/jQuery UI files every time an update is released? Or is better to stick with a particular version until the end of the project?

I’m afraid of “breaking” code changes, and every time an update is released, I have to test everything. That takes too much time. But on the other hand, if I didn’t update, I’m afraid of bugs that later will bite me in the rear.

The project is an ASP.MVC and I use jQuery a lot.

Any thoughts?

答:
Test. Test, test, test, test, test.

I used jQuery UI version (then-current) on a project, and used an external plugin called .autocomplete that did type-ahead functionality, tying a text field to a JSON data source. Used it a LOT of places.

Then, months later, I needed to add a slider control that only came in a later-current version. Unfortunately, that later-current version added a native autocomplete function, which they claimed was the spiritual successor of the plugin I'd used, but which used entirely different methodology, functions, and data requirements, breaking the autocomplete fields on every page I used my new slider on.

Because the pages I was developing this new feature on didn't use autocompletes, I didn't notice. Because my client was in a rush to get this feature up before a trade show, it got rushed through staging and testing, and got into production with a crapton of broken autocompletes.

Ultimately, it was a failure of MY testing. And the lesson learned is, jQuery and jQuery UI have very little interest in backward compatibility. Which puts the requirement on us, as devs, to test and test and test.

OwnerDisplayName: epaulk

Title: When to update jQuery?


答: Caffeine and a lot of patience...

Title: Stuff every programmer needs while working

Body:
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

Body: Caffeine and a lot of patience...


问:
What is the accepted style for using the `this` keyword in Java?
I come from languages like Python or Javascript (and others that are less object-oriented) and I am trying to improve my working knowledge of Java, which I know only in a superficial way.

Is it considered a bad practice to always prepend this to the current instance attributes? It feels more natural to me to write

```<code>...
private String foo;

public void printFoo() {
    System.out.println(this.foo);
}
...
</code>```

than

```<code>...
private String foo;

public void printFoo() {
    System.out.println(foo);
}
...
</code>```

as it helps me to distinguish instance attributes from local variables.

Of course in a language like Javascript it makes more sense to always use this, since one can have more function nesting, hence local variables coming from larger scopes. In Java, as far as I understand, no nesting like this is possible (except for inner classes), so probably it is not a big issue.

In any case, I would prefer to use this. Would it feel weird and not idiomatic?

答:
It's debatable.

Taking C# as an analogy as it has a very similar syntax and structure to Java we find that C# StyleCop has a default rule that insists you add this, but ReSharper has a default rule that says that the this is redundant (which it is) and can be removed.

So if you are using one tool you'll add them but if you use another you'll remove them. If you are using both tools then you'll have to chose and disable one of the rules.

However, what the rules do mean is that you are consistent in your usage - which is probably the most important thing.


答:
I prefer to use this. It makes it easier to read code in various editors that color local and instance variables in the same way. It also makes it easier to read the code on a printed page during something like a code review. It's also a fairly strong reminder as to the scope of the variable to other developers.

However, there are arguments against this. In modern IDEs, you can find out the scope of a variable by hovering over it or viewing it in a tree-like structure. You can also change the color and/or font face of variables depending on their scope (even in such a way that, when printed, it's evident what the scope of the variable is).

I believe that ChrisF's last sentence is dead on: be consistent in your usage.

Title: What is the accepted style for using the `this` keyword in Java?

Body:
I come from languages like Python or Javascript (and others that are less object-oriented) and I am trying to improve my working knowledge of Java, which I know only in a superficial way.

Is it considered a bad practice to always prepend this to the current instance attributes? It feels more natural to me to write

```<code>...
private String foo;

public void printFoo() {
    System.out.println(this.foo);
}
...
</code>```

than

```<code>...
private String foo;

public void printFoo() {
    System.out.println(foo);
}
...
</code>```

as it helps me to distinguish instance attributes from local variables.

Of course in a language like Javascript it makes more sense to always use this, since one can have more function nesting, hence local variables coming from larger scopes. In Java, as far as I understand, no nesting like this is possible (except for inner classes), so probably it is not a big issue.

In any case, I would prefer to use this. Would it feel weird and not idiomatic?


答:
In most IDEs, you can simply mouseover the variable if you want to know. In addition, really, if you're working in an instance method, you should really know all the variables involved. If you have too many, or their names clash, then you need to refactor.

It's really quite redundant.


答:
Is it considered a bad practice to always prepend this to the current instance attributes?

Yes - by some, no - by others.

I like and use this keyword in my projects in Java and C#. One can argue that IDE will always highlight parameters and fields by different color however we don't always work in IDE - we have to do a lot of merges/diffs/some quick changes in a notepad/check some code snippets in e-mail. It's way easier for me to spot from the first look where instance's state is changed - for example, to review some possible concurrency issues.


问:
DDD - Does an aggregate root's repository handle saving aggregates?
I am using a DDD-like approach for a greenfield module of an existing application; it's not 100% DDD due to architecture but I'm trying to use some DDD concepts.  I have a bounded context (I think that's the proper term - I'm still learning about DDD) consisting of two Entities: Conversation and Message.  Conversation is the root, as a Message doesn't exist without the conversation, and all messages in the system are part of a conversation.

I have a ConversationRepository class (although it's really more like a Gateway, I use the term "Repository") which finds Conversations in the database; when it finds a Conversation it also creates (via Factories) a list of messages for that Conversation (exposed as a property).  This seems to be the correct way of handling things as there doesn't seem to be a need for a full-blown MessageRepository class as it only exists when a Conversation is retrieved.

However, when it comes to saving a Message, is this the responsibility of the ConversationRepository, since it's the aggregate root of Message?  What I mean is, should I have a method on ConversationRepository called, say, AddMessage that takes a Message as it's parameter and saves it to the database?  Or should I have a separate repository for finding/saving Messages?  The logical thing seems to be one repository per Entity, but I've also heard "One repository per Context".

答: You could create the ConversationService and inject the IConversationRepository and IMessageRepository in its constructor. Use repositories for simple CRUD operations, and services for everything else (caching, saving logic, etc.)


答:
In the demos I've seen, they disable the button before the await call
  and enable it again afterwards. This seems to me like a very fragile
  solution in a real-world app.

There is nothing fragile about this, and it is what the user would expect. If the user needs to wait before hitting the button again then make them wait.

I can see how certain control scenarios could make deciding which controls to disable/enable at any one time pretty complex, but is it suprising that managing a complex UI would be complex? If you have too many scary side effects from a particular control, you can always just disable the entire form and throw a "loading" whirly-gig over the whole thing. If this is the case on every single control, then your UI is probably not very well designed in the first place (tight coupling, poor control grouping, etc.).

Title: Solutions to C# 5 async re-entrancy

Body:
So, something's been bugging me about the new async support in C# 5:

The user presses a button which starts an async operation. The call returns immediately and the message pump starts running again - that's the whole point.

So the user can press the button again - causing re-entrancy. What if this is a problem?

In the demos I've seen, they disable the button before the await call and enable it again afterwards. This seems to me like a very fragile solution in a real-world app.

Should we code some sort of state machine that specifies which controls must be disabled for a given set of running operations? Or is there a better way?

I'm tempted to just show a modal dialog for the duration of the operation, but this feels a bit like using a sledgehammer.

Anyone got any bright ideas, please?

EDIT:

I think disabling the controls that shouldn't be used while an operation is running is fragile because I think it will quickly become complex when you have a window with many controls on it. I like to keep things simple because it reduces the chance of bugs, both during the initial coding and the subsequent maintenance.

What if there is a collection of controls that should be disabled for a particular operation? And what if multiple operations are running concurrently?


答:
Disabling the widget is the least complex and error-prone option. You disable it in the handler before starting the async operation and you re-enable it at the end of the operation. So the disable+enable for each control are kept local to handling of that control.

You can even create a wrapper, that will take a delegate and control (or more of them), disable the controls and asynchronously run something, that will do the delegate and than re-enable the controls. It should take care of exceptions (do the enable in finally), so it still works reliably if the operation fails. And you can combine it with adding message in status bar, so the user knows what he's waiting for.

You may want to add some logic to count the disables, so the system keeps working if you have two operations, that should both disable a third one, but are not otherwise mutually exclusive. You disable the control twice, so it will become enabled again only if you enable it twice again. That should cover most cases while keeping the cases separate as much as you can get.

On the other hand anything like state machine is going to become complex. In my experience all state machines I ever saw were difficult to maintain and your state machine would need to encompass the whole dialog, tying everything to everything.

Title: Solutions to C# 5 async re-entrancy


答:
Logic should be in the BLL always because:

It can be tested properly

When SQL 20XX becomes obsolete and you need to change to the latest version, you do not have to rewrite your code.

People are not tempted to make to make changes on the fly (which seems to be being put forward as a argument FOR SPs)

SPs, in my experience, are the single biggest point of developer error, especially after a few generations of maintenance/changes.

I believe there should be a law that states that after an SP is more than X lines long, it does not work as intended.

OwnerDisplayName: Pravin Patil


答:
Being a java developer my preference was to put business logic in the BLL (nice and easy source control, familiarity etc etc etc).

However, after working for a large enterprise with many distributed applications using different technologies (C#, Java, Pick (don't ask)) one significant benefit of using stored procedures became apparent :

Stored Procedures can be shared across different applications.


答:
As is so often the case in computing the answer is (a) because of historical circumstance and the need to maintain backwards compatibility and (b) because some methods are better suited to some tasks than others.

On (a) you need to remember that the "Winchester drive" - I am just about old enough to remember them being called that - (what the rest of the world calls a 'hard drive') has only been around for about half the time of electronic computing and even then it has not been accessible to most users for even that long for cost reasons. The FAT file system worked well on floppy disks and also on the original small hard drives as it was reasonably efficient and required low overhead. Once it started to be used - and its use spread widely because it is simple to implement - manufacturers could not tell its users that their old data was suddenly invalid.

Similarly, for Linux users, say, a stable NTFS driver was a long time coming, so keeping devices formatted as FAT meant they could be read and written across multiple systems.

On (b) - think of the differences between a system that, say, stores, billions of text-based database records and one that stores DVD-length media files. For the databse each record could be very small - perhaps just 30 or 40 bytes and certainly a filesystem that allocated a whole 'segment' (however you want to define that) of disk is likely to be wasteful of diskspace. Not so with the DVDs - bigger 'segments' (within reason, obviously) are likely to be highly efficient in space terms.

So different filesystems are designed for different purposes.


问:
Do we need test data or can we rely on unit tests and manual testing?
We're currently working on a medium/large PHP/MySQL project. We're doing unit testing with PHPUnit & QUnit and we have two full time testers that are manually testing the application. Our test (mock) data is currently created with SQL scripts.

We have problem with maintaining scripts for test data. The business logic is pretty complex and one "simple" change in the test data often produces several bugs in the application (which are not real bugs, just the product of invalid data). This has become big burden to the whole team because we are constantly creating and changing tables.

I don't really see the point of maintaining the test data in the scripts because everything can be manually added in the application in about 5 minutes with the UI. Our PM disagrees and says that having project that we can’t deploy with test data is a bad practice.

Should we abandon maintenance of the scripts with test data and just let the testers to test the application without data? What’s the best practice?

答:
You are mixing two different concepts. One is verification, which is based on Unit Testing and Peer Reviews. This can be done by the developers themselves, without test data and its intent is to verify that a set of requirements are met.

The second one is validation, and this is done by QA (your testers). For this step you do need test data since the tester do not need to have any knowledge of the programming in the application, only its intended use cases. Its objective is to validate that the application behaves as intended in a production environment.

Both processes are important and necessary to deliver a quality product to the customer. You can't rely on unit tests alone. What you need to figure out is a reliable way to handle your test data to ensure its valid.

EDIT: OK, I get what you are asking. The answer is yes, because the Tester's job is not to generate the test data, just to test the application. You need to build your scripts in a way that allows easier maintenance and ensures valid data is inserted. Without the test data, tester will have nothing to test. Having said that, however, if you have access to the testing environment, I don't see why you can't you insert the test data manually rather than by using scripts.


答:
Yes, having unit tests and  data mock-ups is a best practice.  The project manager is correct.  Since performing a "simple" change in the test data often produces bugs, then that is the core of the problem.

The code needs improvement. Not doing so (saying hey we don't need tests) is not a fix, that is simply adding technical debt.  Break the code down into smaller more test-able units because being unable to identify units without breakage is a problem.

Start doing a refactor.  Keep the improvements small so they are manageable. Look for anti-patterns like God classes/methods, not following DRY, single-responsibility, etc...

Finally, look into TDD to see if it works for the team.  TDD works well for ensuring all your code is test-able (because you write the tests first) and also ensuring you stay lean by writing just enough code to pass the tests (minimize over engineering).

In general, if a series of complex business logic processes produce a set of data, then I view this as a report.  Encapsulate the report.  Run the report and use the resultant object as input to the next test.

Title: Do we need test data or can we rely on unit tests and manual testing?

Body:
We're currently working on a medium/large PHP/MySQL project. We're doing unit testing with PHPUnit & QUnit and we have two full time testers that are manually testing the application. Our test (mock) data is currently created with SQL scripts.

We have problem with maintaining scripts for test data. The business logic is pretty complex and one "simple" change in the test data often produces several bugs in the application (which are not real bugs, just the product of invalid data). This has become big burden to the whole team because we are constantly creating and changing tables.

I don't really see the point of maintaining the test data in the scripts because everything can be manually added in the application in about 5 minutes with the UI. Our PM disagrees and says that having project that we can’t deploy with test data is a bad practice.

Should we abandon maintenance of the scripts with test data and just let the testers to test the application without data? What’s the best practice?


答:
"Business logic" is a bit of a vague term. I mean it does not have a single definition.
A rule of thumb is to minimize communication between the tiers when you can. So, you don't need to send blank customer name to the server to check it before inserting a row.

There are cases, when a rule is based on a database read. Say you want to transfer money from Account 1 to Account 2. You need to read both accounts, make sure they are in good status and that the amount in Account 1 is sufficient. In this case, the server is a better candidate for this rule because the client (being the BL here) need not issue 3 calls to the database tier for this process.

Of course, if you need your solution to be database independent make stored procs only for CRUD (if at all used).


问:
How do you deal with changing requirements?
In my current job it feels like we have a lot requirement changes. We are an "Agile" shop, so I get that we are supposed to adjust and what not, but sometime the change is large and nothing trivial.

My question is, how do you effectively communicate the cost of the change? Because of being agile, if a change is big enough something will get dropped from the current sprint, but it usually just get added next time around. Since our model is SaaS, the end customer is effectively the business itself, and they know they will get the cut feature n weeks later.

I guess what I am trying to get at is the removal of a feature really isn't anything to use for communication as it was only delayed by n weeks. What other ways do you have to get the business to understand what a change costs?

答:
@Joe "We are an "Agile" shop, so I get that we are supposed to adjust and what not, but sometime the change is large and nothing trivial. "

If your process doesn't allow you to control the rate of change in requirements, your process is not agile, but haphazard. Agile does not mean "taking anything that comes my way."

To control requirement change/creep you can adopt - in your process - the notion that a requirement does not change (a notion that it's at the heart of Scrum.) Treat a requirement change as replacing an old requirement with a new one. You have to have a backlog of requirements, and you have to have the user choose which ones he/she wants to have implemented.

You wanted X and Y in two weeks, but all of the sudden you want Z. Well, then I can deliver you all three in 4 weeks. Or I can give a pair (X and Z) or (X and Y) or (Y and Z) in two weeks and deliver the remaining one later. Choose.

This is how you negotiate with customers. This is how you communicate the cost of requirement change. If your group does not have that power, you are not in an agile shop, and there is nothing that you can do about it. It sucks, but it's true.

In case where you can negotiate, you have to track (with precision) the time it takes to implement requirements and requirement changes. That is, you have to collect this data from past and present projects.

You collect the original time estimate and the actual completion time (in addition to resources like developer count) per request (or module affected by N requests). Better yet, estimate the size of the request/request change (in terms of lines of code or function points in past projects and requests.)

Say you  have a metric that you can talk to the user with. You know that a new request will take, say, 1K lines of code, or 10 web pages with an average of 5 input fields each (50 function points).

Then by looking at historical data specific to your past projects (some by lines of codes, some by web pages, some by actual function points), and you can estimate how each of these cost in terms of absolute completion time. For those with sufficient data, you can also identify those requirements that track an actual developer head count.

Then you use that and you tell your customer that based on historical data; you argue that project failures tend to follow a exponential distribution follow; and then you are armed with the following argument for your customer:

Based on data from our past and present projects and available
  resources, the requirement you are asking will take

X amount of time to complete with a 25% probability of failure (or
  75% of success)

1.5 * X amount of time to complete with a 5% of failure (or 95% of success)

0.5 * X amount of time to complete with a 95% of failure (or 5% of success)

The probability of failure as a function of amount of time resources typically go 95%, 25% and 5% (resembling an exponential distro.) You convey the message that a certain baseline amount gives a somewhat decent chance of success (but with real risks). 1.5 of that might give almost a certain chance of success with minimal risk, but than much less than that (0.5 of the original guarantees almost certain failure.)

You let them digest on that. If they still go for the risky proposition (done yesterday!) at least you have in writing that you told them so. If there is hope for your group of not just being agile but engineering-like, then, the customer might put serious consideration into your numbers and schedule this and future requests accordingly.

It is your job as an engineer to explain in engineer, verifiable and clear terms that request changes are not a free meal.


答:
I think that if you need to use this, you either have a method that is too long, or a class that is trying to do too much, or both.

Methods should never be more than a few lines of code long, use one or two local variables, determining what is what becomes easy; even with only the 3 lines context of most diff tools. If your methods are too long and your classes have too many responsabilities (often meaning too many fields), the solution is to split them instead.

I think that "this" just clutters code. Especially with modern IDEs that will color local parameters/local variables/fields differently.


答:
I'm not sure if this applies to you since I usually use WPF, but I see you referencing a ViewModel so it might.

Instead of disabling the button, set an IsLoading flag to true. Then any UI element you want to disable can be bound to the flag. The end result is that it becomes the UI's job to sort out it's own enabled state, not your Business Logic.

In addition to that, most buttons in WPF are bound to an ICommand, and usually I set the ICommand.CanExecute equal to !IsLoading, so it automatically prevents the Command from executing when IsLoading is equal to true (also disables the button for me)

Title: Solutions to C# 5 async re-entrancy


问:
Involuntarily becoming a programmer: how to do it right?
My background is electrical engineering, DSP to be more precise. The company I currently work for does a lot of diverse projects, mostly building analog hardware. Being somewhat closer to computers than everybody else around here I'm often the one writing code for both embedded devices (which I'm perfectly fine with) and Windows or Linux OS. It is the latter that is foreign territory to me.

I can code, and I know a few languages (C/C++, Java, some VB.NET), but I only used them for algorithm simulations in signal and image processing, neural networks, and other similar applications. For me programming has been a computational tool more than anything else. However, I get more and more projects where I have to write proper full-fledged software, and I don't really know how to do it, because I never had to do it, and I was never really interested enough. I have myself seen quite a few engineers who got converted into coders to a certain degree because of job demands, and most of them weren't that great at what they did. I'm sure many people have encountered the same.

If I were to learn writing proper software with good user interface, good internal architecture and so on, how do I do it? We don't have anyone at work who could tell me what's good practice and what isn't. Given that I can write code in the rawest sense of the word, what else is there to know about writing good software and how I do I get there on my own?

答:
My company does this all the time...and it drives me nuts.

"I'm a software developer, how do I become a EE?"

Well, I think the answer is fairly obvious.  It takes a lot of time and hard work.  And of course, the right learning materials.  The Engineering background helps, at my university the CS and engineering schools were in the same building with a lot of overlap.  The algorithms and math foundations are there.

A mistake I see most newcomers make is to bite off way more than they can chew.  Learning materials across UI, architectures, quality code...that's a lot of ground.  Something that takes years really and is often done by teams of different experts at software companies.

Not to say you can't be pretty decent on your own, if you put in the time.  Just recognize the magnitude of the materials so you don't overwhelm yourself and either A. Quit or B. Build major technical debt into your apps by taking major shortcuts in your learning process.

Because of all this, there's no "catch-all" become an awesome dev with this book out there.  I recommend you start by picking up a well rated book on your most used language and also participating in the Stack community especially for code reviews.

Try Amazon.com, they have good book reviews.