答:
True, coming across as defensive is not helpful; but then - neither is being criticised, so if you feel this is happening you really should vocalise your concerns that the code review is not helping you write better code within the organisation.

The reviewer has a responsibility to review code for real non-compliance and defects, not use it as a means to write your code the way they would have done. This means the review is there to review how you did something, and point out any areas that you made a mistake (something the best of us do) or didn't understand the framework or standards or "historical reasons" some code is written the way it is where you are.

So if there are multiple ways of doing something, there needs to be a good reason why your code is changed to an alternative way, otherwise its simply non-constructive churn that won't help you.

Also, remember that the reviewer isn't perfect either. They may have an idea that Y is the way to do it, and haven't realised that X is better. You should explain the reasons why you did it in way X. The reviewer might agree with you, or he might tell you why Y is a better solution - there may be other factors that you don't know that he does.

In short, reviews are a way to get team members to communicate about their code changes. So talk to the reviewer about it.

IF it helps, talk in an impartial way, as if you were not even the author of the code being reviewed. The code belongs to the company or team after all, and the team will have to maintain it. You just happened to be the guy who wrote it, that's not as important a factor as many believe.

Title: What is the best way for a programmer to handle being code reviewed?

Body:
I am fairly new to code review, but I have been coding for years during my PhD - which doesn't always make you a good programmer!

If the reviewer changes your code and goes through it with you line-by-line, what do you do if you disagree?  Sometimes you made choice X and the reviewer changes it to Y, and you had Y in your mind but decided not to do it because of the disadvantages, but the reviewer asserts that those disadvantages are not important. Should you verbalise your disagreement, or just not and listen to them?

Its difficult if you are not good at accepting criticism, and if the reviewer is a more senior person in the organisation.  It would not be good to come across as too defensive.


问:
Why would programmers ignore ISO standards?
One of the things I run into often is problems caused by programs which don't conform to ISO standardss.

One example would be not using the ISO country tables but making up their own shorthands, which goes okay for the United States (US), or the Netherlands (NL) but goes spectacularly wrong for the United Kingdom (GB, not UK) or Spain (ES, not SP) and a lot of other countries.

As another example, internal date notations. Why would anyone store a date as 01/02/2014 ever? It is completely unclear whether that is 1st February or January 2nd, whereas if you use the ISO standard you just store 2014-02-01* and it's unambiguously February 1st.

My question: When and why should a programmer make up their own constructs when there is an ISO standard available?

* Store 2014-02-01, and format the date accordingly when showing it to an end user.

答:
In the case of inexperienced programmers/database designers, it's because of not knowing. They tend to reinvent the wheel because they don't know a group of people spanning industries, already discussed the issue and came up with an standard approved by all who participated, often after very long discussions, revisions, etc. Recently a co-worker of mine showed incredulity when I told him there was an ISO standard regarding whether a given week is considered the last week of a year or the first one of the next year (ISO 8601). He didn't believe a standard existed regarding something so specific. I told him that the correctness of many applications depended on that standard.

In the case of experienced programmers/database designers, it's disregard caused by "knowing better", not-invented-here syndrome, and/or grandiosity. They don't trust ISO or any other standard bodies because they consider the ISO code is "not stable enough", meaning it will change someday. So they create their own, invented-here or auto incremented codes/identifiers hindering interoperability, which they also disregard. See this similar question, albeight database-design inclined. They give reasons like:

I may not necessarily want my database design to depend on a bunch of
  third parties (IATA, ISO), regardless of how stable their standards
  are. Or, I may not want to depend on a particular standard at all.

Oddly enough those who disregard standards use standard USB ports, buy standard-sized DVDs and BluRays and drive cars with tires that conform to standards.

ContentLicense: CC BY-SA 3.0


问:
How should a REST API handle PUT when missing parameters?
I have a list of users that are being assigned to a certain office. I use checkboxes to select each user and when the client is done, a PUT is performed:

```<code>PUT offices/:id

users[0] : 14
users[1] : 12
users[2] : 25
</code>```

The problem occurs when the server has users saved, but the client decides to clear the board. So he deselects the users and hits save. The problem in this case is that the Ajax request is not sending an empty users[0] : parameter, because each checkbox is unchecked.

In the case when a parameter is not included at all, should PUT overwrite that it and set it to null or should the request include the empty parameter somehow?

答:
The answer is in the RFC describing the PATCH method:

In a PUT request, the enclosed entity
is considered to be a modified version of the resource stored on the
origin server, and the client is requesting that the stored version
be replaced.  With PATCH, however, the enclosed entity contains a set
of instructions describing how a resource currently residing on the
origin server should be modified to produce a new version.

Hence, PUT requires you to submit the complete representation of the resource, whereas PATCH may take an incomplete version, or simply some commands on how to apply the patch. This depends on your specific API implementation.

So in your case you actually want to use PATCH, and not PUT.


问:
what is a language specification?
Either I am being a total n00b or just not with it today but I have been reading a few blogs lately and they talk about language specs. What actually is a language spec? Is php.net a language spec? The best article so far I have read is Grokbase on the PHP Language Specification.</p>

答:
A specification is a document in human language describing how a system is supposed to work. In the case of a programming language, it describes how the compiler or interpreter is to react to various inputs - which are valid/invalid, and what happens when they are executed.

A reference implementation such as "this specific compiler" is not a specification. It also defines a function from inputs to outputs, but it cannot be read by humans, you can only experiment with it. Of course you can write a trivial doc saying "everything that implementation XY does is by definition expected", but that goes completely against the point of having a spec in the first place - the implementation almost certainly contains errors, does undefined things on certain inputs that you can't distinguish from defined but complex things, conversely it behaves consistently in some way where there is really no reason to prescribe one way over the other, etc.

When you need reassurance what a program is supposed to do, when you need to stay correct even across upgrades of a runtime system, when you have to formally prove that a solution is correct, when you want to write code that must run on alternate implementations - in other words, whenever a basic "It works for me" test isn't good enough - then you need a specification, not just a running program.

Title: what is a language specification?


答:
When I program in Ruby, I generally always ignore the ISO Ruby standard. Why? Because it's incredibly restrictive! ISO Ruby is a minimal subset of the intersection of Ruby 1.8 and Ruby 1.9. The current version of Ruby, which is supported by all Ruby implementations (or at least will be very soon) is Ruby 2.1, and it has many features that make programming easier. Programming in ISO Ruby is a PITA.

When I program in C#, I also ignore ISO C#, which is a subset of C# 2.0 (and more importantly, the ISO Class Library is an extremely small subset of the .NET BCL), and instead I program in C# 5.0 and I don't restrict myself to use only the libraries which are specified in the ISO CLI, instead I use the common subset of libraries available in .NET 4.5.2 and Mono 3.4.0.

And when doing web design, I very much prefer to use HTML5 over ISO HTML (which is a small subset of HTML 4.01 Strict), again, because HTML5 is much more feature-rich than a restricted subset of an ancient version of HTML.

So, there are good reasons for ignoring ISO standards.

Title: Why would programmers ignore ISO standards?

Body:
One of the things I run into often is problems caused by programs which don't conform to ISO standardss.

One example would be not using the ISO country tables but making up their own shorthands, which goes okay for the United States (US), or the Netherlands (NL) but goes spectacularly wrong for the United Kingdom (GB, not UK) or Spain (ES, not SP) and a lot of other countries.

As another example, internal date notations. Why would anyone store a date as 01/02/2014 ever? It is completely unclear whether that is 1st February or January 2nd, whereas if you use the ISO standard you just store 2014-02-01* and it's unambiguously February 1st.

My question: When and why should a programmer make up their own constructs when there is an ISO standard available?

* Store 2014-02-01, and format the date accordingly when showing it to an end user.


问:
Dependency injection ; good practices to reduce boilerplate code
I have a simple question, and I'm not even sure it has an answer but let's try.
I'm coding in C++, and using dependancy injection to avoid global state. This works quite well, and I don't run in unexpected/undefined behaviours very often.

However I realise that, as my project grows I'm writing a lot of code which I consider boilerplate. Worse : the fact there is more boilerplate code, than actual code makes it sometimes hard to understand.

Nothing beats a good example so let's go :

I have a class called TimeFactory which creates Time objects.

For more details (not sure it's relevant) : Time objects are quite complex because the Time can have different formats, and conversion between them is neither linear, nor straightforward. Each "Time" contains a Synchronizer to handle conversions, and to make sure they have the same, properly initialized, synchronizer, I use a TimeFactory. The TimeFactory has only one instance and is application wide, so it would qualify for singleton but, because it's mutable, I don't want to make it a singleton

In my app, a lot of classes need to create Time objects. Sometimes those classes are deeply nested.

Let's say I have a class A which contains instances of class B, and so on up to class D.  Class D need to create Time objects.

In my naive implementation, I pass the TimeFactory to the constructor of class A, which passes it to the constructor of class B and so on until class D.

Now, imagine I have a couple of classes like TimeFactory and a couple of class hierarchies like the one above : I loose all the flexibility and readability I'm suppose to get using dependancy injection .

I'm starting to wonder if there isn't a major design flaw in my app ...
Or is this a necessary evil of using dependancy injection ?

What do you think ?

答:
I implemented yet another C++ dependency
injection framework, which recently was proposed for boost – https://github.com/krzysztof-jusiak/di –
library is macro less (free), header only, C++03/C++11/C++14 library providing type safe, compile time, macro free constructor dependency injection.</p>


答:
Storing 20140201 is not unambiguous at all. Only when you include the knowledge that is following the ISO standard does it become unambiguous. The same goes for 01/02/2014: when you include the knowledge that the format is mm/dd/yyyy it is also perfectly unambiguous.

As long as the application does not have to interface with other application any well documented standard can work just as fine.

There is a tradeoff between what is easy for humans (I tend to use 1-2-2014) and computers (who would even be better of with a binary representation instead of ISO). Novice programmers tend to stick with what they can easily understand, more experiences programmers start to see the advantages of computer-oriented storage.


问:
Should temporary code be put under version control and how?
Here are some examples of temporary/local code. It is needed in order to work with the codebase, but would be harmful to be part of it:

Project files. Paths may need to be edited in order to reflect the layout on the current PC.

Makefiles. For example optimization may need to be turned off during debugging, but not for the CI server.

Dirty ugly hacks. For example return 7 in the middle of a function, in order to test something, depending on the function, and suspected to break at value of 7. Or 7 is the code of the not yet implemented button, that I am implementing and need to test throughout the life of my branch.

I have tried keeping those in a git commit that I always rebase to the top before pushing to the repo and then push HEAD~. This is quite inconvenient and doesn't work with svn. Stashing scares me even more - "did I remember to pop after pushing??".

Keeping the code out of version control introduces unpleasant noise everytime a commit is being assembled plus it might accidentally get introduced into a commit some friday evening.

What would be a sane solution for such throw-away code?

答:
I believe that some systems will throw warnings on seeing TODO in a comment, so

```<code>// TODO: remove this hack.
</code>```

might be all that is necessary if you can find a relevant option in some part of your development environment, or just stick some sort of grep command in your buildfile. It might also be possible to arrange for // HACK or any arbitrary string to be picked up.

This is simpler than organising your code in a particular way and hoping that people will remember not to use it. It also makes it safer to follow @gbjbaanb 's advice (if you can ensure that everyone is seeing the warnings!).

Stick everything you like in there becuase one day you might want to see what it was, and those are the days you realise what your SCM is truly about.

Body:
I believe that some systems will throw warnings on seeing TODO in a comment, so

// TODO: remove this hack.

might be all that is necessary if you can find a relevant option in some part of your development environment, or just stick some sort of grep command in your buildfile. It might also be possible to arrange for // HACK or any arbitrary string to be picked up.

This is simpler than organising your code in a particular way and hoping that people will remember not to use it. It also makes it safer to follow @gbjbaanb 's advice (if you can ensure that everyone is seeing the warnings!).

Stick everything you like in there becuase one day you might want to see what it was, and those are the days you realise what your SCM is truly about.


答:
One of the reasons is that the application domain and the users might not use these standards themselves. Even when some domains use some standards, some of them might have made different choices than the ISO standards, often for historical reasons.

If your users already use "UK" in their existing procedures(1) to refer to "United Kingdom of Great Britain and Northern Ireland", it doesn't necessarily make sense to use "GB" in their data structures (especially if what you mean by country isn't quite an "ISO" country, e.g. separating UK nations or having subtle differences with the Channel Islands and so on). Of course, you could have a mapping between internal storage a presentation, but sometimes, it's a bit over the top. You're rarely programming for the sake of programming, you often have to adapt to your environment.(2)

You also have to remember that these standards have evolved in parallel with software. You often have to develop within the context of other pieces of software, some of which may be imperfectly designed, some of which may still be affected by legacy decisions.

Even if you look at internal data storage formats, some ambiguities are hard to resolve. For example, as far as I know, Excel uses a decimal number to represent timestamps: it uses an integer as the number of days since a reference date, then what's after the decimal represents the fraction of the 24 hours to give you the hour... The problem is that this prevents you from taking into account time zones or daylight saving time (23h or 25h in a day), and Excel will convert any date/time to that internal format by default. Whether you want to use the ISO format or not becomes irrelevant if another piece of software you have to work with doesn't leave you a choice.

(1) I don't mean "programming procedures" here.

(2) Don't ask me why people don't use those standards in their daily lives either. I mean YYYYmmdd is clear, dd/mm/YYYY is clear, but ordering a date with medium, small, big order of granularity like mm/dd/YYYY, that just doesn't make sense :-) .


问:
Best pratice for return json in a REST application?
I'm starting now with REST (using Laravel 4.2) and Mobile (Android, iOS, SP, etc.) applications.

Initially I'm checking if the request is ajax/json and then return a json response.

But this condition is in a normal action (HTTP), so:

if ajax/json return json, else return the view/template/layout

Is it correct to do that in the same action, or is the best practice to create another controller for that? For example:

PostsController

PostsMobileController

Or

PostsController

Mobile\PostsController (or Json\Controller) - using namespaces

答:
You have outlined the two main approaches, and each have their advantages and disadvantages.

If you combine both in the same controller, and all you are doing is changing the output, then using a single controller makes sense. The logic is the same, but the output changes.

If the logic has to change because the output is different, then go with two different controllers.

Separating them into two controllers also gives you the ability to easily add support for non web platforms, e.g. native mobile applications. Your Larvel app then has two sides: The web side and a data API.

The direction you take will largely depend on the future needs of the application. My advice is to start out simple. Use a single controller that just changes the output format. It's easier to add complexity later than it is to add simplicity. If you need a data API later, then start adding different controllers after you've done some architecture and system design work.


答:
Although the right solution depends on your context, here is my approach:

When designing classes one should always consider their single responsibility. In case of the PostsController it could probably be described "create, read update and delete" posts. Formatting of the output is a global problem of your application that should not be solved individually in each controller. Better would be to design this as an output strategy / aspect / whatever your language and framework allows.

Just imagine if you need an API for outputting XML at some time. Would you really create new controllers for each entity?

Btw, when considering such questions (for any language) I tend to look at the Rails documentation, which has a nice approach here:

```<code>class UsersController < ApplicationController
  def index
    # Load all users
    @users = User.all
    # Different formattings based on request headers
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render xml: @users}
      format.json { render json: @users}
    end
  end
end
</code>```

Title: Best pratice for return json in a REST application?

Body:
I'm starting now with REST (using Laravel 4.2) and Mobile (Android, iOS, SP, etc.) applications.

Initially I'm checking if the request is ajax/json and then return a json response.

But this condition is in a normal action (HTTP), so:

if ajax/json return json, else return the view/template/layout

Is it correct to do that in the same action, or is the best practice to create another controller for that? For example:

PostsController

PostsMobileController

Or

PostsController

Mobile\PostsController (or Json\Controller) - using namespaces

Body:
Although the right solution depends on your context, here is my approach:

When designing classes one should always consider their single responsibility. In case of the PostsController it could probably be described "create, read update and delete" posts. Formatting of the output is a global problem of your application that should not be solved individually in each controller. Better would be to design this as an output strategy / aspect / whatever your language and framework allows.

Just imagine if you need an API for outputting XML at some time. Would you really create new controllers for each entity?

Btw, when considering such questions (for any language) I tend to look at the Rails documentation, which has a nice approach here:

class UsersController < ApplicationController
  def index
    # Load all users
    @users = User.all
    # Different formattings based on request headers
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render xml: @users}
      format.json { render json: @users}
    end
  end
end


问:
How should I approach storing single boolean results for a whole table?
I previously asked this question on stack overflow. But have not received any responses that might help me. So I thought I would try here.

https://stackoverflow.com/questions/24883527/best-way-for-me-to-approach-storing-single-boolean-results-for-overall-table

Essentially I am creating a Java application that reads and writes form a database. In the course of the design it creates new tables with new information as well as linking the information from those tables.

Anyway, the question is, the client has requested that the JTable that I use to display the Table names from the database now include 3 columns each with a checkbox.
What would the best action be for me to store the data from these checkboxes?

Some of the methods I have considered are

Store the information within the table in new columns (this will involve changing the code for modifying and writing of these tables, which is possible)

Create a new table and store the other table names and the values in columns within (have it on load check the current names against the meta data and add/remove where needed)

Create a properties file and pull the information from that, where it matches the names from the MetaData (ie. TableName=yes,no)

The option that strikes me as the easiest/fastest to do/run would be to go with option 3, and make a properties file.

NOTE: Within the application I already have methods for reading and writing from a properties file, as well as to create a new table within the database, and to write/read from the rows of each table.

答:
Your description sounds like you have already coded a method of saving data.  In my experience, the best thing to do when working on an existing application is to follow the same pattern throughout.  My advice to you is to look at how similar data is being handled by the application.  Follow the same pattern that is being used there when saving the check box data.

Advantages of following existing patterns

There are a lot of good reasons to follow existing patterns when adding functionality to an existing application.  One of the most important advantages is that all the code follows the same rules.  If there is a couple developers that understand how the application works, they will continue to understand how the application works after you make your change.  Another advantage to this is developers can learn one pattern to understand how the application saves data.

Recommendation

I recommend taking a look at what is currently being done to save data of this type.  Use that as a template when adding the functionality with check boxes.  I'm sure there is a pattern already established for you to mimic.  You just need to find out what it is.  Unfortunately, I can't give you anymore advice than that without further understanding the application structure.


问:
Pair Programming and ISO 27001
I’ve been working in an eXtreme programming team and doing pair programming for over 7 years in a windows environment. When we first started doing it someone would log in with their windows credentials and therefore all access to domain resources, and more specifically version control, would be accountable to that windows user. Eventually we have evolved to have windows pairing accounts for specific pairing stations (e.g pairA, pairB, PairC etc…). All the devs know the passwords to these accounts. Accountability for commits (check-ins) is achieved by putting the programmers initials in the comment during the commit.

Up until now this has worked fine for us, but my company is currently going through a ISO 27001 audit and this was flagged up by the auditor as a risk. I have a number of possible solutions such as creating a pairing account for every pair combination, but I really would like to know whether anyone else has encountered this problem and how they solved it?

What solution was acceptable by the auditors?

答:
For Pete's sake, let the driving member of the pair take credit/responsability for the push/commit. Next time the other member will drive. The "driver" will not do anything he doesn't agree upon whith the co-pilot.

Programming is a colaborative effort. No programming deed is 100% individual. There's no need to be fastidious wanting to reflect that a given push/commit was done by Tom and Harry and not just Tom. The benefits of pair programming are worth overlooking that nuance.

The auditor is right, "pool" accounts should be avoided.

Title: Pair Programming and ISO 27001


答:
Per your example, "GB" is the country code for the United Kingdom.  However, "UK" was the at one time the MARC (US Library of Congress) standard code, although I believe that's deprecated.  And the IANA uses .uk for the top-level domain for the United Kingdom.

So, if something doesn't conform to an ISO standard, it doesn't mean that no standard is being used; it may simply mean that a different standard is being used.  (As @Jörg noted in a comment, the nice thing about standards is that there are so many to choose from.)  In which case the question really becomes which standard would be most appropriate for the given problem domain, environment, etc.?

Responses to that question would probably be largely opinion-based and quickly degenerate into a "religious" debate.  But ISO standard conformance isn't necessarily always the best answer.  For example, if a piece of software needs to interface with library databases, MARC standards might be a more appropriate choice than ISO.  If most of your organization's software does things a certain way, you might want to stick with that approach, at least in the short-term -- it's your organization's "standard", after all.

Also, standards do evolve/change.  What was conformant yesterday may not be today.

And, while I wouldn't want to rule out ignorance and/or sloth as the cause of the issues you point out ... the developer might simply not have had enough time to address them.


答:
Well, people tend to ignore ISO standards: for example, you wrote

if you use the ISO standard you just store 20140201* and it's unambiguously February 1st.

but the fully ISO8601-compliant rendition is in fact 2014-02-01. (see also xkcd 1179)


答:
Compliance with an ISO standard is not always a cost-free activity.  If a particular standard isn't already implemented in the toolkit she's using, a programmer is faced with a necessary choice: Is it cheaper to properly implement this now, or not implement the standard and deal with conversions later?

It's easy to say "hey, you should always implement the standard", but everything has a cost.  And there are some good reasons why a programmer may not want to implement an ISO standard.

The customer may be following a proprietary or non-ISO standard.  Better to hew to the standard a customer is expecting than leave unintended headaches for your successor by hiding an additional implementation besides what the customer wants and your language requires.

There may be a great deal of existing data, and a conversion or format-break may not yet be feasible.  If you have twenty years of customer contacts and contracts keyed with local date-times, you don't necessarily want to change all those hundreds of millions of fields to ISO standard dates until you can do it right.

Adherence to the standard may impose a greater cost than the benefit provides.  If you're dealing with entries entirely within the United States, for example, the five-character ISO-3166-2 code (US-NY) is three unneeded characters over the standard US postal code (NY).


答:
In my experience programmers fail to use ISO standards for a variety of stated reasons, e.g.:

"I didn't know that there was an ISO standard" (ceases to be a valid reason once you're told!)

"The standard is inaccessible (can't find /afford a copy)" (really??)

"The standard is too restrictive" (usually if the standard says "don't" then there's a good reason. Ignore it at your, and your customer's, peril!)

"The standard doesn't include the latest functionality / library" (no standard includes EVERY library that you'll ever want to use so adhere to the standard for the things that it DOES include/cover and be consistent with the standard for the things that it doesn't)

"The standard is too cumbersome to implement" (greatly over-used excuse but see below)

The only reason that I accept from my staff, as not being a lame excuse, is "the standard really isn't a good 'fit'" - backed up by evidence.
Sometimes the complexity of the the applicable ISO standard is out of proportion to the problem / solution. Sometimes the context in which you will implement your solution is significantly different from that assumed by the standard. And sometimes the standard can be improved upon - that is how progress happens.

More often than not though, the failure to use the ISO standard can be attributed to inexperience, laziness or arrogance. I regret to say that English-speaking programmers are particularly guilty of laziness as regards internationalisation and that our US colleagues tend to perceive ISO as "an irrelevant European thing" (apologies to the minority to whom this does not apply).


答:
Your first option sounds like the most sane. You have a UI component that displays records from a table, and you now need to display boolean values associated with each record and you need to persist the values that the user sets. Saving these three new values with the record makes the most sense, logically, but I don't know enough about your system to know for certain.

Your second option involves splitting these values out to a separate table. This might make sense if there was some sort of 1:n or n:1 relationship, or these columns were very sparsely populated in a huge number of records and you were concerned about using up too much storage for them. It doesn't sound like any of these issues are relevant here, so you probably don't need to go this route.

Your third option invovles splitting the data out of the table and saving it in a properties file. Why split the data into such different areas? It sounds like your reason to do this is fast development time. I'd recommend against doing this, unless your deadlines are really that tight.

My recommendation is to go with your fist option, but again, there's not enough information about your system to know if that's really the best bet.

Title: How should I approach storing single boolean results for a whole table?

Body:
I previously asked this question on stack overflow. But have not received any responses that might help me. So I thought I would try here.

https://stackoverflow.com/questions/24883527/best-way-for-me-to-approach-storing-single-boolean-results-for-overall-table

Essentially I am creating a Java application that reads and writes form a database. In the course of the design it creates new tables with new information as well as linking the information from those tables.

Anyway, the question is, the client has requested that the JTable that I use to display the Table names from the database now include 3 columns each with a checkbox.
What would the best action be for me to store the data from these checkboxes?

Some of the methods I have considered are

Store the information within the table in new columns (this will involve changing the code for modifying and writing of these tables, which is possible)

Create a new table and store the other table names and the values in columns within (have it on load check the current names against the meta data and add/remove where needed)

Create a properties file and pull the information from that, where it matches the names from the MetaData (ie. TableName=yes,no)

The option that strikes me as the easiest/fastest to do/run would be to go with option 3, and make a properties file.

NOTE: Within the application I already have methods for reading and writing from a properties file, as well as to create a new table within the database, and to write/read from the rows of each table.


问:
Is immutability very worthwhile when there is no concurrency?
It seems that thread-safety is always/often mentioned as the main benefit of using immutable types and especially collections.

I have a situation where I would like to make sure that a method will not modify a dictionary of strings (which are immutable in C#). I’d like to constrain things as much as possible.

However I am not sure whether adding a dependency to a new package (Microsoft Immutable Collections) is worth it. Performance is not a big issue either.

So I guess my question is whether immutable collections are strongly advised for when there are no hard performance requirements and there are no thread safety issues? Consider that value semantics (as in my example) might or might not be a requirement as well.

答:
There is a lot of good answers already. This is just an extra info somewhat specific to .NET. I was digging through old .NET blog posts and found a nice sum-up of
benefits from the point of view of the Microsoft Immutable Collections developers:

Snapshot semantics, allowing you to share your collections in a way
  that the receiver can count on never changing.

Implicit thread-safety in multi-threaded applications (no locks
  required to access collections).

Any time you have a class member that accepts or returns a
  collection type and you want to include read-only semantics in the
  contract.

Functional programming friendly.

Allow modification of a collection during enumeration, while
  ensuring original collection does not change.

They implement the same IReadOnly* interfaces that your code already
  deals with so migration is easy.

If someone hands you a ReadOnlyCollection, an IReadOnlyList, or
  an IEnumerable the only guarantee is that you can’t change the data
  – there is no guarantee that the person that handed you the collection
  won’t change it. Yet, you often need some confidence that it won’t
  change. These types don’t offer events to notify you when their
  contents change, and if they do change, might that occur on a
  different thread, possibly while you’re enumerating its contents? Such
  behavior would lead to data corruption and/or random exceptions in
  your application.


答:
ISO has lots of standards. As did CCITT/ITU. Some of these standards are "aspirational" standards, while other are minimum required functionality. It's not often clear which is which.

I remember in the 1980s asking why some equipment vendors implement one subset of the standard while other vendors implement a different subset. That's when it came out that the standards are often set before something works. And vendors often deliberately choose not to implement standards so that they can hamper interoperability,  which then grants them an advantage.

That's why I like IETF RFCs. They don't even become RFCs until there are 3 independent implementations of the RFC.


问:
How does code coverage work?
Specifically, what is contained inside code coverage data (.nccov or xml file) and how is an html report generated by this? Does the coverage data not include the actual percentage of code covered? Is this only generated when the report is made from the coverage data? Is the coverage data sort of a guideline for the reporting process?  Do coverage files need access to assemblies to create a report?</p>

答:
Specifically, what is contained inside code coverage data?

Code coverage data is used to determine how effectively your tests exercise the code in your application. This data helps you to identify sections of code not covered and sections of code partially covered by your tests, as well as sections of code where you have complete coverage. With this information, you can add to or change your test suites to maximize their effectiveness.

Does the coverage data not include the actual percentage of code covered ?

Yes, it does show the percentage of the code that was run in each assembly, class, and method.

Do coverage files need access to assemblies to create a report?

Yes.

Also, check the MSDN for any other related queries.

Title: How does code coverage work?


问:
In a REST service project, where should we put code that calls a third party REST API?
My project is organized in layers like

Configuration

Controller

Service

Repository

Domain

Our REST Controller is in the Controller layer. We need to connect to another API via REST calls and I'm not sure if I should make a new Controller or do it in the Service layer.

I'm going to implement the REST calls with Spring's RestTemplate.

The way our API will be used is like this:

REST call is made that goes through our REST endpoint.

Our REST endpoint will call the third party API (either by calling another controller method or a service method).

We will then do a conversion between our format and the third party format

Then we will return the JSON of our format back to the client

答: I would put it into the Service layer. It doesn't make sense for you to do it in a NEW Controller. You can even do the remote call directly in your controller if you are sure that other controllers don't need to do a similar thing.


问:
Should I add a key to the items of my REST API response?
I have an REST API endpoint which the JSON response looks like:

```<code>{
    "products": [
        {"id": 1040, "price": 2.95, ...}
        {"id": 4545, "price": 3.95, ...}
    ]
}
</code>```

One of my colleagues suggested that I should add a key for each item in the list. He said it would make easier to browse the browse the API. The example above would become:

```<code>{
    "products": {
        "1040": {"id": 1040, "price": 2.95, ...}
        "4545": {"id": 4545, "price": 3.95, ...}
    }
}
</code>```

Making it will not be harmful for my API's performance and I can understand how it should improve the browsability. Should I do that? Is there any example of public API that does something similar?

答:
It depends.

Is the response an answer to a query that's more like GetListOfProducts() or GetProductIndex()? Is the result intended to be iterated over or used as a single-product lookup by id? Is the sort-order significant?

If it's more like GetListOfProducts() with sort-order implications and/or the intention of iteration, like displaying the records in a table, stick with what you have. It's probably trivial for your API consumers to search or index the items.

If it's more like GetProductIndex() and is intended to be used like an index, and if sort order doesn't matter, consider sending it in the 2nd form. But even in this case, remember that it's probably trivial to index (or search() or filter()) the array client-side. So, I'd be a little hesitant: Consider whether it's more difficult for the client/consumer to index and search a list or for the server to inject a sort order (and the client to respect that order) if needed on a property set that has no inherent ordering.


问:
API Key DDOS protection
Hi I just wanted some feedback on a DDOS preventing php script that I'm designing. It is quite simple and I wanted some feedback on whether you guys think it would be effective.

I'm currently using the ulogin framework as a base and have implemented API Keys. At the moment the user will send a request with a key. This key is checked against the database to see if it correct. So if the key is not correct the program will return.

If the key is correct then some statistics are going to be calculated. The first thing is to increment the counter. The average hit per second will be calculated from the time they started requesting to the current time. Also there is a window of X seconds in which the counter will be reset (Lets say 300). The programmer specifies the max number of requests that should be allowed in this window. If the key is over the limit of requests per stats reset (Window) or over a certain amount of requests per second, they will be blocked and not given access. However the counter still increments but another counter is started (blockcount).

When the counter is set to 0 at the end of the window, the count for the next window will be set to what ever the blockcount is and the blockcount will be set to 0. If the user doesn't use the API key for X (window) seconds then both counters will be reset to 0.

I have added a transferpenalty variable (0-1) that will take a percentage of the blockcount on to the next window instead of the entire block count but I don't think that it is neccessary to have this.

Is this already being done? Would this protect against a sniffed API key being used to (D)DOS a server? What are your thoughts :)

答:
The fact you must check a database leaves your DDOS script vulnerable to that sort of attack. The key to guarding yourself against this sort of thing is building a protective layer that responds quicker than the DOS attackers can send requests your way while still allowing legitimate traffic to access internal resources. I doubt a database can be quick enough.

You might need to store these stats in a persistent memory store like memcached, which has its own security concerns because it is not authenticated.

Title: API Key DDOS protection


答:
Why would I not use ISO 3166-1 alpha-2 country codes?

Because I use STANAG 1059 country codes... and in that UK is the code for the United Kingdom (instead of GB as per ISO 3166-1).

Alternatively I could use the FIPS country codes - again UK is the country code for the United Kingdom.

There are many standards (ISO and non-ISO) and sometimes a particular domain uses/demands a standard which is incompatible with the ISO standard.


问:
How to handle a Restful Call in a RESTless state?
I have a bit of a dilemma. We are choosing our DBContext using a dynamic builder. This is done because in the current database structure we have a separate server for every "Customer". All of these Customer Databases use the same model so they are all exactly the same structure.

Enter picking the context to use with each call. We are using WebApi 2 and angular.

What we do is on the first "page" you pick your customer and we pass the customerId down and I need to store this value until the user decides to swap. That being said Session and WebApi2 are not friends.

I have a base repository that needs the customerId every time a call is made to one of the repositories. We have to verify that we are using the right context for that customer.

So.... That's where I am.

Should I break the rules and use Session to store the customerId? I could use my DI container to inject an instance of HttpContext.Current into every call so that I would ignore the fact that session is null on a WebApiController.

Is there another way to handle this?

答:
I would store this next to your authentication.

If you are using OAuth 2.0 Tokens for example you could add an Claim where you set the customerId. If you are using cookie based authentication I would set the customerId inside a cookie and resolve it every request.

This way you don't keep any state on your server, but always have the CustomerId available. Because the user sends you the data in every request.

Next you could write a DelegatingHandler where you resolve the CustomerId. Then you could add it as a claim to the current user (ClaimsPrincipal) or whatever fits your framework. This is also a nice place to reject any requests that don't include a customerId.

But much off this depends on the way you handle your authentication logic.


问:
In a large statically-typed software project with non-dynamic manual sql statements inside of it, how do you verify all the sql syntax?
One of the things I seem to struggle with frequently is the need to deploy a software application to test the database interaction.  More often than I'd like, I have a syntax error or typo in my sql statement that triggers a runtime error when the statement is invoked.
In some of these projects, there is a very large number of sql queries (>100), which makes it very time consuming if I need check each one. Also, deployment and runtime steps can be so time consuming that it slows me down when checking sql I modified.

Most of the time after checking out an unfamiliar codebase or one I haven't touched in some time, it is taken on faith that all of the sql works correctly.

What are standard practices around verifying database interaction in applications in a non-manual\more automatic fashion?

答:
You could refactor your applications to use Hibernate, or some other framework which generates queries for you automatically, but it sounds like this is legacy code that was not written with such frameworks in mind.

I found this on SO: https://stackoverflow.com/questions/5015613/online-sql-syntax-checker-conforming-to-multiple-databases ...also this: https://stackoverflow.com/questions/7753081/are-there-any-sql-validators-that-can-check-syntax-against-multiple-database-ser

One link seems to be a formatter that also checkes syntax: http://www.wangz.net/cgi-bin/pp/gsqlparser/sqlpp/sqlformat.tpl and an online version: http://www.dpriver.com/pp/sqlformat.htm

Unfortunately, it looks like it's a desktop application or VS add-in so it might only do MS SQL. For what you're suggesting, it would be better to have some tool that can be run from the command line as a part of build process. The closest thing I can think of to that would be attempting to get an execution plan for each query because that would let you know if there's any syntax errors, but your build process would need to make a connection to the database to actually get the query plan.

From the links above, I've found an online tool here: http://developer.mimer.com/validator/
It validates against SQL ANSI standards.

Also found an online tool for MySQL: http://www.piliapp.com/mysql-syntax-check/

For MS SQL there's this one: http://www.ubitsoft.com/products/t-sql-analyzer/

And there's also http://sqlfiddle.com/ which is a lot more than a validator.


问:
Why are some files in programming projects named "commons"?
I have seen numerous projects have a file named commons for example:

```<code>commomns.go
</code>```

I was wondering, why was this convention adopted and what did the meaning of naming a file or a package or something as commons?

答:
commonly used

While writing code, one often finds themselves with a common set of tools/classes/libraries that are used again and again across multiple projects.

The other classic name for this is 'util', but 'util' classes are sometimes seen as an anti-pattern.  Even though thats what these are, such a name can sometimes set off a developer's anti pattern senses and just avoid them for good measure.

the commons

Some projects have a 'commons' associated with them.  For example, Wikimedia Commons is stuff to be shared and used.  The commons also refers to a particular set of resources:

Commons refers to the cultural and natural resources accessible to all members of a society, including natural materials such as air, water, and a habitable earth. These resources are held in common, not owned privately. The resources held in common can include everything from natural resources and common land to software. The commons contains public property and private property, over which people have certain traditional rights. When commonly held property is transformed into private property this process alternatively is termed "enclosure" or more commonly, "privatization."

From wikipedia: Commons

These are things to be shared.  A cultural public good that has been gifted to the community.  There is a great deal more in the Wikipedia Commons page that can be put in this text area.  To sum it up, there is a lot of connotations associated with the concepts of sharing and the commons that dates back centuries.  See also the digital comons.


问:
What is the best way for a programmer to handle being code reviewed?
I am fairly new to code review, but I have been coding for years during my PhD - which doesn't always make you a good programmer!

If the reviewer changes your code and goes through it with you line-by-line, what do you do if you disagree?  Sometimes you made choice X and the reviewer changes it to Y, and you had Y in your mind but decided not to do it because of the disadvantages, but the reviewer asserts that those disadvantages are not important. Should you verbalise your disagreement, or just not and listen to them?

Its difficult if you are not good at accepting criticism, and if the reviewer is a more senior person in the organisation.  It would not be good to come across as too defensive.

答: Code review is probably a good thing in general, but from my experience it is best served as a tool for developers on new teams using new coding guidelines or for fixing important bugs, so that the risk of doing errors gets reduced. If you believe that you know better than the reviewer, you should ask why the solution he or she proposes is better and argument with your insights on the matter. Nobody knows everything best, so code review should or could be a valuable learning experience for both. </p>


答: You should write test cases for all the database interactions. Given that syntax checking is a concern, you should run them against a test database running the same database software your application is using. If you can get a good representative data sample, then this also provides an opportunity to check your queries for performance.</p>

Title: In a large statically-typed software project with non-dynamic manual sql statements inside of it, how do you verify all the sql syntax?

Body:
One of the things I seem to struggle with frequently is the need to deploy a software application to test the database interaction.  More often than I'd like, I have a syntax error or typo in my sql statement that triggers a runtime error when the statement is invoked.
In some of these projects, there is a very large number of sql queries (>100), which makes it very time consuming if I need check each one. Also, deployment and runtime steps can be so time consuming that it slows me down when checking sql I modified.

Most of the time after checking out an unfamiliar codebase or one I haven't touched in some time, it is taken on faith that all of the sql works correctly.

What are standard practices around verifying database interaction in applications in a non-manual\more automatic fashion?


答:
I'd skip the properties file. Since you're keeping data about database tables, it only makes sense to keep it in the database.

If the data in the "checkbox" columns is part of the data already in the tables, then go ahead and just add the columns for it.  If it's metadata that's not related to the data in the table, then create a separate table for it. Denormalizing your database for UI purposes is a design smell.  It's hard to give any further advice with just the information given.


答:
And when you verify that the syntax is ok, how you plan to verify that your queries are ok and return the expected data?. Is perfectly posible, in fact the most usual, that your queries are syntactically correct but logically incorrect.

Test your application, if test manually its time consuming and impractical (and of course it is in every non trivial system) do automatic testing.


答:
"commons" or "util" are normally used for shared code between different parts of a complex project. And off course are a very good example of bad naming and laziness and normally end up as a bag for crap.

What type of things you can find inside a common library in a project?, who knows!, surprise me!.

Title: Why are some files in programming projects named "commons"?

Body:
I have seen numerous projects have a file named commons for example:

```<code>commomns.go
</code>```

I was wondering, why was this convention adopted and what did the meaning of naming a file or a package or something as commons?


问:
"Undoing" an integer wraparound
I ran into an interesting theoretical problem a number of years ago. I never found a solution, and it continues to haunt me when I sleep.

Suppose you have a (C#) application that holds some number in an int, called x. (The value of x is not fixed). When the program is run, x is multiplied by 33 and then written to a file.

Basic source code looks like this:

```<code>int x = getSomeInt();
x = x * 33;
file.WriteLine(x); // Writes x to the file in decimal format
</code>```

Some years later, you discover that you need the original values of X back. Some calculations are simple: Just divide the number in the file by 33. However, in other cases, X is large enough that the multiplication caused an integer overflow. According to the docs, C# will truncate the high-order bits until the number is less than int.MaxValue. Is it possible, in this case, to either:

Recover X itself or

Recover a list of possible values for X?

It seems to me (though my logic could certainly be flawed) that one or both should be possible, since the simpler case of addition works (Essentially if you add 10 to X and it wraps, you can subtract 10 and wind up with X again) and multiplication is simply repeated addition. Also helping (I believe) is the fact that X is multiplied by the same value in all cases - a constant 33.

This has been dancing around my skull at odd moments for years. It'll occur to me, I'll spend some time trying to think through it, and then I'll forget about it for a few months. I'm tired of chasing this problem! Can anyone offer insight?

(Side note: I really don't know how to tag this one. Suggestions welcome.)

Edit: Let me clarify that if I can get a list of possible values for X, there are other tests I could do to help me narrow it down to the original value.

答:
As always, there is a solution from a scientist and solution from an engineer.

Above you will find a very good solution from a scientist, which works always, but requires you to calculate “multiplicative inverse”.

Here is a quick solution from engineer, which will not force you to try all possible integers.

```<code>val multiplier = 33 //used with 0x23456789
val problemAsLong = (-1947051863).toLong & 0xFFFFFFFFL

val overflowBit = 0x100000000L
for(test <- 0 until multiplier) {
  if((problemAsLong + overflowBit * test) % multiplier == 0) {
    val originalLong = (problemAsLong + overflowBit * test) / multiplier
    val original = originalLong.toInt
    println(s"$original (test = $test)")
  }
}
</code>```

What are the ideas?

We got overflow, so let’s use larger types to recover (Int -> Long)

We probably lost some bits due to overflow, let’s recover them

The overflow was not more than Int.MaxValue * multiplier

Full executable code is located on http://ideone.com/zVMbGV

Details:

val problemAsLong = (-1947051863).toLong & 0xFFFFFFFFL

Here we convert our stored number to Long, but since Int and Long are signed, we have to do it correctly.

So we limit the number using bitwise AND with bits of Int.

val overflowBit = 0x100000000L

This bit or multiplication of it could be lost by initial multiplication.

It's a first bit outside of Int range.

for(test <- 0 until multiplier)

According to 3rd Idea the maximal overflow is limited by multiplier, so don’t try more than we really need.

if((problemAsLong + overflowBit * test) % multiplier == 0)

Check if by adding possibly lost overflow we come to a solution

val original = originalLong.toInt

Original problem was in Int range, so let’s return to it. Otherwise we could incorrectly recover numbers, which were negative.

println(s"$original (test = $test)")

Don’t break after the first solution, because there are could be other possible solutions.

PS: 3rd Idea is not strictly correct, but left so to be understandable.

Int.MaxValue is 0x7FFFFFFF, but maximal overflow is 0xFFFFFFFF * multiplier.

So the correct text would be “The overflow was not more than -1 * multiplier”.

This is correct, but not everybody will understand it.

Title: "Undoing" an integer wraparound

Body:
As always, there is a solution from a scientist and solution from an engineer.

Above you will find a very good solution from a scientist, which works always, but requires you to calculate “multiplicative inverse”.

Here is a quick solution from engineer, which will not force you to try all possible integers.

val multiplier = 33 //used with 0x23456789
val problemAsLong = (-1947051863).toLong & 0xFFFFFFFFL

val overflowBit = 0x100000000L
for(test <- 0 until multiplier) {
  if((problemAsLong + overflowBit * test) % multiplier == 0) {
    val originalLong = (problemAsLong + overflowBit * test) / multiplier
    val original = originalLong.toInt
    println(s"$original (test = $test)")
  }
}

What are the ideas?

We got overflow, so let’s use larger types to recover (Int -> Long)

We probably lost some bits due to overflow, let’s recover them

The overflow was not more than Int.MaxValue * multiplier

Full executable code is located on http://ideone.com/zVMbGV

Details:

val problemAsLong = (-1947051863).toLong & 0xFFFFFFFFL

Here we convert our stored number to Long, but since Int and Long are signed, we have to do it correctly.

So we limit the number using bitwise AND with bits of Int.

val overflowBit = 0x100000000L

This bit or multiplication of it could be lost by initial multiplication.

It's a first bit outside of Int range.

for(test <- 0 until multiplier)

According to 3rd Idea the maximal overflow is limited by multiplier, so don’t try more than we really need.

if((problemAsLong + overflowBit * test) % multiplier == 0)

Check if by adding possibly lost overflow we come to a solution

val original = originalLong.toInt

Original problem was in Int range, so let’s return to it. Otherwise we could incorrectly recover numbers, which were negative.

println(s"$original (test = $test)")

Don’t break after the first solution, because there are could be other possible solutions.

PS: 3rd Idea is not strictly correct, but left so to be understandable.

Int.MaxValue is 0x7FFFFFFF, but maximal overflow is 0xFFFFFFFF * multiplier.

So the correct text would be “The overflow was not more than -1 * multiplier”.

This is correct, but not everybody will understand it.


问:
How to design extension mechanism for java app
I have an application where I have a set of core features.

The application itself HAS to work in core only mode.

I would also want to make the application extensible such that, when certain jar/plugin files exist in the classpath/installation location, additional features would be available, things would just be there. This is OPTIONAL.

The way I would do it is using the factory pattern with a modification.
In the core package, I have an extension point (implemented by either a public static variable or a singleton, or other extension point model from my framework - Eclipse RCP). The extension jars/plugins get this extension point and registers its factory object to this extension point. (This is best done with RCP plugin/feature activation mechanism, or it can just be anything that causes a load of the extension jar/plugin factory class)

When the application runs, the core factory would produce objects from the extension factory if one has been registered or use its core factory otherwise.
This is how the application goes from core mode to extension mode if an extension jar exists.

I wonder if this is a decent way to do what I wanted to do or this is just a hack, anti-pattern, etc...
Please propose a better solution if you can. Thanks.

答:
Java has a standard mechanism precisely for this, the java service providers, thinks in the way you use a JDBC plugin, you put the JDBC driver in your classpath and your application now can connect to this concrete database provider (oracle, mysql). In fact this is used in a lot of java standards that define an interface an allow different implementations.

Its not very different from you implementation, but its a standard and there are some classes in the jdk to make this easy to implement, for example take a look to this: http://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html


问:
syncing code with repo/backup
I am doing a small software project on my local PC. I'm the only person working on this. I'd like to back this up to the cloud every day so that if anything happens to my HDD I have a various copies going back in time.

I have a box account although that seems to want to sync continuously and with constant file changes with code I don't really want this.

Can anyone recommend any site or software that will allow me to back up to an external location online? I'm happy to manually kick off this process at the end of each day.

答:
If it's a software project, you should absolutely be using version control, even if you're the only developer. It'll also take care of the backup aspect if you use a repository that's on another machine. I recommend Git. GitHub is a good repository host and free for open source projects.

For my general purpose backup needs I've been very happy with CrashPlan. It runs silently in the background and backups what you want automatically, so that the backups are always up to date (the backup interval is configurable). It keeps multiple old versions of files, which is a life saver when you have deleted or overwritten the wrong files. CrashPlan is free if you backup to your own machines or disks - the online backup costs a little.

Title: syncing code with repo/backup


问:
Why do binary files load quicker than alphanumeric text files?
I've noticed that when I load/store large data files in a binary format, the program runs much faster than if I load data from an ASCII encoded file.

Why is this the case? The data in my case is plain, with limited parsing involved other than read() or fscanf().

答: Using fscanf() in itself probably explains most of it. fscanf() has to interpret the passed-in format string, and then has to scan the input stream from the file, trying to match the specified pattern. That's actually a huge amount of work. read() just has to read in the specified number of bytes from the file and doesn't have to do any parsing of the input. By contrast, fgets() does a little more work than read() since it has to watch for newlines, but it does a lot less work than fscanf().


问:
Deferred execution of Dispose for IDisposable objects
I'm working on an application that does lots of encryption and decryption in-application and this is probably the number-one bottleneck, so I've been spending some time making performance tweaks to it.  A lot of this has involved simply caching things in memory (I realize there is something of a security tradeoff in doing that), but I noticed during profiling that Dispose() was a fair amount of the time doing decryption (I believe for .NET cryptography stuff it zeroes over everything so this makes sense).  So I came up with this idea:

Have a "dispose pool."  Instead of using blocks, create objects, use them, return the result, and add them to the dispose pool in the finally block.  Internally, the dispose pool uses a queue and a timer and every time the timer fires it dequeues the objects and disposes them.

I tried implementing this and it seems to work and improve performance, but then again, profiling it locally is not a really realistic use case.  Is this sound?  Am I likely to run into runaway performance issues I'm not currently thinking about?

I suppose I should add that this is an ASP.NET MVC application so everything revolves around requests.

答:
You might take a look at Microsoft's ScheduledDisposable.  I've never used it, but it looks as though it will queue your objects for disposal on a separate thread.

But if a pool is what you're looking for, I think this will work:

```<code>public interface IDisposableWrapper<TDisposable> : IDisposable where TDisposable : class, IDisposable
{
    TDisposable Reference { get; }
}

public interface IDisposableWrapperFactory<TDisposable> where TDisposable : class, IDisposable
{
    IDisposableWrapper<TDisposable> Create();
}

public sealed class ReusableDisposableFactory<TDisposable> : IDisposableWrapperFactory<TDisposable>, IDisposable
    where TDisposable : class, IDisposable
{
    readonly object padlock = new object();
    Func<TDisposable> getReference;
    Stack<TDisposable> stack;
    int capacity;

    public ReusableDisposableFactory(Func<TDisposable> getReference, int capacity)
    {
        if (getReference == null)
            throw new ArgumentNullException("getReference");
        this.stack = new Stack<TDisposable>(capacity);
        this.capacity = capacity;
        this.getReference = getReference;
    }

    bool IsDisposed { get { return stack == null; } }

    void ThrowOnDisposed()
    {
        if (IsDisposed)
            throw new ObjectDisposedException(GetType().Name);
    }

    sealed class ReusableDisposableWrapper : IDisposableWrapper<TDisposable>
    {
        ReusableDisposableFactory<TDisposable> factory;
        TDisposable reference;

        internal ReusableDisposableWrapper(ReusableDisposableFactory<TDisposable> factory, TDisposable reference)
        {
            if (factory == null)
                throw new ArgumentNullException("factory");
            this.factory = factory;
            this.reference = reference;
        }

        public bool IsDisposed { get { return reference == null; } }

        #region IDisposableWrapper<TDisposable> Members

        public TDisposable Reference
        {
            get { return reference; }
            private set { reference = value; }
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            // Dispose of unmanaged resources.
            Dispose(true);
            // Suppress finalization.  Since this class actually has no finalizer, this does nothing.
            GC.SuppressFinalize(this);
        }

        void Dispose(bool disposing)
        {
            if (disposing)
            {
                // Free any other managed objects here.
                var reference = Interlocked.Exchange(ref this.reference, null);
                if (reference != null)
                    factory.DisposeReference(reference);
            }
            // Free any unmanaged objects here.
        }

        #endregion

        public override string ToString()
        {
            var theReference = Reference;
            if (IsDisposed || theReference == null)
                return base.ToString() + ": Disposed";
            else
                return base.ToString() + ": " + theReference.ToString();
        }
    }

    #region IDisposableWrapperFactory<TDisposable> Members

    public IDisposableWrapper<TDisposable> Create()
    {
        lock (padlock)
        {
            ThrowOnDisposed();
            TDisposable reference;
            if (stack.Count > 0)
            {
                reference = stack.Pop();
            }
            else
            {
                reference = getReference();
            }
            return new ReusableDisposableWrapper(this, reference);
        }
    }

    void DisposeReference(TDisposable reference)
    {
        lock (padlock)
        {
            if (reference == null)
                return;
            ThrowOnDisposed();
            if (stack.Count < capacity)
            {
                stack.Push(reference);
            }
            else
            {
                reference.Dispose();
            }
        }
    }

    #endregion

    #region IDisposable Members

    public void Dispose()
    {
        // Dispose of unmanaged resources.
        Dispose(true);
        // Suppress finalization.  Since this class actually has no finalizer, this does nothing.
        GC.SuppressFinalize(this);
    }

    void Dispose(bool disposing)
    {
        if (disposing)
        {
            lock (padlock)
            {
                if (!IsDisposed)
                {
                    while (stack.Count > 0)
                    {
                        var reference = stack.Pop();
                        reference.Dispose();
                    }
                    stack = null;
                    getReference = null;
                }
            }
        }
        // Free any unmanaged objects here.
    }

    #endregion

    public override string ToString()
    {
        string str = base.ToString();
        if (!Monitor.TryEnter(padlock))
        {
            // Don't block for ToString()
            str = str + ", locked.";
        }
        else
        {
            try
            {
                if (IsDisposed)
                    str = str + ", Disposed";
                else
                    str = string.Format("{0}: {1} {2} cached", str, stack.Count, typeof(TDisposable).Name);
            }
            finally
            {
                Monitor.Exit(padlock);
            }
        }
        return str;
    }
}
</code>```

Note the factory itself is disposable.  I certainly would be reluctant to use this for finalizable objects however.

Body:
You might take a look at Microsoft's ScheduledDisposable.  I've never used it, but it looks as though it will queue your objects for disposal on a separate thread.

But if a pool is what you're looking for, I think this will work:

public interface IDisposableWrapper<TDisposable> : IDisposable where TDisposable : class, IDisposable
{
    TDisposable Reference { get; }
}

public interface IDisposableWrapperFactory<TDisposable> where TDisposable : class, IDisposable
{
    IDisposableWrapper<TDisposable> Create();
}

public sealed class ReusableDisposableFactory<TDisposable> : IDisposableWrapperFactory<TDisposable>, IDisposable
    where TDisposable : class, IDisposable
{
    readonly object padlock = new object();
    Func<TDisposable> getReference;
    Stack<TDisposable> stack;
    int capacity;

    public ReusableDisposableFactory(Func<TDisposable> getReference, int capacity)
    {
        if (getReference == null)
            throw new ArgumentNullException("getReference");
        this.stack = new Stack<TDisposable>(capacity);
        this.capacity = capacity;
        this.getReference = getReference;
    }

    bool IsDisposed { get { return stack == null; } }

    void ThrowOnDisposed()
    {
        if (IsDisposed)
            throw new ObjectDisposedException(GetType().Name);
    }

    sealed class ReusableDisposableWrapper : IDisposableWrapper<TDisposable>
    {
        ReusableDisposableFactory<TDisposable> factory;
        TDisposable reference;

        internal ReusableDisposableWrapper(ReusableDisposableFactory<TDisposable> factory, TDisposable reference)
        {
            if (factory == null)
                throw new ArgumentNullException("factory");
            this.factory = factory;
            this.reference = reference;
        }

        public bool IsDisposed { get { return reference == null; } }

        #region IDisposableWrapper<TDisposable> Members

        public TDisposable Reference
        {
            get { return reference; }
            private set { reference = value; }
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            // Dispose of unmanaged resources.
            Dispose(true);
            // Suppress finalization.  Since this class actually has no finalizer, this does nothing.
            GC.SuppressFinalize(this);
        }

        void Dispose(bool disposing)
        {
            if (disposing)
            {
                // Free any other managed objects here.
                var reference = Interlocked.Exchange(ref this.reference, null);
                if (reference != null)
                    factory.DisposeReference(reference);
            }
            // Free any unmanaged objects here.
        }

        #endregion

        public override string ToString()
        {
            var theReference = Reference;
            if (IsDisposed || theReference == null)
                return base.ToString() + ": Disposed";
            else
                return base.ToString() + ": " + theReference.ToString();
        }
    }

    #region IDisposableWrapperFactory<TDisposable> Members

    public IDisposableWrapper<TDisposable> Create()
    {
        lock (padlock)
        {
            ThrowOnDisposed();
            TDisposable reference;
            if (stack.Count > 0)
            {
                reference = stack.Pop();
            }
            else
            {
                reference = getReference();
            }
            return new ReusableDisposableWrapper(this, reference);
        }
    }

    void DisposeReference(TDisposable reference)
    {
        lock (padlock)
        {
            if (reference == null)
                return;
            ThrowOnDisposed();
            if (stack.Count < capacity)
            {
                stack.Push(reference);
            }
            else
            {
                reference.Dispose();
            }
        }
    }

    #endregion

    #region IDisposable Members

    public void Dispose()
    {
        // Dispose of unmanaged resources.
        Dispose(true);
        // Suppress finalization.  Since this class actually has no finalizer, this does nothing.
        GC.SuppressFinalize(this);
    }

    void Dispose(bool disposing)
    {
        if (disposing)
        {
            lock (padlock)
            {
                if (!IsDisposed)
                {
                    while (stack.Count > 0)
                    {
                        var reference = stack.Pop();
                        reference.Dispose();
                    }
                    stack = null;
                    getReference = null;
                }
            }
        }
        // Free any unmanaged objects here.
    }

    #endregion

    public override string ToString()
    {
        string str = base.ToString();
        if (!Monitor.TryEnter(padlock))
        {
            // Don't block for ToString()
            str = str + ", locked.";
        }
        else
        {
            try
            {
                if (IsDisposed)
                    str = str + ", Disposed";
                else
                    str = string.Format("{0}: {1} {2} cached", str, stack.Count, typeof(TDisposable).Name);
            }
            finally
            {
                Monitor.Exit(padlock);
            }
        }
        return str;
    }
}

Note the factory itself is disposable.  I certainly would be reluctant to use this for finalizable objects however.


问:
An algorithm for finding subset matching criteria?
I recently came up with a problem which I would like to share some thoughts about with someone on this forum. This relates to finding a subset. In reality it is more complicated, but I tried to present it here using some simpler concepts.

To make things easier, I created this conceptual DB model:

Let's assume this is a DB for storing recipes. Recipe can have many instructions steps and many ingredients.

Ingredients are stored in a cupboard and we know how much of each ingredient we have.

Now, when we create a recipe, we have to define how much of each ingredient we need. When we want to use a recipe, we would just check if required amount is less than available amount for each product and then decide if we can cook a dinner - if amount required for at least one ingredient is less than available amount - recipe cannot be cooked. Simple sql query to get the result.

This is straightforward, but I'm wondering, how should I work when the problem is stated the other way round, i.e. how to find recipies which can be cooked only from ingredients that are available?

I hope my explanation is clear, but if you need any more clarification, please ask.

答:
After your clarifications on the question, I would go by this logic to list recipeids  excluding any recipe with a missing/insufficient ingredient.</p>

```<code>SELECT recipeid
FROM recipeingredients RI
WHERE recipeid NOT IN (SELECT RI1.recipeid
                       FROM recipeingredients RI1
                       LEFT OUTER JOIN Ingredients I ON RI1.ingredientsid = I.id
                                                    AND RI1.Requiredquantity <= I.availablequantity
                       WHERE I.id IS NULL
                      )
</code>```

Body:
After your clarifications on the question, I would go by this logic to list recipeids  excluding any recipe with a missing/insufficient ingredient.

SELECT recipeid
FROM recipeingredients RI
WHERE recipeid NOT IN (SELECT RI1.recipeid
                       FROM recipeingredients RI1
                       LEFT OUTER JOIN Ingredients I ON RI1.ingredientsid = I.id
                                                    AND RI1.Requiredquantity <= I.availablequantity
                       WHERE I.id IS NULL
                      )


问:
Are there open-source JavaScript libraries addressing multiple browser tabs and client state for newer browsers?
There are a few new HTML5 features that have made it into recent browsers that allow sharing state among tabs, browser windows, same domain windows, etc. So it's probably gotten a little easier to write a web application that keeps a lot of state on the client and also manages state intelligently between tabs and/or windows.

There are currently libraries like Backbone.js that can help manage state in a single tab or a single window. Is there anything out there yet that helps with multiple tabs (or windows) managing global state, tab specific state, and cross-tab eventing without relying on the server to sync them all up?

答: I recently discovered Intercom, which uses local storage to implement broadcast messaging between windows. Local storage fires an event (onstorage) when data changes, so no polling is necessary. Intercom allows all pages on a domain to communicate, regardless of how they were opened.


问:
Is too much whitespace a bad thing?
I'm often told by my friends and colleagues that I use way to much whitespace. I guess I do use a little too much whitespace. I often add a line break almost after every line and large blocks of whitespace, often 3 or 4 lines because it helps me see what I've written and understand what I've written when I look back on it at a later time. I also think it just looks cleaner.

Although I can see two issues with this, 1) It can increase the file size of the source files, even just a line break every two or three lines can add up in a long file. I know that a good compiler will optimize all the white space out (I'm not actually sure, I think LLVM/Clang does this) but the source file is still large.

And 2) it may cause some people to think I'm embellishing my code to make it look longer and "bigger" to make others think I'm doing more work than I actually am (consider 3000 lines vs. 6000 lines, 3000 being newlines). Which I am not doing that by the way. Is using too much whitespace bad from a technical standpoint and/or a professional standpoint?

答:
There's two reasons why you should strongly consider not doing this:

Code is much harder to understand when you can't see all the relevant parts at once. By inserting a blank line between most lines, you're halving how much code you can see.

Consistency with other people's code is important in group projects. It doesn't matter too much which particular conventions the project follows as long as it's consistent. It's hard enough to understand large systems; it's harder still when each part has different indentation schemes, naming conventions and idioms.

Title: Is too much whitespace a bad thing?


答:
Whitespace is indeed useful it helps break up sections of text to make various parts more distinct and stand out "this is a block.  Look at it in that context."

Horizontal whitespace is used for indentation and scope to also give hints.  One of the dangers of putting too much vertical whitespace in is that the eye looses the ability to track the indentation.  In languages without {}, this can be disastrous for the context of the code.

That context is very important.  If something isn't on the screen, you can't quickly scan back to it - you have to scroll to it.  This can mean either losing the code you were just looking at and having to move the hand to the mouse.  These things take time and some expenditure of mental energy.  While it can be a small amount of mental energy, it is still some unnecessary expenditure.

Lets actually look at this and get some code.  This is from _header_value_parser.py

The text doesn't matter too much, but note that thats quite a bit less on the screen.  One can't even get the full method in the page.  And there is questions about where some of the blocks line up - the eye doesn't travel that well keeping things in line to far (it becomes more obvious in the full size image - does line 176 line up with the scope of 135 or 133?).

Its not about how many lines you are checking in (any one counting code checkin metrics is using source lines of code instead which discounts white space and may also discount comment lines).  Its about keeping things in easy swap distance of the eye and the mind.

Title: Is too much whitespace a bad thing?

Body:
I'm often told by my friends and colleagues that I use way to much whitespace. I guess I do use a little too much whitespace. I often add a line break almost after every line and large blocks of whitespace, often 3 or 4 lines because it helps me see what I've written and understand what I've written when I look back on it at a later time. I also think it just looks cleaner.

Although I can see two issues with this, 1) It can increase the file size of the source files, even just a line break every two or three lines can add up in a long file. I know that a good compiler will optimize all the white space out (I'm not actually sure, I think LLVM/Clang does this) but the source file is still large.

And 2) it may cause some people to think I'm embellishing my code to make it look longer and "bigger" to make others think I'm doing more work than I actually am (consider 3000 lines vs. 6000 lines, 3000 being newlines). Which I am not doing that by the way. Is using too much whitespace bad from a technical standpoint and/or a professional standpoint?


答:
Beside the other good answers, there are also tools issues. Good text editors will provide facilities (like highlighting) to match opening and closing brackets. But some of them, like gedit, won't do it when they are too far away. Of course it means you should also avoid long methods, but too much vertical blank can also harm.

Blank lines can be usefull to help making a program easy to read if they are used to separate logical blocks (like paragraphs in a text). If everything is separated that's like if nothing was.

Title: Is too much whitespace a bad thing?


答:
I recommend the Google Style Guides for the programming language you are using. I abide to these rules and they usually lead to clean-looking code. There are somethings I add myself (like 2 blank lines between functions) but overall I really like the Google Style Guides.

Update:

The different style guides vary a bit per language, as these are put together by different engineers who devote all their time working in that language, so what they have written down is what they believe leads to clean-looking code. It seems that overall, the rule of thumb is to only use blank lines to distinguish code groups. Multiple consecutive blank lines are hardly ever encouraged. Here's some excerpts from these guides:

Java

A single blank line appears:

Between consecutive members (or initializers) of a class: fields, constructors,
  methods, nested classes, static initializers, instance initializers.

Exception: A blank line between two consecutive
    fields (having no other code between them) is optional. Such blank lines are used as needed to
    create logical groupings of fields.

Within method bodies, as needed to create logical groupings of statements.

Optionally before the first member or after the last member of the class (neither
  encouraged nor discouraged).

As required by other sections of this document (such as Section 3.3,
  Import statements).

Multiple consecutive blank lines are permitted, but never required (or encouraged).

Python

Two blank lines between top-level definitions, be they function or class definitions. One blank line between method definitions and between the class line and the first method. Use single blank lines as you judge appropriate within functions or methods.

C++

Minimize use of vertical whitespace.

This is more a principle than a rule: don't use blank lines when you don't have to.  In particular, don't put more than one or two blank lines between functions, resist starting functions with a blank line, don't end functions with a blank line, and be discriminating with your use of blank lines inside functions.

The basic principle is: The more code that fits on one screen, the easier it is to follow and understand the control flow of the program.  Of course, readability can suffer from code being too dense as well as too spread out, so use your judgement.  But in general, minimize use of vertical whitespace.

Some rules of thumb to help when blank lines may be useful:

Blank lines at the beginning or end of a function very rarely help readability.

 Blank lines inside a chain of if-else blocks may well help readability

Objective-C

Blank lines before and after @interface, @implementation, and @end are optional. If your @interface declares instance variables, a blank line should come after the closing brace (}).

Unless an interface or implementation is very short, such as when declaring a handful of private methods or a bridge class, adding blank lines usually helps readability.

I only put the information here regarding vertical whitespace, but some of the guides also have info on horizontal whitespace and a lot more formatting information (comments, blocks, indentation, etc...)

And the project is open source so if you have any suggestions you could email one of the project owners.

Title: Is too much whitespace a bad thing?


问:
How to learn new technologies in short period of time?
The title says it all. I'm a .NET programmer, working mostly on WPF applications with C#. But I need to be familiar with latest web development technologies, JavaScript, HTML5, CSS, ASP.NET MVC, latest WebAPI, Azure and other non .NET ones. I want to work on Windows Store apps & Windows Phone apps. I want to be an efficient programmer on Linux platform. I want to learn the inner details of communication technologies, specifically wireless communications, and program for them.

WCF, REST-ful services, C++, COM, hardware-communication, in depth details of an OS, using NoSql, Power Shell, virtualization technology, etc etc, the list goes on. I think you get the point. So, when so many interesting things are moving around your head, and making you a bit stressed out, what is the best approach, in general, to follow?

And what is the approach to follow when you are eager learn so much but in a shortest possible duration? Because the longer it takes to learn the current one in hand, the more I get depressed and stressed out looking at the rests on my list.

答:
So when so many interesting things are moving around your head, and making you a bit stressed out, what is the best approach to follow?

Pick one subject / technology and study that.  Then when you have mastered that one (to a sufficient level) move onto the next one.

Also, don't try to be good at everything.  It is not humanly possible.  And it is pointless stressing about something that you can't possibly do.

How to learn new technologies in short period of time?

Generally speaking, unless the new technology is similar to one that you are already using, you can't.  Effective learning takes time.  If you rush it, you will find that you didn't really learn.

But if you have the time and money, one of the best ways to learn quickly is to take a good face-to-face intensive training course with experienced trainers who really understand the subject matter.  (Then start using the stuff that you have been taught ... before you forget it all.)


问:
Requesting Advice Regarding Storing Encryption Keys
I am using HMAC to hash some data before inserting it in a database and currently I have my key as a static field.

Just wondering what the best practice regarding storing the key would be. Is having it in code good enough, or should it be in a configuration file.

Thanks!

答:
No, it should definitely not be in code. This means if you use source control it will be commited to the repository where anyone with access can see it. If it is in a config then you can ignore the config file.

You also normally want to have test environment keys vs production keys. With a config it's possible that none of the developers working on the code actually know the production key. The less people that know a secret the better.

There are also additional measures you can take to encrypt the config file. For example with .NET's app.config you can encrypt the config at a machine or user level using DPAPI.


问:
X509 certificate question on WCF
My condition:

A WCF service which is self-hosted and it's on a Win8 Machine.

Client is a WPF Program on another machine.

Then I follow the article on Codeproject about how to set X509 certificate for WCF.

Problem Description:

Communication between Client and Service was OK when they are on the same Machine.

When I put the Client on another machine, exception occurs that it says "The caller is not authenticated by the service".

I believe the cause of the exception above may be relevant to X509 Certificate.

When I put the Client.exe on another computer, I just generate a new certificate for client, is it right?

I want to know if the X509 Client certificate should be exported from the service Machine which has generated both client and server certificate, and then be imported into other Client Machine, or just use makecert.exe generate another certificate for other Client Machine?

In short, can the certificate be generated by any machine or only by the machine having generated the service certificate?

答:
Public key infrastructure always involves a key PAIR (public and private). When you are authorizing to a WCF service with an x509 certificate you must have the private key and the service you are calling must have the public key (which is inside the x509 certificate). It must be the same pair because only your private key's public key knows how to verify the private key's signature. The two are mathematically connected.

You can export the certificate from the certificate store then import it on the other server (using mmc with the ceriticate snap-in). It is also important that you transfer the certificate in a secure means AND/OR verify the hash of the certificate is correct before installing. If the wrong certificate was installed then someone else could access your service with THEIR private key.

Title: X509 certificate question on WCF


答: To expand on TMN's answer, it's very important to extract database logic into it's own layer. You should have classes that wrap every call to the database. This makes unit testing your database classes much easier. Once you have verified that all your Data Access Layer classes are working correctly with THEIR unit tests, you can mock them out in other classes unit tests because you are no longer testing data access in that particular test.</p>


问:
How to develop cross platform mobile applications with native UI and Javascript backend?
I want to build a cross platform(Android, iOS, Windows) mobile application.

I want the UX of the application to be different on the different platforms so that it will be more platform specific and does not force different platform users to stick to a common UI, as this common UI might not gel well in terms of look and feel with other native applications in their platform.
However since it is the same application that I am trying to build across all platforms my backend will mostly be the same.

This image presents what I am trying to achieve.

Is it possible to build different UI for each platform using native technologies like Storyboard(in iOS), XML(in Android), XAML(in Windows)
and then bind these UI elements to native controllers.
And making this controller use a common javascript backend for all the platforms.

I am aware of the concept of Native and Hybrid applications.
The problem that I would face with them are the following

Pure native applications will force me to make the entire source code platform specific which will make me write my backend thrice in 3 different languages. (Least reusable)

Hybrid applications(like those build on PhoneGap) will let me write my code in javascript and html but will create a common ui with HTML5/CSS3 which should be used across all platforms, I want to have different UI and for the UI to be more native than generic.

Is this common javascript backend code achievable.
And if it is then is there a way in which I can create this entire javascript code independently and package it as platform specific libraries like .a(for iOS), .jar(for Android), .dll(for Windows).
Or should I use some other approach?

Thanks in Advance

答:
If I've understood your question correctly then simply yes... Of course.

If you're building the mobile apps separately you can of course just connect to a backend API that you've created on a server. The server is completely independent of the app itself so it doesn't matter from where it's called. Think of any app the has a release on multiple OS's but allows you to log in to a access your independent account.


问:
Need help understanding a recursion example in Python
Python is my first programming language, and I'm learning it from "How to Think Like a Computer Scientist". In Chapter 5 the author gives the following example on recursion:

```<code>def factorial(n):
  if n == 0:
    return 1
  else:
    recurse = factorial(n-1)
    result = n * recurse
    return result
</code>```

I understand that if n = 3, then the function will execute the second branch. But what I don't understand is what happens when the function enters the second branch. Can someone explain it to me?

答:
What happens is that the function is called again, under the control of the first call, and after that there are two invocations of factorial active simultaneously (but the first one is waiting for the second one to return). Each of them has its own copy of n: the subordinate invocation has n == 2 while the original invocation still has n == 3. The subordinate invocation then calls itself another time, and so on, until there are four versions of the function in memory (but the first three are inactive, waiting for the last one to return).

The variable values and return addresses of all those invocations are kept on the call stack, and they disappear automatically when an invocation returns. (This is why a recursion that is too deeply nested can cause the phenomenon that this site was named after: the stack overflow.)

A good way to get your head around what really happens when a recursive function is called is to simulate the call stack with pen and paper, by writing down what versions of n there are at any given time and what their values are. A call to factorial 3 is just the right size for that exercise.


问:
Should each method have a separate JUnit test class?
I am writing JUnit unit tests for my classes.

Is it better to have a separate class for each method, or have just one test class for every actual class?

答:
How your tests are organized is rather unimportant compared to the importance of having them at all.

The most important thing for a good test suite is that it covers all of the functionality; that ensures that whenever a regression defect is introduced, you'll notice right away. Whether to write one test for each method, one test for each input value combination of a method, or even one test for each possible code path within that method is less important. Whether to organize these tests into few or many test classes is even less important: a test suite should always succeed in full, so it doesn't matter whether it fails one of three or two out of seventeen tests - both are wrong and must be fixed.

Of course, test code is also code, so it should follow the normal best practices for being maintainable, modular, etc. But that must be decided by how well-maintainable the test suite itself is, not by how the test classes relate to the classes they test. Both of the policies you mention can help you remember where to find things if you follow them consistently, but for that the consistency is more important than the choice of policy.