问:
Purpose of `return self` from a class method?
I came across something like this in an open-source project. Methods that modify instance attributes return a reference to the instance. What is the purpose of this construct?</p>

```<code>class Foo(object):

  def __init__(self):
    self.myattr = 0

  def bar(self):
    self.myattr += 1
    return self
</code>```

答:
Most language are aware of the 'return self' idiom, and ignore it if it is
not used in a line. However it is notable that in Python, functions
return None by default.

When I was in CS school my instructor made a huge deal about
the difference between functions, procedures, routines, and methods; many hand-cramping essay questions were ground out with mechanical pencils getting hot in  my hands about all that.

Suffice it to say, returning self is the definitive OO way to craft
class methods, but Python allows for multiple return values, tuples, lists, objects, primitives, or None.

Chaining, as they put it, is merely putting the answer to the last operation into the next, and the runtime of Python can optimize that kind of thing. List comprehensions are a built-in form of this. (Very powerful!)

So in Python it is not so important that every method or function return things,
which is why the default is None.

There is a school of thought that every action in a program should report its success, failure, or result back to its invoking context or object, but then
were not talking DOD ADA Requirements here.  If you need to get feedback from
a method, go ahead, or not, but try to be consistent about it.

If a method can fail, it should return success or failure or raise an exception to be handled.

One caveat is that if you use the return self idiom, Python will allow you to assign all your methods to variables and you might think you are getting a data result or a list when you are actually getting the object.

Type-restrictive languages scream and yell and break when you try to do this, but interpreted ones (Python, Lua, Lisp) are much more dynamic.


问:
If I use locks, can my algorithm still be lock-free?
A common definition of lock-free is that at least one process makes progress. 1

If I have a simple data structure such as a queue, protected by a lock, then one process can always make progress, as one process can acquire the lock, do what it wants, and release it.

So does it meet the definition of lock-free?

1 See eg M. Herlihy, V. Luchangco, and M. Moir. Obstruction-free synchronization: Double-ended queues as an example. In Distributed Computing, 2003. "It is lock-free if it ensures only that some thread always makes progress".

答:
Terminology isn't always consistent, but I think what's important is to ask the following questions about a proposed algorithm or system:

Is there any sequence of events where threads could become stuck waiting for each other even if all threads were allowed all CPU time they could use [if so, it's not deadlock free]

If one thread were blocked for an arbitrary long time, could that stall other threads or impair system operation for an arbitrarily long time [if so, it's not non-blocking].

Is there some at-least-theoretically possible combination of thread scheduling which could cause all threads to repeatedly retry the same operations while invalidating each others' work, without anyone making progress [if so, it's not lock-free]

If some threads are given sufficiently CPU time relative to another, could they force the latter thread to keep retrying its operations indefinitely [if so, it's not wait-free].

Much of the significance of lock-free algorithms isn't that they're faster than non-lock-free algorithms, but rather the fact that they aren't prone to dying if a thread gets waylaid [note that such a guarantee merely requires that algorithms be non-blocking, but all lock-free algorithms are].  It's possible for a lock-free algorithm to use locks, but only if lock-acquisition attempts include timeouts along with algorithms to ensure that it will always be possible for someone to make progress (for example, an algorithm could use a CompareExchange loop as its primary arbitration method, but use locks to arbitrate access when contention seems high; if a lock seems to be held for excessively long, other threads could decide to abandon efforts to use that lock and instead create a new one.  Note that because consistency is ensured via CompareExchange, having customers abandon the lock wouldn't jeopardize system consistency, though it may mean that code which had been holding the old lock won't get any work done until it too abandons the old lock and gets in line for the new one.

ContentLicense: CC BY-SA 3.0


问:
Is there any way to get faster app reviews?
I am trying to build a business around an iPhone app. The app will be our main sales channel, and being able to adapt the sales channel faster than the 9-10 days delay cause by the app review times is crucial. Therefore, I was wondering whether there is anything I can do to improve the speed of reviews. I am thinking that the publishers of Angry Birds, surely would not have to wait in line for reviews on the same terms as some obscure free app. So what can I do? Some things I am considering:

Would Apple prioritize apps that they earn money on?

Could I in some way pay Apple directly?

I already know of the possibility of requesting an expedite review, but it seems like one can get punished for supplying a non-technical reason.

答:
Don't know what you app is, but have you considered/would a data driven model work for you - the app would not need to change and the data can be downloaded of servers you provide and manage. Maybe a (yet another) DSL would be of use. </p>

<p>Another alternate is how locked into Apple are you? Build you business on Android - then you have the choice to use a store/deployment model that does not have this limitation. If you are starting out, there are as many Droid devices as there are Apple now days. If (when) you succeed, you will need to support "the other one", and possibly a third anyway, Is there really any need to start up with a handicap from day 1. </p>

Body:
Don't know what you app is, but have you considered/would a data driven model work for you - the app would not need to change and the data can be downloaded of servers you provide and manage. Maybe a (yet another) DSL would be of use.

Another alternate is how locked into Apple are you? Build you business on Android - then you have the choice to use a store/deployment model that does not have this limitation. If you are starting out, there are as many Droid devices as there are Apple now days. If (when) you succeed, you will need to support "the other one", and possibly a third anyway, Is there really any need to start up with a handicap from day 1.


问:
Why SQL is not so widespread in large desktop applications?
As a software developer, I've worked on projects ranging from tiny home-made apps to medium-size enterprise applications. In nearly every project I used a database or regretted choosing not to use it from the beginning.

Now, I am wondering a few things about the databases and their usage in general applications:

Why Windows itself doesn't use any "central" SQL database? For example:

Errors Reporting data is stored in a bunch of files,

Windows Update stores everything in flat files,

Icons cache is stored in a very strange single file which doesn't seem to be accessed through SQL, etc.

Why so many large applications avoid using databases? For example, wouldn't Microsoft Outlook gain by using a real database instead of reinventing the wheel by having its own format for .pst files and storing some data in registry?

If database adds an additional layer of an overall complexity and a tiny performance loss, it is a price of a huge advantage of making the code simpler in most circumstances, especially when it comes to the storage of small organized chunks of data instead of large binary streams. So why so few products are actually using databases? Probably the only application I know which actually uses Sqlite database is Firefox, and maybe Microsoft Exchange (but the last one is not a desktop application)?

Also, wouldn't a set of applications, like Microsoft Office or Microsoft Expression, benefit from having an unified SQL database, making it easier to deploy the applications, to update/upgrade the data, to share data between those applications, to make backups, etc.?

答:
Databases offer flexibility and like every feature there is almost certainly a cost. If a flat-file will work, then you can assume no one is going to need to query the data in unanticipated ways like in an ad hoc report.

Databases also do a good job of handling multiple connections/inputs. Again, if this isn't a requirement for your desktop app, why add the additional complexity? Other than through the user interface/the actual installation of Outlook itself, how many other applications or users are trying to write to the Outlook file on your computer?

It would be easier if all data were in a relational database from a "I want to be able to query all data any way I see fit with a single language like SQL" perspective, but this is rarely a priority with many applications.

Most programmers will look at it from:

I know what the app is suppose to do,
this is all it is suppose to do

my app is the only entitiy that will
ever access and/or manipulate these
data

a simple file structure of my own
design will work

for at least one application I'd like
to avoid relying on other people's
code and have complete control.

ContentLicense: CC BY-SA 2.5


问:
Call a script over the network
I have a Python script on a box that I want to call from a Java server, over the network. I know that I can start a server on the Python side and then connect to it from the Java site, but I am trying to see if there is a way to avoid the overhead of running a server on the Python side. Is there any other way of doing it?</p>

答:
Well, put simply, without a server, the Python side won't be able to receive incoming network messages. (Or, put differently, if the Python side is able to receive network messages, then there must be a server involved.)

There are a few options you have here.

Incorporate a simple custom server into the Python application. This server can be something you write yourself, based on network sockets and your own custom protocol. It takes some work, but you can tailor the protocol to your exact needs and leave out all the overhead that comes with more generic protocols, which is why I would only choose this route if performance is critical and network overhead is going to be an important factor. If the Python server is connected to the (public) internet, firewall it to prevent access to your custom server from the outside. Also, because your application will be long-running, you need to make sure you have good error handling, so that it can recover whenever anything goes wrong. Wrap it in a shell script loop (run server - sleep - repeat) if you want to be sure.

Incorporate an HTTP server into the Python application. There are a few libraries you can use for this, so the programming and testing overhead is going to be much less than for the custom protocol. Since it's HTTP though, you'll have a bit more overhead, and you'll be bound to the request/response paradigm, which is probably fine considering that the Java server initiates the connection. Just like the custom protocol, this solution needs protection - either firewall it, or have it listen on localhost only and put it behind a reverse proxy.

Implement the CGI protocol and run behind a "real" web server. CGI is really easy to implement, but you'll need a web server to drive it. Also, because CGI restarts your program for each request, you'll have to design it to avoid long startup times. On the upside, you won't have to fiddle with HTTP libraries, network sockets, and worry about many of the related security issues - just keep the host web server secure and don't do anything stupid inside your CGI, and you'll be fine.

Use ssh. This requires absolutely no extra effort on the Python part, and probably (I'm not a Java expert, so I don't really know) not much effort on the Java side either; you will have to create and set up a suitable ssh key on the Java side though, and give it access on the Python side. You have to make it an ssh key without a passphrase, because otherwise the server won't be able to use it without human intervention; this in turn means you probably want a dedicated user for just this purpose on the Python side, and lock that user down to the absolute bare requirements.

Use some sort of message-queue library. I've used ZeroMQ in the past, which is available for all popular programming languages, but there are others. You'll still be implementing a custom protocol, but the transport part of it is handled for you, quite efficiently at that. This approach is especially suitable when you need reliable and efficient communication channels, and can't afford restarting your script for each request. Here again, you need to catch any and all crashes to make sure it recovers.

Communicate through a shared persistent storage device. This can be a database, a shared filesystem, memcache, or maybe a server that exposes some sort of persistent storage API. This requires polling on the Python part, so it might not be the most efficient solution, plus you need to look out for race conditions and other timing-related problems. It is a great solution though if you have large quantities of data to process per message, and (provided your processing is designed to be atomic) it will survive close to every conceivable crash scenario without data loss.

A completely orthogonal choice is what your (message-level) API is going to look like. For the SSH case, the matter is already clear - you're just going to pass some command-line options to your script, not much choice there. For the rest, however, your message body can use whatever format you like - JSON, XML, plain text, SOAP, you name it. Which one makes the most sense depends on the kind of data you need to feed your script.

Title: Call a script over the network


问:
Should I be looking for developers with specific skill sets or generalists that need to learn?
Thanks to the great help of this site and SO, I've been able to make a prototype of a software I want to sell but unfortunately although the prototype works I think my code quality is very low. I didn't use much OOP or design patterns so although my code is understandable to me, I think a normal developer would faint if they had to read it.

So I wanted to hire a developer to make it a bit more better quality and improve some of my implementations of API's that I may have not done correctly.   I'm having problems hiring a developer though.

I have met 2 developers and had them read my software specs.The problem is, they lacked my business's domain knowledge(which is completely understandable and no biggie) but they also lacked knowledge of the underlying tech systems I used such as Hadoop, Hbase, Cuda, etc..I spent alot of time explaining map/reduce, bigtables and other technologies I used. I thought it was common knowledge because of my interactions with people on this site but the people I met with mentioned they never had to deal with these things so they didn't know it.

My question is, for software projects that are hiring contractor developers is it a danger if the developer does not have experience with the underlying technologies? or can a general developer who is accomplished in another area realistically pick up new technologies?  I did a very very quick back of envelope calculation and I think the upfront costs would be similar if I hire a student or developer with no experience in my technologies who will work many hours versus hiring a highly experienced developer who charges double but finishes in half the time but what other risks should I be considering or worried about?  Also, should if I do hire a generalist, should I be paying for the time it takes them to learn hadoop or cuda if they are contractors(seems to make business sense but not sure how fair it is to them if they do not use the skill again).

I'm a bit confused so any suggestions would be great.

答:
is it a danger if the developer does not have experience with the
  underlying technologies? or can a general developer who is
  accomplished in another area realistically pick up new technologies?

A developer can pick up technologies (and they will, eventually) but I don't think that meets your requirement.

You have working software, but you want it reviewed, refactored, and perhaps even rewritten. You really need an expert or at least someone experienced in a couple of your technologies to be able to do that, because although there are such things as software patterns, implementations vary between platforms and frameworks due to the uniqueness of the platform and framework.

You'd solved the business problems and mastered the domain, and you've implemented the software. You are now after technical guidance to allow your application to scale and live a long and healthy life. You want someone who has done this in a similar system, or using similar technology.

Different platforms often require completely different mindsets and experience. I'd guess you are working on a big data / parallel computing type project?  A web developer or an integration developer should be able to rewrite your prototype and have it work as well, but why assume they could do so any better than you?

Don't hold out for the perfect person, because they might not exist, but your developer should be familiar with at least some of the technologies and concepts you're using, or, as they say in job advertisements, demonstrate the ability to quickly learn new technologies and concepts.  If they haven't heard of Hadoop or MapReduce then the alarm bells should be going off - big time.


问:
Is a "model" branch a common practice?
I just thought it could be a good thing to have a dedicated version control branch for all database schema changes and I wanted to know if anyone else is doing the same and what have the results been.

Say that you are working with:

Schema model/documentation (some file where you model the database visually to generate the schema source, say MySQL Workbench, with a .mwb file, which is binary)

Schema source (a .sql file)

Schema-based code generation

The normal way we were working was with feature branches, so we would do changes to the model files (the database specific ones), and then have to regenerate points 2 and 3, dealing with the possible conflicts (or even code rewriting).

Now say that your workflow goes the same way as the previous item numbering. With a model branch you wouldn't have to reconcile the schema model with binaries in other feature branches, or have to regenerate schema source and regenerate code (which might have human code on top of it).

It makes so much sense to me it feels weird not having seen this earlier as a common practice.

Edit: I'm counting on branch merges to be the assertions for the model matching the code. I use a DVCS, so I don't fear long-lived branches or scary-looking merges. I'm also doing feature branching.

答:
I would advise against it. Database schemata change together with other related code or resources. To be able to track changes properly, you need to make cohesive changes link to each other, and a shared commit is the best way to go about it.

Consider your suggestion of keeping the schema under a separate branch. First off, you keep branches so you can push changes independently of other unrelated changes. What happens if you push schema commits without the corresponding code?

You create commit history that appears "out of the blue". It's hard to follow where it came from or why, after a while.

If you only commit schema, remember that others can do it as well. That means that others can pull and then rewrite/change your schema changes and still pass all of their tests (because they're not testing your code). Then, when you want to commit your code you get conflicts, which may have otherwise been avoided.

There may be other drawbacks, or even benefits. But these 2 right here are enough of a reason for me not to take this approach.

Hope that helps.

Title: Is a "model" branch a common practice?


答:
I accidentally discovered a way, sort of... I recently updated one of my apps to use the new iOS 6 mapping features (it's a transit routing app) and the review was completed from submission to App Store in just over 24 hours. On the other hand, another unrelated app update has been waiting for a week with no action.

It makes sense that Apple would prioritise apps that take advantage of new OS features, but I was surprised by how much faster it was.

Title: Is there any way to get faster app reviews?

Body:
I am trying to build a business around an iPhone app. The app will be our main sales channel, and being able to adapt the sales channel faster than the 9-10 days delay cause by the app review times is crucial. Therefore, I was wondering whether there is anything I can do to improve the speed of reviews. I am thinking that the publishers of Angry Birds, surely would not have to wait in line for reviews on the same terms as some obscure free app. So what can I do? Some things I am considering:

Would Apple prioritize apps that they earn money on?

Could I in some way pay Apple directly?

I already know of the possibility of requesting an expedite review, but it seems like one can get punished for supplying a non-technical reason.


问:
What is the wireframe of a project?
What is the actual meaning of a wireframe of a project?</p>

答:
A wireframe is a very simple visual representation of a project's layout design, that is used to quickly communicate the basic aspects of the project. It's commonly used in web development, but as a technique has been adopted in other domains as well.

On a very similar question on User Experience Stack Exchange, DA01, the author of the top voted answer notes:

That said, a wireframe is a sketch to communicate the idea/concept. The term comes from 3D modeling where the wireframe is the basic primitives of the object to give a sense of form and scale without committing to a fully rendered model.

In the context of web sites, wireframes serve various purposed depending on the context of the project. These can include:

site flow (typically done with flow charts)

interactions (not always easy to document in a wireframe, but its common)

general content structure

general page layout

Here are a couple of examples of wireframes, early snapshots of Stack Exchange's Area51:

Andreas Wulf's Wireframes: A Great Way to Start Development Projects article on InfoQ gives a quick overview of who's using wireframes:

Who Uses Wireframes?

Wireframes make an effective communication tool from which everyone involved in the development process can benefit:

CLIENTS - get a better understanding of what is going to be developed and can judge if the solution adequately addresses their needs. They can see if something is missing in the user interface, what actions are available, and how the interface elements are put together. Quite often, showing a wireframe to a business stakeholder brings up important aspects not considered before. This is a good thing because fixing issues in the wireframing stage is much easier and cheaper than fixing them later, when they are set in code.

PROJECT MANAGERS - use wireframes to ensure that all stakeholders are on the same page and agree on what is going to be built. As the project progresses they can use the wireframes as checklists to keep track of the progress and verify that everything important has been considered and implemented.

DESIGNERS - can rely on wireframes as blueprints for the visual design of the user interface. Wireframes provide them with the skeletal structure which they can turn into pixel-perfect mockups with colors, fonts, and other design elements.

DEVELOPERS - make use of wireframes to get an understanding of the solution’s functionality and technical requirements. A bunch of wireframes put together in a storyboard can be helpful to developers in determining how a series of user interactions should work together.

Further reading:

Wireframe questions on User Experience Stack Exchange,

The Benefits of Wireframing a Design.

Title: What is the wireframe of a project?


问:
Is there any kind of established architecture for browser based games?
I am beginning the development of a broser based game in which players take certain actions at any point in time.
Big parts of gameplay will be happening in real life and just have to be entered into the system.

I believe a good kind of comparison might be a platform for managing fantasy football, although I have virtually no experience playing that, so please correct me if I am mistaken here.

The point is that some events happen in the program (i.e. on the server, out of reach for the players) like pulling new results from some datasource, starting of a new round by a game master and such.

Other events happen in real life (two players closing a deal on the transfer of some team member or whatnot - again: have never played fantasy football) and have to be entered into the system.

The first part is pretty easy since the game masters will be "staff" and thus can be trusted to a certain degree to not mess with the system. But the second part bothers me quite a lot, especially since the actions may involve multiple steps and interactions with different players, like registering a deal with the system that then has to be approved by the other party or denied and passed on to a game master to decide.

I would of course like to separate the game logic as far as possible from the presentation and basic form validation but am unsure how to do this in a clean fashion.

Of course I could (and will) put some effort into making my own architectural decisions and prototype different ideas. But I am bound to make some stupid mistakes at some point, so I would like to avoid some of that by getting a little "book smart" beforehand.

So the question is:

Is there any kind of architectural works that I can read up on?

Papers, blogs, maybe design documents or even source code?
Writing this down this seems more like a business application with business rules, workflows and such... Any good entry points for that?

EDIT:

After reading the first answers I am under the impression of having made a mistake when including the "MMO" part into the title.
The game will not be all fancy (i.e. 3D or such) on the client side and the logic will completely exist on the server. That is, apart from basic form validation for the user which will also be mirrored on the server side.
So the target toolset will be HTML5, JavaScript, probably JQuery(UI).
My question is more related to the software architecture/design of a system that enforces certain rules.

Separation of ruleset and presentation

One problem I am having is that I want to separate the game rules from the presentation.

The first step would be to make an own module for the game "engine" that only exposes an interface that allows all actions to be taken in a clean way.

If an action fails with regard to some pre/post condition, the engine throws an exception which is then presented to the user like "you cannot sell something you do not own" or "after that you would end up in a situation which is not a valid game state."

The problem here is that I would like to be able to not even present invalid action in the first place or grey out the corresponding UI elements.

Changing and tweaking the ruleset

Another big thing is the ruleset.
It will probably evolve over time and most definitely must be tweaked.
What's more, it should be possible (to a certain extent) to build a ruleset that fits a specific game round, i.e. choosing different kinds of behaviours in different aspects of the game. This would do something like "we play it with extension A today but we throw out extension B."

For me, this screams "Architectural/Design pattern" but I have no idea on who might have published on something like this, not even what to google for.

答:
EDIT:  Your update to the question clarifies a lot of things, and changes the direction of the question quite a bit (at least from my perspective).

The problem here is that I would like to be able to not even present invalid action in the first place or grey out the corresponding UI elements.

The problem seems to be that not only would you like to achieve this, but you'd like to achieve it in some completely generic way, which allows you to vary the rule engine behind the scenes dynamically.  The latter is the really difficult part, and I'm not sure you're going to find a complete solution readily available for your exact needs.

If we take a step back, the "traditional" way of doing this would be something along the lines of the following (let's use a Model-View-Controller architecture, it's probably a good fit for your game):

The model represents the logic of your game, and is responsible for creating a structure which contains all the information that your presentation layer (the view) needs to do its job (preferably without any additional logic in the view).  In practical terms, this means it will figure out exactly what actions are available to the player, which items are "sellable", etc.

The view would be in charge of how this information is presented to the user. Typically, the view is either a server-side template (which results in actual HTML being generated), or a client-side template or other javascript code which results some HTML being updated on the client side (in the latter case, the model is typically sent to the browser as AJAX).

The controller's job is simply to take incoming requests and to route the request to the relevant model, and send this result to the relevant view.

So essentially, if you've designed everything cleverly, the basic MVC pattern already gives a nice separation of the presentation from the logic.  What you need to really figure out how to structure your model so that the view can remain relatively void of logic, and generic.  Some things are easy (e.g. this list of items can be sold by the player) and some things are hard (here's a list of generic actions - if the player chooses action A, they need to select an item worth X to trade, and a player from their friends list).  By carefully considering the axes along which you wish to remain flexible, you can come up with the correct architecture, however.

Changing and tweaking the ruleset

Assuming that the different rule-sets still fit into the same presentation strategy, varying the rule-set will be "relatively easy" to do.  It's difficult to say more without knowing your exact game ideas, but you could have hooks in your core game rules for various modifications to apply their changes, etc.  If you are looking for something more generic than that, consider reading up on rule engines, or even building your own domain specific language, which you can then translate into rules at runtime.

Original bit about MMOs:

Yannis' links go into some detail regarding MMO architectures.  It might not be referring to browser-based games, but much of it is still applicable.  A few things I would like to point out:

You seem to be alluding to having much of the game run purely on the client-side.  Here's the problem with that:  the client cannot be trusted.  It's an old rule of thumb for any kind of development, and it applies to games too.  It is trivial to mess with javascript code, and there are no purely client-side defenses for that.  If this is a concern for you (say, your players' enjoyment or money is at stake), you have to do some work on the server side.  Here's an example discussion over at gamedev (coincidentally, that site might be better suited to this question), where the advice is "Client-side movement handled immediately and then verified by the server is a great method when combined with server proxies with interpolated moves".  Essentially, you want the server to know quite a lot about what's going on in the client, enough to be able to call foul if someone is tampering with the client.  This is the approach used by most realtime multiplayer games (Battlefield, etc) - obviously you can't just trust the client to say "hey, I shot that guy, no, really", you need the server to be able to check that it's at least plausible.  We're basically talking about mirroring the client logic and data on the server side.

This is obviously not the easiest thing to achieve, and will probably slow down your development.  My advice would be to figure out exactly why you'd like this game to be heavily client-side (cost, user experience, etc), and to consider moving most of the functionality into the server-side.  If you do this, your game becomes very similar to a tradition web application, where you just validate all user inputs and run the logic on the server-side.  Many current browser "MMOs" actually use this approach, the good ones just happen to do it slick enough that you don't notice.

Note:  I put MMO in quotes at the end, because if games like Evony are MMOs, then Gmail is one, too.


问:
Is it the job of a developer to suggest IT requirements?
I am the only developer working on a web application which is nearing to its end. Now we are looking into making it Live in maybe a couple of months time.

This is a web application for a non IT company. Though they have their own internal IT team, they have asked me on what will be the hardware requirements for the live servers eg. RAM, 32 bit or 64 bit.

Shouldn't the internal IT team be doing this or since I am the only person working on the project is it my resposiblity to let them know of the any specific hardware requirements which may impact the performance of the project?

The reason I am asking this question is that, I have not done this before. All the times I used to be given a server and asked to deploy apps on it. I never used to worry about the server configuration, etc.

答:
Would depend on a few details. But in general, they can expect at least that you give them some minimum requirements since you should have a better knowledge about the technology you used for the project. You would know what database is used, if you used some additional indexer for full text search, which would maybe require more memory or would make use of additional cores.

On the other side they maybe have some additional knowledge too, like what kind of load to expect, how many customers may access the site and so on.

I would simply try to get in direct contact with the IT team and bring in the knowledge from both sides.


问:
Verfication vs validation again, does testing belong to verification? If so, which?
I have asked before and created a lot of controversy so I tried to collect some data and ask similar question again. E.g. V&V where all testing is only validation: http://www.buzzle.com/editorials/4-5-2005-68117.asp
According to ISO 12207, testing is done in validation:

•Prepare Test Requirements,Cases and Specifications

•Conduct the Tests

In verification, it mentiones.

The code implements proper event sequence, consistent interfaces,
  correct data and control flow, completeness, appropriate allocation
  timing and sizing budgets, and error definition, isolation, and
  recovery. and The software components and units of each software item
  have been completely and correctly integrated into the software item

Not sure how to verify without testing but it is not there as a technique.

From IEEE:

Verification: The process of evaluating software to determine whether
  the products of a given development phase satisfy the conditions
  imposed at the start of that phase. [IEEE-STD-610].

  Validation: The
  process of evaluating software during or at the end of the development
  process to determine whether it satisfies specified requirements.
  [IEEE-STD-610]

At the end of development phase? That would mean UAT..

So the question is, what testing (unit, integration, system, uat) will be considered verification or validation? I do not understand why some say dynamic verification is testing, while others that only validation.

An example: I am testing an application. System requirements say there are two fields with max. lenght of 64 characters and Save button. Use case say: User will fill in first and last name and save.
When checking the fields and Save button presence, I would say its verification. When I follow the use case, its validation. So its both together, done on the system as a whole.

答:
Validation ensures that the product actually meets the user's needs, and that the specifications were correct in the first place, while verification is ensuring that the product has been built according to the requirements and design specifications.

what testing (unit, integration, system, uat) will be considered verification or validation?

Unit, Integration, and System testing are verification. UAT is validation.


答:
Though they have their own internal IT team, they have asked me on
  what will be the hardware requirements for the live servers eg. RAM,
  32 bit or 64 bit.

Perhaps they figure that as the developer, you have more insight into the app's requirements than they do. You've presumably been running the application and know how much memory it requires under different loads.

From the IT department's point of view, they're happy to supply whatever your application needs. They could probably figure out what the application requires through trial and error, or they could ask the one guy in the company who's likely to have some insight into the application's behavior for his opinion.

It's not uncommon for developers to be asked to do things that aren't strictly in their job description. You might have to write some documentation, even though there's a technical writer on staff. You might need to participate in the testing process even though there's a QA department. Or you might be asked to help write a proposal even though there's a business analyst on the project. This is normal -- you're part of a team, and your main concern should be helping the team succeed. It's also good for you since it expands your experience and helps you understand what the other team members do, and it's good for the company since it spreads knowledge around.

Title: Is it the job of a developer to suggest IT requirements?

Body:
I am the only developer working on a web application which is nearing to its end. Now we are looking into making it Live in maybe a couple of months time.

This is a web application for a non IT company. Though they have their own internal IT team, they have asked me on what will be the hardware requirements for the live servers eg. RAM, 32 bit or 64 bit.

Shouldn't the internal IT team be doing this or since I am the only person working on the project is it my resposiblity to let them know of the any specific hardware requirements which may impact the performance of the project?

The reason I am asking this question is that, I have not done this before. All the times I used to be given a server and asked to deploy apps on it. I never used to worry about the server configuration, etc.


问:
About anonymous objects
In Java particularly Android development, is there any difference between declaring an object like

```<code>SomeObject object = new SomeObject();
someField.setObject(object);
</code>```

compared to an anonymous object (not sure if that's what is called)

```<code>someField.setObject(new SomeObject());
</code>```

performance wise? Or improvements in memory. Thanks.

答:
The code new SomeObject() that you write is identical, and it will create identical byte code in both cases, so no, there is no difference with respect to the object creation.

Your examples differ only in what you do with the object: either assigning it to a local variable, or passing it as an argument to a function (which may then assign it to a local variable or a field). The only difference in performance can come from this distinction; e.g. an object stored only in a local variable can get garbage-collected once the scope ends, while an object passed outside the current scope may live longer, perhaps much longer. But that has nothing to do with object creation; it is equally true for old and new objects in your program. Therefore, whether to use temporary variables or nested invocations in your code is largely a matter of readability (which should be more important than optimization anyway, even if there was a difference).)

Title: About anonymous objects


答:
I was wondering whether there is anything I can do to improve the speed of reviews.

You can request an expedited review, but you should only do that when there's a legitimate reason that you need to get your app out there ASAP, such as a glaring security bug. Otherwise, just allow time for the review process in your schedule.

being able to adapt the sales channel faster than the 9-10 days delay cause by the app review times is crucial.

The best way to deal with the issue is to design your app so that you don't need to update the app itself in order to adjust your sales channel. Anticipate the ways you might want to change the app and build all the required behaviors into your app. Then use data files to tell the app how to behave.

A simple example: instead of hard coding your product and price list into the app, put that information in a data file. Have the app download the latest file when it launches for the first time, and check for updates periodically.

A more complex example: An app that collects data from users might have the user fill out various forms. The content of each form can be specified by a data file, and the form built on the fly. Forms can be updated and new forms added just by downloading new data files.

You might even consider building a hybrid app using a tool like PhoneGap, where you specify both the UI and the behavior of your app using HTML and Javascript.

When you do update your app, you can take some steps to at least not prolong the review process:

Make sure that you understand and follow the review guidelines. The guidelines are mostly common sense, and if your app clearly works within the guidelines and doesn't try to push the envelope it'll be that much easier for a reviewer to approve it.

Make sure that your app works. If your app is buggy, or if it looks buggy, it'll be harder to get it approved quickly.

Explain clearly what you've changed in the new version that you're submitting. You can write a note to the reviewer if there's anything special they need to know, and you should also make changes clear in the description that's displayed in the app store.

Anticipate busy times for the reviewers and either submit early or plan for a longer than usual review. For example, update your app early when a new iOS version is available so that you can build against the GM and submit as soon as Apple starts accepting updates for that version.


答:
I'd recommend to put all kinds of sourcecode together that builds up a running system (inlcuding database-queries and -schemas)

Why? Because, then you always have a relation between your code and the rest of the things that build your system (configuration, SQL, Readmes, Tests, ...). If you make a change, you get certainly reminded to change those other artifacts, too.
If you have different branches, or even different repositories, it is much harder to remember which revision of branch A belongs to what revision of branch B, though leading to mistakes.

We used to work with release-branches, once. For that purpose, all developer agreed to a common procedure:

fix a bug in the release-branch

create a patch/diff

apply the diff to the main branch

This is not very nice, because you duplicate changes that could have been merged. But it is an easy approach, every developer can handle, and SVN/CVS-merge sometimes is a pain in the a.

Title: Is a "model" branch a common practice?

Body:
I just thought it could be a good thing to have a dedicated version control branch for all database schema changes and I wanted to know if anyone else is doing the same and what have the results been.

Say that you are working with:

Schema model/documentation (some file where you model the database visually to generate the schema source, say MySQL Workbench, with a .mwb file, which is binary)

Schema source (a .sql file)

Schema-based code generation

The normal way we were working was with feature branches, so we would do changes to the model files (the database specific ones), and then have to regenerate points 2 and 3, dealing with the possible conflicts (or even code rewriting).

Now say that your workflow goes the same way as the previous item numbering. With a model branch you wouldn't have to reconcile the schema model with binaries in other feature branches, or have to regenerate schema source and regenerate code (which might have human code on top of it).

It makes so much sense to me it feels weird not having seen this earlier as a common practice.

Edit: I'm counting on branch merges to be the assertions for the model matching the code. I use a DVCS, so I don't fear long-lived branches or scary-looking merges. I'm also doing feature branching.


问:
The 10 minutes technical interview
I must do a quick assessment of dozens of fresh students very quickly. I have 30 minutes meeting with each of them (in two or three days). I want to use most of the time to discuss non technical aspects. So I plan to use 10 minutes for technical questions. The same questions for all of them.

They are all hired already (they are students), what I need to know is the average level in order to prepare a training.

Ideally, the difficulty must be progressive in order to set a level for each. Level I will average, and I'll do an average on each question too.

If you had only 10 minutes and 10 questions to ask to a candidate, what would be your top 10 ?

答:
Ask them the FizzBuzz question

Did they know how to code it? What language did they use? Why did they code it the way they did? Did they use Recursion? Loops? Other Methods/Functions? Pointers?

You could also use the question as a base for other questions (i.e. Why did/didn't you use Recursion? How would you write this using pointers?)

It doesn't encompass everything, but it might give you an idea of their coding skills

Title: The 10 minutes technical interview


问:
Passing variables from PHP to C++
I need to call a program from PHP and pass some vars and/or sets of key-value pairs to it. How do I pass these vars, through arguments to the called function?

exec("/path/to/program flag1 flag2 [key1=A,key2=B]");

Or is there a better method to achieve this? Somebody suggested to me to write them into a txt file and pass the path to it to as an argument instead,

exec("/path/to/program path_to_txt_file);

but I’m not to excited about this method.

答:
There are several ways that come to mind: doing Inter-Process Communication, building a C++ PHP extension/dll, or directly using the CLI.

You can have your PHP scripts take in shell parameters as you are suggesting (see https://stackoverflow.com/questions/6763997/shell-run-execute-php-script-with-parameters). You can evolve this to passing a single argument in the form of a query string, taking $argv[0] and set it to $_GET or $_POST, or whatever you prefer. Test it with something like:

```<code><?php

parse_str($argv[0], $_POST);
</code>```

Finally, for a more "correct" solution (using socket based communication), you might want to take a look at Thrift. See https://stackoverflow.com/questions/1746207/how-to-ipc-between-php-clients-and-a-c-daemon-server

Title: Passing variables from PHP to C++

Body:
There are several ways that come to mind: doing Inter-Process Communication, building a C++ PHP extension/dll, or directly using the CLI.

You can have your PHP scripts take in shell parameters as you are suggesting (see https://stackoverflow.com/questions/6763997/shell-run-execute-php-script-with-parameters). You can evolve this to passing a single argument in the form of a query string, taking $argv[0] and set it to $_GET or $_POST, or whatever you prefer. Test it with something like:

<?php

parse_str($argv[0], $_POST);

Finally, for a more "correct" solution (using socket based communication), you might want to take a look at Thrift. See https://stackoverflow.com/questions/1746207/how-to-ipc-between-php-clients-and-a-c-daemon-server


问:
Why are Python strings allocated on the stack?
According to this Python code visualizer, Python strings are allocated on the stack and not on the heap.

Why is this? I thought they would be similar to Java where Strings are allocated on the heap.

答:
Has Greg said in his answer, strings are allocated on the heap.

The visualizer has choosen to display some objects in the "frame" part, which seems wrong to me. Fortunately, it has little impact for someone learning python, since affected objects (int, string) are immutable. So reasoning about effects is still possible.

However it gives the false impression that strings are duplicated in memory when you do things like:

```<code>x = "hello"
y = x
</code>```

Body:
Has Greg said in his answer, strings are allocated on the heap.

The visualizer has choosen to display some objects in the "frame" part, which seems wrong to me. Fortunately, it has little impact for someone learning python, since affected objects (int, string) are immutable. So reasoning about effects is still possible.

However it gives the false impression that strings are duplicated in memory when you do things like:

x = "hello"
y = x


答: You can echo out the variables in php and read the returned data from the HTTP request . After sending your request, you can probably use InternetQueryDataAvailable to get the number of bytes coming back, allocate a buffer large enough to accommodate the data, and use InternetReadFile to get the data into the buffer.

Title: Passing variables from PHP to C++

Body:
I need to call a program from PHP and pass some vars and/or sets of key-value pairs to it. How do I pass these vars, through arguments to the called function?

exec("/path/to/program flag1 flag2 [key1=A,key2=B]");

Or is there a better method to achieve this? Somebody suggested to me to write them into a txt file and pass the path to it to as an argument instead,

exec("/path/to/program path_to_txt_file);

but I’m not to excited about this method.


问:
Difference between a REPL and interactive shell
Noob question. I am not quite able to tell the difference between a REPL and an interactive shell just by reading the definitions on Wikipedia.

Wiki notes that REPL is a particular kind of interactive language shell. Is it a proper subset though? The Wiki definition seems to restrict the terminology REPL to Lisp-like languages, whereas the stated properties don't really contain any distinguishing features.

In particular, would it be correct to call IPython a REPL?

答:
This StackOverflow question discusses that very question (among other things).

I am personally on the fence as regards interactive Python. But, if you want to call it a REPL, I don't think anyone will be angry with you (there are slightly too many things that work in source code files, but not in the interactive shell for me to be entirely happy with calling it a REPL).


答:
REPL: This is a procedure that just loops,  accepts one command at a time, executing it, and printing the result.

The three steps at each iteration of the loop are:

Calling read to read the characters that make up a textual expression from the keyboard input buffer, and construct a data structure to represent it,

Calling eval to evaluate the expression--intuitively, eval "figures out what the expression means," and "does what it says to do," returning the value of the expression--and

Calling write to print a textual representation of the resulting from eval, so that the user can see it.

You can write your own read-eval-print loop for your own programs, so that users can type in expressions, and you can interpret them any way you want. You can start up your read-eval-print loop (by typing in (rep-loop)), and it will take over from the normal Scheme read-eval-print loop, interpreting expressions your way.

Here's a very simple read-eval-print loop:

```<code>  (define (rep-loop)
  (display "repl>")      ; print a prompt
  (write (eval (read)))  ; read expr., pass to eval, write result
  (rep-loop))            ; loop (tail-recursive call) to do it again
</code>```

Notice that the expression (write (eval (read))) does things in the proper read-eval-print order, because the argument to each procedure call is computed before the actual call.

Interactive Shell : An interactive shell reads commands from user input on a terminal. Among other things, such a shell reads startup files on activation, displays a prompt, and enables job control by default. The user can interact with the shell.That's how the interactive shell name came into being . Let us consider this bash script :

```<code>     #!/bin/bash
     echo -n "Enter the value of variable 'var1': "
     read var1
     echo "var1 = $var1"
     echo

    echo -n "Enter the values of variables 'var2' and 'var3' "
    echo =n "(separated by a space or tab): "
    read var2 var3
    echo "var2 = $var2      var3 = $var3"
    #  If you input only one value,
    #+ the other variable(s) will remain unset (null).

    exit 0
</code>```

Now the script above interacts with the user, it asks the user to enter inputs based on which it does its calculations. That's why it behaves like an interactive shell.

Similary, the python interpreter which most people use to learn python is an interactive one as it communicates with its user.

Title: Difference between a REPL and interactive shell

Body:
Noob question. I am not quite able to tell the difference between a REPL and an interactive shell just by reading the definitions on Wikipedia.

Wiki notes that REPL is a particular kind of interactive language shell. Is it a proper subset though? The Wiki definition seems to restrict the terminology REPL to Lisp-like languages, whereas the stated properties don't really contain any distinguishing features.

In particular, would it be correct to call IPython a REPL?

Body:
REPL: This is a procedure that just loops,  accepts one command at a time, executing it, and printing the result.

The three steps at each iteration of the loop are:

Calling read to read the characters that make up a textual expression from the keyboard input buffer, and construct a data structure to represent it,

Calling eval to evaluate the expression--intuitively, eval "figures out what the expression means," and "does what it says to do," returning the value of the expression--and

Calling write to print a textual representation of the resulting from eval, so that the user can see it.

You can write your own read-eval-print loop for your own programs, so that users can type in expressions, and you can interpret them any way you want. You can start up your read-eval-print loop (by typing in (rep-loop)), and it will take over from the normal Scheme read-eval-print loop, interpreting expressions your way.

Here's a very simple read-eval-print loop:

  (define (rep-loop)
  (display "repl>")      ; print a prompt
  (write (eval (read)))  ; read expr., pass to eval, write result
  (rep-loop))            ; loop (tail-recursive call) to do it again

Notice that the expression (write (eval (read))) does things in the proper read-eval-print order, because the argument to each procedure call is computed before the actual call.

Interactive Shell : An interactive shell reads commands from user input on a terminal. Among other things, such a shell reads startup files on activation, displays a prompt, and enables job control by default. The user can interact with the shell.That's how the interactive shell name came into being . Let us consider this bash script :

     #!/bin/bash
     echo -n "Enter the value of variable 'var1': "
     read var1
     echo "var1 = $var1"
     echo

    echo -n "Enter the values of variables 'var2' and 'var3' "
    echo =n "(separated by a space or tab): "
    read var2 var3
    echo "var2 = $var2      var3 = $var3"
    #  If you input only one value,
    #+ the other variable(s) will remain unset (null).

    exit 0

Now the script above interacts with the user, it asks the user to enter inputs based on which it does its calculations. That's why it behaves like an interactive shell.

Similary, the python interpreter which most people use to learn python is an interactive one as it communicates with its user.


答:
Technically, it's correct to say that a shell is an instance of a REPL.
However, it isn't a matter of program definition as it is one of common usage scenarios.

Bash, for example, is written in C, but it could well have been written in Python. At that point, if you talk about program features and abilities, would it be correct to say that Bash is a shell while Python isn't?

You could also say that Shells are about running commands while REPLs are about running instructions and function calls. But can't you run commands in REPLs (Python's os.system, os.popen, etc), and can't you run (or define) functions in Bash, using many of its built-ins?

As aforesaid, it's a matter of usage. If you juggle files and ready-made programs, you're using it as a shell. If you're testing libraries or language semantics, it's a REPL.

Hope that helps.


问:
ASP.NET Webforms developers and web designers: how to interact?
I'm an ASP.NET Webforms developer, and I face some problems when I deal with designers.

Designers always complain about the asp.net server controls. They'd rather just have an html file and create css files along with the required images to go with those. Sometimes, if the design phase is done in advance, I get html files with related css files, but then we face many problems integrating the design with the aspx files (sever controls an telerik controls ... etc).

What I want to ask about is:

How do I overcome these problems? The designers prefer php- and mvc developers because of the problems with .net server controls. I need to know how to interact with the designers in the correct way.

Are there any tools or applications to provide the designers with the rendered (html
page) of the .aspx pages? By that I mean the page in runtime rather than the aspx in Visual Studio. They do use Web Expression but they want the rendered page in html as well.

答:
Here is some useful approaches I have taken in the past with designers when they have to work on an ASP.NET WebForms project that is being developed.

Deploy Locally: Developers provide an intermediate version of the project deployed
locally. This saves time to both. The designer requests an .aspx but
interacts with the rendered HTML instead of with the server code.
This approach abstracts the server code from the designer. He
doesn't need to know how the HTML is generated or how the javscript
and css files are delivered to the client. This of course assumes
that the designers are skilled with browser debuggers/DOM inspector.
The designer can apply all of his css changes inside the browser
and afterwards apply them to the css files.

Provide Models: In order to make is more sensible for the designers to work with
HTML, provide them with a model of the HTML rendered by the server
control. They can tweak that HTML to the point where they like it
and propose the changes to be applied in the server-side
implementation. This needs to be done early and often, because you
don't want to end-up with an HTML structure which the client-side
implementation relies on and then for the designer to propose
changes on that structure.

The designers should in general have as little touch points with the server side code as possible, so abstract it away from them as much as you can.


答:
If I use locks, can my algorithm still be lock-free?

It could be, but it depends on the algorithm.

If I have a simple data structure such as a queue, protected by a lock, then one process can always make progress, as one process can acquire the lock, do what it wants, and release it.

So does it meet the definition of lock-free?

Note per se.

If the "do what it wants" step does not involve acquiring any other locks, and it is guaranteed to complete in a finite time, then this particular part of your algorithm will be deadlock free.

However, if those preconditions are not satisfied, there is at least the potential for deadlocks ...

Body:
A common definition of lock-free is that at least one process makes progress. 1

If I have a simple data structure such as a queue, protected by a lock, then one process can always make progress, as one process can acquire the lock, do what it wants, and release it.

So does it meet the definition of lock-free?

1 See eg M. Herlihy, V. Luchangco, and M. Moir. Obstruction-free synchronization: Double-ended queues as an example. In Distributed Computing, 2003. "It is lock-free if it ensures only that some thread always makes progress".


答:
is it my responsibly to let them know of the any specific hardware requirements which may impact the performance of the project?

It is responsibility of a product provider (your company, in this case) to define minimum requirements for the successful product operation. As a responsible person within your company; it might be tech-lead of the project (sounds like you) or your company CTO - which does not matter to your client.

However, there should be provided a minimal specification list to allow good operation of this product on a client machine and server.


问:
Using a GPL game engine
I am confused. I thought I would try and use a new game engine in order to expand my abilities, and found a nice engine called springrts. I was looking through the licensing info and it is licensed under the GPL 2 licence. If I remember correctly, does that mean that anything I make with it, I have to distribute the source code to?</p>

答:
Under the proprietary section they say this:

These games may or may not be free to play. Modifying their content
  (i.e. the art assets) is not allowed without the game authors explicit
  permission, although the code is GPL and some games (P.U.R.E.) include
  large GPL-friendly content collections.

From Spring Engine - Games.

So it's not the code that makes them different, and they are following the GPL.

Title: Using a GPL game engine


答:
So the question is, what testing (unit, integration, system, uat) will be considered verification or validation?

Generally, speaking on high level your example and explanation sounds good.

In your example: verification is about making sure that "there are two fields with max. length of 64 characters and Save button." If some elements are missing according to requirement, then it does not pass verification. It is also a first step.

"validation is" - more about input and behavior of given required elements. In your case, it is validation of max. and min. input length, special character allowance, and any other related business rules.

All this is done on unit testing first and propagated to next stages if there are some related business-data flow.

Title: Verfication vs validation again, does testing belong to verification? If so, which?

Body:
I have asked before and created a lot of controversy so I tried to collect some data and ask similar question again. E.g. V&V where all testing is only validation: http://www.buzzle.com/editorials/4-5-2005-68117.asp
According to ISO 12207, testing is done in validation:

•Prepare Test Requirements,Cases and Specifications

•Conduct the Tests

In verification, it mentiones.

The code implements proper event sequence, consistent interfaces,
  correct data and control flow, completeness, appropriate allocation
  timing and sizing budgets, and error definition, isolation, and
  recovery. and The software components and units of each software item
  have been completely and correctly integrated into the software item

Not sure how to verify without testing but it is not there as a technique.

From IEEE:

Verification: The process of evaluating software to determine whether
  the products of a given development phase satisfy the conditions
  imposed at the start of that phase. [IEEE-STD-610].

  Validation: The
  process of evaluating software during or at the end of the development
  process to determine whether it satisfies specified requirements.
  [IEEE-STD-610]

At the end of development phase? That would mean UAT..

So the question is, what testing (unit, integration, system, uat) will be considered verification or validation? I do not understand why some say dynamic verification is testing, while others that only validation.

An example: I am testing an application. System requirements say there are two fields with max. lenght of 64 characters and Save button. Use case say: User will fill in first and last name and save.
When checking the fields and Save button presence, I would say its verification. When I follow the use case, its validation. So its both together, done on the system as a whole.


问:
Is it ever ok to have an empty catch statement?
I thought about it and could not come up with an example. Why would somebody want to catch an exception and do nothing about it? Can you give an example? Maybe it is just something that should never be done.</p>

答:
If an exception is thrown by an operation that was optional anyway, there might be nothing to do.  It might not be useful to log it.  In that case, you may just want to catch it and do nothing.

If you're doing this, include a comment.  Always comment anything that looks like a bug (fallthrough in a switch statement, empty catch block, assignment in a condition).

You might argue that this isn't a proper use of exceptions, but that's for another question.


问:
Why is Zend Framework so complicated?
I am web developer and have experience of developing several web applications in PHP. I have an idea of developing a product for myself and decided to use a MVC based framework because I really like the idea of MVC and how one can easily manage and modify the application without any difficulty.

I chose Zend Framework and it seems more difficult than learning a new programming language. There are so many things going at one time even to run a small application.

Similarly the idea of routing is very complex as it is new for a core programmer. I know that the guys here read thousand of such questions like one I am asking but I am not looking to learn Zend Framework overnight. I am willing to give as much time as it needs but until now it's making no sense to me. There are thousand of classes in the Zend library, but how would a noob know where to use a specfic class and how to use it? I am still finding it very difficult to understand the bootstrap of Zend Framework and its mapping. I read the manual, follow it and things start working but I really don't exactly how they are actually happening.

I also still have no clue how models, views and controllers work together and how to plan an application in Zend Framework. When it comes to core php I exactly have the idea in my mind what to do and than easily translate them in code but in Zend Framework I don't know how to translate my idea.

答: At least the "quick start" thingy must be easier in order to make a framework friendly.....if you prefer something harder as a better thing then I would say "ZF is the best PHP framework", otherwise NOT. I've downloaded ZF-2 and tried it out (honestly I am newbie to ZF). Sad thing is that I still haven't found a solid "quick start guide" with a simple Project Skeleton on the internet. All I am looking for is simple way of including library files and creating a project folder with MVC features. I have used Codeigniter, Cake php, Yii but i found it pretty unfriendly. Yes i know Zend upgrades PHP but it doesn't mean that it's the best framework or whatever you'll say.</p>

Title: Why is Zend Framework so complicated?


问:
When not to use Spring to instantiate a bean?
I am trying to understand what would be the correct usage of Spring. Not syntactically, but in term of its purpose.
If one is using Spring, then should Spring code replace all bean instantiation code?
When to use or when not to use Spring, to instantiate a bean?

May be the following code sample will help in you understanding my dilemma:

```<code>List<ClassA> caList = new ArrayList<ClassA>();
for (String name : nameList) {
    ClassA ca = new ClassA();
    ca.setName(name);
    caList.add(ca);
}
</code>```

If I configure Spring it becomes something like:

```<code>List<ClassA> caList = new ArrayList<ClassA>();
for (String name : nameList) {
    ClassA ca = (ClassA)SomeContext.getBean(BeanLookupConstants.CLASS_A);
    ca.setName(name);
    caList.add(ca);
}
</code>```

I personally think using Spring here is an unnecessary overhead, because

The code the simpler to read/understand.

It isn't really a good place for Dependency Injection as I am not expecting that there will be multiple/varied implementation of ClassA, that I would like freedom to replace using Spring configuration at a later point in time.

Am I thinking correct? If not, where am I going wrong?

答:
I'd use Spring (or another DI system) between layers, direct instantiation within layers.

So a class that creates a bean that leaves the scope of that class, to some (functionally) external system, possibly defined by that system or some communications layer, would be created through DI. Another bean created purely for internal use within the application layer is created directly, for both code clarity and (in large systems just as important) performance reasons.


问:
If I use locks, can my algorithm still be lock-free?
A common definition of lock-free is that at least one process makes progress. 1

If I have a simple data structure such as a queue, protected by a lock, then one process can always make progress, as one process can acquire the lock, do what it wants, and release it.

So does it meet the definition of lock-free?

1 See eg M. Herlihy, V. Luchangco, and M. Moir. Obstruction-free synchronization: Double-ended queues as an example. In Distributed Computing, 2003. "It is lock-free if it ensures only that some thread always makes progress".

答:
You have to look at the "definition" you quote in context:

The traditional way to implement shared data structures is to use
  mutual exclusion (locks) to ensure that concurrent operations do not
  interfere with one another. Locking has a number of disadvantages with
  respect to software engineering,fault-tolerance, and scalability (see
  [8]). In response,researchers have investigated a variety of
  alternative synchronization techniques that do not employ mutual
  exclusion. A synchronization technique is wait-free if it ensures that
  every thread will continue to make progress in the face of arbitrary
  delay (or even failure) of other threads. It is lock-free if it
  ensures only that some thread always makes progress.

You're using locks for mutual exclusion, thus it's not a lock-free technique they are talking about.


问:
Do programmers need a good memory?
It seems that it's necessary to remember all sorts of syntax to be able to program. If a person doesn't have a good memory for remembering names, will it be more difficult to learn to program?</p>

答:
If you have difficulty remembering the names of people you meet, you could still become a great programmer.

I forget people's names all the time. I am a senior programmer with almost a decade of experience. In my case, my terrible auditory memory is compensated for by a great visual memory.

Even so, the essential requirement for a good programmer is the ability to abstract. No matter how much or how little you can remember, if you cannot understand the concept of a variable, and how to use it in a program, you won't become a good programmer.

My suggestion is that you try one short course in programming, or complete the Python tutorial to see how you like it.

That should give you a good idea about whether programming is a career you might be interested in pursuing.

ContentLicense: CC BY-SA 4.0

Title: Do programmers need a good memory?


答: You're right, Spring is inappropriate for the use case you listed.  Spring is better used for managing external dependencies (like plugging a JDBC connection into a DAO) or configurations (like specifying which database type to use).  In your example, if the bean type was liable to change, then you'd use an interface to specify the bean, and instantiate the beans using a Factory.  You'd use Spring to specify which factory to use, and inject that into the class that needed to instantiate the beans.  You could then have several different factories that created several different types of beans (that all supported the bean interface), and configure that appropriate one at installation (or update) time.</p>

Title: When not to use Spring to instantiate a bean?

Body:
I am trying to understand what would be the correct usage of Spring. Not syntactically, but in term of its purpose.
If one is using Spring, then should Spring code replace all bean instantiation code?
When to use or when not to use Spring, to instantiate a bean?

May be the following code sample will help in you understanding my dilemma:

```<code>List<ClassA> caList = new ArrayList<ClassA>();
for (String name : nameList) {
    ClassA ca = new ClassA();
    ca.setName(name);
    caList.add(ca);
}
</code>```

If I configure Spring it becomes something like:

```<code>List<ClassA> caList = new ArrayList<ClassA>();
for (String name : nameList) {
    ClassA ca = (ClassA)SomeContext.getBean(BeanLookupConstants.CLASS_A);
    ca.setName(name);
    caList.add(ca);
}
</code>```

I personally think using Spring here is an unnecessary overhead, because

The code the simpler to read/understand.

It isn't really a good place for Dependency Injection as I am not expecting that there will be multiple/varied implementation of ClassA, that I would like freedom to replace using Spring configuration at a later point in time.

Am I thinking correct? If not, where am I going wrong?


答:
The only time I've really needed to do something like this was with a logging class for a console app.  There was a top-level global catch handler which emitted the error to STDOUT, logged the error to a file, then closed the app with a >0 error code.

The problem here was that sometimes, the logging to the file failed.  Directory permissions stopped you from writing the file, the file was exclusively locked, whatever.  If that happened, I couldn't handle the exception in the same way I had elsewhere (catch, log the relevant details, wrap in a better exception type, etc) because logging the exception details caused the logger to go through the same actions (trying to write to a file) which had already failed.  When they failed again...  You see where I'm going.  It gets into an infinite loop.

If you drop some of the try {} blocks, you can end up with the exception appearing in a message box (not what you want for a silent config app).  So in that method which writes to the log file, I have an empty catch handler.  This doesn't bury the error since you still get the >0 error code, it just stops the infinite loop and allows the app to exit gracefully.

There's a comment of course, explaining why it's empty.

(I was going to post this earlier, I was just afraid of getting flamed into oblivion.  Since I'm not the only one, though...)

Title: Is it ever ok to have an empty catch statement?

Body: I thought about it and could not come up with an example. Why would somebody want to catch an exception and do nothing about it? Can you give an example? Maybe it is just something that should never be done.</p>


答:
If it is a bean, you should let Spring build it (except you can supply a factory bean — I've used that where I needed to return a specific subclass dependent on a system property — and you should consult the documentation on the @Configuration and @Bean annotations if you're doing that). If it isn't a bean, but rather just a Plain Old Java Object, you've no need to use Spring to make it at all. POJOs are useful, but won't get dependency injection, AOP wrappers, etc. as those are the things that Spring adds for you.

The fundamental decision is whether or not it is really a bean, or just some ordinary object that happens to follow some bean conventions (e.g., method naming). I can't guess which is really the case from the small example you gave.


问:
Are there any design patterns that are unnecessary in dynamic languages like Python?
I've started reading the design pattern book by the GoF. Some patterns seem very similar with only minor conceptual differences.

Do you think out of the many patterns some are unnecessary in a dynamic language like Python (e.g. because they are substituted by a dynamic feature)?

答:
I would say that patterns are always language dependent.
That most python patterns look like those defined in GoF it's because of the OOP of Python, that being said OOP is not like OOP (no two languages define objects and their manipulation 100% alike).

So there's no doubt some patterns will not be applicable "as is", some might make no sense and there are some patterns that might be only be meaningful to Python.

To get back exactly at your question: Patterns are only necessary if you need them. You don't have to use them if there's no need for them (as Jan Hudec already said).

Furthermore, there are much more patterns than those mentioned in GoF. See in wikipedia other patterns


答:
You might want to consider a client-server architecture.

Even if the client is a web application that connects through a web service to a server application that exists on the same hosting machine, it should allow for very efficient separation of game logic and presentation elements. This may be overkill depending on your requirements. MVC might do quite well enough.

So a normal user wants to propose a deal? The client application sends a request to the server adding a new proposed deal. The server might respond that the deal was proposed, or that it has already been proposed, or that our user was blocked by the user he was proposing the deal to. If you add a new restriction, like "the deal may only involve X gold", then the server need only return a new error response, instead of requiring a change on the client application.

Object oriented design should also help. Thinking in terms of what an object knows about itself, and what you can do to it, should help you clarify a game engine interface.

What does a deal need to know about itself? Who proposed it, who it was proposed to, and whether it has been accepted or not, and what the terms of the deal are. What can we do with the proposal? It can be canceled, accepted or rejected.

You should also consider the types of users in your system, and what they are able to do. Use cases will help you clarify what users need to be able to do, and which users should be limited in their actions, and how.

Who can do what with a deal? A user can propose a deal, cancel a deal he has proposed if it's not accepted or rejected yet, accept or reject a deal that was proposed to him. Can an administrator do anything about a deal? Probably not.

Essentially, figure out what your application should do, and why. Then start designing an architecture that fits it.

Title: Is there any kind of established architecture for browser based games?

Body:
I am beginning the development of a broser based game in which players take certain actions at any point in time.
Big parts of gameplay will be happening in real life and just have to be entered into the system.

I believe a good kind of comparison might be a platform for managing fantasy football, although I have virtually no experience playing that, so please correct me if I am mistaken here.

The point is that some events happen in the program (i.e. on the server, out of reach for the players) like pulling new results from some datasource, starting of a new round by a game master and such.

Other events happen in real life (two players closing a deal on the transfer of some team member or whatnot - again: have never played fantasy football) and have to be entered into the system.

The first part is pretty easy since the game masters will be "staff" and thus can be trusted to a certain degree to not mess with the system. But the second part bothers me quite a lot, especially since the actions may involve multiple steps and interactions with different players, like registering a deal with the system that then has to be approved by the other party or denied and passed on to a game master to decide.

I would of course like to separate the game logic as far as possible from the presentation and basic form validation but am unsure how to do this in a clean fashion.

Of course I could (and will) put some effort into making my own architectural decisions and prototype different ideas. But I am bound to make some stupid mistakes at some point, so I would like to avoid some of that by getting a little "book smart" beforehand.

So the question is:

Is there any kind of architectural works that I can read up on?

Papers, blogs, maybe design documents or even source code?
Writing this down this seems more like a business application with business rules, workflows and such... Any good entry points for that?

EDIT:

After reading the first answers I am under the impression of having made a mistake when including the "MMO" part into the title.
The game will not be all fancy (i.e. 3D or such) on the client side and the logic will completely exist on the server. That is, apart from basic form validation for the user which will also be mirrored on the server side.
So the target toolset will be HTML5, JavaScript, probably JQuery(UI).
My question is more related to the software architecture/design of a system that enforces certain rules.

Separation of ruleset and presentation

One problem I am having is that I want to separate the game rules from the presentation.

The first step would be to make an own module for the game "engine" that only exposes an interface that allows all actions to be taken in a clean way.

If an action fails with regard to some pre/post condition, the engine throws an exception which is then presented to the user like "you cannot sell something you do not own" or "after that you would end up in a situation which is not a valid game state."

The problem here is that I would like to be able to not even present invalid action in the first place or grey out the corresponding UI elements.

Changing and tweaking the ruleset

Another big thing is the ruleset.
It will probably evolve over time and most definitely must be tweaked.
What's more, it should be possible (to a certain extent) to build a ruleset that fits a specific game round, i.e. choosing different kinds of behaviours in different aspects of the game. This would do something like "we play it with extension A today but we throw out extension B."

For me, this screams "Architectural/Design pattern" but I have no idea on who might have published on something like this, not even what to google for.


问:
Why not commit unresolved changes?
In a traditional VCS, I can understand why you would not commit unresolved files because you could break the build.  However, I don't understand why you shouldn't commit unresolved files in a DVCS (some of them will actually prevent you from committing the files).

Instead, I think that your repository should be locked from pushing and pulling, but not committing.

Being able to commit during the merging process has several advantages (as I see it):

The actual merge changes are in history.

If the merge was very large, you could make periodic commits.

If you made a mistake, it would be much easier to roll back (without having to redo the entire merge).

The files could remain flagged as unresolved until they were marked as resolved.  This would prevent pushing/pulling.

You could also potentially have a set of changesets act as the merge instead of just a single one.  This would allow you to still use tools such as git rerere.

So why is committing with unresolved files frowned upon/prevented?  Is there any reason other than tradition?

答:
The biggest issue that I can see is that it creates a window of commits where things are half-merged and (probably) not working correctly. When you push the final set of local commits, all of those intermediate commits will also apear for everyone else. In ideal world, I should be able to pull any commit and the code should work. If you start committing in the middle of merges, the state of the code isn't well-defined.

One thing you could do is make local commits to your merge, and then bundle them into one big commit when you push (though I'm not sure how(if?) any vcs support this). While this might yield some of the benefits you mentioned, I'm not sure it's worth the extra complexity (we're already dealing with a fairly confusing and complex area).

Title: Why not commit unresolved changes?


答:
I am most familiar with Git, so I will be answering for that perspective.

I don't see a reason why you or any good VCS would want to allow committing an unmerged file, particularly if it was code. You need to keep the repository in a consistent state, and what you are suggesting would violate commit atomicity. Many VCS's physically change the file to show where the conflicts are - Git, SVN, and CVS use >>>> <<<< type markers. In a VCS with atomic repository-level commits and merges, you would just have created a node that makes no sense to anyone but you. In software development, your project couldn't build. In a group's document, no one knows which changes are correct.

Now, Git provides some tools that could ease this, were the type of commit you suggest allowed. You could squash all you merge commits together before you pushed, for example. That winds up being the same as a typical merge commit.

Specific concerns about your list of benefits:

The actual merge changes are in history. Why do you need extra information? DVCS's are very good about limiting conflicts to confined areas. Once you choose which changeset to keep, comparing the merge commit node's copy to the previous copy will give you exactly this.

If the merge was very large, you could make periodic commits. This is a valid concern, but you shouldn't ever get here in the first place. Branches should constantly be pulling in upstream changes just so this won't ever happen. Tools like rebase or cherry-pickking one commit at a time can also assist you here in some situations.

If you made a mistake, it would be much easier to roll back (without having to redo the entire merge). See above - your conflicts shouldn't become this unmanagable.

The only way this suggestion could work is if the branch was if the whole merge was atomic - you could see a series of commits, but they would be merely steps in a larger merge commit that had to be treated as one node in the commit tree. I don't think any current VCS has support for this type of workflow, and I don't think it is necessary.

Title: Why not commit unresolved changes?

Body:
In a traditional VCS, I can understand why you would not commit unresolved files because you could break the build.  However, I don't understand why you shouldn't commit unresolved files in a DVCS (some of them will actually prevent you from committing the files).

Instead, I think that your repository should be locked from pushing and pulling, but not committing.

Being able to commit during the merging process has several advantages (as I see it):

The actual merge changes are in history.

If the merge was very large, you could make periodic commits.

If you made a mistake, it would be much easier to roll back (without having to redo the entire merge).

The files could remain flagged as unresolved until they were marked as resolved.  This would prevent pushing/pulling.

You could also potentially have a set of changesets act as the merge instead of just a single one.  This would allow you to still use tools such as git rerere.

So why is committing with unresolved files frowned upon/prevented?  Is there any reason other than tradition?


问:
How can I design my classes to include calendar events stored in a database?
I'm developing a web calendar in php (using Symfony2) inspired by iCal for a project of mine.
At this moment, I have two classes: a class "Calendar" and a class "CalendarCell".

Here you are the two classes properties and method declarations.

```<code>class Calendar
{
    private $month;
    private $monthName;
    private $year;
    private $calendarCellList = array();
    private $translator;

    public function __construct($month, $year, $translator) {}

    public function getCalendarCellList() {}

    public function getMonth() {}

    public function getMonthName() {}

    public function getNextMonth() {}

    public function getNextYear() {}

    public function getPreviousMonth() {}

    public function getPreviousYear() {}

    public function getYear() {}

    private function calculateDaysPreviousMonth() {}

    private function calculateNumericDayOfTheFirstDayOfTheWeek() {}

    private function isCurrentDay(\DateTime $dateTime) {}

    private function isDifferentMonth(\DateTime $dateTime) {}
}

class CalendarCell
{
    private $day;
    private $month;
    private $dayNameAbbreviation;
    private $numericDayOfTheWeek;
    private $isCurrentDay;
    private $isDifferentMonth;
    private $translator;

    public function __construct(array $parameters) {}

    public function getDay() {}

    public function getMonth() {}

    public function getDayNameAbbreviation() {}

    public function isCurrentDay() {}

    public function isDifferentMonth() {}
}
</code>```

Each calendar day can includes many calendar events (such as appointments or schedules) stored in a database.
My question is: which is the best way to manage these calendar events in my classes?
I think to add a eventList property in CalendarCell and populate it with an array of CalendarEvent objects fetched by the database.

This kind of solution doesn't allow other coders to reuse the classes without db (because I should inject at least a repository services also) just to create and visualize a calendar... so maybe it could be better to extend CalendarCell (for instance in CalendarCellEvent) and add the database features?

I feel like I'm missing some crucial design pattern!

Any suggestion will be very appreciated!

答:
to add a eventList property in CalendarCell and populate it with an array of CalendarEvent objects fetched by the database.

Note: This is not a PHP solution, instead its a solution based on a RDBMS approach.

Yes you can do what you suggested above. Other developers who don't want to use the events could just not call the method that loads the events. A calendar cell and an event are 2 separate things. Hence, I see them as 2 separate classes.

The associations between a cell and an event (as I would think of it) may be something like:

A calenderCell has 0,1 or more Events.

An Event belongs to one or more calendarCells (for example, in case of a conference or a task spanning many days).

The above represent a Many-To-Many association.

You need a third class "calendarEvnet-MM" that holds the PK of calendarCell and calendarEvents.

So you'd have:

calendarCell Table:

claendarCell_ID     (Primary Key)
...

calendarEvent Table:

calendarEvent_ID    (Primary Key)
...

calendarEvnet-MM Table:

calendarEvnet-MM_ID (Primary Key)

calendarCell_ID_FK  (Foreign Key)

calendarEvent_ID_FK (Foreign Key)
...


问:
Do you actually write 'clean code'?
I have seen some programmers tweaking their code over and over again not only to make it 'work good', but also to make it 'look good'.

IMO, 'clean code' is actually a compliment indicating your code is elegant, perfectly understandable and maintainable. And the difference comes out when you have to choose between an aesthetically appealing code vs. code that's stressful to look at.

So, how many of you actually write 'clean code'? Is it a good practice? What are the other benefits or drawbacks of this?

答:
This is a quote from Clean Code, by Bob Martin:

To drive this point home, what if you were a doctor and had a patient
  who demanded that you stop all the silly hand-washing in preparation
  for surgery because it was taking too much time? Clearly the patient
  is the boss; and yet the doctor should absolutely refuse to comply.
  Why? Because the doctor knows more than the patient about the risks of
  disease and infection. It would be unprofessional (never mind
  criminal) for the doctor to comply with the patient.

So too it is unprofessional for programmers to bend to the will of
  managers who don’t understand the risks of making messes.

Title: Do you actually write 'clean code'?


问:
What is the path to JavaScript mastery?
I know how we start with JavaScript, we cut-and-paste a snippit to gain a little client-side functionality or validation.

But if you follow this path in trying to implement rich interactive behavior, it doesn't take long before you realize that you are creating a Big Ball Of Mud.

So what is the path towards expertise in programming the interaction layer?  What books, tutorials, exercises, and processes contribute towards the ability to program robust, maintainable JavaScript?

We all know that practice is important in any endeavor, but I'm looking for a path similar to the answer here: https://stackoverflow.com/questions/2573135/

答:
Javascript is applied in many development areas right now.

It's the only language present in modern browser.

It can run on the server, thanks to node.js and the V8 engine.

It can run embeded in mobile devices via PhoneGap or other alternatives.

It can be used to create windows 8 applications.

Therefore, I believe that there are more javascript masteries. It dependes on what you want to start with, but rest assured, each of those 4 items mentioned above will give you a different challenge - ok, maybe the window 8 and phonegap fields could be similar but the rest are different -.

If we're talking about the browser environment, learning how almost every web application should be organized could be one of the paths that you could go on. I'm going down that path, and experimenting with ideas of my own, checking out git repos of popular code organization libraries like dojo, backbone, ember etc.

If we're talking about the node js environment, that's a different story. We're not concerned with minification and file size. Creating entire applications in node, build systems, sites, REST api, there's a lot of things to discover there.

If we're talking about the mobile world, over optimization comes to mind. CSS3 accelerated properties, animations, touch events and trying to use the same architecture as the web with more specialized UI components are great things to start with.

All in all, like others responded, experimenting with your own code, and with the code of others is the best way to get involved, keep up with whats new, and who knows, maybe coming up with the next big thing.

Another thing that helps is working in a team, and understanding the differences between your way and the team's way of writing code. Working in a team of javascript developers will force you to write better code, and document it well. I think there's no better way of learning about the architecture of an application than writing a wiki about what you intend to implement or have already implemented.

Title: What is the path to JavaScript mastery?


问:
Model View Presenter over Model View Controller

Possible Duplicate:

  Building websites, which is the better approach MVP or MVC?

I am trying to learn the difference between the MVC and MVP models. So far, I do not see much difference in terms of how they are architecturally set up. So my question is when should the MVP model be chosen over the MVC model? Are there situations where one is better than the other?

答:
The link Rachel shared from SO about MVP vs. MVC goes into a lot more detail, and is probably the definitive answer to your question.  I believe RAD in that question stands for Rational Application Developer, which is an IDE based on eclipse.

They are fairly similar.  From my experience, the particular variant you end up using is in part dictated by the framework you use and which pattern it is geared towards.  WPF and Silverlight, for example, really emphasize an MVVM approach which is a variant of MVP.

Other languages / programming stacks will push different MV* variants.  Use what's native to your stack.

The link Jeff O. posted looks at the question from an MS ASP stack point of view.

For some additional info, look at Martin Fowler's discussion of GUI architecture.  This paragraph comes from the beginning of the MVP discussion.

To approach MVP I find it helpful to think about a significant mismatch between two strands of UI thinking. On the one hand is the Forms and Controller architecture which was mainstream approach to UI design, on the other is MVC and its derivatives. The Forms and Controls model provides a design that is easy to understand and makes a good separation between reusable widgets and application specific code. What it lacks, and MVC has so strongly, is Separated Presentation and indeed the context of programming using a Domain Model. I see MVP as a step towards uniting these streams, trying to take the best from each.


问:
Isn't MVC anti OOP?
The main idea behind OOP is to unify data and behavior in a single entity - the object. In procedural programming there is data and separately algorithms modifying the data.

In the Model-View-Controller pattern the data and the logic/algorithms are placed in distinct entities, the model and the controller respectively. In an equivalent OOP approach shouldn't the model and the controller be placed in the same logical entity?

答:
Controller does not represent the behavior of a model. Controllers altogether represent the behavior of the whole application _ what a user can do and what a user can see.

It is wrong to view controllers and models as one. They have different purposes, different semantics and thus shouldn't be unified in one object.

Title: Isn't MVC anti OOP?


答:
MVC works at a much higher level of abstraction than single objects, and in fact each of the three (model, view and controller) will typically consists of many objects that each have both data and behavior.

That objects which encapsulate data and behavior are a good fundamental building block for programs in general doesn't mean it's the best pattern at all levels of abstraction and for all purposes.

Title: Isn't MVC anti OOP?

Body:
The main idea behind OOP is to unify data and behavior in a single entity - the object. In procedural programming there is data and separately algorithms modifying the data.

In the Model-View-Controller pattern the data and the logic/algorithms are placed in distinct entities, the model and the controller respectively. In an equivalent OOP approach shouldn't the model and the controller be placed in the same logical entity?