问:
Reading source code to learn
As you develop as a programmer, software developer, or coder, IMHO, you begin to see different (best or worst) practices, different algorithms, and "more than one way to do it". Seeing this code can be a great learning experience for you, even though you did not write the code. But is doing this only going to confuse you?

For example, let's say you have a library in any language that was created by a colleague, and you have been using it for a while. You decide to look at the actual source code, regardless of how extensive it is, and get a better look at how this library is written. For the sake of example, the function you use most often from this library is the max function, which finds the largest of two numbers. But this function is a lot more complicated than it needs to be. The way it is written is confusing the heck out of you, and you don't know how this works.

Will this make you a better programmer, because you realize how complicated it is for such a simple function, or will it make you a worse coder because you feel less confidant?

So my question, in general, is does reading source code make you a better programmer and if so how? If not why do people still do it?.

答: I definitely think it does; the trick is finding good code to read.  I think I learned almost as much from reading the source to the old CDC6000 Pascal compiler as I did from my compiler course.  I also learned a great deal about operating system internals from perusing the 4.2 BSD kernel sources.  Nowadays, I'd probably take a look at the L4 microkernel or the OpenJDK sources.</p>

Title: Reading source code to learn


问:
How do I choose a package format for Linux software distribution?
We have a Java-based application that, to date, we've been distributing as a tarball with instructions for deploying. It's mostly self-contained so deployment is fairly straight-forward:

Untar on the disk you'd like it to live on;

Make sure Java is in your path and a suitable distro and version;

Verify ownership and group on all the files

Start up the server processes with our start script

If the user wants to get in to start-on-boot stuff with SysV we have some written instructions and a template init file for it in our tarball.

We'd like to make this installation process a little more seamless; take care of the permissions and the init script deployment. We're also going to start bundling our own JRE with the application so that we're mostly free of external dependencies.

The question we're faced with now is: how do we pick a package format for distribution? Is RPM the standard? Can all package management tools deal with it now? Our clients primarily run RHEL and CentOS, but we do have some using SuSE and even Debian. If we can pick a distro-agnostic format we'd prefer that.

What about a self-extracting shell script? Something akin to how Java is distributed. If we're dependency-free would the self-extracting script be sufficient? What features or conveniences would we lose out on going with the script versus a proper package format meant for use by a package manager?

答:
You should provide a package for each distro/version you want to support. Choose which distros and which of their versions you are going to support and provide the appropriate package (.deb for Debian/Ubuntu, .rpm for RHEL/Fedora, etc.). You might strike it lucky and, for instance, your Debian .deb can be 100% good under Ubuntu, but that doesn't happen all the time (i.e. IIRC, Debian and Ubuntu init scripts are different).

For everyone else, provide a .tar.gz and instructions.

ContentLicense: CC BY-SA 3.0


问:
Developing a feature which sole purpose to be taken out?
What is the name of the pattern in which individual contributors (programmers/designers) developed an artifact for the sole purpose is to serve as a diversion so that management can remove that feature in the final product?

This is a folklore I heard from an ex-colleague who used to work at a large game development company. At that company, it is well known that middle management is pressurized to "give inputs" and "make changes" to the product otherwise they risk being seen as not contributing to the project. This situation have delayed many projects because of these superfluous "management inputs".

In one project at the above company, the artists and developers created a supernumerary animated character that appears in every cutscene and sticks out like a sore thumb. They designed it in such a way that it can be easily removed before the game is shipped (this was when games were still sold in physical media and not a downloadable product). Obviously the management then voted to remove the animation. On the positive side, management didn't introduced any unnecessary changes that would have delayed the project because they have shown that they provided constructive inputs to the product.

This process pattern has a name among game programmers that work in corporates, but I forgot what was the actual name. I believe it's duck-something.  Anybody can help pointing out the name and perhaps some rather credible reference to how the pattern develops?.

答: In some projects I've worked on, we've called them "bike sheds" as a nod to the term bike shed problem. This term came from a passage the book Parkinson's Law, describing nuclear power plants as being so complicated that mismanagers would be afraid to touch anything, but a bike shed is so simple that everyone has to dither and fiddle with it to give the appearance of "managing" things.


问:
Good, simple reasons for having multiple environments
Throughout my career I had worked at companies that had a collection of different environments for different purposes. We always had more or less our desktop environment, a test environment, a QA environment, a staging environment and a production environment. This went for both servers/applications and any data sources we were using.

When I started at my current company I found that 90% of the apps were either developed on a desktop environment against production data sources or developed directly on the production server depending on the platform. This wasn't particularly surprising, as I was hired in part to make changes to improve the way the development team functioned, which was clear from my interview process. We slowly started to turn the philosophy and pretty soon, most of the apps could be run in either a desktop, test or production environment. Not too long after that staging came around as well.

Now most of our developers see the benefit of this methodology and defend it vigilantly. However, we have a number of legacy apps that never got migrated. We also have a number of legacy programmers who think of this as a waste of time. Unfortunately, we got lip service but never full buy-in from management. We got what we thought was a commitment to invest substantially in this about a year ago, but nothing materialized despite the considerable planning that we put into it. Now we are finding that we need more and more environments. We need help from the server/network administration teams for setup and we need participation from the business stakeholders to support the release cycle. We are at a place now where a project can function what reasonable developers would consider "normally" only if you have the right people on the project and the time to set up the proper environments.

I'd love to present a complete argument, but management really has no time and interest in hearing me out until there is a critical issue. I can't really articulate the benefits simply as it always just seemed second nature to me. I was wondering if there are any good, simple, irrefutable reasons for the separation of environments that would get managers lacking development experience to support this idea?. Are there any good resources/literature on the topic?

答:
You want to change how your organization develops its software? Forget worrying about "reasons" for "doing things differently". Humans don't change behavior because of rational arguments. They change because of psychological influences on their habits.

So, where am I going with this?

While occasionally you can successfully change an organization's behavior through argumentation, there are other tactics that work better. These include:

Grassroots support: Find ONE other "legacy" developer who is willing to give you a shot. Partner with him and change how things work. Don't announce the change. Just make the change. If anyone ever asks you about it, just say "Oh yeah, that's how we do it now."

Take over responsibility. Volunteer to handle deployments for the legacy folks. Act like you love it. They may be happy to relinquish that responsibility. Then run it how you want to.

Blame the right people for their mistakes. The next time a legacy app bug is introduced into production because of your stone age deployment mechanism, point it out. Do it subtly... Not in an email. Next time you're in a meeting with a manager, just casually mention the example of a reason that the deployment was problematic. "Yeah, remember how we were scrambling last Friday because of the Foo bug Bob checked into production? Yeah, that was a lot of wasted effort!"

Make it easy to do it the better way. Look at the iphone, for example. There is ONE button on it. (Well, two). It's VERY easy to turn on. Make deployment-to-multiple-environment crazy stupid easy. Make it so easy all the managers can do it!


答: When I started using Arch Linux I have fallen in love in pacman and makepkg apps. It's make building app from sources one of the easiest things in GNU/Linux. It check all dependences and create ready-for-use archive.

Title: How do I choose a package format for Linux software distribution?

Body:
We have a Java-based application that, to date, we've been distributing as a tarball with instructions for deploying. It's mostly self-contained so deployment is fairly straight-forward:

Untar on the disk you'd like it to live on;

Make sure Java is in your path and a suitable distro and version;

Verify ownership and group on all the files

Start up the server processes with our start script

If the user wants to get in to start-on-boot stuff with SysV we have some written instructions and a template init file for it in our tarball.

We'd like to make this installation process a little more seamless; take care of the permissions and the init script deployment. We're also going to start bundling our own JRE with the application so that we're mostly free of external dependencies.

The question we're faced with now is: how do we pick a package format for distribution? Is RPM the standard? Can all package management tools deal with it now? Our clients primarily run RHEL and CentOS, but we do have some using SuSE and even Debian. If we can pick a distro-agnostic format we'd prefer that.

What about a self-extracting shell script? Something akin to how Java is distributed. If we're dependency-free would the self-extracting script be sufficient? What features or conveniences would we lose out on going with the script versus a proper package format meant for use by a package manager?


答:
It’s called a duck, from a legend that allegedly comes from Interplay’s Battle Chess:

This started as a piece of Interplay corporate lore. It was well known that producers (a game industry position, roughly equivalent to PMs) had to make a change to everything that was done. The assumption was that subconsciously they felt that if they didn’t, they weren’t adding value.

The artist working on the queen animations for Battle Chess was aware of this tendency, and came up with an innovative solution. He did the animations for the queen the way that he felt would be best, with one addition: he gave the queen a pet duck. He animated this duck through all of the queen’s animations, had it flapping around the corners. He also took great care to make sure that it never overlapped the “actual” animation.

Eventually, it came time for the producer to review the animation set for the queen. The producer sat down and watched all of the animations. When they were done, he turned to the artist and said, “That looks great. Just one thing—get rid of the duck.”

Title: Developing a feature which sole purpose to be taken out?

Body:
What is the name of the pattern in which individual contributors (programmers/designers) developed an artifact for the sole purpose is to serve as a diversion so that management can remove that feature in the final product?

This is a folklore I heard from an ex-colleague who used to work at a large game development company. At that company, it is well known that middle management is pressurized to "give inputs" and "make changes" to the product otherwise they risk being seen as not contributing to the project. This situation have delayed many projects because of these superfluous "management inputs".

In one project at the above company, the artists and developers created a supernumerary animated character that appears in every cutscene and sticks out like a sore thumb. They designed it in such a way that it can be easily removed before the game is shipped (this was when games were still sold in physical media and not a downloadable product). Obviously the management then voted to remove the animation. On the positive side, management didn't introduced any unnecessary changes that would have delayed the project because they have shown that they provided constructive inputs to the product.

This process pattern has a name among game programmers that work in corporates, but I forgot what was the actual name. I believe it's duck-something.  Anybody can help pointing out the name and perhaps some rather credible reference to how the pattern develops?.


答:
I occasionally peruse source code of software. It provides bits and pieces of tactical information. More strategic information can't be gathered without spending actual time working on it and studying the system overall, I think.

nginx has some quite pretty C code. It's been described as geometric.

SBCL code is pretty nice as well, and is pretty old; you can get a sense of the historical flow of code when you read it.

Title: Reading source code to learn

Body:
As you develop as a programmer, software developer, or coder, IMHO, you begin to see different (best or worst) practices, different algorithms, and "more than one way to do it". Seeing this code can be a great learning experience for you, even though you did not write the code. But is doing this only going to confuse you?

For example, let's say you have a library in any language that was created by a colleague, and you have been using it for a while. You decide to look at the actual source code, regardless of how extensive it is, and get a better look at how this library is written. For the sake of example, the function you use most often from this library is the max function, which finds the largest of two numbers. But this function is a lot more complicated than it needs to be. The way it is written is confusing the heck out of you, and you don't know how this works.

Will this make you a better programmer, because you realize how complicated it is for such a simple function, or will it make you a worse coder because you feel less confidant?

So my question, in general, is does reading source code make you a better programmer and if so how? If not why do people still do it?.


问:
What are the best documentation patterns?
I've seen a lot of different ways to [or not to] comment out the code, specially patterns on desciptions of function details and file purposes.

I'd like to know what is most used pattern to do that [I'm specially interested on documentation generators and their patterns]

答:
I used to put effort into documenting code using these kind of automated documentation tools (doxygen, javadoc). However, I seem to find that the cost of creating and maintaining this kind of documentation was rarely justified by the benefits from having it. As long as your users can see the names/types of your function parameters.

I prefer to spend the time creating/maintaining examples and task focused documentation (how do I x?), as well as general overviews of the functionality/model used by the API. This is especially true if the source code of what ever you are documenting is going to be available to the developers using it (as they can always read the source code to resolve any ambiguities).

A well designed API should be intuative and difficult to use incorrectly once the main concepts of the model have been communicated. Per-method/per-class documentation doesn't really help to communicate these (model) concepts efficently, as it is so fragmented. Using the per-method/per-class approach, your users already have to be quite familiar with your API before they are even able to look in the right place for the documentation they need.

ContentLicense: CC BY-SA 2.5


答:
Is it actually critical?

I can understand the desire to use separate environments.  The non-obvious question is:

Is it actually critical to migrate a legacy system?

I think most technically minded people tend to focus on the academic question of which way is better which is fine in academia.  In business though best doesn't always win out.  I'm not saying this to be negative, or start a flame war. I am stating the obvious, or what should be obvious to those of us who have been in the software business for a few years.

All business decisions are typically made based on the perceived cost/benefit.  So the question the business is probably asking is:

Is the cost of the additional system and development investment in a legacy application worth the benefit versus putting that same investment into another project/product?

I have and still do regular cost benefit analysis to make determinations not just in migrating/rewriting software, but in day-to-day decisions a lead typically engages in.  I've passed on rewriting/migrating old software because it had limited life and therefore value.

Separating Environments

The business reasons to separate environments.

Less risk in releases, and bug fixes.  Prove it with numbers.  How many times has the product failed and cost customer revenue because of a bad release/bug.

Less risk in development.  Accidentally blowing away the dev db is different from accidentally blowing away the production db

The ability to clearly separate roles and access ie. better security. limiting the number of fingers in the production pie is a good thing

The ability to separate environments, and the practices and procedure that go along with this style of development allow for future build out into Cloud Systems.

The separation of environment should force efficiencies in replicating environments which may be useful in scheduled as well as dynamic scaling.

Title: Good, simple reasons for having multiple environments

Body:
Throughout my career I had worked at companies that had a collection of different environments for different purposes. We always had more or less our desktop environment, a test environment, a QA environment, a staging environment and a production environment. This went for both servers/applications and any data sources we were using.

When I started at my current company I found that 90% of the apps were either developed on a desktop environment against production data sources or developed directly on the production server depending on the platform. This wasn't particularly surprising, as I was hired in part to make changes to improve the way the development team functioned, which was clear from my interview process. We slowly started to turn the philosophy and pretty soon, most of the apps could be run in either a desktop, test or production environment. Not too long after that staging came around as well.

Now most of our developers see the benefit of this methodology and defend it vigilantly. However, we have a number of legacy apps that never got migrated. We also have a number of legacy programmers who think of this as a waste of time. Unfortunately, we got lip service but never full buy-in from management. We got what we thought was a commitment to invest substantially in this about a year ago, but nothing materialized despite the considerable planning that we put into it. Now we are finding that we need more and more environments. We need help from the server/network administration teams for setup and we need participation from the business stakeholders to support the release cycle. We are at a place now where a project can function what reasonable developers would consider "normally" only if you have the right people on the project and the time to set up the proper environments.

I'd love to present a complete argument, but management really has no time and interest in hearing me out until there is a critical issue. I can't really articulate the benefits simply as it always just seemed second nature to me. I was wondering if there are any good, simple, irrefutable reasons for the separation of environments that would get managers lacking development experience to support this idea?. Are there any good resources/literature on the topic?


问:
How can I convince cowboy programmers to use source control?
I work on a small team of devs, 4 guys.  They have all used source control.  Most of them can't stand source control and instead choose not to use it. I strongly believe source control is a necessary part of professional development. Several issues make it very difficult to convince them to use source control:

The team is not used to using TFS.  I've had 2 training sessions, but was only allotted 1 hour which is insufficient.

Team members directly modify code on the
server.  This keeps code out of sync.  Requiring comparison just to be sure you are working with the latest code.  And complex merge problems arise

Time estimates offered by developers exclude time required to fix any of these problems.  So, if I say nono it will take 10x longer...I have to constantly explain these issues and risk myself because now management may perceive me as "slow".

The physical files on the server differ in unknown ways over ~100 files.  Merging requires knowledge of the project at hand and, therefore, developer cooperation which I am not able to obtain.

Other projects are falling out of sync.  Developers continue to have a distrust of source control and therefore compound the issue by not using source control.

Developers argue that using source control is wasteful because merging is error prone and difficult.  This is a difficult point to argue, because when source control is being so badly mis-used and source control continually bypassed, it is error prone indeed.  Therefore, the evidence "speaks for itself" in their view.

Developers argue that directly modifying server code, bypassing TFS saves time.  This is also difficult to argue.  Because the merge required to synchronize the code to start with is time consuming.  Multiply this by the 10+ projects we manage.

Permanent files are often stored in the same directory as the web project.  So publishing (full publish) erases these files that are not in source control.  This also drives distrust for source control.  Because "publishing breaks the project".  Fixing this (moving stored files out of the solution subfolders) takes a great deal of time and debugging as these locations are not set in web.config and often exist across multiple code points.

So, the culture persists itself.  Bad practice begets more bad practice.  Bad solutions drive new hacks to "fix" much deeper, much more time consuming problems.  Servers, hard drive space are extremely difficult to come by.  Yet, user expectations are rising.

What can be done in this situation?

答:
Other than the obvious Find a new job, I think the answer is more all of the above.

First go to management to get them on board with moving to and enforcing the use of source control. Then get to what needs to be done to keep things running, even if that means working directly on the server. Start the process of getting everything in source control.

Another option is to make sure the latest is on the server (which you have to do regardless) and start a new repository altogether from the latest. You will lose history, but at this point that is small potatoes.

ContentLicense: CC BY-SA 4.0


答:
It seems from your description that there are one or more problems with the situation - either the dev team is out of control or a bad source control solution was implemented. Either way, it's incumbent on the dev team to use some source control solution - directly modifying source code on the production service is just begging for problems to happen.

From my experience, the first step that must take place immediately is to sync up source control with the production server. This step can be as simple as taking a copy of production code and checking it in - the prod code is presumably the base that your team is developing. This step might need to be augmented by a merge with code that's floating around in the existing source control system. Code should flow from dev to integration/QA (or both), and then to either stage or stage/production.

Next, management needs to mandate use of source control. Quite simply, if the build didn't come from the source control system, code shouldn't get deployed to production. Production access needs to be limited to the support team only, with limited access given to dev to troubleshoot production issues. Developers should generally never do hot deploys of code to production - production problems could definitely happen, particularly if the devs are under pressure.

Management definitely needs to get a better handle on the issues here - it'll be almost impossible to sustain development if code is getting applied to prod directly (and not getting into source control).

Title: How can I convince cowboy programmers to use source control?

Body:
I work on a small team of devs, 4 guys.  They have all used source control.  Most of them can't stand source control and instead choose not to use it. I strongly believe source control is a necessary part of professional development. Several issues make it very difficult to convince them to use source control:

The team is not used to using TFS.  I've had 2 training sessions, but was only allotted 1 hour which is insufficient.

Team members directly modify code on the
server.  This keeps code out of sync.  Requiring comparison just to be sure you are working with the latest code.  And complex merge problems arise

Time estimates offered by developers exclude time required to fix any of these problems.  So, if I say nono it will take 10x longer...I have to constantly explain these issues and risk myself because now management may perceive me as "slow".

The physical files on the server differ in unknown ways over ~100 files.  Merging requires knowledge of the project at hand and, therefore, developer cooperation which I am not able to obtain.

Other projects are falling out of sync.  Developers continue to have a distrust of source control and therefore compound the issue by not using source control.

Developers argue that using source control is wasteful because merging is error prone and difficult.  This is a difficult point to argue, because when source control is being so badly mis-used and source control continually bypassed, it is error prone indeed.  Therefore, the evidence "speaks for itself" in their view.

Developers argue that directly modifying server code, bypassing TFS saves time.  This is also difficult to argue.  Because the merge required to synchronize the code to start with is time consuming.  Multiply this by the 10+ projects we manage.

Permanent files are often stored in the same directory as the web project.  So publishing (full publish) erases these files that are not in source control.  This also drives distrust for source control.  Because "publishing breaks the project".  Fixing this (moving stored files out of the solution subfolders) takes a great deal of time and debugging as these locations are not set in web.config and often exist across multiple code points.

So, the culture persists itself.  Bad practice begets more bad practice.  Bad solutions drive new hacks to "fix" much deeper, much more time consuming problems.  Servers, hard drive space are extremely difficult to come by.  Yet, user expectations are rising.

What can be done in this situation?


答:
You seem to have invested a great deal of effort in bringing about a cultural change in your workplace. This is a great achievement as change is difficult at the best of times, yet cultural change is not simply about changing people's minds, but about changing habits, breaking prejudices, and ultimately about opening potentially closed minds to greater possibilities. So the question to ask yourself at this point is "What did I miss?". The easy answer is that you may not have fully engaged with management.

Getting buy in from management is easy, but even harder is getting acceptance.  Regardless of the arguments about money etc, the reality is that you need to be able to influence management's view of priority. Your manager will have a budget, and will want to show that  budget has been applied sensibly and in keeping with company values and priorities.  Some of those priorities will be fiscal, but others will be about serving other needs.  In some cases, this may mean greasing the palms of other managers in order to get that promotion your boss has always wanted. In most cases though, it will likely be about finding ways to gain more business, or improve relationships with partners and customers. If you can't make your case in these terms, you will only be able to go so far before you find yourself at an impasse.

My suggestion is to try to make a case about productivity and how this affects budget, as others have suggested, but also to make the case in terms of your company's priorities and how your productivity might directly impact on the company's relationships with other companies.


答:
Sometimes, real world issues make it impractical to use.

False.

If the team is not used to using source control, training problems can arise

That has nothing to do with source code control and everything to do with training.  Training is easy, cheap, efficient and done in a matter of hours.  Failing to use source code control is costly, risky, inefficient and the problems persist forever.

If a team member directly modifies code on the server, various issues can arise.

That's the training issue.  Again. Nothing to do with source code control and everything to do with training.

Developers continue to have a distrust of source control and therefore compound the issue by not using source control

They need to be trained in how to use source code control.  It reduces cost, reduces risk, simplifies things and is more efficient.  It's a one-time investment that pays dividends every moment.

What can possibly be done in this type of situation?

Start training everyone on how to use  source code control.

Update

Developers argue that directly modifying source control saves time.

Since they're wrong, it's important to gather data to demonstrate precisely how wrong this is.

Sadly, however, management appears to reward an immediate response that's costly in the long run.

The only way to overcome this reward system is to

A) Identify that the long term cost is higher than the apparent short term value.

B) Identify the actual rewards that are actually in place that make short term  corruption (i.e., direct changes) appear more valuable than long-term correct source code control.  Who gets a pat on the head for doing the wrong thing?  What kind of pat on the head do they get?  Who gives it?  In order to fix things, you must name the things that are wrong and the specific manager(s) who is (are) actually encouraging folks.

C) Recommend a revised reward system that values long-term value instead of short-term quick response.  Different pats on the head for different reasons.

D) Train folks in the rewards you found for long-term value; value which is clearly larger than the short-term quick response.


答:
We solved the problem by first, setting up a continuous integration server to build our source control into dev.  Second, lock down folder access to read only, to prevent people circumventing source control and modifying files directly.

It's a PITA on days where you can't reproduce the bug locally, but other than that it's nicer being able to work, checkin, and move on, knowing it will be pushed to dev automatically by the CI server.


答:
Its more of an issue when you start dealing with interconnected or legacy systems, systems the business depends on to be working and accurate. Its important because there needs to be segregation between the stages, its the reason why you dont DEV on PROD because it has the potential to cause millions of dollars worth of damage in lost time.

We always do DEV -> QA -> PROD (occasionally those steps are broken up into smaller pieces) with identical hardware behind them. Current production data is always pushed from PROD to QA to DEV.

DEV: is intended to be the development sandbox, where things are tried, iterated and beaten on any data in this environment should never be trusted and is regularly trashed by developers simply finding ways to solve a problem.

QA: Once your developers are satisfied with unit testing, its time for the test group to get there eyes on it. They run test cases, performance testing and find bugs. Those bugs/enchancements get fed back to DEV and the cycle continues until everyone is happy.

PROD: Once you get to this stage you should be sure the code works in conjunction with current data and your QA group/business users are happy with the implementation. If you did everything correctly you should simply be able to update the code and be done with it.

In the same way you would never release an untested product to customers you should never release untested code to a production environment.

If the company is not willing to invest the time to do it properly they will pay back the cost in emergency maintenance and errors 10 fold.

As a small example: We had one company who decided to make a change to a report in production on his own. No one knew that it changed until we came in to address a variety of issues a year or two down the line.

When we pointed out the irregularity in the report the CFO's face went white, turns out they were losing ~$250,000 a quarter because of someone making a quick change.

Happens more often then you think, if you cant afford to do it properly then dont do it.


答:
Step 1  - fire incompetent manager!

If you can't do step 1, try to get the manager to limit deployment to prod to only scripts that are taken from source control. If developers (who should not have production rights on prod, see step 1 if they do) want their stuff deployed it has to come from source control. That solved our issue of not using source control quite nicely back when we first swtiched to using it for database stuff as well as C# code.


问:
When is a version control commit too large?
I've heard in several places "Don't make large commits" but I've never actually understood whats a "large" commit. Is it large if you work on a bunch of files even if there related? How many parts of a project should you be working on at once?

To me, I have trouble trying to make "small commits" since I forget or create something that creates something else that creates something else. You then end up with stuff like this:

```
Made custom outgoing queue

Bot
-New field msgQueue which is nothing more than a SingleThreadExecutor
-sendMsg blocks until message is sent, and adds wait between when messages get
sent
-adminExist calls updated (see controller)
-Removed calles to sendMessage

Controller
-New field msgWait denotes time to wait between messages
-Starting of service plugins moved to reloadPlugins
-adminExists moved from Server because of Global admins. Checks at the channel,
server, and global level

Admin
-New methods getServer and getChannel that get the appropiate object Admin
belongs to

BotEvent
-toString() also show's extra and extra1

Channel
-channel field renamed to name
-Fixed typo in channel(int)

Server
-Moved adminExists to Controller

PluginExecutor
-Minor testing added, will be removed later

JS Plugins
-Updated to framework changes
-Replaced InstanceTracker.getController() with Controller.instance
-VLC talk now in own file

Various NB project updates and changes

---

Affected files
Modify  /trunk/Quackbot-Core/dist/Quackbot-Core.jar
Modify  /trunk/Quackbot-Core/dist/README.TXT
Modify  /trunk/Quackbot-Core/nbproject/private/private.properties
Modify  /trunk/Quackbot-Core/nbproject/private/private.xml
Modify  /trunk/Quackbot-Core/src/Quackbot/Bot.java
Modify  /trunk/Quackbot-Core/src/Quackbot/Controller.java
Modify  /trunk/Quackbot-Core/src/Quackbot/PluginExecutor.java
Modify  /trunk/Quackbot-Core/src/Quackbot/info/Admin.java
Modify  /trunk/Quackbot-Core/src/Quackbot/info/BotEvent.java
Modify  /trunk/Quackbot-Core/src/Quackbot/info/Channel.java
Modify  /trunk/Quackbot-Core/src/Quackbot/info/Server.java
Modify  /trunk/Quackbot-GUI/dist/Quackbot-GUI.jar
Modify  /trunk/Quackbot-GUI/dist/README.TXT
Modify  /trunk/Quackbot-GUI/dist/lib/Quackbot-Core.jar
Modify  /trunk/Quackbot-GUI/nbproject/private/private.properties
Modify  /trunk/Quackbot-GUI/nbproject/private/private.xml
Modify  /trunk/Quackbot-GUI/src/Quackbot/GUI.java
Modify  /trunk/Quackbot-GUI/src/Quackbot/log/ControlAppender.java
Delete  /trunk/Quackbot-GUI/src/Quackbot/log/WriteOutput.java
Modify  /trunk/Quackbot-Impl/dist/Quackbot-Impl.jar
Modify  /trunk/Quackbot-Impl/dist/README.TXT
Modify  /trunk/Quackbot-Impl/dist/lib/Quackbot-Core.jar
Modify  /trunk/Quackbot-Impl/dist/lib/Quackbot-GUI.jar
Modify  /trunk/Quackbot-Impl/dist/lib/Quackbot-Plugins.jar
Modify  /trunk/Quackbot-Impl/lib/javarebel.stats
Add /trunk/Quackbot-Impl/lib/jrebel.info
Modify  /trunk/Quackbot-Impl/nbproject/private/private.properties
Modify  /trunk/Quackbot-Impl/nbproject/private/private.xml
Modify  /trunk/Quackbot-Impl/nbproject/project.properties
Modify  /trunk/Quackbot-Impl/plugins/CMDs/Admin/reload.js
Add /trunk/Quackbot-Impl/plugins/CMDs/Operator/hostBan
Modify  /trunk/Quackbot-Impl/plugins/CMDs/Operator/mute.js
Modify  /trunk/Quackbot-Impl/plugins/CMDs/lyokofreak/curPlaying.js
Modify  /trunk/Quackbot-Impl/plugins/CMDs/lyokofreak/lfautomode.js
Modify  /trunk/Quackbot-Impl/plugins/listeners/onJoin.js
Modify  /trunk/Quackbot-Impl/plugins/listeners/onQuit.js
Modify  /trunk/Quackbot-Impl/plugins/testCase.js
Add /trunk/Quackbot-Impl/plugins/utils/whatsPlaying.js
Modify  /trunk/Quackbot-Impl/src/Quackbot/impl/SandBox.java
Add /trunk/Quackbot-Impl/vlc_http
Add /trunk/Quackbot-Impl/vlc_http/current.html
Modify  /trunk/Quackbot-Plugins/dist/Quackbot-Plugins.jar
Modify  /trunk/Quackbot-Plugins/dist/README.TXT
Modify  /trunk/Quackbot-Plugins/dist/lib/Quackbot-Core.jar
Modify  /trunk/Quackbot-Plugins/nbproject/private/private.properties
Modify  /trunk/Quackbot-Plugins/nbproject/private/private.xml
Modify  /trunk/Quackbot-Plugins/src/Quackbot/plugins/JSPlugin.java
Add /trunk/Quackbot-Plugins/vlc_http
Add /trunk/global-lib/jrebel.jar
```

Yea....

So for questions:

What are some factors for when a commit becomes too large (non-obvious stuff)?

How can you prevent such commits? Please give specifics

What about when your in semi-early stages of development when things are moving quickly? Are huge commits still okay?

答:
It isn't the size of the commit that really matters, it is the scope of the change that should determine how your commitments are organized.

You might, for instance change every instance of __macro1 to __macro2 in a large code base, which changes 200 files. 200 commitments would not be sane in that case.

What you want to end up with is being able to pull the repository at any single revision and having the build work. Did you change from libfoo to libbar? I hope that change includes updating your build scripts and Makefiles as well (or whatever is applicable).

Sometimes, you might need to make a series of experimental changes that accomplish one thing, in which case, you have to determine what scope is more important to you if you need to revert later. Does one depend on the other? Commit them all at once in one single revision. Otherwise, in that case, I'd suggest one commit per change. You should be doing something like that in another branch, or in another repo anyway.

While yes, you do have the power to revert a single file to a previous revision (thus backing one file out of a larger commitment), doing so really screws up tools like bisection later on down the road, and pollutes the history.

If you stop and think "Ok, tests pass, I think this works .. but if it goes bad, can I easily back it out?" .. you'll end up making sensible commitments.


答:
It's not a training issue, it's a human factors issue. They do not want to, and are creating road blocks. Deal with the broken group dynamics, what is the root cause of their objection - usually fear, is it just fear of change, or is it more sinister.

No professional developer today, or for the last 20 years, has resisted source control. Once, about 30 or 40 years ago, when computers were slow, source control even slower and programs consisted of one 500 line file, it was a pain and there were valid reasons not to use it. These objections can only be coming from the worst kind of cowboys I can think of.

Is the system forced on them making their lives difficult in some way?  Find out what it is, and change the system to invalidate the objection. Repeat until done.

I suggest looking at GIT or Mercurial. You can create a repository in each source code tree, they won't even notice and can keep on hacking the way they do now. You can track the changes they have hacked into the code base, make commits, merge them into other source trees etc. When they see you do a merge of a weeks worth of effort into another product in seconds, they might change their ideas. When you roll back one of their screw ups with one command, and save their ass, they might even thank you (don't count on it). At worst, you look good in front of the boss and, for a bonus, make them look like the cowboys they are.

Merging would take not only a great knowledge of the project

In that case, I am afraid you're up the proverbial creek with no paddle. If merging is not an option, neither is implementing it, so you are saying that you can no longer add features you already have in one branch (term used loosely) to another.

If I were you I would reconsider my career prospects...


问:
Can the Abstract Factory pattern be considered as a case of polymorphism?
I was looking for a pattern/solution that allows me call a method as a runtime exception in a group of different methods without using Reflection. I've recently become aware of the Abstract Factory Pattern.

To me, it looks so much like polymorphism, and I thought it could be a case of polymorphism but without the super class GUIFactory, as you can see in the example of the link above. Am I correct in this assumption?

答:
I guess it depends on how it is used.

Essentially the Factory pattern is a reference to a set of objects.  Normally combined with something else, possibly like the Strategy pattern (which is more likely to be defined as a type of polymorphism) to provide reference to an object to act on.

The Abstract Factory Pattern by itself is intended to be polymorphic as it is defined as an abstract class type.  However the concrete implementation of the factory is the WidgetFactory in your type and is only polymorphic in reference to using a factory and providing an implementation of a factory.

In terms of what you are after, you certainly require a concrete factory, and presumably the actions you perform depend on the exception being caught. To that end you would use your factory implementation in a non-polymorphic way simply by passing it the exception caught, and have the factory pattern return a method to invoke a strategy or even a chain-of-command pattern to deal with how you would like to handle the exception.

Therefore, your factory would not necessarily be polymorphic, and your exception handlers would be polymorphic.


问:
Is loose coupling w/o use cases an anti-pattern?
Loose coupling is, to some developers, the holy grail of well-engineered software.  It's certainly a good thing when it makes code more flexible in the face of changes that are likely to occur in the foreseeable future, or avoids code duplication.

On the other hand, efforts to loosely couple components increase the amount of indirection in a program, thus increasing its complexity, often making it more difficult to understand and often making it less efficient.

Do you consider a focus on loose coupling without any use cases for the loose coupling (such as avoiding code duplication or planning for changes that are likely to occur in the foreseeable future) to be an anti-pattern?  Can loose coupling fall under the umbrella of YAGNI?

答:
The simple answer is loose coupling is good when done correctly.

If the principle of one-function, one purpose is followed then it should be easy enough to follow what is going on.  Also, loose couple code follows as a matter of course without any effort.

Simple design rules:
1. don't build knowledge of multiple items into a single point (as pointed out everywhere, depends) unless you are building a facade interface.
2. one function - one purpose (that purpose may be multi-faceted such as in a facade)
3. one module - one clear set of interrelated functions - one clear purpose
4. if you cannot simply unit test it then it does not have a simple purpose

All these comments about easier to refactor later are a load of cods.  Once the knowledge gets built into many places, particularly in distributed systems, the cost of refactoring, the rollout synchronisation, and just about every other cost blows it so far out of consideration that in most cases the system ends up being trashed because of it.

The sad thing about software development these days is 90% of people develop new systems and have no ability to comprehend old systems, and are never around when the system has got to such a poor state of health due to continual refactoring of bits and pieces.


问:
Choosing a web development framework?
So, I've sort of reached a point where I want to start developing a website. Originally, I planned to build said website using PHP and CodeIgniter, I'm familiar with both, but, truth be told, I'm not too fond of either. I find they just get rather messy, CodeIgniter helps somewhat, but no matter what, it seems that most PHP comes out more obfuscated than it has to be.

Anyways, I've come to the point where I want to either use Python or Ruby. I'm familiar in both, though more so towards Python, but I've never done any web development in them. I'll take the necessary time to learn the frameworks (and further my knowledge in the language of my choosing), but I need to choose one.

I don't like either language more than the other, they both have their benefits...

However, since I've never done any web development with either language, I was hoping that you guys could give me some pointers. What are the available frameworks for each language? What do you recommend and why?

Note: I've primarily looked into Rails and Django - but I'm still open to others. I'm looking for one that will work for just one (or maybe two) developers. It has to be fairly easy to learn (but I will take the time to learn it). Also, I'd like it to easily support clean code and agile development.

答:
You answered it yourself: you prefer to code in Python and in Ruby rather than in PHP, and you are more familiar with Python out of the two.

So Python it is, and Django as the framework, as it's the most popular one (meaning you'll find more information/tutorials for it).

Title: Choosing a web development framework?


问:
Random pairing algorithm
If you have a list of items and you want to randomly pair the items in the list together, what kind of algorithm would you use to do that, such that the items can only be matched to one other item.</p>

答:
Randomize the list and then grab pairs of adjacent items.

(I'm not sure I understand your last requirement, "the items can only be matched to one other item." If I haven't fully answered your question, please edit the question to expand on that point.)

Title: Random pairing algorithm


问:
Is Razor or XSLT better for my project?
I'm in the early stages in the design of a system that will essentially be split into two parts. One part is a service and the other is an interface with the service providing data through something like OData or XML. The application will be based on the MVC architectural pattern. For the views, we are considering using either XSLT or Razor under ASP.NET.

XSLT or Razor would help to provide a separation of concerns where the original XML or response represents your model, the XSLT or 'Razor view' represents your view. I'll leave the controller out for this example. The initial design proposal recommends XSLT, however I suggested the use of Razor instead as a more friendly view engine.

These are the reasons I suggested for Razor (C#):

Easier to work with and build more complicated pages.

Can easily produce non-*ML output, eg csv, txt, fdf

Less verbose templates

The view model is strongly typed, where XSLT would need to rely on
convention, eg boolean or date values

Markup is more approachable, eg nbsp, newline normalization, attibute
value normalization, whitespace rules

Built in HTML helper can generate JS validation code based on DTO attributes

Built in HTML helper can generate links to actions

And the arguments for XSLT over razor were:

XSLT is a standard and will still exist many years into the future.

It is hard to accidentally move logic into the view

Easer for non programmers (which I don't agree with).

It's been successful in some of our past projects.

Data values are HTML-encoded by default

Always well formed

So I'm looking for aguments on either side, recommendations or any experience making a similar choice?

答:
You don't have to choose, you can use both. In ASP.NET MVC you can use multiple view engines at the same time. In the project I'm currently working on I'm using XSLT for readonly views and Razor for forms. You can also use XSLT with Razor layout or Razor with XSLT layout. I'm using XSLT layout, so I simply use a Razor layout that calls the XSLT layout and passes the sections HTML as parameters:

```<code>@{
   Html.RenderPartial("~/Views/shared/htmlRaw.xsl", null, new ViewDataDictionary {
      { "head", RenderSection("head", required: false) },
      { "content", RenderBody().ToString() }
   });
}
</code>```

... and in htmlRaw.xsl you simply use disable-output-escaping="yes":

```<code><div id="content">
   <xsl:value-of select="$content" disable-output-escaping="yes"/>
</div>
</code>```

See Using Razor and XSLT in the same project.

Title: Is Razor or XSLT better for my project?

Body:
You don't have to choose, you can use both. In ASP.NET MVC you can use multiple view engines at the same time. In the project I'm currently working on I'm using XSLT for readonly views and Razor for forms. You can also use XSLT with Razor layout or Razor with XSLT layout. I'm using XSLT layout, so I simply use a Razor layout that calls the XSLT layout and passes the sections HTML as parameters:

@{
   Html.RenderPartial("~/Views/shared/htmlRaw.xsl", null, new ViewDataDictionary {
      { "head", RenderSection("head", required: false) },
      { "content", RenderBody().ToString() }
   });
}

... and in htmlRaw.xsl you simply use disable-output-escaping="yes":

<div id="content">
   <xsl:value-of select="$content" disable-output-escaping="yes"/>
</div>

See Using Razor and XSLT in the same project.


答: I think Ruby on Rails is your answer. It is designed for web applications. It supports clean code and agile development.</p>

Title: Choosing a web development framework?

Body:
So, I've sort of reached a point where I want to start developing a website. Originally, I planned to build said website using PHP and CodeIgniter, I'm familiar with both, but, truth be told, I'm not too fond of either. I find they just get rather messy, CodeIgniter helps somewhat, but no matter what, it seems that most PHP comes out more obfuscated than it has to be.

Anyways, I've come to the point where I want to either use Python or Ruby. I'm familiar in both, though more so towards Python, but I've never done any web development in them. I'll take the necessary time to learn the frameworks (and further my knowledge in the language of my choosing), but I need to choose one.

I don't like either language more than the other, they both have their benefits...

However, since I've never done any web development with either language, I was hoping that you guys could give me some pointers. What are the available frameworks for each language? What do you recommend and why?

Note: I've primarily looked into Rails and Django - but I'm still open to others. I'm looking for one that will work for just one (or maybe two) developers. It has to be fairly easy to learn (but I will take the time to learn it). Also, I'd like it to easily support clean code and agile development.


问:
What benefits are there to native JavaScript development?
Given how much simpler jQuery development is, when compared to native JavaScript, what makes people forgo libraries like jQuery altogether?

Is this because jQuery has limitations or it is slow? I mean, if jQuery is so easy compared to native javascript, what reasons do people have to still use pure javascript?

答:
I think people use jQuery because it's simpler, easier, and more powerful, and because it helps them forget about IE. Besides, for customized functionalities people do use javascript.
Try referring the DOC for more details</p>

OwnerDisplayName: Mike

OwnerDisplayName: Mithun Sasidharan


答:
Reasons I know:

When the need is extremely minimal, say 1 onclick.

When download speed is critical and the jQuery library is too large AND you don't have to write much (custom) code to replace it.

When integrating with other technologies, sometimes raw js is better.

When working on a legacy system (aka 'production') already written in js with established patterns and the team is not open to constant (but ideally gradual) change like this.

Title: What benefits are there to native JavaScript development?

Body:
Given how much simpler jQuery development is, when compared to native JavaScript, what makes people forgo libraries like jQuery altogether?

Is this because jQuery has limitations or it is slow? I mean, if jQuery is so easy compared to native javascript, what reasons do people have to still use pure javascript?

OwnerDisplayName: Michael Durrant


答:
jQuery is simply a framework – a set of tools written in JavaScript. By using that set of tools you are still using JavaScript. Some people prefer to write JavaScript using the tools jQuery provides, some choose not to, other choose other sets of tools.

Some reasons you might want to write "pure" JavaScript without jQuery:

Pages load faster without including extra jQuery files

Some frameworks may be incompatible with jQuery

The code being written doesn't do anything that jQuery helps with

The code is being written for others to use, and requiring jQuery as a dependency would make sharing more difficult

The code author wants more control than jQuery provides


问:
With PHP frameworks, why is the "route" concept used?
The reason I ask this is because isn't a PHP script a route? For example, if you have an article.php then your route is simply http://mysite.com/article.php.

Why further abstract away the concept of a route when it already exists as a simple file?

答:
To understand what a router does, you must first understand what a rewrite engine is. From the Wikipedia article (emphasis mine):

A rewrite engine is software that modifies a web URL's appearance (URL rewriting). Rewritten URLs (sometimes known as short, fancy URLs, or search engine friendly - SEF) are used to provide shorter and more relevant-looking links to web pages. The technique adds a degree of separation between the files used to generate a web page and the URL that is presented to the World.

When a rewrite engine is used you don't have a 1:1 correlation between the URL and a PHP script. An example from the same article:

http://example.com/wiki/index.php?title=Page_title

can be rewritten as:

http://example.com/wiki/Page_title

There are various benefits to using the technique. Since PHP is usually tightly coupled with Apache, the most commonly used rewrite engine is Apache's mod_rewrite.

If you want rewritten URLs, you need some kind of routing, as routing is the process of taking the URL, breaking it into components and deciding what is the actual script to call. The documentation page for the standard router of the Zend Framework explains the process as:

Routing is the process of taking a URI endpoint (that part of the URI which comes after the base URL) and decomposing it into parameters to determine which module, controller, and action of that controller should receive the request.

Most PHP frameworks nowadays are based on the MVC pattern, and on an MVC framework the process goes something like this*:

The browser is pointed to a URL,

Web server catches request and forwards it to a common entry point, usually an index.php script,

index.php gets the URL and starts the routing process.

URL is decomposed into parameters, where the first is the controller, second is the action method, and the rest are considered dynamic parameters,

If a controller class matching the first parameter exists, a controller object is instantiated,

The action method which is usually a function of the controller object is called and its return is what actually returned to the browser.

Matching parameters to controllers and methods usually employs matching via regular expressions to be able to handle complex and dynamic routing patterns, known as routes. Good examples of routes can be found on CodeIgniter's URI Routing documentation page:

$route['journals'] = "blogs";

$route['blog/joe'] = "blogs/users/34";

$route['product/(:any)'] = "catalog/product_lookup";

$route['product/(:num)'] = "catalog/product_lookup_by_id/$1";

The $route array holds the patterns as keys and the resulting actions as values in controller/action_method/dynamic_parameter format.

*This is not intended as a description of the canonical process, just an oversimplified explanation.


答:
As you will be aware, jQuery is a general-purpose framework which provides a lot of methods which many of us don't use in our projects. (Some of them I haven't used at all.)

There are two main reasons for not using jQuery or any other well-established frameworks.

1. The project is not big or complex enough to use such a framework:
In this case, the coder takes an informed decision based on his experience and knowledge in JavaScript. This will help him to reduce the page weight and also more control on the code.

2. The coder develops his own framework
I have seen a project in my company which has its own JavaScript framework. The reason what they quote is that if they are using jQuery and there is any bug to fix in it, they have to wait till the next version. Moreover, if there is a feature to be added, they need to ask the jQuery team for it or add a plugin even though making it a plugin won't be a good idea (they gave the example of having used a .live similar thing in their framework even before it was officially added to JQuery). Having your own framework gives you more control to the code. The disadvantage is that you need to reinvent the wheel regarding browser compatibility issues, etc. Moreover, if the development process is not good, your framework will bloat and will only increase the time to maintain it.


问:
Why do new programmers seem to ignore compiler error messages/runtime exception messages?
I think we’ve all seen this. Beginners ask questions on Stack Overflow that follow the basic outline...

I’m trying to do (very vague description of the goal) but it doesn’t work/I get an error/exception. Please help!

Isn’t it bizarre that so many of them seem to consider it unnecessary to paste the error message?

I wonder what the psychology of this is. What is it about error messages that makes people initially assume that they are useless and not worth paying any attention to?

The answer I’m looking for is not “they don’t understand the error message”. That doesn’t explain why they wouldn’t consider telling anyone else who might understand it.

答:
This applies more on IRC than online websites such as Stack Overflow, which is much more rare.

I think the reasoning behind it is that people feel better if they know that a person in particular is interested in their problem and is willing to help them. So they start by saying that they have a problem, but they don't go into details until someone asks them, because they are afraid that otherwise they won't get an answer anyways.

Sometimes (not in the case of compiler errors) this behavior actually makes sense. If I have a big complicated problem I'll make sure there is someone listening first before writing a long explanation that no one will read.


问:
Why is scanf called scanf? (Same for printf.)
I am just curious why in the C programming language the function to read formatted input was called "scanf" as opposed to "readf".  I assume it is derived from an earlier language, so in that case why was it named that way in the earlier language? (Recurse.)

Also, why "printf" rather than "writef"?  In languages other than C, why "print" or "write" rather than "display"?

答: "Read" actually requires comprehension of what you are looking at. As opposed to "Scan", which basically means to capture the input, then I will figure out what to do with it later.</p>


答:
This is an answer that is just "intuition". The name readf() assumes you already have something to read. But scanf() actually has two things to do: Wait for the user input (in other words, keep scanning the input buffer till it finds something) and then read it. Note that I'm not judging how the operating system actually implements that, I'm just describing the conceptual operation.

I know you'll tell me fscanf() and sscanf() do not match this idea, but I assume they are extensions to scanf() and thus it was just "normal" to give them the same name.

By the way, why is your name "Doug" and not "ABCD"?? :-P

Title: Why is scanf called scanf? (Same for printf.)

Body:
I am just curious why in the C programming language the function to read formatted input was called "scanf" as opposed to "readf".  I assume it is derived from an earlier language, so in that case why was it named that way in the earlier language? (Recurse.)

Also, why "printf" rather than "writef"?  In languages other than C, why "print" or "write" rather than "display"?


答:
Management has a big part behind the success of the Software Companies and Software Products which required to generate these environments. Let take an example of your project. If your software is developed on a large scale then if you do not manage your project requirements, process control, Test Builds etc then this is chances of failure.  so that Project Management exist.

I am  somewhat agree with @Stargazer712 that your statement point to
  the Money matters, But Check the following statement that i have
  gotten from Marc Hamilton's book on Software Development: Building
  Reliable Systems (Prentice Hall PTR, 1999, ISBN 0-13-081246-3). After
  looking all of these factors; my Opinion about your question is that
  Single Environment is not give you savings, it will make a long term
  process to complete the project/software. Distributed Environments
  will save Time and revenue  as i learned and seen in my experience
  that what happened with the start-up software companies from which i
  have start my carrier.

There are lots of articles demonstrate that what matter for success, Check this one Organizing for Successful Software Development

Each individual in an organization has certain skills, and these
  skills are typically measured against formal or informal performance
  metrics leading to rewards (compensation) as incentives for future
  performance. The people in an organization establish its culture—those
  behavior patterns and values that are generally recognized as being
  adopted.

A great set of software developers will struggle and ultimately fail to meet their goals if they have to spend all their time fighting against an inappropriate organizational structure.

Many a software startup begins life with no more than a couple of developers working out of a garage. Not much organizational structure is required at this point in a company's history, but organizational structure still exists. For instance, in 1977, when Bill Gates and Paul Allen formed their partnership and officially named it Microsoft, the company had minimal organizational structure. Fewer than a dozen employees worked at Microsoft's first office in Albuquerque, New Mexico, and everyone knew who was in charge. No complicated organizational charts were needed to figure out everyone's reporting structure. At the same time, all employees knew their role in the company and what they were trying to accomplish. This was because any organizational structure that was needed could be informally communicated between each of the employees.


问:
Best Upper Bound & Best Lower Bound of an Algorithm
I am studying for a final exam and I came past a question I had on an earlier test.

The questions asks us to find the minimum value in an unsorted array of integers. We must provide the best upper bound and the best lower bound that you can for the problem in the worst case.

First, in such an example, the upper and lower bound are the same (hence, we can talk in terms of Big-Theta). In the worst case, we would have to go through the whole list as the minimum value would be at the end of the list. Therefore, the answer is Big-Theta(n).

Is this a correct & good explanation?

答:
In the worst case, we would have to go through the whole list as the minimum value would be at the end of the list.

You have to go through the whole list in any case, because otherwise you do not know if the current minimum is indeed the absolute minimum. So the algorithm would always require n iterations.

The only exception is if you know bounds on the possible values, for example that the integers are all positive, and you have already found a 1 (then you can stop). That does not change the complexity discussion, though.

OwnerDisplayName: Nayefc

OwnerDisplayName: Thilo


问:
Dissection of Google indexing services
There are more than a few questions that hop into mind when someone thinks about Google's indexing services. Jeff Atwood wrote about them at The Elephant in the Room: Google Monoculture and Trouble In the House of Google.

I have two questions:

How does google index dynamic websites?

This site has dynamic pages, QUESTIONS, TAGS, USERS, BADGES, UNANSWERED, ASK QUESTION. The content of these pages is dynamically generated, therefore we access the dynamic content and not the physical files on the server. But how does Google shows every question of the site or other dynamic websites?

What does Google index and keep on its servers? Does it copy the complete page into its server or just the title, meta tags and body?

答:
How does google index dynamic websites?

Google, and every other search engine, use internet bots called web crawlers, to index websites. From the Wikipedia article:

A Web crawler is a computer program that browses the World Wide Web in a methodical, automated manner or in an orderly fashion. Other terms for Web crawlers are ants, automatic indexers, bots, Web spiders, Web robots, or—especially in the FOAF community—Web scutters.

Essentially, and without going into much detail, the web crawler visits this and every other website periodically and "sees" exactly the same as you see when you visit a site. It makes no difference if it's a static or a dynamic website, the crawler "sees" the rendered output as you see it in your browser.

The crawler visits high traffic sites many times per day and stores the indexing information each time, giving the impression that it has access to live data. There are a lot of open source web crawlers you can examine to get a more technical grasp of the concepts involved. Google's own web crawler is called Googlebot and there's an official faq page for it.

What does Google index and keep on its servers?

That kind of information is not fully publicly available. We can assume that they store and analyse everything that would make sense search-wise. There are a lot of talks and presentations on Google internals at various conferences but no definitive source on exactly what kind of information they store.

As to how the information is stored and analyzed, there is a good description of the Google index on the Wikipedia article on the Google platform:

Like most search engines, Google indexes documents by building a data structure known as inverted index. Such an index allows obtaining a list of documents by a query word. The index is very large due to the number of documents stored in the servers.

The index is partitioned by document IDs into many pieces called shards. Each shard is replicated onto multiple servers. Initially, the index was being served from hard disk drives, like it's done in traditional information retrieval (IR) systems.

And they don't just index website content, but also several types of binary files, anything that can be found on the web really.

Title: Dissection of Google indexing services


答:
jQuery is a library written in and for JavaScript. The idea is it makes all the difficult / tedious JavaScript things simple, thus speeding up development time and making your scripts much more likely to work cross-browser.

What makes jQuery preferable to use:

Fast

Lightweight JavaScript library

CSS 3 compliant

Supports many browsers.

The jQuery framework is extensible and handles DOM manipulations, CSS,
Ajax, events and animations.

JavaScript is a language whereas jQuery is a library written using
  JavaScript.

Here are reasons that makes JavaScript preferable to use rather than jQuery:

It loads the whole jQuery script library every time with the page. It is drawback for
peed/ fast query processing website.

Sometimes jQuery framework collapse/conflict with others frameworks.

If you are writing simple code for just selecting an element and show alter then native JavaScript is much better.

If operations are small and performed within few line of code of JavaScript  then it is not good to use jQuery.

Due to these reasons, I like to use JavaScript to avoid the jQuery framework. It is much better to learn JavaScript rather depending on such a library...

Even if you want to extend them, you need to write code in JavaScript. Which is also a big talk. Developers get dependent on these libraries, so to have control on projects, JavaScript is better than using frameworks.


问:
What is the supposed productivity gain of dynamic typing?
I often heard the claim that dynamically typed languages are more productive than statically typed languages. What are the reasons for this claim? Isn't it just tooling with modern concepts like convention over configuration, the use of functional programming, advanced programming models and use of consistent abstractions - all of which could be used in statically typed languages as well? Admittedly there is less clutter because the (for instance in Java) often redundant type declarations are not needed, but you can also omit most type declarations in statically typed languages that use type inference, without losing the other advantages of static typing. And all of this is available for modern statically typed languages like Scala as well.

So: what is there to say for productivity with dynamic typing that really is an advantage of the type model itself?

Clarification: I'm more interested in big / medium sized projects than in quick hacks. :-)

答:
I actually think it's a pretty close call. Both dynamic typing and static typing have their advantages.

Reasons for dynamic typing being more productive:

It's more concise - A lot of extraneous boilerplate code can be removed if everything is dynamically typed - type declarations, typecasting logic etc. All other things being equal, shorter code is marginally quicker to write, but more importantly it can be quicker to read and maintain (since you don't need to wade through many pages of code to get a grip on what is happening)

Easier to "hack" techniques such as duck typing and monkey patching can get you results very quickly (although might confuse you later on...)

More interactive - dynamic typing is arguably more suitable for interactive, REPL-like programming for rapid prototyping, real-time debugging of running program instances or even live coding.

Test cases can catch the runtime errors - assuming you are using TDD or at the very least have a good test suite, this should pick up any typing issues in your code.

Better polymorphism - dynamic languages are potentially more likely to encourage the creation of polymorphic functions and abstractions, which can boost productivity and code re-use. Clojure for example makes great use of dynamic polymorphism in its many abstractions.

Prototypes - prototype based data / object models are in my view more powerful and flexible than statically typed inheritance heirarchies. Dynamic languages are more likely to allow or encourage a prototype-based approach, Javascript being a great example.

Reasons for static typing being more productive:

Better design - being forced to think about the types of values in your software up front can push you towards cleaner, more logical solutions. (I say can - it's still possible to design really bad code...)

Better compile time checking - static typing can enable more errors to be caught at compile time. This is a huge advantage, and is arguably the best thing about statically typed languages overall.

Auto-completion - static typing can also give more information to the IDE so that auto-completion of code or documentation lookup is more effective.

Discourages hacks - you have to keep type discipline in your code, which is likely to be an advantage for long term maintainability.

Type inference - in some languages (e.g. Scala) this can get you many of the conciseness benefits of dynamic languages will still maintaining type discipline.

On average my conclusion (after many years of experience on both sides of the fence) is that dynamic typing can be more productive in the short term, but it ultimately becomes difficult to maintain unless you have very good test suites and testing discipline.

On the other hand, I actually prefer statically typed approaches overall, because I think the correctness benefits and tool support give you better productivity in the long term.


问:
How faster is an 'if' construct compared to an immediate 'if' statement (IIF) and when should I use it?
How does the traditional if statement compare with that of the immediate if statement (IIF, the one usually written as condition ? value_if_true : value_if_false) in terms of speed of execution?

Also, in what scenarios should we be ideally using the IIF?

答:
EDIT: WRONG: Most likely, there is no measurable difference in terms of speed.

CORRECT: Since IIf is a library function in VB, both truepart and falsepart are evaluated, so if one of those is expensive to evaluate but eventually not choosen, it might be much slower than a conventional If.

Therefore, you should be using it when it makes your code more compact and readable.

In many cases, using iif (or the ternary ?: operator in C-like languages) makes it possible to avoid introducing an intermediate variable (or code replication)

Consider:

```<code>A = B + C + IIf(D<=3, D, 3)
</code>```

vs.

```<code>If D<=3 Then
  E = D
Else
  E = 3
End If

A = B + C + E
</code>```

or

```<code>If D<=3 Then
  A = B + C + D
Else
  A = B + C + 3
End If
</code>```

Body:
EDIT: WRONG: Most likely, there is no measurable difference in terms of speed.

CORRECT: Since IIf is a library function in VB, both truepart and falsepart are evaluated, so if one of those is expensive to evaluate but eventually not choosen, it might be much slower than a conventional If.

Therefore, you should be using it when it makes your code more compact and readable.

In many cases, using iif (or the ternary ?: operator in C-like languages) makes it possible to avoid introducing an intermediate variable (or code replication)

Consider:

A = B + C + IIf(D<=3, D, 3)

vs.

If D<=3 Then
  E = D
Else
  E = 3
End If

A = B + C + E

or

If D<=3 Then
  A = B + C + D
Else
  A = B + C + 3
End If


问:
What's Microsoft's strategy on Windows CE development?
Lots of specialized mobile devices use Windows CE or Windows Mobile.

I'm not talking about smart phones here -- I know that Windows Phone 7 is Microsoft's current technology of choice here. I'm talking about barcode readers, embedded devices, industry PDAs with specialized hardware, etc... the kind of devices (Example 1, Example 2) where Windows Phone Silverlight development is not an option (no P/Invoke to access the hardware, etc.).

Since direct Compact Framework support has been dropped in Visual Studio 2010, the only option to develop for these device currently is to use outdated development tools (VS 2008), which already start to cause trouble on modern machines (e.g. there's no supported way to make the Windows Mobile Device Emulator's network stack work on Windows 7).

Thus, my question is: What are Microsoft's plans regarding these mobile devices? Will they allow native applications on Windows Phone, such that, for example, barcode reader drivers can be developed that can be accessed in Silverlight applications? Will they re-add "native" Compact Framework support to Visual Studio and just haven't found the time yet? Or will they leave this niche market?

答:
I think the roadmap of Windows CE is still clear, because there's Microsoft Windows CE 7, the next successor of Windows CE 6.x.

Frustatingly, they named the product officially as Microsoft Windows Embedded Compact 7, but they said it's because in line with Windows 7 releases, only now for embedded.

http://www.microsoft.com/windowsembedded/en-us/develop/windows-embedded-compact-for-developers.aspx

for Windows Embedded Compact 7:
http://www.microsoft.com/windowsembedded/en-us/develop/windows-embedded-compact-7-for-developers.aspx

I suggest you install VS 2008 for Windows CE 7 because VS 2008 support Windows CE5, CE6 and CE7 devices, and VS 2010 still can't support Windows CE devices.
This is from CE7 website:

NEW: Developing with Windows Embedded Compact 7 (formerly CE)

  Just released, Windows Embedded Compact 7 (the next generation of Windows
  Embedded CE) is based on the power of the Windows 7 platform. Compact
  7 is a real-time operating systems for a wide range of small-footprint
  consumer and enterprise devices. Development tools like Platform
  Builder, a Visual Studio 2008 plug in, provide an integrated
  development environment (IDE) that enables you to build applications
  and Windows Embedded CE operating system software in a familiar
  environment.

And Windows CE 7 has little relation with Windows Phone 7, because they share the same code base of basic services of Windows 7. There's also no detail information about Silverlight running on Windows CE 7, but I can assure you they support it:

http://www.microsoft.com/windowsembedded/en-us/develop/windows-embedded-compact-7-user-interface-development-gui-design.aspx


问:
What would you do if your client required you not to use object-oriented programming?
I am writing a program to simulate the activity of ants in a grid (PDF). The ant can move around, pick up things and drop things.

The problem is while the action of the ants and the positions of each ant can be tracked by class attributes easily (and we can easily create many instances of such ants) my client said that since he has a background in functional programming he would like the simulation to be made using functional programming.

To be clear, the original words from the client is "no class" only, but not "functional programming". So I assume he doesn't mean functional programming and I can do it imperatively. Additionally, I have no prior experience in functional programming.

However, I think it's beneficial to focus on this question being particularly about a functional programming requirement than just simply "do it imperatively."

How would you handle this situation? Would you try to persuade your client that using object-oriented programming is much cleaner, try to follow what he required and give him poor-quality code, or do something else?

答: Object-oriented code is not by definition cleaner, and conversely non-OO code is not by definition crappy.  While there does seem to be a rather obvious object-oriented mapping to this particular problem,  I would suggest that you try the functional programming approach anyway.  Give it your best shot, try to solve the problem in the best functional programming style that you can muster, and you might just learn something you didn't expect.</p>


答:
@ammoQ's answer needs something clarified, he means that the programmer doesn't have to intoduce a temporary variable, not the compiler. In all cases there'll be a temporary variable to hold the result of the conditional operator.

The real difference I know about (at least in C, C++ and Java) is that it's an expression, as opposed to a statement. In other words, it can act as an RValue (I mean a value that can be assigned to a variable). A statement doen't evaluate to a value. This makes their usage more convenient, such as:

```<code>int x = (y > 0 ? 1 : 2);
</code>```

which can't be written as

```<code>int x = if (y > 0) 1; else 2;
</code>```

But rather split into more than one line. This will be noticeable as the logic inside the if/else grows.

Title: How faster is an 'if' construct compared to an immediate 'if' statement (IIF) and when should I use it?

Body:
How does the traditional if statement compare with that of the immediate if statement (IIF, the one usually written as condition ? value_if_true : value_if_false) in terms of speed of execution?

Also, in what scenarios should we be ideally using the IIF?

Body:
@ammoQ's answer needs something clarified, he means that the programmer doesn't have to intoduce a temporary variable, not the compiler. In all cases there'll be a temporary variable to hold the result of the conditional operator.

The real difference I know about (at least in C, C++ and Java) is that it's an expression, as opposed to a statement. In other words, it can act as an RValue (I mean a value that can be assigned to a variable). A statement doen't evaluate to a value. This makes their usage more convenient, such as:

int x = (y > 0 ? 1 : 2);

which can't be written as

int x = if (y > 0) 1; else 2;

But rather split into more than one line. This will be noticeable as the logic inside the if/else grows.


答:
You mention that the client used to program in a functional language, maybe he has a reason that he requires you to write the code in a functional style. You should ask him why.

Maybe he intends to keep the code and maintain it himself later.

Moreover, I don't think the two choices are either do it OO-style or write crappy code like you mentioned. Sure writing functional code in an example like this could be harder, especially if you only have experience in object oriented languages, but if the client is willing to wait a bit longer for you to get up to speed with the functional style then it wouldn't hurt to ask him that.

I would ask him why he wants the code in functional style and if time isn't so much of an issue I would ask for some extra days to get up to speed with functional programming. (hurray for getting paid to learn!)

If all else fails explain that it would take you much less time to do it in a OO style.

Title: What would you do if your client required you not to use object-oriented programming?

Body:
I am writing a program to simulate the activity of ants in a grid (PDF). The ant can move around, pick up things and drop things.

The problem is while the action of the ants and the positions of each ant can be tracked by class attributes easily (and we can easily create many instances of such ants) my client said that since he has a background in functional programming he would like the simulation to be made using functional programming.

To be clear, the original words from the client is "no class" only, but not "functional programming". So I assume he doesn't mean functional programming and I can do it imperatively. Additionally, I have no prior experience in functional programming.

However, I think it's beneficial to focus on this question being particularly about a functional programming requirement than just simply "do it imperatively."

How would you handle this situation? Would you try to persuade your client that using object-oriented programming is much cleaner, try to follow what he required and give him poor-quality code, or do something else?


答:
Are you aware that functional programming doesn't just mean "programming without classes"?

See the Wikipedia article about it for the full schtick, but in short...

In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state.

Functional programming is a programming paradigm, just like OO is a programming paradigm.

If your background is in OO, then I can see how you'd want all your ants to be objects. On the other hand, if you're simulating an ant farm with millions of ants, OO and message-passing may become inefficient.

Luckily for you, Python has excellent tools for functional programming (the most important one being that functions are first-class objects.)

Python functional programming HOWTO


答:
There is a common misconception that "OO" is completely contrary to "functional". These things can go hand-in-hand very well. In your example, I guess an "Ant" can be modeled well as an abstract data type, which can be straight forward implemented using classes and objects. Transitions between "Ant states" can be naturally modeled using functions, which will lead you to a functional approach as far as your "Ant" class is an immutable type.

And be aware that "objects" can be interchanged by the functional concept of a closure, since objects are the poor man's closures are the poor man's objects are the ... ;-):

https://stackoverflow.com/questions/2497801/closures-are-poor-mans-objects-and-vice-versa-what-does-this-mean

https://stackoverflow.com/questions/501023/closures-and-objects


问:
When to use Constants vs. Config Files to maintain Configuration
I often fight with myself on whether to put certain keys in my web.config or in a Constants.cs class or something like this.

For example if I wanted to store application specific keys for whatever the case may be..I could store it and grab it from my web config via custom keys or consume it by referencing a constant in my constants class.

When would you want to use Constants over config keys?

This question really applies to any language I think.

答:
You can also simply use this design pattern: "convention over configuration".

http://msdn.microsoft.com/en-us/magazine/dd419655.aspx
http://en.wikipedia.org/wiki/Convention_over_configuration


答:
There is a theoretical view to this problem too:
A static type system is essentially a specialized theorem prover which only accepts the program when it can prove the type-correctness of it. All static type systems reject some valid programs because no decidable static type system is powerful enough to prove all possible type-correct programs.

One could argue that those programs that are not provable by a static typechecker are hacks and/or bad style, but if you already got a valid program and the typechecker doesn't accept it, it certainly is impairing your productivity in the short run.

Some cases where you might notice the type-checker getting in the way is with generic containers and co-/contravariance in arguments and return types.

Title: What is the supposed productivity gain of dynamic typing?

Body:
I often heard the claim that dynamically typed languages are more productive than statically typed languages. What are the reasons for this claim? Isn't it just tooling with modern concepts like convention over configuration, the use of functional programming, advanced programming models and use of consistent abstractions - all of which could be used in statically typed languages as well? Admittedly there is less clutter because the (for instance in Java) often redundant type declarations are not needed, but you can also omit most type declarations in statically typed languages that use type inference, without losing the other advantages of static typing. And all of this is available for modern statically typed languages like Scala as well.

So: what is there to say for productivity with dynamic typing that really is an advantage of the type model itself?

Clarification: I'm more interested in big / medium sized projects than in quick hacks. :-)


答:
jQuery, as any library or framework, adds another layer of bugs. I love it, but I've also lost a day looking for a bug that turned out to be in jQuery core and not my code (a rare occasion, but not that rare).

Other than that I don't find any other reason not to use it:

The overhead is minimal, especially if you go with the hosted Google version,

It helps less experienced Javascript developers write cleaner and more efficient code,

It's mostly cross-platform, which can be life saving when you have to deal with older browsers,

The huge gallery of plugins help me write prototypes in very short times,

The DOM makes sense,

blah blah blah...

BUT it should be never be used as a substitute of Javascript knowledge. If you don't know how to do it in pure Javascript, you may get away with a library initially but in the long run you are going to pay for it.

And of course there are all of us who've been locked in mortal combat with IE6 for quite a few years, and won't easily let go of our old school tricks in favour of a shiny new toy.


答:
How does google index dynamic websites?

"Crawler" is a generic term for any program (such as a robot or spider) used to automatically discover and scan websites by following links from one webpage to another. Google's main crawler is called Googlebot. Check out this list of Google Crawlers.

Today, most crawlers cannot index the entire dynamic page, but they will index most of the content on all the pages, and that is exactly the end result we are seeking.

After a page is crawled, the next step is to index its content. The indexed page is stored in a giant database, from where it can later be retrieved.

Essentially, the process of indexing is identifying the words and expressions that best describe the page and assigning particular keywords to the page. For a human it will not be possible to process such amounts of information but generally search engines deal just fine with this task.

Sometimes they might not get the meaning of a page right but if you help them by optimizing it, it will be easier for them to classify your pages correctly and for you to get higher rankings.

When a search request comes, the search engine processes it – i.e. it compares the search string in the search request with the indexed pages in the database. Since it is likely that more than one page (practically it is millions of pages) contains the search string, the search engine starts calculating the relevancy of each of the pages in its index with the search string.

For a list of ranking factors you can see Search Engine Ranking Factors and the  googlewebmastercentral blog. A good article regarding the indexing issue is "How to optimize a dynamic web site" that will clear you doubts regarding the indexing of dynamic websites.

What does Google index and keep on its servers?

From the Wikipedia article on Search Engine Index:

Search engine indexing collects, parses, and stores data to facilitate fast and accurate information retrieval. Index design incorporates interdisciplinary concepts from linguistics, cognitive psychology, mathematics, informatics, physics, and computer science. An alternate name for the process in the context of search engines designed to find web pages on the Internet is Web indexing.

Title: Dissection of Google indexing services

Body:
There are more than a few questions that hop into mind when someone thinks about Google's indexing services. Jeff Atwood wrote about them at The Elephant in the Room: Google Monoculture and Trouble In the House of Google.

I have two questions:

How does google index dynamic websites?

This site has dynamic pages, QUESTIONS, TAGS, USERS, BADGES, UNANSWERED, ASK QUESTION. The content of these pages is dynamically generated, therefore we access the dynamic content and not the physical files on the server. But how does Google shows every question of the site or other dynamic websites?

What does Google index and keep on its servers? Does it copy the complete page into its server or just the title, meta tags and body?


答:
A constant by definition is a memory location for a value that should not change (such as PI).

I assume you meant 'parameter' and not a constant

In addition to what have been said, note that exposing variables to user input from config file may harm the application.

When possible, don't expose values in config file without validating them in code to have a sanity check. Also, I suggest that you don't place business rules parameters (such as max. salary, etc.) in config files and don't use constants for those either. Such values should be stored in database with the appropriate table definitions so that some security is enforced when they are changed and you could automatically create versions of the data values (using stored procs or db logs). Of course, this depends on how sensitive your application is.

If you ever use config files to store data, make sure you version them.

Title: When to use Constants vs. Config Files to maintain Configuration

Body:
I often fight with myself on whether to put certain keys in my web.config or in a Constants.cs class or something like this.

For example if I wanted to store application specific keys for whatever the case may be..I could store it and grab it from my web config via custom keys or consume it by referencing a constant in my constants class.

When would you want to use Constants over config keys?

This question really applies to any language I think.


问:
How to deal with checked exceptions that cannot ever be thrown
Example:

```<code>foobar = new InputStreamReader(p.getInputStream(), "ISO-8859-1");
</code>```

Since the encoding is hardcoded and correct, the constructor will never throw the UnsupportedEncodingException declared in the specification (unless the java implementation is broken, in which case I'm lost anyway). Anyway, Java forces me to deal with that exception anyway.

Currently, it looks like that

```<code>try {
    foobar = new InputStreamReader(p.getInputStream(), "ISO-8859-1");
}
catch(UnsupportedEncodingException e) { /* won't ever happen */ }
</code>```

Any ideas how to make it better?

答: My habit is, just to be on the safe side, to put an assert into the catch block. Someone might change the contents of the try block later, and you do want to know if the code fails don't you?


答: If you are the only developer who will ever get to see this code then I'd say its fine, but if you are not then I would treat it as a real possibility or at least change the "won't ever happen" comment to something more useful.</p>

Title: How to deal with checked exceptions that cannot ever be thrown

Body:
Example:

```<code>foobar = new InputStreamReader(p.getInputStream(), "ISO-8859-1");
</code>```

Since the encoding is hardcoded and correct, the constructor will never throw the UnsupportedEncodingException declared in the specification (unless the java implementation is broken, in which case I'm lost anyway). Anyway, Java forces me to deal with that exception anyway.

Currently, it looks like that

```<code>try {
    foobar = new InputStreamReader(p.getInputStream(), "ISO-8859-1");
}
catch(UnsupportedEncodingException e) { /* won't ever happen */ }
</code>```

Any ideas how to make it better?


答:
Printf is "print - formatted". It has the same root as "print" in "printer", which is shorthand for "teleprinter", a synonym for "teletypewriter", and comes likely from the time when you used real TTYs for interacting with computers instead of monitors and keyboards.

Scanf is "scan - formatted", and matches the "print" paradigm, compare to the use of "scanner" in the context of OCR. Also, one could assume that read/write have been a pair of system calls for a long time, and in the same way as printf is distinct from write (2), there has been desire to separate scanf from read(2).