问:
How to convince my company (operating in the financial sector) to switch from PHP to Java
My company is in the financial sector and it is using PHP as programming language. I am a PHP developer myself.

I am leading a big project started from almost scratch. I can see how PHP is not the best candidate for building robust platforms.

I want to convince my company to gradually switch to Java (which I have experience with).

I was trying to find as many supporting arguments as possible. Can you help with this?

So far I have found these:

Most of the competitors are using Java (anyway not PHP)

Most financial companies use Java rather than PHP

On average, Java developers are better prepared (on average!)

The compilation process catches a lot of problems before the software runs in production

Strong typing makes everything more robust as contracts between interfaces is well defined

Any other points I am missing?

Thanks!

答:
Java code is easier to unit test.

This benefit might sound simple enough, but since your existing system is written in PHP, you may have other points to sell in order to make it sound appealing.

I know that there have been improvements in the area of testing PHP code using frameworks such as PHPUnit, but I am skeptical about the ability to automate these tests (after reading up on the latest PHPUnit documentation). As far as I know, there is still no true way to utilize continuous integration as there are no actual builds, only subversion (or other VCS) tags to roll back to in the event of discovered defects.

The last PHP project on which I worked (2 years ago), required the developers to come up with our own, project specific solution to run unit tests, which were expected to be manually run before requesting that code be deployed (meaning, plain text files moved) from our development server to our staging server. (Note use of the word 'expected', rather than 'required'.) Much room for human error.

Hope that helps!


问:
Query Language for Java Code Analysis
I want to write a refactoring tool for the Java programming language.

For this reason I need to do structural queries against the abstract syntax tree. Given this AST how do I get answers to the following statements:

Get superclasses of an object.

Give me the expression where I call a method x() on type XClass

Is method x() is called without arguments (check overloading)

Is method x() called anywhere in the execution path of object of type XClass (eg. is close() called anywhere)

答:
It rather depends on what generated your AST and how it looks.

But, if it's an XML format with a decent XSD/XMLSchema then I think "groovy" would be the best bet as it has excellent built in support for XML.

Actually it has two built in supports -- one API for xpath and one API for DOM.

Groovy is a scripting language built on top of Java. All valid java is valid Groovy, but, groovy also has many Dynamic features such a Dynamic data type, closures, Dictionaries as a built in datatype, native SQL support, native XML support, multiline string literals and lots of other goodies.

ContentLicense: CC BY-SA 3.0

Title: Query Language for Java Code Analysis


问:
How to shorten the case statement from hades?
I'm refactoring code and have reached a horribly gigantic switch statement.  Every single API method available to end users is represented as an enum and we have a switch statement iterating over the enum and responding to each possible API call.

Each individual enum option has only a few lines of code.  Any sufficiently complicated command gets a method call that is made.  However, with so many different enums ever a half dozen lines per enum grows to be rather huge.

What is the correct approach to make this cleaner?  I could write a unique method for every command, but I already moved all the complicated functionality to their own classes.  Does having a new method for a 4-5 lines of code only ever called once really add that much additional cleaneness to the code as a whole?

It seems rather tedious to create unique methods for all these cases, and the switch would still be a bit ugly even if it only allocated two lines to each enum (method call and break).  Is there a better way to avoid the switch statement entirely?

How would one try to keep this clean?

ps. this is in java, functional programing is clearly not an option.

答:
My advice would be to leave well alone.

A switch is the most efficient possible branching mechanism especially when coupled with an enum.

Anything else will incur a performance hit.

It may well be worth factoring out the inline code into separate methods for readability ( The JIT compiler will probably just inline them again -- so no overhead here ).

I personally find nothing wrong with two or three line methods if it helps readability.

Also for readability you could consider putting every case on a single line like so:----

```<code>switch {humungous_ENUM) {
    case OPTION_1:      exOption_1();            break;
    case OPTION_2:      exOption_2();            break;
     ......
    case OPTION_99:     exOption_99();           break;
    default:            exOption_error();
}
</code>```

Body:
My advice would be to leave well alone.

A switch is the most efficient possible branching mechanism especially when coupled with an enum.

Anything else will incur a performance hit.

It may well be worth factoring out the inline code into separate methods for readability ( The JIT compiler will probably just inline them again -- so no overhead here ).

I personally find nothing wrong with two or three line methods if it helps readability.

Also for readability you could consider putting every case on a single line like so:----

switch {humungous_ENUM) {
    case OPTION_1:      exOption_1();            break;
    case OPTION_2:      exOption_2();            break;
     ......
    case OPTION_99:     exOption_99();           break;
    default:            exOption_error();
}


问:
Does it make sense to write tests for legacy code when there is no time for a complete refactoring?
I usually try to follow the advice of the book Working Effectively with Legacy Code. I break dependencies, move parts of the code to @VisibleForTesting public static methods and to new classes to make the code (or at least some part of it) testable. And I write tests to make sure that I don't break anything when I'm modifying or adding new functions.

A colleague says that I shouldn't do this. His reasoning:

The original code might not work properly in the first place. And writing tests for it makes future fixes and modifications harder since devs have to understand and modify the tests too.

If it's GUI code with some logic (~12 lines, 2-3 if/else block, for example), a test isn't worth the trouble since the code is too trivial to begin with.

Similar bad patterns could exist in other parts of the codebase, too (which I haven't seen yet, I'm rather new); it will be easier to clean them all up in one big refactoring. Extracting out logic could undermine this future possibility.

Should I avoid extracting out testable parts and writing tests if we don't have time for complete refactoring? Is there any disadvantage to this that I should consider?

答:
Here's my personal unscientific impression: all three reasons sound like widespread but false cognitive illusions.

Sure, the existing code might be wrong. It might also be right. Since the application as a whole seems to have value to you (otherwise you'd simply discard it), in the absence of more specific information you should assume that it is predominantly right. "Writing tests makes things harder because there's more code involved overall" is a simplistic, and very wrong, attitude.

By all means expend your refactoring, testing and improvement efforts in the places where they add the most value with the least effort. Value-formatting GUI subroutines are often not the first priority. But not testing something because "it's simple" is also a very wrong attitude. Virtually all severe errors are committed because people thought they understood something better than they actually did.

"We will do it all in one big swoop in the future" is a nice thought. Usually the big swoop stays firmly in the future, while in the present nothing happens. Me, I'm firmly of the "slow and steady wins the race" conviction.


问:
Why is PHP's method of comparing different types bad?
I'm working on designing a new programming language and trying to decide how I will do variable comparisons.  Along with many different types of languages, I've used PHP for years and personally had zero bugs related to its comparison operations other than situations where 0 = false. Despite this, I've heard a lot of negativity towards its method of comparing types.

For example, in PHP:

```<code> 2  <  100      # True
"2" < "100"     # True
"2" <  100      # True
</code>```

In Python, string comparison goes like this:

```<code> 2  <  100      # True
"2" < "100"     # False
"2" <  100      # False
</code>```

I don't see any value in Python's implementation (how often do you really need to see which of two strings is lexicographically greater?), and I see almost no risk in PHP's method and a lot of value.  I know people claim it can create errors, but I don't see how.  Is there ever really going to be a situation where you are testing if (100 = "100") and you don't want the string to be treated as a number?  And if you really did, you could use === (which I've also heard people complain about but without any substantial reason).

So, my question is, not counting some of PHP's weird conversion and comparison rules dealing with 0's and nulls and strings mixed with characters and numbers, are there any substantial reasons that comparing ints and strings like this is bad, and are there any real reasons having a === operator is bad?

答:
Data on the Web is transmitted as strings, for example a GET request:
www.foo.bar/?number=2

Even though we intuitively know that this is a number that is sent as a request and not a string, technically it is a string since it is the only type of data you can get from an url.

IMO, Web languages such as PHP and Javascript have dynamic typing allowing automatic conversion of types depending on context mainly because of that. This is a pragmatic approach and I think this is also why they vastly dominate the Web.

I think that it's likely that if PHP had been created for another environment than the Web (like Python, C, whatever...) the typing rules would have been different and probably more strongly typed and less dynamic, but this is a Web language and dynamic typing fits the ecosystem it is in.


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答:
Probably the most dangerous one I've seen, because it gets accepted so readily, is that being able to write code quickly is good, and therefore the more quickly you can code [insert feature here] in a given language, the better the language is.

This is a serious example of premature optimization, since far more work goes into maintaining code than creating it.  This means that it's much more important to write code that's easy to read, comprehend and debug than code that's easy to write quickly, and facilitating easy-to-read code is a much more useful measurement of language quality.

ContentLicense: CC BY-SA 2.5


答:
Re: "The original code might not work properly":

Tests are not written in stone. They can be changed. And if you tested for a feature that was wrong, it should be easy to rewrite the test more correctly. Only the expected result of the tested function should have changed, after all.

Title: Does it make sense to write tests for legacy code when there is no time for a complete refactoring?

Body:
I usually try to follow the advice of the book Working Effectively with Legacy Code. I break dependencies, move parts of the code to @VisibleForTesting public static methods and to new classes to make the code (or at least some part of it) testable. And I write tests to make sure that I don't break anything when I'm modifying or adding new functions.

A colleague says that I shouldn't do this. His reasoning:

The original code might not work properly in the first place. And writing tests for it makes future fixes and modifications harder since devs have to understand and modify the tests too.

If it's GUI code with some logic (~12 lines, 2-3 if/else block, for example), a test isn't worth the trouble since the code is too trivial to begin with.

Similar bad patterns could exist in other parts of the codebase, too (which I haven't seen yet, I'm rather new); it will be easier to clean them all up in one big refactoring. Extracting out logic could undermine this future possibility.

Should I avoid extracting out testable parts and writing tests if we don't have time for complete refactoring? Is there any disadvantage to this that I should consider?


答:
There is a culture in some companies where they're reticent to allow developers any time to enhance code that doesn't directly deliver additional value e.g. new functionality.

I'm probably preaching to the converted here, but that is clearly false economy. Clean and concise code benefits subsequent developers. It is just that the payback isn't immediately evident.

I personally subscribe to the Boy Scout Principle but others (as you've seen) don't.

That said, software suffers from entropy and builds up technical debt. Previous developers short on time (or perhaps just lazy or inexperienced) may have implemented sub-optimal buggy solutions over well designed ones. Whilst it may seem desirable to refactor these, you risk introducing new bugs to what is (to the users anyway) working code.

Some changes are lower risk than others. For example, where I work there tends to be a lot of duplicated code that can safely be farmed out to a subroutine with minimal impact.

Ultimately, you have to make a judgement call as to how far you take the refactoring but there is undeniably value in adding automated tests if they don't exist already.


答:
I don't see anything about the financial impact in your question/arguments. You HAVE TO talk about this as well when presenting your idea and your arguments. This is a business and money is the only thing managers and stakeholders care about. As long as it's profitable, managers and stakeholders don't care if you code in C#, Java, PHP, Javscript or even COBOL (may God have mercy on your soul if you deal with this one).

This is obviously going to have a negative impact on all employees productivity and is going to cost the company a lot of money short-term and medium-term even though you mentioned a gradual switch to Java.

But, if you really strongly think that this will result in a PROFIT on the long run, then this should be your primary argument when making this suggestion. Otherwise, I kind of doubt you'll succeed. Oh, and make sure you have some proof about WHY this would be profitable on the long run. Just saying that it will doesn't make it true.

Good luck :) .

Title: How to convince my company (operating in the financial sector) to switch from PHP to Java

Body:
My company is in the financial sector and it is using PHP as programming language. I am a PHP developer myself.

I am leading a big project started from almost scratch. I can see how PHP is not the best candidate for building robust platforms.

I want to convince my company to gradually switch to Java (which I have experience with).

I was trying to find as many supporting arguments as possible. Can you help with this?

So far I have found these:

Most of the competitors are using Java (anyway not PHP)

Most financial companies use Java rather than PHP

On average, Java developers are better prepared (on average!)

The compilation process catches a lot of problems before the software runs in production

Strong typing makes everything more robust as contracts between interfaces is well defined

Any other points I am missing?

Thanks!


问:
What is stopping people from copy-pasting open-sourced codes into their own projects and releasing only the compiled binaries?
Hi I'm new to programming, and I've always wondered what would be the point of contributing open-sourced codes if there is no way to ensure everybody who uses the code will adhere to the licenses (or is there?).</p>

答:
Contributing on open source projects is, at least in my opinion, a very idealistic thing to do. Idealists thend to believe in the good in people - and that means, that other people don't steal source code to copy-paste it in their closed source projects.

On the other hand, music, movies, books can also be easily copied - and that has not (yet) stopped artists from publishing new stuff.


答:
For many people, it's vanity, getting your name associated with something awesome (that's why small OSS projects tend to stay small, and large ones tend to have to have very rigorous processes to vet potential new submitters, they simply get flooded with applications from everyone and their dog).

For others, it's an attempt to get others to do their coding for them. Throw a half baked idea out onto sourceforge (for example), hype about it using a few accounts with other names on slashdot (for example), and sit back and wait for the code to come in (which usually fails, but people still keep trying it after all these years).

Then there's people (and usually companies) who've something they developed in house for internal use and think would be useful for the world at large but they don't have the time, money, people, whatever to polish it up for sale and/or to market it (maybe it's something that doesn't fit into their existing product portfolio well for example). They put it out there as open source, using a foundation or other legal entity created for the purpose as a front to own and oversee development, stocked with initially their own people, and make it known (good marketing) that they're sponsoring that foundation (by hosting its website and allowing their employees to spend some of their work hours on it).

And then there's the real altruists, the people with their heads stuck in rose coloured clouds if you wish, who do it out of a sense of "everything should be free" (without considering that they can only contribute to those projects because they have a job doing exactly the same thing for pay).

Those together are probably 90%+ of contributors to open source projects. Legal issues like others using some of that code in their closed source projects don't matter to most of them, at least no more than as a nagging feeling somewhere. And it's not really much of an issue. If you see most open source licenses there's no restriction on commercial use of the open source library or product as part of something else. Many ask that you credit them if you do, but not even all of them.

And I seriously doubt the situation you describe comes up all that much. Most open source projects are not very suitable for it, either being tightly grouped libraries or complete products (and most of those not very mature, though the best ones are very good at all), so the effort needed to extract bits and pieces useful for your own use and splicing those into your product is likely to be higher than the effort needed to create the functionality from scratch (maybe using the OSS source as inspiration or guidance).

Title: What is stopping people from copy-pasting open-sourced codes into their own projects and releasing only the compiled binaries?

Body: Hi I'm new to programming, and I've always wondered what would be the point of contributing open-sourced codes if there is no way to ensure everybody who uses the code will adhere to the licenses (or is there?).</p>


答:
There are many Java libraries that provide ASTs parsed from Java source code or bytecode. Some examples:

Javac AST (used by JavaDoc, you can look at the JavaDoc source code for inspiration)

Soot

JastAddJ

Polyglot

I suggest that you pick one library after some research to see which one you prefer. There may be other tools out there, for example Eclipse JDT, which fit better. How you do each of the things you listed will vary between library/tool.

Title: Query Language for Java Code Analysis

Body:
I want to write a refactoring tool for the Java programming language.

For this reason I need to do structural queries against the abstract syntax tree. Given this AST how do I get answers to the following statements:

Get superclasses of an object.

Give me the expression where I call a method x() on type XClass

Is method x() is called without arguments (check overloading)

Is method x() called anywhere in the execution path of object of type XClass (eg. is close() called anywhere)


问:
Android Design - Service vs Thread for Networking
I am writing an Android app, finally (yay me) and for this app I need persistant, but user closeable, network sockets (yes, more than one).  I decided to try my hand at writing my own version of an IRC Client.

My design issue however, is I'm not sure how to run the Socket connectivity itself.  If I put the sockets at the Activity level, they keeps getting closed shortly after the Activity becomes non-visible (also a problem that needs solving...but I think i figured that one out)...but if I run a "connectivity service", I need to find out if I can have multiple instances of it running (the service, that is...one per server/socket).  Either that or a I need a way to Thread the sockets themselves and have multiple threads running that I can still communicate with directly (ID system of some sort).

Thus the question: Is it a 'better', or at least more "proper" design pattern, to put the Socket and networking in a service, and have the Activities consume said service...or should I tie the sockets directly to some Threaded Process owned by the UI Activity and not bother with the service implementation at all?  I do know better than to put the networking directly on the UI thread, but that's as far as I've managed to get.

答:
Just a suggestion (something I haven't yet tried w/Android, but should work).

Try putting a WebView in your main activity (so it won't die when you switch child activities) which includes a full DOM document and a child iframe element. Set the iframe's src attribute to a comet service you define, with a keep-alive header. Push the messages using comet. Works like a charm in chrome. If your back end doesn't support comet, you can set it up manually.


答:
Kilian's answer covers the most important aspects, but I want to expand on points 1 and 3.

If a developer wants to change (refactor, extend, debug) code, she has to understand it. She has to make sure her changes affect exactly the behavior she wants (nothing in the case of refactoring), and nothing else.

If there are tests, then she has to understand the tests as well, sure. At the same time, the tests should help her understand the main code, and tests are far easier to understand than functional code anyway (unless they're bad tests). And the tests help show what changed in the behavior of the old code. Even if the original code is wrong, and the test tests for that wrong behavior, that is still an advantage.

However, this requires that the tests are documented as testing preexisting behavior, not a specification.

Some thoughts on point 3, too: in addition to the fact that the "big swoop" rarely ever actually happens, there's also another thing: it isn't actually easier. To be easier, several conditions would have to apply:

The antipattern to be refactored needs to be easily found. Are all your singletons named XYZSingleton? Is their instance getter always called getInstance()? And how do you find your overly deep hierarchies? How do you search for your god objects? These require code metrics analysis and then manually inspecting the metrics. Or you just stumble over them as you work, as you did.

The refactoring needs to be mechanical. In most cases, the hard part of refactoring is understanding the existing code well enough to know how to change it. Singletons again: if the singleton is gone, how do you get the required information to its users? It often means understanding the local callgraph so that you know where to get the information from. Now what is easier: searching out the ten singletons in your app, understanding the uses of each (which leads to needing to understand 60% of the codebase), and ripping them out? Or taking the code that you already understand (because you're working on it right now) and ripping the singletons being used there out? If the refactoring isn't so mechanical that it requires little to no knowledge of the surrounding code, there's not use in bunching it up.

The refactoring needs to be automated. This is somewhat opinion-based, but here goes. A bit of refactoring is fun and satisfying. A lot of refactoring is tedious and boring. Leaving the piece of code you just worked on in a better state gives you a nice, warm feeling, before you move on to more interesting stuff. Trying to refactor an entire code base will leave you frustrated and angry at the idiot programmers who wrote it. If you want to do a big swoop refactoring, then it needs to be largely automated so as to minimize the frustration. This is, in a way, a meld of the first two points: you can only automate the refactoring if you can automate finding the bad code (i.e. easily found), and automate changing it (i.e. mechanical).

Gradual improvement makes for a better business case. The big swoop refactoring is incredibly disruptive. If you refactor a piece of code, you invariably get into merge conflicts with other people working on it, because you just split the method they were changing into five parts. When you refactor a reasonably-sized piece of code, you get conflicts with a few people (1-2 when splitting up the 600-line megafunction, 2-4 when breaking up the god object, 5 when ripping out the singleton from a module), but you would have had those conflicts anyway because of your main edits. When you do a codebase-wide refactoring, you conflict with everyone. Not to mention that it ties up a few developers for days. Gradual improvement causes each code modification to take a little longer. This makes it more predictable, and there isn't such a visible time period when nothing happens except cleanup.


答: Also re: "The original code might not work properly" - that doesn't mean you just change the code's behaviour without worrying about the impact. Other code may rely on what appears to be broken behaviour, or side-effects of the current implementation. Test coverage of the existing application ought to make it easier to refactor later, because it'll help you find out when you've accidentally broken something. You should test the most important parts first.</p>


问:
Git Repository Setup
I am moving my companys source control from TFS to GIT.
We have TFS currently defined as.

Project Collection /

/ Client A

/ Product A

/ Product B

/ Product C

/ Client B

/ Product D

/ Product E

/ Product F

What is the best way to do this in Git? I have thought about the following:

Repository (Client A)

Branch (Product A)

Branch (Product B)

Branch (Product C)

Repository (Client B)

Branch (Product D)

Branch (Product E)

Branch (Product F)

What do you think is the best approach as the design is slightly different?

答:
You should create a new repo for each independent project. Why?

Someone working on project D does not have to download all the history for E and F.

Git repos are cheap to initialize, so you can use as many as you like.

It is painful to work with multiple projects at once when they are represented as branches in a repo: When switching from A to B to quickly look up something, you'd have to stash your uncommitted changes, then check out the the other branch (which would rewrite the complete directory structure, expensive for large projects), then check out the original branch again and apply your stashed changes. It's not generally possible to view the projects side-by-side without cloning the repo multiple times.

The history will be a mess. When using Git, one will sometimes work on multiple  feature branches that get merged back in after a while. But when having a project per (main) branch, you'd have multiple parallel but absolutely unconnected branches. They share nothing, so why should they share the repo?

If a project depends on another project, you can use git submodules to connect the repos without having to put everything in a single repo.

Title: Git Repository Setup


问:
Unit of Work pattern
I have gone through many articles and I am still confused whether to use the Unit of Work pattern or not. I use generic repositories (Repository Pattern) but if my understanding of the UOW pattern is correct, most persistence tools today offer a unit of work pattern already implemented (DbContext, ObjectContext, DbSet). </p>

<p>I want to know if, in such cases, we should not try to implement the UOW pattern altogether? or I did see in one of the articles (sorry can't reference it since I missed it somewhere) that they had wrapped the DbContext inside an UOW class and I was left wondering what reason they might have of doing so. </p>

答:
I have went through this loop in the last few years, Unit Of Work, wrapping of repo's all calling Entity Framework.

You end up with a lot of pointless repository classes (with associated interface), probably wrapping a generic base repo class with a Unit Of Work on top that has lots of properties which expose the repo's.

And yes, you are correct, Entity Framework IS essentially a unit of work with repo's.

I am now at the point where I won't be doing that again for my next "from scratch" project and I'm looking at something more like this from Jimmy Bogard. (He's using an NHibernate session, but could equally be replaced by EF)

But what about mocking out the DBContext for unit tests? This can still be achieved by creating a Fake DBContext.

Please note. this is not a recommendation as such, just my current way of thinking, and I'm happy to hear about any issues this approach might have.

Title: Unit of Work pattern


答:
A few thoughts :

When you're refactoring legacy code, it doesn't matter if some of the tests you write happen to contradict ideal specifications. What matters is that they test the program's current behavior. Refactoring is about taking tiny iso-functional steps to make the code cleaner; you don't want to engage in bugfixing while you're refactoring. Besides, if you spot a blatant bug, it won't be lost. You can always write a regression test for it and temporarily disable it, or insert a bugfix task in your backlog for later. One thing at a time.

I'd agree that pure GUI code is hard to test and perhaps not a good fit for "Working Effectively ..." -style refactoring. However, this doesn't mean you shouldn't extract behavior that has nothing to do in the GUI layer and test the extracted code. And "12 lines, 2-3 if/else block" is not trivial. All code with at least a bit of conditional logic should be tested.

In my experience, big refactorings are not easy and they rarely work. If you don't set yourself precise, tiny goals, there's a high risk that you embark on a never-ending, hair-pulling rework where you'll never land on your feet in the end. The bigger the change, the more you risk breaking something and the more trouble you will have finding out where you failed.

Making things progressively better with ad hoc small refactorings isn't "undermining future possibilities", it's enabling them - solidifying the swampy ground where your application lies. You should definitely do it.


问:
Is saving SQL statements in a table for executing later a bad idea?
Is saving SQL statements in a MySQL table for executing later a bad idea? The SQL statements will be ready for execution, i.e. there will be no parameters to swap or anything, for example DELETE FROM users WHERE id=1.

I guess I'm being lazy, but I thought of this idea because I'm working on a project that will require quite a few cron jobs that will execute SQL statements periodically.

答: If you want to save SQL statements in a database for later execution, there's a better option than putting them in a table: use the built-in functionality provided for this specific purpose.  Put them in stored procedures.</p>


问:
RESTful API design. What should I return if there are no rows?
I'm currently coding an API for a social network with the Slim Framework. My question is: What are the best practices when there are no rows to return in the json structure?

Lets say that this call /v1/get/movies returns 2 rows from the table movie names:

```<code>[
    {"name": "Ghostbusters"},
    {"name": "Indiana Jones"}
]
</code>```

But, then I call /v1/get/books and there are no rows in that table. Should I just return an empty structure?

```<code>[
]
</code>```

...or would it be better a message and an error code?

```<code>[
    "errors": {
        "message": "no matches found",
        "code": 134
    }
]
</code>```

Which is a better practice? (the API will be used in iOS and Android apps) Thanks!

答:
I would "It depends".

If zero is a reasonable result then return the empty list. For example if you want to get all employees called "bob" where "none" is a quite reasonable result. If it's not an expected result return an error. For example getting a historical list of street addresses for a person you employ.. They must live somewhere so no result is probably an error, not just a normal condition.

I'm sure you can argue with the specifics of my example, but you get the idea...


问:
Find possible variations of one item out of multiple baskets.
I have three baskets of balls and each of them has 10 balls which have the following numbers:

Basket 1: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Basket 2: 11, 12, 13, 14, 15, 16, 17, 18, 19, 20

Basket 3: 21, 22, 23, 24, 25, 26, 27, 28, 29, 30

What would be the possible variations If I were to pick one ball from each basket? I guess this is called as Probability in Mathematics but not sure. How would you write this code in C#  (or any other programming language) to get the correct results?

Edit:

Based on @Kilian Foth's comment, here is the solution in C#:

```<code>class Program
{
    static void Main(string[] args)
    {
        IEnumerable<string> basket1 = new List<string> { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
        IEnumerable<string> basket2 = new List<string> { "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
        IEnumerable<string> basket3 = new List<string> { "21", "22", "23", "24", "25", "26", "27", "28", "29", "30" };

        foreach (var item1 in basket1)
        foreach (var item2 in basket2)
        foreach (var item3 in basket3)
        {
            Console.WriteLine("{0}, {1}, {2}", item1, item2, item3);
        }

        Console.ReadLine();
    }
}
</code>```

答:
What you are looking for is called a Cartesian product (or sometimes cross product). One possible algorithm is nested loops, but there is an extensive literature on the subject. Don't reinvent the wheel.

There is also an extensive answer here: https://stackoverflow.com/questions/1741364/efficient-cartesian-product-algorithm.


答:
It's safe, if that's what you're asking. As long as you're as careful about your security as you are with your data's security.

But don't reinvent the wheel, Stored Procedures ARE bits of SQL stored in a table. And they support, nay encourage, parameterisation.

Also note, you can make your security simpler AND reduce the number of points of failure AND reduce the network communications by using the MySql Event Scheduler instead of cron.

Other databases have equivalents to these, for good reason. You're not the first to need this functionality.

Title: Is saving SQL statements in a table for executing later a bad idea?

Body:
Is saving SQL statements in a MySQL table for executing later a bad idea? The SQL statements will be ready for execution, i.e. there will be no parameters to swap or anything, for example DELETE FROM users WHERE id=1.

I guess I'm being lazy, but I thought of this idea because I'm working on a project that will require quite a few cron jobs that will execute SQL statements periodically.


答:
I actually wrapped Entity Framework DbContext and DbSet into my own generic classes that follow the unit of work. The main reason to do so is unit testing.

I got my IUnitOfWork and IRepository interfaces that actually have got two implementations.

First one is EFUnitOfWork which wraps DbContext and IRepository for DbSet. This injected in production code whenever I expect an UnitOfWork.

Second one is a substitute for IUnitOfWork (I do use NSubstitute for doing mocks) and my own ListBasedInMemoryRepository that, as the name suggests, stores data in a list instead of Database.

This implementation is used in unit tests whenever I want to test code that would normally use Entity Framework. So my tests are now independent of actual database connection as they should be.

Title: Unit of Work pattern

Body:
I have gone through many articles and I am still confused whether to use the Unit of Work pattern or not. I use generic repositories (Repository Pattern) but if my understanding of the UOW pattern is correct, most persistence tools today offer a unit of work pattern already implemented (DbContext, ObjectContext, DbSet). </p>

<p>I want to know if, in such cases, we should not try to implement the UOW pattern altogether? or I did see in one of the articles (sorry can't reference it since I missed it somewhere) that they had wrapped the DbContext inside an UOW class and I was left wondering what reason they might have of doing so. </p>


答:
No, I would say it is not a good idea.

It means every "real" query/update will need 2 hits on the database - one to get the "real" query/update, and one to execute it.

This may not be a huge issue in a small system, but the more users/transactions your system gets, the less it will scale.

I am guessing this comes from looking for an alternative to embedding SQL in your code?

Encapsulating the SQL in a stored procedure as Mason Wheeler suggested, would be one way that be a lot better than this idea.


问:
iOS chat application design, sending/relaying the message over to the end user
I have a design question. Let us say you were tasked with building a chat application, specifically for iOS (iOS Chat Application). For simplicity let us say you can only chat with one person at a time (no group chat functionality).

How then can you achieve sending a message directly to an end user from phone A to phone B?

Obviously there is a web service layer with some API calls. One of the API calls available will be startChat(). After starting a chat, when you send a message, you make another async call, let us call it sendMessage() and pass in a string with your message. Once it goes to the web service layer, the message gets stored in a database.

Here is where I am currently stuck. After the message gets sent to the web service layer, how do we then achieve sending/relaying the message over to the end user? Should the web server send out a message to the end user and notify them, or should each client call a receiveMessage() method periodically, and if the server side has some info for them it can then respond with that info?

Finally, how can we handle the case in which the user you are trying to send a message to is offline? How can we make sure the end user gets the packet when he moves back to an area with signal?

答:
I´m assuming there is some sort of client ID involved in this solution. Then it´s simple, Client A sends a messages to the server with Client B´s ID, the server stores the Messages (perhaps a flag indicating that it hasn´t been read). Whenever Client B connects it asks the server if there is any unread messages, and if so, polls them.

In the case that Client B is connected whilst Client A sends a message then the server should directly distribute the message to Client B.

Best of luck


答:
The easy way out would be to have an .ini or other configuration flavor file to keep the queries in. This way you can have them in one place, change anything without having to access the database to do so, not hit the database multiple times and also you may want/need at some point to use parameters or add conditions to your queries (augment them with more complex stuff for a particular case in your code).

Of course you can keep them at database level (either in a table or, better yet, as stored procedures), however if you're as lazy as I am ;-) but are also concerned with performance, an .ini file and PHP's beloved parse_ini method to read it, are the way to go (if you're going for another programming language, you're on your own figuring out similar approaches)! Usually I would read this file in the application's bootloader and keep it in a static object (maybe with a cache layer on top) to really speed things up if we're talking about a very large number of distinct queries.


答:
Sorry, I don't think that is a good idea.

Consider the case where the table in question changes. Say your id column gets renamed to new_id.

As well as the change itself, there is a version of your code written for an old vintage of the database that may no longer run. Sure, you might know to check in the code table but it isn't immediately obvious for someone else.

For a change such as I've described, I'd typically look at standalone SQL files, stored procedures, triggers, in-line SQL in client code (VB, C#, C++ etc) but the last place I'd think to look is in the database tables. Although maybe I will now! :)


问:
Form cancellation. Where should any data rollback occur?
You have a form that has an object injected into it. The user interacts with the form and updates the injected object via the UI. If the user then 'Cancels' the form, whose responsibility is it to undo those changes?

Should the form have created a clone of the object passed in, and return that to the client? Or should the client watch for the 'Cancel' action and perform the undo action?

Is there a 'best practice' for this?

答:
Ideally, the UI shouldn't know about your business objects directly. It should know what it has to display and where to send any submission. The receiver of the submission should know how to process that submitted data with respect to your domain objects.

Thus there should be nothing to roll back, only form data to be discarded.

Sometimes you have to store form data somewhere, in case the submission is put on hold, or the application crashes, or whatever. In those cases, I would still suggest storing form data separately from domain data, making it just as easy to discard.

In the rare occasion where you might need to apply data changes and test it before rolling it back. If you absolutely can't use a staging area then use soft-deleting and history records, but definitely don't expose that to the UI. Only allow it to switch between revisions.


答:
If I am following correctly, you have clicked the save button, but then want the ability to discard those changes almost straight away.

There is a further complication here which may be that before hitting the cancel button, the user might make another change and hit Save.

So it could be the case that you store a history of the object in the database, track a "last version ID" and use that on Cancel postback to restore the last version.

Title: Form cancellation. Where should any data rollback occur?

Body:
You have a form that has an object injected into it. The user interacts with the form and updates the injected object via the UI. If the user then 'Cancels' the form, whose responsibility is it to undo those changes?

Should the form have created a clone of the object passed in, and return that to the client? Or should the client watch for the 'Cancel' action and perform the undo action?

Is there a 'best practice' for this?


问:
Next power of 2 for a number (in search for better "bit-twiddling" way)
I just wonder if there exists better (i.e. faster?) way to get the next
power of 2 for a given number than the following one (maybe some
better sort of "bit-twiddling" hack is possible?) ...

```<code>static size_t
npow2(size_t n)
{
        n--;
        n |= n >> 1;
        n |= n >> 2;
        n |= n >> 4;
        n |= n >> 8;
        n |= n >> 16;
        return n + 1;
}
</code>```

Thanks for your ideas.

答:
According to Sean Eron Anderson's collection of Bit Twiddling Hacks, that's probably the fastest way.

The alternatives are an IEEE float casting hack, which involves fewer C operations but ends up slower, and directly using the x86 BSR (bit scan reverse) machine instruction, but in Anderson's testing that didn't end up significantly faster than the above OR-ing trick.


答:
Don't assume that it's not possible to detect that a compiled binary is a copy of someone else's code.

For a start, all string literals go through the compilation process unchanged.  If a closed-source program has lots of string literals that match those of an open-source project, then it's bound to raise suspicions.

After that, there will be someone, somewhere, who is obsessive enough to decompile/reverse-engineer the code to work out that it's doing the same things as the open source library.

If the open-source code is from a major project, then the next thing is that you get a letter from their lawyers, suggesting that you might like to open source the project that contains the code you've copied.  If you fail to do that, the next step is a lawsuit.  During the discovery phase, they will ask you to present to the court your source code, to prove that it isn't just a copy of theirs.

If you lose the court case, you could be looking at damage payments, and being forced to withdraw your product from the market.


问:
ANSI C pointers corrupted values
I am working on ANSI C and having some issues with the pointers.

That is that after a point in my program the pointer's values change without me interfering, is something like overwriting them.

I know that this could happen in C, but while being a beginner, can not find a remedy for that.

Is there a straightforward way of solving this? As I understand, many people will have faced similar issues.

Thank you guys for your answers,were very helpful,was indeed a memory problem solved by just allocating larger blocks of memory!!!
Thank you again!!!!

答:
If you have values being changed and you didn't intentionally write code to change them, then in all likelihood, you are writing to an array and overwriting the buffer. This can do all sorts of things. Usually you will see functions getting called that you didn't intend to be called or not getting called etc... However, it can also corrupt your data. I would carefully investigate all of your memcpy, memmove, strcpy, and array loops and see if you find something. I am pretty sure, just looking at your compiler warnings will tell you what is going on. Msft likes to complain about use of the old c functions that weren't safe.

To avoid this problem, ALWAYS do range checks on arrays.

This may not be the problem, but it seems the most likely. If you would like some more hints, we need to see some code.

In reponse to your edit. Allocating more memory merely hides the symptoms. You have a bug in your code where you are not checking the bounds of your arrays properly before writing to them. Fix the bug, your problem is not really solved until you have done that.

Title: ANSI C pointers corrupted values


答:
You can do several things. On an unmodified 32-bit application in Windows you may be able to use DrMemory.

(I assume you already configured your compiler to issue all the warnings it can. Never understimate the potential troubles hiding behind a "warning").

You might also port your program to Linux (on a VMware virtual machine, maybe) and use Valgrind. Then as soon as you run the program, you will be informed of an array of possible mistakes in the code, complete with file name, line number and description.

Finally, there are "memory checking libraries" (eFence, but there are others) that you will compile/link with your ANSI C program, and will replace most ways in which you can mess up with memory. Sometimes you will also have to include calls to some check function, so that your code becomes something like:

```<code>CHECKPOINT
at = getAnotherTree(i++, info);
CHECKPOINT
</code>```

Then, if you perform a flawed standard call in getAnotherTree(), you will get an error such as

```<code>treebuild.c at line 597: strcpy: attempt to copy 192 bytes into 128-byte buffer
ABORTING
</code>```

and if you do that by hand, for example with

```<code>for (i = 0; i < bufSize; i++) {
    buffer[i] = 0;
}
</code>```

then the second checkpoint will throw an error such as

```<code>treebuild.c at line 1080: CHECKPOINT FAILURE
</code>```

thereby pinpointing the source of the error to something in the program flow between the last known good checkpoint and the failing one.

Title: ANSI C pointers corrupted values

Body:
I am working on ANSI C and having some issues with the pointers.

That is that after a point in my program the pointer's values change without me interfering, is something like overwriting them.

I know that this could happen in C, but while being a beginner, can not find a remedy for that.

Is there a straightforward way of solving this? As I understand, many people will have faced similar issues.

Thank you guys for your answers,were very helpful,was indeed a memory problem solved by just allocating larger blocks of memory!!!
Thank you again!!!!

Body:
You can do several things. On an unmodified 32-bit application in Windows you may be able to use DrMemory.

(I assume you already configured your compiler to issue all the warnings it can. Never understimate the potential troubles hiding behind a "warning").

You might also port your program to Linux (on a VMware virtual machine, maybe) and use Valgrind. Then as soon as you run the program, you will be informed of an array of possible mistakes in the code, complete with file name, line number and description.

Finally, there are "memory checking libraries" (eFence, but there are others) that you will compile/link with your ANSI C program, and will replace most ways in which you can mess up with memory. Sometimes you will also have to include calls to some check function, so that your code becomes something like:

CHECKPOINT
at = getAnotherTree(i++, info);
CHECKPOINT

Then, if you perform a flawed standard call in getAnotherTree(), you will get an error such as

treebuild.c at line 597: strcpy: attempt to copy 192 bytes into 128-byte buffer
ABORTING

and if you do that by hand, for example with

for (i = 0; i < bufSize; i++) {
    buffer[i] = 0;
}

then the second checkpoint will throw an error such as

treebuild.c at line 1080: CHECKPOINT FAILURE

thereby pinpointing the source of the error to something in the program flow between the last known good checkpoint and the failing one.


答:
Well, yes. Answering as a software test engineer. Firstly you should test everything you ever do anyway. Because if you don't, you don't know whether it works or not. This may seem obvious to us but I have colleagues who see it differently. Even if your project is a little one that may never be delivered, you have to look the user in the face and say you know it works because you tested it.

Non-trivial code always contains bugs (quoting a guy from uni; and if there are no bugs in it, it's trivial) and our job is to find them before the customer does. Legacy code has legacy bugs. If the original code doesn't work the way it should, you want to know about it, believe me. Bugs are ok if you know about them, don't be afraid to find them, that's what release notes are for.

If I remember rightly the Refactoring book says to test constantly anyway., so it's part of the process.


答:
I've done something similar.  iOS --(Sends request with message and id of recipient)--> Server --- Sends message over to recipient --> iOS

However I used notifications to do the final delivery.  This means the server has the tokens for the devices stored, once it determines who is who it sends a request to APNS.

Title: iOS chat application design, sending/relaying the message over to the end user

Body:
I have a design question. Let us say you were tasked with building a chat application, specifically for iOS (iOS Chat Application). For simplicity let us say you can only chat with one person at a time (no group chat functionality).

How then can you achieve sending a message directly to an end user from phone A to phone B?

Obviously there is a web service layer with some API calls. One of the API calls available will be startChat(). After starting a chat, when you send a message, you make another async call, let us call it sendMessage() and pass in a string with your message. Once it goes to the web service layer, the message gets stored in a database.

Here is where I am currently stuck. After the message gets sent to the web service layer, how do we then achieve sending/relaying the message over to the end user? Should the web server send out a message to the end user and notify them, or should each client call a receiveMessage() method periodically, and if the server side has some info for them it can then respond with that info?

Finally, how can we handle the case in which the user you are trying to send a message to is offline? How can we make sure the end user gets the packet when he moves back to an area with signal?


问:
Separate domain entity in small ones
I have the Customer entity, this entity has a huge list of attributes, so you are thinking in separate in small entities (for example: "basic info", "document", "declarations", etc). This approach will be used in the view layer, where the user can fill your info, step by step, making possible stop and comeback later. But I'm no sure if make sense to reflect this fragmentation in others layers. Because, we will have a lot of controllers in client and server side (since we are using express.js and angular.js).

Follows an overview of the complexity in terms of fields, remembering each "partial" must be valid and once valid, it is saved in the database:

```
- info for generate the customer
  -- name
  -- email
- basic info
  -- dob
  -- gender
  -- hometown
  -- state
  -- country
- phone info (just one phone)
  -- prefix
  -- phone number
- bank info (can be more than one)
  -- bank
  -- agency
  -- account number
- etc
```

Any suggestions?

答: This depends on how your customer entity is processed in those other layers. If you only store that data in a table with an even huge list of attributes, it won't make sense to split the entity into parts. But if your controllers contain some business logic for customers, I guess they will probably have processing steps with smaller customer parts either. So a separation would make sense at that layer, too.</p>

Title: Separate domain entity in small ones


问:
inheritance and static final variables
I'm a programing student.

I've been having problem to organize Java classes that use inheritance and static final variables.

Let say I have an abstract class named Form that has two children named Rectangle and Triangle. Those two children have a final static variable named NumberOfSides.

Both children classes need identical getters for that variable....

Would it be possible to write that getter in the "mother" class?

Thanks for your help.

答:
This should not be a constant (aka static final).

Given an instance of 'form' (you don't know what class it is), you can call a method 'getNumberOfSides' that will give you what you want. That's a standard method.

You could also consider a factory: FormFactory.createNewFormWithNumberOfSides(n).

Now, you could have something like:

```<code>class Triangle implements Form {
  public final static int TRIANGLE_SIDES = 3;

  @Override
  public int getNumberOfSides(){
    return TRIANGLE_SIDES;
  }
}
</code>```

But avoiding constants (statics) within a hierarchy that shadow each other is a good idea.

Title: inheritance and static final variables

Body:
This should not be a constant (aka static final).

Given an instance of 'form' (you don't know what class it is), you can call a method 'getNumberOfSides' that will give you what you want. That's a standard method.

You could also consider a factory: FormFactory.createNewFormWithNumberOfSides(n).

Now, you could have something like:

class Triangle implements Form {
  public final static int TRIANGLE_SIDES = 3;

  @Override
  public int getNumberOfSides(){
    return TRIANGLE_SIDES;
  }
}

But avoiding constants (statics) within a hierarchy that shadow each other is a good idea.


答:
If you only need the SQL statement once, for example, if you are queuing a bunch of operations to perform during off-hours, then yes, putting them into a table will work just fine.

If you need to execute the same SQL statement at specified intervals, then the stored procedure route others have mentioned is likely a better choice for you.

That said, what you are asking about is fairly unusual, and may be an indication of some other problem.  For example, if you are waiting to delete a user from a database, it may be better to call a scheduled script that does the operation through your application code, rather than recording the actual SQL statements.  This way the SQL and code are never out of sync.


问:
Use of fixtures in unit testing
I'm trying to understand the use of fixtures in the context of unit testing models in a web MVC system.

The problem I am trying to understand is that fixture data does no give a true representation of the data that the system accepts.

A simple example is say I have a user model that has email validation. Fixtures will bypass the validation so the tests maybe testing invalid data.

Edit: What I'm trying to get at is, wouldn't it make more sense to create the test data through the application business logic?

So for the email example, if a developer accidentally created a fixture with an email that would not pass validation, this could cause false negatives in testing (eg testing sending emails would fail because the fixture has invalid data).

The email example probably isn't the best, but I hope that makes more sense what I'm trying to get at?

答:
Tests that pass invalid data to some code under test tell you whether that code reacts properly to that data.

For example, when a method that doesn't specifically need to accept null parameters receives one, an IllegalArgumentException should be thrown immediately to prevent less-obvious failure later on. Even if this code is behind an interface that prevents those null values from propagating into the code under test, it doesn't hurt to verify the exception behavior.

In many web applications, data is validated in Javascript before it gets submitted to the server, however that Javascript can be circumvented, so validation (and validating testing) must be included in the server-side code.

Title: Use of fixtures in unit testing


问:
What are the tradeoffs for using 'partial view models'?
I've become aware of an itch due to some non-DRY code pertaining to view model classes in an (ASP.NET) MVC web application and I'm thinking of scratching my itch by organizing code in various 'partial view model' classes.

By partial-view-model, I'm referring to a class like a view model class in an analogous way to how partial views are like views, i.e. a way to encapsulate common info and behavior.

To strengthen the 'analogy', and to aid in visually organizing the code in my IDE, I was thinking of naming the partial-view-model classes with a _ prefix, e.g. _ParentItemViewModel.

As a slightly more concrete example of why I'm thinking along these lines, imagine that I have a domain-model-entity class ParentItem and the user-friendly descriptive text that identifies these items to users is complex enough that I'd like to encapsulate that code in a method in a _ParentItemViewModel class, for which I can then include an object or a collection of objects of that class in all the view model classes for all the views that need to include a reference to a parent item, e.g. ChildItemViewModel can have a ParentItem property of the _ParentItemViewModel class type, so that in my ChildItemView view, I can use @Model.ParentItem.UserFriendlyDescription as desired, like breadcrumbs, links, etc.

As a second example, imagine that I have entity classes SomeKindOfBatch, SomeKindOfBatchDetail, and SomeKindOfBatchDetailEvent, and a view model class and at least one view for each of those entities. Also, the example application covers a lot more than just some-kind-of-batches, so that it wouldn't really be useful or sensible to include info about a specific some-kind-of-batch in all of the project view model classes. But, like the above example, I have some code, say for generating a string for identifying a some-kind-of-batch in a user-friendly way, and I'd like to be able to use that in several views, say as breadcrumb text or text for a link.

As a third example, I'll describe another pattern I'm currently using. I have a Contact entity class, but it's a fat class, with dozens of properties, and at least a dozen references to other fat classes. However, a lot of view model classes need properties for referencing a specific contact and most of those need other properties for collections of contacts, e.g. possible contacts to be referenced for some kind of relationship. Most of these view model classes only need a small fraction of all of the available contact info, basically just an ID and some kind of user-friendly description (i.e. a friendly name). It seems to be pretty useful to have a 'partial view model' class for contacts that all of these other view model classes can use.

Maybe I'm just misunderstanding 'view model class' – I understand a view model class as always corresponding to a view. But maybe I'm assuming too much.

答: I use partial view models all of the time when the 'partial' part is supposed to look the same between different pages.  For example, if I have a list of items that may be displayed in the same way on several pages, I will have a partial view model (e.g. '_ListOfWhatevers.cshtml') that may use IList<Whatever> as the model type upon which it is based.  Then I will render that partial view with the appropriate list of items from my higher level views.  So far I have not encountered a point where I wish I had not done it.  It helps a lot with DRY when you have many pages showing the same type of data in slightly different contexts.


问:
What programming language generates fewest hard-to-find bugs?
What language, in your opinion, allows the average programmer to output features with the least amount of hard-to-find bugs? This is of course, a very broad question, and I'm interested in very broad and general answers and wisdoms.

Personally I find that I spend very little time looking for strange bugs in Java and C# programs, while C++ code has its distinct set of recurring bugs, and Python/similar has its own set of common and silly bugs that would be detected by the compiler in other languages.

Also I find it hard to consider functional languages in this regard, because I've never seen a big and complex program written in entirely functional code. Your input please.

Edit: Completely arbitrary clarification of hard-to-find bug: Takes more than 15 minutes to reproduce, or more than 1 hour to find cause of and fix.

Forgive me if this is a duplicate, but I didn't find anything on this specific topic.

答:
The more powerful the type system of the language, the more bugs will be caught at the compile time itself.

The following figure compares some of the well known programming languages in terms of the power, simplicity, and safety of their type systems. [ Source ]

*Factoring in the ability to use unsafe constructs.

C# gets stuffed into the unsafe row because of the "unsafe" keyword and associated pointer machinery. But if you want to think of these as a kind of inline foreign function mechanism feel free to bump C# skyward.

I've marked Haskell '98 as pure but GHC Haskell as not pure due to the unsafe* family of functions. If you disable unsafe* then jump GHC Haskell up accordingly.


问:
Uploading files(code) on a web server?
I have a very small and basic web site on a web server. Usually I'm doing the changes on a localhost where the development version is, and after that I upload it to the server with FileZilla. That's the very obvious way, but it's not the most convenient. </p>

<p>I've worked with SVN, but I've never needed to set anything - just checkout, commit, update. Reading some tutorials I wonder is this the easier way to upload the files to a server? Or are there any easier? </p>

答:
You are specifically asking about the easiest way.  That would probably be rsync or scp.  Put calls to either in a script or batch file, and uploading is very simple.  The difference between the two is scp is a copy - it will upload everything, while rsync will only upload (or download) the differences.

Using source control works nicely too.  Log in to your 'live' server, and do a git pull to download the latest updates.  I would recommend using github or another service as an intermediary.  Push to github from your development environment so you can review the changes, and then pull from the live server to update.

Title: Uploading files(code) on a web server?


问:
How to store currency ranges in a Postgres table?
I am using Postgres 9.3.

I have to store range data like <$250K, $250K-$4M, etc which we will display in a dropdown.

now I am making a table for all possible options that can be configured from an admin interface.

Should I take separate column for min,max,currency_type(dollar,euro) and a column to store K,M etc or there is a better way to do that ?

答:
If these are intended to be all-encompassing ranges that all values must fall within, I'd just store either the maximum or minimum value of the range in a single column.

```<code>ID | Amount
-----------
 1 |      0
 2 | 250000
 3 | 500000
 4 |1000000
 5 |2000000
</code>```

You can calculate the actual ranges on the fly from this.

Body:
If these are intended to be all-encompassing ranges that all values must fall within, I'd just store either the maximum or minimum value of the range in a single column.

ID | Amount
-----------
 1 |      0
 2 | 250000
 3 | 500000
 4 |1000000
 5 |2000000

You can calculate the actual ranges on the fly from this.


问:
Python for a desktop app
I currently have a .NET app that I want to convert to being cross platform, as a growing number of my users want a Mac version.  Since this forum doesn't seem to like questions that are "what languages are suitable for these requirements", I'll focus this question on Python as the language of choice.  Will Python be a good fit for the requirements below?  Drawbacks?

Desktop app - many of my users do not have an Internet connection where they use the software, so a web app will not do

Object oriented

Store data in a relational database as well as configuration files

Reporting engine, preferably using templates

Network connectivity - Some users setup multiple workstations sharing a single data file

Support RS-232 serial port communications, read and write

Support video capture

Play WAV and other sound files

Simple app installation - too many of my users are not very computer savvy, so the easier the install the better

Be able to implement a demo or time-limited licensing model

I considered Java, but am hesitant being at the mercy of Oracle and many people have had security concerns about the JVM.  I also considered the Mono project to keep the app in .NET, but their MoMA utility shows thousands of unsupported items.  I really prefer to have just one code base to maintain, instead of one for Windows and one for Mac.  Python seems to be what I keep coming back to.

For some background on myself, most of my experience has been with VB, VB.NET, C#, and Java with some dabbling in PHP/Javascript/HTML.  All of my desktop experience has been with Windows.

答:
You'd be surprised at how feature rich the python environment is. Going down the list, I'll try and give feedback on each of the points.

Desktop app - Yes. You can write applications which require no internet connectivity to function.

Object oriented - Big yes. Python supports lots of fun stuff with objects, such as injecting methods into individual instances of classes. You may find some parts less intuitive though, like a lack of a scope, or interfaces.

Store data in a relational database as well as configuration files - Yep. You can use databases either locally or through the web. Here's a link to some more info

Reporting engine, preferably using templates - A simple google search showed options of varying complexity based on what you need

Network connectivity - Yes, networking is fully supported. You can get down to creatig sockets if you want, or use fully formed libararies to do the lifting for you.

Support RS-232 serial port communications, read and write - PySerial

Support video capture - Video Libraries are an option

Play WAV and other sound files - PyAudio

Simple app installation - You talked about this in the comments, but you could also look into python eggs as a form of distribution, or .deb packages if you're running debian

Be able to implement a demo or time-limited licensing model - This is pretty much just limiting the source code that you provide to them. This is no different than any other language in that regard though.

Title: Python for a desktop app


问:
Is there a better way of writing unit tests than a series of 'AssertEquals'?
Here's a basic example of what my unit test needs to be, using qunit:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<link rel="stylesheet" href="qunit/qunit-1.13.0.css">
<script src = "qunit/qunit-1.13.0.js"></script>
<script src = "../js/fuzzQuery.js"></script>

<script>

test("Fuzz Query Basics", function()
        {
            equal(fuzzQuery("name:(John Smith)"), "name:(John~ Smith~)");
            equal(fuzzQuery("name:Jon~0.1"), "name:Jon~0.1");
            equal(fuzzQuery("Jon"), "Jon~");
            //etc

        }
    );

</script>
</head>
<body>
    <div id="qunit"></div>
</body>
</html>
</code>```

Now I was thinking this is a bit repetitive.

Could put all the inputs/outputs into an array, and loop through it.

```<code>test("Fuzz Query Basics", function()
        {
            var equals = [
                           ["name:(John Smith)", "name:(John~ Smith~)"],
                           ["name:Jon~0.1", "name:Jon~0.1"],
                           ["Jon", "Jon~"]
                           ];

            for (var i = 0; i<equals.length; i++)
                {
                    equal(fuzzQuery(equals[i][0]), equals[i][1]);
                }

        }
    );
</code>```

And this works fine.

The single advantage I can think of for this second method, is that if it turns out that you don't actually want to use equal it's easier to make that change in one spot.

In terms of readability, I don't think it's conclusive either way, though I probably prefer the second.

Abstracting it further, you could put the input/output cases into a separate CSV file, which might make it easier to modify.

Question is - what are the general conventions around writing these kinds of unit tests?

Is there a reason you shouldn't put them into arrays?

答:
It seems like you really want a Data Driven Unit Test. Since you mentioned using QUnit, I found a plugin that enables parameterized tests:

https://github.com/AStepaniuk/qunit-parameterize

There's nothing ideologically wrong with a data driven test, as long as the test code itself is not conditional. Looking at your test code, it appears to be a very good candidate for a Data Driven Test.

Example code for the GitHub README:

```<code>QUnit
    .cases([
        { a : 2, b : 2, expectedSum : 4 },
        { a : 5, b : 5, expectedSum : 10 },
        { a : 40, b : 2, expectedSum : 42 }
    ])
    .test("Sum test", function(params) {
        var actualSum = sum(params.a, params.b);
        equal(actualSum, params.expectedSum);
    });
</code>```

Body:
It seems like you really want a Data Driven Unit Test. Since you mentioned using QUnit, I found a plugin that enables parameterized tests:

https://github.com/AStepaniuk/qunit-parameterize

There's nothing ideologically wrong with a data driven test, as long as the test code itself is not conditional. Looking at your test code, it appears to be a very good candidate for a Data Driven Test.

Example code for the GitHub README:

QUnit
    .cases([
        { a : 2, b : 2, expectedSum : 4 },
        { a : 5, b : 5, expectedSum : 10 },
        { a : 40, b : 2, expectedSum : 42 }
    ])
    .test("Sum test", function(params) {
        var actualSum = sum(params.a, params.b);
        equal(actualSum, params.expectedSum);
    });


问:
Extending Internet Explorer to use a credit card machine and cash drawer
I have a software application which is currently a win forms application using an embedded IE web browser control. The win forms application provides access to an attached credit card machine and cash drawer to the web site running in the IE web control. Its does this by creating JavaScript objects in the IE web browser control which the web applications calls to do operations such as perform a credit card swipe or open a cash drawer. Those js objects are mapped to methods in the win forms application which then interacts with the devices. Its a pretty cool solution except that the embedded IE web control lacks all of the great development tools of a standard web browser window. So...

I want to move the web application to being used in a normal web browser window (sticking with IE is fine for this client) while still having access to the credit card machine and the cash drawer. So my question is this... What solution is best or even possible?

Active X Control - I do not really like this option

Java Applet

Flash

Create an IE Extension - with an IE extension is it possible to do something like we are doing with our current solution? - Preferred option if possible

Does anyone have any experience with this or any ideas? Thank you very much for your help!

答:
At a previous job I worked we used Silverlight for precisely this type of purpose, we would send out SmartCards and SD cards with devices that recorded data onto them. Users would go to our website where we had an upload section which was a little Silverlight control that accessed the local SmartCard reader or drives looking for an SD card that had our folder structure. The Silverlight control would read the data and send it to a SOAP web service we had hosted in the website.

It was quite effective and easy to work with and maintain, if I had to access local devices again from a website I would definitely look at this approach.


答:
First a definition: a hard-to-find bug, as I understand it, is a bug that can be reproduced but the cause is hard to find.

Probably the most important aspect is what I would call narrowness, i.e. how far can a bug escape, how large is the scope a bug can potentially influence. In languages like C, a bug, e.g. a negative array index or uninitialized pointer, can affect literally everything everywhere in the whole program, so in the worst case, you have to check everything everywhere to find the source of your problem.

Good languages in that regard support access modifiers and enforce them in a way that makes it hard or impossible to bypass them. Good languages encourage you to limit the scope of your variables, instead of making it too easy to have global variables (e.g. "everything not explicitely declared is a global variable with a default type and value").

The second important aspect is concurrency. Race conditions are generally hard to reproduce and therefore hard to find. Good languages offer easy-to-use synchronisation mechanisms, and their standard libs are thread safe where necessary.

This already completes my list; other things like strong typing help to catch bugs at compile time, but those bugs probably wouldn't be hard to find later.

Considering all that, I'd say that Java and C#, and many other languages in the JVM and .net world, are suitable to avoid hard-to-find bugs.

Title: What programming language generates fewest hard-to-find bugs?

Body:
What language, in your opinion, allows the average programmer to output features with the least amount of hard-to-find bugs? This is of course, a very broad question, and I'm interested in very broad and general answers and wisdoms.

Personally I find that I spend very little time looking for strange bugs in Java and C# programs, while C++ code has its distinct set of recurring bugs, and Python/similar has its own set of common and silly bugs that would be detected by the compiler in other languages.

Also I find it hard to consider functional languages in this regard, because I've never seen a big and complex program written in entirely functional code. Your input please.

Edit: Completely arbitrary clarification of hard-to-find bug: Takes more than 15 minutes to reproduce, or more than 1 hour to find cause of and fix.

Forgive me if this is a duplicate, but I didn't find anything on this specific topic.


答:
For your specific example, I would recommend that /v1/get/books should return HTTP 200 with an empty array.

If I'm reading your post right, your API intends to collect books. Metaphorically speaking, you have a bookshelf for books, a DVD rack for movies, and possibly other containers that you haven't mentioned here. Because you intend to collect books, /v1/get/books is your bookshelf. This means there's a valid resource there -a list of books- which happens to be empty in your specific example.

The reason I don't suggest returning HTTP 404 in this case is that the bookshelf is still there. There aren't any books on it at the moment, but it is still a bookshelf. If it weren't a bookshelf -if the API didn't intend to collect books, for example- then HTTP 404 would be appropriate. But because there's a resource there, you shouldn't signal that there isn't one, which HTTP 404 does. Therefore, I argue that 200 with an empty array (signifying the collection) is more appropriate.

The reason I don't suggest returning HTTP 204 is that this would suggest that "No Content" is the ordinary state of affairs: performing this action on this resource normally wouldn't return anything. That's why it's usually used as a response to DELETE requests, for example: the nature of deletion generally means that there is left nothing to return. The case is similar when it's used to respond to requests with the If-Modified family of headers: you only wanted content if the resource had changed, but it hasn't, so I won't give you any content.

But I argue that for GETting an empty-but-valid collection, HTTP 204 doesn't make sense. If there were items in the collection, then the proper representation would be an array of that data. Therefore, when there is no data there (but the collection is valid), the proper representation is an empty array.

Title: RESTful API design. What should I return if there are no rows?

Body:
I'm currently coding an API for a social network with the Slim Framework. My question is: What are the best practices when there are no rows to return in the json structure?

Lets say that this call /v1/get/movies returns 2 rows from the table movie names:

```<code>[
    {"name": "Ghostbusters"},
    {"name": "Indiana Jones"}
]
</code>```

But, then I call /v1/get/books and there are no rows in that table. Should I just return an empty structure?

```<code>[
]
</code>```

...or would it be better a message and an error code?

```<code>[
    "errors": {
        "message": "no matches found",
        "code": 134
    }
]
</code>```

Which is a better practice? (the API will be used in iOS and Android apps) Thanks!


问:
Sorting an array when values are decreased by each swap
Recently in an interview I come across a question:

We have an unsorted array, we need to sort it with minimum number of swap. We have in sort a 'tax' of 1 is deducted from the number we are swapping.

so suppose initially we have an array as

```<code>2 4 1 3 5
^   ^
</code>```

on swaping say 2 and 1, the new state of the array is:

```<code>0 4 1 3 5  // 'tax' of 1 is deducted from 1 and 2
^   ^      // so we have 0 and 1 at there place after the swap
</code>```

So we need to sort the array in min. number of swap. Any suggestions regarding the algorithm design?

I thought of doing this with merger sort but still not sure if this is the best approach.

答:
I don't believe that applying an existing sorting algorithm will help much.  In your example, I believe the minimum number of swaps is 2:

```<code>2 (4) (1) 3 5 -> 2 0 3 3 5
(2) (0) 3 3 5 -> -1 1 3 3 5
</code>```

This happens to fit the profile of a bubble sort, but that algorithm takes 7 steps to solve "5 4 3 2 1", which an insertion sort can handle in 2 steps:

```<code>(5) 4 3 2 (1) -> 0 4 3 2 4
0 (4) 3 (2) 4 -> 0 1 3 3 4
</code>```

There are also situations where you can find multiple distinct solutions to the same problem:

```<code>2 4 1 5 3
2 4 1 2 4
2 1 1 3 4
0 1 1 3 4
</code>```

or

```<code>2 4 1 5 3
2 4 1 3 3
2 0 3 3 3
-1 1 3 3 3
</code>```

Body:
I don't believe that applying an existing sorting algorithm will help much.  In your example, I believe the minimum number of swaps is 2:

2 (4) (1) 3 5 -> 2 0 3 3 5
(2) (0) 3 3 5 -> -1 1 3 3 5

This happens to fit the profile of a bubble sort, but that algorithm takes 7 steps to solve "5 4 3 2 1", which an insertion sort can handle in 2 steps:

(5) 4 3 2 (1) -> 0 4 3 2 4
0 (4) 3 (2) 4 -> 0 1 3 3 4

There are also situations where you can find multiple distinct solutions to the same problem:

2 4 1 5 3
2 4 1 2 4
2 1 1 3 4
0 1 1 3 4

or

2 4 1 5 3
2 4 1 3 3
2 0 3 3 3
-1 1 3 3 3


问:
Why is PHP's method of comparing different types bad?
I'm working on designing a new programming language and trying to decide how I will do variable comparisons.  Along with many different types of languages, I've used PHP for years and personally had zero bugs related to its comparison operations other than situations where 0 = false. Despite this, I've heard a lot of negativity towards its method of comparing types.

For example, in PHP:

```<code> 2  <  100      # True
"2" < "100"     # True
"2" <  100      # True
</code>```

In Python, string comparison goes like this:

```<code> 2  <  100      # True
"2" < "100"     # False
"2" <  100      # False
</code>```

I don't see any value in Python's implementation (how often do you really need to see which of two strings is lexicographically greater?), and I see almost no risk in PHP's method and a lot of value.  I know people claim it can create errors, but I don't see how.  Is there ever really going to be a situation where you are testing if (100 = "100") and you don't want the string to be treated as a number?  And if you really did, you could use === (which I've also heard people complain about but without any substantial reason).

So, my question is, not counting some of PHP's weird conversion and comparison rules dealing with 0's and nulls and strings mixed with characters and numbers, are there any substantial reasons that comparing ints and strings like this is bad, and are there any real reasons having a === operator is bad?

答:
You ask what situation would ever come up in which you want to compare 100 to "105" and want the string to be converted to a number, but I'm having more trouble coming up with a situation in which you'd want to deliberately compare 100 to "105" at all.

This situation happens in PHP all the time, of course, as well as in many other programming languages, but convert-and-compare is almost never what you actually want. Very nearly 100% of the time, you want to compare two numbers or two strings, and the only reason the types don't match is that something's wrong in the way you process the user input.

PHP's tries to Do What I Mean, which it assumes to be "convert the string to a number, and compare the numbers." At first blush, this sounds like a reasonable way of doing things, as long as PHP's assumptions about what you want are correct. But the moment you depart from those assumptions, this comes back to bite you. It might not even cause harm during that particular operation, instead wreaking havoc much later down the line, but the earlier the error can be caught, the easier it is to find the source and fix it.

And that, ultimately, is the problem with PHP's type comparison: in a well-meaning attempt to Do What I Mean, it masks errors that come up earlier in the code. Hidden bugs stay hidden because of it, only surfacing later to cause trouble.


答:
Note that the task is to optimize the number of swaps, not the number of comparisons. For standard sorting, it should be obvious that simple "selection sort" does not need more than n-1 swaps, so I guess this modified problem won't need more swaps in general.

Here a first try:

Loop through the array until you find a number which is smaller than the one before (lets say at the index i). If there is none, the array is sorted and you can stop

find the smallest element in the subarray a[i],...,a[n], lets say a[j]

swap a[j] with the first element from a[1],...,a[i-1] which is bigger than a[j] (lets say a[k]. Since a[k] must be greater than a[k-1] (or k=1), swapping won't destroy the existing order of a[1],...,a[i-1]. Note that there must be such an element, since a[k]>a[i]>=a[j] for every k

repeat these steps until the array is sorted

I admit, I am not sure if this will always produce the minimum number of swaps, still trying to find a proof (or a counterexample). But lets make some examples:

```<code>5 4 3 2 1    -> 1 is the smallest beyond 5: swap with 5
0 4 3 2 4    -> 2 is the smallest beyond 4: swap with 4
0 1 3 3 4
</code>```

or your original example:

```<code>2 4 1 3 5  ->  1 is the smallest beyond 4: swap with 2
0 4 1 3 5  ->  1 is the smallest beyond 4: swap with 4
0 0 3 3 5
</code>```

If someone finds a counterexample, showing that this algorithm is not optimal, please don't hesitate to present it.

Title: Sorting an array when values are decreased by each swap

Body:
Recently in an interview I come across a question:

We have an unsorted array, we need to sort it with minimum number of swap. We have in sort a 'tax' of 1 is deducted from the number we are swapping.

so suppose initially we have an array as

```<code>2 4 1 3 5
^   ^
</code>```

on swaping say 2 and 1, the new state of the array is:

```<code>0 4 1 3 5  // 'tax' of 1 is deducted from 1 and 2
^   ^      // so we have 0 and 1 at there place after the swap
</code>```

So we need to sort the array in min. number of swap. Any suggestions regarding the algorithm design?

I thought of doing this with merger sort but still not sure if this is the best approach.

Body:
Note that the task is to optimize the number of swaps, not the number of comparisons. For standard sorting, it should be obvious that simple "selection sort" does not need more than n-1 swaps, so I guess this modified problem won't need more swaps in general.

Here a first try:

Loop through the array until you find a number which is smaller than the one before (lets say at the index i). If there is none, the array is sorted and you can stop

find the smallest element in the subarray a[i],...,a[n], lets say a[j]

swap a[j] with the first element from a[1],...,a[i-1] which is bigger than a[j] (lets say a[k]. Since a[k] must be greater than a[k-1] (or k=1), swapping won't destroy the existing order of a[1],...,a[i-1]. Note that there must be such an element, since a[k]>a[i]>=a[j] for every k

repeat these steps until the array is sorted

I admit, I am not sure if this will always produce the minimum number of swaps, still trying to find a proof (or a counterexample). But lets make some examples:

5 4 3 2 1    -> 1 is the smallest beyond 5: swap with 5
0 4 3 2 4    -> 2 is the smallest beyond 4: swap with 4
0 1 3 3 4

or your original example:

2 4 1 3 5  ->  1 is the smallest beyond 4: swap with 2
0 4 1 3 5  ->  1 is the smallest beyond 4: swap with 4
0 0 3 3 5

If someone finds a counterexample, showing that this algorithm is not optimal, please don't hesitate to present it.


问:
Most efficient multiple condition IF statement
I am using a function to compare over 100 variables inside of classes to each other an am curious if one method of comparing multiple condition statements is more efficient than another.  I am currently considering one of these methods.  I think the 'single If using And/Or' looks the cleanest but performance is more important. (my code is VB.Net)

Multiple ElseIf

```<code>If Not ClassA.num = ClassB.num Then
    Return False
ElseIf Not ClassA.str = ClassB.str Then
    Return False
Else : Return True
End If
</code>```

Single If using And/Or

```<code>If Not ClassA.num = ClassB.num Or
   Not ClassA.str = ClassB.str Then
       Return False
Else : Return True
End If
</code>```

Nested If

```<code>If ClassA.num = ClassB.num Then
    If ClassA.str = ClassB.str Then
        Return True
    End If
End If
Return False
</code>```

Edit: Changed second code snippet from And to Or

Edit 2: Changed third snippet from If Not to If

答:
I don't think it gets any more efficient than short-circuit evaluation for real trivial chains like this:

```<code>Return ClassA.intVariable = ClassB.intVariable AndAlso ClassA.longVariable = _
        ClassB.longVariable AndAlso ClassA.str = ClassB.str
</code>```

Notice how AndAlso is used, not And.  Also shorter, quicker-to-compare stuff is mentioned (and evaluated) first, with longer, slower-to-compare stuff further in the back.

Body:
I don't think it gets any more efficient than short-circuit evaluation for real trivial chains like this:

Return ClassA.intVariable = ClassB.intVariable AndAlso ClassA.longVariable = _
        ClassB.longVariable AndAlso ClassA.str = ClassB.str

Notice how AndAlso is used, not And.  Also shorter, quicker-to-compare stuff is mentioned (and evaluated) first, with longer, slower-to-compare stuff further in the back.


答:
in the context of unit testing

wouldn't it make more sense to create the test data through the application business logic?

In some cases, that might be a more useful test to write.  But be aware you have moved out of the realm of unit testing and into integration testing.  Both are necessary.

if a developer accidentally created a fixture with an email that would not pass validation, this could cause false negatives

I would argue you should intentionally create invalid test input, and test that your unit handles it appropriately.  If you do this for every unit, your code becomes more robust.

In other words, testing against invalid data forces you to code defensively, which is a good thing.

Title: Use of fixtures in unit testing

Body:
I'm trying to understand the use of fixtures in the context of unit testing models in a web MVC system.

The problem I am trying to understand is that fixture data does no give a true representation of the data that the system accepts.

A simple example is say I have a user model that has email validation. Fixtures will bypass the validation so the tests maybe testing invalid data.

Edit: What I'm trying to get at is, wouldn't it make more sense to create the test data through the application business logic?

So for the email example, if a developer accidentally created a fixture with an email that would not pass validation, this could cause false negatives in testing (eg testing sending emails would fail because the fixture has invalid data).

The email example probably isn't the best, but I hope that makes more sense what I'm trying to get at?


问:
How do we go from assembly to machine code(code generation)
Is there an easy way to visualize the step between assembling code to machine code?

For example if you open about a binary file in notepad you see a textually formatted representation of machine code. I assume that each byte(symbol) you see is the corresponding ascii character for it's binary value?

But how do we go from assembly to binary, what's going on behind the scenes??

答:
Assembly opcodes have, for the most part, a one-to-one correspondence with the underlying machine instructions.  So all you have to do is identify each opcode in the assembly language, map it to the corresponding machine instruction, and write the machine instruction out to a file, along with its corresponding parameters (if any).  You then repeat the process for each additional opcode in the source file.

Of course, it takes more than that to create an executable file that will properly load and run on an operating system, and most decent assemblers do have some additional capabilities beyond simple mapping of opcodes to machine instructions (such as macros, for example).


答:
Look at the instruction set documentation, and you will find entries like this one from a pic microcontroller for each instruction:

The "encoding" line tells what that instruction looks like in binary.  In this case, it always starts with 5 ones, then a don't care bit (which can be either one or zero), then the "k"s stand for the literal you are adding.

The first few bits are called an "opcode," are are unique for each instruction.  The CPU basically looks at the opcode to see what instruction it is, then it knows to decode the "k"s as a number to be added.

It's tedious, but not that difficult to encode and decode.  I had an undergrad class where we had to do it by hand in exams.

To actually make a full executable file, you also have to do things like allocate memory, calculate branch offsets, and put it into a format like ELF, depending on your operating system.

Title: How do we go from assembly to machine code(code generation)

Body:
Is there an easy way to visualize the step between assembling code to machine code?

For example if you open about a binary file in notepad you see a textually formatted representation of machine code. I assume that each byte(symbol) you see is the corresponding ascii character for it's binary value?

But how do we go from assembly to binary, what's going on behind the scenes??


问:
Using Hibernate Criteria framework for complex queries vs. just making views in DB
I like using Hibernate for regular simple CRUD operations.

However, I am trying to understand why anyone would resort to its Criteria framework to assemble complex recordset criteria as opposed to simply creating a view at the database level.

E.g. here is a paraphrased snippet I am working with:

```<code>Criteria tableCriteria = session
    .createCriteria(SomeEntity.class)
    .add(Restrictions.eq("someID", someID))
    .add(Restrictions.gtProperty("scoreOne", "scoreTwo"))
    .add(Restrictions.gt("scoreThree", scoreThreeMin))
    .add(Restrictions.or(Restrictions.eq("inactive", Boolean.FALSE), Restrictions.isNull("inactive"))).addOrder(Order.asc("ordCol"))
</code>```

From the naked eye perspective, it is possible but let legible to discern what this filter definition is stipulating than to simply make a DB view where these restrictions could be expressed in the form of simpler WHERE clauses.

Am I missing something? Is there an advantage to using Criteria vs. DB views that I am not aware of?  Using views seems much cleaner.  Is there a performance upside to Criteria?

答:
The main benefit of using the Criteria framework is programmatic query creation, and as Aaronaught implies, it's much easier with Criteria to run an arbitrarily complex query on many different RDBMSs than it is with a named view that would need to be created and maintained separately.

Depending on your situation (and for your example), a view may be more maintainable and easily optimized. HQL would certainly be easier to read.


问:
Coding standards for c#
I wanted to know if there are some default standards for writing c# code. By default I mean may be something officially from Microsoft, or any other organization.

I am looking for something where I can find answers to questions like following:

should I do this:

```<code>public void DoSomeThing(int id)
{
    //method body
}
</code>```

or:

```<code>public void DoSomeThing(int id) {
    //method body
}
</code>```

should I do this:

```<code>Car car = new Car();
</code>```

or:

```<code>Car car =
    new Car();
</code>```

should I declare my variable in camel or pascal case, should I declare input parameters in method signature camel or pascal, should the global variable be prefixed with underscore or internal variable be prefixed with underscore ...

all these kind of questions ... any suggestions?

The actual issue is, I work on two projects for two different companies. and both have exactly opposite standards. I want to convince either of those and my self that such and such is the right way, because of such and such reason.

I know there is no one right way, but still any defaults documented from any leader organization would help. Thanks.

答:
My suggestion would be to go with the Coding style product that are out there for Visual Studio.  In particular Style Cop and FxCop.  We set these up and use them on every build, we will even brake our CI builds for some of the cases.  Thats a good automated way to enforce coding standards and you have an excuse for following one way because the code isn't going to compile if you don't.

http://stylecop.codeplex.com/

http://msdn.microsoft.com/en-us/library/bb429476(v=vs.80).aspx

For the record I would be using the first example in those two cases.

Title: Coding standards for c#