答: You must use ORM if you want to stay DRY and as @Travis pointed you should use NHibernate because it has support for all of them already prepared. Without ORM you will either have data access completely in stored procedures and you will write all of them in every database again or you will have special data access assembly per database with queries and commands defined in DB specific SQL dialect. ORM already wrap this functionality and uses universal query language translated to dialect required by the database.</p>

Title: How can I design an application so that it works well with a database selected by the customer?

Body:
I want to write an ASP.NET 4.0 application with IBM DB2 Express-C as its back-end. One thing that worries me, is hosting this application on a remote server. I don't know any hosting provider who provides ASP.NET DB2 hosting in the same price range as of SQL Server.

I also want to allow the customer to select the database of their choice from this list:

SQL Sever

Oracle

DB2

PostgreSQL

Firebird

There are the same hosting worries with Oracle and Firebird.

Hosting issues aside, I want to know how to design an application so it is agnostic to the kind of RDBMS used and will work with any of the above mentioned ones.

Are there any such applications around?


问:
Best way to handle class relationship
Take a User class and the idea that a User is to be profiled. I see four ways to handle this:

Write the code for the profile into the User class. I am dismissing this right away.

Create a Profile class and make it a property of the User class.

Write a User class (with the boiler-plate name, address stuff), write a Profile class,
and write a UserProfile class - UserProfile is the union of User and Profile.

Write a User class and a Profile class that each have an ID property and let the ID act
as the intersection. This way the User and Profile are independent and another class,
possibly an abstract class with nothing but static methods handles the logic that
describes the connection.

Choices 3 and 4 each require at least three classes. For this case, which is the best choice? If possible to generalize this, would it generally be better to use one of these possibilities?

答:
Write the code for the profile into the User class. I am dismissing this right away.

Why? This is the simplest solution. I would do this until the pain appeared.  That moment may come very soon.  So what if it does?  Just extract the profile data into a separate class.

ContentLicense: CC BY-SA 3.0

Title: Best way to handle class relationship


问:
Documenting and enforcing programming standards and guidelines for shared library
Myself and another developer with the go ahead from our IT director have started a general purpose library in .NET with the intention that it will provide many common purpose classes that we use in our day to day development.

During discussions and design of the library we have come up with a set of standards that we want the library to follow to ensure it is maintained and expanded on in a consistent manner.

What is the best way to ensure these decisions we made for the library get feed to the other developers who might be using and adding to this library in the future.  One of our decisions was to ensure we review all checked in code so we expect initially there to be some differences in coding styles of individuals not fitting in with the project standards.

Some ideas I had were:

Add a Read-me.txt to the project that outline the guidelines and standards

Send an email out to everyone in the team to let them know about the project etc

Call a team meeting to go through this new project and our expectations and standards we were aiming to follow

Try and enforce the standards via Visual Studio (not sure if this would be possible or how just an idea)

At the moment there is no general company programming standards so this would be a first really insofar as we are creating a standard that different project teams would need to adhere to.

答:
Internal style of the code is a secondary thing IMHO - its much more important to have a consistent set of documentation teaching the user of the library what's available and how to use it.

From that you need to start as you mean to go on, write this documentation with the correct format and depth, then expect all contributions to provide a similar level of documentation. This is difficult to enforce automatically, but you could prevent checkins unless the doc source files are present, and then decide whether it is acceptable in a 'code' review phase. Only those additions that pass are then incorporated into the trunk (assuming everyone adds their contributions to a branch).

Too many developers think that the code is all that matters. It isn't, and for a library its probably the least part of the whole. Get the documentation, with examples of use, descriptions of calls and parameters and you'll get better adoption and it'll save a lot of time for the users of your library. (yes, and its boring to do it, but too bad - do it properly)


问:
Should I avoid private methods if I perform TDD?
I'm just now learning TDD. It's my understanding that private methods are untestable and shouldn't be worried about because the public API will provide enough information for verifying an object's integrity.

I've understood OOP for a while. It's my understanding that private methods make objects more encapsulated, thus more resistant to change and errors. Thus, they should be used by default and only those methods that matter to clients should be made public.

Well, it's possible for me to make an object that has only private methods and interacts with other objects by listening to their events. This would be very encapsulated, but completely untestable.

Also, it's considered bad practice to add methods for the sake of testing.

Does this mean TDD is at odds with encapsulation? What is the appropriate balance? I'm inclined to make most or all of my methods public now...

答:
Avoid using?  No.

Avoid starting with?  Yes.

I notice you didn't ask about whether it's ok to have abstract classes with TDD; if you understand how abstract classes emerge during TDD, the same principle applies to private methods as well.

You can't directly test methods in abstract classes just like you can't directly test private methods, but that's why you don't start out with abstract classes and private methods; you start with concrete classes and public APIs, and then you refactor common functionality as you go.


问:
Programming "everything" using HTML5?
HTML 5 applications in the browser really seem to be taking off. I've been using src:kit within Google Chrome for a few weeks and love it. I'm an ASP.Net (C#/MVC 3) developer by trade, and in the past did several pieces of WebForms programming.

With Windows 8 app development moving into the trade of local HTML5 apps, and the major smartphone browsers supporting HTML5 installation, as well as many platforms supporting it (PhoneGap and Titanium, for example), are we already/will we soon be at the point that I could create an app that would be fully "installable" to run as a standalone on every platform?

I do realise that a database (or instert-your-data-store-here) would also be necessary, so adding another language in there for middleware would be necessary. C# on Mac/Linux with Mono is possible, but Mono generally only creates a GTK+ Application, so I would likely need to create another wrapper to house the application... I think.

Any suggestions of a better language to use as middleware? I.e. for ease of transportation - I've got far more experience with C# than anything else so would like something from that family if I'll need to do something different.

Basically, how far away are we from this? What still needs to change? Most importantly, if it is possible (which I believe, theoretically it is), what is the big jump between where we are now and when we will be there?

This will eventually turn into a program, so it is a completely practical problem that I'm working my way through (I'll start development after Christmas).

EDIT: To clarify, by 'every' platform, I include at least the following: Windows XP+/Mac OS X/Linux: any distro pretty much in the last 2 years/iOS/Android/Blackberry 5+/Windows Phone 7+

答:
I'd say yes - the UI layer should be decoupled from the rest of the application anyway (in a perfect world, obviously...) so exposing your back-end software logic to a HTML-based front-end (note that I consider the web server to be part of the presentation layer) makes perfect sense.

The difficulty with this is that there are some things are are either not supported or just plain difficult to implement with HTML. This is changing rapidly so I'm not sure (but not 100% convinced either) that this is no longer a problem.

For example, you could only get 'push' to the client using polling-via-AJAX, but today we have websockets. You could only get fancy graphics using a plugin like Flash, but today we have WebGL. Once you had slow networks but today we have very fast and low-latency ones.

I think aspects like validation and responsive-ui without having to front-load a ton of data still requires a lot of design thought, but these are solveable problems.

So I'd go for it. Note that there is some interesting frameworks coming along now - especially Wt which changes the drawing commands of Qt from 'raw pixels' to html components so your 'desktop' Qt code will run on the web without any modification. I think that's pretty damn cool.

Title: Programming "everything" using HTML5?


问:
Should I drop in on local businesses and offer my services as an intern to get experience?
I am trying to get an entry-level developer job, but have no relevant experience. I am able to code C#, SQL, HTML, and CSS and understand principles of OOP and have completed a couple of applications both in WinForms and WebForms.

I've tried applying to graduate roles, but I get blocked by recruiters who don't like my experience so far.

I was thinking about writing a detailed report (like a CV) on what I've done so far, visiting software shops, introducing myself, and ask for an internship.

Is this an effective way to get my foot in the door in software development? Should I try cold-calling first, to try and get a formal interview?

答:
I wouldn't drop in unannounced. Depending on the company, you'll get as far as the receptionist, who may or may not pass on your information and may or may not pass it to the right person.

At worst, if you do get through to any engineers and/or managers, you'll be quickly dismissed and forgotten about if they're not actively looking for interns.

My suggestion would be:

Set up a github account (or bitbucket, w/e) and post your work there (if you can).

Get involved with projects in your domain of interest and contribute to them via patches

Add your github link to your resume. If your work is of even decent quality, this will set you apart from the rest of the pack.

Search online for companies looking for interns. Apply online. Follow up with a phone call if you don't hear back after a week or so.

Scour meetup.com and similar sites to find C# (or whatever else interests you) events in your area. This is where you do your networking. Bring business cards. Don't have some? Get a few printed up.. You won't be passing out hundreds of them at these meetups.

If you're interested in companies with OS projects, contribute to them. Get on their IRC channels and be active. For example, if you're interested in Adobe, get involved with Phonegap or Flex (even though its future is a little in doubt). If you're interested in Mozilla, get your hands dirty with any one of their multiple projects.

Having an account on github with work can help show that you know (at least the basics of) what you're doing. It also shows that you're familiar with the basics of source control, which is pretty much a requirement in any team setting that isn't horrible.

If you're contributing to other projects, you demonstrate the ability to 1) read/debug someone else's code and 2) work in a team environment. This will set you apart from the rest of the pack by far (you'll also learn a ton of new things working with other people's code). You may also run into professionals in your area working on OS projects.

If you get involved with meetup groups, you become a face to a name/handle to industry professionals. If you don't just sit in the corner twiddling your thumbs, people will take notice. Employers will also sometimes attend meetups in search of interns or full time employees.

Of course, just dropping by companies with work demos and resumes can't hurt, but you can definitely make better use of that time.


问:
What characteristics or features make code maintainable?
I used to think I knew what this was, until I really started thinking about it... "maintainable"... what exactly makes code maintainable?

To me, if code must be maintainable that means we can expect to revisit the code to make some sort of change to it in the future. Code is always "changeable" no matter what state it is in. So does this mean code needs to be easy to change? However, if our code was scalable/extensible, there would be no need to directly change it, because it will "change" (adapt) for free and automatically.

I've also seen code maintainability used interchangeably with coding standards. Using a consistent coding pattern or style, does this really make code more maintainable? More readable and more consistent? Sure, but how does this improve the maintainability?

The more I try to think into this, the more confused I get. Anyone have a proper explanation?

答: When working with other developers who need assistance in understanding what maintainability means, I will ask them, "If you application crashes at 3:00 AM and you get called out of bed to fix it, is this code you would want to look at then?"  You'd be surprised how this can change people's point of view. </p>


问:
How to provide a solid explanation that no two software should have same version number?
We are an outsourcing company. We develop firmware and software for our client. They have a hardware engineer team with whom we, firmware developers, work.

Our client has a strictly defined process to release a firmware. A change in firmware version number has a big impact in that process. When we release a firmware to them for testing, the hardware engineers test it first. Then another SQA test it. Finally, the product is released to customers.

Sometimes, when the change is minor in a new release, our client insist to keep the version number same as the last one. Say, latest release from developers (not released to the customers) had version number 10. Then we found a place for optimization. Or may be slightly change in behavior of the firmware in a very special case which may or may not be visible from outside. When we propose them that we found these places for minor improvements, they insist us to do the changes but keep the version number 10.

We insist that every firmware we release must have distinct version number. We pointed out several common pitfalls if we don't change the firmware version number with every release. They say that they understand why it is necessary. Yet they force us to keep the version number same. Keeping the version number same will help their strictly defined process of releasing firmware to customer end.

We manage the code in our own repository (SVN). We strictly tie a given version number to a given revision number. The version number is stored in the EEPROM of the product our client release. There is defined 2 bytes where the version number is stored. The PC software that reads version number always reads the 2 bytes and display the version number in PC monitor. There is no other way to define version number. They won't change the software that read version number and they won't allocate more memory to introduce another version number that developers can only use.

I'm about to change a firmware and release with the modifications today. I've got another request to keep version number same as previous one. I want to email several unbeatable arguments again what problems we might face if we keep the version number same as previous release.

How can I convince my client not to use same version number?

答:
You can't and you shouldn't.

If you've already done your due diligence in educating them of the pitfalls of not properly versioning the firmware, then any sour spots that they run into sits squarely on their shoulders, not yours.

I'd ensure that for every request asking for an unversioned product that I send them the same e-mail detailing the "unbeatable arguments". This is a cover-your-own-arse step to ensure that you have a paper trail to avoid any he-said-she-said arguments down the road (and make sure you hang onto them permanently for obvious reasons).

If you're the outsourcer and you want a happy client, you fulfill their requests (with that paper trail). It's not your product, it's theirs. If they maintain they want an improperly versioned product, that's their prerogative.


答:
So create and maintain your own internal minor version/build number in the EEPROM.

All you need is one byte; that will give you 256 iterations before your client finally OK's a change to their version number.  When that happens, you can start counting again from zero.

The PC software doesn't have to display the build number.  You can get that using a special outboard utility that you write, if you need it.

Think outside the box.

Title: How to provide a solid explanation that no two software should have same version number?

Body:
We are an outsourcing company. We develop firmware and software for our client. They have a hardware engineer team with whom we, firmware developers, work.

Our client has a strictly defined process to release a firmware. A change in firmware version number has a big impact in that process. When we release a firmware to them for testing, the hardware engineers test it first. Then another SQA test it. Finally, the product is released to customers.

Sometimes, when the change is minor in a new release, our client insist to keep the version number same as the last one. Say, latest release from developers (not released to the customers) had version number 10. Then we found a place for optimization. Or may be slightly change in behavior of the firmware in a very special case which may or may not be visible from outside. When we propose them that we found these places for minor improvements, they insist us to do the changes but keep the version number 10.

We insist that every firmware we release must have distinct version number. We pointed out several common pitfalls if we don't change the firmware version number with every release. They say that they understand why it is necessary. Yet they force us to keep the version number same. Keeping the version number same will help their strictly defined process of releasing firmware to customer end.

We manage the code in our own repository (SVN). We strictly tie a given version number to a given revision number. The version number is stored in the EEPROM of the product our client release. There is defined 2 bytes where the version number is stored. The PC software that reads version number always reads the 2 bytes and display the version number in PC monitor. There is no other way to define version number. They won't change the software that read version number and they won't allocate more memory to introduce another version number that developers can only use.

I'm about to change a firmware and release with the modifications today. I've got another request to keep version number same as previous one. I want to email several unbeatable arguments again what problems we might face if we keep the version number same as previous release.

How can I convince my client not to use same version number?


答:
```<code>1.Write the code for the profile into the User class. I am dismissing this right away.
</code>```

It voilates Single Responsibility principle .Every class should provide only single responsibility.

```<code>2.Create a Profile class and make it a property of the User class.
</code>```

It seems best option for two reasons.

1.satisfies Single responsibility Principle.

2.these two classes are loosly coupled.

```<code>3.Write a User class (with the boiler-plate name, address stuff), write a Profile class, and write a UserProfile class - UserProfile is the union of User and Profile.
</code>```

This is not a good option because User and UserProfile,Profile and UserProfile are tightly coupled.tight coupling is not a good design.

```<code>4.Write a User class and a Profile class that each have an ID property and let the ID act as the intersection. This way the User and Profile are independent and another class, possibly an abstract class with nothing but static methods handles the logic that describes the connection.
</code>```

this is very complex,I strongly feel this complexity is not required.

finally you might want to read Headfirst Object Oriented analysis and design

Title: Best way to handle class relationship

Body:
Take a User class and the idea that a User is to be profiled. I see four ways to handle this:

Write the code for the profile into the User class. I am dismissing this right away.

Create a Profile class and make it a property of the User class.

Write a User class (with the boiler-plate name, address stuff), write a Profile class,
and write a UserProfile class - UserProfile is the union of User and Profile.

Write a User class and a Profile class that each have an ID property and let the ID act
as the intersection. This way the User and Profile are independent and another class,
possibly an abstract class with nothing but static methods handles the logic that
describes the connection.

Choices 3 and 4 each require at least three classes. For this case, which is the best choice? If possible to generalize this, would it generally be better to use one of these possibilities?

Body:
1.Write the code for the profile into the User class. I am dismissing this right away.

It voilates Single Responsibility principle .Every class should provide only single responsibility.

2.Create a Profile class and make it a property of the User class.

It seems best option for two reasons.

1.satisfies Single responsibility Principle.

2.these two classes are loosly coupled.

3.Write a User class (with the boiler-plate name, address stuff), write a Profile class, and write a UserProfile class - UserProfile is the union of User and Profile.

This is not a good option because User and UserProfile,Profile and UserProfile are tightly coupled.tight coupling is not a good design.

4.Write a User class and a Profile class that each have an ID property and let the ID act as the intersection. This way the User and Profile are independent and another class, possibly an abstract class with nothing but static methods handles the logic that describes the connection.

this is very complex,I strongly feel this complexity is not required.

finally you might want to read Headfirst Object Oriented analysis and design


问:
Rendezvous in Ada
In a test I was asked:

What elements present in the general form of a rendezvous are not present in Ada language?

I was a bit stumbled as I thought Ada fully supported rendezvous. Now it seems it doesn't. Can anyone tell me what are those elements?

答:
I don't think there's such a thing as a "generalized form of rendezvous." I think the term originated with Ada.  The information available in the wild about this so called "generalized form of rendezvous" is seemingly nonexistent.

See Limitations of Ada's Concurrent Programming Facilities, and this Synchronous Rendezvous link on Wikipedia which redirects to Barrier (Computer Science).

Title: Rendezvous in Ada


问:
How to choose a language, when taking in account the community it includes?
I was reading the following article: Great Hackers

The following part grabbed my attention:

"When you choose a language, you're also choosing a community. The programmers you'll be able to hire to work on a Java project won't be as smart as the ones you could get to work on a project written in Python. And the quality of your hackers probably matters more than the language you choose. Though, frankly, the fact that good hackers prefer Python to Java should tell you something about the relative merits of those languages."

I would like to apply his advice on a commercial web application I am building (I am a strong believer in culture and community), yet this article was written in 2004, and python has increased in popularity in the recent years.

How can I decided a language when taking in consideration its community, rather than the popularity? Any recommendations?

Is there any language community that show dedication and passion for developing, rather than learning a language to get a Job and a paycheck?

答: If you're hiring locally, go to meetup groups for software developers who specialize in the languages that you're choosing from. The best way to check out the "community" is to do field research.</p>


问:
How to store record statuses (like pending, complete, draft, cancelled...)
Quite a lot of applications require records in their tables to have a status, such as 'complete', 'draft', 'cancelled'. What's the best way of storing these statuses? To illustrate what i'm getting at here is a *very short) example.

I have a simple Blog application and each post has a status one of: published, draft or pending.

The way i see it there are 2 ways to model this in the database.

The Post table has a text field that includes the status text.

The Post table has a status field that contains the ID of a record in the PostStatus table

The Blog example here is a very simple example. Where an enum (if supported) might suffice. However i'd like responses to the question to take into account that the list of statuses could change at any time, so more could be added or removed.

Can anyone explain the advantages/disadvantages of each?

Cheers!

My initial optnion on this is that its better to use another table and look up the status as its better for normalisation and i've always been taught that normalisation is good for databases

答:
Yes, you should go with option 2, having a PostStatus table.

Apart from all the advantages mentioned in other answers.

Keeping in mind that the statuses needs to be added or removed, you can have an "enabled" column in the PostStatus table, so if the status is removed mark the "enabled" column as "N", that way you will be able to add or remove statuses and also the existing records will stay without issues.


问:
Should I use non-standard tags in a HTML page for highlighting words?
I would like to know if it's a good practice or legal to use non-standard tags in an HTML page for certain custom purposes.

For example:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam
  consequat, felis sit amet suscipit laoreet, nisi arcu accumsan arcu,
  vel pulvinar odio magna suscipit mi.

I want to highlight "consectetur adipiscing elit" as important and "nisi arcu accumsan arcu" as highlighted.

So in the HTML I would put:

Lorem ipsum dolor sit amet, <important>consectetur adipiscing
  elit</important>. Nullam consequat, felis sit amet suscipit laoreet,
  <highlighted>nisi arcu accumsan arcu</highlighted>, vel pulvinar odio
  magna suscipit mi.

and in the CSS:

```<code>important {
 background: red
 color: white;
}

highlighted {
 background: yellow;
 color: black;
}
</code>```

However, since these are not valid HTML tags, is this ok?

答:
There are quite a few answers here explaining why you should never create your own custom tags. Arguably, they are all incorrect.

WHATWG's analysis of custom tags concludes that they are acceptable, standards compliant (since the handling of unrecognized tags is well defined) and more accessible than, for instance, styling a generic div.

<x-accordion></x-accordion> is no worse than

 in every mechanical sense. In the absence of
  definition for "x-accordion" (or component model support), both mean
  the same thing, both can be styled in the same way. One is
  HTMLUnknownElement, the other is HTMLDivElement, and their API surface
  is identical.

What you should do, which the OP did not, is prefix all custom tags with 'x-' per convention. This clearly indicates that you intend this tag to be local to your document and avoids conflicts with future spec elements.

Some argue that since certain popular browsers do not handle custom tags in a standards compliant way, you should not use them. However, the behavior of non-compliant browsers is its own problem and preferably will not coerce you into writing non-semantic markup. There are both Javascript and non-Javascript solutions to that problem, which should only be applied for those non-compliant browsers you wish specifically to support.

All that said, if a tag exists in the spec () which clearly covers the semantic meaning of the tag you've created (<highlight>), then it is certainly preferable to use the existing tag.

Body:
There are quite a few answers here explaining why you should never create your own custom tags. Arguably, they are all incorrect.

WHATWG's analysis of custom tags concludes that they are acceptable, standards compliant (since the handling of unrecognized tags is well defined) and more accessible than, for instance, styling a generic div.

<x-accordion></x-accordion> is no worse than <div
  class="accordion"></div> in every mechanical sense. In the absence of
  definition for "x-accordion" (or component model support), both mean
  the same thing, both can be styled in the same way. One is
  HTMLUnknownElement, the other is HTMLDivElement, and their API surface
  is identical.

What you should do, which the OP did not, is prefix all custom tags with 'x-' per convention. This clearly indicates that you intend this tag to be local to your document and avoids conflicts with future spec elements.

Some argue that since certain popular browsers do not handle custom tags in a standards compliant way, you should not use them. However, the behavior of non-compliant browsers is its own problem and preferably will not coerce you into writing non-semantic markup. There are both Javascript and non-Javascript solutions to that problem, which should only be applied for those non-compliant browsers you wish specifically to support.

All that said, if a tag exists in the spec (<mark>) which clearly covers the semantic meaning of the tag you've created (<highlight>), then it is certainly preferable to use the existing tag.


问:
Is it possible to use C++ with the .NET framework?
I've read many comments about GUI programming, in both, C# and C++. And I noticed that Microsoft's .NET framework is powerful for GUI programming. So is it possible to use C++ and .NET framework?

I think it will be a great combination since C++ is powerful language, and .NET framework is preferred for GUI programming on Windows, as I've read. Is it possible to write the GUI in C# and the functionality in C++?

答:
The C++/CLI angle has been covered by plenty of answers so far, but another way of doing this is to use PInvoke. This allows C# programs to call functions contained in dlls that were written in C++. The advantage of PInvoke is that your dll is totally agnostic about the fact that it will be called from .Net. This means you can call dll's for which you have no source code, and even if you did, you wouldn't have to recompile the source code using the /clr option. This means you can use this dll with other C++ programs, as well as C# programs. There are some fantastic C/C++ libraries out there: PInvoke allows you to take advantage of these. Sometimes Win32 libraries provide functions that just aren't available in .Net: PInvoke allows you to use them.

One of the trickiest parts of using PInvoke is knowing how to convert the unmanaged signature to a managed signature. But there is a cheatsheet to help with that.

ContentLicense: CC BY-SA 4.0


问:
Selective mutual exclusion in Dining Philosophers and Readers and Writers problem
I've been reading about selective mutual exclusion (SME). The idea I got is that if a process competes for its resources against a subset of all the other process instead of competing with all the other processes then I'm facing a SME problem.

1) Can you confirm my definition is right?

Now, the dining philosophers problem is a classic example of this (SME by proximity)

2) In the distributed solution (in which each philosopher competes for both forks against two other philosophers), if instead of 5 philosophers, there were 3 of them, would it still be a SME problem? (I think not, because each philosopher will be competing with all of the others)

3) And in the centralized "conductor" solution, having 5 philosophers, would it still be a SME problem? (I think it would, because although all processes are competing to get to the waiter, each philosopher is only competing with two of the other to get both specified forks)

Finally, in the readers and writers problem (SME by process type)

4) If only 1 reader and 1 writer were allowed, would it still be a SME problem? (I think not, because actually every process will be competing with all the others)

答:
1) Can you confirm my definition is right?

Yes. Three or four references I found by searching the web for concurrency "selective mutual exclusion" seem to comply with your understanding: "if a process competes for its resources against a subset of all the other process instead of competing with all the other processes"

2) In the distributed solution (in which each philosopher competes for both forks against two other philosophers), if instead of 5 philosophers, there were 3 of them, would it still be a SME problem? (I think not, because each philosopher will be competing with all of the others)

Most likely it will be a SME, or some gray area flavor of it. Think of the fork laying between "first" and "second" philosophers - "third" philosopher doesn't use it and because of that we've got "subset competition", limited only to first and second one

3) And in the centralized "conductor" solution, having 5 philosophers, would it still be a SME problem? (I think it would, because although all processes are competing to get to the waiter, each philosopher is only competing with two of the other to get both specified forks)

As long as you define forks as shared resources, it will still be SME - because "first" and "third" philosophers won't have shared resources (forks) to compete for.

Though, if you define waiter as a resource (in programming terms this may be viewed as a singleton with contended access - which would be not too great a design I think) - then there would be no SME since all the philosophers would compete for access to that single shared resource.

4) If only 1 reader and 1 writer were allowed, would it still be a SME problem? (I think not, because actually every process will be competing with all the others)

It would not be SME because in case like above, set of processes consists of precisely two (reader and writer), and both need mutually exclusive access to resource: reader can't read while writer writes and writer can't write while reader reads.

For SME to occur in readers and writers, there should be 1) more than one reader - to make a subset that doesn't compete in between itself and 2) at least one writer - to establish a need in mutual exclusion between read and write accesses

Bottom line is, to find out about SME one needs to precisely define set of processes and set of resources. And have a solid understanding of mutex of course.

Another point worth keeping in mind is that the purpose of this high-brow looking concept is quite practical indeed. Knowing when some processes have no need to compete for particular resource gives one an opportunity to reduce lock contention by using finer grained locks.

Readers-writers problem is a good example here. If you find out that there are, say, ten readers heavily fighting for an access to some resource when there is no real need in that, addressing this may make your application about ten times faster, go figure.


问:
Query language for JSON
I have a server which is returning very big JSON message and my client application is only dependent on part of this response. Client application needs to check if "xyz" property exist in JSON message and depending on the result run a specific usecase.

For this requirement converting the whole JSON message to object sounds bit expensive to me and hence this question.

Is there a standard JSON query language like one we have for XML? If yes what are best know implementation of this query language in java.

FYI : Changing or adding new service on server side is not an option.

答:
Why not just use javascript? (JSON is Javascript Object Notation after all). You then won't have to parse or manipulate the JSON.

EDIT Have a look at http://json.org/java

For this requirement converting the whole JSON message to object
  sounds bit expensive to me and hence this question.

It isn't. Deserializing an object is cheap (bench test it yourself). Talking to the external API will be an order of magnitude more expensive. You could directly manipulate the string which might be slightly faster but you would risk bugs, reduce extensibility and reduce readability. A high cost.

Title: Query language for JSON


答:
Do not forget about the most flexible and simple option, a typical for Unix world but, for some reason, not that common in Windows: splitting GUI and logic into different processes, communicating via any reasonable form of RPC (e.g., even a pipe should work). Preferably with a simple, human-readable text protocol.

This way you can implement you GUI (or various GUIs) with any technologies you fancy, and build up logic components from whatever suits the need better - C++, scripts, whatever else.

I'm not aware of any reasonable advantages of a monolithic design approach from the Windows world.

Title: Is it possible to use C++ with the .NET framework?

Body:
I've read many comments about GUI programming, in both, C# and C++. And I noticed that Microsoft's .NET framework is powerful for GUI programming. So is it possible to use C++ and .NET framework?

I think it will be a great combination since C++ is powerful language, and .NET framework is preferred for GUI programming on Windows, as I've read. Is it possible to write the GUI in C# and the functionality in C++?


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

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

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

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

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

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

答:
Welcome to creative developers circus.

Instead of respecting all 'legal/reasonable' way to code at the beginning,

 try intuition, above all if it is important and new for you and if no sample around looks like you want:

- Write with your instinct, from things you already know, not with your mental and imagination.

- And stop.

- Take a magnifying glass and inspect all words you write :
You write "text" because "text" is near to String, but "verb", "adjective" or something more accurate is needed, read again and adjust method with new sense

 ... or, you wrote a piece of code thinking about future? remove it

- Correct, do other task (sport, culture or other things outside business),
 come back and read again.

- All fit well, pass to UML

- Correct, do other task, come back and read again.

- All fit well, pass to TDD

- Now all is correct, good

- Try benchmark to point out things to be optimized, do it.

What's appear :

- you wrote a code respecting all rules

- you get an experience, a new way for work,

- something change in your mind, you'll never afraid by new configuration.

And now, if you see an UML looking like the above, you will be able to say
"Boss, I begin by TDD for this...."

it is another new thing ?

"Boss, I would try something before decide the way I'll code.."

Best regards from PARIS

Claude


答:
Maintainable is - to some extent - subjective. However, it's code that is written less with the writer's ego in mind and more with the recognition that at some point, someone is likely to have to revisit this code and modify it for reasons currently undefined. Very few codebases stay static for years on end.

What one person considers maintainable may be very different to another's view in some respects but some qualities I think it should include are:

no hidden traps for the unwary in the future

logic and rationale should be documented

it should conform to some documented local standards

We have discussions here on the subject of documentation and commentary from time to time.

Code whose remit and logic is easy to follow should for the most part be easy to update as required with some caveats on original design considerations (which should be but ime never are documented adequately).

Title: What characteristics or features make code maintainable?

Body:
I used to think I knew what this was, until I really started thinking about it... "maintainable"... what exactly makes code maintainable?

To me, if code must be maintainable that means we can expect to revisit the code to make some sort of change to it in the future. Code is always "changeable" no matter what state it is in. So does this mean code needs to be easy to change? However, if our code was scalable/extensible, there would be no need to directly change it, because it will "change" (adapt) for free and automatically.

I've also seen code maintainability used interchangeably with coding standards. Using a consistent coding pattern or style, does this really make code more maintainable? More readable and more consistent? Sure, but how does this improve the maintainability?

The more I try to think into this, the more confused I get. Anyone have a proper explanation?


问:
How do you stop yourself from bringing work home?
Programming is a highly cerebral job, and one of the biggest problems I have is bringing my work home with me. It's so easy to do: whenever I get the chance to think, my mind naturally wanders to work-related matters. I find so many of the other things in my day rather mentally unstimulating and as they say, nature abhors a vacuum. Unfortunately, constantly thinking about work is stressing me out and I can't seem to just flip that switch at the end of the day. It's been causing me quite a bit of insomnia.

To make matters worse, nearly all of my friends are co-workers, and many of our conversations do very little to make me forget about the week. They're fun people to be around generally, and once we've had our bitch-fest we all stop talking about work, but suffice it to say it does little to encourage me to forget about work-related matters.

So what can I do to leave my programming projects behind me at the end of the day? Or failing that, what type of mentally stimulating activities could I do to occupy my non-work hours with (that are non-stressful and don't involve mind-altering drugs)?

答:
Between pleasure and addiction

No ready made response, it is your innermost problem.

As I am more than five Chinese buffalo, I crossed this situation.

You have to be able to say no, to the other, sometime, but to your ego, always.

No work at home : cut internet connection, write your ideas on paper, no more than ideas.

this evening, THIS EVENING, try this, a twelve hours world without computers.

do this ... or not, so you will know if you are able to have pleasure to go to work in morning,

or an addict which need help to understand how and why ego lure yourself.

HTH
Claude


问:
Shortcomings of using dynamic types in C#
I have been recently studying more on the dynamic types in C#. With some examples I understood once the code is compiled, it does not need to be recompiled again but can be executed directly.

I feel the flexibility provided by the keyword to actually be able to change data type at will is a great advantage.

Question,

Are there any specific shortcomings apart from wrong dynamic method calls which throw run time exceptions which developers must know before starting the implementation.

答:
The main shortcoming is that you throw away one of the main properties (not necessarily advantages) of C# - that it is statically typed (and for most part type safe).

The problem with dynamic typing is that it often hides bugs that would be otherwise revealed during compilation. Such bug then only manifests on run-time, which of course makes it much harder to detect.

There are IMO very few reasons to use dynamic typing in C#, the main one being collaboration with dynamically typed languages (which is AFAIK the reason dynamic was introduced in the first place).

If you want to do fully dynamically typed programming, you should look at some language which is designed to be dynamic, not hack C# to be dynamic. You can use for example IronPython if you want to use .Net libraries


问:
The Joel Test's equivalent for measuring a programmer
I understand that to measure a project or code, we can use The Joel Test, but is there any simple standard test (like The Joel Test) that is able to measure and filter how good a programmer is?

My plan is to have this test as a quick filter first before going to a more detail test.

答:
There is the programmer competency matrix.

As with the Joel test it's just a vague guide. The only way to properly assess a programmer is to ask good programmers who have worked with them.


答:
The Joel Test is just an informal baseline check to quickly judge whether a place has good working conditions for programmers. Even if it scores a perfect 10, it can still be a hell-hole that is going to go bankrupt six months down the road. A low score is an indication of something not quite right, and makes for excellent interview questions ("You're not currently using source control; are there any plans to do so in the future?"), and the answers might be such that you'd accept the job despite a low Joel score.

The Joel Test is not a 'standard' test either; it's just a checklist Joel Spolsky posted on his blog.

As far as 'measuring' the quality of a programmer goes; unfortunately, the really important skills and qualities of a good programmer are hard or impossible to quantify, so there is no replacement for thorough human evaluation. You can weed out the completely clueless candidates quite easily though, using a very simple programming task - ideally, something that involves recursion, tree structures or pointers (a programmer who doesn't 'get' these is unlikely to be of much use). For those who pass this test, you'll have to evaluate skills manually: read code they wrote, test drive applications they wrote, give them more programming tasks (both design and implementation), watch them work, talk to them, see if you can spark a professional discussion. If you're looking for a specialist / language guru, you might also want to ask a few knowledge questions, but for a general programming candidate I wouldn't bother.

Title: The Joel Test's equivalent for measuring a programmer

Body:
I understand that to measure a project or code, we can use The Joel Test, but is there any simple standard test (like The Joel Test) that is able to measure and filter how good a programmer is?

My plan is to have this test as a quick filter first before going to a more detail test.


问:
Why is naming a table's Primary Key column "Id" considered bad practice?
My t-sql teacher told us that naming our PK column "Id" is considered bad practice without any further explanations.

Why is naming a table PK column "Id" is considered bad practice?

答:
I always use 'id' as the primary column name for every table simply because it's the convention of the frameworks I use (Ruby on Rails, CakePHP), so I don't have to override it all the time.

That won't beat academic reasons for me.


答:
I'm not sure what kind of shortcomings are you looking for, but if you want to know about features that work with static typing, but not with dynamic, there are few:

Extensions methods don't work. This is probably the biggest one. If you have dynamic collection, you can't use code like collection.Distinct(). That's because available extension methods depend on namespace usings and the DLR has no way of knowing them.

As a workaround, you can either invoke the method as if it was normal static method: Enumerable.Distinct(collection). Or you can change the type of the collection to something like IEnumerable<dynamic>.

foreach requires IEnumerable. In normal C#, foreach is pattern-based. That is, it doesn't require any specific interface, just a GetEnumerator() method that returns suitable object. If you use foreach on dynamic, the implementation of IEnumerable is required. But since the reason for this behavior is that C# 1.0 didn't have generics, this "shortcoming" is pretty much irrelevant.

Title: Shortcomings of using dynamic types in C#

Body:
I have been recently studying more on the dynamic types in C#. With some examples I understood once the code is compiled, it does not need to be recompiled again but can be executed directly.

I feel the flexibility provided by the keyword to actually be able to change data type at will is a great advantage.

Question,

Are there any specific shortcomings apart from wrong dynamic method calls which throw run time exceptions which developers must know before starting the implementation.


问:
Who should participate in time estimation?
In an IT project:

Who should participate in time estimation? Developer, team leader, scrum master and etc?

Whose vote should be counted most?

答:
In my experience, estimations tend to be done by the person who will most likely do the task itself. SCRUM teams should strive to be cross-functional, but after a while, certain types of tasks are usually done by the same people.

Of vital importance is to get an accept from the team on all estimates. If a developer feels they own an estimate, they will work to meet it. If the developers get handed an estimate that they did not do themselves and had no input or influence over, they will not feel the same level of responsibility to it and overdrafts will be explained away with "I told you it would take longer".

ContentLicense: CC BY-SA 2.5


问:
Project estimation with increasing requirements
Making a project estimation with given a requirements set is one thing.

But, what happens when the user suddenly starts changing them on the fly and starts adding new requirements to the already defined set? And even goes to an extent to be mad about why the project is not finished in the originally planned time frame.

How should I deal with these situations? Proposing some methodologies and readings could be helpful.

答:
Think of your project as a triangle (a PM buddy of mine actually made a physical triangle he used for added effect). The edges are called time, cost and scope. You tell your client that he can have control of 2 sides, but you (responsible for delivery) must have control of at least one.

So, you can do it fast and cheap - but then you have to have the power to cut scope.

Or, you can get more features, but that will take either more time or more money.

Read more at http://en.wikipedia.org/wiki/Project_triangle


问:
What does your Lisp workflow look like?
I'm learning Lisp at the moment, coming from a language progression that is Locomotive BASIC -> Z80 Assembler -> Pascal -> C -> Perl -> C# -> Ruby.  My approach is to simultaneously:

write a simple web-scraper using SBCL, QuickLisp, closure-html, and drakma

watch the SICP lectures

I think this is working well; I'm developing good 'Lisp goggles', in that I can now read Lisp reasonably easily.  I'm also getting a feel for how the Lisp ecosystem works, e.g. Quicklisp for dependencies.

What I'm really missing, though, is a sense of how a seasoned Lisper actually works.

When I'm coding for .NET, I have Visual Studio set up with ReSharper and VisualSVN.  I write tests, I implement, I refactor, I commit.  Then when I'm done enough of that to complete a story, I write some AUATs.  Then I kick off a Release build on TeamCity to push the new functionality out to the customer for testing & hopefully approval.  If it's an app that needs an installer, I use either WiX or InnoSetup, obviously building the installer through the CI system.

So, my question is: as an experienced Lisper, what does your workflow look like?  Do you work mostly in the REPL, or in the editor?  How do you do unit tests?  Continuous integration?  Packaging & deployment?  When you sit down at your desk, steaming mug of coffee to one side and a framed photo of John McCarthy to the other, what is it that you do?

Currently, I feel like I am getting to grips with Lisp coding, but not Lisp development ...

答:
To supplement the other answers, I do a combination of the "Think hard about the problem, then write down the solution" kind of development and "Start with a repl, and beat your program into shape iteratively" style. Its usually in the middle. What i do is I start with a general idea of what I want my program to look like, and then I start writing it, trying to acquire new knowledge about the problem domain as i go, in order to revise my approach. In practice that means that I do a lot of experimentation and write a lot of trow away code. I try different approaches and I can switch direction very fast. Lisp is good for this kind of development. That's why I don't like TDD so much, I have to know what I want to do first, in order to to TDD effectively.

Another important thing I try to do is think more about the protocol between the different parts of a program. Unlike other OO languages, In Common Lisp CLOS is focused more on the concept of a Generic function, IOW methods live outside of classes, and they are the focus of development. Sometimes i just start with a set of GFs defining the protocol i want, I write a simple implementation and use it to flesh out the protocol, before I write a real implementation. Say I'm writing a layer that stores a bunch of blog posts, i might have a set of GFs that define how blog posts are created, edited and searched, and I would write a simple implementation that saves blog posts in a list in memory, and after I'm happy with my protocol, i write an implementation that saves blog posts to a database, or writes them to files.

Lisp makes it so easy to change direction and do a different approach when you know that your current solution is suboptimal that I try to maximize on that.

Also important point: Use your environment to the fullest, learn about using different compilation settings to compile your code with more debugging information, take advantage of the fact that lisp can be both compiled and interpreted. Use lisps introspective facilities, such as the MOP, use slimes features to look up documentation, use the inspector to look inside objects, consult the hyperspec regularly, treat your system more like an OS, than a static compiler for your code, it's much more powerful than that.

For a beginner, lisp isn't that much of a win over python and ruby, but as you get more experienced with it, you get enormous wins over lesser environments.

Most important, you have to have fun and love this language, sometimes its just to easy to get discouraged and go use the currently popular blub languages. If you stick with lisp, it will repay you.

Title: What does your Lisp workflow look like?


问:
Deployment Tools that Integrate with TFS?
So I have this issue.  The Operations team where I work has taken over TFS because they are using MS Build to build and deploy code to production servers.  As a result developers have lost A LOT of functionality from TFS (see earlier question.)

Essentially the operations team has taken owner ship of Trunk in order to manage their deployments. The development cycle thus goes something like this:

Request Operations Team to create a Branch from Main for development work.

Perform Development work on development branch.

Merge from Trunk to development branch prior to release (basically make sure that the development branch has all of the latest changes)

Request Operations Team merge to Trunk from development branch (Developers do not have permissions to do this) -> this request will cause Operations to not only to merge to Trunk but also to deploy to the development environment.

Perform integration Testing, fix defects found in development branch.

Repeat steps 3 - 6 as necessary.

Request Operations Team merge from Trunk to a QA branch (there is only ONE on-going QA branch per project) -> this request will cause a deployment into the QA environment (An MS Build template is used to compile the code from QA branch and then deploy to QA servers)

QA tests, fix defects found in development branch.

Repeat steps 3 - 8 as necessary.

Request Operations Team merge from QA branch into PROD branch (there is only ONE on-going PROD branch per project) -> this request will caus a deployment into the PROD environment (Again an MS Build template is used to re-compile the code from PROD branch and then deploy to PROD servers)

As a result of the Ops team using an MS Build template to deploy to Production servers, the Development team has now lost the "Builders" role.  We cannot create our own MS Build templates, we cannot create or edit a Build definition, and we cannot queue a build -- Even in the Development Environment -- because the Build process runs under a service account which has access to Production servers (since it is use to deploy to production servers).

Besides the removal of TFS permissions, I have some issues with this process:

The assemblies which were compiled and tested in the QA environment are not the assemblies being deployed into the Production environment.  Because the MS Build process is being used to deploy to production, code is recompiled and deployed from the Production branch.  In theory, the resulting assemblies should be the same, however this is depenent upon a) the operations team (who are not developers) properly merging the code from the QA branch to the PROD branch (human error potential) b) the build environment not changing in such a way as to affect the way assemblies are compiled (since this is primarily .Net improbable but not impossible)

Since there is only ONE QA branch, if I have a production issue which needs a "hot fix" after other work has been merged to QA, I have to wait for Ops to rollback changes to the QA branch, merge my changes in and perform the build and then HOPE that operations correctly performed the rollback and merge operations on the QA branch in order to get my "hot fix" into the QA environment.

Many of my projects have multiple outputs (e.g. a web-application and a windows service).  Often I may want to only deploy one or the other.  But if I upgrade one to a new version, I no longer have a PROD branch which represents the one I didn't upgrade.

Operations team has already demonstrated that merge operations are not being performed correctly: Following a recent merge from Development to Trunk I performed a compare on the two branches and they were different.

Because code is recompiled for each environment we cannot use automated versioning, or make use of the "build quality" features of TFS.

Essentially what it comes down to is the Operations Team has attached themselves to using MS Build for deployments and as such have adopted a rediculous Source Control branching and merging strategy to support using MS Build for managing deployments. (I see no benefit in having a QA and PROD branch other than to support MS Build based deployments).

What I am trying to do is convince the powers that be and the operations team that what we're doing is a bad practice, and also give them an alternative deployment strategy.  What I need for this is a Deployment tool that integrates with TFS (e.g. it will show a list of Builds that have a specified "build quality" level (depending upon the environment being deployed into) as a "deployment source" and allow then to maintain a list of "deployment targets" so that at deployment time, they simply pick the build (source) and the target and click the "GO!" button.

A proper deployment tool will hopefully eliminate their dependence upon MS Build, allow them to remove access to QA and Production servers from the MS Build process, follow a more sane approach to branching and merging (e.g adopt a "branch per release" best practices strategy) and restore to the developers the TFS permissions which were revoked to support this rediculous process.

答:
We're using Visual Build Pro. It allows you to do what you're talking about (if I'm following what you're saying correctly). We use it to deploy builds of both desktop apps and web services to test, user acceptance and production environments. We can select the TFS branch we want to build and where to deploy it to. Click the 'run' button, answer some dialogs, and you're done.

The trick with it is setting up the automation scripts. I didn't create the scripts we're using, they were done by a predecessor, however, it doesn't look that difficult to figure out.


问:
Why did Google develop a cross-compiler from Java to JavaScript?
Google developed a cross-compiler from Java to JavaScript. Why did they do this? Does this mean that JavaScript is not good enought for developing advanced web apps?</p>

答: Because at the time, people didn't see any value in learning JavaScript, JavaScript lacked a large implementation base (though it's got the largest install base out there!), and in general Java programmers seem to prefer programming in Java more than anything else.</p>


问:
Why use try … finally without a catch clause?
The classical way to program is with try ... catch. When is it appropriate to use try without catch?

In Python the following appears legal and can make sense:

```<code>try:
  #do work
finally:
  #do something unconditional
</code>```

However, the code didn't catch anything. Similarly one could think in Java it would be as follows:

```<code>try {
    //for example try to get a database connection
}
finally {
  //closeConnection(connection)
}
</code>```

It looks good and suddenly I don't have to worry about exception types, etc. If this is good practice, when is it good practice? Alternatively, what are the reasons why this is not good practice or not legal? (I didn't compile the source. I'm asking about it as it could be a syntax error for Java. I checked that the Python surely compiles.)

A related problem I've run into is this: I continue writing the function/method, at the end of which it must return something. However, it may be in a place which should not be reached and must be a return point. So, even if I handle the exceptions above, I'm still returning NULL or an empty string at some point in the code which should not be reached, often the end of the method/function. I've always managed to restructure the code so that it doesn't have to return NULL, since that absolutely appears to look like less than good practice.

答:
@yfeldblum has the correct answer: try-finally without a catch statement should usually be replaced with an appropriate language construct.

In C++, it's using RAII and constructors/destructors; in Python it's a with statement; and in C#, it's a using statement.

These are nearly always more elegant because the initialization and finalization code are in one place (the abstracted object) rather than in two places.


答:
They provide part of the answer on this page:

http://code.google.com/webtoolkit/makinggwtbetter.html

To start with the basics, why does GWT exist in the first place? The
  short answer is that GWT exists to make the web better for users.
  We've infused a slightly longer answer into our mission statement:

GWT's mission is to radically improve the web experience for users by
    enabling developers to use existing Java tools to build no-compromise
    AJAX for any modern browser.

In other words, it was a way of getting Java developers to write Ajax-heavy apps.

Title: Why did Google develop a cross-compiler from Java to JavaScript?

Body: Google developed a cross-compiler from Java to JavaScript. Why did they do this? Does this mean that JavaScript is not good enought for developing advanced web apps?</p>


答:
Java is a compiled language with a variety of mature tools and a large developer community. It has types, objects, exceptions, frameworks, great tools, community support, etc.

JavaScript has all of these things too - except for the compilation.

If you could compile your code, thoroughly test it in Java and then translate it to something the client can run (i.e. JavaScript - I'm guessing VBScript had no chance here) then it'll reduce the overall development costs. Developing large, complex AJAX applications like GMail is expensive.

There are many "write in one language, run in another" techniques around - but this was a good one.

UPDATE

To clarify my point further, JavaScript is an interpreted language where the parser will check syntax, but not pick up semantic errors such as:

```<code>function f(x) {
  g(y);
}
</code>```

where neither 'g()' nor 'y' exist. This will only be picked up at runtime.

There are many JavaScript Engines such as V8, Nitro (JavaScriptCore) and Spider/Jaeger/TraceMonkey which will do a fantastic job of parsing and running the parsed code as fast as possible (perhaps by emitting machine code), but won't catch the semantic errors that a full compilation process would. This is often because scripts are delivered to the web browser independently of each other and the JavaScript Engine doesn't have the whole story until all of the required scripts have been downloaded/cached, the DOM has been initialised and any dynamically-generated scripts have been triggered. So the engine normally cannot have the whole source until quite late in the download and render process.

A full compiler will highlight the above code snippet as an error, which is one motivation to use a compiled language, verify correctness, perform unit tests and then use reflection or decompilation to generate the verified-correct JavaScript to run on the client.

Body:
Java is a compiled language with a variety of mature tools and a large developer community. It has types, objects, exceptions, frameworks, great tools, community support, etc.

JavaScript has all of these things too - except for the compilation.

If you could compile your code, thoroughly test it in Java and then translate it to something the client can run (i.e. JavaScript - I'm guessing VBScript had no chance here) then it'll reduce the overall development costs. Developing large, complex AJAX applications like GMail is expensive.

There are many "write in one language, run in another" techniques around - but this was a good one.

UPDATE

To clarify my point further, JavaScript is an interpreted language where the parser will check syntax, but not pick up semantic errors such as:

function f(x) {
  g(y);
}

where neither 'g()' nor 'y' exist. This will only be picked up at runtime.

There are many JavaScript Engines such as V8, Nitro (JavaScriptCore) and Spider/Jaeger/TraceMonkey which will do a fantastic job of parsing and running the parsed code as fast as possible (perhaps by emitting machine code), but won't catch the semantic errors that a full compilation process would. This is often because scripts are delivered to the web browser independently of each other and the JavaScript Engine doesn't have the whole story until all of the required scripts have been downloaded/cached, the DOM has been initialised and any dynamically-generated scripts have been triggered. So the engine normally cannot have the whole source until quite late in the download and render process.

A full compiler will highlight the above code snippet as an error, which is one motivation to use a compiled language, verify correctness, perform unit tests and then use reflection or decompilation to generate the verified-correct JavaScript to run on the client.


问:
Rendezvous in Ada
In a test I was asked:

What elements present in the general form of a rendezvous are not present in Ada language?

I was a bit stumbled as I thought Ada fully supported rendezvous. Now it seems it doesn't. Can anyone tell me what are those elements?

答:
The Ada rendezvous concept is based on the CSP rendezvous, so reading up on CSP may be a worthwhile.

An Ada rendezvous appears to provide more than a CSP rendezvous, so what you really lose out on is the ability to easily reason formally about the behaviour.

Incidentally, at university we were actually taught CSP using Occam syntax, since we had been taught Occam in our first year. We were also taught the Z notation along with Miranda (a functional language which was the precursor to Haskell).

Together, these provided a solid grounding in formal reasoning for software systems, both distributed and non-distributed.

Title: Rendezvous in Ada


答:
An example where try... finally without a catch clause is appropriate (and even more, idiomatic) in Java is usage of Lock in concurrent utilities locks package.

Here's how it is explained and justified in API documentation (bold font in quote is mine):

...The absence of block-structured locking removes the automatic release
  of locks that occurs with synchronized methods and statements. In most
  cases, the following idiom should be used:

```<code> Lock l = ...;
 l.lock();
 try {
     // access the resource protected by this lock
 } finally {
     l.unlock();
 }
</code>```

When locking and unlocking occur in different scopes, care must be
  taken to ensure that all code that is executed while the lock is held
  is protected by try-finally or try-catch to ensure that the lock is
  released when necessary.

Title: Why use try … finally without a catch clause?

Body:
The classical way to program is with try ... catch. When is it appropriate to use try without catch?

In Python the following appears legal and can make sense:

```<code>try:
  #do work
finally:
  #do something unconditional
</code>```

However, the code didn't catch anything. Similarly one could think in Java it would be as follows:

```<code>try {
    //for example try to get a database connection
}
finally {
  //closeConnection(connection)
}
</code>```

It looks good and suddenly I don't have to worry about exception types, etc. If this is good practice, when is it good practice? Alternatively, what are the reasons why this is not good practice or not legal? (I didn't compile the source. I'm asking about it as it could be a syntax error for Java. I checked that the Python surely compiles.)

A related problem I've run into is this: I continue writing the function/method, at the end of which it must return something. However, it may be in a place which should not be reached and must be a return point. So, even if I handle the exceptions above, I'm still returning NULL or an empty string at some point in the code which should not be reached, often the end of the method/function. I've always managed to restructure the code so that it doesn't have to return NULL, since that absolutely appears to look like less than good practice.

Body:
An example where try... finally without a catch clause is appropriate (and even more, idiomatic) in Java is usage of Lock in concurrent utilities locks package.

Here's how it is explained and justified in API documentation (bold font in quote is mine):

...The absence of block-structured locking removes the automatic release
  of locks that occurs with synchronized methods and statements. In most
  cases, the following idiom should be used:

 Lock l = ...;
 l.lock();
 try {
     // access the resource protected by this lock
 } finally {
     l.unlock();
 }

When locking and unlocking occur in different scopes, care must be
  taken to ensure that all code that is executed while the lock is held
  is protected by try-finally or try-catch to ensure that the lock is
  released when necessary.


答:
Do you maintain/support multiple releases? If not why use a branch per release strategy? The one flaw I see in your current branching strategy is the hotfix scenario you mentioned. If you have a hotfix that needs to be applied after work on the next release has commenced, there is no way to deploy that hotfix independent of the new release. Well there is a way, but it takes a lot of discipline to isolate the code that applies only to the hotfix from the code for the new release.

You are also correct when you say that rebuilding the code for the various environments can potentially create problems. Check out Continuous Delivery for some ideas on addressing some of your very concerns.

To answer your question about a separated Build/Deployment tool, Paul Stovell is working on a product called Octopus That uses the Nuget system to do just what you want.

Title: Deployment Tools that Integrate with TFS?

Body:
So I have this issue.  The Operations team where I work has taken over TFS because they are using MS Build to build and deploy code to production servers.  As a result developers have lost A LOT of functionality from TFS (see earlier question.)

Essentially the operations team has taken owner ship of Trunk in order to manage their deployments. The development cycle thus goes something like this:

Request Operations Team to create a Branch from Main for development work.

Perform Development work on development branch.

Merge from Trunk to development branch prior to release (basically make sure that the development branch has all of the latest changes)

Request Operations Team merge to Trunk from development branch (Developers do not have permissions to do this) -> this request will cause Operations to not only to merge to Trunk but also to deploy to the development environment.

Perform integration Testing, fix defects found in development branch.

Repeat steps 3 - 6 as necessary.

Request Operations Team merge from Trunk to a QA branch (there is only ONE on-going QA branch per project) -> this request will cause a deployment into the QA environment (An MS Build template is used to compile the code from QA branch and then deploy to QA servers)

QA tests, fix defects found in development branch.

Repeat steps 3 - 8 as necessary.

Request Operations Team merge from QA branch into PROD branch (there is only ONE on-going PROD branch per project) -> this request will caus a deployment into the PROD environment (Again an MS Build template is used to re-compile the code from PROD branch and then deploy to PROD servers)

As a result of the Ops team using an MS Build template to deploy to Production servers, the Development team has now lost the "Builders" role.  We cannot create our own MS Build templates, we cannot create or edit a Build definition, and we cannot queue a build -- Even in the Development Environment -- because the Build process runs under a service account which has access to Production servers (since it is use to deploy to production servers).

Besides the removal of TFS permissions, I have some issues with this process:

The assemblies which were compiled and tested in the QA environment are not the assemblies being deployed into the Production environment.  Because the MS Build process is being used to deploy to production, code is recompiled and deployed from the Production branch.  In theory, the resulting assemblies should be the same, however this is depenent upon a) the operations team (who are not developers) properly merging the code from the QA branch to the PROD branch (human error potential) b) the build environment not changing in such a way as to affect the way assemblies are compiled (since this is primarily .Net improbable but not impossible)

Since there is only ONE QA branch, if I have a production issue which needs a "hot fix" after other work has been merged to QA, I have to wait for Ops to rollback changes to the QA branch, merge my changes in and perform the build and then HOPE that operations correctly performed the rollback and merge operations on the QA branch in order to get my "hot fix" into the QA environment.

Many of my projects have multiple outputs (e.g. a web-application and a windows service).  Often I may want to only deploy one or the other.  But if I upgrade one to a new version, I no longer have a PROD branch which represents the one I didn't upgrade.

Operations team has already demonstrated that merge operations are not being performed correctly: Following a recent merge from Development to Trunk I performed a compare on the two branches and they were different.

Because code is recompiled for each environment we cannot use automated versioning, or make use of the "build quality" features of TFS.

Essentially what it comes down to is the Operations Team has attached themselves to using MS Build for deployments and as such have adopted a rediculous Source Control branching and merging strategy to support using MS Build for managing deployments. (I see no benefit in having a QA and PROD branch other than to support MS Build based deployments).

What I am trying to do is convince the powers that be and the operations team that what we're doing is a bad practice, and also give them an alternative deployment strategy.  What I need for this is a Deployment tool that integrates with TFS (e.g. it will show a list of Builds that have a specified "build quality" level (depending upon the environment being deployed into) as a "deployment source" and allow then to maintain a list of "deployment targets" so that at deployment time, they simply pick the build (source) and the target and click the "GO!" button.

A proper deployment tool will hopefully eliminate their dependence upon MS Build, allow them to remove access to QA and Production servers from the MS Build process, follow a more sane approach to branching and merging (e.g adopt a "branch per release" best practices strategy) and restore to the developers the TFS permissions which were revoked to support this rediculous process.


答:
Since dynamic is just a marked object it boxes value types.

This can have performance implications, but since I'd use static typing in performance critical code anyways, that's probably not a problem in practice.

This boxing also interferes with mutable value types. If you modify them with dynamic, you only modify the boxed copy. But since you should not use mutable value types in the first place, this isn't a big problem either.


问:
Github-like "pull requests" without Github
I work as an analyst for a financial institution, which, due to data sensitivity, will not store any data in the cloud. However, I'm having some success getting my team to use Git for code management. I was wondering whether there was any way to implement Github-like pull requests in our own server. The specific feature I'm interested in is the ability to submit a changeset for comments, without actually having it merged into a given branch. I like the workflow of (1) submit changes, (2) have changes reviewed and commented on, and (3) either accept the commit or reject it. Can this be implemented (even better, can this be easily implemented) on our own servers?

答:
git request-pull anyone?

Summarizes the changes between two commits to the standard output, and includes the given URL in the generated summary...

This should do the trick...


问:
What is the difference between writing test cases for BDD and TDD?
I have been learning writing test cases for BDD (Behavior Driven Development) using specflow. If I write comprehensive tests with BDD, is it necessary to write TDD (Test Driven Development) test separately? Is it necessary to write test cases for both TDD and BDD separately, or are they effectively the same thing?

It seems to me that both are same, the only difference being that BDD test cases can be understood by non developers and testers.

答:
BDD utilizes something called a "Ubiquitous Language," a body of knowledge that can be understood by both the developer and the customer.  This ubiquitous language is used to shape and develop the requirements and testing needed, at the level of the customer's understanding.

Within the confines of the requirements and testing dictated by BDD, you will use "ordinary" TDD to develop the software.  The unit tests so created will serve as a test suite for your implementing code, while the BDD tests will function more or less as acceptance tests for the customer.


答:
Behavior Driven Development is an extension/revision of Test Driven Development.  Its purpose is to help the folks devising the system (i.e., the developers) identify appropriate tests to write -- that is, tests that reflect the behavior desired by the stakeholders.  The effect ends up being the same -- develop the test and then develop the code/system that passes the test.  The hope in BDD is that the tests are actually useful in showing that the system meets the requirements.

UPDATE

Units of code (individual methods) may be too granular to represent the behavior represented by the behavioral tests, but you should still test them with unit tests to guarantee they function appropriately.  If this is what you mean by "TDD" tests, then yes, you still need them.

Title: What is the difference between writing test cases for BDD and TDD?

Body:
I have been learning writing test cases for BDD (Behavior Driven Development) using specflow. If I write comprehensive tests with BDD, is it necessary to write TDD (Test Driven Development) test separately? Is it necessary to write test cases for both TDD and BDD separately, or are they effectively the same thing?

It seems to me that both are same, the only difference being that BDD test cases can be understood by non developers and testers.


答:
In many languages a finally statement also runs after the return statement. This means you can do something like:

```<code>try {
  // Do processing
  return result;
} finally {
  // Release resources
}
</code>```

Which releases the resources regardless of how the method was ended with an exception or a regular return statement.

Whether this is good or bad is up for debate, but try {} finally {} is not always limited to exception handling.

Body:
In many languages a finally statement also runs after the return statement. This means you can do something like:

try {
  // Do processing
  return result;
} finally {
  // Release resources
}

Which releases the resources regardless of how the method was ended with an exception or a regular return statement.

Whether this is good or bad is up for debate, but try {} finally {} is not always limited to exception handling.


答:
The problem with dynamic types (not variables declared as dynamic) in .net is that they don't have a lot of the functionality available to static types.

there's no reflection (you can iterate over members but not much else)

no metadata (there goes your validation in dynamic data sites/mvc)

absolutely no checking at compile time (any misspellings will not be caught)

since this is a powerful feature noobs may tend to abuse/misuse/misunderstand it

code written with dynamic types tends to be hard to maintain and damn hard to refactor

because of duck typing and other features gurus may write code that is unreadable to anyone else

So don't write code with dynamic types unless you know what you are doing.


问:
Can Agile be accomplished without client involvement?
I couldn't write a book on Agile.  I have worked in several shops that call their process Agile.  One of the main points of Agile development is regular client involvement.  After a sprint, the work can be demo'd to the client to obtain their feedback.  Rinse and repeat.

The problem I come across is that many clients do not want to be that involved.  They would much prefer a waterfall approach.  Gather the requirements up front, then come back when you are done.  In my experience, waterfall does not work.  Clients do not know what they want until they see it.  The waterfall dilemma is further propagated by a large community of developers that want to have all the requirements up front.  This way they know what they are building, they can architect accordingly, and the client is to blame because they "signed off" on said requirements.

Am I incorrect?  Can Agile work without client involvement?  If so, how and how do you overcome the issues I discussed?

答:
They don't want to put in the time and if given a choice they'd rather get software for free, but you're still going to charge them, right? This gets blurred if you're developing software internally for your company. They think the IT Department has been bought and paid for (salaried employees), so they might as well get as much work out of you as they can.

You can be potentially agile. Get all the specs and start coding. Once the client interupts the work because they just thought of soomething and you have to make changes and reworks, you just became a little more agile. You could also do the approvals within your team. Have one of your team put on a suit and tie and pretend to be the customer.

Making a large time commitment up front may scare them away. Suggest doing a sprint to try it out. Then give them the chance to opt out. You can always shift to a waterfall for the rest of the project.  Also suggest that different people on their team could do the review and approve if time is a constraint for the person writing the check.

At some point, you have to tell them that you don't think the waterfall is going to work. Ask them if they were satisfied with this approach and if so, why don't they have the last guy do this project?


答: No methodology can work without client involvement. Having sign-off on requirements can be meaningless as I witnessed in projects I participated. Your problem goes beyond being able to do Agile, you need to educate your client and make sure they understand how important it is for them to participate.</p>

Title: Can Agile be accomplished without client involvement?

Body:
I couldn't write a book on Agile.  I have worked in several shops that call their process Agile.  One of the main points of Agile development is regular client involvement.  After a sprint, the work can be demo'd to the client to obtain their feedback.  Rinse and repeat.

The problem I come across is that many clients do not want to be that involved.  They would much prefer a waterfall approach.  Gather the requirements up front, then come back when you are done.  In my experience, waterfall does not work.  Clients do not know what they want until they see it.  The waterfall dilemma is further propagated by a large community of developers that want to have all the requirements up front.  This way they know what they are building, they can architect accordingly, and the client is to blame because they "signed off" on said requirements.

Am I incorrect?  Can Agile work without client involvement?  If so, how and how do you overcome the issues I discussed?


答:
How could it?  The very nature of the technique dictates some sort of feedback loop between the customer and the developer.

Parts of your team can, however, act as "proxy" customers (a similar process to "eating your own dog food") so that you can "pretend" to be agile, although that won't be as satisfactory as getting actual customer feedback.

Like it or not, the customer will be involved in the design process; it's just a matter of how much they want the rework to cost (the longer it is delayed, the more expensive it is).

Since the customer wants "Big Design Up Front," help them understand that it will take more time and effort upfront on their part to get the design right the first time.


问:
How viable is it to switch stacks for setting up a startup
I am currently employed with a company for 2.5 years and I have been working with the .net stack for the entire duration mainly on the MVC framework. I believe I have some cool ideas for a startup but I am not sure if I should continue in this stack or switch to some other stack like Ruby on Rails.

The reason why I am consider this switch is due to the Infrastructure required to host a dot net application and scaling it successfully as compared to setting up a live running site on some other stack.

I have a really good domain expertise in dot net at this moment but I believe it should be not so hard to move onto a new stack and adopt the best practices that I have picked up in the past two years.

Let me know if I am missing something in the puzzle and if I am taking the right decision? Are there any complications of learning a new stack and building on it?

Please guide me in the right direction.

答:
There are a lot of complications with switching stacks, but they are not insurmountable. Here's what I think (my day job is .NET, everything else I do is open source).

Cost

This is why most people want to switch to open source, or at least away from .NET. It almost always costs more to set up a decent server infrastructure to host .NET. If you go with a standard cloud infrastructure, most hosting companies will charge between 3 and 10 times as much per month for the basic plans.

Where it gets tricky is measuring long-term costs of development on a stack you don't yet know vs. opportunity cost of developing on one you do. However, if you're like a lot of bootstrappers, you don't have a lot of money to spend on server hosting, and it has to be as cheap as possible.

As an example, I spent approximately $150 my first year in hosting and bandwidth charges for 1 small server while I was working on setting up my business. If I had chosen to go with a Microsoft server, it would have cost more because they simply don't allow as small of servers. And, SQL Server is super expensive. It would have cost almost $2000. A comparably powered Ubuntu server would have cost around $500.

You

A lot of it depends on your ability to adapt and learn a new stack. It's not easy, because as a startup it's about much more than just learning a programming language. You have to set up the servers, manage the infrastructure, the databases, everything. There are services out there now that offer Platform as a Service and can abstract a lot of that management away for you, but that is often more money. You'll have to determine if that trade-off is worth it.

Knowledge Transfer

You say that you hope to adopt the best practices you've learned from .NET and transfer them to a different stack. My experience is that other than very high-level tactics, you're going to pretty much throw out whatever it is you know about .NET web dev when you move to anything else. There's just too many different pieces, different cultures, and different approaches to really achieve that much reuse.

That's not a bad thing though. You really should go learn other stacks, as they will challenge whatever you currently know and make you a better programmer.

Summary

My opinion is that if you're willing to trade off a slower start for a stack that's easier to manage and scale, and at a lower price, you should go with an alternate stack. Other people may say that software costs are not really the big cost, but unless you have funding, a lot of money saved up, or are willing to borrow a lot of money, that's just really not true at all. It's expensive to buy all that software and server infrastructure up front, and if you don't have the money, you can't pay for it.


答:
The differences between TDD and BDD are subtle and mostly boil down to language.  BDD tests are often written in the following form:

```<code>public void shouldBuyBread() throws Exception {
   //given
   given(seller.askForBread()).willReturn(new Bread());

   //when
   Goods goods = shop.buyBread();

   //then
   assertThat(goods, containBread());
 }
</code>```

If you frame the test in terms of behavior it helps scope the responsibility of the class and leads to better design (at least according to BDD'ers).  BDD sometimes focuses on executable specifications that your domain experts/customers can understand.

BDD is also more associated with what Martin Fowler calls 'outside-in' or 'mockist' tests, as opposed to state-based verification.

Body:
The differences between TDD and BDD are subtle and mostly boil down to language.  BDD tests are often written in the following form:

public void shouldBuyBread() throws Exception {
   //given
   given(seller.askForBread()).willReturn(new Bread());

   //when
   Goods goods = shop.buyBread();

   //then
   assertThat(goods, containBread());
 }

If you frame the test in terms of behavior it helps scope the responsibility of the class and leads to better design (at least according to BDD'ers).  BDD sometimes focuses on executable specifications that your domain experts/customers can understand.

BDD is also more associated with what Martin Fowler calls 'outside-in' or 'mockist' tests, as opposed to state-based verification.


答:
Why not try and see?

spending a week knocking up a quick prototype with rails, or similar, will at least give you some insight into where there are impedance mismatches, and will give you some experience when you want to do the real thing, at least at the language/library level

it probably won't help much insight into what issues you might get on scaling up but there is no point in worrying about that until you know if you can live with it in the small scale

Title: How viable is it to switch stacks for setting up a startup

Body:
I am currently employed with a company for 2.5 years and I have been working with the .net stack for the entire duration mainly on the MVC framework. I believe I have some cool ideas for a startup but I am not sure if I should continue in this stack or switch to some other stack like Ruby on Rails.

The reason why I am consider this switch is due to the Infrastructure required to host a dot net application and scaling it successfully as compared to setting up a live running site on some other stack.

I have a really good domain expertise in dot net at this moment but I believe it should be not so hard to move onto a new stack and adopt the best practices that I have picked up in the past two years.

Let me know if I am missing something in the puzzle and if I am taking the right decision? Are there any complications of learning a new stack and building on it?

Please guide me in the right direction.


问:
Using a try-finally (without catch) vs enum-state validation
I have been reading the advice on this question about how an exception should be dealt with as close to where it is raised as possible.

My dilemma on the best practice is whether one should use a try/catch/finally to return an enum (or an int that represents a value, 0 for error, 1 for ok, 2 for warning etc, depending on the case) so that an answer is always in order, or should one let the exception go through so that the calling part would deal with it?

From what I can gather, this might be different depending on the case, so the original advice seems odd.

For example, on a web service, you would always want to return a state of course, so any exception has to be dealt with on the spot, but lets say inside a function that posts/gets some data via http, you would want the exception (for example in case of 404) to just pass through to the one that fired it. If you don't, you would have to create some way to inform the calling part of the quality of the outcome (error:404), as well as the outcome itself.

Though it IS possible to try-catch the 404 exception inside the helper function that gets/posts the data, should you? Is it only I that use a smallint to denote states in the program (and document them appropriately of course), and then use this info for sanity validation purposes (everything ok/error handling) outside?

Update: I was expecting a fatal/non-fatal exception for the main  classification, but I didn't want to include this so as not to prejudice the answers. Let me clarify what the question is about: Handling the exceptions thrown, not throwing exceptions. What the desired effect is: Detect an error, and try to recover from it. If recovery isn't possible, provide the most meaningful feedback.

Again, with the http get/post example, the question is, should you provide a new object that describes what happened to the original caller? If this helper was in a library you are using would you expect it to provide you with a status code for the operation, or would you include it in a try-catch block? If you are designing it, would you provide a status code or throw an exception and let the upper level translate it to a status code/message instead?

Synopsis: How do you chose if a piece of code instead of producing an exception, returns a status code along with any results it may yield?

答:
Exceptions should be used for exceptional conditions.  Throwing an exception is basically making the statement, "I can't handle this condition here; can someone higher up on the call stack catch this for me and handle it?"

Returning a value can be preferable, if it is clear that the caller will take that value and do something meaningful with it.  This is especially true if throwing an exception has performance implications, i.e. it may occur in a tight loop.
Throwing an exception takes much longer than returning a value (by at least two orders of magnitude).

Exceptions should never be used to implement program logic.  In other words, don't throw an exception to get something done; throw an exception to state that it couldn't be done.