答:
Well, there's the practical answer, and then there's this one.

The question is titled "Where should the application logic run?"  But if you think about it, this conflates two things that ought to be separable:

How should the application logic be coded?

Where should the application logic be run?

One of the big, not generally recognized weaknesses of present-day database technology is that making a choice for either of these questions usually forces your hand on the other one:

If you choose to run application logic on the database, you're forced to either use the database's procedural language (eeek, PL/SQL), or really cumbersome support for third-party language stored procedures.

If you choose to code application logic in a good programming language, then you lose the data integrity advantages unless you duplicate effort and code some of the same logic at the database as well.

But ideally, I should be able to code all my application logic once, in a powerful programming language of my choice, and whether the logic runs on the application or the database should be a late-bound decision—one that I choose when I deploy the application, or even as late as runtime.

In fact, ideally I should be able to run the same logic simultaneously in the browser, the application server and the database.  Think of validation rules in a forms-driven web application.  Ideally you want the validation logic to run at all three tiers:

The browser should run the validation logic, because it can provide very low latency feedback to the user when they're filling the form wrong.  Also, by preventing the user from submitting invalid forms, it reduces load on the lower tiers.

The application server should run the validation logic, because it cannot trust the browser to do so—a hacker can bypass the browser's logic.  Also, by catching invalid forms before they're sent to the database, it reduces the load on that critical shared resource.

The database should run the validation logic, because it's responsible for enforcing data integrity for multiple users of the data.

So really you'd want to code that logic once, and have tools that apply it in all three places.  But precious little technology exists to achieve this.

Title: Databases: Where should the application logic run?

Body:
http://highscalability.com/blog/2010/11/9/facebook-uses-non-stored-procedures-to-update-social-graphs.html talks about how Facebook moved logic out of the database into the application in order to improve ease of development (scaling better across employees instead of across databases).

Are there any studies/articles/benchmarks that evaluate the business and technical tradeoffs of running as much of the logic in the database versus in the application?

Specifically, I'm wondering what scales better (both in terms of the database performance and ease of development as the business grows):

Scenario 1 (Logic in database)

Running as much of the logic on the database end.

Using database-specific SQL extensions/features.

Using stored procedures.

Few queries over short transactions, low network overhead.

Scenario 2 (Logic in application)

Running as much of the logic on the application end.

Limiting oneself to features which are common across all major databases.

Not using stored procedures.

Many queries over long transactions, high network overhead.

What kind of people-scaling overhead can one expect in Scenario 1?

What kind of database-scaling overhead can one expect in Scenario 2?


问:
Should test data be checked into version control?
I'm writing some test code for a feature which processes PDF files.  The basic idea behind the tests is that I point them towards some PDFs I've selected specially, they process them and I check that the output is what I expect.

My question is: where should I be storing these large-ish PDFs?  Should I check them into version control along with the code?  Or put them somewhere else?  Obviously, the test code is useless without the PDFs (or even with different PDFs) but still, putting them into our repository feels wrong.

答:
If the tests are useless without the setup files that you have prepared, then it makes sense to include the files in your VCS along with the test code.

While the files used in the test aren't code, you can view them as a dependency that the code relies upon.  So there is merit in keeping everything together.

As a counterpoint, some VCSs don't handle large binary files well, and others have strong opposition to including any sort of binary file in a VCS.  If either of those cases apply to you, then storing the test files in a well known location that is easily accessed would also make sense.

I would also consider putting a comment in the test code that says "relies upon foo.pdf in order to run all tests."

ContentLicense: CC BY-SA 3.0


答:
Your version control system should contain everything it needs to build, compile, test, and package an application for distribution (e.g. MSI, RPM). I would also argue build configurations and other scripts should also be in version control.

I should be able to check out a project and have a complete compile, build, and test environment.

There are two approaches to checking in test data. First, you can check in the test data itself (PDFs in this case). Second, you can check in source data that can be used to generate test data (if applicable). This could be a SQL script loaded into a blank database containing test data, or maybe a text-based file that can be compiled into a PDF or other file.

Others may disagree with checking everything into version control, but I have found in my professional experience it is critical to ensuring a complete environment is able to be rebuilt from scratch.

Title: Should test data be checked into version control?

Body:
I'm writing some test code for a feature which processes PDF files.  The basic idea behind the tests is that I point them towards some PDFs I've selected specially, they process them and I check that the output is what I expect.

My question is: where should I be storing these large-ish PDFs?  Should I check them into version control along with the code?  Or put them somewhere else?  Obviously, the test code is useless without the PDFs (or even with different PDFs) but still, putting them into our repository feels wrong.


问:
When writing object-oriented code, should I always be following a design pattern?
Is there a conceivable design pattern for any object-oriented program? I ask this because recently I saw an implementation of a Door class with a Lock. It was part of a test and the answer said that the code is following the Null Object pattern:

class Lock
{
public:
    virtual void close() = 0;
    virtual void open() = 0;
    virtual bool is_open() const = 0;
    virtual ~Lock() { }
};

class DummyLock
    : public Lock
{
private:
    DummyLock();
    DummyLock(const DummyLock&) = delete;
    DummyLock& operator=(const DummyLock&) = delete;

private:
    void close() { }
    void open() { }
    bool is_open() const { return true; }

public:
    static DummyLock m_instance;
};

class Door
{
public:
    Door() : m_lock(DummyLock::m_instance) { }
    Door(Lock &lock) : m_lock(lock) { }

public:
    Lock& get_lock() const { return m_lock; }

private:
    Lock &m_lock;
};
```

This made me think: This code follows a good design pattern even though the description is so simple (this class is designing a door class with a lock), so if I am writing more complex code, should there always be some design pattern that I am following?

答:
should there always be some design pattern that I am following?

Dear God NO!

I mean, you can go ahead and say that any random code is following some random XYZ pattern, but that's no more useful than me claiming to be king of my computer chair. Nobody else really knows what that means and even those that do won't exactly respect my claim.

Design patterns are a communication tool so that programmers can tell other programmers what has been done or what should be done without spending a bunch of time repeating themselves. And since they're things that come up a bunch of times, they're useful concepts for programmers to learn "hey, making XYZ always seems to come up because it's good/useful".

They do not replace the need for you to think for yourself, to tailor the patterns for the unique problem in front of you, or to handle all of the inevitable things that don't fit into nice buckets.


问:
A good guide on choosing the point scale to use with Agile/SCRUM?
We're using Pivotal Tracker for our project, which lets us choose from these three point scales:

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

And I'm looking for a resource to help guide our decision. (After using 0,1,2,3 for two iterations, we can see where one of the others would be a lot more useful or meaningful.)

答:
"Fibonacci" story point scale is very popular: 1, 2, 3, 5, 8 etc.  Popular planning poker card decks (by Mountain Goat Software and Crisp) are based on it: question mark, 0, 1/2, 1, 2, 3, 5, 8, 13, 20, 40, 100, infinity.

Mike Cohn notes in his Agile Estimation and Planning book that using 1-2-4-8 instead of 1-2-3-5-8 is okay.

It is important to remember when applying story points on "micro-sized" teams: limit the maximum story size, don't "mix pebbles with boulders" (see more at Agile for the Solo Developer)

ContentLicense: CC BY-SA 2.5


答:
if I am writing more complex code, should there always be some design pattern that I am following?

No. Design patterns are just that: patterns in relationships between objects. In other words, relationships that are used and reused often enough that someone said "Hey, we seem to be doing this a lot, let's give it a name." The list of design patterns were not determined all at once in the beginning of OOP and then handed down by GOF! They were discovered and eventually documented, and then popularized by the book.

That said, a big part of the benefit of design patterns is that they make it easier to think about software design at a higher level. They let you skip worrying about implementation details and think more about the big picture. In that sense they free you from the minutia, but they can also limit you in the same way that the way you express yourself can be limited by the words that you know. So, there may come a time when there is a design pattern for most of what you do simply because the patterns that you know are the terms in which you think. Keep your eyes open for cases where you might be abusing a pattern, and where you may need to think more deeply about better ways to do things.

Also, realize that in practice you often don't implement a given design pattern so much as recognize the pattern in some existing code, like an object framework. Knowing about common design patterns makes it much easier to learn how a framework is intended to be used because you can see the relationships between classes in terms that you already understand.

Title: When writing object-oriented code, should I always be following a design pattern?

Body:
Is there a conceivable design pattern for any object-oriented program? I ask this because recently I saw an implementation of a Door class with a Lock. It was part of a test and the answer said that the code is following the Null Object pattern:

class Lock
{
public:
    virtual void close() = 0;
    virtual void open() = 0;
    virtual bool is_open() const = 0;
    virtual ~Lock() { }
};

class DummyLock
    : public Lock
{
private:
    DummyLock();
    DummyLock(const DummyLock&) = delete;
    DummyLock& operator=(const DummyLock&) = delete;

private:
    void close() { }
    void open() { }
    bool is_open() const { return true; }

public:
    static DummyLock m_instance;
};

class Door
{
public:
    Door() : m_lock(DummyLock::m_instance) { }
    Door(Lock &lock) : m_lock(lock) { }

public:
    Lock& get_lock() const { return m_lock; }

private:
    Lock &m_lock;
};
```

This made me think: This code follows a good design pattern even though the description is so simple (this class is designing a door class with a lock), so if I am writing more complex code, should there always be some design pattern that I am following?


问:
Are frameworks used for "big" websites?
I'm kind of new to PHP. I can create basic sites with login/registration, etc., but I always struggle to build complex sites with lots of features, because eventually the code becomes messy and I just run into more and more little bugs, and then fixing those produces another, and so on. I realise that that's partially to do with me simply not writing clean code (I'm working on that!) but I would also probably benefit from using a framework.

But is using ready-made frameworks "unprofessional"? Would a big site such a YouTube or Facebook use a framework like CakePHP or CodeIgniter?

答:
Even if you don't use a framework you end up with your own anyway.

You're going to have standards in your company, libraries which you use, conventions. And at some point your own small or big project will basically have its' own custom framework. (although you probably won't call it that.)

Title: Are frameworks used for "big" websites?


问:
Is there a 'standard' SQL that can replace all the various custom versions?
I have been writing SQL for over 10 years now. I am extremely proficient at it and have experience working in SQL Server, Oracle, MySQL, PostgreSQL, etc. While there are multiple standards out there, they seem to be more suggestions than standards. When you start talking about column types and stored procedures, there's almost no consistency across the board.

I wonder if someone ever considered defining a new querying language. I recently played around with some ideas. Here are some examples: https://gist.github.com/jehugaleahsa/03888d13ef2745cb67d0. Of course, this just covers the most obvious DML. This syntax would make it easier to support auto-completion, give more control over the temp table generation, make the join syntax easier, make working with grouped data easier and make sub-expressions/calculations easier to build up, just to name a few. I especially like it because it could very easily be extended to support some noSQL databases, as well. Imagine what a committee could come up with given more time!

My question is whether any effort has been put into defining a different querying language, supported by the different providers. I recognize that SQL is "good enough" and that defining and implementing a new standard would be a monumental undertaking. I know there were a lot of SQL standards proposed over the years. I just wonder if a non-"SQL" standard ever was proposed and whether it made progress or just fizzled out.

答:
The answer to this was ANSI SQL.

Although initial adoption was hard, especially for databases like Oracle, many of them now allow the ANSI standard.

For example Oracle started allowing that format in 9i (see http://allthingsoracle.com/ansi-sql/)

Also - PostgreSQL prides itself in standards compliance. Its SQL implementation strongly conforms to the ANSI-SQL:2008 standard (http://www.postgresql.org/about/)

For mysql, see http://dev.mysql.com/doc/refman/5.0/en/compatibility.html which states:

This section describes how MySQL relates to the ANSI/ISO SQL
  standards. MySQL Server has many extensions to the SQL standard, and
  here you can find out what they are and how to use them. You can also
  find information about functionality missing from MySQL Server, and
  how to work around some of the differences.

The SQL standard has been evolving since 1986 and several versions
  exist.   In this manual, “SQL-92” refers to the standard released in
  1992, “SQL:1999” refers to the standard released in 1999, “SQL:2003”
  refers to the standard released in 2003, and “SQL:2008” refers to the
  most recent version of the standard, released in 2008.


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答:
The first bad sign I can think of is when management is not willing to pass bad news up the chain or to the client in the hopes that it will go away - i.e. management by wishful thinking. I can't think of how many times, developers have proven they can't meet the deadline weeks or even months ahead of it and yet no one wants to tell the client. I've rarely seen a client who wouldn't push a deadline when there is genuine reason to when the need is explained well in advance; I've often seen a pissed off client when told the day of the deadline that it wasn't going to be met and that it wouldn't be met the next day either but two months down the road. At this point they, rightly I might add, question your processes - how come you didn't know this earlier. (True answer but the one we never give - we did know but we were afraid to tell you.)

Another sure sign that failure is coming up is to assign new developers to the hardest most complicated, most critical part of the process rather than the people who understand the current system already. Then don't watch them carefully to see if they really are getting work completed properly or have questions (BIG BIG RED FLAG if there are no questions). New employees need to be monitored until you know they really have the skills they claimed to have. I can still remember spending one painful summer redoing the work (already past deadline when I got it) of a new employee who got a critical piece of a project and told everyone everything was fine for months and then quit without notice one week from the deadline and nothing he did was usable.

Another sure sign of failure is when developers are working on pieces that depend on other things being done first and those things are not done or even started. If management can't get the work assigned in the right order, you are going down the tubes.

Of course feature creep without pushing the deadline back every time is one of the most common signs things are going to go bad. You add 20 hours of work to my plate, the deadline gets moved by 20 hours. If it doesn't then the project will fail, guaranteed.


答:
If it's static data, then yes put it in version control. Those files won't really change once they're checked in; they'll either get removed if that functionality's no longer needed, or new test files will be added alongside. Either way, you don't need to worry about poor binary diffs taking up space.

If you're generating test data, eg. randomly, then you should automatically save it when a test fails, but discard it otherwise. Any data saved this way should be turned into regular regression tests, so that those edge-cases are definitely tested in the future rather than relying on the luck of the draw.


答:
Design patterns have two advantages

They are easy to describe to other developers, because people generally agree on what the patterns are

They tend to have been beaten on pretty thoughtfully by our predecessors, so their strengths and weaknesses are well understood.

The goals of every program should be

It works.  It has to do whatever the end goal is, or it doesn't matter how many design patterns you use.  OO design patterns make it easy to dice up the problem into easy to understand bits so its easier to prove it works.

It is easy to read.  This is where design patterns are nice.  The OO problems they solve are complicated.  If you solve them in a "standard" way, its easier on the next developer

It is easy to grow.  Almost 0 modern programs finish where everyone planned them to.  Every program grows after its initial release.  OO patterns are known for being curiously good at growing.

That all being said, note that every reference to OO design patterns is "they're just good at the job."  They are not perfect, but they do fill a niche very effectively.  Use them when they work, avoid them when they don't.

As an example, of "complex code," as you mentioned in your question, take a scripting language I wrote.  Most of it is OO with design patterns everywhere.  However, when it came to writing the garbage collector, I unceremoniously dropped all pretenses of OO, because the particular things I needed to do were better modeled as good ol' fashioned bit-bashing.  There's not an OO pattern in the entire thing up until it came to writing finalizers, where once again OO started to be a useful model again.  Without any pomp nor circumstance, the code suddenly shifted back into using OO techniques again.

Use design patterns whenever they make your product better; avoid them when they make your product worse.


问:
Traits, Inheritance and Interfaces in Groovy, when to use them?
I'm learning groovy and I've just learned about the new feature added in 2.3, which is the addition of Traits.  Now to me it seems like Traits allow you to do basically everything a super-class and an Interface can do.

Does the addition of Traits to Groovy make Inheritance and Interfaces obsolete?

And if not, then what is the best time to use each of these mechanisms?

答:
Traits combine the best of both worlds - the inheritance of (abstract) classes and the implementation of interfaces. A trait can contain default implementations of methods and yet a type can implement multiple traits at once. This allows some kind of multiple inheritance, but in a good way, avoiding the deadly diamond of death.

If you don't know how to start, then use traits. You gain flexibility and can switch to interfaces or class inheritance later on if required.


答:
No.

This is what the Gang of Four (who originally popularized design patterns) had to say about it in their book:

"No discussion of how to use design patterns would be complete without
  a few words on how not to use them.  Design patterns should not be
  applied indiscriminately.  Often they achieve flexibility and
  variability by introducing additional levels of indirection, and that
  can complicate a design and/or cost you some performance.  A design
  pattern should only be applied when the flexibility it affords is
  actually needed."

The example you show doesn't actually do much of anything (I don't think it was meant to, I think it was just meant to be an example).  By itself, it has no need of the null object pattern.  In the context of a larger program, it might.

The wrong approach is assuming that just because it has been labelled a "design pattern" it must be good, and then looking for more places to cram more patterns in.  Use them when they fit the program and actually solve a problem for you.


问:
What is the argument for never forcing a push in a DVCS (Mercurial)?
I always preach never to force push anything, because that adds ambiguity to the repository server.

In this specific example, we collaborate with a customer and they "skip a step" and force push instead of appropriately pulling and merging. This takes the ambiguity of what code is good, what code is bad, out of their working directory and into the server. Two heads on this branch, which one do I use, etc. I am looking to use a hook to disallow force pushing, I just didn't want to lock down that ability if there was a good use case for it.

We are relatively new (2 or 3 years) to DVCS, moving from SVN previously. What are the arguments for not doing a force push in a DVCS?  What exceptions exist for this hard and fast rule?

答:
This is written from a git perspective, since the force push isn't unique to Mercurial

There are commands which allow you to change your repo local repo. git commit --amend, rebase are two of the more common things that people do to modify their own repo history. This is perfectly acceptable.  I've often done a git commit --amend after forgetting to include the tracking number for github in the message.  But its not without peril (as the documentation says)

Ahh, but the bliss of rebasing isn’t without its drawbacks, which can be summed up in a single line:

Do not rebase commits that you have pushed to a public repository.

The thing is that the public repo should be append only.  You append commits as you create them.  Rewriting the public rep causes all sorts of headaches and causes everyone who has pulled form it to have to adjust their own repos to match.

There are certainly times when you will need to force a push.  If you really need to modify that last commit (oppose there was a password in there), or worse, you need to go back and find old files that contain sensitive data.

git push --force is a tool.  It is a very heavy handed tool that allows you to do quite a bit of rewriting of history, but it is still a tool (people have written even bigger tools yet titled bfg for cleaning repos).  To say 'never force a push' ignores all those times when you do need to rewrite the history.

In this specific example, we collaborate with a customer and they "skip a step" and force push instead of appropriately pulling and merging. This takes the ambiguity of what code is good, what code is bad, out of their working directory and into the server. Two heads on this branch, which one do I use, etc. I am looking to use a hook to disallow force pushing, I just didn't want to lock down that ability if there was a good use case for it. So far I haven't seen one yet.

The problem that is ebbing encountered, however, is not one with the tool.  It is a problem with the people using the tool.  If they don't have the... maturity... to handle a force push correctly, then by all means take it away from them.  They likely don't need it, don't know when they should use it, or are aware of the problems that it causes.  Forcing them to use a proper workflow will certainly mean more work for them... it will also mean less work for you cleaning up.  On the balance, its likely that using a better workflow will reduce the overall work done and make things cleaner.  Once they are fully aware of how to use the tool, and the proper way the workflow works, then let them have the unfettered toolchain again.


问:
What should take precedence: YAGNI or Good Design?
At which point should YAGNI take precedence against good coding practices and vice versa?  I'm working on a project at work and want to slowly introduce good code standards to my co-workers (currently there are none and everything is just kind of hacked together without rhyme or reason), but after creating a series of classes (we don't do TDD, or sadly any kind of unit testing at all) I took a step back and thought it's violating YAGNI because I pretty much know with certainty that we don't require the need to extend some of these classes.

Here's a concrete example of what I mean: I have a data access layer wrapping a set of stored procedures, which uses a rudimentary Repository-style pattern with basic CRUD functions.  Since there are a handful of methods that all my repository classes need, I created a generic interface for my repositories, called IRepository.  However, I then created a "marker" interface (i.e. interface that doesn't add any new functionality) for each type of repository (e.g. ICustomerRepository) and the concrete class implements that.  I've done the same thing with a Factory implementation to build the business objects from DataReaders/DataSets returned by the Stored Procedure; the signature of my repository class tends to look something like this:

```<code>public class CustomerRepository : ICustomerRepository
{
    ICustomerFactory factory = null;

    public CustomerRepository() : this(new CustomerFactory() { }

    public CustomerRepository(ICustomerFactory factory) {
        this.factory = factory;
    }

    public Customer Find(int customerID)
    {
        // data access stuff here
        return factory.Build(ds.Tables[0].Rows[0]);
    }
}
</code>```

My concern here is that I'm violating YAGNI because I know with 99% certainty that there is never going to be a reason to give anything other than a concrete CustomerFactory to this repository; since we don't have unit tests I don't need a MockCustomerFactory or similar things, and having so many interfaces might confuse my co-workers.  On the other hand, using a concrete implementation of the factory seems like a design smell.

Is there a good way to come to a compromise between proper software design and not overarchitecting the solution?  I'm questioning if I need to have all of the "single implemenation interfaces" or if I could sacrifice a bit of good design and just have, for example, the base interface and then the single concrete, and not worry about programming to the interface if the implementation is that will ever be used.

答:
Can you, right now, write down a vaguely reasonable ICustomerRepository?  E.g., (really reaching here, probably a bad example) in the past your customers have always used PayPal?  Or everybody in the company is abuzz about hooking up with Alibaba?  If so, you might want to use the more complex design now, and appear farsighted to your bosses.  :-)

Otherwise, wait.  Guessing at a interface before you have one or two actual implementations usually fails.  In other words, don't generalize / abstract / use a fancy design pattern until you have a couple of examples to generalize.


问:
Reducing dependency cycles and reducing coupling
I'm trying to learn how to produce quality object-oriented code and have been studying concepts like SOLID. I'm currently working on an entity-component-process system for a small game engine.

Currently, I have it implemented as such:

There is a ScreenStack which contains a stack of Screens

Each Screen has an EntityManager and ProcessManager.

The ProcessManager updates all Processes given entities from the EntityManager.

A Process handles all game logic, so it needs to be able to use ScreenStack to possibly push and pop screens. It can also create, remove, and change entities, so it needs the EntityManager from Screen. Basically a Process needs to know everything about the game since it affects so much of it, but it feels wrong.

How do I go about implementing this better? It seems like everything has a clear dependency hierarchy until you get to a process, where it gets thrown out the window.

There also seems to be tight coupling when I would want to push a new screen. Say, for example, I have a process in a MainMenu screen that checks for menu choice. If "New Game" is clicked, I need to push a new screen, which gets created at that moment. I've read that I shouldn't randomly throw in new which this seems to be doing.

答:
I suppose you are trying to make the game engine Process-driven. I.e. Process will decide what should happen it the game and change game's state. I like the idea, but I was never able to apply it to my game (I've finished only one).

The core of the problem was that my game was not truly process-driven. The inputs came from the frontend (Screen or ScreenStack in your case) obviously, so I had to sacrifice process-driven architecture for a layered one: 'frontend' uses 'backend'. Backend contains most of the game logic (processes and entities in your case), but the frontend is the driver. Backend cannot push screens. Backend does not know anything about frontend. Backend is only a slave of the frontend. That's what I ended up with. Maybe your game is similar.


问:
Should an ASP.NET MVC application directly use Entity Framework as the model?
I'm building my first MVC application in Visual Studio 2013 (MVC 5) and I'm a bit unclear on the best way to setup my model.

I've generated an entity framework model using code-first from an existing database. My first instinct was to create some intermediary classes that would be the model used by the views and have those classes work with the entity framework classes.

As I was writing the intermediary classes I realized that I was mostly just re-implementing a lot of the things that the EF classes already did just with the occasional private setter or cast from one datatype to another. So that seemed like a waste.

Is the general rule to directly use the entity framework classes as the Model for an MVC application? Or is there some benefit I'm missing for building these intermediary classes?

答:
I would say it really depends on your application. Is it just doing pure CRUD, without any business logic? Then I would use EF models directly in my views.

Most of the time there is at least some business logic involved and then a layer between the data/EF models and the view might be a good idea. In this case it might be appropriate to do "CQRS-lite" (see below) and use different models in to and out of your controller. Most of the time the read models are a lot "fatter" than the write models...

However, if the application contains a lot of business logic and/or needs to scale a lot, I would implement at least the core of it using CQRS (Command Query Responsibility Segregation), DDD (Domain Driven Design) and possibly Event Sourcing. Then EF could be used as the read model facade.

Also remember that you don't need to stick to one strategy/pattern for the whole application, some areas may be pure CRUD and other areas may contain a lot of business logic...


问:
An algorithm for finding converse duplicates of ordered pairs
Given an array of ordered pairs of values, what algorithm will find converse duplicates? [Converse meaning the same values, but in the opposite order.]

That is, given [ab,ac,ad,bc,bd,ca,db] is there an efficient way to find ca and db, being the converse duplicates for ac and bd?

The application is simple enough: the ordered pairs are edges in a directed graph and if there is a converse edge then a single double-ended edge is to be drawn rather than one edge in each direction. The values are strings, being node names.

It can be viewed as a lookup in a sparse array. Given coordinates (a,b), check whether (b,a) exists. However, common programming languages do not (appear to) provide sparse 2d arrays.

I have written a solution in ruby using hash-of-hash, but it's about 20 lines of awkward code and an unsatisfying outcome. Writing the same code in a language like C# or Java would be longer. A better solution is sought, in pseudocode or a description (steps) of the algorithm. Either way, I am seeking an answer that describes how to find the solution as well as the benefits and drawbacks of the particular algorithm.

I haven't attempted to define 'efficient' or 'better', and performance is not an overriding consideration for a drawing of a few hundred nodes.

The nodes are not sorted, so the default algorithm would be, for each pair, to form the converse and brute-force search the preceding half. A binary search would require a prior sort. A solution based on hash indexing should be much faster.

答:
Just collect the pairs in a set.  (In Ruby, it will be a Set of two-element Arrays.)

```<code>let Set s = {}
for each pair [a,b]
   if s contains [a,b]
      // duplicate, do nothing
   else if s contains [b,a] // converse duplicate
      ...
   else
      add [a,b] to S
</code>```

If you are writing Ruby, it is already capable of using arrays

Body:
Just collect the pairs in a set.  (In Ruby, it will be a Set of two-element Arrays.)

let Set s = {}
for each pair [a,b]
   if s contains [a,b]
      // duplicate, do nothing
   else if s contains [b,a] // converse duplicate
      ...
   else
      add [a,b] to S

If you are writing Ruby, it is already capable of using arrays


问:
Should I denote that a method satisfies an interface?
When writing a class which has ("satisfies") 1 or more interfaces, should I note somehow (e.g. in an XML comment, or with an attribute) that a particular method was added for one of the interfaces?

For example, the IComparable interface requires an int CompareTo(Object) method.

I know I don't need to do anything other than implement the appropriate methods, but for maintainability and ease of understanding are there any "best practices" for letting others know why the method exists?

答:
There should be no need to treat the method any differently than any other. In this example, a method named CompareTo() would be obvious to anyone with significant .NET experience as being the implementation of IComparable<T>. The idiot who comments it out or deletes it will be told by the compiler that the class no longer implements IComparable<T>.CompareTo(), and at that point should understand they messed up and put it back. The total bozo who, on receiving this error, thinks the best solution is to remove the IComparable<T> interface from the class definition (without one hell of a good reason, like he's traced every usage of the class across your codebase and is 100% positive the class is never part of any sort operation) probably doesn't need to be working for your company.

If you wanted to be nice, //Implementation of IComparable<T> placed somewhere near the function declaration (just above it, or just inside the function body) should make it clear enough even to the boneheads mentioned above.

If you wanted to be really nice, you can xml-doc the class/method, and in the <remarks> tag, affirm that this method is the implementation of IComparable<T> for the class. This will not only show up in source, but also in any SandCastle documentation you create. It might show up in IntelliSense, but I doubt it; remarks can be pretty big. If it absolutely positively has to be known via IntelliSense that the method is the implementation of the interafce, mention it in the <description> tag.


问:
Handling database schema changes when pushing new versions
During times of heavy development, the database schema changes both rapidly and continuously, and by the time our weekly push to the beta build comes around, the schema has changed so much that the only sensible option is to nuke all of the tables I can and copy the new versions from my dev database. Obviously, this isn't going to work once we launch, since nuking production data is a recipe for disaster, so I was wondering what strategies were out there for managing database schema changes from one version/revision to another?

Some I've found or experienced:

Straight nuke-and-dump from one database to another (what I am doing now)

Maintaining an UPDATE.sql file with SQL statements that get run either via script or by hand.

Maintaining an update.php file with a corresponding "db-schema-version" value in the active database

The third option seems to be the most sensible, but there still exists the possibility of a badly constructed SQL query failing mid-script, leaving the database in a half-updated state, necessitating a restoration of a backup.

It seems like a non-issue, but it does happen, since we as a team, we use phpMyAdmin, and I can't seem to even rely on myself remember copying the executed SQL statement to paste into the update.php file. Once you navigate to another page, I have to re-write the SQL statement out by hand, or reverse my change and do it again.

I guess what I am hoping for is a solution that doesn't impact our established development workflow?

答:
Take a look at http://south.aeracode.org — it's a DB migrations library for Django (a Python framework) but:

you can get great ideas from it (and perhaps even find a PHP clone)

you can actually use it independently from the rest of Django to manage your PHP/MySQL app's tables.

It can also generate schema update scripts; it also handles change reversals automatically most of the time.


问:
Is it possible to antialias existing lines, circles, text, etc. of a single color?
I want to manually antialias the output of GDI drawing functions on Windows. Each drawing function is rendered onto its own image and then blitted back (so alpha blending can work, as GDI doesn't do that natively), so the image has only two colors: transparent and the drawing color.

My question is simple: is there a way to antialias an existing line, circle, text, etc. drawn after the fact by hand (in a loop)?

I found this but I have no idea how it works, or if it even does work.

I'd rather not reimplement the drawing primitives myself; if I did that then I wouldn't need to be using GDI. I already have an alpha premultiplication loop; can I do the antialiasing there?

Update 23 September 2014/Alternate Question - there's this CodeProject article which suggests using HALFTONE blit stretching, however the GDI AlphaBlend() API does not support it, and I'm not sure if the output of using a third image for doing the halftone resize will be properly alpha-premultiplied if the input color is; is it?

答:
Technically no, you can't antialias an existing line because you don't truly know where the bounds of the line are--or mathematically where the line exists in relation to the surrounding pixels.  Add that to the fact that the line actually obscures underlying pixels--which can't be blended into line.

You could smooth the image; but I don't believe that's even close to anti-aliasing.


问:
What is the benefit of a function without parameters which only calls another function
A tutorial (for Javascript) I'm doing suggests we write a function like this one:

```<code>function sayHello() {
   //Some comments explaining the next line
   window.alert("Hello");
}
</code>```

Other than obfuscation are there benefits to writing something like this in real life? If so, what are the benefits?

答:
It's a good idea to keep calculation of values (expressions) separate from execution of actions (statements). We want precise control over where and when actions will be taken (like displaying messages), but when calculating values we'd rather work at a more abstract level and not have to care about how those values are being calculated.

A function which only calculates a return value, using only the arguments it's given, is called pure.

A "function" which performs an action is actually a procedure, which has an effect.

Any effects caused during the calculation of a value are called side-effects, and it's better to avoid them where possible ("I just needed that string, I didn't know it would hammer the database!").

To minimise the chance of side-effects, we should avoid sending too much data to our procedures, or putting any calculation in them; if some calculation needs to be performed beforehand, it's usually better to do it separately in a pure function, then pass only the required result to the procedure. This keeps the purpose of the procedure clear, and reduces the chance that it'll be re-used by later as part of a calculation (the pure function can be re-used instead).

For the same reason, we should avoid processing results inside a procedure. It's better to return the result (if any) our our action, and perform any subsequent processing with pure functions.

If we follow these rules, we might end up with a procedure like sayHello, which doesn't need any data and doesn't have a result. Hence the best interface for it is to have no arguments and not return a value. This is preferable to, for example, calling "console.log" in the middle of some calculation.

To reduce the need for effects during calculation, we can have calculations which return procedures; eg. if we need to decide on an action to take, we can have a pure function choose a procedure and return it, rather than executing it directly.

Likewise, to reduce the need for calculation during procedures, we can have procedures take other procedures as parameters (possibly the result of a function); eg. taking an array of procedures and running one after another.


问:
design for buffering or queuing data streams to replace database
We have a system (ms stack, .net, sql) that receives data from thousands of remote devices (several independent readings/min). We currently save all the data to a db as it arrives and a second service reads and processes the data - using the database to 'buffer' the input.

We want the second process to be scaleable as it can take quite a while to complete. Ideally we should be able to run multiple instances of the second process but we have to make sure that the data is processed in a specific order (cannot have two processes working on data from the same remote device at the same time). We've been using the database to manage this by reading all the data from one device at a time and preventing other processes from reading data from that device until its complete.

This is stating to show performance problems and has high db traffic so we are looking for alternative architectures to using the DB as a buffer.

Can object caching systems like memcache allow us to retrieve all data for 1 device into one process and prevent that data being used by another process?

Or are there message queuing systems that would do this?

Or something else?

-EDIT-

Reading the data back to be processed needs to be done by machines on different servers so I'm looking for something that can cross application / process boundaries and maintain locks on some data items to preserve the order they are processed

答:
The problem with "a database" is that it is generally a single-point of failure/scalability.  You can scale databases, but it's difficult and costly depending on what scale you're talking about.

Typically, what you describe are implemented as messages.  Message queues would then store and forward the messages to multiple readers or clients.  You can scale out the number of readers (in addition to the number of queues and communication amongst the queues) that is generally considered a very scalable architecture.

I've worked with RabbitMQ to do exactly these types of things; but there are many vendors with various features.


问:
When does it make sense to compile my own language to C code first?
When designing an own programming language, when does it make sense to write a converter that takes the source code and converts it to C or C++ code so that I can use an existing compiler like gcc to end up with machine code? Are there projects that use this approach?</p>

答:
You have some excellent answers above but given that, in a comment, you answered the question "Why do you want to create a programming language of your own in the first place? " with "It would be for learning purpose mainly," I'm going to answer from a different angle.

It makes sense to write a converter that takes the source code and converts it to C or C++ code, so that you can use an existing compiler like gcc to end up with machine code, if you are more interested in learning about lexical, syntax and semantic analysis than you are in learning about code generation and optimization!

Writing your own machine code generator is a pretty significant piece of work which you can avoid by compiling to C code, if it's not what you are primarily interested in!

If, however, you are into assembly program and fascinated by the challenges of optimizing code at the lowest level, then by all means, write a code generator yourself for the learning experience!


问:
What do you call the line/s of code that declare that a class or function is a template?
I'm writing some macros which declare template types and I'm a bit stumped for terminology. To illustrate, take the following example:

```<code>// template class declaration
template <typename A, typename B> // what is this called?
class A;
</code>```

My question is: What is the name of the line above class A?

答:
That is simply part of the class declaration.

When you declare a type, you essentially say "this is a type." Compared to the definition which provides the contents of the type: its data members and member functions (although those functions may themselves be declarations, with the definitions separate).

That the declaration you provided involves a template does not change this fact, nor does the fact that they are on separate lines in the file. The newline is irrelevant here: the important thing is what occurs from the beginning of the statement to its end (the semicolon).


问:
When writing object-oriented code, should I always be following a design pattern?
Is there a conceivable design pattern for any object-oriented program? I ask this because recently I saw an implementation of a Door class with a Lock. It was part of a test and the answer said that the code is following the Null Object pattern:

class Lock
{
public:
    virtual void close() = 0;
    virtual void open() = 0;
    virtual bool is_open() const = 0;
    virtual ~Lock() { }
};

class DummyLock
    : public Lock
{
private:
    DummyLock();
    DummyLock(const DummyLock&) = delete;
    DummyLock& operator=(const DummyLock&) = delete;

private:
    void close() { }
    void open() { }
    bool is_open() const { return true; }

public:
    static DummyLock m_instance;
};

class Door
{
public:
    Door() : m_lock(DummyLock::m_instance) { }
    Door(Lock &lock) : m_lock(lock) { }

public:
    Lock& get_lock() const { return m_lock; }

private:
    Lock &m_lock;
};
```

This made me think: This code follows a good design pattern even though the description is so simple (this class is designing a door class with a lock), so if I am writing more complex code, should there always be some design pattern that I am following?

答:
Broken question. Let me give you a novel definition of design pattern that would undo a lot of damage released by GoF: a design pattern is a good coding practice. That's it.

Any reasonably complex module will have several design patterns in it. Any time you cache it's probably a flyweight pattern but I'm not going to revoke your programming degree if you don't call it that. Any time you have a callback in it you're in some sort of event / fire / callback pattern. etc. If you have the word "static" you have a singleton. If you have a static constructor you have a factory pattern. If a resource is passed to your module you are using dependency injection.

"Design pattern" is a broken term ill-popularized by GoF, that makes it sound like all patterns are on the same level or you should use the doctor recommended 3 to 5 per class. Any time you do something right that someone else did right, it's a design pattern. A for(;;) is a common pattern used to represent an infinite loop, for instance.

You shouldn't go try to learn a bunch of design patterns. Programming knowledge is not indexed by design patterns! Rather you should learn how to write good code by read books, blogs, and attend conferences in your field. For instance, if you're already using dependency injection but just haven't labeled it, you might benefit from always using DI or using an IoC framework. Or if you're struggling to code right in events and callbacks, go learn Haskell so you're familiar with functional design patterns and it becomes easy.

And if your entire class reads as one big thing someone else did right, why are you reinventing the wheel? Just use their stuff.


答:
As far as I'm aware, there doesn't seem to be an official name for it.

In the C++ standard, the grammar for a template declaration is:

template-declaration:
    "template" "<" template-parameter-list ">" declaration
```

so it doesn't actually designate a name for the template<...> part.

Title: What do you call the line/s of code that declare that a class or function is a template?

Body:
I'm writing some macros which declare template types and I'm a bit stumped for terminology. To illustrate, take the following example:

```<code>// template class declaration
template <typename A, typename B> // what is this called?
class A;
</code>```

My question is: What is the name of the line above class A?

Body:
As far as I'm aware, there doesn't seem to be an official name for it.

In the C++ standard, the grammar for a template declaration is:

template-declaration:
    "template" "<" template-parameter-list ">" declaration

so it doesn't actually designate a name for the template<...> part.


答:
Yes. Your inclination is sound. You should leave a comment in the method's source code and/or larger documentation.

```<code>// Implements IComparable interface
</code>```

in the method source should do the trick, allowing those who will be reading the code closely (you later on, or someone else maintaining, modifying, or adapting it) to easily and rapidly acertain why the method exists.

If the method is part of a promoted API, it can also be mentioned in the API docs (the form of which will vary based on what documentation system you're using).

Even if you're not fully committed to literate programming, in which an explanation of the code is considered co-equal to the code itself, it is an excellent practice to use comments in the program source and notes in the API documentation to explain how the program works, why it is defined and implemented as it is, and how to use it.

Title: Should I denote that a method satisfies an interface?

Body:
When writing a class which has ("satisfies") 1 or more interfaces, should I note somehow (e.g. in an XML comment, or with an attribute) that a particular method was added for one of the interfaces?

For example, the IComparable interface requires an int CompareTo(Object) method.

I know I don't need to do anything other than implement the appropriate methods, but for maintainability and ease of understanding are there any "best practices" for letting others know why the method exists?

Body:
Yes. Your inclination is sound. You should leave a comment in the method's source code and/or larger documentation.

// Implements IComparable interface

in the method source should do the trick, allowing those who will be reading the code closely (you later on, or someone else maintaining, modifying, or adapting it) to easily and rapidly acertain why the method exists.

If the method is part of a promoted API, it can also be mentioned in the API docs (the form of which will vary based on what documentation system you're using).

Even if you're not fully committed to literate programming, in which an explanation of the code is considered co-equal to the code itself, it is an excellent practice to use comments in the program source and notes in the API documentation to explain how the program works, why it is defined and implemented as it is, and how to use it.


答:
No. The reality is that the SQL required by Oracle, DB2, SQLite, MySQL, PostgreSQL, and name your favorite other relational DBMS is different from the SQL required by each of the other DBMS systems--the various SQL "standards" notwithstanding.

Very basic functionality and semantics, like what data types are supported (and what they're called), how row identifiers are allocated (with what semantics), and what type of operations are supported (including keywords, functions, restrictions, and semantics) differ enormously. These many differences are why DBMS migrations are so famously difficult, and why they require custom tools and consulting services.

Yes the basic form of SELECT * FROM table WHERE ... is common across all relational database systems. But the devil of real applications is in the details, and the details differ in important ways between different data stores.

This is to say nothing of the even greater differences seen between relational and non-relational DBMSs (be they traditional hierarchical, network, flat file, record stores, or the new hotness of NoSQL). Even if they have "SQL compatibility layers," the extent and semantics of their SQL vary greatly.

SQL (and other data definition and query langauge) homogenization is an approach that has been worked on, tried, and hoped for at least four decades now. It never quite works out as well as hoped. Given the fundamental economic incentive for DBMS producers to prevent their customers from easily migrating to competing products or vendors, there's little hope of this being resolved any time in the next decade or two.

Title: Is there a 'standard' SQL that can replace all the various custom versions?

Body:
I have been writing SQL for over 10 years now. I am extremely proficient at it and have experience working in SQL Server, Oracle, MySQL, PostgreSQL, etc. While there are multiple standards out there, they seem to be more suggestions than standards. When you start talking about column types and stored procedures, there's almost no consistency across the board.

I wonder if someone ever considered defining a new querying language. I recently played around with some ideas. Here are some examples: https://gist.github.com/jehugaleahsa/03888d13ef2745cb67d0. Of course, this just covers the most obvious DML. This syntax would make it easier to support auto-completion, give more control over the temp table generation, make the join syntax easier, make working with grouped data easier and make sub-expressions/calculations easier to build up, just to name a few. I especially like it because it could very easily be extended to support some noSQL databases, as well. Imagine what a committee could come up with given more time!

My question is whether any effort has been put into defining a different querying language, supported by the different providers. I recognize that SQL is "good enough" and that defining and implementing a new standard would be a monumental undertaking. I know there were a lot of SQL standards proposed over the years. I just wonder if a non-"SQL" standard ever was proposed and whether it made progress or just fizzled out.


答:
... make the join syntax easier, make working with grouped data easier and make sub-expressions/calculations easier to build up, just to name a few. I especially like it because it could very easily be extended to support some noSQL databases...

Now I think that's where One Standard To Rule Them All breaks down... Current NoSQL solutions are not as optimal as traditional RDBMS for running join operations, if they even support it natively in the first place, and for good reasons. Sure, they are trying to improve in this aspect, but there's no magic bullet yet. And why stop at NoSQL vs RDBMS, how about graph databases? Cypher for Neo4j has a MATCH clause instead that 'is analogous to the JOIN in SQL'.

I think one should look towards polyglot persistence frameworks to adequately handle the "various custom SQL" problem. If it turns out that your application uses a small in-memory RDBMS solution for simple caching, and writes to a multi-terabyte data warehouse powered by a NoSQL solution, the "solution" to a standardized database interface may not be some mytical common dialect, but a well-written framework that understands the differences and handles appropriately.


问:
Do we need to test 32-bit software in 64-bit Windows?
I'm working in a software development team as software developer. I've been working on the same project for three years now. The software is a 32-bit desktop based C# application in .NET 4. Our target platform in Windows 7 (we had to support Windows XP till last year). The software communicates with various custom hardware for which custom drivers are written. The hardware manufacturing and driver software is written by our client. There is different driver for 32-bit and 64-bit Windows of course.

During our system testing phase, we execute all/most test cases in both 32-bit and 64-bit Windows 7. I can't recall if we got any bug in our software that exist in only one flavor of Windows. Having this experience I've started to wonder, do we really need to test 32-bit software on 64-bit Windows?

What's the industry standard?

答:
The default assumption in enlightened QA circles is "If you didn't test it, then it doesn't work".

As a practical matter that's usually an unreachable goal to strive for in much the same way application engineers might like to have unit-tests for everything; but they don't believe they'll ever reach it and release on schedule.

However your question can only be answered by, or in conjunction with, sales and marketing. You provide them with a cost to test and they provide an analysis of the market benefit. If estimations on both sides were sufficiently accurate, the answer would be simple

```<code>if B > C:
    test_32bit_version()
</code>```

In my experience, everyone's cost estimates are inaccurate. As far as the other side of the equation, Dilbert once parodied decision making there with "I just asked my cat, Mittens". To do much better, they'd need training in anthropological field methods.

Body:
The default assumption in enlightened QA circles is "If you didn't test it, then it doesn't work".

As a practical matter that's usually an unreachable goal to strive for in much the same way application engineers might like to have unit-tests for everything; but they don't believe they'll ever reach it and release on schedule.

However your question can only be answered by, or in conjunction with, sales and marketing. You provide them with a cost to test and they provide an analysis of the market benefit. If estimations on both sides were sufficiently accurate, the answer would be simple

if B > C:
    test_32bit_version()

In my experience, everyone's cost estimates are inaccurate. As far as the other side of the equation, Dilbert once parodied decision making there with "I just asked my cat, Mittens". To do much better, they'd need training in anthropological field methods.


问:
Why is there no default constructor generated if you define an explicit constructor?
```<code>class Employee{

    String name;
    int id;

   //No explicit constructors
}
</code>```

Now I can invoke the following statement:

```<code>Employee e1 = new Employee();
</code>```

With the above code, the compiler will provide the definition for the constructor Employee().

If I define a single explicit constructor as follows:

```<code> class Employee{

    String name;
    int id;

    Employee(String aName){
        this.name=aName;
    }
}
</code>```

Now, why can't I invoke the following statement:

```<code>Employee e2 = new Employee();
</code>```

Even though the compiler knows how to provide definition of Employee().

Now, just because I have defined an explicit constructor Employee(String aName), why can't I use a default constructor?

Also, if the compiler had allowed the use of the default constructor even after defining an explicit one, it would have helped us to reuse the code for default constructor.

答:
The language puts the default constructor in as a favor to you. The presumption is that if you've written a custom constructor, your no-argument constructor may well require special attention too. Not a great reason, but not horrible, either.

The secondary reason id that cruft just gets pile onto that language with no thought to its symmetry with existing practice and very little interest in making it readable. Stoustroup's original "C with Classes" was a hacked up C-preprocessor which probably shouldn't made it out of the lab. The world's funny that way.


答:
Amazing that not a single other person has mentioned testing.

The particular "wrapped" line that you picked, window.alert('hello'), is actually a perfect example of this. Anything involving the window object is really, really painful to test. Multiply that by 1000 times in your application and I guarantee that the developers will eventually give up on testing. On the other hand, it's pretty easy to just clobber the sayHello function with a spy and test that it got called.

A more practical example - because really, who actually uses window.alert(...) in production code? - is checking the system clock. So for example, this would be wrapping DateTime.Now in .NET, time(...) in C/C++, or System.currentTimeMillis() in Java. You really want to wrap those in a dependency that you can inject, because they are not only (almost) impossible to mock/fake, they are read-only and non-deterministic. Any test covering a function or method that makes direct use of the system clock function is extremely likely to suffer from intermittent and/or random failures.

The actual wrapper is a 1-line function - return DateTime.Now - but that's all you need in order to take a poorly-designed, non-testable object and make it a clean and testable one. You can substitute a fake clock for the wrapper, and set its time to whatever you want. Problem solved.

Title: What is the benefit of a function without parameters which only calls another function

Body:
A tutorial (for Javascript) I'm doing suggests we write a function like this one:

```<code>function sayHello() {
   //Some comments explaining the next line
   window.alert("Hello");
}
</code>```

Other than obfuscation are there benefits to writing something like this in real life? If so, what are the benefits?


问:
Static methods vs Interface implementation
Here is my problem:

I stared to create an e-commerce web site info collector.

So I created a parser for each site.
The parser class is stateless.

I have got methods like:

```<code>getItemPrice(WebElement page)
getItemTitel(WebElement page)
getItemDescription(WebElement page)
etc..
</code>```

While creating a JUnit tests for that the convenient way was to make them static methods.

While creating the next parser for the next page ,again I needed the same methods.
So it just popped out that an interface of an IItem is required here for future changes, etc.
Therefore I have a problem to set these methods as static.
Which require to create an instance of a stateless class which lead to simple factory to create these instances etc.

I'm not sure whether this Interface is causing me too much of an overhead or not.

Any ideas?

答:
I don't think there will be too much overhead when using an interface. You can even argue that the use of static methods could generate more overhead in this case, depending on how much different implementations you want to support and how many methods you need.

When using static methods, you need to have some logic which implementation you have to use, which is basically a big switch statement for every method. This can be simplified by putting a wrapper around all those implementations, but evaluating the same switch statement over and over again for each method you want to call is not really advisable.

With the use of interfaces this will be reduced to just one evaluation of the switch statement (in the factory).


答:
Most of the bugs we encountered with running 32-bit software on 64-bit windows had to do with the location of the software (Program Files (x86) instead of Program Files), locations of registry keys (some were found in Wow6432Node). We had these problems mostly because we needed to communicate with other software (also 32-bit), and so we needed to test the software on both 32-bit and 64-bit...

When you didn't have these problems, I believe it is quite safe not testing on both platforms when you explicitly compile in 32-bit mode. When compiled in 32-bit, the .NET runtime will run everything in 32-bit mode, and it should work the same as the 32-bit mode on 32-bit platforms.

According to 64-bit Applications (MSDN), 32-bit applications are run in Wow64 mode and Running 32-bit Applications (MSDN) explains this mode in more detail.

Title: Do we need to test 32-bit software in 64-bit Windows?

Body:
I'm working in a software development team as software developer. I've been working on the same project for three years now. The software is a 32-bit desktop based C# application in .NET 4. Our target platform in Windows 7 (we had to support Windows XP till last year). The software communicates with various custom hardware for which custom drivers are written. The hardware manufacturing and driver software is written by our client. There is different driver for 32-bit and 64-bit Windows of course.

During our system testing phase, we execute all/most test cases in both 32-bit and 64-bit Windows 7. I can't recall if we got any bug in our software that exist in only one flavor of Windows. Having this experience I've started to wonder, do we really need to test 32-bit software on 64-bit Windows?

What's the industry standard?


答:
A constructor with arguments isn't just a handy shorthand for using setters. You write a constructor in order to ensure that an object will never, ever exist without certain data being present.

If there is no such requirement, fine. But if there is one, as indicated by the fact that you've written such a constructor, then it would be irresponsible to generate a default constructor, through which a client could circumvent the "no object without data" rule. Doubly so, because the auto-generated default constructor is invisible to a casual code reader, which hides the fact that it exists! No, if you want constructors with arguments and a default constructor, you must write the default constructor yourself. It's not as if it's a lot of effort to write an empty block, anyway.

Title: Why is there no default constructor generated if you define an explicit constructor?

Body:
```<code>class Employee{

    String name;
    int id;

   //No explicit constructors
}
</code>```

Now I can invoke the following statement:

```<code>Employee e1 = new Employee();
</code>```

With the above code, the compiler will provide the definition for the constructor Employee().

If I define a single explicit constructor as follows:

```<code> class Employee{

    String name;
    int id;

    Employee(String aName){
        this.name=aName;
    }
}
</code>```

Now, why can't I invoke the following statement:

```<code>Employee e2 = new Employee();
</code>```

Even though the compiler knows how to provide definition of Employee().

Now, just because I have defined an explicit constructor Employee(String aName), why can't I use a default constructor?

Also, if the compiler had allowed the use of the default constructor even after defining an explicit one, it would have helped us to reuse the code for default constructor.


答:
The hardware manufacturing and driver software is written by our client. There is different driver for 32 bit and 64 bit Windows of course.

So on 32 bit Windows, your software talks to one driver, and on 64 bit Windows, it talks to a different one? Let us assume there are new versions of these drivers from time-to-time. So when you only test your software on 32 bit Windows you cannot be sure there won't be some differences in the 64 bit driver which will make the combination of your software + 64 bit driver fail. And from the viewpoint of your users, it does not matter who is to blame (you or the author of the driver), all they see is a non-working system. So even if your code is free of bugs, a test might reveal a bug in the 64 bit driver, and finding such a bug might help you take the right measures (like sending a bug report to the author of the driver).

Of course, when you have used those two drivers for years, and you are very confident that the behaviour is exactly the same, you might skip the tests for one platform, following the arguments in @DavidPerfors's answer. As a compromise, you could run tests on 64 bit Windows only whenever a new driver version is available. Actually, this depends on the complexity of the drivers, your experience with and confidence in them.

Some additional things to consider:

what OS type is your user base using most? 32 bit or 64 bit Windows? If you decide to test only on one platform, choose the one your users use most often.

how severe is it when a new release of the software will not work on a less frequently used platform? For example, can your customers immediately step back and install the previous working release? Do they have only some inconvenience or real financial loss by this? If it is the former, testing on only one platform may be fine, if it is the latter, obviously not.


答:
Seeing as 99% of all Windows installations of Windows 7 and up, and a good portion of Vista as well, are 64 bit, why the hell would you even consider not testing for that platform?

It's just a no-brainer, unless you're making it specifically for a very limited group of users you KNOW are using 32 bit Windows and will continue to do so for the life of your product.

So yeah, test for 64 bit problems. In fact develop on 64 bit platforms, and probably supply a 64 bit version as standard with a 32 bit compiled version as an option for those few customers who've not upgraded to a new computer and OS in the last 6-8 years or so.


问:
Who provides hardware resources in private cloud?
I find myself confusing to understand the concept of private cloud. If a company has an offshore data-center, and now if the company wants to move into a private cloud, what does the company has to do?

If I am correct, in order to use the term cloud, there should be virtualization. If there is no virtualization, there is no cloud. So is a private cloud, where you virtualize your existing data center? Or is it simply throwing out your existing hardware and purchasing hardware from a cloud provider, so that now all your resources are on the Internet?

And also how does the private cloud differ from virtual private cloud?

答:
"Cloud" is simply a trendy term for "on someone else's computer". (That, by the way, is also a great handy way of deciding whether or not it's a good idea to move something to the cloud or not.) If you run processes on computers owned by someone else who has a data center specifically for providing this service, that's the cloud. Virtualization is not strictly necessary, but usually done because it's a better deal for the cloud provider.

A private cloud is the same except that your company also owns the data center (or maybe owns the company that owns the data center). Theoretically, if you're a customer of Amazon's cloud services, and one day you get really, really rich and buy Amazon wholesale, you've moved from cloud usage to private cloud usage without anything else changing.


问:
Is this a commonly encountered situation in C++? Is there a pattern to handle it?
I am writing a game in C++, and something I have noticed is that I have many resource files which need to be loaded after a particular point in initialization.

For example, OpenGL textures and VAOs can't be created until there's a current OpenGL context. Once loaded, they will never be modified, so it is most convenient to make them global.

If these objects could be created without a current OpenGL context, this would be trivial to do:

```<code>const texture ground_texture = load_texture("ground.png");
const texture robot_texture = load_texture("robot.png");
const model robot_model = load_model("robot.obj");
</code>```

where texture and model are simple POD structs containing (among other things) OpenGL object IDs.

Instead, I can do this:

```<code>texture ground_texture;
texture robot_texture;
model robot_model;

void load_resources() {
    ground_texture = load_texture("ground.png");
    robot_texture = load_texture("robot.png");
    robot_model = load_model("robot.obj");
}
</code>```

and then call load_resources after the OpenGL context is initialized. But that requires about twice as much code (three times if these globals are also declared in a header file as well) and loses the const modifier.

It could conceivably be produced by a simple script to reduce duplication - then the only downside compared to the original non-working code is that the globals aren't const.

There's also this:

```<code>class texture_loader;
class model_loader;
static std::vector<const texture_loader*> tex_loaders;
static std::vector<const model_loader*> model_loaders;

class texture_loader {
    mutable texture tex;
    mutable bool initialized;
    const char *filename;
public:
    texture_loader(const char *filename)
        : initialized(false), filename(filename)
    {
        tex_loaders.push_back(this);
    }

    void load() const {
        tex = load_texture(filename);
        initialized = true;
    }

    operator texture() const {
        assert(initialized);
        return tex;
    }
};
// similarly for model_loader

const texture_loader ground_texture("ground.png");
const texture_loader robot_texture("robot.png");
const model_loader robot_model("robot.obj");

void load_textures() {
    for(texture_loader *t : tex_loaders) t->load();
    for(model_loader *m : model_loaders) m->load();
}
</code>```

but that seems like quite a lot of complexity for something that is conceptually simple. Also, texture_loader and model_loader (and anything_else_loader) would need to be exposed outside the resource loading module in order for other code to be able to use the globals.

Is this a commonly encountered case? How is it typically solved?

答:
Even if it is true that these things will never change, these textures and models are logically part of a specific part of your program: the 3D environment.  They only make sense and will only be used within this context.  Thus they should not be globals; they should be declared within the relevant context of your program.

A basic principle is that all variables should have the smallest scope that fits their use case and should be declared as close to where they are used as possible.  Even if variables will never change, there is benefit to limiting their scope:

It makes the code easier to understand.

It makes the code more flexible to change in the future.

It aids code reuse (you can take a specific piece of code and use it elsewhere without bringing along a bunch of global variables).


答:
Java generating a parameterless constructor when you don't have any other is like a polite waiter taking your coat for you.

Java still generating a parameterless constructor after you define another version of it is like the same waiter taking the coat off you after you gave a clear indication that you have your own plans of what to do with the coat.

If I have a class (that I want to be immutable):

```<code>class Person
{
    final String firstName;
    final String lastName;
</code>```

And I add a constructor:

```<code>    Person(String firstName, String lastName)
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}
</code>```

And Java was still to provide a default, parameterless constructor, then this code can't compile, because firstName and lastName fields are declared as final, yet they are not set after you call Person p = new Person().

You are forcing me to provide another implementation:

```<code>private Person()
{
    this.firstName = null; // or "", or whatever
    this.lastName = null;
}
</code>```

And since I don't want it - as it's useless, I might feel inclined to put skull and crossbones on it:

```<code>@Deprecated
private Person()
{
    // don't use this constructor! i don't want it to ever be called!
    throw new RuntimeException("Illegal constructor called");
}
</code>```

But I still can't forbid another developer to create a method (inside the Person class, so marking the constructor as private didn't help):

```<code>public static Person createPerson()
{
    return new Person(); // this will blow in our face
}
</code>```

All this fuss could be - and is - avoided thanks to the fact that Java (and not only Java) works the way it works.

If you define a method setCoordinates(int x, int y), you don't expect compiler to automatically accept a parameterless version of it - setCoordinates(). It wouldn't do a thing.

How is this different from expecting a parameterless constructor? Well, obviously, a constructor always does at least one thing - it creates an object (or dies trying).

But I like to be in control of how I want my objects to be instantiated. Forcing me to have a parameterless constructor no matter what I do takes this control away from me.

Body:
Java generating a parameterless constructor when you don't have any other is like a polite waiter taking your coat for you.

Java still generating a parameterless constructor after you define another version of it is like the same waiter taking the coat off you after you gave a clear indication that you have your own plans of what to do with the coat.

If I have a class (that I want to be immutable):

class Person
{
    final String firstName;
    final String lastName;

And I add a constructor:

    Person(String firstName, String lastName)
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

And Java was still to provide a default, parameterless constructor, then this code can't compile, because firstName and lastName fields are declared as final, yet they are not set after you call Person p = new Person().

You are forcing me to provide another implementation:

private Person()
{
    this.firstName = null; // or "", or whatever
    this.lastName = null;
}

And since I don't want it - as it's useless, I might feel inclined to put skull and crossbones on it:

@Deprecated
private Person()
{
    // don't use this constructor! i don't want it to ever be called!
    throw new RuntimeException("Illegal constructor called");
}

But I still can't forbid another developer to create a method (inside the Person class, so marking the constructor as private didn't help):

public static Person createPerson()
{
    return new Person(); // this will blow in our face
}

All this fuss could be - and is - avoided thanks to the fact that Java (and not only Java) works the way it works.

If you define a method setCoordinates(int x, int y), you don't expect compiler to automatically accept a parameterless version of it - setCoordinates(). It wouldn't do a thing.

How is this different from expecting a parameterless constructor? Well, obviously, a constructor always does at least one thing - it creates an object (or dies trying).

But I like to be in control of how I want my objects to be instantiated. Forcing me to have a parameterless constructor no matter what I do takes this control away from me.


问:
Building a string parser for user command and control?
My goal is to build a command parser that has basic syntax and multiple possible branches at each point. These commands come from users of the system and are text input (no GUI). The basic syntax is base_command [sub_command [optional_parameters]], where optional_parameters is a space seperated list of parameters.

Examples:

```<code>add event "Program-a-thon"
add notification program-a-thon meeting
add pattern "follow the white rabbit"
remove event "Program-a-thon"
remove notification meeting
remove pattern "follow the white rabbit"
edit pattern "follow the white rabbit" "follow the white tiger"
reload settings
</code>```

As you can see, I have 4 base commands (add, remove, edit and reload). However, I anticipate adding more in the future. I also have 4 subcommands (event, notification, pattern and settings). However, edit only has 1 subcommand and settings only applies to the reload base command. Not all subcommands are associated with all base commands. Finally, I have parameters. For simplicity, I am planning on making these position based.

I am writing this application in Python (utilizing the 2.7 branch).

So far, I've come up with this:

Utilize the .split() command and take the first two results to get the command and base command. The third index (if it exists) will be the positional arguments.

OR

Utilize a regular expression to get the base command and sub-command. The third index will be positional arguments.

Then utilizing this information, look at a dictionary like this to see if the command/sub-command option is viable. If it is, call the method described in the commands[base_command][sub_command]['method'] key to perform my action.

The upside of this is that I can easily tell if the command/subcommand combination is valid. The downside is maintaining such a dictionary and possibly extending it if I wish to add more options or information. For just these few commands I already have a dictionary like this (with some supporting attributes)

```<code>commands =
{
    'add' :
    {
        'help_text' : "Add a `event`, `notification`, or `pattern`",
        'sub_commands': {
                'event' : {
                    'help_text' : "Add an event",
                    'method' : "add_event",
                    'permissions' : 'trusted',
                },
                'notification' : {
                    'help_text' : "Recieve a notification for events that are tagged with the values you wish (tag1 [,tag2[,tag3[,tag4]]])",
                    'method' : "add_notification",
                    'permissions' : 'all',
                },
                'pattern' : {
                    'help_text' : "Add a pattern you wish the system to watch for in new event descriptions",
                    'method' : "add_pattern",
                    'permissions' : 'all',
                },
            },
        'sub_command_required' : True,
        'method' : None,
    },
    'remove':
    {
        'help_text': "Remove a `event`, `notification`, or `pattern`",
        'sub_commands': {
                'event' : {
                    'help_text' : "Remove an event",
                    'method' : "remove_event",
                    'permissions' : 'trusted',
                },
                'notification' : {
                    'help_text' : "Remove a notification for specific tags (tag1 [,tag2[,tag3[,tag4]]])",
                    'method' : "remove_notification",
                    'permissions' : 'all',
                },
                'pattern' : {
                    'help_text' : "Add a pattern you wish the system to watch for in new event descriptions",
                    'method' : "remove_pattern",
                    'permissions' : 'all',
                },
            },
        'sub_command_required' : True,
        'method' : None,
    },
    'edit':
    {
        'help_text': "Edit an existing `pattern`",
        'sub_commands': {
                'pattern' : {
                    'help_text' : "Edit a pattern pattern to watch for in new event descriptions (old_pattern, new_pattern)",
                    'method' : "edit_pattern",
                    'permissions' : 'all',
                },
            },
        'sub_command_required' : True,
        'method' : None,
    },
    'reload':
    {
        'help_text': "Reload application options",
        'sub_commands': {
                'settings' : {
                    'help_text' : "Reload the settings of the application",
                    'method' : "reload_settings",
                    'permissions' : 'owner',
                },
            },
        'sub_command_required' : True,
        'method' : None,
    },
}
</code>```

My questions are, how do I properly design the parser so that I can

Extend the command tree easily in the future?

Have a combination of sub-commands that may or may not apply to all base commands?

And

Is utilizing a dictionary, like above, worth the hassle of maintenance when adding commands? I realize that commands will be 'relatively' stable (once added, modifications will be rare to the dictionary itself). However, when I do add them, they will probably come in at least pairs (add and remove), meaning the potential for messing up the dictionary occurs in multiple places.

答:
Parsing this kind of commands is very much like parsing command line options and the fact that you have one word commands and arguments just makes it easier.

What you basically can do is to read a line and split it using a regex. The reason I would choose for a regex is that it makes it easier to split the string and keep the text in quotes together.

When the line is split you have to lookup the command, or you can lookup the subcommand first. Since an 'event' can be added and removed, it could be logical to combine them in the dictionary under 'event' instead of 'add' and 'remove', because you do the add and remove operation on an event.

The values in the dictionary could be command classes that have the knowledge to parse the arguments, run the command and print the help text. This way the main dictionary will stay readable and maintainable and the commands could be tested individually.

A small example in python like pseudo code of what I mean:

```<code>class commandBase
    def execute(subcommand, args):
        self.subCommands[subcommand].method(args);

class eventCommand : commandBase
    def __init__(self):
        self.subCommands = {
           "add": { "help_text" : "add an event", method: self.add }
           "remove": { "help_text" : "remove an event", method: self.remove }
        }

command = { "event" : new eventCommand }
parsedLine = parseLine(line)
command[parsedLine[1]].execute(parsedLine[0], pardesLine[2])
</code>```

Body:
Parsing this kind of commands is very much like parsing command line options and the fact that you have one word commands and arguments just makes it easier.

What you basically can do is to read a line and split it using a regex. The reason I would choose for a regex is that it makes it easier to split the string and keep the text in quotes together.

When the line is split you have to lookup the command, or you can lookup the subcommand first. Since an 'event' can be added and removed, it could be logical to combine them in the dictionary under 'event' instead of 'add' and 'remove', because you do the add and remove operation on an event.

The values in the dictionary could be command classes that have the knowledge to parse the arguments, run the command and print the help text. This way the main dictionary will stay readable and maintainable and the commands could be tested individually.

A small example in python like pseudo code of what I mean:

class commandBase
    def execute(subcommand, args):
        self.subCommands[subcommand].method(args);

class eventCommand : commandBase
    def __init__(self):
        self.subCommands = {
           "add": { "help_text" : "add an event", method: self.add }
           "remove": { "help_text" : "remove an event", method: self.remove }
        }

command = { "event" : new eventCommand }
parsedLine = parseLine(line)
command[parsedLine[1]].execute(parsedLine[0], pardesLine[2])


问:
Is there a language-agnostic specification for "string natural sorting order"?
As I painfully try to find a good natural sorting algorithm written in JavaScript, I then stumble upon a bunch of different implementations, interesting blog posts, and answers on StackOverflow.

Each implementation provides its technical tricks. However, the more I looked into it the more a question became very clear: "Is there actually any language-agnostic specification regarding natural sorting order of strings?"

I mean, if not, then how could one expect to write a piece of code that is actually "correct for everyone" or "agreed on by the community"? I would have expected a specification stating the result of the compromises/decisions made, at least for English, as it is simple (no accents/diacritics)...

Note that I wrote "language-agnostic" as I would expect this specification to then be used to implement solutions in different languages, not only in JavaScript, C#, or Java.

Resources:

Sorting for Humans: Natural Sort Order

Alphanum: JavaScript Natural Sorting Algorithm

www.davekoelle.com/alphanum.html

How to sort strings in JavaScript

Natural sort of alphanumerical strings in JavaScript

答:
There is ISO 14651. This is an ISO Standard specifying an algorithm that can be used when comparing two strings. The standard also specifies a datafile specifying the comparison order, the Common Tailorable Template, CTT.

There is the European Ordering Rules. This is an implementation of the iso CTT. It defines an ordering for strings written in languages that are written with the Latin, Greek and Cyrillic alphabets.

There is the Unicode Collation Algorithm. The Unicode collation algorithm (UCA) is an algorithm defined in Unicode Technical Report #10, which defines a customizable method to compare two strings.

ContentLicense: CC BY-SA 4.0


答:
Typically, globals and their friendly disguise the singleton are commonly over-used.

However the fact that your data doesn't change once loaded means that, if your process is multi-threaded, once you can be sure they actually are loaded you can have multiple threads access the data at the same.

There are different models that could be used to load the data:

All upfront. The simplest model. As you start up you load everything before anything can go. Unfortunately I often find too many apps are guilty of doing this, especially if they are loading something you don't care about. Windows Media Player making you wait while it loads / updates its "library" when all you want to do is play one music file or video that you know the location of is a typical example.

All lazy. Nothing is pre-loaded and only loaded the first time it is requested. This works in some cases.

A mix: Some pre-loading, others loaded lazy.

Pre-loading in a background thread. Items are loaded at the start but the application can run before they are all loaded. If you request something that isn't loaded yet you have to wait for it, though (or have logic to load that item instantly).

In a multi-threaded loading environment you can use futures and once-loading calls to ensure the data is loaded exactly ones.

Title: Is this a commonly encountered situation in C++? Is there a pattern to handle it?

Body:
I am writing a game in C++, and something I have noticed is that I have many resource files which need to be loaded after a particular point in initialization.

For example, OpenGL textures and VAOs can't be created until there's a current OpenGL context. Once loaded, they will never be modified, so it is most convenient to make them global.

If these objects could be created without a current OpenGL context, this would be trivial to do:

```<code>const texture ground_texture = load_texture("ground.png");
const texture robot_texture = load_texture("robot.png");
const model robot_model = load_model("robot.obj");
</code>```

where texture and model are simple POD structs containing (among other things) OpenGL object IDs.

Instead, I can do this:

```<code>texture ground_texture;
texture robot_texture;
model robot_model;

void load_resources() {
    ground_texture = load_texture("ground.png");
    robot_texture = load_texture("robot.png");
    robot_model = load_model("robot.obj");
}
</code>```

and then call load_resources after the OpenGL context is initialized. But that requires about twice as much code (three times if these globals are also declared in a header file as well) and loses the const modifier.

It could conceivably be produced by a simple script to reduce duplication - then the only downside compared to the original non-working code is that the globals aren't const.

There's also this:

```<code>class texture_loader;
class model_loader;
static std::vector<const texture_loader*> tex_loaders;
static std::vector<const model_loader*> model_loaders;

class texture_loader {
    mutable texture tex;
    mutable bool initialized;
    const char *filename;
public:
    texture_loader(const char *filename)
        : initialized(false), filename(filename)
    {
        tex_loaders.push_back(this);
    }

    void load() const {
        tex = load_texture(filename);
        initialized = true;
    }

    operator texture() const {
        assert(initialized);
        return tex;
    }
};
// similarly for model_loader

const texture_loader ground_texture("ground.png");
const texture_loader robot_texture("robot.png");
const model_loader robot_model("robot.obj");

void load_textures() {
    for(texture_loader *t : tex_loaders) t->load();
    for(model_loader *m : model_loaders) m->load();
}
</code>```

but that seems like quite a lot of complexity for something that is conceptually simple. Also, texture_loader and model_loader (and anything_else_loader) would need to be exposed outside the resource loading module in order for other code to be able to use the globals.

Is this a commonly encountered case? How is it typically solved?