答:
Frankly, if you look around, the desktop application landscape is in complete and total flux.  There are unverified rumors that future Silverlight support is wavering and according to an ex (and potentially disgruntled) MS project manager it is  effectively dead, WPF is getting a younger, cooler brother with a much larger friends list in Windows 8 (WinRT), and Windows Forms can't deliver modern application experiences.

So, while I agree that today Silverlight/WPF are the best choices for a Rich Desktop UI in .NET, if you're interested in future-proofing your project and, perhaps, your career, I would urge you to consider implementing it as an HTML 5 application following an approach similar to the Microsoft Patterns & Practices Group's Project Silk.

Title: Creating Compelling Desktop Application in .NET

Body: I'm about to create an open source desktop application.  I'm primarily a .NET developer , with experience in ASP.NET and SharePoint.  I've created basic Windows Forms applications before, but I have never developed using WPF or Silverlight before.  I want a compelling, highly interactive UI for my desktop application.  What are my technology choices for doing this, using .NET?  In particular, is HTML5 something I should be considering?</p>


问:
Databinding to an Entity Framework in WPF
Is it good to use databinding to Entity Framework's Entity in WPF?

I created a singleton entity framework context:

To have only one connection and it won't open and close all the time.

So I can pass the Entity around to any class, and can modify the Entity and make changes to the database.

All ViewModels getting the entity out from the same Context and databinding to the View saves me time from mapping new object, but now I imagine there is problem in not using the newest Context:

A ViewModel databinding to a Entity, then someone else updated the data.  The ViewModel will still display the old data, because the Context is never being dispose to refresh.

I always create new Context and  then dispose of it.  If I want to pass the Entity around, then there will be conflicts between Context and Entity.

What is the suggested way of doing this ?

答:
.net actually does a good job of managing the connections behind the scenes for you by pooling connections. </p>

<p>This is a classic case of optomising too early. You are actually much better off writing an application that works and bench testing to find the bottle necks rather than making assumptions and overcompicating your design too early. You may find you need to use the singleton pattern but I doubt it. </p>

ContentLicense: CC BY-SA 3.0

Body:
.net actually does a good job of managing the connections behind the scenes for you by pooling connections.

This is a classic case of optomising too early. You are actually much better off writing an application that works and bench testing to find the bottle necks rather than making assumptions and overcompicating your design too early. You may find you need to use the singleton pattern but I doubt it.


问:
Why would a company develop an atmosphere which discourage code comments?
I was taught in university to write comments for our programs. As I write comments, I feel like I have a better organization and understand the programs better.

However, I am in a company where most of the code I encounter doesn't have comments. Why would a programmer not write comments? Are there are any objective reasons? Do you think comments are annoying when you read others' code? I don't write comments either, and I can think of some reasons why not:

Because I can already easily understand the program.

My boss won't care how my program gets the job done.

Nobody is likely to pick up my program after I am gone.

The purpose of comments is usually to include explanations for the program, however, I found that in my company, comments are used to cover obsolete code instead. For example:

```<code>/* Obsolete code */
New code
</code>```

What is your opinion on commenting? Should we do it? Or does it depend on the situation?

答:
The only comments I like are the ones explaining why the current design is bad and how to improve it.

Outside those "this is why this sucks" comments, if you can't understand what it does by looking at the code and reading/running the tests then there is no hope.


答:
The suggested way is don't do it -- results are unpredictable to the point of being dangerous to your data. You should not give the view direct access to the database. Results are unpredictable.

First, the nature of both databinding and the modern fancy ORMs is pretty heavy reflection and other similar stunts. Oftentimes things just don't work or just don't get updated in the way that the ORM expects so there are very odd bugs to track down. Second, those DbContexts are pretty stateful and there can be lots of complications when newing them up and passing in objects. Third issue is the potential for the SELECT N+1 sort of performance issues -- if you cut off database access then your view can't reach back to the database to do a sub-select for every single customer you put in the list, for instance. Finally, for non-trivial applications, one rarely sees scenarios where the front-end views want to talk to an object shaped like the back-end entities.

Title: Databinding to an Entity Framework in WPF

Body:
Is it good to use databinding to Entity Framework's Entity in WPF?

I created a singleton entity framework context:

To have only one connection and it won't open and close all the time.

So I can pass the Entity around to any class, and can modify the Entity and make changes to the database.

All ViewModels getting the entity out from the same Context and databinding to the View saves me time from mapping new object, but now I imagine there is problem in not using the newest Context:

A ViewModel databinding to a Entity, then someone else updated the data.  The ViewModel will still display the old data, because the Context is never being dispose to refresh.

I always create new Context and  then dispose of it.  If I want to pass the Entity around, then there will be conflicts between Context and Entity.

What is the suggested way of doing this ?


问:
Logistically, how do you manage embedded SQL?
My current application is running into issues with its ORM, and we're relying on some pretty hairy SQL to express queries that the ORM can't.  Are there best practices in terms of how to manage the SQL queries?  For example, where do these usually live in relation to other parts of the code?  Are they in separate .sql files, or do you edit them directly in your other source files?  If the latter, does your IDE (or editor) allow syntax highlighting?  Are there schemes for Vim or Eclipse which will perform SQL syntax highlighting given a set of tags (like #begin sql and #end sql, or something similar?)

答: We typically segregate DB-specific stuff into one or more Strategy classes, and then configure them at deployment time.  I once over-engineered a solution that would auto-wire everything at run time after introspecting the database connection, but it was overkill for the trivial effort required for a one-time set-up procedure.


问:
Do We Have a Responsiblity to Improve Old Code?
I was looking over some old code that I wrote.  It works, but it's not great code.  I know more now than I did at the time, so I could improve it.  It's not a current project, but it's current, working, production code.  Do we have a responsibility to go back and improve code that we've written in the past, or is the correct attitude "if it ain't broke, don't fix it"?  My company sponsored a code review class a few years ago and one of the major takeaways was that sometimes it's just good enough; move on.

So, at some point should you just call it good enough and move on, or should you try to push projects to improve old code when you think it could be better?

答:
Unless you will be making changes to this "old code" to fix bugs or add features, I wouldn't bother improving it just for the sake of it. If you do want to eventually improve it, make sure you have unit tests in place that will test the code before you start refactoring it.

You can use the "old code" to learn better practices. If you do this, it's a part-time learning experience and you shouldn't expect that code to replace what's currently released or deployed by clients/customers.


答:
Not necessarily. However if you are performing code maintenance and happen to stumble upon something that could be better, you could change it provided you have the appropriate unit tests to make sure you didn't create a regression.

If no such tests exist and you can't be sure it will behave exactly how it should, you are better off leaving it alone.

Title: Do We Have a Responsiblity to Improve Old Code?

Body:
I was looking over some old code that I wrote.  It works, but it's not great code.  I know more now than I did at the time, so I could improve it.  It's not a current project, but it's current, working, production code.  Do we have a responsibility to go back and improve code that we've written in the past, or is the correct attitude "if it ain't broke, don't fix it"?  My company sponsored a code review class a few years ago and one of the major takeaways was that sometimes it's just good enough; move on.

So, at some point should you just call it good enough and move on, or should you try to push projects to improve old code when you think it could be better?


问:
What are some best practices for report writing?
I need to give a presentation to a coworker on some of the best practices regarding reports. Right now I use jaspersoft's iReport to do my reports and I need to give some input to a coworker. I'm looking for some general knowledge and insight on the topic.</p>

答:
Unlike the votes to close, I do think this is an excellent, answerable question.

The single most important thing in reporting is to understand your data and your data model. I mean really understand it, you need to be able to look at the results you get as you are developing and be able to tell if they are the right results. You need to know when you need to have a left join vice an inner join for instance (do you know if every table in your query has or should have a matching record in every other table it is joined to?) You need to know where to find the information and how to aggregate it correctly and what where conditions might be needed that are not obvious.

Report queries are often extremely complex and return or consolidate the results of many records, as a result the SQL you write for them must be far more performant than most people are used to writing. This is especially true in a report that will present all the data over a period of time. This report will grow and grow and grow in number of records returned and will get slower and slower to execute. Techniques like correlated subqueries which seem fine when you only have one month's data or test data will fail miserably when running 3 years worth of data (use CTEs or derived tables instead). Don't use them. Anyone writing reports needs to read  the chapter on queries in a performance tuning book for the database backend you are using. There are many techniques to avoid.

As far as the design of the report, usually you get told what filter items and what columns in the requirements.  There is no excuse for sending a report to testing that doesn't mactch the requirements. Sadly people do all the time.

One technique I use in developing the query is to start the final select (or the original select if I don't have some complex preprocessing stuff) with the requirements list. So first I write

```<code>SELECT
 [COLUMN 1 NAME]
 ,[COLUMN 2 NAME]
 ,[COLUMN 3 NAME]
FROM
</code>```

Then I comment out all the columns.

Then I start writing the joins and where conditions and add actual field names and calculations and uncomment them one at a time and check the data. So after the first field is working it might look like this:

```<code>SELECT
  t1.field1 as[COLUMN 1 NAME]
 --,[COLUMN 2 NAME]
 --,[COLUMN 3 NAME]
FROM table1 t1
WHERE t1.field3 = 'Yes'
</code>```

Then it might look like this:

```<code>SELECT
  t1.field1 as [COLUMN 1 NAME]
 ,coalesce(t2.field4, t1.field6) as [COLUMN 2 NAME]
 --,[COLUMN 3 NAME]
FROM table1 t1
JOIN table2 t2 on t1.table1id = t2.table1id
WHERE t1.field3 = 'Yes'
</code>```

And so on. If you do one chunk at a time and your final select starts with all the columns and their exact names per the requirement then you will find it easier both to build the report query and to debug it as you go. IN SQL server we also have the ability to use CTEs. I use them extensively in reporting so I can grab chunks of data and check that each chunk will have what I want before I put it all together.  Derived tables are also critical to reporting if you don't have CTEs available.

If I am getting incorrect data, I may need to see the whole record of each table to figure out what is causing it to return incorrectly. SO I also tend to add a commented out select * that I can use to see everything if I need to. Sort of like:

```<code>SELECT
  t1.field1 as [COLUMN 1 NAME]
 ,coalesce(t2.field4, t1.field6) as [COLUMN 2 NAME]
 --,[COLUMN 3 NAME]
--SELECT *
FROM table1 t1
JOIN table2 t2 on t1.table1id = t2.table1id
WHERE t1.field3 = 'Yes'
</code>```

To run the full query start highlighting from the second select on. Only do this on dev!

Body:
Unlike the votes to close, I do think this is an excellent, answerable question.

The single most important thing in reporting is to understand your data and your data model. I mean really understand it, you need to be able to look at the results you get as you are developing and be able to tell if they are the right results. You need to know when you need to have a left join vice an inner join for instance (do you know if every table in your query has or should have a matching record in every other table it is joined to?) You need to know where to find the information and how to aggregate it correctly and what where conditions might be needed that are not obvious.

Report queries are often extremely complex and return or consolidate the results of many records, as a result the SQL you write for them must be far more performant than most people are used to writing. This is especially true in a report that will present all the data over a period of time. This report will grow and grow and grow in number of records returned and will get slower and slower to execute. Techniques like correlated subqueries which seem fine when you only have one month's data or test data will fail miserably when running 3 years worth of data (use CTEs or derived tables instead). Don't use them. Anyone writing reports needs to read  the chapter on queries in a performance tuning book for the database backend you are using. There are many techniques to avoid.

As far as the design of the report, usually you get told what filter items and what columns in the requirements.  There is no excuse for sending a report to testing that doesn't mactch the requirements. Sadly people do all the time.

One technique I use in developing the query is to start the final select (or the original select if I don't have some complex preprocessing stuff) with the requirements list. So first I write

SELECT
 [COLUMN 1 NAME]
 ,[COLUMN 2 NAME]
 ,[COLUMN 3 NAME]
FROM

Then I comment out all the columns.

Then I start writing the joins and where conditions and add actual field names and calculations and uncomment them one at a time and check the data. So after the first field is working it might look like this:

SELECT
  t1.field1 as[COLUMN 1 NAME]
 --,[COLUMN 2 NAME]
 --,[COLUMN 3 NAME]
FROM table1 t1
WHERE t1.field3 = 'Yes'

Then it might look like this:

SELECT
  t1.field1 as [COLUMN 1 NAME]
 ,coalesce(t2.field4, t1.field6) as [COLUMN 2 NAME]
 --,[COLUMN 3 NAME]
FROM table1 t1
JOIN table2 t2 on t1.table1id = t2.table1id
WHERE t1.field3 = 'Yes'

And so on. If you do one chunk at a time and your final select starts with all the columns and their exact names per the requirement then you will find it easier both to build the report query and to debug it as you go. IN SQL server we also have the ability to use CTEs. I use them extensively in reporting so I can grab chunks of data and check that each chunk will have what I want before I put it all together.  Derived tables are also critical to reporting if you don't have CTEs available.

If I am getting incorrect data, I may need to see the whole record of each table to figure out what is causing it to return incorrectly. SO I also tend to add a commented out select * that I can use to see everything if I need to. Sort of like:

SELECT
  t1.field1 as [COLUMN 1 NAME]
 ,coalesce(t2.field4, t1.field6) as [COLUMN 2 NAME]
 --,[COLUMN 3 NAME]
--SELECT *
FROM table1 t1
JOIN table2 t2 on t1.table1id = t2.table1id
WHERE t1.field3 = 'Yes'

To run the full query start highlighting from the second select on. Only do this on dev!


答:
You can normally write code better the second time round, you learned more about the domain by writing it initially.

There isn't a simple answer for wether it's worth refracoring. Generally you shouldn't unless a) it's a good learning excerise for you or b) you would save time in the long run with better code. Remember every change risks bugs.

As a side note I would strongly advocate unit tests. It's very easy to muck up refracoring especially if you don't have current behavior clearly marked down with automated rests.


答:
From a engineer's perspective, sure I would very much like to work on old code until it can't be improve any more. But is there a business case for it? At the end of the day, the code is there to contribute to the bottom line, the profitability of your workplace. If it is not, just leave it.

There is a big caveat, if by improving the code, you are going to avoid a bug from occurring, (thinking the big Y2K balls up here..) I would definitely bring it up with someone higher up, maybe your business unit manager, and discuss the consequences of improving the code.


答:
Definitely don't improve it just for the sake of improving it. As others have said (and is common sense), we all get better (for some value of "better") as time goes on. That being said, reviewing code (either formally or informally) often illuminates these bits and pieces that we probably wish never saw the light of day again.

Although I don't believe we have a responsibility to go back and improve code that isn't fundamentally broken, insecure, or depends upon features on a deprecated/EOL list, here are some things I've done in the past in this situation:

Identify people on the team who really dig going back and improving code, as a sort of brain cleanse or nice, bite-sized task that gives a sense of accomplishment, and find time in the schedule for them to do it on a regular basis.  I've always had at least one of these sorts of folks on a team, and this approach can also boost morale (or at least the mood) if we're all in a lull or down period.

Use it as the basis for a learning exercise.  For interns, students, or new/junior members of the team, refactoring old code with guidance from senior members of the team gives them the opportunity to communicate with new team members, understand more about the system, and get in the habit of writing/updating unit tests and working with continuous integration.  It is important to note that this exercise is done with guidance, and clearly framed as an exercise to make the code better because it does not conform to current standards/norms.

So, no responsibility to fix it, but that old stuff can be really useful.  And unit tests and CI are your friends!


答:
As for me, the question can be rephrased and generalized: "Why should somebody spend additional resource (time, money, mental, etc.) if that concrete piece of code works fine now? Isn't it a waste of resource(s)?"

Every time I find a legacy code, I think about several things that seem to be important.

What for I'm going to make changes?

Will I need to support this code? How soon can it happen (near/far future)?

Is this code comfortable enough to work with? (Right now)

Can I be sure that all the changes which I do are safe? Different tests usually help to answer this question.

What consequences can I meet if I will make mistake(s) during code modification? Is it possible to revert my changes quickly? Will it be a waste of time?

...

Actually, you should ask yourself a lot of questions. There is no a full and final list of them. Only you and probably your teammates can find the answer.

P.S. I have noticed that I tend to rewrite the code very often, whereas my friend and teammate tend to leave it untouched. That's because we answer the mentioned questions differently. And I have to say that we answer them wrong very often... because we can't predict the future.


答:
Refactor the areas of code you need to modify most often.  Since you visit these areas frequently, refactoring will improve your understanding of the code and readability for when you have to visit them again, whereas there is no point to refactor code no one is ever going to look at again.

Moreover, if you only refactor areas of code when you need to modify them, it gives you a valid excuse if your refactoring causes a regression.  Of course, try to cover your refactorings with unit tests, but this is not always possible, especially with legacy code and you should expect big refactorings to create regressions every once in a while.

If you need to add features and your design is slowing you down or causing duplication then refactor.  When I design code I almost never predict exactly what changes will be needed in the future.  However, when I add new features, I usually end up refactoring the shared code.  By the time, I've added a third feature/refactoring cycle, my refactoring is already paying for itself and my shared code is fairly stable.

TLDR: refactor as needed, there is no obligation.


问:
How do you keep emails short but complete?
I'm the odd kind of developer that likes writing and explaining - emails, specs, you name it.  I enjoy helping people understand things deeply. I hate ping-pong communications where groups go through 30 or 40 emails, phone calls and meetings because 25% of the group misunderstood the previous dashed-off email in which the writer only half-explained their position, or was in a hurry and miswrote a critical word or left out a negative or two.

This trait is great for documentation, but my emails are long, so people simply don't read them. A couple strategies I've used are formatting long emails as attached Word documents to encourage people to view them as documentation (works surprisingly well sometimes), or trying to use more bullet points instead of free paragraphs. These strategies increase readership, but the content is still long.

Of course I want to yell and scream that complex technical topics require a lot of exposition and clarification, but that doesn't help anyone. Obviously there are tradeoffs that can be made, but I have a hard time justifying making statements that aren't clear or that will result in a million questions, misunderstandings, or added "terms and conditions" later on.

How do you keep your communications short but complete?

答:
Read Strunk & White's The Elements Of Style

I quote, "Vigorous writing is concise. A sentence should contain no unnecessary words, a paragraph no unnecessary sentences, for the same reason that a drawing should have no unnecessary lines and a machine no unnecessary parts. This requires not that the writer make all his sentences short, or that he avoid all detail and treat his subjects only in outline, but that every word tell."

My favorite line, "Omit needless words."

ContentLicense: CC BY-SA 2.5


问:
How big should OSGi bundles be?
Or more completely "What are the trade-offs and questions that should be raised when trying to decide the bundle structure of an OSGi application?"

Our existing OSGi bundles have tended to be quite fat: basically an API bundle and an implementation bundle, but with a lot of functionality. That has advantages in terms of project and build complexity, but maybe doesn't give us all the reusability and flexibility we desire.

So in a recent project, we intentionally made quite thin bundles. We did a walkthrough this AM and we wondered if we'd gone too far. In this quite-small service we had 7 bundles, several of which only had 1 domain class. The question raised was "This is almost like we're driving towards a bundle per package. But we have classes and packages already in the language, are we going too far with our bundle granularity?"

To make it concrete, this is a Web Service that performs a calculation on the aggregate results of other Web queries (specifically, we query a bunch of astronomical databases for objects in a given area and then we filter the results based on our own criteria and then we estimate a probability of an adequate observation based on the filtered results). We ended up with 7 bundles, which seems like a lot for what is essentially "a servlet that performs a calculation."

Is such very-fine granularity good (lots of flexibility at runtime) or bad (overly complicated)? How can we develop our intuition about the "just right" granularity of our OSGi bundles?

答: One of the biggest benefits of OSGi is that it creates really loose dependencies between your components or services. This lets you do hot deployment in production environments. If you view this as a key reason for using OSGi, then it makes sense to bundle packages that you think will need to change together. If it can be changed independent of the rest of the application, you should probably put it in its own bundle. The overhead of creating a new bundle is reasonably low, so you shouldn't worry too much about over-complicating your system with multiple bundles.</p>

Title: How big should OSGi bundles be?


问:
Sprint planning and accommodating slack
After reading Tom DeMarco's Slack, I'm wondering how to factor slack into sprints.

For those who haven't read the book, TDM describes 'slack' as providing time for innovation and other good things.

Scrum leans towards eliminating slack and resisting change within the sprint. Allowing stories to be re-prioritised between sprints. I appreciate the purpose of a sprint, and am not trying to ask how to respond to change within them.

My initial thought about adding slack to sprints would be to plan a sprint with 8/9 days of work for a two week sprint. If you're conscious of this decision, can still calculate your velocity accurately? Based on story points completed in your 8/9 day window (vs 10).

Conversely, these are two competing ideas and don't belong together... ?

gnat's focus factor link is interesting.

答: As someone who spent almost ten years studying manpower requirements, I can tell you that no one in any profession should ever be planned at 100% for direct work.  We used a figure of a little over 30 hours of direct work per week per person. You have to account for meetings, breaks, unavoidable delay (fire drills comes to mind as an example), non-direct tasks (things such as the developers being called to do a fix for someone else or filling out HR forms or moving your desk), and vacation, sick time, and other types of leave such as bereavement leave. The lack of consideration of this is one of the main reasons why most software projects miss the promised due dates (or make the date but with less functionality than orginally promised) whether using waterfall or Agile methods.</p>

Title: Sprint planning and accommodating slack


问:
What is a software maintenance retainer contract?
I'm a one man software start up and need to consider a software maintenance retainer contract for a client.

What is this, in simple terms? How could it benefit me or my client?

答:
A software maintenance retainer contract is an agreement between two parties to maintain a piece of software after its initial release.

As it's a retainer (and not a subscription), the client agrees to pay a certain amount up front for the purposes of handling any expenses that might occur in maintaining the software.

This benefits the client by having their bases covered—should bug fixes or security updates need to happen after release—without having to negotiate pricing or secure approval every time a change needs to be made to the software.

This benefits the developer in that they get the money up front and can specify the exact conditions under which a change counts as part of the agreement ahead of time.

A similar concept (but not exactly the same) is the Service Level Agreement (SLA) that Zsolt mentioned: SLAs are used for services that require a certain amount of up-time or availability (hence the name). As part of the negotiated price for the service, the developer/host/etc. guarantees a certain level of support, reliability, and availability.

When negotiating the retainer fee (or what type of SLA you can offer), you need to decide a few things:

What level of service you're willing to offer after the project is completed

How much time you think you'll need to spend on maintenance and support

From experience, it's also important to keep in mind that maintenance and support is not second-rate work: do not lower your rates just because it happens after the initial project is done. The main reason why maintenance would cost less to the client is that it takes up less time.


答:
This is a contract that you draw up between you and your client that lays out details such as:

Service Level Agreement - what level of service will you give to the customer in the event the software goes wrong, when can they get hold of you, how quickly you guarantee to acknowledge their problem (not fix yet), time frames for fixes.

Classifications of severity (spelling error in UI through to 'business is down')

Whether you'll provide point releases (or even major updates)

How much you'll charge them for this, and how often

Title: What is a software maintenance retainer contract?

Body:
I'm a one man software start up and need to consider a software maintenance retainer contract for a client.

What is this, in simple terms? How could it benefit me or my client?


答:
I believe that we have a responsibility to write the best possible code that we can today. That means using everything we have learned in the past and refusing to take short cuts in our design. If schedule pressures cause something to be cut, I don't believe the quality of our software should even be considered, that neat little animated paper clip, on the other hand...

Now if you are working and find that code you need to interact with is not written up to the level you are currently capable of writing, then it is reasonable to fix it IF you are able to do it in a controlled methodical manner. I personally have very minimal experience with this kind of Refactoring, like everyone (nearly everyone?) I tried the whole "lets just change everything and pray it works" and got bite by that bad enough. I'd suggest looking into Martin Fowler's discussions (either his book or one of many articles) on the matter. He seems to have inspired most of the current thought on the process.

Of course sometimes you may not be able to clean the code as you'd like. Joel Spolsky wrote an article on why you may want to devote a few weeks to simply Refactor your code. Read it here and yes it is a little old, but I think the information is still relevant.

I hope that helps


答:
What is this, in simple terms?

A maintenance retainer contract is a contract wherby the client pays the vendor an amount to cover support the software they bought. ie fixing any bugs that come up.
It sometimes but not always includes training.

```<code>How could it benefit me or my client?
</code>```

Client : They get a guarantee of software quality. If the software they bought is buggy or experiences major problems then its the vendor the fronts the cost of fixing them. The vendor thus has a vested interest in producing quality software. Its very like buying an insurance against any future bugs, they would pay more if nothing were to happen but if anything significant happens they wont be out of pocket. Its also very easy to budget for, all support will be covered by this one off cost rather than paying by hour.

Vendor (you) : you get a fixed regular wage. If your software is built well you will be getting a fairly large sum for a few trivial bug fixes. Its also generally very hard to make money from support, the clients feel cheated paying extra for the problems you created if your paying by hour. If the cost of bug fixes is covered by the retainer contract then the client is less likely to feel cheated.

Body:
What is this, in simple terms?

A maintenance retainer contract is a contract wherby the client pays the vendor an amount to cover support the software they bought. ie fixing any bugs that come up.
It sometimes but not always includes training.

How could it benefit me or my client?

Client : They get a guarantee of software quality. If the software they bought is buggy or experiences major problems then its the vendor the fronts the cost of fixing them. The vendor thus has a vested interest in producing quality software. Its very like buying an insurance against any future bugs, they would pay more if nothing were to happen but if anything significant happens they wont be out of pocket. Its also very easy to budget for, all support will be covered by this one off cost rather than paying by hour.

Vendor (you) : you get a fixed regular wage. If your software is built well you will be getting a fairly large sum for a few trivial bug fixes. Its also generally very hard to make money from support, the clients feel cheated paying extra for the problems you created if your paying by hour. If the cost of bug fixes is covered by the retainer contract then the client is less likely to feel cheated.


问:
Using PHP's ternary operator with only two arguments
I was recently reviewing some of my code and noticed that in a fit of absent-mindedness, I'd left a structure like the following:

```<code>$guid = empty($subscription->guid) ?  : $subscription->guid;
</code>```

Now, this wasn't doing what it's supposed to and is wrong, but since that property is always set now it was working fine, and there's no syntax error since 5.3 because of the following change:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

I wasn't aware of this change, and now I'm curious if I should be using it or not. This is something I was sorely missing from languages like ruby where you can do eg, a = b || c to get either b or c rather than a 'real' boolean. However, the syntax they've chosen for the ternary operator seems a little counter intuitive to me. Should I be using this in production code? It definitely threw myself when I saw it by accident.

答:
The ternary conditional operator without the second argument is a bit novel, but it is similar1 to the null-coalescing operator found in other Algol-derivative languages like C# and Perl, and as you mention, the || operator in Ruby (and JavaScript).

It looks weird at first, but it's not too out there (especially since there's precedent for similar operators in other languages), and can save a good deal of keystrokes. And, if what happened with the namespace delimiter (\) is any indication, weird syntaxes will eventually be adopted by the PHP community.

But one of the major problems PHP applications tend to face is the (sometimes) excruciatingly long lag time between release of a new version of PHP and when hosts start to support it. This leads to issues where you need to be backwards compatible with older versions of PHP, forgoing the use of convenience changes like this.

If that's not a concern to you, and your team agrees on its usage (or if you're a solo developer, if you're comfortable with it), by all means go for it. Like the namespace delimiter, I really think it's really going to be a matter of when, not if, it'll be acceptable in all future PHP projects.

Note 1: But not identical, given null-coalescing operators only test on non-null values (and not truthy values like PHP), and the ?: syntax doesn't suppress undefined notices as you mentioned in the comments.


问:
Is there a canonical book on requirements gathering?
Is there a book out there that's the de-facto standard for describing best practices, methodologies, and other helpful information on gathering requirements for software and database projects? What about that book makes it special?</p>

答:
In my answer to a related question, I quoted the book:

Managing Information Technology Projects: Applying Project Management Strategies to Software, Hardware, and Integration Initiatives by James Taylor, ISBN: 0814408117.

It is quite easy to read, IMO, and provides enough information about the requirements.

You also can read the chapter 11 of:

Project Management: A Systems Approach to Planning, Scheduling, and Controlling by Harold Kerzner, ISBN: 0471225770.

But it's not very detailed about the requirements, so I wouldn't recommend this as the only source or for people who are really interested in the subject.

Finally, you can read the chapter 3 of:

Advanced Project Management: A Complete Guide to the Key Processes, Models and Techniques by Alan D. Orr, ISBN: 0749440945.

It's much more detailed and explains requirements gathering, control systems, change control, etc.


答:
Software Requirements and More About Software Requirements: Thorny Issues and Practical Advice provide a solid coverage of requirements engineering in a manner that's generally independent of the development methodology used on the project.

There is now a third edition of Software Requirements that has not only been revised, but covers a chunk of the material in More About Software Requirements.

Software Requirements covers requirements from the perspective of both the customer as well as the requirements analyst. It contains discussions of elicitation, analysis, specification, validation, and management. It also includes information about product vision and scope, risk management, various requirements tools, and provides sample documents for different requirement related activities.

More About Software Requirements begins with a brief overview of many of the topics covered in Software Requirements. However, the focus is sightly more on the more agile approaches than the previous book, discussing the on-site customer, use cases, and determining the appropriate types of documentation needed to capture requirements.

Title: Is there a canonical book on requirements gathering?

Body: Is there a book out there that's the de-facto standard for describing best practices, methodologies, and other helpful information on gathering requirements for software and database projects? What about that book makes it special?</p>


答:
Everything you do has a cost.  You have limited time to program.  Everything you do in programming should be looked at against, "What's the benefit of doing this?" and "What's the benefit of doing something else?"

If you don't take into account the opportunity cost (What's the cost of doing something else?) then quality is free.  It's better to improve your code.  You'll learn something.  It'll run better.  It'll sell more.

The real question is what's the next best thing you could be doing with your time?  And then you have make trade-offs.

Will it sell more of the software?

Will it cause less headaches to support?

What will you learn?

Will it become more aesthetically pleasing?

Will it improve your reputation?

Ask these questions (and any others relevant to you) for this and other activities in your queue, and that'll help answer if it's worth fixing.  These trade-offs are why economics is important for programmers.  Joel said it before I did, and an old mentor said it to me even before Joel.

Or if you want a simpler answer, just stop watching TV until you've fixed the code.  :-)


答: I feel that refactoring / improving old code defines the programmer himself. Wanting to improve code that you wrote a year ago only shows your progress, and if it makes the application better and you have the ability, time, and approval to improve it, do it.</p>


答:
I think you should start by asking yourself the question that seems to have been missed. In what way is the code bad? And by this you are really asking yourself the following:

Does the code not do what it is supposed to do?

Is the code causing you problems when you are maintaining the software?

Is the code completely self-contained?

Do you have plans to update or replace the code at any time in the foreseeable future?

Is there a sound business case that you can make to update the code that has you concerned?

If there is one thing I've learned over the years, it's that you can't afford to second guess yourself after the fact.  Every time you solve a problem in code, you learn something and will probably see how your solution - or something similar - might have been a better solution to a problem you solved differently years ago. This is a good thing, because it shows you that you have learned from your experiences. The real question however is whether the code you wrote before is likely to become a legacy problem that gets more difficult to deal with over time.

What we are really talking about here is whether or not the code that bothers you is easy or difficult to maintain, and how costly that maintenance is likely to be as time passes. This is essentially a question about Technical Debt, and whether it is worth paying off that debt using a little surgical maintenance now, or whether the debt is small enough that you can let it slide for a little while.

These are questions that you really need to weigh up against your present and future work load, and should be discussed at length with your management and team in order to get a better understanding about where to invest your resources, and whether your old code is worth the time you may need to spend on it - if at all. If you can make a good business case for introducing change, then by all means do so, but if you are facing the urge to tinker with code because you feel embarrassed about the way in which you wrote it, then I suggest that there is no room for personal pride when it comes to maintaining old code. It either works, or it doesn't, and it is either easy to maintain, or costly to maintain, and it is never good or bad simply because today's experience was not available to you yesterday.


答:
Better/improved is a multi-axis comparison.  Do you think you can make it faster, smaller, more resource efficient, more readable, more useful information, more precise results, more flexible, more general, able to run on more systems, eliminate a dependency on a separate product?

Why should your company pay you to spend time rewriting this code, instead of writing new code or rewriting some other piece of code?

You should make improvements as opportunity presents itself, but opportunity means that you are either already working on the code, or you've indentified a business reason to make the change.

Pushing a change to production introduces a non-zero chance of breaking things (unit and functional testing only reduce this chance, they do not eliminate it), and should only be done when the expected benefit outweighs the risk.

Which is another point to consider -- do you INTEND to push this change to production, or simply to the development branch?  The bar for the two scenarios are completely different.  If it is only going in the development branch, and may never get into production, then opportunity basically means you're looking at the code for some reason, and it's not time consuming to do. It can be reviewed as required if a push should ever happen, and left out if it is considered unwarranted at that time. If on the other hand, it's going to production now, as I said above, you need to consider if this change is worth the cost: in terms of time spent making the push, and the benefits of using the new code.


问:
Is having C++ header files without extension a good practice?
I have an argument with a collegue of mine regarding the C++ guidelines to follow.

He currently designs all his libraries that way:

He uses inconsistently uppercase and lowercase letters in his filenames

Some of his headers don't have any extension

I believe that having no extension is something reserved for C++ standard files and that using uppercase letters is error prone (espcially when you deal with code which is meant to work on both Windows and Linux).

His point is that he follows Qt conventions (even for code that doesn't uses Qt) and keep saying : "If Qt does it that way, then it can't be bad."

Now I try to keep an open-mind, but I really feel bad when I have to work on/with his libraries. Is there a common established set of rules regarding this ? Does the standard tell something about it ?

Thank you very much.

答:
As I know, since 1998 standard, only standard library headers would be without the .h.
So non-standard C++ header files are conventionally still written with .h.
But bear in mind that it's a convention, you can use no extension or even .txt extension, it is like you write your classes starting with lower case, it's still working, but it's not the convention.</p>

OwnerDisplayName: ereOn

OwnerDisplayName: Mario A. Corchero Jiménez


答:
The extension (or lack of) isn't going to, as far as I know, cause you issues. I would say that dropping the extension altogether is inconvenient as it makes it difficult to search header files (for example with the wildcards *.h and *.hpp) and it makes it more difficult to identify the contents of a file (for example if your editor relies on the extension to choose the proper syntax highlighting mode).

From a code point of view it doesn't make much difference, even the casing is not problematic so long as you use a consistent case everywhere and don't rely on case differences alone to differentiate files. From a convenience point of view it's easier to stick to lower case and have an extension (either .h or .hpp).

More important that any of the above, however, is to pick one convention for your entire development team and stick to it. It is far worse to have to look up how a file is cased, named and what extension it uses whenever you want to include something - all of these should be "guessable" with knowledge of the thing you are trying to use.

Title: Is having C++ header files without extension a good practice?

Body:
I have an argument with a collegue of mine regarding the C++ guidelines to follow.

He currently designs all his libraries that way:

He uses inconsistently uppercase and lowercase letters in his filenames

Some of his headers don't have any extension

I believe that having no extension is something reserved for C++ standard files and that using uppercase letters is error prone (espcially when you deal with code which is meant to work on both Windows and Linux).

His point is that he follows Qt conventions (even for code that doesn't uses Qt) and keep saying : "If Qt does it that way, then it can't be bad."

Now I try to keep an open-mind, but I really feel bad when I have to work on/with his libraries. Is there a common established set of rules regarding this ? Does the standard tell something about it ?

Thank you very much.

OwnerDisplayName: Adam Bowen


答:
There is no rule (in the standard) that only standard header files can
be without an extension; the filename can be pretty much anything you
want.  General good practice, however, suggests that:

no files ever be without an extension, and

different types of files have different extensions—in
particular, C++ headers use a different extension (.hpp or .hh) than
headers that are acceptable to a C compiler.

(Regretfully, the second rule is often violated, and one often sees C++
header files with .h.  From personal experience, I can assure that
this will causes maintenance problems down the road, but it is common
practice.)

With regards to case, extreme care is required, since filenames are case
sensitive in some systems, and not in others.  I've seen two different
rules which work: either everything in lowercase in the filename, or the
filename follows exactly the same rules regarding case as for symbols in
C++.

In both cases, you establish rules for the project, by consensus, and
everyone follows them.

OwnerDisplayName: James Kanze


答:
These are conventions not rules there is no constraint to adhere to conventions,but conventions do make life easier when u come around for reference.

as per the extensions(.h,.hpp) those files which have been included in the c++ need not have extensions, u need to use the extensions if you are using headers from other than c++,like c libraries or boost libraries.

OwnerDisplayName: ken


答:
One good rule of thumb is that if it took you time to understand what the code is doing, and if this time could be reduced going forward by some well-chosen refactorings, then you are serving the needs of the business and of your team by taking these steps.

If the code does not benefit from your analysis, if the field names have not become expressive of the code intent and the methods have not been broken down into readable chunks, then the business has lost something of value: your state of comprehension.  With tools like Visual Studio and ReSharper, these kinds of refactoringss are safe, logic neutral, and of potentially great value in future developer productivity and confidence.

As Uncle Bob Martin says, "Always leave the campground cleaner than you found it."


答:
```<code>If Qt does it that way, then it can't be bad.
</code>```

Yes. Yes, it really, really can. Their library design is "We so badly want to be Java". It's a total mess. The Standard library is much better.

Also, fundamentally, it's a logical fallacy. Qt's design is only worth emulating if you can give logical arguments about why it's good, it's not good just because it's Qt.

Body:
If Qt does it that way, then it can't be bad.

Yes. Yes, it really, really can. Their library design is "We so badly want to be Java". It's a total mess. The Standard library is much better.

Also, fundamentally, it's a logical fallacy. Qt's design is only worth emulating if you can give logical arguments about why it's good, it's not good just because it's Qt.


问:
Recommendation for a database to query records with attributes that are arrays or hashes?
I'm building site with a very simple data structure: documents that are nodes that reference other nodes that each have arrays of parents, children and siblings, so the structure is:

```<code>Node:
uuid
name [string]
description [string]
children, parents, siblings [arrays of node uuids]
</code>```

What is most important is making the following query fast and easy: all nodes with uuid x in their children/parents/siblings array.

I'm considering using Riak or possibly Postgres with hstore, but would like other suggestions as to a good database designed to easily and quickly store and retrieve data with this structure.

Persistence is important, scalability is a secondary concern right now.

答:
You may find the ARRAY column type and associated operators help out here: you can efficiently index and query on array content, including contains and contained by operations.

PostgreSQL also features Common Table Expressions, which are an efficient and reasonably portable way to express a recursive query in a single SQL statement.

Finally, PostgreSQL has a native UUID data type that is efficient to store, index, and operate on.

Given your specified query, you should have something as simple as:

```<code>select uuid from node where ANY(children) = X OR ANY(parents) = X
</code>```

There are other ways to write that - array concatenation, or array containment operations, but that is probably the simples.  CTEs will allow you to extend that recursively if your tree structure query, as I anticipate, ends up needing to collect multiple levels in one operation.

In my testing both features performed well for search across a 15GB data set without substantial tuning, on an 8GB Mac laptop with slow spinning disk storage.  Given your statements, I would strongly advise PostgreSQL as the conservative choice.

Again, in our testing, Riak performs well and has solid tools, but you need a three physical machine cluster to really start to see basic performance.  Since you need much more persistence robustness than scalability, I think that will much less well fit your needs right now.

Body:
You may find the ARRAY column type and associated operators help out here: you can efficiently index and query on array content, including contains and contained by operations.

PostgreSQL also features Common Table Expressions, which are an efficient and reasonably portable way to express a recursive query in a single SQL statement.

Finally, PostgreSQL has a native UUID data type that is efficient to store, index, and operate on.

Given your specified query, you should have something as simple as:

select uuid from node where ANY(children) = X OR ANY(parents) = X

There are other ways to write that - array concatenation, or array containment operations, but that is probably the simples.  CTEs will allow you to extend that recursively if your tree structure query, as I anticipate, ends up needing to collect multiple levels in one operation.

In my testing both features performed well for search across a 15GB data set without substantial tuning, on an 8GB Mac laptop with slow spinning disk storage.  Given your statements, I would strongly advise PostgreSQL as the conservative choice.

Again, in our testing, Riak performs well and has solid tools, but you need a three physical machine cluster to really start to see basic performance.  Since you need much more persistence robustness than scalability, I think that will much less well fit your needs right now.


答:
First off all non-trivial applications have issues with ORM. They are great for CRUD operations but beyond that they just don't work. This isn't a unique problem to your situation. Don't let anyone tell you that you are doing something wrong by running up on the limits of whatever ORM you are using, they all suck at something, most of the times performance and flexibility.

SQL is just source code. Whether it is embedded in your application language, or stored in its own files, it is just source code that needs to be version managed just like any other source code asset.

The idea that separating this logic out and storing it somewhere else (stored procedures) is a panacea, is false, it just moves the problem to somewhere (and probably someone) else, which will cause more synchronization issues in the long run.

All software systems should strive for high cohesion ( sometimes referred to as locality ), this means in your case, put the logic closest to where it is used so it is easily found, managed and follows the Principle of Least Astonishment.

Even the act of putting it in its own file that is loaded as a external resource by the application can put an artificial level of indirection that can cause confusion and maintenance hassles.

Title: Logistically, how do you manage embedded SQL?

Body: My current application is running into issues with its ORM, and we're relying on some pretty hairy SQL to express queries that the ORM can't.  Are there best practices in terms of how to manage the SQL queries?  For example, where do these usually live in relation to other parts of the code?  Are they in separate .sql files, or do you edit them directly in your other source files?  If the latter, does your IDE (or editor) allow syntax highlighting?  Are there schemes for Vim or Eclipse which will perform SQL syntax highlighting given a set of tags (like #begin sql and #end sql, or something similar?)


问:
How can I organize fast and comfortable solution compilation in VS 2010?
Most of programmers who are involved into development of more or less large project(s) know how annoying the process of compilation can be. There are some other things which are dependent on compilation, for example unit tests. TDD requires tests to execute fast, otherwise developers tend to run them rarely.

The process of compilation of whole solution my team is working with takes about 5 minutes.  Our Visual Studio solution consists of many projects, so we usually don't have to recompile all of them. Normally, this 'partial' compilation requires about 2 minutes. It's easy to calculate that compiling the solution 10 times we lose 20+ minutes! The situation is even worse when we have to rebuild whole solution often. For this reason I unload a lot of projects manually very often but it scarcely helps.

1. How can we accelerate the process of compilation?

2. Can you recommend any Visual Studio [2010] extension which allows continuous background solution compilation?

答:
I use a ramdisk (40 MB) to speed up compilations.
Before starting Visual Studio, I launch a PowerShell script that replaces the bin/ and obj/ directories with junctions to the ramdisk.

```<code>param([Parameter(Mandatory=$true)][string] $folder)

function MoveToRamdisk($folder, $target){
    $folder.Delete($true);
    [IO.Directory]::CreateDirectory($target);
    cmd /c mklink /J $folder.FullName $target
}

function MoveRepositoryFolderToRamdisk($folder){
    $target = $folder.FullName.Replace('D:\Repositories\', 'E:\TempBinaries\');
    MoveToRamdisk $folder $target
}

dir $folder -Recurse -Include bin,obj | %{ MoveRepositoryFolderToRamdisk $_ }

MoveToRamdisk (Get-Item "${env:LocalAppData}\Microsoft\VisualStudio\10.0\ProjectAssemblies") 'E:\VsProjectAssemblies'
</code>```

Then create a link to:

```<code>%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe "C:\Path\To\InitializeDevelopmentRamDisk.ps1" "D:\Repositories\Solution1"
</code>```

I use DataRAM RamDisk, it's freeware and does not run background processes.

Body:
I use a ramdisk (40 MB) to speed up compilations.
Before starting Visual Studio, I launch a PowerShell script that replaces the bin/ and obj/ directories with junctions to the ramdisk.

param([Parameter(Mandatory=$true)][string] $folder)

function MoveToRamdisk($folder, $target){
    $folder.Delete($true);
    [IO.Directory]::CreateDirectory($target);
    cmd /c mklink /J $folder.FullName $target
}

function MoveRepositoryFolderToRamdisk($folder){
    $target = $folder.FullName.Replace('D:\Repositories\', 'E:\TempBinaries\');
    MoveToRamdisk $folder $target
}

dir $folder -Recurse -Include bin,obj | %{ MoveRepositoryFolderToRamdisk $_ }

MoveToRamdisk (Get-Item "${env:LocalAppData}\Microsoft\VisualStudio\10.0\ProjectAssemblies") 'E:\VsProjectAssemblies'

Then create a link to:

%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe "C:\Path\To\InitializeDevelopmentRamDisk.ps1" "D:\Repositories\Solution1"

I use DataRAM RamDisk, it's freeware and does not run background processes.


问:
Why is it so difficult to make C less prone to buffer overflows?
I'm doing a course in college, where one of the labs is to perform buffer overflow exploits on code they give us. This ranges from simple exploits like changing the return address for a function on a stack to return to a different function, all the way up to code that changes a programs register/memory state but then returns to the function that you called, meaning that the function you called is completely oblivious to the exploit.

I did some research into this, and these kinds of exploits are used pretty much everywhere even now, in things like running homebrew on the Wii, and the untethered jailbreak for iOS 4.3.1

My question is why is this problem so difficult to fix? It's obvious this is one major exploit used to hack hundreds of things, but seems like it would be pretty easy to fix by simply
truncating any input past the allowed length, and simply sanitizing all input that you take.

EDIT: Another perspective that I'd like answers to consider - why do the creators of C not fix these issues by reimplementing the libraries?

答: I think the real problem isn't that these kinds of bugs are hard to fix, but that they're so easy to make: If you use strcpy, sprintf and friends in the (seemingly) simplest way that can work, then you've probably opened the door for a buffer overflow. And nobody will notice it until someone exploits it (unless you have very good code reviews). Now add the fact that there are many mediocre programmers and that they're under time pressure most of the time - and you have a recipe for code that is so riddled with buffer overflows that it'll be hard to fix them all simply because there's so many of them and they're hiding so well.


问:
How to use BPMN and use case and other diagrams together
I asked this question on stackoverflow, but it seems this question is not suitable there, so I post here for discussion.

BPMN (Business Process Modeling Notations) is used for modeling business process by visualization, thus making intangible ideas become physically concrete through the expression of BPMN diagrams. The question is, how do I organize the BPMN with the UML.

Initially, I thought of two ways to organize use cases and business process diagram:

1 to one/many: By mapping each step (step here means each node in the BPMN digram) in the business process diagram with one or several use cases. Each use case is mapped with relevant several class diagrams/component diagrams (I prefer this one, since you can encapsulate a set of classes into one component which has input and output), several sequence diagrams (optional). After you have class diagrams/sequence diagrams, code is written/generated based on the model.

Many to one: By mapping several steps into one use case. The subsequence steps are the same.

Many to many: For example, one step in the business process can be mapped with two or more use cases, and the same two or more use cases can be mapped with other steps.

The above methods can be done by the modeling tool, and in my case, I use Enterprise Architect from Sparx System. I discover it recently and I am using its trial, but I will buy it in the future. I can organize many use case diagrams with one step of the BPMN diagram, and can click to view the necessary use cases. However, I don't if it supports many to many cases.

After thinking my own method for organizing BPMN and Use Cases, I searched the Internet, and found two other papers, each suggest the following method:

Turn each use case into each step of BPMN diagrams: To visualize how refined use cases fit into the business process. I like this approach, since the business process with steps can be modeled, and later each step is turned into a use case. One step is one use case.  This is the same with my one to one mapping above. Original presentation is here: Visualizing Use Case Sets as BPMN Processes

Each use case is exactly a business process: Each step in the use case is each step of the business process. Original paper is here: Describing Business Processes with Use Cases

It seems to me that there's not standardized way of gluing these artifacts (BPMN and Use Cases and other digrams) together. Maybe it's a management problem and rely more on creative usage rather than follow a formal steps. What are the usage of these diagrams together?

答:
What's not clear is whether you're talking about Use Cases or UML.

Use cases:

With regards to use cases: with BPMN, you use those to develop the BPMN. In fact, to some degree, BPMN is meant to replace some of the use cases. Use cases are typically used to illustrate the business process to the developer -- but in this case, the business analyst/use case writer can put a lot of that "description" into the BPMN.

What's left over is maybe some detail about the BPMN process, which analysts can add in a document. But again, in that document, it needs to be clear that the BPMN is what's being described (and not that the BPMN is an addition to the text).

(This also depends on whether or not the analyst or the developer is writing the BPMN: if the developer is writing the BPMN, then obviously you need the use cases to help the developer define the BPMN -- but that's a little weird. In an effective organization, the business analysts know how to and can write BPMN and the developers can help double-check it. BPMN is, to some degree, meant to free developers from writing business logic code and get analysts to "write" it.)

The only use cases that should be left over should be cases that describe situations that are not fully covered by the BPMN. For example:

Web page or UI interactions

Technical use cases involving multiple systems

web service descriptions, for example.

The whole purpose of BPMN is to remove the business logic from your application (code). Use cases which describe business logic are often used to build business logic into an application. In short, if you're using both, you need to make rules about which one is the defining definition. (Otherwise, we get possibly conflicting descriptions of the same process/logic...)

UML:

With regards to UML: the BPM engine becomes an actor. Similar to how use cases should be used, it's important to not describe the same thing in both your UML and your BPMN. Otherwise, you may have two slightly similar but conflicting descriptions of the same thing.


答: It's difficult to fix buffer overflows because C provides virtually no useful tools to address the problem. It's a fundamental language flaw that the native buffers provide no protection and it's virtually, if not completely, impossible to replace them with a superior product, like C++ did with std::vector and std::array, and it's hard even under debug mode to find buffer overflows.

Title: Why is it so difficult to make C less prone to buffer overflows?

Body:
I'm doing a course in college, where one of the labs is to perform buffer overflow exploits on code they give us. This ranges from simple exploits like changing the return address for a function on a stack to return to a different function, all the way up to code that changes a programs register/memory state but then returns to the function that you called, meaning that the function you called is completely oblivious to the exploit.

I did some research into this, and these kinds of exploits are used pretty much everywhere even now, in things like running homebrew on the Wii, and the untethered jailbreak for iOS 4.3.1

My question is why is this problem so difficult to fix? It's obvious this is one major exploit used to hack hundreds of things, but seems like it would be pretty easy to fix by simply
truncating any input past the allowed length, and simply sanitizing all input that you take.

EDIT: Another perspective that I'd like answers to consider - why do the creators of C not fix these issues by reimplementing the libraries?


答:
The problem is as much one of managerial shortsightedness than of programmer incompetence. Remember, a 90,000-line application needs only one insecure operation to be completely insecure. It is almost beyond the realms of possibility that any application written on top of fundamentally insecure string handling will be 100% perfect - which means that it will be insecure.

The problem is that the costs of being insecure are either not charged to the right addressee (the company selling the app will almost never have to refund the purchase price), or not clearly visible at the time decisions are made ("We have to ship in March no matter what!"). I'm fairly certain that if you factored long-term costs and costs to your users rather than to your company profit in, writing in C or related languages would be much more expensive, probably so expensive that it is clearly the wrong choice in many fields where nowadays conventional wisdom says that it is a  necessity. But that won't change unless much stricter software liability is introduced - which nobody in the industry wants.


答:
I would also recommend Mastering the Requirements Process by Suzanne Robertson.

It gives a thorough description of all stages and criteria of the process.


问:
Is JSF really ready to deliver high performance web applications?
I have heard a lot of good about JSF but as far as I know people also had lots of serious complains with this technology in the past, not aware of how much the situation has improved. We are considering JSF as a probable technology for a social network project. But we are not aware of the performance scores of JSF neither we could really come across any existing high performance website that had been using JSF. People complain about its performance scalability issues.

We are still not very sure if we are doing the right thing by choosing jsf, and thus would like to hear from you all about this and take your inputs into consideration.

Is it possible to configure JSF to satisfy the high performance needs of social networking service ? Also till what extent is it possible to survive with the current problems in JSF. What exactly are its problems ?

I am not  worried about the development complexities with JSF what others usually complain about because as per my personal experience I believe that's not at all true, but I am more concerned about what performance and scalability issues. And please don't just abuse it on its old issues linked to previous versions. I just care about the present state whatever had been its past.

答:
JSF is most definitely capable of delivering high performance web applications. The app I'm currently working on is completely in JSF and from the log stats I can see that many non-DB intensive pages have minimum execution times of 0ms and average times of less than 10ms.

Some of the Wicket guys have been saying things about JSF' performance, but according to this elaborate benchmark JSF actually performs better than Wicket: http://prezi.com/dr3on1qcajzw/www-world-wide-wait-devoxx-edition/

Notice that as long as the server isn't saturated, JSF also performs better than GWT. The GWT/JSF benchmark comparison is difficult though, since it's really important that the server for GWT also does the conversion and validation of data in the postback that JSF does. This is something you simply can't leave out in practice (never trust the client). Also, for the GWT vs JSF/Wicket graphs, it should be taken into account that the browser's rendering step is trivial for JSF/Wicket (since they mostly serve ready-to-render HTML), but the GWT client still has some work to do after receiving the server response.

One of the major performance/scalability issues that old JSF versions (prior to 2.0) had, was abusing state saving by putting way too much data in it. Things that absolutely should not have been there where put into it (like constants such as 'foo' as in <my:tag attribute="foo"/>).

JSF 2.0 introduced the partial state saving mechanism, which means only delta state is being saved. In practice this can be very little and reductions of two orders of magnitude compared to JSF 1.x are not uncommon.

After years of using JSF, I can say that except for saving too much state in JSF 1.x, I've never run into any performance issue that I could attribute to JSF. Any performance problems we ever had were always rooted in the DB and/or how we set up back-end services, wrote our queries, etc.


问:
Best practice/Patterns for two way data synchronisation
Quite often in my work the idea of 2-way data synchronisation between database systems crops up. The classic example is two slightly different CRM systems (say, Raiser's Edge and Salesforce) and the need to have a two-way sync of Contact data between them.

API considerations aside, assuming you have a shared key to sync on, and purely thinking of the algorithm/pattern to be employed, this is a task that is often underestimated by non-techies.

For example, you have to watch out for:

Can you easily detect which records have changed in both systems (or will you have to compare all records between the systems to detect changes)

If you're going for a once-every-N-hours sync, how to deal with conflicts where the same record changes at more-or-less the same time in both systems

If you're going for a real-time sync (ie an update in one system immediately triggers an update to the other system) how to handle divergence over time due to bugs or system crashes

Personally I can think of ways to tackle all this but I'm wondering if there are any well known patterns, literature or best practices that I could refer to.

答:
There are many theories about remote site DB synchronization. First start with INSERT. handling this one is easy - as you can create a unique ID for every site (for example an initial of the site name + ID (number): site_a_177 vs. site_b_53)

So insert should not create any conflicts. the problem is the update.
I don't believe that there's a 100% failure proof method, but you can start an update by "locking" the record in the remote DB, and only after you got the handle - continue with the update, and finish by syncing the update and only then release the lock.


问:
What are the best resources for learning about concurrency and multi-threaded applications?
I realised I have a massive knowledge gap when it comes to multi-threaded applications and concurrent programming. I've covered some basics in the past, but most of it seems to be gone from my mind, and it is definitely a field that I want, and need, to be more knowledgeable about.

What are the best resources for learning about building concurrent applications? I'm a very practical oriented person, so if said book contains concrete examples the better, but I'm open to suggestions. I personally prefer to work in pseudocode or C++, and a slant toward game development would be best, but not required.

答:
These are the books I have found useful lately:

Java Concurrency in Practice - by the author of much of Java's concurrency utils. Somewhat Java-specific, but very clear and informative about the dangers and pitfalls of threads.

The Art of Concurrency - not a scintillating theoretical treatise as the title suggests, in fact a rather folksy and down-to-earth compendium of useful advice and examples.

Programming Concurrency on the JVM - This one actually is a scintillating theoretical treatise, but very, very readable and insightful. If you need to know what STM or actors are, what their strengths and weaknesses are and why, this book will tell you.

There are many dedicated utility libraries such as the Intel Threading Building Blocks or Apple's Grand Central Station -  these generally have their own dedicated manuals, which are usually quite good, and anyway are mandatory reading if you want to do something big with them.


问:
Should SpecFlow be used with BDD as a solo developer?
I am a long time fan of TDD and after reading the RSpec book, would like to transistion to a BDD process. I like the idea of driving from the outside in, as it is presented in the book.

What I am having a hard time getting a handle on is how to structure the tests. I have tried SpecFlow, but it seems cumbersome to use when I am the only one really ever going to be looking at the tests. I like the idea of just using straight NUnit, rather then adding another framework, like it is presented here.

Is this a good way to try and structure BDD tests? Is there more information out there on comparing the two ways (that may even be more recent)?

答:
If you are looking at a BDD framework to use, you need to find one that you personally feel comfortable with, and which you feel adds value.  There are a number of options available for .NET, and each has several pro's and cons which you should weigh up to decide which framework provides you personally with the best balance between comfort, ease of use, and of course functionality.

I have used each of the following, and incidentally reviewed a few of them as a part of a blog entry only a couple of months ago:

StoryQ

SpecFlow

NBehave

NSpec

I believe that there are a few others floating around, but I was unable to locate links to them while I was writing this.

Like you, I found SpecFlow - and also a few others - a little cumbersome to either install or use.  I don't want to need to add additional products to support the BDD framework. I also don't like having to decorate my code with lot's of additional text or attributes which tend to add a lot of additional noise to the code. I wanted something that allowed me to simply represent my BDD test syntax in a natural flowing and easy to read manner within the code. After a lot of testing and a bit of a lengthy review process, I ended up settling on StoryQ, which I've been using for about a year now combined with NUnit and Moq.  It has a couple of minor limitations to do with support for anonymous delegates which works but messes up the output, and for me the API required a tiny bit of customization to improve the story/scenario syntax, which turned out to be an easy modification to a DSL template. The limitations however were far outweighed by the ease with which I found the framework could be used, and the active support by it's creators.

This is a choice that I made after careful consideration with regards to my needs and my own particular methodology. While I would happily recommend StoryQ to anyone, I am also mindful that your own methodology and needs may be different. However to answer your question, if you are like me and convinced that BDD is a better approach when writing software test-first, then yes, you should use an appropriate BDD framework.  Just make sure it is the right framework for you.

When structuring your tests, I have found two approaches that work reasonably well.  One is to make all of your BDD code exist within a separate class.  It's a nice way to keep your BDD code all together, and if needs be reusable, however it kind of messes with the free flow of text that makes the code really readable.  The other way which I have now settled on, has been to create a base test class with all of the really common stuff that I do, such as generalized Assertions, SUT instantiation, and other common things. All of my test units descend from this base, and simply add the Assignment, Action, and specialized Assertion statements needed to complete my tests.  In this way, I comfortably stick to the DRY principal, have elegantly readable test code, and I get to conform nicely with a comfortable AAA style of syntax. It works well for me, but I've needed to go through several iterations of code to get it right so to speak.


答:
It is simple to understand why the overflow problem isn't fixed. C was flawed in a couple of areas. At the time those flaws were seen as tolerable or even as a feature. Now decades later those flaws are un-fixable.

Some parts of the programming community doesn't want those holes plugged. Just look at all the flame wars that start over strings, arrays, pointers, garbage collection...


问:
Is there a pattern that will help with this data structure
I'm doing a java project. My main structure contains 2 lists with elements of type A the other type B. B itself contains a list of objects which may contain elements of A.

It must be that when an element from list of A is removed it must be removed from all subelements in list B. also if an possible member of list A is added to a B it should also be added to A. And also I need some way to find the parent objects containing an A.

So far I have a "working" implementation - using lots of loops. I am wondering - can you suggest patterns that will help me in this task?

more details.

I think my main issue is boils down to that i have objects A that have multiple parents. And when I add/remove from one parent I need to adjust some other parents.

I can't help but believe such a problem is solved already.

to clarify: I have a main List , and each B contains a List

When a A is removed from the main list it must be removed from all B. But not when it is removed from a B. It's essential that all A used in the application are present in the main list.

答:
for some strange reasone I cannot add comment under your question . So I am going to comment here . Please don't vote this down if you don't like it . I have no choice .

It seems this is very similar to problems in sql database. For example

```<code>create table A
(
    id int not null primary key,
    val varchar(20) not null
);

create table B (
    id int not null primary key,
    val varchar(20) not null
);

create table BA (
    b_id int not null ,
    a_id int not null,
    constraint ba_b_fk foreign key (b_id) references B(id),
    constraint ba_a_fk foreign key (a_id) references A(id) on delete CASCADE  ,
    constraint ba_pk primary key (b_id , a_id)
);

drop table ba;

insert a (id, val) values (1 , 'a1');
insert a (id, val) values (2 , 'a2');
insert a (id, val) values (3 , 'a3');
insert a (id, val) values (4 , 'a4');

insert b (id, val) values (1 , 'b1');
insert b (id, val) values (2 , 'b2');

insert ba (b_id , a_id) values (1 , 2);
insert ba (b_id , a_id) values (1 , 3);

delete a where a.id = 2

select * from ba;
--  only ( 1 , 3) left in ba
</code>```

I am not familiar with java ( but i do work in C# ) . Anyway some pseudo code here that might help . I ran out of time to implement it . ( please note that ATable , BTable are singletons )

```<code>class RecA {
    public int id;
    public string val;
    public override bool Equal(object x) { ... }
    public override int GetHashCode() { return ... }
}
class RecB {
    public int id;
    public string b_val;
    public HashSet<A> listA;

}
class ATable extends HashSet<RecA> {

}

class BTable extends HashSet<RecB> {

    public static Dictionary<A, List<B>> dict = new Dictionary<A, List<B>>() ; // to track relationship between BTable and ATable
    public override void Add(RecB) {
    }

    public void addA_to_BTable(RecA) {
        // use the dictionary to track it
    }

    public void delete_A(RecA) {
    }
}
</code>```

Body:
for some strange reasone I cannot add comment under your question . So I am going to comment here . Please don't vote this down if you don't like it . I have no choice .

It seems this is very similar to problems in sql database. For example

create table A
(
    id int not null primary key,
    val varchar(20) not null
);

create table B (
    id int not null primary key,
    val varchar(20) not null
);

create table BA (
    b_id int not null ,
    a_id int not null,
    constraint ba_b_fk foreign key (b_id) references B(id),
    constraint ba_a_fk foreign key (a_id) references A(id) on delete CASCADE  ,
    constraint ba_pk primary key (b_id , a_id)
);

drop table ba;

insert a (id, val) values (1 , 'a1');
insert a (id, val) values (2 , 'a2');
insert a (id, val) values (3 , 'a3');
insert a (id, val) values (4 , 'a4');

insert b (id, val) values (1 , 'b1');
insert b (id, val) values (2 , 'b2');

insert ba (b_id , a_id) values (1 , 2);
insert ba (b_id , a_id) values (1 , 3);

delete a where a.id = 2

select * from ba;
--  only ( 1 , 3) left in ba

I am not familiar with java ( but i do work in C# ) . Anyway some pseudo code here that might help . I ran out of time to implement it . ( please note that ATable , BTable are singletons )

class RecA {
    public int id;
    public string val;
    public override bool Equal(object x) { ... }
    public override int GetHashCode() { return ... }
}
class RecB {
    public int id;
    public string b_val;
    public HashSet<A> listA;

}
class ATable extends HashSet<RecA> {

}

class BTable extends HashSet<RecB> {

    public static Dictionary<A, List<B>> dict = new Dictionary<A, List<B>>() ; // to track relationship between BTable and ATable
    public override void Add(RecB) {
    }

    public void addA_to_BTable(RecA) {
        // use the dictionary to track it
    }

    public void delete_A(RecA) {
    }
}


答: You could do it with weak references. Wrap a List<WeakReference> and and the wrapper has a reference to the master data structure(thinking a set but not sure) that keeps the real references to each A. When you delete from a wrapped structure you remove the weak reference and delete from the set, which should be the only real reference to each A. This has some problems with working with the lists due to having the weed out the dead weak references.

Title: Is there a pattern that will help with this data structure

Body:
I'm doing a java project. My main structure contains 2 lists with elements of type A the other type B. B itself contains a list of objects which may contain elements of A.

It must be that when an element from list of A is removed it must be removed from all subelements in list B. also if an possible member of list A is added to a B it should also be added to A. And also I need some way to find the parent objects containing an A.

So far I have a "working" implementation - using lots of loops. I am wondering - can you suggest patterns that will help me in this task?

more details.

I think my main issue is boils down to that i have objects A that have multiple parents. And when I add/remove from one parent I need to adjust some other parents.

I can't help but believe such a problem is solved already.

to clarify: I have a main List , and each B contains a List

When a A is removed from the main list it must be removed from all B. But not when it is removed from a B. It's essential that all A used in the application are present in the main list.

Body: You could do it with weak references. Wrap a List<WeakReference<A>> and and the wrapper has a reference to the master data structure(thinking a set but not sure) that keeps the real references to each A. When you delete from a wrapped structure you remove the weak reference and delete from the set, which should be the only real reference to each A. This has some problems with working with the lists due to having the weed out the dead weak references.


答: If your main list contains only A's that are in some B's, you can compute the main list from the B's you have. (You can later think about caching the main list.)</p>


问:
How do programmers quit a job?
I'm thinking about leaving my current employer and wondering how one goes about that process in the programming world. We have a lot of projects on the go at the moment and I'm the only developer. We have 4-5 projects that are fairly big and need to be done in the next few months and even a few longer than that.

I'm leaving because I'm the only employee and that's doing me no good. I'm young and want to learn, so a team would be nice. It's also too much work and the company is managed horribly.

I have no contract to worry about so I could theoretically quit and just not come back without notice. Just wondering how this is normally handled.

Should I write a resignation letter

How much notice should I give

Should I give a reason for leaving

Should I go to my boss who is the main reason I'm leaving or go to his boss?

Overview of replies

From the feedback here, it looks as though it's best to give 2-4 weeks of notice, and present a written resignation. Don't go into detail explaining why you're leaving in most cases. Don't burn bridges. Be professional.

答:
I have quited from 3 jobs, not because they were bad (well one sort of was) but because I had better opportunities (first to go study abroad, then to work in my "dream" industry, third because the last company didnt keep its promises and wage was super low).

For the first two, I went with my manager and just said that even though I really liked it there I had a great opportunity that I couldn't let pass, that I appreciated them for having me for the time I lasted. In the first company they actually helped me out giving recommendation letters for the student visa.

In the second one, my manager did panicked a little bit since we were on a really really tight schedule and the deadline was soon, but she understood that I had to do it (eventually she was in the same situation, and also left).

In both occasions they asked me to write a letter, I think they even had the format, so I only had to put my name and sign it. In the second one I also had to go to some government office to declare I was voluntarily quitting (it needed to be done this way because it was a government sponsored project) .

In the last one, I was very dissapointed with the company and just told my boss all the things that I had been dissapointed with, and said that I really think I was not using my time adecuately, and that I had to quit. He seemed fine enough, though he did asked me to give more details about my reasons, once I did he seemed hurt by it, and then never talked to me again.

All in all, I say that giving 2 weeks
  notice is fine enough, if they find
  somebody in that time and want you to
  train him, its fine, but I wouldn't
  stay around until they find somebody.
  Just bring it forth to your manager,
  say you want to do other things and
  you are going to quit, after that, its
  either gonna be ok or they'll explode,
  if they do you I wouldnt stay the 2
  weeks.

Title: How do programmers quit a job?


答:
They did fix the libraries.

Any modern C standard library contains safer variants of strcpy, strcat, sprintf, and so on.

On C99 systems - which is most Unixes - you will find these with names like strncat and snprintf, the "n" indicating that it takes an argument that's the size of a buffer or a maximum number of elements to copy.

These functions can be used to handle many operations more securely, but in retrospect their usability is not great. For example some snprintf implementations don't guarantee the buffer is null-terminated. strncat takes a number of elements to copy, but many people mistakenly pass the size of the dest buffer.

On Windows, one often finds the strcat_s, sprintf_s, the "_s" suffix indicating "safe". These too have found their way into the C standard library in C11, and provide more control over what happens in the event of an overflow (truncation vs. assert for example).

Many vendors provide even more non-standard alternatives like asprintf in the GNU libc, which will allocate a buffer of the appropriate size automatically.

The idea that you can "just fix C" is a misunderstanding. Fixing C is not the problem - and has already been done. The problem is fixing decades of C code written by ignorant, tired, or hurried programmers, or code that has been ported from contexts where security didn't matter to contexts where security does. No changes to the standard library can fix this code, although migration to newer compilers and standard libraries can often help identify the problems automatically.


答:
I don't think you need any particularly complex pattern for this. Looping through the structures and doing the obvious changes should work (assuming you don't have any concurrency issues)

Some ideas to consider:

Make the List objects into a HashMap<A, Set>, where the key is an object of type A and the value is a set of all parent B objects.

Then you can easily find all parents of a given A, and if you remove an instance of A then you can quickly find all the B objects that you also need to remove the instance of A from.

You will of course need to update this structure whenever you add an A to a B, but this is only an O(1) operation.

The B objects should have a remove(A a) function which encapsulates all the code required to remove a given A instance from the internal data structure. This should recursively call a similar remove function in any substructures.

Body:
I don't think you need any particularly complex pattern for this. Looping through the structures and doing the obvious changes should work (assuming you don't have any concurrency issues)

Some ideas to consider:

Make the List<A> objects into a HashMap<A, Set<B>>, where the key is an object of type A and the value is a set of all parent B objects.

Then you can easily find all parents of a given A, and if you remove an instance of A then you can quickly find all the B objects that you also need to remove the instance of A from.

You will of course need to update this structure whenever you add an A to a B, but this is only an O(1) operation.

The B objects should have a remove(A a) function which encapsulates all the code required to remove a given A instance from the internal data structure. This should recursively call a similar remove function in any substructures.


问:
Do We Have a Responsiblity to Improve Old Code?
I was looking over some old code that I wrote.  It works, but it's not great code.  I know more now than I did at the time, so I could improve it.  It's not a current project, but it's current, working, production code.  Do we have a responsibility to go back and improve code that we've written in the past, or is the correct attitude "if it ain't broke, don't fix it"?  My company sponsored a code review class a few years ago and one of the major takeaways was that sometimes it's just good enough; move on.

So, at some point should you just call it good enough and move on, or should you try to push projects to improve old code when you think it could be better?

答:
This is a question to ask the management in your company.

Do you have the time and resources necessary to go back and make changes to old code?

Do you have the time and resources to have a QA team TEST what you've changed to make sure it's not broken?

I've fallen into this trap before where I would be in a module fixing a bug, and see code I or someone else wrote that was inefficient or inelegant, change it, and end up with more problems to deal with than if I just fixed the bug I was tasked to fix.


答:
Does Microsoft need to update windows?
Do all the *nix Distros have to keep evolving?
Or a more practical example does everyone still drive 1970's cars?</p>


问:
How to answer "When will it be done?"
We all have it, problems that prove difficult to fix and working out a fix through obscure code and bizarre unexpected functionality. Slowly, logically working your way through trying to find patterns, errors, mistakes. This process takes time and the issues are often not easily understood by the client.

How does one answer when asked the question "When will it be done?", especially when the client may not understand the inherent complexities of software development?

答:
You answer the question honestly.

You tell them it's a difficult problem, the solution is not obvious, and you are not sure how long it will take to resolve.  Promise to update them on your progress every [time frame], so they know you're working on it, and of course, actually send them the updates.

OwnerDisplayName: Emdiesse

Title: How to answer "When will it be done?"


答: To me, that looks like an error in the code.  It looks wrong, and in general, I avoid using syntax that looks like you've made an error for the sake of saving a few keystrokes.  When you (or someone else) goes back to read the code later, I think that line is going to trip you up and cause you to have to spend time parsing what it's doing, for what is essentially a simple operation.</p>

Title: Using PHP's ternary operator with only two arguments

Body:
I was recently reviewing some of my code and noticed that in a fit of absent-mindedness, I'd left a structure like the following:

```<code>$guid = empty($subscription->guid) ?  : $subscription->guid;
</code>```

Now, this wasn't doing what it's supposed to and is wrong, but since that property is always set now it was working fine, and there's no syntax error since 5.3 because of the following change:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

I wasn't aware of this change, and now I'm curious if I should be using it or not. This is something I was sorely missing from languages like ruby where you can do eg, a = b || c to get either b or c rather than a 'real' boolean. However, the syntax they've chosen for the ternary operator seems a little counter intuitive to me. Should I be using this in production code? It definitely threw myself when I saw it by accident.