答:
Practice I doubt the first 1000 lines of code anyone writes are very unique.

Expand your toolset Using a framework has more benefit when you understand what it is doing (Alost to the point you could do it yourself.) so you know how to apply it.

Understand the "Wheels" Using a poorly constructed and worn-out wheel or one that doesn't fit, is no excuse for blindly sticking to this rule-of-thumb. You may be short on time, funding, expertise, so you just patch it up and finish the trip.

There are few absolutes.


问:
How to set-up a simple subversion workflow
I am trying to set-up a simple SVN workflow at home. I am new to subversion (and programming) so I have been reading the official PDF documentations but still not sure about how to set-up my repository.

I am working mainly with python, bash and rsl (Renderman Shading Language)

So I already have a /dev structure on my disk as this:

http://imageshack.us/f/708/devstructure.png/

And I have a /site structure that links to my /dev folder:

http://imageshack.us/f/651/sitestructure.png/

So obviously starting to use SVN will change this approach that I already have in place.

The question is when I am setting-up my SVN repository for the work I do in my /dev folder:

Will I set-up a separate repository for each different programming platform?
and Where exactly I should be placing my repository?

Thanks.

答:
Where to put files, directory structure etc. doesn't have anything to do with version control systems. Whether you use svn or git, they all keep track of the files you want in some way.

If you want to learn about how to structure your files, directories etc, it's entirely a different question.

If you want to learn an efficent way to use version control systems, I suggest you to check this blog post, which describes a perfect workflow with git.

ContentLicense: CC BY-SA 3.0


问:
Is the phrase "never reinvent the wheel" suitable for students?
I find myself constantly running into this expression "don't reinvent the wheel" or "never reinvent the wheel" when I ask some questions on SO.  They tell you to use some frameworks or existing packages.  I know where this attitude is coming from since it's unwise to waste time on something others have already solved.  Or it that so?

As a student,  I find by using some code others wrote to solve my problem I can't learn as much as I'd like to, and I gain less insight.  And sometimes I think that phrase is mainly for working programmers facing deadlines and not for students like me.

Is it that bad to "reinvent the wheel"?  Maybe I'm thinking it wrong? Maybe there is a way I can avoid reinventing the wheel and at the same time learn a lot?

答:
I would say that it depends on whether you are reinventing to see how the wheel works or reinventing the wheel in the process of accomplishing some other task.  Certainly there are wheels that every student needs to implement at least once on their own.  You have to know how some elementary data structures and algorithms work in order to understand how they will affect the performance of your code or choose which ones to use in various circumstances.

Stacks, heaps, linked lists, trees, etc. are definitely worth the investment in time to implement once; then ever after use the ones provided by the framework. Everyone who uses a jQuery plugin ought to write at least one, but you don't have to write every different type of one that you will ever use. I'd say that it's helpful, but not necessary, to write a small process scheduler or mini-OS so you can understand what goes on under the hood on a computer.  You DO need to understand how processes, threads, etc. work, though.

Once you have a good working knowledge, it can also be important (and fun) to go back and implement new structures/algorithms to get a feel for them.  Unless it's your job or you're really good at it, I would stick with using the existing ones in your code.


问:
Can defect containment metrics be readily applied at an organizational level when there is only a consistant organizational process framework?
Defect containment metrics, such as total defect containment effectiveness (TDCE) and phase containment effectiveness (PCE), can be used to give a good indicator of the quality of the process. TDCE captures the defects that are captured at some point between requirements and the release of a product into the field, indicating the overall effectiveness of the entire process to find and remove defects. PCE provides more detail at each phase of the software development life cycle and how the defect detection and removal techniques are working.

Applying these metrics makes sense at a level where you have a well-defined process and methodology for product development, often a project. However, some organizations provide a process framework that is tailored at the project level. This process framework would include the necessary guidance for meeting certifications (ISO9001, CMMI), practices for incorporating known good techniques (agile methods, Lean, Six Sigma), and requirements for legal or regulatory reasons. However, the specific details of how to gather requirements, design the system, produce the software, conduct test, and release are left to the product development teams.

Is there any effective way to apply defect containment metrics at an organizational level when only a process framework exists at the organizational level? If not, what might be some ideas for metrics that can be distilled from each project (each using a tailored process that fits into the organizational process framework) that captures defect containment metrics to discuss the ability of the process to find and remove defects?

The end goal of such a metric would be to consolidate the defect containment practices of a large number of ongoing projects and report to management. The target audience would be people in roles such as the chief software engineer and the chief engineer (of all engineering disciplines) for the organization. Although project specific data would be available, the idea is to produce something that quantifies the general effectiveness of all tailored processes across all ongoing projects. I would suspect that this data would also be presented as part of CMMI, ISO, or similar audits to demonstrate process quality.

答:
IMHO opinion (downvote if you disagree) this is square peg, round hole.

Process frameworks specifically like Agile exist purely because process is not as important as people (See the Agile Manifesto).  That is not to say that metrics are not as important.  The important ones like Velocity for instance have to do with the rate of user story completion.  Defects should be associated with a user story and short lived, otherwise they simply should become yet another user story.  But I digress.

Metrics like TDCE and PCE don't make sense in process frameworks like Agile because Agile specifically runs counter to viewing software on the macro project level, especially bug resolution which inherently implies a rigid set of requirements before the development phase.

It is like trying to measure the Dustiness of Bacon.  Sure you could probably measure it if you tried, but why would you want to?

With that being said, a process framework encourages the development of a custom framework that specifically meets the project or organizational needs.  I don't see why a Mini-PCE metric couldn't be devised as long as you feel that it is relevant and beneficial to the organization, the product, and the customer.


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答:
Linking obviously GPL'd source code into a commercial, closed-source program.

Not only does it create an immediate legal problem, but in my experience, it usually indicates either carelessness or unconcern which is reflected elsewhere in the code as well.

ContentLicense: CC BY-SA 2.5


答:
Ignoring all biases towards one or another VCS, the layout of your dev directories should conform to what works best for you while working.  Then you map the version control to that.

One (lazy) pattern is just to host the VCS at the top level (/dev) and let everything be part of one big repo.  I don't like this, and it's probably a bad idea anyway.  Ties too much stuff together (and yay, this is how my office uses TFS).

A better idea is to split along either project lines or conceptual lines.  A conceptual split in your case would be to put all the bash projects into one repo.  Another similar idea is to put all projects related to one larger goal into a repo together.  A project split would be to put each individual project as its own repo.  I like the project split best myself, as I think this gives you the most granularity in maintaining the repo, and it keeps the history clean by only showing one project.  Obviously some VCS will favor different splits, and offer varying support for them.

In SVN in particular, it is very common to have something like:

```<code>/ProjectX (RepoRoot)
|
|--/trunk
|  |--/ProjectX
|--/branch
|  |--/ProjectX_401changes
|  |--/ProjectX_refactoring
|  |--/ProjectX_failedExperiment
|--/tag
|  |--/ProjectX_Release20120101
|  |--/ProjectX_Release20120411
</code>```

Again, most VCS programs will have their own ideas about how that actually looks, but pretty much all of them offer something like this conceptual divide.  They key is that not only is your code versioned through changes, but also release states.  Code can be the main line of development (Trunk), an offshoot to add complex new features or to experiment (a Branch), or a known good state that you should be able to easily get back to (a Tag).

Generally you'd host the "central" repo on another machine, but you can also just use another folder on your computer (but preferably on a different harddrive at the very least).  If you have multiple repos, then you'd probably roughly mirror your working pattern, but with the SVN structure above in each repo folder.  Note that in reality, the remote repo is often called "bare" or something similar because it doesn't actually have a copy of the real files exposed, it just hides everything inside the .svn folder (or .git, .bzr, etc).

Finally, using any VCS means learning the tools.  You can use a graphical tool if available, and they tend to make using VCS a lot more pleasant.  However, the command line tools are usually quite easy and will help you understand what VCS is actually doing.

You typically need 3 basic commands for daily work: download (get changes from repo), upload (put changes into the repo), and status (what changes do I have).  In SVN, these are:

```<code>svn update  (download)
svn commit (upload)
svn status (status)
</code>```

Other commands are less used, so you won't have to be as intimately familiar with them.  Typically the additional ones you need to get started are: add, create repo, and create local copy.  In SVN:

```<code>svn checkout (create local repo)
svn add (add files to the repo)
svn create (create a repository, ie on the server)
</code>```

Other VCS will have some extra commands you need to know.  Git, Mercurial, Bazaar, and other distributed systems usually have a distinction between local commit and remote commit. In most of them (git and bazaar as I recall, at the least) the command to locally commit is commit and the command to push your changes up to the remote system is push intuitively enough.  Pull is used to get changes instead of update.

Title: How to set-up a simple subversion workflow

Body:
I am trying to set-up a simple SVN workflow at home. I am new to subversion (and programming) so I have been reading the official PDF documentations but still not sure about how to set-up my repository.

I am working mainly with python, bash and rsl (Renderman Shading Language)

So I already have a /dev structure on my disk as this:

http://imageshack.us/f/708/devstructure.png/

And I have a /site structure that links to my /dev folder:

http://imageshack.us/f/651/sitestructure.png/

So obviously starting to use SVN will change this approach that I already have in place.

The question is when I am setting-up my SVN repository for the work I do in my /dev folder:

Will I set-up a separate repository for each different programming platform?
and Where exactly I should be placing my repository?

Thanks.

Body:
Ignoring all biases towards one or another VCS, the layout of your dev directories should conform to what works best for you while working.  Then you map the version control to that.

One (lazy) pattern is just to host the VCS at the top level (/dev) and let everything be part of one big repo.  I don't like this, and it's probably a bad idea anyway.  Ties too much stuff together (and yay, this is how my office uses TFS).

A better idea is to split along either project lines or conceptual lines.  A conceptual split in your case would be to put all the bash projects into one repo.  Another similar idea is to put all projects related to one larger goal into a repo together.  A project split would be to put each individual project as its own repo.  I like the project split best myself, as I think this gives you the most granularity in maintaining the repo, and it keeps the history clean by only showing one project.  Obviously some VCS will favor different splits, and offer varying support for them.

In SVN in particular, it is very common to have something like:

/ProjectX (RepoRoot)
|
|--/trunk
|  |--/ProjectX
|--/branch
|  |--/ProjectX_401changes
|  |--/ProjectX_refactoring
|  |--/ProjectX_failedExperiment
|--/tag
|  |--/ProjectX_Release20120101
|  |--/ProjectX_Release20120411

Again, most VCS programs will have their own ideas about how that actually looks, but pretty much all of them offer something like this conceptual divide.  They key is that not only is your code versioned through changes, but also release states.  Code can be the main line of development (Trunk), an offshoot to add complex new features or to experiment (a Branch), or a known good state that you should be able to easily get back to (a Tag).

Generally you'd host the "central" repo on another machine, but you can also just use another folder on your computer (but preferably on a different harddrive at the very least).  If you have multiple repos, then you'd probably roughly mirror your working pattern, but with the SVN structure above in each repo folder.  Note that in reality, the remote repo is often called "bare" or something similar because it doesn't actually have a copy of the real files exposed, it just hides everything inside the .svn folder (or .git, .bzr, etc).

Finally, using any VCS means learning the tools.  You can use a graphical tool if available, and they tend to make using VCS a lot more pleasant.  However, the command line tools are usually quite easy and will help you understand what VCS is actually doing.

You typically need 3 basic commands for daily work: download (get changes from repo), upload (put changes into the repo), and status (what changes do I have).  In SVN, these are:

svn update  (download)
svn commit (upload)
svn status (status)

Other commands are less used, so you won't have to be as intimately familiar with them.  Typically the additional ones you need to get started are: add, create repo, and create local copy.  In SVN:

svn checkout (create local repo)
svn add (add files to the repo)
svn create (create a repository, ie on the server)

Other VCS will have some extra commands you need to know.  Git, Mercurial, Bazaar, and other distributed systems usually have a distinction between local commit and remote commit. In most of them (git and bazaar as I recall, at the least) the command to locally commit is commit and the command to push your changes up to the remote system is push intuitively enough.  Pull is used to get changes instead of update.


问:
Why is it called a 'Here Document'?
(Let me know if this is the wrong SE for this)

Why is a Here Document (or Heredoc) called that? Wikipedia didn't have anything to say on that particular subject. I did find unix docs describing a "Here is document", is that the original form?

答:
Well, the document is right here. Here it is. It's a logical name for the thing, yeah?

When people speak of 'here documents' they are generally speaking of a unit of data that is embedded into code. That data will be displayed to a user or used to compose a request to a server or to write information to a log or to update a configuration file, or, or, or,or... It's a mistake to overload the name with meanings and connotations. It's a programming technique and it has a name.

Title: Why is it called a 'Here Document'?


问:
Should I store "system b" password in "system a"?
I am developing a system for mailing which has a account id/password to login and I need to store the smtp server account and password for sending mail. Since the mail is auto send I can't request the user input password/id each time when sending.

Therefore, is storing the user account id/password (system b password) in my system (system a) insecure design? How can I improve this?

答:
I don't know in which language/platform you are developing your applications, but for .NET you can take advantage of encrypting and decrypting configuration sections.
To my knowledge these sections are meant to store sensitive data, like passwords. You can also place other date, like SMTP server, account, etc. in it.

I'm pretty sure other languages have similar protection mechanisms.

One thing I saw for the Orchard CMS installations, the username and password for databases are stored (in plain text) in the App_Data folder. Users can't really access these folders, so it's rather safe, but if your server/web application gets hacked, one could easily gain access in the database.

If you want to be sure, encrypt the information, but make sure you can decrypt it in your application.


答:
Consolidation of defect management sounds like a good idea unless the projects are so orthogonal as to require separate defect managing systems.  For instance, a solo developer doing his own testing could get by with bullet list, while a distributed organization with customers reporting bugs to a support team requires a much more heavy-weight process.  This is obvious, but it is important to consider how your consolidation will effect all the developers involved and whether they will be motivated to buy into it.

The problem with bug metrics is if developers feel that bug counts are a way of measuring their performance, then they may get fudge numbers (grouping multiple bugs into one, underestimating bug impact, saying they caught the bug further upstream).  This is especially a risk if you present the reports to management.  Even you get support from all the developers there can be large variances simply from how they individually report bugs.

Defect containment metics, in particular seem to hold the assumption of an exponentially increasing cost curve downstream.  While this may be the case, agilists make a convincing arguments for changing the cost-curve rather than stopping defects as early as possible.  I would be skeptical of any metric that assumes a fixed cost-curve, since each project and type of bug may have a dramatically different cost-curves.

If it is dramatically more expensive to catch a bug downstream, then lowering the cost curve by adopting better tools, adopting continuous integration, automated testing, or other agile practices may be a better solution.  Of course, in some projects there may be large unavoidable downstream costs (e.g. space shuttle code) in which case defect containment metrics make more sense.

Otherwise, useful 'metrics' in my opinion are categorizing bugs by type to help analyze any systemic flaws.  Tracking where the bug was caught (development, integration, or in the field) is also important for analysis, but as I said before I would be hesitant in plugging them into a fixed cost curve to get a single number.  Instead cost to fix bug can be estimated by tracking the hours a developer spends on it using a tool such as Mylyn, although this requires some discipline on the developer's part.

Title: Can defect containment metrics be readily applied at an organizational level when there is only a consistant organizational process framework?

Body:
Defect containment metrics, such as total defect containment effectiveness (TDCE) and phase containment effectiveness (PCE), can be used to give a good indicator of the quality of the process. TDCE captures the defects that are captured at some point between requirements and the release of a product into the field, indicating the overall effectiveness of the entire process to find and remove defects. PCE provides more detail at each phase of the software development life cycle and how the defect detection and removal techniques are working.

Applying these metrics makes sense at a level where you have a well-defined process and methodology for product development, often a project. However, some organizations provide a process framework that is tailored at the project level. This process framework would include the necessary guidance for meeting certifications (ISO9001, CMMI), practices for incorporating known good techniques (agile methods, Lean, Six Sigma), and requirements for legal or regulatory reasons. However, the specific details of how to gather requirements, design the system, produce the software, conduct test, and release are left to the product development teams.

Is there any effective way to apply defect containment metrics at an organizational level when only a process framework exists at the organizational level? If not, what might be some ideas for metrics that can be distilled from each project (each using a tailored process that fits into the organizational process framework) that captures defect containment metrics to discuss the ability of the process to find and remove defects?

The end goal of such a metric would be to consolidate the defect containment practices of a large number of ongoing projects and report to management. The target audience would be people in roles such as the chief software engineer and the chief engineer (of all engineering disciplines) for the organization. Although project specific data would be available, the idea is to produce something that quantifies the general effectiveness of all tailored processes across all ongoing projects. I would suspect that this data would also be presented as part of CMMI, ISO, or similar audits to demonstrate process quality.


问:
Biggest mistake you've ever made
Similar to the question I read on Server Fault, what is the biggest mistake you've ever made in an IT related position. Some examples from friends:

I needed to do some work on a production site so I decided to copy over the live database to the beta site. Pretty standard, but when I went to the beta site it was still pulling out-of-date info. OOPS! I had copied the beta database over to the live site! Thank god for backups.

And for me, I created a form for an event that was to be held during a specific time range. Participants would fill out the form for a chance to win, and we would send the event organizers a CSV from the database. I went into the database, and found ONLY 1 ENTRY, MINE. Upon investigating, it appears as though I forgot an auto increment key, and because of the server setup there was no way to recover the lost data.

I am aware this question is similar to ones on Stack Overflow but the ones I found seemed to receive generic answers instead of actual stories :)

What is the biggest coding error/mistake ever…

答:
Allowed my manager to brow beat me into leaving a job I loved. I should have let him mess things up, get fired and then I should have stepped up and clean up the pieces.
Instead I quit and have regretted it ever since.</p>

Title: Biggest mistake you've ever made


问:
SDLC approach for small size projects
For small size projects, is it worth following the SDLC? is SCRUM/agile development a better approach?

Edit: The project I have in mind is a small change but it will affect multiple layers/parts of the application, so there will be 2 or 3 developers involved each from a different team, then the code will be integrated at a later step.

Thanks.

答:
Agile processes work for small projects very well. We have been doing it for last 2 years on projects which lasts between 2-4 months.

The good thing about agile development is that you don't see much difference between big and small projects as most of our concentration is on the specific "sprint"s that we are currently working on.

Do not go ahead without following any SDLC processes!! You never know when your "small" project will become "big" :) I have seen many projects which start small but does not end as "small".

One of the artcle that I read was saying agile development was first thought to be good for small projects only and then moved on to big projects.

link

Title: SDLC approach for small size projects

ContentLicense: CC BY-SA 4.0


问:
Array or Malloc?
I'm using the following code in my application, and it's working fine. But I'm wondering if it's better to make it with malloc or to leave it as is?</p>

```<code>function (int len)
{
char result [len] = some chars;
send result over network
}
</code>```

答:
Something that nobody has mentioned yet is that the variable length array option is probably going to be vastly faster than malloc/free since allocating a VLA is just a case of adjusting the stack pointer (in GCC at least).  </p>

<p>So, if this function is one that is called frequently (which you will, of course, determine by profiling), the VLA is a good optimisation option.  </p>

Title: Array or Malloc?

Body:
Something that nobody has mentioned yet is that the variable length array option is probably going to be vastly faster than malloc/free since allocating a VLA is just a case of adjusting the stack pointer (in GCC at least).

So, if this function is one that is called frequently (which you will, of course, determine by profiling), the VLA is a good optimisation option.


答: If you don't have a set deadline for your project, IMO, it is better to reinvent the wheel. If you don't have a job, or are just looking to learn to program, not to make money programming, what is the point of using shortcuts that will not make you a better programmer, ones that will merely get your project done faster? Although this is true, it is definitely a good skill to know how to use libraries, frameworks, and other people's code.

Title: Is the phrase "never reinvent the wheel" suitable for students?

Body:
I find myself constantly running into this expression "don't reinvent the wheel" or "never reinvent the wheel" when I ask some questions on SO.  They tell you to use some frameworks or existing packages.  I know where this attitude is coming from since it's unwise to waste time on something others have already solved.  Or it that so?

As a student,  I find by using some code others wrote to solve my problem I can't learn as much as I'd like to, and I gain less insight.  And sometimes I think that phrase is mainly for working programmers facing deadlines and not for students like me.

Is it that bad to "reinvent the wheel"?  Maybe I'm thinking it wrong? Maybe there is a way I can avoid reinventing the wheel and at the same time learn a lot?


答:
SDLC stands for "software development life cycle" or sometimes "system development life cycle," and it refers to the process that you follow for developing your product. There's no single SDLC process that everyone follows -- you're free to define your own, and to change it as the project (or your organization) grows. The point is to have a defined process, preferably one that's written down, that you follow for the work related to development and maintenance of your project. The alternative is to work by the seat of your pants, making things up as you go along.

So, if you want to use Scrum or some other "agile" methodology in your process, that's perfectly fine. Just write it into your SDLC and you're good to go.

Title: SDLC approach for small size projects

Body:
For small size projects, is it worth following the SDLC? is SCRUM/agile development a better approach?

Edit: The project I have in mind is a small change but it will affect multiple layers/parts of the application, so there will be 2 or 3 developers involved each from a different team, then the code will be integrated at a later step.

Thanks.


问:
Is Tax Localization a good use for Workflow Foundation?
Scenario: We have both Winforms and MVC code that is being used to work on a nation wide multi-user platform that does lots of logistics for lots of users. Tax rules change per state and even per city or county. These tax rules make a huge difference for our industry.

The other issue is that rules can change based on legislation. The system will have to handle cases where before a date it works one way and then different after that date. This changeover will need to be entered into the system and tested before that date comes.

Proposed Solution: Use Workflow Foundation to create a time based system where our users can change and add rules that change the way taxes are calculated.

Question: I have not used Workflow Foundation and searching has returned books to look at but not a lot of examples of people using this technology successfully. Is my scenario a good use of Workflow Foundation?(I think so.) If you have any experience with Workflow Foundation, any tips on making this work well?

答: This sounds more like a rules management and implementation problem than a workflow management problem.  I'd consider using a BRMS (Business Rules Management System), which vary in weight and complexity.  SRE is a fairly lightweight open source rules engine that folks like. </p>


答: Sometime before when coding the JS, I was not able to distinguish between "1" (one) and "l"  "small L". Even when I was typing this answer both looks almost same in editor! </p>

Title: Biggest mistake you've ever made

Body:
Similar to the question I read on Server Fault, what is the biggest mistake you've ever made in an IT related position. Some examples from friends:

I needed to do some work on a production site so I decided to copy over the live database to the beta site. Pretty standard, but when I went to the beta site it was still pulling out-of-date info. OOPS! I had copied the beta database over to the live site! Thank god for backups.

And for me, I created a form for an event that was to be held during a specific time range. Participants would fill out the form for a chance to win, and we would send the event organizers a CSV from the database. I went into the database, and found ONLY 1 ENTRY, MINE. Upon investigating, it appears as though I forgot an auto increment key, and because of the server setup there was no way to recover the lost data.

I am aware this question is similar to ones on Stack Overflow but the ones I found seemed to receive generic answers instead of actual stories :)

What is the biggest coding error/mistake ever…


问:
planning the same app for both OSX and iOS
I would like to ask which is the best strategy for creating an application that will be developed both on Mac and iPad, so to make minumum effort to port it from one platform to the other, starting from iPad, for example, but rather trying to make both at the same time. The application, in fact, would be an iPad-style one on the Mac too. How should I have to plan the project? Which are the main tricks to easily get the goal?</p>

答:
You'll have to recode the UI no matter what.  The OS X UI is different enough to the iOS UI to mean that any lesser attempt at porting the UI direct (such as the one mentioned by Chiron) is going to result in a less than perfect compromise.

For instance:

OS X users expect there to be a set of menus on the menu bar through which you can access most of the functionality.  There's no direct equivalent on iOS.

OS X users expect resizeable windows.

OS X users expect to be able to open multiple document windows (if your app is a document based app).

Many iOS style controls simply do not work well if your input device is a mouse.

Some of the OS X style controls have richer functionality while also being easier for the programmer to use than their iOS "equivalents" (compare NSTableView with UITableView).

So, given that you need to redesign your UI, you need to separate the functionality from the UI as much as possible.  This is somewhat encouraged in MVC anyway.  However, one way to enforce this is to physically separate the model (the M part) by compiling it as a static library on iOS and a framework on Mac OS X.  Careful design of the controllers (the C part) using maybe protocols or delegates might allow you to reuse some code there too.

Anyway, the one thing you should never do (this applies to any app on any platform) is compromise the UI in the name of portability.


答:
Just like WPF, Workflow Foundation has a pretty steep learning curve to become proficient with it. That being said it is a very powerful framework albeit with a few quirks. Depending on your time frame for delivery, there are alternatives for embedding a simple rules engine into your application.

One option, which I had moderate success with is to create your own rules engine that is based on conditions and results. Basically, we had a logistics application that needed to apply different tariffs (rates), mileage calculations, and delivery times (among other calculations) based on different conditions such as origin/destination of the shipment, who the customer was, who the shipper was, what kinds of materials were being shipped, etc.

I created a "contract" system that allowed users to enter conditions and map them to various terms. So for example a shipment for customer A originating from Chicago destined for Texas would have a five day delivery deadline. When a user entered a new shipment, the system would match the shipment against the terms and apply the specified conditions automatically to the shipment.

Your system appears to have the same problem. Taxes can be applied to shipments (I'm assuming that's what you're handling because you mentioned logistics) based on origin, destination, and date. You can preload new tax rules and they would match when they apply. It's all data driven, so you wouldn't have to re-deploy to accommodate new tax rules.

Hope this helps.

Title: Is Tax Localization a good use for Workflow Foundation?

Body:
Scenario: We have both Winforms and MVC code that is being used to work on a nation wide multi-user platform that does lots of logistics for lots of users. Tax rules change per state and even per city or county. These tax rules make a huge difference for our industry.

The other issue is that rules can change based on legislation. The system will have to handle cases where before a date it works one way and then different after that date. This changeover will need to be entered into the system and tested before that date comes.

Proposed Solution: Use Workflow Foundation to create a time based system where our users can change and add rules that change the way taxes are calculated.

Question: I have not used Workflow Foundation and searching has returned books to look at but not a lot of examples of people using this technology successfully. Is my scenario a good use of Workflow Foundation?(I think so.) If you have any experience with Workflow Foundation, any tips on making this work well?


问:
Optimum Number of Parallel Processes
I just finished coding a (basic) ray tracer in C# for fun and for the learning experience. Now I want to further that learning experience. It seems to me that ray tracing is a prime candidate for parallel processing, which is something I have very little experience in. My question is this: how do I know the optimum number of concurrent processes to run?

My first instinct tells me: it depends on how many cores my processor has, but like I said I'm new to this and I may be neglecting something.

答:
The .NET framework has a built-in setting that optimizes the number of concurrent threads if you use the ThreadPool directly or the more convenient Task Parallel Library API. I believe it is something like 20 per logical core (but I don't see that in the documentation anymore). If you want to control your threads directly, you can still call the ThreadPool's GetMaxThreads function to see what the framework recommends. For a really neat demo of leveraging the features of C#, check out this raytracer implemented using LINQ

Updating for new information According to the current documentation

Beginning with the .NET Framework 4, the default size of the thread pool for a process depends on several factors, such as the size of the virtual address space. A process can call the GetMaxThreads method to determine the number of threads. The number of threads in the thread pool can be changed by using the SetMaxThreads method. Each thread uses the default stack size and runs at the default priority.

Of course the important thing is to recognize that for a CPU bound operation, theoretically there should be one thread per core. But also recognize that your application (without explicitly setting thread priority) will have to share time on the core with other processes. Meaning, optimal threading depends on a number of factors. By default, I'd let the system manage threading for me. The Task Parallel Library is the best route for that currently.

Title: Optimum Number of Parallel Processes


答:
Not sure it was my "biggest mistake", but definitely a memorable one. In my first week or two at a new job, I was assigned to do a small "feature enhancement" that involved modifying the sort order of some items on one of the most popular pages on the site. I wasn't too familiar with the code base, but quickly found the relevant Comparator and added calls to a couple harmless-looking methods inside the compareTo method without thinking too much about it. The code tested locally and in QA w/o issues and went live.

I had a 1 on 1 with my boss that same day and with a big smile on his face, he congratulated me on getting my first "feature" live so soon after joining. We both looked on as he visited the corresponding page to see the feature in action. The page took 47 seconds to load. My heart sank. He refreshed the page: 53 seconds. His smile vanished. I went back to my desk and spent a long evening debugging and pushing critical patches to the live site.

It turns out one of the harmless looking methods I added was a remote service call that resulted in at least one DB hit. In each compareTo call. So on a page where 2,000+ items were being sorted, I was making ~6000 (nlogn) DB hits. Ouch.

Title: Biggest mistake you've ever made


答: The maximum improvement one could achieve is described by Amdahl's law. How parallelizable your application can become is a combination of the task and algorithms used. To determine the optimal number of processor cores will involve measuring performance and probably simulation. </p>

Title: Optimum Number of Parallel Processes

Body:
I just finished coding a (basic) ray tracer in C# for fun and for the learning experience. Now I want to further that learning experience. It seems to me that ray tracing is a prime candidate for parallel processing, which is something I have very little experience in. My question is this: how do I know the optimum number of concurrent processes to run?

My first instinct tells me: it depends on how many cores my processor has, but like I said I'm new to this and I may be neglecting something.


问:
Form Follows Function in Programming?
Does the saying, "form follows function" hold true in programming or language-design? Why or why not?

答:
It does, in that the way a program is organized will be determined by the functionality required.

With that being said, "form follows function" says nothing about the quality of the form.  Only that the requirements of the functionality play a major part of the form of the design.

Title: Form Follows Function in Programming?


问:
Database Table Prefixes
We're having a few discussions at work around the naming of our database tables. We're working on a large application with approx 100 database tables (ok, so it isn't that large), most of which can be categorized in to different functional area, and we're trying to work out the best way of naming/organizing these within an Oracle database.

The three current options are:

Create the different functional areas in separate schemas.

Create everything in the same schema but prefix the tables with the functional area

Create everything in the same schema with no prefixes

We have various pro's and con's around each one but I'd be interested to hear everyone's opinions on what the best solution is.

Edit: Thanks for all the answers.  It's hard to pick a right answer seems it is very subjective so I'll go for the one with the most votes (it helps that it matches what I was thinking! ;-)

答:
Creating everything in separate schemas is what makes the most sense, IMO. It provides a logical separation, and also will allow you to easily organize what you are doing.

If your application grows, it will become easier to replicate data over to separate read servers as well, since you could split out to have one or more read servers per-schema. It will be much easier to track that way.

Title: Database Table Prefixes


问:
Understanding the problem when things break in production
Scenario:

You push to production

The push broke multiple things

That same build did not break qa or dev

As a developer, you don't have prod access.

There is lots of pressure from above to get things working agian.

Specifics:

PHP/MVC application that is API-driven in Zend.

Deployed to a few servers.

My question:

While investigating, lets say I have a hunch that something is wrong.  But, I don't know for sure.  And, of course, I can't test things in production.  If I have a suggested fix based on that hunch, would it be wise to try and apply it and see if it works, before understanding what the problem is?

答:
How well do you understand the problem? What's the risk that your hunch will make things worse? Is it possible to go back and reproduce the problem in DEV/QA regions? What can you do to sync your DEV/QA region to get it closer to PROD? Maybe you have to change some environmental or database settings, maybe you have to import the PROD data to DEV, maybe you have to change some debug setting.

In general, I would not recommend pushing your hunch of a solution to PROD unless you can confirm that it is indeed correct in another region. I understand the sort of problems that come up when a bug happens in PROD and can't be reproduced anywhere else. That's when it comes down to seeing what else differs between DEV/QA and PROD and focusing on those. In my experience, it's usually an environmental setting or some configuration that is different, specifically for PROD. And I know that there is probably a lot of pressure from above to fix this, so is it possible to roll back to the previous working state and then try to reproduce the problem in DEV, come up with a fix in DEV, and then try again in PROD? That's what I'd suggest.


答:
Depends on the kind of fix. More often than not, problems in production that don't appear in dev are related to contend in the database. So applying a bug that changes database content without being sure what exactly is "out there" may be a first step in a big disaster. If you can easily take the change back, you may be able to try around. But in general, if you don't have direct access, there should at least be a copy of the database or the whole server for tests. People with the right privileges would still have to run the new code, but at least without risk of data loss. (But sometimes size of the database or complexity of infrastructure prohibits such a setup)

It's really difficult, since there are many possibilities like different settings, libraries and versions of software.

Maybe you can write a piece of code first that evaluates with some debug output if your guess for the source of the bug was right and only then apply the actual bugfix.

Title: Understanding the problem when things break in production

Body:
Scenario:

You push to production

The push broke multiple things

That same build did not break qa or dev

As a developer, you don't have prod access.

There is lots of pressure from above to get things working agian.

Specifics:

PHP/MVC application that is API-driven in Zend.

Deployed to a few servers.

My question:

While investigating, lets say I have a hunch that something is wrong.  But, I don't know for sure.  And, of course, I can't test things in production.  If I have a suggested fix based on that hunch, would it be wise to try and apply it and see if it works, before understanding what the problem is?


答:
Grab as much information about the problem as you can (logfiles etc.) and then  rollback the production servers to a working state. That's a pain from the developer's point of view of course, but is most likely a given.

Next, try and see if you can reproduce the problem in a development environment.
If you can, then fix it and try releasing again.

If you can't reproduce it, then see if you can add more diagnostics and release to one server for a short time to get more information about the problem.

If that's not possible then look more closely at the differences between production and the dev/qa environments and try to make a dev environment closer to production.


答:
Definitely don't name every table with a prefix. I tried that once and it's annoying to maintain and keep straight, especially since some tables apply to multiple sections.

I currently work with a system which has no naming prefix for most tables, but there is a naming prefix for modules-specific tables

For example, we have the usual Users, Customers, Products tables for most objects, however a module that is specifically designed to work with customer relations management  might prefix it's module-specific tables with CRM_

I would use separate schemas for sections that are completely separate from each other, however if there are links between the two (such as the CRM_ module linking to the main Customers table), then I'd probably just add the module-specific tables to the existing schema and prefix them with something

Title: Database Table Prefixes

Body:
We're having a few discussions at work around the naming of our database tables. We're working on a large application with approx 100 database tables (ok, so it isn't that large), most of which can be categorized in to different functional area, and we're trying to work out the best way of naming/organizing these within an Oracle database.

The three current options are:

Create the different functional areas in separate schemas.

Create everything in the same schema but prefix the tables with the functional area

Create everything in the same schema with no prefixes

We have various pro's and con's around each one but I'd be interested to hear everyone's opinions on what the best solution is.

Edit: Thanks for all the answers.  It's hard to pick a right answer seems it is very subjective so I'll go for the one with the most votes (it helps that it matches what I was thinking! ;-)


答:
It's called a here document because it is 'here', in the source file that needs it, rather than being elsewhere, as a separate file.  I guess looking deeper into it would be rather like trying to analyse the term '4 wheel drive' in great depth.

It can be very convenient to have your data within your code.

Title: Why is it called a 'Here Document'?

Body:
(Let me know if this is the wrong SE for this)

Why is a Here Document (or Heredoc) called that? Wikipedia didn't have anything to say on that particular subject. I did find unix docs describing a "Here is document", is that the original form?


问:
Command-Query-Separation and multithreading safe interfaces
I like the command query separation pattern (from OOSC / Eiffel - basically you either return a value or you change the state of the class - but not both). This makes reasoning about the class easier and it is easier to write exception safe classes.

Now, with multi threading, I run into a major problem: the separation of the query and the command basically invalidates the result from the query as anything can happen between those 2.

So my question is: how do you handle command query separation in an multi-threaded environment?

Clarification example:

A stack with command query separation would have the following methods:

push (command)

pop (command - but does not return a value)

top (query - returns the value)

empty (query)

The problem here is - I can get empty as status, but then I can not rely on top really retrieving an element since between the call of empty and the call of top, the stack might have been emptied. Same goes for pop & top. If I get an item using top, I can not be sure that the item that I pop is the same.

This can be solved using external locks - but that's not exactly what I call threadsafe design.

答:
Your comments have helped.  I'll try a new perspective.  New answer has two parts:  1.  Some commands must return success or failure.  I understand that traditionally commands should not return values, but things get really awkward if you don't allow at least a boolean success result.  2.  Documentation.  You must explain to users of your API that a value returned from a query simply means that value existed at the time of the query, and it may have been invalidated immediately after the query.  Thus a query can be considered an absolute fact about the past, but only a hint about the future.

For the stack example, the API might look like,

push(value) (command, always succeeds)

pop(value) (command, succeeds if value could be popped)

top() (query, returns two things: top value and empty boolean.  value is undefined if empty = true)

That's not a conventional pop command, but a pop command with no value specified or with no success result would be pointless.  It would be a command to make a change to the stack without the caller having any way to know for sure what change, if any, was made.  Also, top() must return some status about whether there was a top value.

Your implementation of the API is responsible for data synchronization.  "External" locking (I wasn't appreciating what you meant by external before) is not required by users of your API.  In your implementation, you can use whatever synchronization is available to you in your language.


答:
I did use schemas because they also make it easy to handle security on the tables: you can define what type of access each user or group of user on the overall schema.

I also have table such as Users or Currencies which are used for every department and I created a Common schema for it.

I think it does make a lot of sense and it's definitely the easier to maintain.

Title: Database Table Prefixes


答: I told my Director that just because he is OLD and has more years of experience than I have does not mean that I will respect him. The only thing that I would respect is ABILITY. I didn't have to face the consequences of such a pathetic statement may be because I was a junior Programmer than. Looking back this seems to be my bisggest mistake. Where was my common sense\humility ?? :-(</p>

Title: Biggest mistake you've ever made


答:
In my opinion, Prefixes don't seem to have physical or logical value, except in cases like this:

To distinguish normal tables from aggregated summary tables. This is to remove confusion from Sales and Sales summary tables without using the word summary.

To distinguish views from actual tables

When you deal with demoralized database where a single table has to appear twice to distinguish between staging area data vs. transactional data.

Prefixing tables is not possible to be done right because it is common to find shared tables across business functions. For example, a table like Country, can be part of the functional areas: Payroll, Sales, Accounts, Security, etc.

Information Engineering methodology promotes logical categorization of tables into what is referred to as Business Subject Areas. However, in the physical implementation, there is no such division and there is no name prefixing required.

Advanced data modeling tools allows you to group tables in separate groups from a main model and allow the admin. of the main model to provide access rights so that each sub-model can be viewed and changed in a controlled manner.

Another problem with prefixes, is that they make names longer without providing value to either developer, dba or end user.

I need to mention here that Microsoft Dynamics have a different approach to this. Tables in MS Dynamics are prefixed with some prefix, for example:

CustBankAccount

BankAccountStatement

BankAccountTrans

Again, personally, I don't see the value of prefixes except where mentioned above.

Title: Database Table Prefixes


答:
Prefixes are best if you:

a) Want to be able to install multiple copies of the same application within a single schema or database

b) Have to provide protection against SQL injection especially for common CMS platforms

However I find them a drag and problem. Your tables should be named in such a way that their names define their contents, just like @Emmad Kareen has described from Microsoft Dynamics above.

I am from the MySQL world where applications that use multiple databases are not that common, though they are in Oracle and other databases.

Also what is common is that you use one application user to connect the application to the database then use applications security to control what a user can see or access.

My advice, stay away from them as they make development and ORM mapping more complex

Title: Database Table Prefixes


答:
Usually it is either configuration or data issues, assuming that the code and DB are identical between Prod, QA, and dev.

I would first look at the following:

Any logging data your code has.

Check the event viewer for unhandled exceptions.

Check the data representing the progress of your application, it can
be in the DB, files, etc. Does it make sense or not? Is what you
expect?

Once you understand what is going on, you need to rollback the production to a working state and work on fixing the problem in a lower environment, till fixed and re-deployed to production.


答:
I wouldn't do it. More than that - if you can clearly split your application into different sections handling each a different functionality, you could just go message-bus-oriented all the way and make them completely separated apps, each with data in a separate schema (or even server) all passing messages through a shared bus under a publish/subscribe mechanism.

So, to keep the answer short, don't. If you try to guess where the table will be used at this time, you'll probably be wrong and be annoyed forever because crm_users table will unavoidably be used in the identity manager. Your question makes me suspicious your organization is trying a BDUF approach. Whatever you think you know about the system now, trust me, you really don't. ;-)

Title: Database Table Prefixes


答:
I like the idea that you can have a run-time allocated array without memory fragmentation, dangling pointers, etc. However, others have pointed out that this run-time allocation can silently fail. So I tried this using gcc 4.5.3 in a Cygwin bash environment:

```<code>#include <stdio.h>
#include <string.h>

void testit (unsigned long len)
{
    char result [len*2];
    char marker[100];

    memset(marker, 0, sizeof(marker));
    printf("result's size: %lu\n", sizeof(result));
    strcpy(result, "this is a test that should overflow if no allocation");
    printf("marker's contents: '%s'\n", marker);
}

int main(int argc, char *argv[])
{
    testit(100);
    testit((unsigned long)-1);  // probably too big
}
</code>```

The output was:

```<code>$ ./a.exe
result's size: 200
marker's contents: ''
result's size: 4294967294
marker's contents: 'should overflow if no allocation'
</code>```

The overly large length passed in the second call clearly caused the failure (overflowing into marker[]). This doesn't mean that this kind of check is fool-proof (fools can be clever!) or that it meets the standards of C99, but it might help if you have that concern.

As usual, YMMV.

Title: Array or Malloc?

Body:
I'm using the following code in my application, and it's working fine. But I'm wondering if it's better to make it with malloc or to leave it as is?</p>

```<code>function (int len)
{
char result [len] = some chars;
send result over network
}
</code>```

Body:
I like the idea that you can have a run-time allocated array without memory fragmentation, dangling pointers, etc. However, others have pointed out that this run-time allocation can silently fail. So I tried this using gcc 4.5.3 in a Cygwin bash environment:

#include <stdio.h>
#include <string.h>

void testit (unsigned long len)
{
    char result [len*2];
    char marker[100];

    memset(marker, 0, sizeof(marker));
    printf("result's size: %lu\n", sizeof(result));
    strcpy(result, "this is a test that should overflow if no allocation");
    printf("marker's contents: '%s'\n", marker);
}

int main(int argc, char *argv[])
{
    testit(100);
    testit((unsigned long)-1);  // probably too big
}

The output was:

$ ./a.exe
result's size: 200
marker's contents: ''
result's size: 4294967294
marker's contents: 'should overflow if no allocation'

The overly large length passed in the second call clearly caused the failure (overflowing into marker[]). This doesn't mean that this kind of check is fool-proof (fools can be clever!) or that it meets the standards of C99, but it might help if you have that concern.

As usual, YMMV.


问:
Difference between "String" and "string" in .NET and which is best?
In the .NET Framework, at least in the C# language, we have two "versions" of the string type:

"string"

"String"

It appears that they are interchangeable, but are they really?  If they are not interchangeable, is it generally better to use one instead of the other, and under what circumstances?

答:
Well according to the MSDN

string is an alias for String in the .NET Framework.

Where "String" is in fact System.String.

I would say that they are interchangeable and there is no difference when and where you should use one or the other.

It would be better to be consistent with which one you did use though.


问:
Right approach to convert a word document that contains forms in a web app
I would know if someone can suggest a good approach to convert a word document that contains forms in a web app, specifically in an application built with WaveMaker.(but I'm curious also with a general approach not strictly dependent on the technology that I have mentioned).
For example, if I have a page in a word document, that maps the fields of a user entity, what could be my "programmer approach" to convert it without much use of copy-paste, but with a dynamic methodology ?</p>

答: Apache POI is a set if libraries providing a Java API for working with Microsoft-type documents.  It's not going to code-generate anything for you (or be generated), but you might be able to build a service around POI that your web app could then use to pull the fields out of your documents.</p>


问:
How can I get started using TDD to code some simple functionality?
I basically have the gist of TDD.  I'm sold that it's useful and I've got a reasonable command of the MSTEST framework.  However, to date  I have not been able to graduate to using it as a primary development method.  Mostly, I use it as a surrogate for writing console apps as test drivers (my traditional approach).

The most useful thing about it for me is the way it absorbs the role of regression testing.

I have not yet built anything yet that specifically isolates various testable behaviors, which is another big part of the picture I know.

So this question is to ask for pointers on what the first test(s) I might write for the following development task: I want to produce code that encapsulates task execution in the fashion of producer/consumer.

I stopped and decided to write this question after I wrote this code (wondering if I could actually use TDD for real this time)

Code:

```<code>interface ITask
{
    Guid TaskId { get; }
    bool IsComplete { get; }
    bool IsFailed { get; }
    bool IsRunning { get; }
}

interface ITaskContainer
{
    Guid AddTask(ICommand action);
}

interface ICommand
{
    string CommandName { get; }
    Dictionary<string, object> Parameters { get; }
    void Execute();
}
</code>```

答:
Starting with this concept:

1) Start with the behavior that you desire.  Write a test for it.  See test fail.

2) Write enough code to get the test to pass.  See all tests pass.

3) Look for redundant / sloppy code -> refactor.  See tests still pass.  Goto 1

So on #1, let's say that you want to create a new command (I'm stretching to how the command would work, so bear with me).  (Also, I'll be a bit pragmatic rather than extreme TDD)

The new command is called MakeMyLunch, so you first create a test to instantiate it and get the command name:

```<code>@Test
public void instantiateMakeMyLunch() {
   ICommand command = new MakeMyLunchCommand();
   assertEquals("makeMyLunch",command.getCommandName());
}
</code>```

This fails, forcing you to create the new command class and have it return its name (purist would say this is two rounds of TDD, not 1).  So you create the class and have it implement the ICommand interface, including returning the command name.  Running all tests now shows all pass, so you proceed to look for refactoring opportunities.  Probably none.

So next you want it to implement execute.  So you have to ask: how do I know that "MakeMyLunch" successfully "made my lunch".  What changes in the system because of this operation?  Can I test for this?

Suppose it is easy to test for:

```<code>@Test
public void checkThatMakeMyLunchIsSuccessful() {
   ICommand command = new MakeMyLunchCommand();
   command.execute();
   assertTrue( Lunch.isReady() );
}
</code>```

Other times, this is more difficult, and what you really want to do is test the responsibilities of the subject-under-test (MakeMyLunchCommand).  Perhaps the responsibility of MakeMyLunchCommand is to interact with Fridge and Microwave.  So to test it you can use a mock Fridge and mock Microwave.  [two sample mock frameworks are Mockito and nMock or look here.]

In which case you would do something like the following pseudo code:

```<code>@Test
public void checkThatMakeMyLunchIsSuccessful() {
   Fridge mockFridge = mock(Fridge);
   Microwave mockMicrowave = mock(Microwave);
   ICommand command = new MakeMyLunchCommand( mockFridge, mockMicrowave );
   command.execute();
   mockFramework.assertCalled( mockFridge.removeFood );
   mockFramework.assertCalled( microwave.turnon );
}
</code>```

The purist says test the responsibility of your class - its interactions with other classes (did the command open the fridge and turn on the microwave?).

The pragmatist says test for a group of classes and test for the outcome (is your lunch ready?).

Find the right balance that works for your system.

(Note: consider that perhaps you arrived at your interface structure too early.  Perhaps you can let this evolve as you write your unit tests and implementations, and in step #3 you "notice" the common interface opportunity).

Body:
Starting with this concept:

1) Start with the behavior that you desire.  Write a test for it.  See test fail.

2) Write enough code to get the test to pass.  See all tests pass.

3) Look for redundant / sloppy code -> refactor.  See tests still pass.  Goto 1

So on #1, let's say that you want to create a new command (I'm stretching to how the command would work, so bear with me).  (Also, I'll be a bit pragmatic rather than extreme TDD)

The new command is called MakeMyLunch, so you first create a test to instantiate it and get the command name:

@Test
public void instantiateMakeMyLunch() {
   ICommand command = new MakeMyLunchCommand();
   assertEquals("makeMyLunch",command.getCommandName());
}

This fails, forcing you to create the new command class and have it return its name (purist would say this is two rounds of TDD, not 1).  So you create the class and have it implement the ICommand interface, including returning the command name.  Running all tests now shows all pass, so you proceed to look for refactoring opportunities.  Probably none.

So next you want it to implement execute.  So you have to ask: how do I know that "MakeMyLunch" successfully "made my lunch".  What changes in the system because of this operation?  Can I test for this?

Suppose it is easy to test for:

@Test
public void checkThatMakeMyLunchIsSuccessful() {
   ICommand command = new MakeMyLunchCommand();
   command.execute();
   assertTrue( Lunch.isReady() );
}

Other times, this is more difficult, and what you really want to do is test the responsibilities of the subject-under-test (MakeMyLunchCommand).  Perhaps the responsibility of MakeMyLunchCommand is to interact with Fridge and Microwave.  So to test it you can use a mock Fridge and mock Microwave.  [two sample mock frameworks are Mockito and nMock or look here.]

In which case you would do something like the following pseudo code:

@Test
public void checkThatMakeMyLunchIsSuccessful() {
   Fridge mockFridge = mock(Fridge);
   Microwave mockMicrowave = mock(Microwave);
   ICommand command = new MakeMyLunchCommand( mockFridge, mockMicrowave );
   command.execute();
   mockFramework.assertCalled( mockFridge.removeFood );
   mockFramework.assertCalled( microwave.turnon );
}

The purist says test the responsibility of your class - its interactions with other classes (did the command open the fridge and turn on the microwave?).

The pragmatist says test for a group of classes and test for the outcome (is your lunch ready?).

Find the right balance that works for your system.

(Note: consider that perhaps you arrived at your interface structure too early.  Perhaps you can let this evolve as you write your unit tests and implementations, and in step #3 you "notice" the common interface opportunity).


答: I'd suggest using lowercase string.  Uppercase String will use the first class named String it finds in the imported namespaces ... which is generally System.String.  It's possible for your own String class to be used instead.

Title: Difference between "String" and "string" in .NET and which is best?

Body:
In the .NET Framework, at least in the C# language, we have two "versions" of the string type:

"string"

"String"

It appears that they are interchangeable, but are they really?  If they are not interchangeable, is it generally better to use one instead of the other, and under what circumstances?


问:
Is it a bad decision to release code that is not open source
I work for a company that owns several closed source software. One of our software is used to service clients and generate income so it has commercial value to us (and it pays my salary).

I've talked about open sourcing the code, but the option of open sourcing under something like the MIT or GPL or any other open source license that allows competitors to install it and offer it to our clients for cheaper has met clear resistance.

What about showing the code but not under an open source license?

The arguments I've been getting against this is that this move will confuse clients and developers and will get us more bad publicity than any good thing. The developer of PAINT.NET used to release his code and got a lot of flack when he started reminding competitors that the code is only for educational purposes and isn't really open source.

I've also been told that open sourcing for the sake of open sourcing doesn't make sense, bla bla bla, and that unless I have a plan for how that's going to bring more revenue, it's not for us. Well, honestly I don't have a plan, but I thought why not try. Of course I can't say if this will help us or hurt us. I don't want to take the responsibility for a move that might hurt a company that's doing well and get people laid off.

As I said, an open source license does not look like an option, so it's between closed source or showing the code but still under a normal copyright license. But as I said there's resistance to showing the code because of the worry that competitors will use our code to create their own.

Does anyone know of any facts that can help with this decision, whether in favor or against showing the code.

答:
The primary question here isn’t: what do you get from showing the source – it’s what do others get from being shown the source. If you can’t answer this question, then nobody will bother looking at it, and that in turn will mean you and your company don’t benefit.

Now, if the source isn’t Open Source then the usefulness of the code to others is drastically reduced. I can imagine only two scenarios which make it worthwhile publishing the code:

It’s a showcase of good architecture and design. In that case, you can annotate it and publish it as an educational aid.

It uses a hitherto unknown pattern or algorithm that you might want to publish, and your project serves as a demonstration.

OwnerDisplayName: samiii


问:
Pointers in C vs No pointers in PHP
Both languages have the same syntax.

Why does C have the weird * character that denotes pointers (which is some kind of memory address of the variable contents?), when PHP doesn't have it and you can do pretty much the same things in PHP that you can do in C, without pointers? I guess the PHP compiler handles this internally, why doesn't C do the same?

Doesn't this add unneeded complexity in C? For example I don't understand them :)

答:
Like so many things, the answer is of the form "Because X and Y are different things with different purposes".

In this case, the designers of both languages assumed that the users of their languages had a very different set of goals.  For C, the primary use case was "portable assembly language", which really means getting down into the nitty-gritty of how the computer is actually managing its resources.  There's no practical way to avoid memory address manipulation at the lowest level of abstraction, and so C has robust support for it.

PHP was intended to make dynamic web page content as flexible and painless as possible.  This is quite a few steps removed from the super-low level of the C world; managing memory is, for the purposes PHP is intended to address, much too low level to be of much interest.  Any kind of automatic memory management would be fine, so long as it is robust and reliable, and stays out of the way.  That's exactly the situation you see in PHP; objects are allocated automatically, when needed, and garbage collected when they are no longer useable, and it all happens without the intervention of the PHP programmer.

It's perhaps of some interest to observe that PHP is itself written in C!  the nitty gritty of memory management is written in C, which provides the tools needed to do that kind of thing, so that the language created, doesn't require the programmer to do much themselves.

Title: Pointers in C vs No pointers in PHP


答:
PHP is actually an extremely limited language.  It can do one thing well--produce webpages--because it was only ever designed to do that one thing.  But if you wanted to build a 3D game, or write an operating system, or create a competitor to Photoshop, you wouldn't want to do that in PHP!

C, on the other hand, is a general-purpose language.  It was first designed to build operating systems, which provide an interface between the hardware and the rest of the software.  To do that, you need a concept of direct memory access.  (For example, if you want to send something to a printer, you need to be able to send data over a network, you need to be able to write directly to the location in memory where the network hardware's input buffer is located.)  That's what pointers are really for.

The problem with pointers in C, and the thing that makes them difficult to understand, is that in C they're used as a "magic hammer".  Earlier languages had better ways to do certain things that in C are only available by using pointers.  (FORTRAN had pass-by-reference, and ALGOL and Pascal had real arrays, for example.  C has neither; you have to fake both by abusing pointers.)  Since they're used all over the place for many different things that can and should be done other ways, it makes it difficult to understand what they're about.

Title: Pointers in C vs No pointers in PHP

Body:
Both languages have the same syntax.

Why does C have the weird * character that denotes pointers (which is some kind of memory address of the variable contents?), when PHP doesn't have it and you can do pretty much the same things in PHP that you can do in C, without pointers? I guess the PHP compiler handles this internally, why doesn't C do the same?

Doesn't this add unneeded complexity in C? For example I don't understand them :)


答:
C is a pretty low level language, it's pretty much one step removed from Assembly (and C was designed to be a portable assembly). It's an abstraction of the machine, and uses pointers because it allows you to operate at the machine level, and back then you would use pointers to directly access memory (virtual memory has made this practice mostly arcane).

Note that C was created in the 70s, when computers were far simpler than they were now, and direct memory addressing was how software worked. Pointers are also used for things like arrays (you could say arrays are syntactic sugar for pointers in C), and dynamic memory allocation to create data whose size may be unknown at compile time.

PHP is much newer than C (late 90s) and is heavily influenced by C in its design, but it, like many other languages newer than C, abstracts away raw pointer usage and instead uses things like References, which are like limited pointer, in that they can refer to other data, but you can not do things like perform pointer arithmetic, nor do they represent addresses.

PHP was designed to be easy for people to learn, and a pain point many programmers have when using C (or C++) is pointers, so PHP and many other languages abstract away pointers and use references, objects, implicit heap allocation, etc. to hide pointer usage from you. Internally, PHP will be using pointers (it is written in C, after all), but you yourself do not have to be concerned about that.

As for complicating C? I think C is a rather simple language (the de facto book is 300 pages and shorter than most other language books), but pointers do take some mental work to understand.

Title: Pointers in C vs No pointers in PHP


答:
PHP does allow you to use pointers, as you can see in the official documentation on References.

It's not exactly the same thing as in C, as the latter does allow you to allocate memory very precisely, but pointers are present in a lot of language.

Basically, remember that every time that you create an array or a class in an object-oriented language (C++, C#, Java, ...) you actually create a pointer that is stored in the variable. What allows you to skip the * operators is some kind of synthaxic sugar.

Title: Pointers in C vs No pointers in PHP


答:
string is just an alias for String, they're ultimately the same.

You can use whichever you prefer, although I generally use string when I'm planning on using it much like a primitive data type (similar to int, float, or bool) and String when I'm planning on using it as an object/class. For example:

```<code>string foo = "   ";
if (String.isNullOrWhitespace(foo))
{
    // ...
}
</code>```

In the case above, I'm planning on using foo simply to store some text (effectively as a primitive), so I use string; however, when I call String.isNullOrWhitespace(string) I use String. I do this, because generally the first letter of class names are capitalized (String) while the first letter of primitives (such as int) are not.

Body:
string is just an alias for String, they're ultimately the same.

You can use whichever you prefer, although I generally use string when I'm planning on using it much like a primitive data type (similar to int, float, or bool) and String when I'm planning on using it as an object/class. For example:

string foo = "   ";
if (String.isNullOrWhitespace(foo))
{
    // ...
}

In the case above, I'm planning on using foo simply to store some text (effectively as a primitive), so I use string; however, when I call String.isNullOrWhitespace(string) I use String. I do this, because generally the first letter of class names are capitalized (String) while the first letter of primitives (such as int) are not.


答:
You actually can't do the same things in PHP, if it concerns actual (physical, not pretend virtual) hardware and/or video bitmaps (etc.) at fixed non-remapped physical addresses, perhaps in some constrained number of CPU cycles.

Web sites are not the only things run by software.

Title: Pointers in C vs No pointers in PHP


问:
Can defect containment metrics be readily applied at an organizational level when there is only a consistant organizational process framework?
Defect containment metrics, such as total defect containment effectiveness (TDCE) and phase containment effectiveness (PCE), can be used to give a good indicator of the quality of the process. TDCE captures the defects that are captured at some point between requirements and the release of a product into the field, indicating the overall effectiveness of the entire process to find and remove defects. PCE provides more detail at each phase of the software development life cycle and how the defect detection and removal techniques are working.

Applying these metrics makes sense at a level where you have a well-defined process and methodology for product development, often a project. However, some organizations provide a process framework that is tailored at the project level. This process framework would include the necessary guidance for meeting certifications (ISO9001, CMMI), practices for incorporating known good techniques (agile methods, Lean, Six Sigma), and requirements for legal or regulatory reasons. However, the specific details of how to gather requirements, design the system, produce the software, conduct test, and release are left to the product development teams.

Is there any effective way to apply defect containment metrics at an organizational level when only a process framework exists at the organizational level? If not, what might be some ideas for metrics that can be distilled from each project (each using a tailored process that fits into the organizational process framework) that captures defect containment metrics to discuss the ability of the process to find and remove defects?

The end goal of such a metric would be to consolidate the defect containment practices of a large number of ongoing projects and report to management. The target audience would be people in roles such as the chief software engineer and the chief engineer (of all engineering disciplines) for the organization. Although project specific data would be available, the idea is to produce something that quantifies the general effectiveness of all tailored processes across all ongoing projects. I would suspect that this data would also be presented as part of CMMI, ISO, or similar audits to demonstrate process quality.

答:
I found an article from CrossTalk magazine titled Advancing Defect Containment to Quantitative Defect Management, written by two engineers at Raytheon. This article describes a technique to do exactly what I want to do - bring software defect containment metrics and try to make them meaningful at an organizational level. They call this technique Quantitative Defect Management (QDM).

It centers around historical defect data and comparing current project data against historical data. By determining the number of defects generated in a given phase in similar past projects, it's possible to estimate the number of defects that you expect to generate in your current project in that same phase. Of course, in an environment that embraces continuous improvement, you would expect to see a downward trend in defects over time, but you can account for this.

Once you know your historical data, you can compare your found in-phase defects to that projected number. This allows you to allocate time and resources to various defect detection strategies for each phase of development, along with reviewing your defect removal and containment data to improve the process to prevent defects in future projects. By budgeting time appropriately for each phase, and continually monitoring and improving the techniques used to detect defects, one can expect an improvement in both process and product quality.

The authors also talk about this metric in relationship to Six Sigma and CMMI (especially Level 4 and Level 5).

Although this doesn't correspond exactly to defect containment, I feel that this is appropriate for management. It will provide data that can be used across projects to compare the current process quality to previous projects, provide additional data for monitoring product quality, and (over time) demonstrate the effectiveness of process improvement efforts.


问:
Scrum: What if the Product Owner has tasks?
I have just started working with a team that has picked up some aspects of Scrum (two week timeboxing) but not others (the team does not currently agree to all estimates or to the number of points in a sprint, but I'll change this soon.)  The product owner is also a technical resource (scientist) with some development background.

Is it appropriate to have the product owner's tasks (which mostly involve research) mixed in with the team's tasks (some of which are research and some development).

答:
Scrum is first and foremost about communication, and doing work that is relevant and timely. Anything to further that goal is OK if that's what lets your team be its most productive.

It is difficult to do well, however. I'm in that position now and I find it hard to devote an appropriate amount of time as the product owner while still leaving time for development. However, the arrangement works well for this specific team at this point in time. We'll revisit the decision for me to pull double duty when our performance drops, but until then we'll keep working this way.

So, try it. Do retrospectives so you can continually improve your process. Don't let sticking previously to some methodology get in the way of your team's productivity.

OwnerDisplayName: Lauren J


答:
C is a systems programming language, which can be used to create things like device drivers, embedded software and operating systems.

PHP is a scripting language used to create websites.

They're not the same thing at all.  Apples and oranges.

It is not true that both languages have the same syntax.  The C language requires that variables be explicitly declared.  PHP deduces a variable's type from its usage. Parameter passing is different.  Rules about variable scope are different.  There are some syntactical similarities, but it's not true that they use the same syntax.

Address oriented operations (which are enabled by the availability of pointers) are required by many low level tasks that the C language is used for.

Title: Pointers in C vs No pointers in PHP


问:
Is the phrase "never reinvent the wheel" suitable for students?
I find myself constantly running into this expression "don't reinvent the wheel" or "never reinvent the wheel" when I ask some questions on SO.  They tell you to use some frameworks or existing packages.  I know where this attitude is coming from since it's unwise to waste time on something others have already solved.  Or it that so?

As a student,  I find by using some code others wrote to solve my problem I can't learn as much as I'd like to, and I gain less insight.  And sometimes I think that phrase is mainly for working programmers facing deadlines and not for students like me.

Is it that bad to "reinvent the wheel"?  Maybe I'm thinking it wrong? Maybe there is a way I can avoid reinventing the wheel and at the same time learn a lot?

答:
In real life, the wheel is reinvented over and over again. If we look for the reasons, we might find some insight as when we need to reinvent the wheel in programming.

Since Sumerian times, many things have changed:

The material used to build wheels: from stone, wood, metal, carbon, ...

the size of objects needing wheels -  in the size of nanometers for medical instruments and wheels for earning brown coal, 100m in size

the production environment - hand made, or industry production

the precision of wheels which are needed

The right situation around your wheel. There might be a perfect wheel for your job, but it might be patented.

The shining and polish for your wheel. A Cadillac might deserve another wheel than a VW Golf.

The optimal wheel for a baby stroller depends on many parameters: Size and weight of stroller (plus baby/~ies), climate circumstances, resource prices for oil or natural rubber, machines to build wheels and craftsmen, available for production. Shortly spoken: World economics.

How does that translate to the software world? Well,

there might be a webserver, but unfortunately it is written in PHP. You would prefer to have it in a language you're fluent in

a sorting algorithm might be oversized for 10 elements, but does not scale up to 1T of elements

you might need a solution which is itself generated by second program

precision is most often a digital question in software land, if an algorithm sorts a list it is sorted - not mostly sorted. But beside performance, code size, memory usage or other restrictions can happen

Patents don't need further explanation, I guess.

The look and feel is a constant reason for reinventing something - think dropDownList (ComboBox).

The global economic situation can influence your software-wheel: will it be a cloud wheel, an Open Source wheel, a Browser-wheel or an App wheel?

And of course the most famous reason to build your own wheel: You like to learn it.


答:
Do what the assignment/question/exam asks you to do.

Years ago I was a TA for a C programming class. An exam question was 'Write a program to copy a file'. Several students asked the same type of question - can they spawn a process and run the OS cp command?

What we asked them back was 'Will your program copy the file?'

The exam question asked them to write code to copy a file. If the answer did not have C code that copied the file (e.g. open input, open output, a loop to read/write bytes, close input, close output) then it did not copy the file.

If the teacher says use a framework or library (e.g. a graphics class might tell you to use a 3D library ) then use what they tell you to use. Do not invent your own or use a different one. Anything different will make it harder for the teacher to grade your work.

In a job interview a knowledge of popular frameworks will help you answer questions. Create your own projects to learn. Good luck with your studies.


答:
Pointers in C serve three main purposes:

Faking pass-by-reference

C passes all function arguments by value; the formal parameters and the actual parameters are different objects in memory, so changes to the formal parameter are not reflected in the actual parameter.  If you want a function to change the value of something in the caller, you must pass the pointer to that object:

```<code>void swap(int *a, int *b)
{
  int tmp = *a;
  *a = *b;
  *b = tmp;
}

int main(void)
{
  int x = 3, y = 4;
  swap(&x, &y);
  return 0;
}
</code>```

The expressions *a and *b in swap correspond to the objects x and y in main, so writing to *a updates x and writing to *b updates y.

Tracking dynamically allocated memory

The C memory allocation functions malloc, calloc, and realloc all return pointers to the first element of the dynamically allocated buffer.

```<code>int *arr = malloc(sizeof *arr * N); // allocates a block of memory large
                                    // enough to hold N ints
</code>```

You can apply the subscript operator to a pointer as though it were an array (the subscript operation a[i] is equivalent to *(a + i); that is, offset i elements from a and dereference the result).

Building self-referential data structures

Although generations of Fortran programmers were building lists, trees, queues, stacks, etc., without them, pointers make building self-referential structures very easy, such as this binary tree node:

```<code>struct tnode {
  K key;                // for some arbitrary type K
  T data;               // for some arbitrary type T
  struct tnode *left;   // explicitly points to left subtree
  struct tnode *right;  // explicitly points to right subtree
};
</code>```

I'm not familiar enough with PHP to say how you would do these things in that language.  I would point out that C predates PHP by at least a couple of decades, and that PHP is pretty specific to a particular domain.

As to why C doesn't handle all this automagically...

One of the guiding philosophies of C is to keep the language as simple as possible, making it relatively easy to implement.  Automatic memory management would add some complexity to the language (adding the threading library in C11 certainly did).  Not to mention that automatic memory management can also play hell with performance-critical code.

Title: Pointers in C vs No pointers in PHP

Body:
Pointers in C serve three main purposes:

Faking pass-by-reference

C passes all function arguments by value; the formal parameters and the actual parameters are different objects in memory, so changes to the formal parameter are not reflected in the actual parameter.  If you want a function to change the value of something in the caller, you must pass the pointer to that object:

void swap(int *a, int *b)
{
  int tmp = *a;
  *a = *b;
  *b = tmp;
}

int main(void)
{
  int x = 3, y = 4;
  swap(&x, &y);
  return 0;
}

The expressions *a and *b in swap correspond to the objects x and y in main, so writing to *a updates x and writing to *b updates y.

Tracking dynamically allocated memory

The C memory allocation functions malloc, calloc, and realloc all return pointers to the first element of the dynamically allocated buffer.

int *arr = malloc(sizeof *arr * N); // allocates a block of memory large
                                    // enough to hold N ints

You can apply the subscript operator to a pointer as though it were an array (the subscript operation a[i] is equivalent to *(a + i); that is, offset i elements from a and dereference the result).

Building self-referential data structures

Although generations of Fortran programmers were building lists, trees, queues, stacks, etc., without them, pointers make building self-referential structures very easy, such as this binary tree node:

struct tnode {
  K key;                // for some arbitrary type K
  T data;               // for some arbitrary type T
  struct tnode *left;   // explicitly points to left subtree
  struct tnode *right;  // explicitly points to right subtree
};

I'm not familiar enough with PHP to say how you would do these things in that language.  I would point out that C predates PHP by at least a couple of decades, and that PHP is pretty specific to a particular domain.

As to why C doesn't handle all this automagically...

One of the guiding philosophies of C is to keep the language as simple as possible, making it relatively easy to implement.  Automatic memory management would add some complexity to the language (adding the threading library in C11 certainly did).  Not to mention that automatic memory management can also play hell with performance-critical code.


答:
Experts in Scrum are very firm in stating that the Product Owner and Scrum Master should be two different people.  However, there is no such rule excluding either from the Development Team.  Note in the Scrum Guide:

Development Team Size

Optimal Development Team size is small enough to remain nimble and
  large enough to complete significant work. Fewer than three
  Development Team members decreases interaction and results in smaller
  productivity gains. Smaller Development Teams may encounter skill
  constraints during the Sprint, causing the Development Team to be
  unable to deliver a potentially releasable Increment. Having more than
  nine members requires too much coordination. Large Development Teams
  generate too much complexity for an empirical process to manage. The
  Product Owner and Scrum Master roles are not included in this count
  unless they are also executing the work of the Sprint Backlog.

The corollary to that last line would be that, if the Product Owner is executing the work of the Sprint Backlog, he or she is counted as a member of the Development Team.

That said, do whatever works to get your work done well.

Title: Scrum: What if the Product Owner has tasks?

Body:
I have just started working with a team that has picked up some aspects of Scrum (two week timeboxing) but not others (the team does not currently agree to all estimates or to the number of points in a sprint, but I'll change this soon.)  The product owner is also a technical resource (scientist) with some development background.

Is it appropriate to have the product owner's tasks (which mostly involve research) mixed in with the team's tasks (some of which are research and some development).


问:
Why do programmers write closed source applications and then make them free?
As an entrepreneur/programmer who makes a good living from writing and selling software, I'm dumbfounded as to why developers write applications and then put them up on the Internet for free.  You've found yourself in one of the most lucrative fields in the world.  A business with 99% profit margin, where you have no physical product but can name your price; a business where you can ship a buggy product and the customer will still buy it.

Occasionally some of our software will get a free competitor, and I think, this guy is crazy.  He could be making a good living off of this but instead chose to make it free.

Do you not like giant piles of money?

Are you not confident that people would pay for it?

Are you afraid of having to support it?

It's bad for the business of programming because now customers expect to be able to find a free solution to every problem. (I see tweets like "is there any good FREE software for XYZ? or do I need to pay $20 for that".) It's also bad for customers because the free solutions eventually break (because of a new OS or what have you) and since it's free, the developer has no reason to fix it. Customers end up with free but stale software that no longer works and never gets updated. Customer cries. Developer still working day job cries in their cubicle. What gives?

PS: I'm not looking to start an open-source/software should be free kind of debate. I'm talking about when developers make a closed source application and make it free.

答: If you're writing a platform instead of a product, making it open source assures that people can build on it with confidence. So that's one reason.</p>


答:
As pointed out, they are the same thing and string is just an alias to String.

For what it's worth, I use string to declare types - variables, properties, return values and parameters. This is consistent with the use of other system types - int, bool, var etc (although Int32 and Boolean are also correct).

I use String when using the static methods on the String class, like String.Split() or String.IsNullOrEmpty(). I feel that this makes more sense because the methods belong to a class, and it is consistent with how I use other static methods.


问:
Advice on whether to use scripting, run time compile or something else
I work in the prodution area at my works and I design and create the software to run our automated test equipment for testing our products. Everytime I get involved with a new machine I end up with a different and (hopefully) better design. Anyway I have come to the point where I feel I need to start standardizing all the machines with the same program. I see a problem when it comes to applying updates as at the moment the test procedures are hard coded into the program at each station. I neeed to be able to update the core program without affecting the testing section.

The way I see it is that this will mean splitting the program into 2 sections.

Main UI - This is the core that talks to everything on the machine such as cameras, sensors, printer etc and is a standalone application.

Test Procedure - This is the steps that is executeted everytime the machine runs through a test.

The main UI will load the test procedure and execute when ever a test is required.

My question is what is the best approach to this in terms of having an application load a file and execute the code with in? Take into account that the code in the test procedure will need access to public methods on the UI/core system to communicate to sensors etc. I have heard about MS Roslyn and had a quick look, would this solve my issue?

答:
It sounds like what you need for the test procedure is Automated GUI testing. This allows you to replay GUI actions (normally via a script) and then check the results.  The Main GUI as you describe remains unchanged and is just automated via the GUI Tester.

Below are some links with futher references:

https://stackoverflow.com/questions/120359/tools-for-automated-gui-testing-on-windows

https://stackoverflow.com/questions/2125839/has-anybody-used-sikuli-for-testing-their-gui-based-apps

https://stackoverflow.com/questions/9136541/third-party-wpf-suites-w-automated-coded-ui-testing

There's some functionality built into VS 2010 (Premium) called 'Coded UI'

http://msdn.microsoft.com/en-us/library/dd286726.aspx