问:
What's the best documentation you produce and why?
I think it's safe to assume that for most programmers, producing documentation is not as fun as actually coding. I think it's also safe to assume that most good programmers recognize the need for useful documentation, and the code that they write is not an exception by any stretch of the imagination.

So, I'd like to know: what's the best documentation you produce (and source code doesn't count). Answer can be anything from comments to unit tests.

The bigger question is why is that the best documentation you produce?

答:
The documentation I write when I know someone else is going to have to take over my code. After an initial draft, I sit down with them and the document and go over the code. The document gets updated based on this review.

If the new person does the same for the third developer, it's probably pretty thorough. Then again, most 3rd versions are.


问:
How to avoid jumping to a solution when under pressure?
When under a particularly strict programming deadline (like an hour), if I panic at all, my tendency is to jump into coding without a real plan and hope I figure it out as I go along.  Given enough time, this can work, but in an interview it's been pretty unsuccessful, if not downright counter-productive.  I'm not always comfortable sitting there thinking while the clock ticks away.

Is there a checklist or are there techniques to recognize when you understand the problem well enough to start coding?  When is it most productive to think and design more vs. code some experiments and figure out the over-all design later?

Here is a list of techniques for taking a math test and another for taking an oral exam.  Is there is a similar list of techniques for handling a programming problem under pressure?

ANSWERS: I think this is a valid answer: How To Solve It.  I found that link as an answer to Steps to solve or approach towards a solution.  There were also some really good tips at Is thinking out loud during an interview really the best strategy?.  A great and concise argument for TDD is the first answer to TDD Writing code vs Figuring out the answer to a problem?.

答:
...my tendency is to jump into coding without a real plan and hope I figure it out as I go along.

I did this while at university.  It became a real problem and would typically result in rewriting code.  I began to address this by not writing code. I placed emphasis on thought about the problem.  With enough practice, I instinctively reach for my thoughts rather than a keyboard.

...in an interview it's been pretty unsuccessful, if not downright counter-productive. I'm not always comfortable sitting there thinking while the clock ticks away.

Within an interview, there must be a reasoned, well thought out implementation to a solution and that does not always come easy.  What you do not want to do is blurt out answers without thinking.  If you know the answer, quickly give it.  If you don't, rely on your thoughts to reason a solution.  Always indicate when you do not know and demonstrate how you would go about finding a solution.

Is there a checklist or are there techniques to recognize when you understand the problem well enough to start coding?

I would discourage such because you may rely on it rigidly. Rather, ask yourself if you understand the problem well enough to start coding.  How would you know?  Because when you reason your approach and then examine it, given your present knowledge of the language, it will make sense.  Always have a plan and approach.  Also remember that code is never finished and code that doesn't evolved will die so expect to return to your code often.

When is it most productive to think and design more vs. code some experiments and figure out the over-all design later?

You will want to know the over-all design and give thought to it.  Then you begin making the class structure and stubs.  Then review it again.  Does it make sense?  Coding experiments is great way to demonstrate something works well and should be used but not to be relied on to fashion or shape the code you write.

ContentLicense: CC BY-SA 3.0


问:
Can/should the Single Responsibility Principle be applied to new code?
The principle is defined as modules having one reason to change. My question is, surely these reasons to change are not known until the code actually starts to change?? Pretty much every piece of code has numerous reasons why it could possibly change but surely attempting to anticipate all of these and design your code with this in mind would end up with very poor code. Isn't it a better idea to only really start to apply SRP when requests to change the code start coming in? More specifically, when a piece of code has changed more than once for more than one reason, thus proving it has more than one reason to change. It sounds very anti-Agile to attempt to guess reasons for change.

An example would be a piece of code which prints a document. A request comes in to change it to print to PDF and then a second request is made to change it to apply some different formatting to the document. At this point you have proof of more than a single reason to change (and violation of SRP) and should make the appropriate refactoring.

答:
Yes, the Single-Responsibility-Principle should be applied to new code.

But! What is a responsibility?

Is "prints a report a responsibility"?
The answer, I believe is "Maybe.".

Let's try to use the definition of SRP as "having only a single reason to change".

Suppose you have a function that prints reports.
If you have two changes:

change that function because your report needs to have a black background

change that function because you need to print to pdf

Then the first change is "change the report style" the other is "change the report output format" and now you should put them in two different functions because these are different things.

But if your second change would have been:

2b. change that function because your report needs a different font

I would say both changes are "change the report style" and they can stay in one function.

So where does that leave us?
As usual, you should try to keep things simple and easy to understand.
If changing the background color means 20 lines of code and changing the font means 20 lines of code, make it two functions again. If it is one line each, keep it in one.


问:
Why is new product development always rushed?
If you are working on something new you have less than the required time to do it, and sometimes you are expected to work late, weekends etc (even when you are waiting on people who are not working those hours). I even had a boss once who came by and told me to make sure I had something to do on Saturday. This seems to be true even when no competitors are putting something similar on the market.

If you are working on feature enhancements or maintenance you are encouraged to take your time, review your options, study up on things, etc. Sometimes I even get the feel that you are expected by leadership to catch up on your fantasy football and analyze topics like Game of Thrones, Call of Duty, etc.

My question is: why not just take the extra time from the existing software development and spend it on the new projects that are starving for time?

答:
For new development, there are no customers yet to foot the bill, so the budget has to be allocated by upper management. And you may count yourself lucky if the upper management even asks for an estimation by the technical staff, let alone that they will allocate the budget accordingly. It is more likely that the budget allocation is based on their own, non-technical, gut-feeling of how hard it is to create a piece of software.

For enhancements and maintenance, there is usually a paying customer who can foot the bill and who pays for the work billed by the hour, so there is no incentive for the company to hurry with those enhancements or bug fixes (as long as they don't get so slow that the customers switch to the competition).


答:
A lot of times when you are working on something new, it just has to be "good enough".  Mistakes, bugs and such are often (though not always) tolerated more because ...

There is nothing else to compare it against.

There is a desire to get it out the door and start making some $$$.

More time may be devoted later to feature enhancements and maintenance because ...

The product is already generating a revenue stream.

There is something the enhancements and bug fixes can be compared against.

There is a desire not break what you already have (see #2) as it can jeopardize #1.

Sometimes mistakes from pushing it out the door have taught a lesson or two.

I'm sure there are other reasons, but those are the first that come to mind.

Hope this helps.

Title: Why is new product development always rushed?

Body:
If you are working on something new you have less than the required time to do it, and sometimes you are expected to work late, weekends etc (even when you are waiting on people who are not working those hours). I even had a boss once who came by and told me to make sure I had something to do on Saturday. This seems to be true even when no competitors are putting something similar on the market.

If you are working on feature enhancements or maintenance you are encouraged to take your time, review your options, study up on things, etc. Sometimes I even get the feel that you are expected by leadership to catch up on your fantasy football and analyze topics like Game of Thrones, Call of Duty, etc.

My question is: why not just take the extra time from the existing software development and spend it on the new projects that are starving for time?


问:
Keeping SQL Server DB Up to date in Team environment
We are working in a Visual Studio Environment using TFS.
When developers get the latest source code it includes a copy of the 'update' sql scripts for the database of the application.
The challenge is keeping our local copies of the DB up to date.

When changes are made to the DB by another developer, we are looking for a way to:

indicate to other developers that their version of the DB is out of date

indicate to other developers the order in which they should
run the update scripts

We are looking for suggestions. For point number 2, I have used numbers such as 01_DropCreate_TableX, 02_Create_StoreProcedure_X. etc

DH

答:
My solution is to have a schema version table in the database.

If the (max) version number defined in the scripts (I actually do this in code: see https://softwareengineering.stackexchange.com/a/142553/866 and variously on stackoverflow) doesn't match the max number in the database then you have a problem (my apps simply refuse to run if there's a mismatch - but you could be more flexible than that).

This is a simple (crude even!) solution but it works well for me. On a legacy system we've got even cruder - we have a table of applied scripts (from the point at which we got slightly smarter) with the scripts prefixed yyyy-MM-dd so they sort. Shortly we'll have another script to see which haven't been applied.

The key to me is being able to compare an actual schema version/list of scripts applied with an expected version/list of scripts.

There are now newer toys to do this sort of thing - EF Migrations seems to be getting close to the point where it will work wonders - but for now I have a pattern that works well for me.


问:
What is the etiquette of renaming an open source fork?
I want to fork on Github the TestNG java testing framework (Apache 2 license) so I can add/change some minor things to suit my needs.

It's unlikely that all of my changes would be approved in the main project or that other people would use my fork. This would in no way be a competition to the main project.

Now, in terms of naming, I want to change the artifact name (testng-mycompany) or the version (6.8.mycompany) so there's no confusion with the official version in my maven repository. Would this be considered poor etiquette? If yes, what is the best approach to distinguish your fork?

答:
Open Source projects are intended to be advanced. The great thing about open source projects is that they encourage outside collaboration. When you decide to fork a project you simply state that you have taken the initiative to produce your own "flavor" or "interpretation" of the project. Many teams will end up forking their own projects in order to expand the base of the project for multiple purposes.

Example: Webkit and Blink

As far as naming goes, you want to be as clear as possible. Basic nomenclature practices in development are rather ambiguous.

Go To: What "version naming convention" do you use?

If you were to fork you would want to state your "Name" and then convey exactly what version you are using.

I do not see a reason to fork unless you plan on taking the project in a fundamentally different direction than what was intended. I have found that, in most cases, the added features/modifications that I would propose offered a great learning opportunity from both directions. If anything I am with Dave on the idea of creating separate modules in order to promote modularity while preserving the integrity of the core project.


答:
What you are looking to do is do database migrations. There are a number of different tools out there that handle this in a number of ways. Given you already have a bunch of scripts that should be runned in order, I would start with RoundHouse as it can handle the legacy stuff you've got as it is just a sql script runner on serious steroids.

One protip for integrating it with the existing db -- the trick is to migrate a new "database" and then grab the roundhouse tables and insert them into production. Once you start shipping backups out to dev again it will have a copy of the roundhouse stuff so the migrations work. Moreover, you can also apply the migrations on production directly at that point and have all the benefits of the tool.

Title: Keeping SQL Server DB Up to date in Team environment

Body:
We are working in a Visual Studio Environment using TFS.
When developers get the latest source code it includes a copy of the 'update' sql scripts for the database of the application.
The challenge is keeping our local copies of the DB up to date.

When changes are made to the DB by another developer, we are looking for a way to:

indicate to other developers that their version of the DB is out of date

indicate to other developers the order in which they should
run the update scripts

We are looking for suggestions. For point number 2, I have used numbers such as 01_DropCreate_TableX, 02_Create_StoreProcedure_X. etc

DH


问:
What is the best way to load balance javascript applications?
I write a lot of javascript applications and in many different circumstances the browser will become unresponsive or give a "slow script" error. Even when following best practices, initializing large data sets, complex animation, or when too many event handlers fire at once, I have to include extra setTimeouts or requestAnimationFrames around script blocks to load balance them. Seems like there should be some standard way of managing the browser load for large javascript applications.

Any ideas? It seems like there must be JS application designers thinking about this, but I can find nothing on the web or on stack.

edit

I appreciate all the response. My question is not "How can I write efficient Javascript?" which seems to be the question the current responses are answering. My question is: How can I balance the load of multiple sequential threads of javascripts running in the same browser?

I am well aware of all the information posted in the responses so far and appreciate the posters, but I am looking for a framework or a design pattern that balances script execution in a browser. This question is common in many other languages and for devops, I am simply asking the same question for javascript.

答:
You shouldn't be writing synchronized JavaScript. JavaScript is single threaded in the browser. What you are doing is not load balancing - see Load Balancing.

What best practices are you using? JavaScript is pretty quick in modern browsers, and if you're using even the most simple of best practices, unless you're doing something incredibly complex you should be fine.


答:
You have a very short span of time in your hands.

Before talking about threads:

The DOM is slow

Really.

If your website is DOM-heavy, then find ways to offshore these manipulations. Use CSS3 transitions, use canvas for animations, avoid unneccessary paints, etc.

There are also techniques to make it faster, like DocumentFragments, using off-DOM elements, etc.

JavaScript runs in a single thread in the browser

This means your scripts have to be very quick if you want the user to not feel any form of lag.

You can, for example, break intensive calculations into small fragments, for (a simple) example:

```<code>function findMax(arr){
   var currentMax = -Infinity;
   var i=0;
   setImmidiate(function() doWork{
       if(arr[i] > currentMax){
           currentMax = arr[i];
       }
       i++;
       if(i< arr.length){
           setImmidiate(doWork);
       }
   });
   return currentMax;
};
</code>```

Wait, don't go yet! I lied! It's not really single threaded

JavaScript doesn't have to run single threaded in the browser any more! If you support modern browsers, you can use WebWorkers.. This will let you run intensive scripts in background threads and not interrupt the main program flow.

If you support modern browsers, this is probably the correct way to handle CPU intensive calculations.

WebWorkers let you use threads you're used to from other langauges but in a save (actor-system'ish) way. You can split work between workers and balance it just like you would in any other programming language.

Note web workers require IE10, Safari 4+, Opera 10.6 +, Chrome 3+ or Firefox 3.5+

One last thing

JavaScript is designed to perform asynchronous I/O, while this might not be what you're doing more often than not JavaScript performance issues might be the result of synchronous code where asynchronous code is appropriate. Synchronous event handling, blocking code, and more generally anything that isn't CPU intensive should take very little time any way and not require the use of 'the big guns' like web workers.

Title: What is the best way to load balance javascript applications?

Body:
I write a lot of javascript applications and in many different circumstances the browser will become unresponsive or give a "slow script" error. Even when following best practices, initializing large data sets, complex animation, or when too many event handlers fire at once, I have to include extra setTimeouts or requestAnimationFrames around script blocks to load balance them. Seems like there should be some standard way of managing the browser load for large javascript applications.

Any ideas? It seems like there must be JS application designers thinking about this, but I can find nothing on the web or on stack.

edit

I appreciate all the response. My question is not "How can I write efficient Javascript?" which seems to be the question the current responses are answering. My question is: How can I balance the load of multiple sequential threads of javascripts running in the same browser?

I am well aware of all the information posted in the responses so far and appreciate the posters, but I am looking for a framework or a design pattern that balances script execution in a browser. This question is common in many other languages and for devops, I am simply asking the same question for javascript.

Body:
You have a very short span of time in your hands.

Before talking about threads:

The DOM is slow

Really.

If your website is DOM-heavy, then find ways to offshore these manipulations. Use CSS3 transitions, use canvas for animations, avoid unneccessary paints, etc.

There are also techniques to make it faster, like DocumentFragments, using off-DOM elements, etc.

JavaScript runs in a single thread in the browser

This means your scripts have to be very quick if you want the user to not feel any form of lag.

You can, for example, break intensive calculations into small fragments, for (a simple) example:

function findMax(arr){
   var currentMax = -Infinity;
   var i=0;
   setImmidiate(function() doWork{
       if(arr[i] > currentMax){
           currentMax = arr[i];
       }
       i++;
       if(i< arr.length){
           setImmidiate(doWork);
       }
   });
   return currentMax;
};

Wait, don't go yet! I lied! It's not really single threaded

JavaScript doesn't have to run single threaded in the browser any more! If you support modern browsers, you can use WebWorkers.. This will let you run intensive scripts in background threads and not interrupt the main program flow.

If you support modern browsers, this is probably the correct way to handle CPU intensive calculations.

WebWorkers let you use threads you're used to from other langauges but in a save (actor-system'ish) way. You can split work between workers and balance it just like you would in any other programming language.

Note web workers require IE10, Safari 4+, Opera 10.6 +, Chrome 3+ or Firefox 3.5+

One last thing

JavaScript is designed to perform asynchronous I/O, while this might not be what you're doing more often than not JavaScript performance issues might be the result of synchronous code where asynchronous code is appropriate. Synchronous event handling, blocking code, and more generally anything that isn't CPU intensive should take very little time any way and not require the use of 'the big guns' like web workers.


答:
This is what we do, but we are PHP developers not VS so maybe Microsoft has a better approach, but the idea should be the same.

We keep a change log table in the database. Each time the update scripts execute this table is updated to reflect the current state of the database. It also keeps a history of changes (this allows you to spot customer database's that might of had special hotfixes installed that others don't have).

```<code>CREATE TABLE `changelogs` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `version` varchar(45) NOT NULL,
  `previous` varchar(45) NOT NULL,
  `log` text,
  `started` datetime DEFAULT NULL,
  `finished` datetime DEFAULT NULL,
  `created` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `created` (`created`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1$$
</code>```

There are two types of updates from source control that the developers will need to know about.

The update is redundant, meaning they can simply delete a record from their database change logs and re-run the updates. The updates don't require a critical point in the schema.

The update is dependant, and they must rollback the database to a stable version so the updates can bring it forward. The updates require a specific schema.

While customers may be running version 2.0.0 of the database. Developers may only have to rollback to 2.9.9 to test upgrading to 3.0.0 (beta). You can also have downgrade scripts that perform quick hacks to the database to make the upgrades safe to run.

The update process is basically any automated technique of your choice. We use a directory in each project that stores a list of SQL files. The directory contents look like this.

```<code>install.sql
update.txt
update-2.0.0.sql
update-2.0.1.sql
update-3.0.0.sql
hotfix-3.0.1.sql
</code>```

install.sql is our zero point entry script. It creates the database for new installs.

update.txt is our update guide for the deployment script, and the rest are SQL files to be executed.

The contents of the update.txt look like this.

```<code>#
# Defines the update mapping of which SQL files are executed.
# The order of this file isn't important, but do not create
# endless circular versions (i.e. update 3 to 4, then 4 down to 3).
#
# Usage for each line:
# [current_version]=update-[new_version].sql
#
3.3.14=update-3.4.0.sql

# DATE: 20130107 144921
3.4.0=update-3.4.1.sql
</code>```

The only value the deployment script understands is the first current_verion part. That equals a file. When the deployment script executes it reads what the current version is from the changelogs table, and then executes the SQL file that matches that version. This steps the database forward in the schema changes. This process repeats until there are no more matches in the update.txt file (order in the file isn't important).

This approach works fine for us. We can single out customers with hotfixes, but still migrate then to formal releases later. Even install small SQL change files to bring them up to date from their hotfit.

The only problem with this approach is that it requires discipline by the developer. We also separate this process by software module, rather than one large update directory per application. For each module we prefix the changelog table. So we have multiple tables called things like documents_changelog, and users_changelog. That has worked well for us since modules are shared across multiple applications.

Body:
This is what we do, but we are PHP developers not VS so maybe Microsoft has a better approach, but the idea should be the same.

We keep a change log table in the database. Each time the update scripts execute this table is updated to reflect the current state of the database. It also keeps a history of changes (this allows you to spot customer database's that might of had special hotfixes installed that others don't have).

CREATE TABLE `changelogs` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `version` varchar(45) NOT NULL,
  `previous` varchar(45) NOT NULL,
  `log` text,
  `started` datetime DEFAULT NULL,
  `finished` datetime DEFAULT NULL,
  `created` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `created` (`created`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1$$

There are two types of updates from source control that the developers will need to know about.

The update is redundant, meaning they can simply delete a record from their database change logs and re-run the updates. The updates don't require a critical point in the schema.

The update is dependant, and they must rollback the database to a stable version so the updates can bring it forward. The updates require a specific schema.

While customers may be running version 2.0.0 of the database. Developers may only have to rollback to 2.9.9 to test upgrading to 3.0.0 (beta). You can also have downgrade scripts that perform quick hacks to the database to make the upgrades safe to run.

The update process is basically any automated technique of your choice. We use a directory in each project that stores a list of SQL files. The directory contents look like this.

install.sql
update.txt
update-2.0.0.sql
update-2.0.1.sql
update-3.0.0.sql
hotfix-3.0.1.sql

install.sql is our zero point entry script. It creates the database for new installs.

update.txt is our update guide for the deployment script, and the rest are SQL files to be executed.

The contents of the update.txt look like this.

#
# Defines the update mapping of which SQL files are executed.
# The order of this file isn't important, but do not create
# endless circular versions (i.e. update 3 to 4, then 4 down to 3).
#
# Usage for each line:
# [current_version]=update-[new_version].sql
#
3.3.14=update-3.4.0.sql

# DATE: 20130107 144921
3.4.0=update-3.4.1.sql

The only value the deployment script understands is the first current_verion part. That equals a file. When the deployment script executes it reads what the current version is from the changelogs table, and then executes the SQL file that matches that version. This steps the database forward in the schema changes. This process repeats until there are no more matches in the update.txt file (order in the file isn't important).

This approach works fine for us. We can single out customers with hotfixes, but still migrate then to formal releases later. Even install small SQL change files to bring them up to date from their hotfit.

The only problem with this approach is that it requires discipline by the developer. We also separate this process by software module, rather than one large update directory per application. For each module we prefix the changelog table. So we have multiple tables called things like documents_changelog, and users_changelog. That has worked well for us since modules are shared across multiple applications.


答:
If a script is running slow (assuming client side code here), it generally isn't down to JS being slow. Your bottlenecks are far more likely to be found somewhere else. The notoriously slow DOM API, for example.

As soon as you talk about DOM manipulations (such as animation), you're almost certainly going to notice a drop in speed.

A lot of people have (and are continuing to) critique the DOM API for being badly designed, overly complex at times, and down-right slow.

The main issue with the DOM API is that it's not controlled by ECMA, as JavaScript is, but by W3. Simply put: client side JS is often 60-75% made up of DOM manipulations, but for those, JS relies on an API maintained and developed by a third party. I think it's pretty obvious that's just a recipe for slow-food.

Still, if you need to perform a lot of long and complex computations, a Worker allows you to (sort-of) spawn a background thread, which fires an event upon completion.

Another bottleneck that can be noticeable is the over-usage of libs/toolkits such as jQuery. These often aren't very modular in terms of allowing you to include only those bits you really need, and bring with them an additional overhead. Compare

```<code>document.getElementById('foo');//calls DOM API
</code>```

to

```<code>$('#foo');//calls jQuery init, a few if's and else's to make up what to do
          //then string is passed to querySelector (DOM API),
          //new jQ object is constructed (which also constructs an array)
          //return new jQObject
</code>```

At least, that's what sort of happened behind the scenes in jQuery.

While I'm on the subject of jQ: a lot of jQ code actually binds too many event listeners, bringing us to a third (and, for now, last) possible bottleneck.

Event listeners are checked in an infinite loop, as you probably well know. If you have 1 listener, you won't notice any loss in performance. If you bind a 1000 individual handlers directly to references to individual Nodes, you will. Each reference is kept in memory, all the handlers (fuction objects) are, too.

Event delegation isn't that hard and it can make the event loop a lot faster, as I have found out here

Body:
If a script is running slow (assuming client side code here), it generally isn't down to JS being slow. Your bottlenecks are far more likely to be found somewhere else. The notoriously slow DOM API, for example.

As soon as you talk about DOM manipulations (such as animation), you're almost certainly going to notice a drop in speed.

A lot of people have (and are continuing to) critique the DOM API for being badly designed, overly complex at times, and down-right slow.

The main issue with the DOM API is that it's not controlled by ECMA, as JavaScript is, but by W3. Simply put: client side JS is often 60-75% made up of DOM manipulations, but for those, JS relies on an API maintained and developed by a third party. I think it's pretty obvious that's just a recipe for slow-food.

Still, if you need to perform a lot of long and complex computations, a Worker allows you to (sort-of) spawn a background thread, which fires an event upon completion.

Another bottleneck that can be noticeable is the over-usage of libs/toolkits such as jQuery. These often aren't very modular in terms of allowing you to include only those bits you really need, and bring with them an additional overhead. Compare

document.getElementById('foo');//calls DOM API

to

$('#foo');//calls jQuery init, a few if's and else's to make up what to do
          //then string is passed to querySelector (DOM API),
          //new jQ object is constructed (which also constructs an array)
          //return new jQObject

At least, that's what sort of happened behind the scenes in jQuery.

While I'm on the subject of jQ: a lot of jQ code actually binds too many event listeners, bringing us to a third (and, for now, last) possible bottleneck.

Event listeners are checked in an infinite loop, as you probably well know. If you have 1 listener, you won't notice any loss in performance. If you bind a 1000 individual handlers directly to references to individual Nodes, you will. Each reference is kept in memory, all the handlers (fuction objects) are, too.

Event delegation isn't that hard and it can make the event loop a lot faster, as I have found out here


答: Aside from any specific techniques, modern browser dev tools all have JavaScript profilers. Switch them on and run through some tasks and see which functions are taking the most time. Attack each bottleneck one at a time.</p>


答:
I always start with understanding the requirements and looking for gaps in them that need answers.

Then I sketch (very roughly and on paper or a whiteboard) two or three possible solutions. Then I ask myself, "Is there anything else I need to know to implement any of these?"

Once I have an my initial questions (there are questions 100% of the time, if you have none, you haven't really looked at the requirement in depth.), I go back to the stakeholders to get my answers.

While I'm wating on their responses I consider my solutions and see if any are better than the others or would be better once I get the answers to the questions. For instance if the how soon do you need it questions is immediately, I might go for the one with the fastest development but leaving open a way to improve the design later. If they tell me performance is critical, then I look at the solutions and determine which one is more likely to perform better (these are guesses at this point, but informed ones generally). If a GUI is involved, I might make up a paper prototype of several differnt designs and get the stakeholders to look at them before I code anything (Usually they will see that they forgot to tell you about XYZ which is something that is central to the design!)

Once I get my answers I choose a rough design and then I make a list of all the things I will have to do to implement it. Then I start coding.

Title: How to avoid jumping to a solution when under pressure?

Body:
When under a particularly strict programming deadline (like an hour), if I panic at all, my tendency is to jump into coding without a real plan and hope I figure it out as I go along.  Given enough time, this can work, but in an interview it's been pretty unsuccessful, if not downright counter-productive.  I'm not always comfortable sitting there thinking while the clock ticks away.

Is there a checklist or are there techniques to recognize when you understand the problem well enough to start coding?  When is it most productive to think and design more vs. code some experiments and figure out the over-all design later?

Here is a list of techniques for taking a math test and another for taking an oral exam.  Is there is a similar list of techniques for handling a programming problem under pressure?

ANSWERS: I think this is a valid answer: How To Solve It.  I found that link as an answer to Steps to solve or approach towards a solution.  There were also some really good tips at Is thinking out loud during an interview really the best strategy?.  A great and concise argument for TDD is the first answer to TDD Writing code vs Figuring out the answer to a problem?.


问:
Is it possible to write a code without class methods, globals, and class variables?
I'm designing my own programming language for fun, and I'm thinking of making it fully Object-oriented (no statics, no globals, no class variables, no class methods), so I need to find a way to completely eliminate the needs of class methods, but, first, I need to make sure that I know all the problems that could only be solved by using class methods.

So, usually, class methods is used for creating helpers, and named constructors, yes? (Anything else?).

Currently, this is what I have to replace those with Object-oriented designs:

For example: the File helpers, I'm thinking of designing it like this:

```<code>class File
  def initialize(path)
    @path = path
  end

  def copy(destination)
    # Copy file from @path to destination
    # Then open destination path by creating new file instance
  end
end
</code>```

I'm actually using C, but I wrote the example in Ruby so it will be easier to understand.

No class methods, and you could chain it like this:

```<code>File.new("directory/file").copy("new_path").copy("other_path")
</code>```

If its too long, I could just drop the "new" method like what Python do:

```<code>File("directory/file").copy("new_path").copy("other_path")
</code>```

Math helpers can be replaced with mixins:

```<code>module Math
  def pow(value)
    @value = @value ** value
  end
end

class Integer
  include Math

  def initialize(value)
    @value = value
  end
end
</code>```

Call it like this:

```<code>Integer.new(100).pow(10).pow(10).pow(10)
</code>```

In case you still need some helpers:

```<code>module Helpers
  # Some block of codes
end

class Object
  include Helpers
end
</code>```

And now it's accessible everywhere.

To add more helpers, just modify the Helpers module:

```<code>module Helpers
  # Add more helpers
end
</code>```

We can create factory class instead of named constructor:

```<code>class Lexer
  def initialize(source)
    @source = source
  end
end

class LexerFactory
  def create_from_file(file)
    return Lexer.new(File.read(file))
  end

  def create_from_string(string)
    return Lexer.new(string)
  end
end

class Base
  def initialize(lexer_factory)
    @lexer_factory = lexer_factory
  end

  def lexer
    @lexer_factory
  end
end

lexer = Base.new(LexerFactory.new).lexer.create_from_file("directory/file")
</code>```

So my questions is: What am I missing? What you can't do without class methods, and class variables? What problems that could only be solved by using those?

答:
Is it possible to create a programming language or write object-oriented code without static/class methods/variables?  Absolutely.  Case study:  the Javascript programming language.  The key insight is that, if you squint a bit and hold your head at an awkward language, classes start looking like objects.  Special objects that do funny things when you poke them a certain way, sure, but objects nonetheless.  Add in a prototype system (as Javascript does), and suddenly you have not only the standard approaches for object-oriented code reuse, but many others too.  And all without special support for statics -- instead, just add a field to your "class" (which is actually an object) and you have a static/class variable.  Add a method to your "class" and you have a static/class method.

But what about globals?  Well, I'm not exactly sure what you mean by globals, so let's generalize and talk about free variables, or variables from some enclosing scope (including the global one, which is the "enclosing-est" scope there is :) ).  Can you imagine how hard it would be to write a program without free variables?  It's not fun :( , but people have tried and succeeded, and you might find these articles interesting.

When you ask:

So my questions is: What am I missing? What you can't do without class methods, and class variables? What problems that could only be solved by using those?

I think the real question you're getting at is "what are the minimal constructs needed to create a Turing-complete programming language?" or possibly "what are the minimal constructs needed to create a practical programming language?"

Those kinds of questions are awfully difficult to answer.  Like, PhD-worthy, which is why people spend their lives researching answers to them.  Perhaps learning about formal systems of computation, such as a lambda calculus, would help you to understand these questions better.  But ultimately, they're slippery slope questions, and nearly impossible to answer when you throw practical considerations (so that real people can use it) into the mix.  If you try hard enough, you can program without nearly every single modern programming construct -- does that mean it's all just sugar?


问:
What are the 'must know' Emacs commands?
I'm a fairly new convert to Emacs and I really love it as an editor, primarily because I keep finding new and super-useful commands. Are there any other programmer 'must known' commands missing from my list?</p>

```<code>M-x replace-string     - Find and replace a given string.
M-x goto-line          - Goto a specific line
M-x column-number-mode - Show the current column number in text bar
</code>```

答: M-x revert-buffer is one I use a lot.</p>

ContentLicense: CC BY-SA 2.5

Body: M-x revert-buffer is one I use a lot.


问:
Functional Programming: right ideas about concurrency and state?
FP proponents have claimed that concurrency is easy because their paradigm avoids mutable state.  I don't get it.

Imagine we're creating a multiplayer dungeon crawl (a roguelike) using FP where we emphasize pure functions and immutable data structures.  We generate a dungeon composed of rooms, corridors, heroes, monsters and loot.  Our world is effectively an object graph of structures and their relationships. As things change our representation of the world is amended to reflect those changes.  Our hero kills a rat, picks up a shortsword, etc.

To me the world (current reality) carries this idea of state and I'm missing how FP overcomes this.  As our hero takes action, functions amend the state of the world.  It appears to be every decision (AI or human) needs to be based on the state of the world as it is in the present.  Where would we allow for concurrency?  We can't have multiple processes concurrently ammending the state of the world lest one process base its outcomes on some expired state.  It feels to me that all control should occur within a single control loop so that we're always processing the present state represented by our current object graph of the world.

Clearly there are situations perfectly suited for concurrency (i.e. When processing isolated tasks whose states are independent of one another).

I'm failing to see how concurrency is useful in my example and that may be the issue.  I may be misrepresenting the claim somehow.

Can someone better represent this claim?

答:
Listening to a few Rich Hickey talks -- this one in particular -- alleviated my confusion.  In one he indicated that it is okay that concurrent processes may not have the most current state.  I needed to hear that.  What I was having trouble digesting was that programs would actually be okay with basing decisions on snapshots of the world that have since been superseded by newer ones.  I kept wondering how concurrent FP got around the issue of basing decisions on old state.

In a banking application we would never want to base a decision on a snapshot of state that has since been superseded by a newer one (a withdrawal occurred).

That concurrency is easy because the FP paradigm avoids mutable state is a technical claim that doesn't attempt to say anything about the logical merits of basing decisions on potentially old state.  FP still ultimately models state change.  There's no getting around this.


问:
How to handle product rebranding in code in a short time frame
We've all been there - a product feature is called "gold", and then a week before launch they decide it is to be called "platinum". Luckily, you had some nous about you so the UI code is easy to change.

But...what about all the variables and methods? Sure, you could change all these but what about the testing time?

Obviously Resharper or some other enterprise level refactoring tool may help but how do you sell a zero-value proposition to the business? After all, that text change on the front screen is just a 2 minute job - right?

答:
In this case I'd use a simple text search to find references to "gold", then use a refactor tool to rename the variables and methods. After that, running the test suite should confirm that there's no issues.

If renaming variables or methods causes issues, you should look at your workflow and find out why it's a problem. If it's very problematic, you could rename the method to the new name, then add a new method under the old name that just passes execution through to the new one, but is marked as deprecated.

Another option would be to add some notes to a general README or wiki, or whatever tool you use for knowledge sharing, and then as people work on different sections, they could rename them piecemeal


问:
is it wrong for my parent object to make assumption about child objects?
I have a simple domain with about 6 objects in the model.  For the most part they have a clear child/parent relationship with parent having multuple children.  I'm going to have all of them be immutable.  However, at some point I'll need to both fetch a set of all objects of a given type, and be able to fetch a specific object of a certain type by it's label.

I was going to have a model with some generic maps, and an abstract class for objects in the model.  Adding to the model sticks the object in my map, and asks for the parent objects and sticks those in the map etc.  Likewise a delete can delete all classes that called themselves children.  This way I can query for specific classes in a generic method without writing logic to hunt down each class.

Once I thought of this my next thought was rather I can use a similar framework to save CPU by looking up children in the same manner.  If I already have to store "these objects claimed x was a parent" to do the delete I can then say "give me children of X".  However, this assumes that X knows something about the other objects (what classes are effectively children of it).  I can put in type safty via reflection mostly; but is it brittle for one object to presume that certain other class is going to claim it as a parent and persumably be in the model as such?

TO clarify,  lets say I have a node and edge class.  My edge would report a node as it's parent.  My Node can then say "give me all Objects that claimed me as parent and are edges" and do logic on them; even though it never did anything to ensure that there were edges out there using it as a node.  Is this wrong?

Note, this is a small system.  I know that there are great abstraction patterns for huge systems, that I mostly don't think are worth the implementation cost or less explicit code for such a simple system.

答:
Like an interface, a non-final class is like a contract. Classes that derive from it are expected to satisfy the contract, regardless of what other features they support. Object-oriented languages do a lot to ensure that child classes do indeed satisfy the contracts specified by their base-classes, but in a few cases, the contract cannot be satisfied by the features of the language alone. </p>

<p>You should do what you can within your language of choice to ensure that the contract is satisfied (generics or templates might help here if they are supported). But I would say it's okay to treat the child classes as though they satisfy the contract if you are not able to guarantee it through the language. </p>

Body:
Like an interface, a non-final class is like a contract. Classes that derive from it are expected to satisfy the contract, regardless of what other features they support. Object-oriented languages do a lot to ensure that child classes do indeed satisfy the contracts specified by their base-classes, but in a few cases, the contract cannot be satisfied by the features of the language alone.

You should do what you can within your language of choice to ensure that the contract is satisfied (generics or templates might help here if they are supported). But I would say it's okay to treat the child classes as though they satisfy the contract if you are not able to guarantee it through the language.


问:
Please tell me I'm not alone (can't program on paper)
So I went to a job interview today. Long story short, the interviewers were delighted with my knowledge and experience, they were practically showing me to my new desk. Needless to say, what delighted them was a factual and unexaggerated description of things that I've actually worked on. But then suddenly, as I was getting ready to leave, one of the interviewers says to me: "Well, I know that this is probably too easy for someone with your experience, but because of protocol, we need you to complete a simple test".

No problem I thought... After this I get handed a piece of paper, a pencil (seriously wtf? who uses these primitive devices anymore?) and instructions telling me to code a function returning a Fibonacci number and another doing that with recursion. God I hate math.

I distinctly remember doing this precise exercise on 3rd semester of college. I probably nailed it back then, but not so much today. It took me about 40 minutes and I got close, but the functions didn't work. Ironically, I knew exactly why they were wrong and what erroneous result was being returned, but I just couldn't figure out how to fix them. Something about having to scratch graphite marks off a paper, just made me really, really nervous. Or perhaps it's that I'm self-conscious about having my math skills evaluated. I can't calculate a tip with a waiter watching because I'm slow with numbers, and it makes me feel embarrassed.

All of this got me thinking about this Coding Horror article. Apparently, 199 out of 200 applicants pretend to know how to code, but actually can't. I think there's something else going on here. I mean, none of you are going to hire me, I've no reason to lie to you when I tell you that I've coded much more complex things. And yet I couldn't code a simple function, not under those conditions. Has anyone else experienced this?

答:
All the time! I've done one test which consisted entirely of math questions - mainly fractions. I know historically, us coders have had a mathematical bent but do I really have to know how to calculate a root function using an exponential?

Another interview was a SQL paper. And when I say paper, I mean paper - it had a series of about 10 questions which had hand-written working and previous candidate's guesses on it. I could have dealt with the raw questions, but all the other hand written stuff just threw me for some reason.

If an interview result is based on a single question, they've failed not only you but themselves. A test should demonstrate what you can do, not what you can't.


问:
Abstract methods being used as static methods in java?
In an attempt to write some generic code I find myself putting, in my abstract class, a method that returns some static information about how the class should be treated.  This method doesn't use any state data and would be static, except that static abstract methods aren't allowed.  Is this a code smell?  is there something one should do to avoid this?

I haven't writtent he real code yet.  Here is a quick example, conceptually.  Little slopy programing wise to make to make it a quick read.  basically a way for the code to return information to the model, in this case, about how it should be treated within the generic functions of the model.  Assume the enum stored whatever configuration state in this case.

```<code>public abstract modelObject{

    public abstract ModelGroup getModelGroup;

    public final void addToModel(){
        Model.store(this.getModelGroup, this);
    }
}

public class myObject extends modelObject{
    public ModelGroup getModelGroup(){
        return ModelGroup.MyGroup;
    }
}

public class DifferentClass extends ModelObject{
    public ModelGroup getModelGroup(){
        return ModelGroup.differentGroup;
    }
</code>```

}

答:
Preferably, rather than providing properties that specify how the object should be treated, the class-dependent behavior should instead be encapsulated inside an abstract method. For example, use:

```<code>obj.doSomething(); // Abstract method - subclasses override with appropriate behavior
</code>```

instead of:

```<code>if(obj.getModelGroup() == ModelGroup.MyGroup) {
    doSomethingWith(obj); // Behavior specific to one subclass
} else {
    doSomethingElseWith(obj); // Behavior specific to another subclass
}
</code>```

Having said that, there are perfectly legitimate cases where implementers of a method might not use instance-specific state.

As an example, consider the java.sql.Driver interface (it's not an abstract class, but it easily could be). If you have a separate class for each type of driver, its methods probably don't require any instance-specific state. The jdbcCompliant, getMinorVersion, and getMajorVersion methods likely return hard-coded constants. The acceptsURL and connect methods likely have behavior that isn't instance-specific.

In short: it depends. Not using instance state in an abstract method implementation isn't inherently wrong; however, in some cases it may indicate that your code could benefit from being restructured.

Body:
Preferably, rather than providing properties that specify how the object should be treated, the class-dependent behavior should instead be encapsulated inside an abstract method. For example, use:

obj.doSomething(); // Abstract method - subclasses override with appropriate behavior

instead of:

if(obj.getModelGroup() == ModelGroup.MyGroup) {
    doSomethingWith(obj); // Behavior specific to one subclass
} else {
    doSomethingElseWith(obj); // Behavior specific to another subclass
}

Having said that, there are perfectly legitimate cases where implementers of a method might not use instance-specific state.

As an example, consider the java.sql.Driver interface (it's not an abstract class, but it easily could be). If you have a separate class for each type of driver, its methods probably don't require any instance-specific state. The jdbcCompliant, getMinorVersion, and getMajorVersion methods likely return hard-coded constants. The acceptsURL and connect methods likely have behavior that isn't instance-specific.

In short: it depends. Not using instance state in an abstract method implementation isn't inherently wrong; however, in some cases it may indicate that your code could benefit from being restructured.


答:
(and source code doesn't count)

On the contrary, production code is the only truly accurate documentation you have. It describes exactly what your program does. Everything else: design documents, diagrams, code comments... can be misleading.

That's not to say there isn't value in all of those things. There is a great deal of value in many of them. But they all suffer the same problem. They are extrapolations of what the code actually does. As such, they will always be prone to inaccuracy.

Even unit tests are not immune to this. A unit test that isn't run can quickly become out of sync with the production code its supposed to test. And entire books have been written on how to write good tests. Which implies that it is just as easy to write bad ones.

That is why there is such a focus on clear, readable code in Agile methodologies. Knuth refers to it as literate programming. Writing code so others can read it and not just the compiler. Everything else just points to the code.

Title: What's the best documentation you produce and why?

Body:
I think it's safe to assume that for most programmers, producing documentation is not as fun as actually coding. I think it's also safe to assume that most good programmers recognize the need for useful documentation, and the code that they write is not an exception by any stretch of the imagination.

So, I'd like to know: what's the best documentation you produce (and source code doesn't count). Answer can be anything from comments to unit tests.

The bigger question is why is that the best documentation you produce?


问:
OOP principles and method names
```<code>class Boxer:

    def punch(self, punching_bag, strength):
        punching_bag.punch(strength)

class PunchingBag:

    def punch(self, strength):
        print "Punching bag punched with strength", strength

boxer = Boxer()
punching_bag = PunchingBag()

boxer.punch(punching_bag, 2)
</code>```

No doubts that punch is a good method name in case of a boxer.
But is name punch also good for the method of punching bag?
In both cases I mean punch as a command (i.e. do punch).

答: It is matter of taste, I think. Punching bag's punch() method is at least consistent with file.close() or frame.move() in sense of experiencing action on itself. Greater question would be, why Boxer does have punch(something) method at all?

Title: OOP principles and method names


答:
I agree that "punch" is a good method name for the Boxer class, as (with some tweaking) it could be reused against other objects. It also accurately describes that an object of a class is doing an action on another object. Though, I would rename the method to "doPunch", to more clearly demonstrate the relation.

For the PunchingBag class however, I find the method name to be either too vague or a little inaccurate of what is happening in the method. When I see "punch", I think that something is punching something else. However, in here, the PunchingBag object is reacting to a punch from an object (in this case, a Boxer object). So, I would rename the method here to "isPunched" to illustrate that the object is reacting to a punch.

Though, this is my interpretation of how I would name the methods. It's all a matter of taste and which standards you are following.

Title: OOP principles and method names

Body:
```<code>class Boxer:

    def punch(self, punching_bag, strength):
        punching_bag.punch(strength)

class PunchingBag:

    def punch(self, strength):
        print "Punching bag punched with strength", strength

boxer = Boxer()
punching_bag = PunchingBag()

boxer.punch(punching_bag, 2)
</code>```

No doubts that punch is a good method name in case of a boxer.
But is name punch also good for the method of punching bag?
In both cases I mean punch as a command (i.e. do punch).


答:
is this the first time in your life to program on paper??
well in my university they force us to program on paper in final exams...
well writing code in paper is the same if you wrote it on IDE. i see it only demonstrates that you can write the code yourself without any help (they say that they want to test if we understand the concept or not) and they probably want to check how many mistakes you are going to do in this code.</p>

Title: Please tell me I'm not alone (can't program on paper)

Body:
So I went to a job interview today. Long story short, the interviewers were delighted with my knowledge and experience, they were practically showing me to my new desk. Needless to say, what delighted them was a factual and unexaggerated description of things that I've actually worked on. But then suddenly, as I was getting ready to leave, one of the interviewers says to me: "Well, I know that this is probably too easy for someone with your experience, but because of protocol, we need you to complete a simple test".

No problem I thought... After this I get handed a piece of paper, a pencil (seriously wtf? who uses these primitive devices anymore?) and instructions telling me to code a function returning a Fibonacci number and another doing that with recursion. God I hate math.

I distinctly remember doing this precise exercise on 3rd semester of college. I probably nailed it back then, but not so much today. It took me about 40 minutes and I got close, but the functions didn't work. Ironically, I knew exactly why they were wrong and what erroneous result was being returned, but I just couldn't figure out how to fix them. Something about having to scratch graphite marks off a paper, just made me really, really nervous. Or perhaps it's that I'm self-conscious about having my math skills evaluated. I can't calculate a tip with a waiter watching because I'm slow with numbers, and it makes me feel embarrassed.

All of this got me thinking about this Coding Horror article. Apparently, 199 out of 200 applicants pretend to know how to code, but actually can't. I think there's something else going on here. I mean, none of you are going to hire me, I've no reason to lie to you when I tell you that I've coded much more complex things. And yet I couldn't code a simple function, not under those conditions. Has anyone else experienced this?


问:
Future of web development - Front-end > Back-end development?
People used to say it's "better"/"Make more money" to do back-end programming (PHP, asp.net) instead of front-end(HTML, javascript) for web development.

But I notice that HTML5, CSS3, WebGL, Javascript are gaining importance.  We can even use HTML5, CSS3 and JAVASCRIPT for building mobile web applications(For both iphone/android) and even Windows 8 applications in the future!

Does it mean new web developers should now focus on front-end development instead of server-side development?

答:
You need to know both. Where would you even know where to start if you didn't know how a database worked? If you don't know how your end customer will view your data then your just spitting out UN-imaginitive code that will be clunky to use.

HTML5/CSS3 : Learn it, its literally how the world views information

Javascript/Jquery: Learn it, Its how the world interacts with information

PHP/MYSQL: Learn it: Its how the world puts information places

I do primarily front end work: which is nothing like it was 2 years ago (we live in exciting times) Honestly though with node.js and the way UX/UI has developed over the last 5 years (from nothing to really putting a focus on the user) the lines are so blurred its hard to figure out which side is up.

Learn the trinity, they were built to communicate with one another! (well not technically, but put enough duct tape on anything and you have yourself a house :)


问:
Why do some programmers categorize C, Python, C++ differently? - regarding level
I am taking an introductory course on python and the instructor says that python is a high level language and C and C++ are low level languages. It's just confusing. I thought that C, C++, Python, Java, etc were all high level languages. </p>

<p>I was reading questions at stackoverflow on C, C++, etc and they all seem to refer to those languages as high level. It seems to me that some programmers use those terms interchangeably. </p>

答:
Think of this in terms of a sliding scale, from LOW-level languages all the way through to HIGH-level languages. As a language moves up the scale, from LOW to HIGH, the language provides more and more abstraction from the specific interface with the computer.

LOW-level languages are written to explicitly direct the computer - think machine code and assembly code.

HIGH-level languages attempt to abstract away the nitty-gritty details (particularly memory allocation and release of memory). The idea is to provide a more "natural" interface to programming and hopefully allow the programmer to focus on design and production.

These days, C is regarded as a LOW-level language. It still has some significant abstractions from machine code and assembly code, so is technically 'higher' than these. However, it does still provide direct memory addressing and not provide garbage collection. So these are details a programmer must design for.

Compare this to other languages such as Python, Ruby or Haskell and you have a much more obscure interface. These languages have large libraries of code that abstract away most of the computer command. Ever wondered what happens to a variable in Python when you leave the local scope of a function, or delete it? Probably haven't right? And that is because in a HIGH-level language you don't have to! They look after the memory allocation / release for you.

HIGH-level languages have the advantage of function. They allow us to design and develop freely (and safely!).

LOW-level languages have the advantage of speed in most cases. There is a cost to interpreting HIGH-level code. Plus, it is kinda cool to write something in 'computer speek'.

Hope this helps


问:
When should I care about performance?
For the longest time in places like Java's IRC channel, SO, and other places I've been told something along the lines of "Worry about how the code looks and its readability/understandability now, and performance later if absolutely necessary". So for the longest time, I haven't really been OCD about performance for my small desktop or web apps, just removing the obviously inefficient.

Most responses are "What about scalability?". Thats a legitimate point, but if my app was only built to parse, say, files 10,000 lines long, should I make my code a mess for the small percentage of people that are going to shove in a 1,000,000 line file?

My main question is when should I trade the easy but somewhat inefficient ways of doing tasks for big giant complicated beasts that do things extremely quickly but destroy any possible ways of upgrading and make the code excessively difficult and prone to rewriting anyway by the next developer?

答:
Worry about performance when it becomes a problem.

If you write a small app to process 10,000 line files and you get a 1,000,000 line file every 100th file, it probably doesn't matter that it takes longer to process that one file. However, if you are regularly getting files that are 5-10 times larger than initially and your application is taking too long to do its job, then you start profiling and optimizing.

Now, I said "too long to do its job". That is up to the user or sponsoring organization to decide. If I'm doing a task and it takes me 5 minutes to do something when it took me 3 without the software or with a different tool, I'd probably file a bug report or maintenance request to have that improved.

If you are the user, how long you want your software to take to do its job is up to you - only you can decide if you want it done faster or if you are willing to wait longer to have more readable code.

Title: When should I care about performance?


答:
High level and low level are relative terms so the usage has changed over time. In the 70s UNIX made waves because it showed that an operating system could be written primarily in a high level language: C. At the time C was considered high level as in contrast to assembler.

Nowadays C is considered a low level language because neither the language nor the standard libraries provide any of the bread and butter data structures like vectors, dictionaries, iterators, and so on. You can have all those structures in a C program, but you'll end up writing them yourself. Python, Java, etc. are high level relative to C because many of those standard data structures are built in to the language or are part of the standard libraries. Having those right out of the box makes it easier to program at a more abstract level.

C is low level in a 2nd sense: it enables direct manipulation of the computer hardware (at least as direct as the OS will allow). The most common implementations of Python, Java, etc. are at least one step further removed from the hardware because they run in a VM. If you want to manipulate the hardware from Python you'll have write an extension to the Python VM, usually in C or C++.

C++ is an odd case. It provides tons of nice data structures as part of the standard library, but it also allows low-level manipulation of the hardware.

Title: Why do some programmers categorize C, Python, C++ differently? - regarding level

Body:
I am taking an introductory course on python and the instructor says that python is a high level language and C and C++ are low level languages. It's just confusing. I thought that C, C++, Python, Java, etc were all high level languages. </p>

<p>I was reading questions at stackoverflow on C, C++, etc and they all seem to refer to those languages as high level. It seems to me that some programmers use those terms interchangeably. </p>


答:
When faced with the dreaded 'program on paper' phase of an interview, I often ask something along the lines of "Can you set me up with an Ubuntu machine running in a VM where I can install {perl, Python, PHP, whatever} and {eacs, vim, yadda, yadda}?   You can return to a snapshotted state when I am done.

No one has ever responded with a yes.


答:
You have two different messages: one to command an object to punch and one to inform an object that it was punched. Consider that a Boxer object is likely going to need to respond to both. Differently. That's a really good reason to give them different names.

My inclination would be to keep punch(boxer, object, strength) and rename the opposite method to punched. You could call it handle_punch or something like that but then it's still ambiguous whether it's to handle a punch command or the notification that it got punched.

Title: OOP principles and method names


问:
Is there a name for the school of thought behind writing tests?
Essentially it is a branch of software engineering but SE itself is too large an umbrella.  I was curious if there was a title for the knowledge base that encompasses TDD, BDD, mocks/stubs/spys, unit tests vs. integration tests, code coverage, etc.  </p>

答: You know that's a good question. I think that TDD and its ilk falls under the "Agile" umbrella. The concepts certainly were introduced by Agile proponents as means of providing a safety net that enables the other practices of Agile development.</p>


问:
What's the next level of abstraction?
Since programming languages initially only used lines of code executed sequentially, and it evolved into including functions which were one of the first levels of abstraction, and then classes and objects were created to abstract it even further; what is the next level of abstraction?

What's even more abstract than classes or is there any yet?

答:
I am surprised nobody has mentioned category theory.

The most fundamental unit of programming is the function which is based on types. Functions are usually denoted as f: A -> B, where A and B are types. If you put these things, which I'm calling types and functions, together in the right way you get something called a category. You don't have to stop at this point.

Take these things, categories, and ask yourself what would be the correct way to relate them to each other. If you do it right you get something called a functor which goes between two categories and is usually denoted as F: C -> B. Once again you don't have to stop.

You can take all functors and put them together in the right way and if you do things just right you start to wonder how to relate two functors to each other. At this point you get something called a natural transformation, mu: F -> G, where F and G are functors.

My knowledge at this point gets fuzzy but you can continue to do this and keep climbing the ladder of abstraction. Objects and classes don't even come close to describing how high you can climb up the abstraction ladder. There are many languages that can express the above concepts computationally and the most prominent of those languages is Haskell. So if you really want to know what abstraction is really about then go learn some Haskell or Agda or HOL or ML.

Title: What's the next level of abstraction?


答:
High-level vs. low-level is not a black-and-white thing, but a continuous scale. The terms are used to describe how close a programming language is to the hardware; the higher the level, the more it abstracts the hardware away.

The lowest level, obviously, is binary machine code - it is the exact representation the OS loads and feeds to the CPU. Assembly is the first level of abstraction built on top of it: instead of binary code, one writes mnemoics, human-readable symbolic codes that represent binary machine instructions. This is what people used for systems programming before UNIX.

C is the next step up in the abstraction chain, bundling common patterns into flow control constructs and abstracting machine-specific instructions into platform-agnostic syntax, and this last abstractions was one of the major factors that made UNIX both revolutionary and highly successful, because it meant that the same code could be compiled for any platform without any major changes.

C++ adds another layer of abstractions: it adds classes (abstracting vtables and context passing into an OOP syntax), new and delete (bundling memory allocation and variable initialization into a single construct), compile-time type checking, templates (type-safe compile-time metaprogramming), and a bunch of compile-time syntax conveniences like namespaces, function and operator overloading, etc.

Python takes another big step away from the hardware. C++ still gives the programmer full control over memory allocation, and allows for direct manipulation of RAM; Python takes care of memory management for you. Additionally, instead of compiling your code to all-native machine instructions, it runs it against a virtual machine; this carries a performance penalty (which can sometimes be hefty, but usually isn't something to worry about), but it also allows for neat things that would be tricky in C++ and excruciatingly hard in C, such as manipulating functions and classes at run time, getting the names of arbitrary objects at run time, instantiating classes by name at run time, monkey-patching, etc. etc.

So when people divide languages into "high level" and "low level" ones, they draw an arbitrary line somewhere, and that line isn't always the same. In 1970, the line was between assembly and C (abstracting away platform-specific machine instructions being the decisive factor); in 1987, it may have been somewhere between C and C++; today, it may be between C++ and Java (with automatic memory management as the decisive factor).

Long story short: high-level-ness is a sliding scale, and for the three languages you mention it's C < C++ < Python.


答:
Software quality assurance (SQA) is probably a good term to use. A good discussion of of the different relevant practices may be found here.

SQA "examines and changes the software engineering process itself to reduce the number of faults that end up in the delivered software" (Wikipedia_software_testing). It is concerned with improving the software development process to reduce the 'defect rate', and this includes practices such as BDD and TDD.

Title: Is there a name for the school of thought behind writing tests?

Body: Essentially it is a branch of software engineering but SE itself is too large an umbrella.  I was curious if there was a title for the knowledge base that encompasses TDD, BDD, mocks/stubs/spys, unit tests vs. integration tests, code coverage, etc.  </p>


答:
A good rule of thumb is that method names should be verbs or predicates such that the object you call them on (self in standard Python convention, this in most other languages) becomes the subject.

By this rule, file.close is kind of wrong, unless you go with the mental model that the file closes itself, or that the file object doesn't represent the file itself, but rather a file handle or some sort of proxy object.

A punching bag never punches itself though, so punchingBag.punch() is wrong either way. be_punched() is technically correct, but ugly. receive_punch() might work, or handle_punch(). Another approach, quite popular in JavaScript, is to treat such method calls as events, and the convention there is to go with the event name, prefixed with 'on', so that would be on_punched() or on_hit(). Alternatively, you could adopt the convention that past participles indicate passive voice, and by that convention, the method name would be just punched().

Another aspect to consider is whether the punching bag actually knows what hit it: does it make a difference whether you punch it, beat it with a stick, or run into it with a truck? If so, what is the difference? Can you boil the difference down to an argument, or do you need different methods for different kinds of received punishment? A single method with a generic parameter is probably the most elegant solution, because it keeps the degree coupling low, and such a method shouldn't be called punched() or handle_punch(), but rather something more generic like receive_hit(). With such a method in place, you can implement all sorts of actors that can hit punching bags, without changing the punching bag itself.

Title: OOP principles and method names


问:
Is there any situation when there's no alternative to instanceof?
It seems to me that instanceof comes from the land of functional programming and is a watered down version of pattern matching and that the OO altenative to it should be dynamic dispatching.

In OO languages (think Ruby), is there any situation where instanceof is the only solution? I can't think of any myself, especially in Ruby where you can patch any class with any methods you like.

答:
The usual argument for avoiding instanceof is "Instead of checking the type of a thing to decide on an action, you should make that action a method of that thing, and use inheritance to ensure that every thing automatically does the right thing." In other words, use the method look-up mechanism built into the language rather than program your own.

However, that usually is restricted to single dispatch: selecting an action based on the exact type of one participant. If there are two or more participants with varying types, it simply doesn't work, because most languages only have single dispatch built in. You can sometimes rearrange things so that the two participants become arguments to a method on a third one and use method overloading, which does support selection based on several parameter types, but (again, usually) only when the alternatives aren't subtypes of each other. It may also also be resolved at compile time rather than at run time, which subtly changes the semantics of your program.

That is by no means the only thing that instanceof makes possible, but in my view the most relevant one.


答:
Not really, no. In a language that supports interfaces (either explicitly, or in the form of multiple inheritance with pure virtual classes, like C++), you can always use the following pattern:

```<code>interface Fooable {
    void foo();
}

abstract class BaseBaz {
    public abstract Fooable asFooable();
}

class BazOne extends BaseBaz {
    public Fooable asFooable() { return null; } // not a Fooable!
}

class BazTwo extends BaseBaz implements Fooable {
    public void foo() { Console.print("I am teh foobar!"); }
    public Fooable asFooable() { return this; }
}

// --- snip ---

void runFooOnBaz(Baz baz) {
    Fooable fooable = baz.asFooable();
    if (fooable == null)
        throw new NotFooableException();
    fooable.foo();
}
</code>```

That is, you approach each object by interface, and give the base class a method to return you the object by interface if possible. (There is probably a name for this pattern, but I don't know it - if anyone knows, feel free to edit.)

In a duck-typing language like Python, you'd go a different route: rather than asking whether the object inherits from a given class, you just pretend it does and prepare for failure:

```<code>class BazOne(object):
    pass

class BazTwo(object):
    def foo():
        print "I am teh foobar!"

def runFoo(baz):
    try:
        baz.foo()
    except AttributeError:
        raise NotFooableError()
</code>```

However, the latter isn't always possible; reasons as to why not include:

You might rely on more than one method, and the first call has side effects that you cannot allow unless the second method also exists. Inspecting the object instead of having it run into the exception can usually solve this, but it's not necessarily very pretty.

You might have to decide on how to treat the object in a way that does not depend on a particular method; for example, you may want to treat unicode and string objects differently.

The objects might implement a method of the same name, but with different meanings - hero.save(hostage) and file.save(filename) are completely unrelated things, but the method names happen to collide, so just checking whether a method called save exists can yield false positives.

And then there's the situation where you have to decide on a code path based on more than one object; you can certainly work your way out using the self-describing method approach, or by testing relevant attributes of all the objects, but sometimes, instanceof is just easier to write, more readable, and more concise, in other words, the pragmatic choice.

Title: Is there any situation when there's no alternative to instanceof?

Body:
It seems to me that instanceof comes from the land of functional programming and is a watered down version of pattern matching and that the OO altenative to it should be dynamic dispatching.

In OO languages (think Ruby), is there any situation where instanceof is the only solution? I can't think of any myself, especially in Ruby where you can patch any class with any methods you like.

Body:
Not really, no. In a language that supports interfaces (either explicitly, or in the form of multiple inheritance with pure virtual classes, like C++), you can always use the following pattern:

interface Fooable {
    void foo();
}

abstract class BaseBaz {
    public abstract Fooable asFooable();
}

class BazOne extends BaseBaz {
    public Fooable asFooable() { return null; } // not a Fooable!
}

class BazTwo extends BaseBaz implements Fooable {
    public void foo() { Console.print("I am teh foobar!"); }
    public Fooable asFooable() { return this; }
}

// --- snip ---

void runFooOnBaz(Baz baz) {
    Fooable fooable = baz.asFooable();
    if (fooable == null)
        throw new NotFooableException();
    fooable.foo();
}

That is, you approach each object by interface, and give the base class a method to return you the object by interface if possible. (There is probably a name for this pattern, but I don't know it - if anyone knows, feel free to edit.)

In a duck-typing language like Python, you'd go a different route: rather than asking whether the object inherits from a given class, you just pretend it does and prepare for failure:

class BazOne(object):
    pass

class BazTwo(object):
    def foo():
        print "I am teh foobar!"

def runFoo(baz):
    try:
        baz.foo()
    except AttributeError:
        raise NotFooableError()

However, the latter isn't always possible; reasons as to why not include:

You might rely on more than one method, and the first call has side effects that you cannot allow unless the second method also exists. Inspecting the object instead of having it run into the exception can usually solve this, but it's not necessarily very pretty.

You might have to decide on how to treat the object in a way that does not depend on a particular method; for example, you may want to treat unicode and string objects differently.

The objects might implement a method of the same name, but with different meanings - hero.save(hostage) and file.save(filename) are completely unrelated things, but the method names happen to collide, so just checking whether a method called save exists can yield false positives.

And then there's the situation where you have to decide on a code path based on more than one object; you can certainly work your way out using the self-describing method approach, or by testing relevant attributes of all the objects, but sometimes, instanceof is just easier to write, more readable, and more concise, in other words, the pragmatic choice.


问:
Retrieving maximum value from a range in unsorted array
I have an unsorted array. I have queries in which I give a range and then the maximum value from that range has to returned.
For example:

```<code>array[]={23,17,9,45,78,2,4,6,90,1};
query(both inclusive): 2 6
answer: 78
</code>```

Which algorithm or data structure do I construct to quickly retrieve maximum value from any range. (There are a lot of queries)

EDIT:
This is indeed a simple version of the actual problem. I can have the array size as large as 100000 and the number of queries upto 100000. So I definitely require some preprocessing which'll facilitate a fast query response.

答:
I think you could construct some kind of binary tree where each node represents the maximum value its children:

```<code>            78
     45            78
  23    45     78      6
23 17  9 45   78 2    4 6
</code>```

Then you only need to find a way to determine which nodes you minimally need to check to find the maximum value in the range queried. In this example, to get the maximum value in the index range [2, 6] (inclusive) you would have max(45, 78, 4) instead of max(9, 45, 78, 2, 4). As the tree grows, the gain will be larger.

Body:
I think you could construct some kind of binary tree where each node represents the maximum value its children:

            78
     45            78
  23    45     78      6
23 17  9 45   78 2    4 6

Then you only need to find a way to determine which nodes you minimally need to check to find the maximum value in the range queried. In this example, to get the maximum value in the index range [2, 6] (inclusive) you would have max(45, 78, 4) instead of max(9, 45, 78, 2, 4). As the tree grows, the gain will be larger.

ContentLicense: CC BY-SA 4.0


答:
I think the actor model is missing from the list of candidates.

Here's what I mean by Actors:

independent entities

that receive messages, and when receiving a message, may

create new actors,

update some internal state for the next message,

and send out messages

This model is something beyond deterministic Turing machines, and is actually closer to our real-world hardware when looking at concurrent programs. Unless you employ extra (costly) synchronization steps, these days, when your code receives data, that value may already have changed on the other side of the same die, maybe even inside the same core.

Short discussion/introduction: http://youtube.com/watch?v=7erJ1DV_Tlo

Title: What's the next level of abstraction?

Body:
Since programming languages initially only used lines of code executed sequentially, and it evolved into including functions which were one of the first levels of abstraction, and then classes and objects were created to abstract it even further; what is the next level of abstraction?

What's even more abstract than classes or is there any yet?


问:
Why should I should url routes to the user in a single page application?
Why a single page application is a desktop client replacement why should I show certain url`s in the url bar of the browser.

Why is mysite.com not enough.

My question to you guys is now:

What are the reasons and advantages for the user to show such an url like mysite.com/customers/3

Are there any reasons like the user wants to be able and bookmark a site and this would need an URI ?

答: Bookmarks are one reason; another reason is that you want to keep the back/forward buttons functioning according to the user's expectation. Users don't care whether it's a single-page application or not; they hit "back" and expect to go back one conceptual step. Without special precautions, the "back" button will take them away from your single page, which is invariably not what they expect, and it can be seriously annoying.


答:
try "segment tree" data structure

there are 2 step

build_tree() O(n)

query(int min, int max) O(nlogn)

http://en.wikipedia.org/wiki/Segment_tree

edit:

you guys just don't read the wiki i sent!

this algorithm is:

- you traverse the array 1 time to build tree. O(n)

- next 100000000+ times you want to know max of any part of array, just call the query function. O(logn) for every query

- c++ implement here geeksforgeeks.org/segment-tree-set-1-range-minimum-query/

old algorithm is:

every query, just traverse the selected area and find.

so, if you gonna use this algorithm to process once, OK, it slower than old way.
but if you gonna process huge number of query(billion), it's very efficient
you can generate text file like this, for test

line 1: 50000 random number from 0-1000000, split by '(space)'(it's the array)

line 2: 2 random number from 1 to 50000, split by '(space)'(it's the query)

...

line 200000: likes line 2, it's random query too

this is the example problem, sorry but this is in vietnamese

http://vn.spoj.com/problems/NKLINEUP/

if you solve it by old way, you never pass.

Title: Retrieving maximum value from a range in unsorted array

Body:
I have an unsorted array. I have queries in which I give a range and then the maximum value from that range has to returned.
For example:

```<code>array[]={23,17,9,45,78,2,4,6,90,1};
query(both inclusive): 2 6
answer: 78
</code>```

Which algorithm or data structure do I construct to quickly retrieve maximum value from any range. (There are a lot of queries)

EDIT:
This is indeed a simple version of the actual problem. I can have the array size as large as 100000 and the number of queries upto 100000. So I definitely require some preprocessing which'll facilitate a fast query response.


问:
Helper Methods Placement
Here's a question that's always bugged me. I'm going to use java as an example because I've almost never run into a problem in java where I didn't need to use helper methods in its class structure.

Let's say I have a method that does a thing or two and then calls a helper method:

```<code>public void doStuff() {
    int x = 4;
    int y = 5;
    doStuffHelper(x, y);
}
</code>```

Now I need to create a private method, doStuffHelper, that doStuff calls with x and y. For readability I always put the helper directly above or below the function, but I can never quite decide which one is better. What are your thoughts/experiences with it?

I know the question seems trivial, but since I don't have any guiding principles on it, I find that it always kills coding time deciding what to do and re-organizing my code if it doesn't work out. If there is no consensus, I think it's time to finally commit to one over the other for me.

答:
I always put the function doStuffHelper afterwards. This makes it easier to read, as when you start reading the code from the top, you won't have to first remember what doStuffHelper does (without understanding its context) and then while rememering that, read function doStuff(). Instead you read function doStuff() which should be the "main" function of the class, understand what it's trying to do, and then read function doStuffHelper().

Sort of like the difference between a passive and active sentence in English.

Title: Helper Methods Placement


答: It also means if their connection drops out they can refresh the current page easily. </p>

Title: Why should I should url routes to the user in a single page application?

Body:
Why a single page application is a desktop client replacement why should I show certain url`s in the url bar of the browser.

Why is mysite.com not enough.

My question to you guys is now:

What are the reasons and advantages for the user to show such an url like mysite.com/customers/3

Are there any reasons like the user wants to be able and bookmark a site and this would need an URI ?


答:
Don't materialize business plans in code.

Every program that has a real lifecycle will have the problem you're describing.  The only way to deal with it is to say "that is not an issue in the code", and to ignore it.  Instead of having "gold", "silver", and "bronze" levels and dealing with the rename of "gold" to "platinum" and the insertion of "bismuth" below bronze, have "level 3.0", "level 2.0", and "level 1.0" and change 3.0's name to "platinum" in the metadata (typically in a database) and insert "level 0.9".  Or if you prefer integers, count by 1000s - that's plenty of room for insertion and range.

Heck, I once worked on a project where the product name changed so often it was known all through the technical side of the company as "&V2", because that was the substitution symbol we used in the architectural documentation.

Title: How to handle product rebranding in code in a short time frame

Body:
We've all been there - a product feature is called "gold", and then a week before launch they decide it is to be called "platinum". Luckily, you had some nous about you so the UI code is easy to change.

But...what about all the variables and methods? Sure, you could change all these but what about the testing time?

Obviously Resharper or some other enterprise level refactoring tool may help but how do you sell a zero-value proposition to the business? After all, that text change on the front screen is just a 2 minute job - right?


答:
There are situations where instanceof is unavoidable. This applies to languages, where a class can be closed. For example, in Java there can be final classes. You can't inherit from them, nor can you make such a class implement an interface of your own.

An example case would be to have a list containing Integer and Double objects and you want to do different things based on the type.


问:
Is there a common mathematical symbology for collections?
I am being asked to define several of my algorithms in mathematical terms to describe my work to a customer.  I am trying to determine if anybody knows whether common operators for collections like sequences, lists, tuples, etc have been defined. If so, is there a good reference that I could be pointed to. Thanks. I am interested in the actual symbols used.  I am wondering if the following would make sense or be appropiate to anybody.

Given two sequences (or strings):

S = (A, B, C) and T = (A, D, H)

In my mind, the intersection of these sequences would look like S ∩ T = (A) and the union of these sequences would be S ∪ T = (A, B, C, A, D, H)

答: Sounds like set notation and set-builder notation.  Check out the links for more details and references.</p>


问:
Why does gmail use java? Is there really a advantage over something like php or python?
Note: I know that none of you (probably) work for google, so this is a lot more of a conceptual question.

So yeah, i discovered that Gmail uses java and that got me thinking, Why?

I personally never really learned java and am familiar with C/C++, Python, Php e.t.c
But what i dont understand is why do some websites use languages such as java? (Note: This is in no way a thread saying one language is better than the other).
What i want to know is why do some websites such as Gmail use java and similar languages?What advantages/disadvantages come with using java/similar languages over languages such as php/python/ruby for web development?

Ps: I know that some sites prefer to compile their code for optimization(Like facebook's hiphop)

答:
Because Java has a pretty good trade-off between productivity and performance; it is somewhere between PHP/Python which are very productive and C/C++ which are very performant.

Gmail is a large site which has lots of clients; here problems of scalability occur and Java is a more scalable language than PHP or Python.

Also Java has some very good frameworks good for web, being the first language used for web programming even if now is used more rarely, only in large systems such as Gmail reigning only in the enterprise area.

Take Twitter as another example; it was initially written in Ruby but has been migrated to Java for scalability.