答:
Here are some things that I find help me:

Take note of what you like/don't like in other software. We're programmers, we spend a large portion of our lives at the computer. Try and take note of what you love/hate when using software. Doesn't matter if it's computer software, video games, mobile devices, etc just try and keep your eye out for what is convenient and easy to use, and what is not.

Find an easy-to-use sketching tool for sketching out the UI for you and your users. I love using Balsamiq since it is fast, simple, and the web version is free to use.

Remember that you don't need to find someone that specializes in software design to help you design something - any user will do. I often run my sketches by some people who are totally unrelated to the project just because I know they're around software all day and can tell me if something looks OK or is user-friendly. Just keep in mind that they will often give you crazy ideas about what to do, and you have to know what would be simply "cool" to do, and what would actually improve productivity.

Feel free to ask on https://ux.stackexchange.com/ for detailed questions


问:
Unicode Explanation Required
Can someone explain what this means?

Unicode defines a codespace of 1,114,112 code points in the range 0hex to 10FFFFhex.

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

答:
A code point or code position is any of the numerical values that make up the codespace.

As per the Wikipedia entry on Code point:

The notion of a code point is used for abstraction, to distinguish both:

the number from an encoding as a sequence of bits, and

the abstract character from a particular graphical representation (glyph).

This is because one may wish to make these distinctions:

encode a particular code space in different ways, or

display a character via different glyphs.

So Unicode defines space for over a million distinct glyphs, which are accessed in the hex range from 0 to 10FFFF. You may be familiar with Extended ASCII which comprises 256 code points in the range 0hex to FFhex.

ContentLicense: CC BY-SA 3.0

Title: Unicode Explanation Required


问:
Benefits to starting JavaScript "for" loops at 0, or just traditional?

Possible Duplicate:

  Defend zero-based arrays

I'm running code that loops through an array of HTML IDs.

With the HTML IDs named content1, content2, …, content12, my loop looks like:

```<code>for (var i = 1; i<13; i++) {
    var contentFind = $('#content'+i)[0];
</code>```

I know that the usual way to run loops is to start at i = 0. Is there any benefit to this, or is it just the traditional, standard or normal way to write loops?

答:
In modern languages, you may think of it as tradition. There is a reason why it was done so originally though, and that reason was: to conserve memory.

(EDIT: Since 2 people have completely snapped already; I understand that arrays could have been implemented differently in C. The fact remains that they weren't. They really are just pointers in C, and C just so happens to be the ancestor of most modern languages which start at 0. - There may be other reasons to start at 0, I am merely providing the one related to how arrays work in the ancestor of C-style languages... the programming language C. Not Fortran, but C. Thank you for your understanding.)

The godfather of general-purpose programming languages, C (and by extension, C++), considers certain variables as memory addresses called pointers. These days, memory management is left up to the runtime environment, not the programmer which is why you've probably never heard of pointers. But when you use C, when you use variables, you're really dealing with the memory in a less abstract fashion.

This may be way too complicated if you're new to programming, but hopefully this will make some sense.

A pointer is a kind of variable that stores a memory address. In C, you can work with "normal" variables but they are limited in a number of ways... you always end up having to work with so-called pointers, which you may consider a different kind of variable, one that points to a location in memory, rather than the actual content of that location in memory. I will skip the discussion on why this is, just remember that pointers are variables containing memory addresses which then are used to point toward the data... as opposed to storing the data itself. ("Normal" variables are said to be located on the stack, but pointers are said to be located on the heap - nevermind this if it confuses you.)

In C, when you use an array, what you really have is a memory address (a pointer) indicating the start of the array. The pointer itself doesn't contain the content, it doesn't even contain the length of the array, merely the memory address of its starting point. But when you allocate that memory, you have to specify exactly how large the array is, so that the compiler will know how much memory to allocate.

Let's imagine an array in C called some_array.

some_array will determine the memory location of the array. The array itself is nothing but a sequence of reserved memory address space where the content of some_array is expected to reside. When we create that array, we give it a name (some_array), and we tell it how many items in the array we need. (In C/C++, arrays don't expand on demand, you have to declare their size beforehand or otherwise use more complicated classes like lists or vectors).

But now we want the second entry in our array. How do we figure out where it is? We only have the memory address, the pointer! That doesn't tell us where the second entry is, merely where the first entry starts!

But what we do know (in C), is the size of the variable type of our array... which also must be explicitly stated when you create the array. If we have an integer, for instance, let's say it's 16 bits in size.

We can then know the location of the second entry by knowing the location of the first entry (which is the start of the array), and then we can simply add the size of each entry (size of integer)!

In other words;

location_of_second_entry = location_of_first_entry + (size_of_integer).

What about the third entry? That will be:

location_of_third_entry = location_of_first_entry + (2 * size_of_integer).

As you might be able to tell, the physical memory location will always be as follows:

location_of_any_entry = location_of_first_entry + (iterator * size_of_integer)

So if you want the first item, the iterator will be 0. And that's why iterators originally started as 0, because the variables used to denote arrays were typically just memory addresses.

Now, this wouldn't have to work this way. You might start at 1 in C, but then you would be wasting the address space between the first entry and the second one because "location_of_first_entry" would never be used to store any data.

Memory management is handled completely differently in more recent runtimes and languages, so this is not really a technical requirement for more high-level programming languages (such as PHP, Python, Perl), but it's a tradition that has lived on because there was a time when programmers were expected to handle memory with some respect.

<s>In more high-level languages, the question of whether to start from 0 or 1 is mostly a question of how much programmers feel like arguing about it. So, in the end of the day for 2011 and super-high-level programming languages, it's really just a tradition.</s> - Apparently I'm a complete idiot that knows nothing about anything, spouting utter nonsense to the detriment of humanity and the world as we know it. Well, actually, I just neglected to take into account the modern debate and so I have earned the wrath of those who graciously know better. Turns out there's a perfectly rational debate around this that relates to modern languages, independent of the historical reasons behind C-style languages. So while the historical reason for C-style languages taking it from C is true, there is apparently a deeper discussion as well, as it turns out.

(EDIT: Since someone mentioned it, this was done differently, starting at 1, in other low-level programming languages like Fortran. The reason it was done this way in C is because of how arrays are implemented in C. They could have implemented them differently, in which case it could have started at 1 without wasting memory, but they didn't.)


答: The value of 0x10FFFF is 1,114,111. Between 0x000000 and 0x10FFFF, you have 1,114,112 numerical values. In Unicode, every character is represented by a number in the range 0 through 1,114,111. Software then interprets this numerical value to render the character on the screen.</p>

Title: Unicode Explanation Required

Body:
Can someone explain what this means?

Unicode defines a codespace of 1,114,112 code points in the range 0hex to 10FFFFhex.

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


问:
What qualifies "too many database requests" in code?
This is a discussion myself and some of my colleagues are having and thought I'd come out here and see what if there's a general consensus on it.

It basically comes down to the following 2 opinions on database calls:
1.  Make one large call to get everything that may be needed to reduce database the number of DB calls
2.  Make smaller separate calls based on what is requested to reduce the size of DB calls

Where this is especially coming into play is in common code.  We'll use the example of an Employee class as that's fairly straight forward.

Let's say that your Employee class has 10 value attributes (first name, last name, hiredate, etc.) and then 2 class attributes ... 1 pointing to a Department class and then 1 supervisor that points back to another Employee object.

In mindset #1, you'd make one call that returns the Employee data as well as the fields needed to populate the Department and Supervisor attributes ... or at least the fields that most often used from those sub objects.

In mindset #2, you'd only populate the Employee object at first and then only populate the Department and Supervisor objects if and when they are actually requested.

2's stance is pretty straight-forward ... minimize the size of the requests and how many database objects need to be hit each time one of those requests is made.  #1's stance is that even if it could be implemented properly, the sheer fact that the code would have to make multiple connections is going to cause more strain on the connection between the webserver and the database as opposed to reducing it.

The driving force behind researching this is that the amount of traffic between our webserver and database server is getting out of control.

答: Your question seems based on the assumption that you have to guess what data will be needed for any given page.  That's not the case.  It's not as easy as the naive approach, but you can architect your code so you will know whether you're going to need department or supervisor attributes before making any database calls.  </p>


问:
How exactly do we go from Binary/Hex to Assembly Instruction sets?
So i've been trying to learn some Embedded/Assembly programming for a bit here lately, as well as going far as trying to learn the lowest level (gates and such).

One thing puzzles me though....is how do we "get" instruction sets. I understand somewhat how gates/TTL and such works, but I don't see how we get from that to mov,add,clr etc...?

It's probably a stupid question....but I mean I think back to the first micro-processors/controllers and think....how exactly did they design an instruction set and make it work?

edit: I guess for Clarity, pretend im talking about the first microprocessor, how did they go from Binary to actually creating an Instruction Set?

答:
The heart of a CPU is the ALU.  It's responsible for taking an instruction (like MOV) which is just some pre-defined series of binary digits, and also taking 0, 1, or 2 operands, and performing the applicable operation on them.  The simplest instruction could be a NOP (no operation) which essentially does nothing.  Another typical operation is ADD (adds two values).

The ALU reads and writes data from and to "registers".  These are small memory locations internal to the CPU.  Part of the instruction (2 to 3 bits for each input depending on how many registers you have) indicates which register to read from.  There are units in the CPU external to the ALU that handle loading required data (and the instruction) from memory into registers, and writing the result from registers back into memory.  The location to write the result will also be encoded into another 2 or 3 bits.

The choice of "op codes", which is the binary number that represents an operation, is not arbitrary.  Well-chosen opcodes reduce the complexity of the ALU.  Each bit or group of bits tends to enable and disable certain logic gate in the ALU.  For instance, an ADD instruction would have to enable the output stage to choose the result of the internal adding logic.  Likewise, a MUL instruction would choose the result of the multiply logic.  Depending on the design, it's quite likely that both the adder and multiply circuits both actually perform their operation on the input operands, and it's just the output selection (what gets written to the output bits of the ALU) that changes.


问:
License placement curiosities
Ruby gems have LICENSE file with the license text in each gem. Cocoa[Touch] open source frameworks (say ShareKit, StackKit, etc.) have license at the very beginning of each file (.h and .m). I am not sure about .NET or other interpreted languages (except ruby), but I'm pretty sure there are own choices at hand. I am wondering what are the reasons behind placing license into open source software source packages like this. Why not LICENSE file everywhere or at the beginning of every source file?

答: Each source file contains a license extract to make sure that all the code within said file is in that license.  The LICENSE file should contain the full text of the license for the whole project.  Those two could be similar and they could not be.</p>

Title: License placement curiosities


答:
The codespace is an abstract layer between the glyphs (User Interface level) and the (byte-)encoding. Every character defined in Unicode has its own code point, and there 1,114,112 possible code points (not all are used).

For example, the euro sign is always code point U+20AC.
Depending on the selected encoding it may be encoded as +IKw- (UTF-7), E2 82 AChex (UTF-8), 20 AChex (UTF-16) OR 00 00 20 AChex (UTF-32).

Title: Unicode Explanation Required


问:
Great Programmer Productivity - Accounting for 10,000 fold difference?

A great lathe operator commands several times the wage of an average lathe operator, but a great writer of software code is worth 10,000 times the price of an average software writer. - Bill Gates

Say there's a "great" software engineer and an "average" software engineer on the same team. How can you account for one engineer being 10,000 times more productive? I can't quite fathom this, given they're both taking on their share of features, bugs and investigations, and consistently deliver with quality. Would my description possibly justify them to be above "average"? "great"?

答:
The average olympic swimmer can swim around 2.5 miles per hour at a distance.

The average person (who can swim) can swim about 1.5 miles per hour ata distance.

This means that the average olympic swimmer can swim the English Channel in about 8 hours.

It would stand to reason then that the olymic swimmer is 60% faster than the average and that the average swimmer would take around 13 hours to complete the race...

Except that if I, an average swimmer, were to attempt to swim the English Channel, the only way I'm going to get across is washed up on the shore a week later.

Many aspects of programming are like swimming the English Channel. It is sink or swim. I do not even know if 10,000X better is really even accurate way to describe the distinction between completed software that works and incomplete software that does not work.

OwnerDisplayName: TheImpact


问:
How do you share your craft with non programmers?
Sometimes I feel like a musician who can't play live shows. Programming is a pretty cool skill, and a very broad world, but a lot of it happens "off camera"- in your head, in your office, away from spectators.

You can of course talk about programming with other programmers, and there is peer programming, and you do get to create something that you can show to people, but when it comes to explaining to non programmers what is it that you do, or how was your day at work, it's sort of tricky.

How do you get the non programmers in your life to understand what is it that you do?

NOTE: this is not a repeat of Getting non-programmers to understand the development process, because that question was about managing client expectations.

答:
My two go-to analogies for this purpose are: a recipe, and a massive bureaucracy. That's what I explained in this QA:
30 minutes to explain programming to a 15 year old

I've used the recipe analogy many times to explain how programming is about writing a rigorous set of instructions that have a tangible and predictable result when followed.

I've only used the bureaucracy analogy a couple times actually, because most people don't really need to understand beyond the recipe analogy, but both times were very illuminating for the person. They seemed to think programming meant total recall of every line of code (eg. "But if you have such a crappy memory, then how can you program a computer?") but really it's about building lots of self-contained modules that work together to accomplish the larger goal. The modules of a program are like the departments in a big company: self-contained units that mostly deal with their own bit of the whole and communicate with other departments through memos.

ContentLicense: CC BY-SA 2.5


问:
Is agile more than just small waterfalls?
I've mostly used the waterfall methodology on my projects, but now I'm expanding my horizons into agile methodologies. From what I've read so far, and maybe I've read the wrong things, agile means small waterfalls. Instead of a big waterfall spread over one or two years, you have small waterfalls that last weeks or maybe a few months at most.

Is my understanding correct or is there more to it than that? What are the agile philosophies?

答:
Yes, that's more or less correct. There has been much written and discussed about how to go about it, but a bunch of little waterfalls is the crux of it. </p>

<p>The specific implementation of how to use a bunch of little waterfalls isn't trivial though. For example, you're not going to switch from making big projects in a couple of years to making a number of small projects. There's still the big project with 1-2 years worth of work to put into it. So you need to split the big project into a number of small projects. That may seem pretty obvious, but it fills pages and pages of books. </p>

Body:
Yes, that's more or less correct. There has been much written and discussed about how to go about it, but a bunch of little waterfalls is the crux of it.

The specific implementation of how to use a bunch of little waterfalls isn't trivial though. For example, you're not going to switch from making big projects in a couple of years to making a number of small projects. There's still the big project with 1-2 years worth of work to put into it. So you need to split the big project into a number of small projects. That may seem pretty obvious, but it fills pages and pages of books.


答: Yes and no - the actual process can be seen as a series of small waterfalls but the difference is that the process evolves and is improved upon from the input of the entire team (dev, qa, business etc), in retrospectives, which should lead to a much tighter unit which is able to react to issues and accurately plan and deliver.  I'm grossly over simplifying it here, there is a lot more to it, but I don't think this is a bad starting point.</p>

Title: Is agile more than just small waterfalls?

Body:
I've mostly used the waterfall methodology on my projects, but now I'm expanding my horizons into agile methodologies. From what I've read so far, and maybe I've read the wrong things, agile means small waterfalls. Instead of a big waterfall spread over one or two years, you have small waterfalls that last weeks or maybe a few months at most.

Is my understanding correct or is there more to it than that? What are the agile philosophies?


答:
Is that correct or is there more to it than that

Both. Yes that is an accurate summation of the concept, but there is a lot of detail being summed up. I mean, pretty much every aspect of planning changes when you are planning for just the next week instead of the next year.


答:
I would say that is a simplistic way o putting it. Yes, when you get down to it, it is small waterflows, but there is so much more behind it that makes it work. An entire methodology that changes how you approach projects... Not to mention the mindset needed for it.

If you are serious about Agile, here is a good (and long) series of webcasts you might be interested in:

http://autumnofagile.net/


答:
At a simple level, yes. Simply performing a Waterfall every two weeks does not make you agile, but it is iterative (which is half of agile).

The waterfall model defines phases - requirements, architecture, design, implementation, verification (testing), validation (acceptance testing), and release. In any iterative methodology, you go through each of these phases within every iteration. There might be overlap between them, but you elicit and capture requirements, adopt the architecture and design of the system to allow for implementation, develop the new features or fix the defects, test the new modules, and then present it to the customer for acceptance testing and deployment.

However, there's a lot more to agile than just being iterative and incremental. The tenants of agile are captured in the Manifesto for Agile Software Development. There are four key points made in the Manifesto:

Individuals and interactions over processes and tools

You involve individual people frequently. Many implementations are centered around self-organizing and self-directing teams. Nearly all have frequent interactions with the customer or someone who has voice of the customer. Rather than having a formal set of procedures to follow and tools to use, you let the people working on the project drive how the project gets done to let it get done in the best possible manner.

Working software over comprehensive documentation

In a software project, the primary goal is the delivery of software. However, in some projects, there is wasteful production of documents that add no value. Scott Ambler wrote a good article on Agile/Lean Documentation. It's not about not producing documentation, but about choosing documentation that adds value to your team, future developers, the customer, or the user. Rather than producing documentation that doesn't add value, your software engineers are instead producing software and associated tests.

Customer collaboration over contract negotiation

Rather than defining the terms and timetables and costs up front, it becomes a continuous effort with the customer. For example, you might capture your requirements in the form of user stories and assign them points. After a few iterations, you settle on a velocity (points/iteration) and can determine how many features your team can implement in an iteration. As your customer provides feedback on which features add the most value, they can decide when the project is done at any point. Any number of things can happen with frequent delivery and customer interaction - the requirements have been satisfied and the project concludes into maintenance and eventually end-of-life, the customer finds out that they don't need everything they thought so decides to end the project, the project is failing and the customer sees this early and can cancel it...the list goes on.

Responding to change over following a plan

You don't have a big design or ultimate plan up front and have to perform rework whenever that design or plan has to change. You continually estimate and revise estimates based on the information that you have. You choose your metrics carefully to provide insight into the health of the project and when to make internal changes. You frequently add, remove, and reprioritize requirements with the customer. Ultimately, you understand that change is the only constant.

Being agile means focusing on people and meeting their needs by delivering high-quality, value-adding software quickly. As the needs of the customer change, you adapt to those needs to focus on adding value. There are specific implementations of agile methodologies, but they are all centered on people, timely delivery of working software, and adapting to a rapidly changing environment.


答:
If you look at the static structure (process definition) of an agile project, it does look like many small waterfalls yes. But the goal of an agile project is to get quicker and better feedback.

You do test-driven development to immediately know if your software still works

A customer is onsite and performs acceptance-tests to know when you're done

You have retrospectives to adjust your process based on what went well and what didn't.

The agile manifesto highlights some differences between agile and waterfall (as perceived by those who signed).


答:
Really "agile" often means waterfalls of 1-2 days, not weeks. That does not mean you don't follow an overall plan, and that the real release cycles are 1-2 day. But you should try to have a working, tested product every day, and you could release it - in theory - every day.

Scrum, for example, uses sprints of 4 weeks, but a sprint is not just one waterfall (at least, it should not be). You can change priorities every day whenever you see that something does not go the way it was planned at the beginning of the sprint.


问:
Using a CMS that I'm not familiar with just for the sake of the job?
I've been designing and developing with Wordpress for about two years (and I love it). Recently, a respectable designer told me that I could work for him. He works with Joomla! My job was to create a Joomla! template. I didn't feel myself comfortable using it. I don't like the back-end's UI, the way you add elements and content (I don't even like Joomla!'s logo). I'm used to simple interfaces and Joomla! seems too cluttered to me.

That's why I started to wonder if I'm better off just finding clients and  using the CMS that I love or making an effort to learn a CMS that I don't like using?

答: Probably wouldn't hurt to learn, depending how much spare time you have.  I have used both, and I do like wordpress better as well, but it really won't take that long to get up to speed.  You can also ask your designer (or a forum) why they prefer Joomla over Wordpress, the advice may make it seem more appealing at least.  But if you really hate it after a least a little bit of time getting used to it, then its not worth it, as you don't want to be doing something you hate to do.</p>


答: In the technology world, if you want a job, learn something.  If you want a career, learn everything you can.  Because all technologies go away in time.  </p>

Title: Using a CMS that I'm not familiar with just for the sake of the job?

Body:
I've been designing and developing with Wordpress for about two years (and I love it). Recently, a respectable designer told me that I could work for him. He works with Joomla! My job was to create a Joomla! template. I didn't feel myself comfortable using it. I don't like the back-end's UI, the way you add elements and content (I don't even like Joomla!'s logo). I'm used to simple interfaces and Joomla! seems too cluttered to me.

That's why I started to wonder if I'm better off just finding clients and  using the CMS that I love or making an effort to learn a CMS that I don't like using?


答:
I would suggest learning it. Tying yourself to any language, technology, framework, or tool is just shooting yourself in the foot. It's perfectly fine to have favorites, but it's good to have options.

Think about it this way: what would happen to your work if, tomorrow, WordPress just died? You would have to learn something new to find work, and it would be harder to find work over people who already had the experience you didn't. However, if you get some exposure to other technologies now, it becomes easier to learn them when you need to use them for a job.

There are personal benefits as well. Learning how to learn and applying those techniques makes it easier to learn. Therefore, you shouldn't stop learning just because you found something you like. You might also see a new way of approaching problems that is better that might have an impact on the way you do things now, and I don't think anyone would argue against self improvement.


问:
Why don't relational databases support returning information in a nested format?
Suppose I'm building a blog that I want to have posts and comments. So I create two tables, a 'posts' table with an autoincrementing integer 'id' column, and a 'comments' table that has a foreign key 'post_id'.

Then I want to run what will probably be my most common query, which is to retrieve a post and all of its comments. Being rather new to relational databases, the approach that appears most obvious to me is to write a query that would look something like:

```<code>SELECT id, content, (SELECT * FROM comments WHERE post_id = 7) AS comments
FROM posts
WHERE id = 7
</code>```

Which would give me the id and content of the post that I want, along with all the relevant comment rows packaged neatly in an array (a nested representation like you'd use in JSON). Of course, SQL and relational databases don't work like this, and the closest they can get is to do a join between 'posts' and 'comments' that will return a lot of unnecessary duplication of data (with the same post information repeated in every row), which means processing time is spent both on the database to put it all together and on my ORM to parse and undo it all.

Even if I instruct my ORM to eagerly load the post's comments, the best it'll do is to dispatch one query for the post, and then a second query to retrieve all of the comments, and then put them together client-side, which is also inefficient.

I understand that relational databases are proven technology (hell, they're older than I am), and that there's been a ton of research put into them over the decades, and I'm sure there's a really good reason why they (and the SQL standard) are designed to function the way they do, but I'm not sure why the approach I outlined above isn't possible. It seems to me to be the most simple and obvious way to implement one of the most basic relationships between records. Why don't relational databases offer something like this?

(Disclaimer: I mostly write webapps using Rails and NoSQL datastores, but recently I've been trying out Postgres, and I actually like it a lot. I don't mean to attack relational databases, I'm just perplexed.)

I'm not asking how to optimize a Rails app, or how to hack my way around this problem in a particular database. I'm asking why the SQL standard works this way when it seems counterintuitive and wasteful to me. There must be some historical reason why the original designers of SQL wanted their results to look like this.

答:
You have a specific need. It would be prefered to extract data out of a database in the format you want, so you can do with it what you want.

Some things databases don't do as well, but it's not an impossibility to build them to do it anyway. Leaving formating to other applications is the current recommendation, but doesn't justify why it can't be done.

The only arguement I have against your suggestion is being able to handle this result set in a "sql" way. It would be a bad idea to create a result in the database an not be able to work with it or manipulate it to some extent. Let's say I created a view built the way you suggest, how do I include it in another select statement? Databases like to take results and do things with them. How would I join it to another table? How would I compare your result set to another?

Then benefit of RDMS's is the flexibility of sql. The syntax for selecting data from a table is pretty close to a list of users or other objects in the system (At least that's the goal.). Not sure there is any point to doing something completely differet. They havne't even gotten them to the point of handling procedural code/cursors or BLOBS of data very efficiently.

OwnerDisplayName: PreciousBodilyFluids


答:
These are the rules I use, maybe they'll be of use to you.

Measure first!  I won't even look at code that "might be slow" unless I can actually see traffic flowing to that resource and that resource is responding slowly.

1 Request = K queries. The number of times I talk to the database is fully determined by the kind of resource requested; and never by the nature of the request or state of that resource;  In your example, that's probably at most 3 queries: 1 for Employees, 1 for Departments and 1 for Supervisors;  It doesn't matter how many of each there happen to be.

Don't query what you won't Use.  If this is HTTP we're talking about, theres no sense in querying data for later; there is no later; each request starts from a clean slate.  Sometimes I need most of the columns from a table, but on occasion I only need one or two; when I know exactly the fields I need, I'll ask for just that.

Throw hardware at the problem.  Servers are cheap;  Sometimes you can get enough performance just by moving the database to a beefier box; or sending some queries to a read-only replica.

First invalidate the cache, then implement caching. The urge to put often used or hard to query data in a cache is strong; but all-too-often, evicting unused data or expiring superseded data is overlooked.  If you know how to take data out of the cache; then you are safe putting it in the cache;  If it turns out its more expensive to invalidate the cache than to just do the query; then you didn't need a cache.

Title: What qualifies "too many database requests" in code?

Body:
This is a discussion myself and some of my colleagues are having and thought I'd come out here and see what if there's a general consensus on it.

It basically comes down to the following 2 opinions on database calls:
1.  Make one large call to get everything that may be needed to reduce database the number of DB calls
2.  Make smaller separate calls based on what is requested to reduce the size of DB calls

Where this is especially coming into play is in common code.  We'll use the example of an Employee class as that's fairly straight forward.

Let's say that your Employee class has 10 value attributes (first name, last name, hiredate, etc.) and then 2 class attributes ... 1 pointing to a Department class and then 1 supervisor that points back to another Employee object.

In mindset #1, you'd make one call that returns the Employee data as well as the fields needed to populate the Department and Supervisor attributes ... or at least the fields that most often used from those sub objects.

In mindset #2, you'd only populate the Employee object at first and then only populate the Department and Supervisor objects if and when they are actually requested.

2's stance is pretty straight-forward ... minimize the size of the requests and how many database objects need to be hit each time one of those requests is made.  #1's stance is that even if it could be implemented properly, the sheer fact that the code would have to make multiple connections is going to cause more strain on the connection between the webserver and the database as opposed to reducing it.

The driving force behind researching this is that the amount of traffic between our webserver and database server is getting out of control.


问:
Why would it ever be possible for Java to be faster than C++?
Sometimes Java outperforms C++ in benchmarks.  Of course, sometimes C++ outperforms.

See the following links:

http://keithlea.com/javabench/

http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy/

http://blog.cfelde.com/2010/06/c-vs-java-performance/

But how is this even possible?  It boggles my mind that interpreted bytecode could ever be faster than a compiled language.

Can someone please explain?  Thanks!

答:
Posted by Tim Holloway on JavaRanch:

Here's a primitive example: Back when machines operated in
  mathematically-determined cycles, a branch instruction typically had 2
  different timings. One for when the branch was taken, one for when the
  branch wasn't taken. Usually, the no-branch case was faster.
  Obviously, this meant that you could optimize logic based on the
  knowledge of which case was more common (subject to the constraint
  that what we "know" isn't always what's actually the case).

JIT recompilation takes this one step further. It monitors the actual
  real-time usage, and flips the logic based on what actually is the
  most common case. And flip it back again if the workload shifts.
  Statically-compiled code can't do this. That's how Java can sometimes
  out-perform hand-tuned assembly/C/C++ code.

Source: http://www.coderanch.com/t/547458/Performance/java/Ahead-Time-vs-Just-time


问:
How do I pick up a new language quickly, given I know several others?
One type of question that keeps coming up on Programmers.SE is how to learn a specific language, given you know several others (usually through a lot of experience or education).

In some cases, however, one might need to get up to speed quickly for a job, or for personal development, or even to check out a hot new platform.

In your experience, what general strategies have you used to pick up a new language quickly? Are there specific aspects of a language you try to focus on when starting cold? What types of resources do you find helpful in this process?

答:
As a specific suggestion for just using the language:

Fix Bugs

Find an interesting open-source project in the target language, preferably one with a public bug tracker, moderately active development, and a decent test suite.

Pick a bug to fix, preferably one that annoys you when you actually use the program.

Figure out why the program exhibits the buggy behavior.

Write tests and code to fix the problem.

Submit a patch upstream.

Revise your patch until the upstream developers are happy.

Go back to step 1 or 2.

This process tends to be more fulfilling than writing yet another toy program, but much easier than starting your own full project from scratch.  You get exposed to some of the language idioms in their natural context, and (with any luck) someone's idea of what good code looks like.

On the other hand, it can also be extremely frustrating, particularly if you pick a nasty bug, or if the developers reject your patch without properly explaining why.


答: If you can earn a living doing the option that makes you happier, then of course do that.  Otherwise, do what you have to do.</p>


问:
Overcoming general lack of UI design skill in developers
I have been told, and have found for myself, that lots of developers are not good at UI design  (I don't know how true is this) but it is true about me at least.

In web development good code development skills are not enough without great skills in UI design to go with them.

So for me, and many developers like me, that only have half of the thing (good development skills) how should we complete our other half other than paying for a designer?

Is using Open Source web templates with little modifications the best solution for this, or are there other options?

答:
Hire a pro.

Seriously, UIs from developers have a terrible reputation. This is not because developers are below average at design, but rather because developers are below average at asking help.

A developer has the tendency to take on every digital challenge that come their way.

(I was a professional developer for 10 years and my wife is a user interface designer for 20 years)


问:
How do I convince my fellow devs to WANT to add comments to source code commits?
I know that Subversion (what we're using at work) can be configured to require comments on commits, however I'm not in a position of power to simply turn this on.  I know that my reason for commenting my commits is because it is useful, if only as a memory-jogger, to quickly understand the reason behind the commit.  However, this doesn't seem to be enough to combat the two responses I always get:

It takes too long and I just want to get my changes into the repo.

It's easy enough to just look at the diffs.

I even show them the value of simply putting in a JIRA issue ID and how it automatically gets tied to the issue, but still no dice with them.

Worst of all, the person who can make the call is in the same camp: doesn't want to bother and is fine with looking at diffs.

I know it's the right thing to do, but how can I make them see the light?  Even if I can't convince my fellow devs, how can I convince management that it's the right thing to do for the business?

答:
Another way of looking at this is as a way for the developer(s) involved to grow their careers - they should own the documentation of their work.

In addition to other points raised in the above-referenced article, there is the ability to be able to review the code changes to find out where/when/why a change was done. That could be vital when tracking-down an elusive bug.


答:
See the following links ... But how is this even possible? It boggles
  my mind that interpreted bytecode could ever be faster than a compiled
  language.

Do those blog posts provide trustworthy evidence?

Do those blog posts provide definitive evidence?

Do those blog posts even provide evidence about "interpreted bytecode"?

Keith Lea tells you there are "obvious flaws" but does nothing about those "obvious flaws". Back in 2005 those old tasks were discarded and replaced by the tasks now shown in the benchmarks game.

Keith Lea tells you he "took the benchmark code for C++ and Java from the now outdated Great Computer Language Shootout and ran the tests" but actually he only shows measurements for 14 out of 25 of those outdated tests.

Keith Lea now tells you he wasn't trying to prove anything with the blog post seven years before, but back then he said "I was sick of hearing people say Java was slow, when I know it's pretty fast..." which suggests back then there was something he was trying to prove.

Christian Felde tells you "I didn’t create the code, just re-ran the tests." as-if that absolved him from any responsibility for his decision to publicise measurements of the tasks and programs Keith Lea selected.

Do measurements of even 25 tiny tiny programs provide definitive evidence?

Those measurements are for programs run as "mixed mode" Java not interpreted Java - "Remember how HotSpot works." You can easily find out how well Java runs "interpreted bytecode", because you can force Java to only interpret bytecode - simply time some Java programs run with and without the -Xint option.

Title: Why would it ever be possible for Java to be faster than C++?

Body:
Sometimes Java outperforms C++ in benchmarks.  Of course, sometimes C++ outperforms.

See the following links:

http://keithlea.com/javabench/

http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy/

http://blog.cfelde.com/2010/06/c-vs-java-performance/

But how is this even possible?  It boggles my mind that interpreted bytecode could ever be faster than a compiled language.

Can someone please explain?  Thanks!


问:
How do I know if the compiler broke my code and what do I do if it was the compiler?
Once in a while C++ code will not work when compiled with some level of optimization. It may be compiler doing optimization that breaks the code or it may be code containing undefined behavior which allows the compiler to do whatever it feels.

Suppose I have some piece of code that breaks when compiled with higher optimizations level only. How do i know if it's the code or the compiler and what do I do if it's the compiler?

答: Examine the assembly code that resulted and see if it does what your source is calling for.  Remember that the odds are very high that it's really your code at fault in some non-obvious fashion.</p>


答:
I think there is some empirical evidence that supports Gates' quote.  I remember reading (though I don't recall the source) that in typing pools the difference in output (easily measurable for a typing pool) between those in the 5th percentile and those in the 95% percentile was something like 3 to 1.  But after word processing software became available, the ratio rose to something like 10 or 20 to 1, because those who could use the advanced features of the software gained even more relative advantage.

Presumably for software development the ratio would be even higher, since there is even more freedom to take advantage of all kinds of tools, techniques, etc.  It's harder to measure the differences, but most attempts come out with at least 10 to 1, and that's presumably underestimating the difference because it's only measuring what's easy to measure.

In something like typing or operating a lathe the people in the top 1% are probably pretty close to hitting the physiological limits of what is possible.  In the case of programming they clearly are not (the ratio of how long it takes to write code versus how long it takes to type out code is enormous) so there should be room for much more variation.

Title: Great Programmer Productivity - Accounting for 10,000 fold difference?

Body:
A great lathe operator commands several times the wage of an average lathe operator, but a great writer of software code is worth 10,000 times the price of an average software writer. - Bill Gates

Say there's a "great" software engineer and an "average" software engineer on the same team. How can you account for one engineer being 10,000 times more productive? I can't quite fathom this, given they're both taking on their share of features, bugs and investigations, and consistently deliver with quality. Would my description possibly justify them to be above "average"? "great"?


问:
What are some good tasks to assign co-op students/interns?
My company is investigating hiring a University Computer Science co-op student (BSc year 3) for a 4- or 8-month work term. (I'm not sure how internationally-recognized the term co-op is - it's essentially a paid internship, after which the student returns to their studies.) My team develops a web application in ASP.NET and handheld thick clients on iOS, BlackBerry, and Android.

For any of you that have brought interns into an experienced development team, what kind of tasks did you find for them to do? I realize that's a hard question to ask since any answer can be quite specific to an individual business.

I'd expect the following:

Tasks that require mentoring but not babysitting

Tasks that will take a few weeks to finish (so the mentor can remain productive)

Tasks that expand the student's understanding of software development

I've considered things like expanding code coverage in our unit tests, or developing a feature that's been designed, or improving/writing missing requirements documentation from features that were added without any supporting documentation.

I never did an internship so I don't know what sort of tasks are valuable to both the student and the company. Any recommendations?

Edit: These are all excellent and thoughtful answers that have helped me a great deal. Thank you all very much. I can only choose one answer, so I'll go along with the crowd and accept the most popular one.

答:
We used to have our co-op students work on internal tools that were not critical to the main application we delivered, but helped in areas such as build automation, making a complex dataset easily viewable in a web application, converting an internal HTML site to a dynamic (and easy-to-update!!) application. I think one co-op student once wrote a log viewer that made it easier to manage logs from one particular application that had a very verbose output. I think some co-op students also got assigned to the testing team, so I imagine they were writing and executing tests.

These applications were great for co-ops because the code-bases were small and easy to get into. Since the projects were only used internally on our team the students didn't have to go through lengthy processes to get approval for deployment and implementation. They got to make their own design decicions (with guidance from senior devs) and learnt quite a lot. Occasionally we'd give them simpler defects from the production applications, but only if there wasn't enough on internal tools area to keep them busy.


问:
Why is PHP so frequently used on web servers?
My web server uses PHP as do 77.7% of web servers according to W3Techs, as of 14/03/2022.

The reason I use PHP is an inertia born out of seeing everyone else using it on web servers. What is it about PHP that would make it so ubiquitous on web servers?

(Note that this question is similar to the following question but takes it in a different direction: Why isn't Java used for modern web application development?)

答:
PHP is a language specifically designed for web development with built-in support for MySQL, the most popular open source database.

Easy to start with: As a beginner it is easy to start with PHP. The user just has to add a few PHP-tags in their existing HTML files and upload it to the server and see the result. Dynamic typing and associative arrays also make it easier to start using PHP.

Easy to use: Compared to other solutions like Java, PHP doesn't need to be compiled, so you just need to write the script and upload it to the server.

Integrated database support: PHP has built-in support for some of the most popular databases such as MySQL, PostgreSQL, SQLite, Microsoft SQL Server, IBM, and Oracle. That means it is easy to start using databases as no additional drivers need to be installed. The easy-to-use web-based admin tool PHPMyAdmin (released in 1998) is also a significant reason for PHP's success.

Old language with a big user base: PHP became popular early (in 1995) since it was designed for web development. Since then, the user base has grown and now there are many PHP frameworks and libraries, such as WordPress, Woocommerce, Magento, MediaWiki (which powers Wikipedia), Laravel, Bagisto, and Statamic.

Cheap hosting: Since PHP has existed for long time and works well on both Linux and Windows, many web servers support it. There is no problem finding hosting services with PHP pre-installed.

ContentLicense: CC BY-SA 4.0


答:
Testing and QA.

It will immerse them into software requirements, Agile development methodologies, writing test cases, working with developers, etc...

On the side though for the programming side of things I will sometimes assign an easy or unimportant feature and see how they do.  Most of the time they mess up and then you try to teach them what they did wrong and how they can do it better next time.

Title: What are some good tasks to assign co-op students/interns?

Body:
My company is investigating hiring a University Computer Science co-op student (BSc year 3) for a 4- or 8-month work term. (I'm not sure how internationally-recognized the term co-op is - it's essentially a paid internship, after which the student returns to their studies.) My team develops a web application in ASP.NET and handheld thick clients on iOS, BlackBerry, and Android.

For any of you that have brought interns into an experienced development team, what kind of tasks did you find for them to do? I realize that's a hard question to ask since any answer can be quite specific to an individual business.

I'd expect the following:

Tasks that require mentoring but not babysitting

Tasks that will take a few weeks to finish (so the mentor can remain productive)

Tasks that expand the student's understanding of software development

I've considered things like expanding code coverage in our unit tests, or developing a feature that's been designed, or improving/writing missing requirements documentation from features that were added without any supporting documentation.

I never did an internship so I don't know what sort of tasks are valuable to both the student and the company. Any recommendations?

Edit: These are all excellent and thoughtful answers that have helped me a great deal. Thank you all very much. I can only choose one answer, so I'll go along with the crowd and accept the most popular one.


答:
CPUs operate on 0's and 1's. All instructions had a sequences of bits that defined them. Thsi was machine code. That hard for humans to read and write. As a first step we grouped the 0's and 1's into 4 bits sequences and used 0 through F to represents them. This reduced the numbers we had to memorize, but it still was not easy to remember the hex code for instructions.

So we started using assembly which had "words" like MOV and ADD. The assembler would replace the instructions with the correct set of 0' and 1's converting the assembly "listing" to machine code.

Eventually we developed "higher" level languages where "instructions" could represent entire sequences of machine code.

Title: How exactly do we go from Binary/Hex to Assembly Instruction sets?

Body:
So i've been trying to learn some Embedded/Assembly programming for a bit here lately, as well as going far as trying to learn the lowest level (gates and such).

One thing puzzles me though....is how do we "get" instruction sets. I understand somewhat how gates/TTL and such works, but I don't see how we get from that to mov,add,clr etc...?

It's probably a stupid question....but I mean I think back to the first micro-processors/controllers and think....how exactly did they design an instruction set and make it work?

edit: I guess for Clarity, pretend im talking about the first microprocessor, how did they go from Binary to actually creating an Instruction Set?


答:
I'm teaching myself PHP right now, so maybe I can answer.

A PHP source code file can contain a mix of HTML, JavaScript and PHP, so it seems really easy to get simple web applications up and running. More complex interactions, that would require lots of Java in a JSP situation, or some weird contortions in a CGI-BIN situation, get catered to by the PHP builtins: you don't even have to know if an HTTP GET or POST called your code, everything your code wants to know lives in _REQUEST or _SERVER or _COOKIE global variables.

PHP-the-langauage gets parsed and executed pretty rapidly so you won't notice a huge performance drop when generating HTML, rather than just having a bunch of static HTML files.

PHP-the-interpreter has library calls for just about every open source DBMS, and a lot of the proprietary ones, too, so making a 3-tier-style web app looks easy.  PHP-the-interpreter includes library calls for a lot of other commons situations (a.k.a. "use cases"), so you don't have to write a lot of code yourself, just call the library. So, just like J2EE "enterprise apps", the problem moves from knowing how to code to knowing how to look library stuff up.  This is aided by the very decent php.net PHP manual.

As a programming language, PHP doesn't have a lot of exotic constructs, or differ too much from, say C, FORTRAN 4 or Pascal, so programmers that already know one language can easily pick up PHP-the-programming language.

Title: Why is PHP so frequently used on web servers?

Body:
My web server uses PHP as do 77.7% of web servers according to W3Techs, as of 14/03/2022.

The reason I use PHP is an inertia born out of seeing everyone else using it on web servers. What is it about PHP that would make it so ubiquitous on web servers?

(Note that this question is similar to the following question but takes it in a different direction: Why isn't Java used for modern web application development?)


答:
For the same reason MySQL is so popular: it was at the right place in the right time.

With the Linux server boom in the 90's, the LAMP platform (Linux-Apache-MySQL-PHP) came to scene as a reliable and, most importantly, free option.

As a side note, take MySQL at the time. These were two missing features from MySQL (from the top of my mind, there might be more) not so long ago:

No triggers

Not fully ACID compliant

How did a DB that wasn't even ACID (atomicity-consistency-isolation-durability) compliant get to be so popular? Same answer as PHP: it was at the right place in the right time.

Further reading about the "right place right time" on LAMP components:

https://www.dlitz.net/software/php/

http://www.firebirdfaq.org/faq54/

http://blog.ivanristic.com/2009/05/how-did-mysql-become-so-successful.html

http://news.ycombinator.com/item?id=2463305

https://stackoverflow.com/questions/309300/what-makes-php-a-good-language


问:
Why are zero-based arrays the norm?
A question asked here reminded me of a discussion I had with a fellow programmer. He argued that zero-based arrays should be replaced with one-based arrays since arrays being zero-based is an implementation detail that originates from the way arrays and pointers and computer hardware work, but these sort of stuff should not be reflected in higher level languages.

Now I am not really good at debating so I couldn't really offer any good reasons to stick with zero-based arrays other than they sort of feel like more appropriate. Why is zero the common starting point for arrays?

答:
My feeling is that it's completely arbitrary. There's nothing special about zero- or one-based arrays. Since liberating myself from Visual Basic (mostly, sometimes I do tiny things in Excel) I haven't worked with 1-based arrays, and... it's the same. The fact is that if you need the third element of the array, it's just an implementation detail that it is called 3 or 2. However, 99% of the work you do with arrays is only interested in two absolute points: the first element and the count or length. Again, it's just an implementation detail that the first element is called zero instead of one, or that the last element is called count-1 or, instead, count.

Edit: Some of the answerers have mentioned that 1-based arrays are more prone to fencepost errors. In my experience, thinking about it now, this is true. I remember thinking, in VB, "this will either work or will blow up because I'm off by one." In Java that never happens. Though I thought I was getting better, some of the answerers point out cases in which 0-based arrays result in nicer arithmetic, EVEN when you don't have to deal with a lower-level lang.

OwnerDisplayName: DrJokepu

Title: Why are zero-based arrays the norm?

OwnerDisplayName: Yar


答:
Zero-based arrays have their roots in C and even assembler.  With C, pointer math basically works like this:

Each element of an array occupies a certain number of bytes.  A 32 bit integer is (obviously) 4 bytes;

The address of an array is occupied by the first element of the array with subsequent elements in equal-sized contiguous blocks after that.

To illustrate, assume int a[4] is at 0xFF00, the addresses are:

a[0] -> 0xFF00;

a[1] -> 0xFF04;

a[2] -> 0xFF08;

a[3] -> 0xFF0C.

So, with zero based indices, the addres math is simple:

Address of element = Address of array + index * sizeof(type)

In fact the expressions in C are all equivalent:

a[2];

2[a]; and

*(a+2).

With one-based arrays, the math is (ever so) slightly more complicated.

So the reasons are largely historical.

Title: Why are zero-based arrays the norm?

Body:
A question asked here reminded me of a discussion I had with a fellow programmer. He argued that zero-based arrays should be replaced with one-based arrays since arrays being zero-based is an implementation detail that originates from the way arrays and pointers and computer hardware work, but these sort of stuff should not be reflected in higher level languages.

Now I am not really good at debating so I couldn't really offer any good reasons to stick with zero-based arrays other than they sort of feel like more appropriate. Why is zero the common starting point for arrays?

OwnerDisplayName: cletus


答:
The reasons are not just historical: C and C++ are still around and widely used and pointer arithmetic is a very valid reason for having arrays start at index 0.

For other languages lacking pointer arithmetic, whether the first element is at index 0 or 1 is more of a convention rather than anything else.

The problem is that languages that use index 1 as their first element don't exist in a vacuum and usually have to interact with libraries that are often written in -you guessed it- C or C++...

VB and its derived flavours have suffered from having arrays start either at 0 or 1 and it's been a source of problems for a long time.

Bottom-line is: it doesn't matter what your language consider the first element index as long as it's consistent throughout. The problem is that considering 1 as a first index makes it harder to work with in practice.

Title: Why are zero-based arrays the norm?

OwnerDisplayName: Renaud Bompuis


答:
Code including some original position/relative position information are much cleaner with arrays starting at 0.

For instance :
The code to copy a vector at a defined position in a bigger vector is a pain with arrays starting at 1 :

```<code>function copyAtPos (dest, vect, i):
    for i from 1 -> vect.length do
        dest[pos+i-1] = vect[i]
</code>```

By opposition with arrays starting at 0:

```<code>function copyAtPos (dest, vect, i):
    for i from 0 -> vect.length-1 do
        dest[pos+i] = vect[i]
</code>```

If you begin writing big convolutions formula, it becomes a must.

Title: Why are zero-based arrays the norm?

Body:
Code including some original position/relative position information are much cleaner with arrays starting at 0.

For instance :
The code to copy a vector at a defined position in a bigger vector is a pain with arrays starting at 1 :

function copyAtPos (dest, vect, i):
    for i from 1 -> vect.length do
        dest[pos+i-1] = vect[i]

By opposition with arrays starting at 0:

function copyAtPos (dest, vect, i):
    for i from 0 -> vect.length-1 do
        dest[pos+i] = vect[i]

If you begin writing big convolutions formula, it becomes a must.

OwnerDisplayName: poulejapon


答: I think that when you're trying to think about how your code works at a lower level, if this becomes necessary, zero-based arrays map more nicely to this lower level.  Also, I'd assume that you'd need an extra add instruction for every dereference of a one-based array to make the pointers work correctly.  I see one way around this (make the pointer point to the -1st/0th element of the array, not the 0th/1st), but that might wreak havok with garbage collectors, since you now have pointers pointing outside their allocated blocks.</p>

Title: Why are zero-based arrays the norm?

OwnerDisplayName: dsimcha


答:
There are actually several different ways to implement this:

0-based array indexes

1-based array indexes

either 0 or 1 based arrays (like VB 6.0... this is truly horrible)

Ultimately, I don't think it matter whether a language uses 0 or 1 based arrays.
But, I think the best choice is to use 0-based arrays, for the simple reason that most programmers are used to that convention, and it is consistent with the vast majority of already written code.

The only way you can really go wrong, though, is to be inconsistent like Visual Basic. The code base that I am currently maintaining is split between 0 and 1 based arrays; and it is exceedingly difficult to figure out which is which. This leads to an annoyingly verbose for loop:

```<code>dim i as integer, lb as integer, ub as integer
lb = LBound(array)
ub = UBound(array)
for i = lb to ub
       '...
next
</code>```

Title: Why are zero-based arrays the norm?

Body:
There are actually several different ways to implement this:

0-based array indexes

1-based array indexes

either 0 or 1 based arrays (like VB 6.0... this is truly horrible)

Ultimately, I don't think it matter whether a language uses 0 or 1 based arrays.
But, I think the best choice is to use 0-based arrays, for the simple reason that most programmers are used to that convention, and it is consistent with the vast majority of already written code.

The only way you can really go wrong, though, is to be inconsistent like Visual Basic. The code base that I am currently maintaining is split between 0 and 1 based arrays; and it is exceedingly difficult to figure out which is which. This leads to an annoyingly verbose for loop:

dim i as integer, lb as integer, ub as integer
lb = LBound(array)
ub = UBound(array)
for i = lb to ub
       '...
next

OwnerDisplayName: Colin


答:
At the most atomic level, its simply due down to being binary.

```<code>0   =>  0
1   =>  1
10  =>  2
11  =>  3
</code>```

"0" is the first binary number, and likewise arrays are index by their "first" binary number.

Also, given An arbitrary base address for a dataset, the first record exists at that address, not that address + 1,

```<code>$base = 010110;
$firstvalue  = $base + 0 * $unitsize
$secondvalue = $base + 1 * $unitsize
$thirdvalue  = $base + 2 * $unitsize
</code>```

If you had a "1" based array the internal system would have to constantly decrement the target value by 1 to find the underlying memory address that data was stored at.

0 is just as much the first binary number as it is the first decimal number. Not compelling.

Write the number "0" on a page.  How many numbers do you have?

If I have the numbers 500 to 550 on the page, how many numbers do I have?  I have 51! But the difference is only 50.

Put 50 sheep in a paddock. Surprisingly, none of them look like numbers, but they are still a countable volume.

We however have this crazy idea that when a sheep looks a little bit too much like a 0, it must not be used, and it must be thrown out and we have to find a sheep looking like 50 to take its place.

Simplified

Use 1 to N for counting.
But 0 is still a valid place holding symbol, and as such, it should be used.

If 0 is not a valid place holding symbol, then we should scrap 10, 20, 30, 40 ... etc from our number system, and go straight from 9 to 11.

1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19 21 22 23 24 25 26 27

In essence, we humans not starting with "0" is a CULTURAL thing. Its not a rational one.

Title: Why are zero-based arrays the norm?

Body:
At the most atomic level, its simply due down to being binary.

0   =>  0
1   =>  1
10  =>  2
11  =>  3

"0" is the first binary number, and likewise arrays are index by their "first" binary number.

Also, given An arbitrary base address for a dataset, the first record exists at that address, not that address + 1,

$base = 010110;
$firstvalue  = $base + 0 * $unitsize
$secondvalue = $base + 1 * $unitsize
$thirdvalue  = $base + 2 * $unitsize

If you had a "1" based array the internal system would have to constantly decrement the target value by 1 to find the underlying memory address that data was stored at.

0 is just as much the first binary number as it is the first decimal number. Not compelling.

Write the number "0" on a page.  How many numbers do you have?

If I have the numbers 500 to 550 on the page, how many numbers do I have?  I have 51! But the difference is only 50.

Put 50 sheep in a paddock. Surprisingly, none of them look like numbers, but they are still a countable volume.

We however have this crazy idea that when a sheep looks a little bit too much like a 0, it must not be used, and it must be thrown out and we have to find a sheep looking like 50 to take its place.

Simplified

Use 1 to N for counting.
But 0 is still a valid place holding symbol, and as such, it should be used.

If 0 is not a valid place holding symbol, then we should scrap 10, 20, 30, 40 ... etc from our number system, and go straight from 9 to 11.

1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19 21 22 23 24 25 26 27

In essence, we humans not starting with "0" is a CULTURAL thing. Its not a rational one.

OwnerDisplayName: Kent Fredric


答:
Certain types of array manipulation get crazy complicated with 1-based arrays, but remain simpler with 0-based arrays.

I did some numerical analysis programming at one point.  I was working with algorithms to manipulate compressed, sparse matrices, written in both FORTRAN and C++.

The FORTRAN algorithms had a lot of a[i + j + k - 2], while the C++ had a[i + j + k], because the FORTRAN array was 1-based, while the C++ array was 0-based.

Title: Why are zero-based arrays the norm?

OwnerDisplayName: Jay Bazuzi


答:
Why not 2 or 3 or 20? It isn't like having 1-based arrays is somehow easier or simpler to understand then zero based arrays. In order to switch to 1-based arrays, every programmer out there would have to relearn how to work with arrays.

And furthermore, when you're dealing with offsets into existing arrays, it makes more sense too.  If you've read 115 bytes out of an array, you know the next chunk starts at 115.  And so on, the next byte is always the size of the byte's you've read. With 1-based you'd need to add one all the time.

And you do sometimes need to deal with chunks of data in arrays, even in language without "true" pointer arithmetic. In java you could have data in memory mapped files, or buffers. In that case, you know block i is at size * i.  With a 1-based index it would be at block*i+1.

With 1-based indexing, a lot of techniques would require +1s all over the place.

Title: Why are zero-based arrays the norm?

OwnerDisplayName: Chad Okere


答:
If you use zero-based arrays, the array's length is the set of the valid indices. At least, that's what Peano arithmetic says:

```<code>0 = {}
1 = 0 U {0} = {0}
2 = 1 U {1} = {0,1}
3 = 2 U {2} = {0,1,2}
...
n = n-1 U {n-1} = {0,1,2...n-1}
</code>```

So it's the most natural notation, in a sense.

Title: Why are zero-based arrays the norm?

Body:
If you use zero-based arrays, the array's length is the set of the valid indices. At least, that's what Peano arithmetic says:

0 = {}
1 = 0 U {0} = {0}
2 = 1 U {1} = {0,1}
3 = 2 U {2} = {0,1,2}
...
n = n-1 U {n-1} = {0,1,2...n-1}

So it's the most natural notation, in a sense.

OwnerDisplayName: Eduardo León


答:
A heap is one example of the advantages to 1-based arrays. Given an index i, the index of i's parent and left child are

PARENT[i] = i ÷ 2

LCHILD[i] = i × 2

But only for 1-based arrays. For 0-based arrays you have

PARENT[i] = (i + 1) ÷ 2 - 1

LCHILD[i] = (i + 1) × 2 - 1

And then you have the property that i is also the size of the sub-array to that index (i.e. indices in the range [1,i]).

But in the end it doesn't matter, because you can make a 0-based array into a 1-based array by allocating one more element than normal, and ignoring the zeroth.  Thus you can opt-in to get the benefits of 1-based arrays when appropriate, and keep the 0-based arrays for cleaner arithmetic in almost all the other situations.

Title: Why are zero-based arrays the norm?

OwnerDisplayName: sgm


答: Half-open intervals compose well.  If you're dealing in 0 <= i < lim and you want to extend by n elements, the new elements have indices in the range lim <= i < lim + n.  Working with zero-based arrays makes arithmetic easier when splitting or concatenating arrays or when counting elements.  One hopes the simpler arithmetic leads to fewer fencepost errors.

Title: Why are zero-based arrays the norm?

OwnerDisplayName: Norman Ramsey


答:
It is just so, and has been for many years.   To change it, or even to debate it, is just as pointless as to change or debate changing traffic lights. Let's make blue=stop, red=go.

Look into changes made over time in Numerical Recipes for C++.  They had used macros to fake 1-based indexing, but in the 2001 edition gave up and joined the herd.  There may be enlighting material on the reasons behind this at their site www.nr.com

BTW, also annoying is the variants of specifying a range out of an array. Example: python vs. IDL; a[100:200] vs a[100:199] to get 100 elements.  Just gotta learn the quirks of each language.  To change a language that does it one way to match the other would cause such cussing and gnashing of teeth, and not solve any real problem.

Title: Why are zero-based arrays the norm?

OwnerDisplayName: DarenW


答: I don't think any of us can provide a stronger argument than Edsger W. Dijkstra's article "Why numbering should start at zero".</p>

Title: Why are zero-based arrays the norm?

OwnerDisplayName: Bill the Lizard


答:
I'm going to step out on a limb here and suggest something different than an integer 'keyed' array.

I think your coworker is getting at creating a one to one mapping of a 'set' in the physical world where we always start counting at 1.  I can understand this, when you are not doing anything fancy, it is easy to understand some code when you are mapped 1 to 1 between software and the physical world.

My suggestion

Don't use integer based arrays for whatever you are storing, but use some other kind of dictionary or key value pair.  These map better to real life as you aren't bound by an arbitrary integer.  This has its place and I would recommend using it as much as you can due to the benifits of mapping concepts 1 to 1 between software and the physical world.

i.e. kvp['Name Server'] = "ns1.example.com";  (This is just one out of a million possible examples).

Discaimer

This most definitely not work when you are working with concepts based in mathmatics, basically because math is closer to the actual implementation of a computer.  Using kvp sets are not going to help anything here, but will actually mess things up and make it more problematic.  I haven't thought through all the corner cases where something may work better as kvp or as an array.

The end idea is to use the zero-based arrays or key value pairs where it makes sense, remember that when you only have a hammer, every problem starts looking like a nail...

Title: Why are zero-based arrays the norm?

OwnerDisplayName: Redbeard 0x0A


答:
As a 10+yr C/C++ programmer, with a very strong background in Pascal and Delphi, I still miss Pascal's strong array bound and index type checking, and the flexibility and safety that comes with it. An obvious example of this is an array data holding values for each month.

Pascal:

```<code> Type Month = (Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec);

  Var Days[Month] of integer;

  ...
  if Year mod 4 = 0 then // yes this is vastly simplified for leap years and yes i don't know what the comment marker is in pascal and no i won't go look it up
    Days[Feb] := 29
  else
    Days[Feb] := 28;
</code>```

Writing similar code in C languages without using +/-1's or 'magic numbers' is pretty challenging. Note that expressions like Days[2] and Days[Jan+Dec] simply won't compile, which can appear brutal to people who still think in C or Assembler.

I have to say there are many aspects of Pascal/Delphi languages that I don't miss a bit, but C zero-based arrays do seem just "dumb" by comparison.

Title: Why are zero-based arrays the norm?

Body:
As a 10+yr C/C++ programmer, with a very strong background in Pascal and Delphi, I still miss Pascal's strong array bound and index type checking, and the flexibility and safety that comes with it. An obvious example of this is an array data holding values for each month.

Pascal:

 Type Month = (Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec);

  Var Days[Month] of integer;

  ...
  if Year mod 4 = 0 then // yes this is vastly simplified for leap years and yes i don't know what the comment marker is in pascal and no i won't go look it up
    Days[Feb] := 29
  else
    Days[Feb] := 28;

Writing similar code in C languages without using +/-1's or 'magic numbers' is pretty challenging. Note that expressions like Days[2] and Days[Jan+Dec] simply won't compile, which can appear brutal to people who still think in C or Assembler.

I have to say there are many aspects of Pascal/Delphi languages that I don't miss a bit, but C zero-based arrays do seem just "dumb" by comparison.

OwnerDisplayName: Roddy


答:
Zero is natural when talking about the location of an item in a linear collection.

Think of a shelf full of books - the first book is located flush with the side wall of the shelf - that's location zero.

So I guess it depends on whether you consider array indices a means of finding things or referring to things.

OwnerDisplayName: DrJokepu

Title: Why are zero-based arrays the norm?


答:
Authority argument

Well... Apparently, most languages, including very recent ones, are zero-based. As those languages were written by quite skilled people, your friend must be wrong...

Why one?

why 1 would be a better starting index than zero? Why not 2, or 10? The answer itself is interesting because it shows a lot about the though process of the people defending the idea.

The first argument is that it's more natural, because the 1st is usually the one before all others, at least, for the majority of people...

The number-one argument is that the last index is also the size of the array...

I'm still impressed by the "quality" of the reasons I usually hear for this kind of arguments... And even more when I'm reminded that...

Why not zero?

... "One-based" notations are left-overs from the western culture that ignored the existence of zero for centuries, if not more.

Believe it or not, the original gregorian calendar goes from -3, -2, -1, 1, 2, 3... Try to imagine the problem it contributed to western science (for example, how many years from 1st January -2 to 1st January 2 to see than the original gregorian calendar conflicts with something as simple as substraction...).

Keeping to one-based arrays is like (well, I'll be downmodded for that... ^_^ ...), keeping to miles and yards in the 21th century...

Why Zero? Because it's math!

<s>First</s> (OOops... Sorry... I'll try again)

Zero, Zero is nothing, one is something. And some religious texts hold that "At the beginning, there was nothing". Some computer-related discussion can be as burning as religious debates, so this point is not so out of topics as it seems... ^_^

First, It's easier to work with a zero-based array and ignore its zero-th value than work with one-based array and hack around to find its zero-th value. This reason as almost as stupid as the previous, but then, the original argument in favor of one-based arrays was quite a fallacy, too.

Second, Let's remember that when dealing with numbers, chances are high you'll deal with math one moment or another, and when you deal with math, chances are good you are not in the mood for stupid hacks to get around obsolete conventions. The One-based notation plagued maths and dates for centuries, too, and by learning from our mistakes, we should strive to avoid it in future oriented sciences (including computer languages).

Third, As for computer language arrays being tied to hardware, allocate a C array of 21 integers, and move the pointer 10 indices to the right, and you'll have a natural [-10 to 10] array. This is not natural for hardware. But it is for maths. Of course, math could be obsolete, but the last time I checked, most people in the world believed it was not.

Four, As already pointed elsewhere, even for discrete position (or distances reduced to discrete values), the first index would be zero, like the floor in a building (starting at zero), the decreasing countdown (3, 2, 1, ZERO!), the ground altitude, the first pixel of an image, the temperature (zero Kelvin, for the absolute zero, or zero centigrade degrees, as water freezing temperature of 273 K). In fact, the only thing that really starts with one is the traditional way of "first, second, third, etc." iteration notation, which leads me naturally to the next point...

Five the next point (which naturally follows the previous) is that high-level containers should be accessed, not by index, but by iterators, unless the indices themselves have an intrinsic value. I'm surprised your "higher-level-language" advocate did not mention that. In the case the index itself is important, you can bet half the time you have a math-related question in mind. And thus, you'd like your container to be math-friendly, and not math-disabled like "thy olde gregorian calendar" starting at 1, and needing regurgitated hacks to make it work.

Conclusion

The argument given by your fellow programmer is a fallacy because it needlessly ties spoken/written language habits, which are, by nature, blurry, to computer languages (where you don't want your instruction blurred), and because by attributing wrongly an hardware reason to this problem, he.she hopes to convince you, as languages go higher and higher in abstraction, that the zero-based array is a thing of the past.

Zero-based arrays are zero-based because of math-related reasons. Not for hardware-related reasons.

Now, if this is a problem to your fellow programmer, have him start to program with real high level constructs, like iterators and foreach loops.

Title: Why are zero-based arrays the norm?

OwnerDisplayName: paercebal


答:
Personally, the one argument is when seeing array indexes as offsets. It just makes sense.

One could say that its the first element, but the offset of the first element relative to the origin of the array is zero. As such, taking the array origin and adding zero will yield the first element.

So in computing its easier to add zero to find the first element than to add one and then remove one.

I think anyone who did some lower level stuff always think the base zero way. And the people who are beginning or used to higher level often not-algorithmic programming might wish for a base one system. Or maybe we are just biased by past experiences.

Title: Why are zero-based arrays the norm?

OwnerDisplayName: Loki


答:
I prefer 0 based index since since modulo (and the AND operator when used for modulo) always returns 0 for some values.

I often find myself using arrays like this:

```<code>int blah = array[i & 0xff];
</code>```

I often get that kind of code wrong when using 1 based indices.

Title: Why are zero-based arrays the norm?

Body:
I prefer 0 based index since since modulo (and the AND operator when used for modulo) always returns 0 for some values.

I often find myself using arrays like this:

int blah = array[i & 0xff];

I often get that kind of code wrong when using 1 based indices.

OwnerDisplayName: Laserallan


答: The index in an array is not really an index. It is simply an offset that is the distance from the start of the array. The first element is at the start of the array so there is no distance. Therefore the offset is 0.</p>

Title: Why are zero-based arrays the norm?

OwnerDisplayName: Thomas


答:
It is hard to defend 0-base without programming a lot of array-based code, such as string searching and various sorting/merging algorithms, or simulating multi-dimensional arrays in a single-dimension array. Fortran is 1-based, and you need a lot of coffee to get this kind of code done right.

But it goes way beyond that. It is a very useful mental habit to be able to think about the length of something rather than the indices of its elements. For example, in doing pixel-based graphics, it is much clearer to think of coordinates as falling between pixels rather than on them. That way, a 3x3 rectangle contains 9 pixels, not 16.

A little more far-fetched example is the idea of look-ahead in parsing, or in printing sub-totals in a table. The "common-sense" approach says 1) get the next character, token, or table row, and 2) decide what to do with it. The look-ahead approach says 1) assume you can see it, and decide if you want it, and 2) if you do want it, "accept" it (which allows you to see the next one). Then if you write out the pseudo-code, it is much simpler.

Still another example is how to use "goto" in languages where you have no choice, such as MS-DOS batch files. The "common-sense" approach is to attach labels to blocks of code to be done, and label them as such. Often a better approach is to put labels at the ends of blocks of code, for the purpose of skipping over them. This makes it "structured" and much easier to modify.

Title: Why are zero-based arrays the norm?

OwnerDisplayName: Mike Dunlavey


答:
The only two (very) serious reasons to used 0-based indices instead of 1-based indices seem to avoid reeducating a lot of programers AND for backward compatiblity.

I didn't see any other serious arguments against 1-based indices in all the answers you received.

In fact, indices are naturally 1-based, and here is why.

First, we must ask : Were does arrays come from ? Do they have real-world equivalents ? The answer is yes : they are how we modelize vectors and matrix in computer science. However, Vectors and matrix are mathematicals concepts that were using 1-based indices before the computer-era (and that still mostly use 1-based indices nowaday).

In the real world, indices are 1-bases.

As Thomas said above, languages that used 0-bases indices are in fact using offsets, not indices. And developers who are using these languages think about offsets, not indices. This would not be a problem if things were clearly stated, but they are not. A lot of developers using offsets still talk about indices. And a lot of developers using indices still don't know that C, C++, C#, ... use offsets.

This is a wording problem.

(Note about Diskstra's paper - It says exactly what I have said above : mathematician do use 1-based indices. But Diskstra think that matematicians should not use them because some expression would then be ugly (eg.: 1 <= n <= 0). Well, not sure he is right on that one - doing such a paradigm shift in order to avoid those exceptional empty sequences seems a lot of trouble for a little result...)

Title: Why are zero-based arrays the norm?

OwnerDisplayName: Sylvain


答:
Have you ever been annoyed by "20th century" actually referring to the 1900s? Well, it's a good analogy for the tedious things you deal with all the time when using 1-based arrays.

Consider a common array task like the .net IO.stream read method:

```<code>int Read(byte[] buffer, int offset, int length)
</code>```

Here is what I suggest you do to convince yourself 0-based arrays are better:

In each indexing style, write a BufferedStream class that supports reading. You may change the definition of the Read function (eg. use a lower bound instead of an offset) for the 1-based arrays. No need for anything fancy, just make it simple.

Now, which one of those implementations is simpler? Which one has +1 and -1 offsets sprinkled here and there? That's what I thought. In fact I would argue that the only cases where the indexing style doesn't matter is when you should have used something that wasn't an array, like a Set.

Title: Why are zero-based arrays the norm?

Body:
Have you ever been annoyed by "20th century" actually referring to the 1900s? Well, it's a good analogy for the tedious things you deal with all the time when using 1-based arrays.

Consider a common array task like the .net IO.stream read method:

int Read(byte[] buffer, int offset, int length)

Here is what I suggest you do to convince yourself 0-based arrays are better:

In each indexing style, write a BufferedStream class that supports reading. You may change the definition of the Read function (eg. use a lower bound instead of an offset) for the 1-based arrays. No need for anything fancy, just make it simple.

Now, which one of those implementations is simpler? Which one has +1 and -1 offsets sprinkled here and there? That's what I thought. In fact I would argue that the only cases where the indexing style doesn't matter is when you should have used something that wasn't an array, like a Set.

OwnerDisplayName: Strilanc


答:
With zero-based arrays, you can use an unsigned int as the index and then you don't have to test for index out of range on the lower bound. e.g:</p>

```<code>int GetValue(unsigned index)
{
    ASSERT(index < arraySize);
    return(array[index];
}
</code>```

Title: Why are zero-based arrays the norm?

Body:
With zero-based arrays, you can use an unsigned int as the index and then you don't have to test for index out of range on the lower bound. e.g:

int GetValue(unsigned index)
{
    ASSERT(index < arraySize);
    return(array[index];
}

OwnerDisplayName: Jason Williams


答:
I prefer 0-based arrays because, as mentioned by others, it makes math easier.  For example, if we have a 1-dimensional array of 100 elements emulating a 10x10 grid, then what is the array index i of the element in row r, col c:

```
0-based: i = 10 * r + c
1-based: i = 10 * (r - 1) + c
```

And, given the index i, going back to the row and column is:

```
0-based: c = i % 10
         r = floor(i / 10)
1-based: c = (i - 1) % 10 + 1
         r = ceil(i / 10)
```

Given that the math above is clearly more complex when using 1-based arrays, it seems logical to choose 0-based arrays as the standard.

However, I think that someone could claim that my logic is flawed because I assume that there would be a reason to represent 2D data in a 1D array.  I have run into a number of such situations in C/C++, but I must admit that needing to perform such computations is somewhat language dependent.  If arrays truly performed all index math for the client, all the time, then the compiler could simply convert your M-based array accesses to 0-based at compile-time and hide all of these implementation details from the user.  In fact, any compile-time constant could be used to do the same set of operations, although such constructs would probably just lead to incomprehensible code.

Perhaps a better argument would be that minimizing the number of array index operations in a language with 1-based arrays would require that integer division be performed using the ceiling function.  However, from a mathematical perspective, integer division should return d remainder r, where d and r are both positive.  Therefore, 0-based arrays should be used to simplify math.

For example, if you are generating a lookup table with N elements, the nearest index prior to the current value into the array for value x would be (approximately, ignoring values where the result is an integer prior to rounding):

```
0-based with floor: floor((N - 1) * x / xRange)
1-based with floor: floor((N - 1) * x / xRange) + 1
1-based with ceil : ceil ((N - 1) * x / xRange)
```

Notice that if the standard convention of rounding down is used, 1-based arrays require an additional operation, which is undesirable.  This kind of math cannot be hidden by the compiler, as it requires lower-level knowledge about what is happening behind the scenes.

Title: Why are zero-based arrays the norm?

Body:
I prefer 0-based arrays because, as mentioned by others, it makes math easier.  For example, if we have a 1-dimensional array of 100 elements emulating a 10x10 grid, then what is the array index i of the element in row r, col c:

0-based: i = 10 * r + c
1-based: i = 10 * (r - 1) + c

And, given the index i, going back to the row and column is:

0-based: c = i % 10
         r = floor(i / 10)
1-based: c = (i - 1) % 10 + 1
         r = ceil(i / 10)

Given that the math above is clearly more complex when using 1-based arrays, it seems logical to choose 0-based arrays as the standard.

However, I think that someone could claim that my logic is flawed because I assume that there would be a reason to represent 2D data in a 1D array.  I have run into a number of such situations in C/C++, but I must admit that needing to perform such computations is somewhat language dependent.  If arrays truly performed all index math for the client, all the time, then the compiler could simply convert your M-based array accesses to 0-based at compile-time and hide all of these implementation details from the user.  In fact, any compile-time constant could be used to do the same set of operations, although such constructs would probably just lead to incomprehensible code.

Perhaps a better argument would be that minimizing the number of array index operations in a language with 1-based arrays would require that integer division be performed using the ceiling function.  However, from a mathematical perspective, integer division should return d remainder r, where d and r are both positive.  Therefore, 0-based arrays should be used to simplify math.

For example, if you are generating a lookup table with N elements, the nearest index prior to the current value into the array for value x would be (approximately, ignoring values where the result is an integer prior to rounding):

0-based with floor: floor((N - 1) * x / xRange)
1-based with floor: floor((N - 1) * x / xRange) + 1
1-based with ceil : ceil ((N - 1) * x / xRange)

Notice that if the standard convention of rounding down is used, 1-based arrays require an additional operation, which is undesirable.  This kind of math cannot be hidden by the compiler, as it requires lower-level knowledge about what is happening behind the scenes.

OwnerDisplayName: Jeff G