答:
I think a person who has power over the others would be enough, administrator or moderator to cut irrelevant comments, speed up reviewing things that need quick review. Single decision maker.

Minus of this would be that this person has to do it as main task, while he could be doing something else, and probably you would like to have most experienced person on this position.

Second thing is automating as much as you can!

controling white spaces

style controling software

automated builds before code review

automated testing before code review

Those things will remove at least some things that people might comment without real need.
If it is not building or have trailing whitespaces it is not good enough for review, fix it and apply for review again. If it is not building or some test fail then it is obvious that it is not good enough.

Lot of it depends on your technologies, but find what you can check automatically the more the better.

We have not won this battle yet, but that is what we found useful.

Title: Good guidelines and practices for mandatory code review

Body:
We are trying out mandatory code review on each commit -- nothing gets into master that hasn't been validated by at least 1 person not the author -- for a couple of sprints. We have buy in from both developers and management (which is an amazing situation to be in) and we want to get some of the benefits that it is known for:

obvious bug reduction

more awareness of changes happening around the project

the "I know someone is going to look at this so I won't be lazy"/anti-cowboy effect

increased consistency within/across projects

But we're introducing something that is known to reduce velocity, and if done wrong could create a stupid bureaucratic step in the commit pipeline that doesn't do anything but take up time. Things that I'm concerned about:

reviews devolving into just nit picking

(hyperbolically) people opening up huge architectural issues as part of a two line commit review.

I don't want to bias answers with other things.

While we're all reasonable people and we'll be doing a lot of self analysis, we could definitely use some battle-won insight into what kinds of things we should be trying to accomplish in a review session to really make reviews work for us. What are some guidelines and policies that you have found to work?


问:
Software without a testable goal
I hope you bear with me here. It's difficult to explain this problem, especially so without direct reference to the specific domain.

I work on a component of a larger system which performs computationally expensive pre-processing in order that the "real-time" component can perform it's functions quickly. My product effectively creates a big lookup dataset for the main component to query.

My product computes the results of a finite set of "scenarios" (a few hundred thousand) any one of which may be performed by a customer. The component uses a k-shortest paths algorithm and a number of rules engines to consider each scenario and build up the lookups, operating on reference data that represents the problem domain.

For the scenarios that are very commonly performed by our customers the test cases are easy; the expected outcomes are easy to devise and assert acceptance tests. However, for the scenarios that are not "popular", the expected outcomes are difficult to establish and in any case their outcomes may be changed by changes to the reference data which are virtually impossible to predict. In other words, changes to the reference data changes the inputs to the shortest-path algorithm which in turn may change the output.

Creating acceptance tests for these unpopular cases is also tricky, because the business "doesn't know what it doesn't know", and so has no baseline against which it can be tested.

Whenever a tester comes back to me with a defect, 99.9% certainty it's because conditions in the reference data have changed, rather than because of any code changes. I therefore spend a load of time chasing defects that are "data issues". I think what confuses the situation is that the reference data is key to the functionality of the system, and the system without a specific set of reference data would produce no results that had any meaning to the business. I could create a set of "fake" reference data against which to test, but any assertion against this engineered reference data would be invalid in the real world.

I would be very interested to hear any perspectives on this especially from those who have encountered similar problems. I am anxious not to simply shrug my shoulders and reply "data issue" but get to the root of the problem and work out how to build and test this thing in a reliable, repeatable and valuable way.

答:
I think you discount fake data to quickly.  The point of testing is to show that your k shortest path implementation is in fact finding shortest paths, not that it works on the exact user input.  If it works on good enough fake data it will work on real data modulo any errors in the data or your understanding of the data.

It sounds like you need two rounds of testing, one for your algorithm (with fake data meant to exercise every code path not just the ones the customer happens to use) and one for the data to verify its integrity and compatibility(that should be treated as data errors until shown otherwise).

ContentLicense: CC BY-SA 3.0

Title: Software without a testable goal


问:
How to best protect from 0 passed to std::string parameters?
I have just realized something disturbing.  Every time I have written a method that accepts a std::string as a paramater, I have opened up myself to undefined behaviour.

For example, this...

```<code>void myMethod(const std::string& s) {
    /* Do something with s. */
}
</code>```

...can be called like this...

```<code>char* s = 0;
myMethod(s);
</code>```

...and there's nothing I can do to prevent it (that I am aware of).

So my question is: How does someone defend themself from this?

The only approach that comes to mind is to always write two versions of any method that accepts an std::string as a parameter, like this:

```<code>void myMethod(const std::string& s) {
    /* Do something. */
}

void myMethod(char* s) {
    if (s == 0) {
        throw std::exception("Null passed.");
    } else {
        myMethod(string(s));
    }
}
</code>```

Is this a common and/or acceptable solution?

EDIT:  Some have pointed out that I should accept const std::string& s instead of std::string s as a parameter.  I agree.  I modified the post.  I don't think that changes the answer though.

答:
I don't think you should protect yourself. It's undefined behavior on the caller's side. It's not you, it's the caller who calls std::string::string(nullptr), which is what is not allowed. The compiler lets it be compiled, but it lets other undefined behaviors be compiled as well.

The same way would be getting "null reference":

```<code>int* p = nullptr;
f(*p);
void f(int& x) { x = 0; /* bang! */ }
</code>```

The one who dereferences the null pointer is making UB and is responsible for it.

Moreover, you cannot protect yourself after undefined behavior has happened, because the optimizer is in its full right to assume that the undefined behavior had never happened, so the checks if c_str() is null can be optimized out.

Body:
I don't think you should protect yourself. It's undefined behavior on the caller's side. It's not you, it's the caller who calls std::string::string(nullptr), which is what is not allowed. The compiler lets it be compiled, but it lets other undefined behaviors be compiled as well.

The same way would be getting "null reference":

int* p = nullptr;
f(*p);
void f(int& x) { x = 0; /* bang! */ }

The one who dereferences the null pointer is making UB and is responsible for it.

Moreover, you cannot protect yourself after undefined behavior has happened, because the optimizer is in its full right to assume that the undefined behavior had never happened, so the checks if c_str() is null can be optimized out.


问:
Source code vs source files?
I'm in a situation with my company where this may be an important distinction.

Is there any distinction between "source code" and "source files" in a technical context?

Is there any distinction between "source code" and "source files" in a legal context?

Thanks.

Edit: I saw some close votes on this. I want to note that this is a possible issue between two companies - and where necessary, we'll definitely use legal counsel. I'm asking this because I'm attempting to be prepared if I'm asked for any technical definitions (as the developer role in this).

答:
Technically:

Source files are anything that is in source control.  This could be source code or other types of files such as deployment scripts, content, configuration files, etc.  Anything that is produced by your organization that is part of a deployment.

Source code are files that compiled into a DLL or EXE OR a file (script) that is parsed and interpreted at runtime.

Legally:

From a legal prospective source code/files that are distributed to end users will have a license agreeement that governs its use, distribution, and any corresponding restrictions.  You probably have encounted many of these when downloading a product or product update.  Usually these are long and written by lawyers to protect the company.  In most cases, end users simply click next and install the software.

Additionally, there may be a separate license aggreement on using the source code itself (open source) that governs its use, distribution, and restrictions of using the code for commercial or non-commercial purposes.

If you need to identify any differences between source code/source file it should be defined in the legalese in the licensing agreements for your product/code.

Open source licensing link on WIKIPedia

Title: Source code vs source files?


答:
A good approach to this (assuming your company has the stomach for it) would be to model several  major classes of customer data scenarios as testable requirements, write testable requirements for those, and then write tests for those requirements.  To identify the generalizations that define the most common of the uncommon scenarios, in other words, and make sure your software adequately addresses them.

This would have several benefits.  Your company would understand their software better, have the tools for creating better customer documentation and service, and maybe even identify ways to utilize the software that were previously unforeseen.

Any such effort would have to be driven directly by customer feedback, so that you can justify the effort for those scenarios that have a genuine customer interest.  In other words, you don't just go looking for scenarios that might be useful.

Title: Software without a testable goal

Body:
I hope you bear with me here. It's difficult to explain this problem, especially so without direct reference to the specific domain.

I work on a component of a larger system which performs computationally expensive pre-processing in order that the "real-time" component can perform it's functions quickly. My product effectively creates a big lookup dataset for the main component to query.

My product computes the results of a finite set of "scenarios" (a few hundred thousand) any one of which may be performed by a customer. The component uses a k-shortest paths algorithm and a number of rules engines to consider each scenario and build up the lookups, operating on reference data that represents the problem domain.

For the scenarios that are very commonly performed by our customers the test cases are easy; the expected outcomes are easy to devise and assert acceptance tests. However, for the scenarios that are not "popular", the expected outcomes are difficult to establish and in any case their outcomes may be changed by changes to the reference data which are virtually impossible to predict. In other words, changes to the reference data changes the inputs to the shortest-path algorithm which in turn may change the output.

Creating acceptance tests for these unpopular cases is also tricky, because the business "doesn't know what it doesn't know", and so has no baseline against which it can be tested.

Whenever a tester comes back to me with a defect, 99.9% certainty it's because conditions in the reference data have changed, rather than because of any code changes. I therefore spend a load of time chasing defects that are "data issues". I think what confuses the situation is that the reference data is key to the functionality of the system, and the system without a specific set of reference data would produce no results that had any meaning to the business. I could create a set of "fake" reference data against which to test, but any assertion against this engineered reference data would be invalid in the real world.

I would be very interested to hear any perspectives on this especially from those who have encountered similar problems. I am anxious not to simply shrug my shoulders and reply "data issue" but get to the root of the problem and work out how to build and test this thing in a reliable, repeatable and valuable way.


问:
What must be done to allow a development team to minimize difficulties as new team members are added?
I work at a small Web Dev firm, and have been handling all the PHP/MySQL/etc. for a while. I'm looking at improving our practices to allow for easier collaboration as we grow. Some things I have in mind are:

Implementing a versioning system (source control)

Coding standards for the team (unless
mandated by a certain framework,
etc.)

Enforcing a common directory
structure for our Desktops (for
backup purposes, etc.)

Web-based
task/project/time/file/password/contact
management and collaboration
app(we've tried a bunch; I may just
create one)

What do more experienced developers view as necessary first steps in this area? Do you recommend any books? One thing to consider is that the bulk of our daily tasks involve maintenance and adding minor functionality rather than new projects, and the team size will be between 3 and 5.

I just found a related question about teams that will be expanding from a solo developer.

答:
Chat is Awesome

All you really need to collaborate, IMO, is anything with chat and file transfer and something like Google docs for issue tracking. I've found Skype to be among the most useful tools at every company I've worked at that adopted it.

Chat is invaluable because it lets you inform people of issues or concerns that aren't immediately blocks without having to wait around and wait for them to finish off another conversation, etc. and it tends to get a more immediate look than e-mail.

Also, the one thing I like about Scrum-like processes is the daily standup, except just chat it at roughly the same time of day. No meeting room waits. It's easier for people to work at home when sick or waiting on the cable guy or whatever... And it's valuable to have that written record so you can document frequently recurring issues when you see the same things coming up over and over again. Create a different room for that daily check-in so it's kept clear of all the other day to day details that tend to pop up in chat.

Training on Tools/Legacy Code

I've never seen more time wasted on anything else. If you have a tool somebody is unfamiliar with, familiarize them with it. Hand them a good book. Have them sit down with you for occasional debug sessions on an IDE, etc... Likewise with code that you're maintaining or re-using a lot. Make a point of documenting it as you introduce new devs to it and they ask questions, etc. but definitely sit down with people and talk about legacy code before throwing them at it and give them plenty of debug tasks early on so they can dig into a bit more before adding features or re-using portions of it.

Whatever You Choose For Documention, Stick With It

Keeping docs all in one place, written with the same tool, and accessed the same way is huge. You're not doing anybody in the future a favor letting people just doc however, wherever, with whatever they want.

Have the Entire Team Do Estimates for related projects

It is hugely valuable for rookies to get more experienced opinions and ultimately helps everybody get better at it.

Nip Configuration Issues in the Bud

I've been in scenarios where it could take days to configure a new machine. There's no excuse for that. Get all essential tools and pre-configured servers on one build/ghost image keep it up to date as new stuff is added. Don't assume devs can just handle installing their own stuff. It's easy to forget just how many layers of stuff you've added over the years.

Use Version Control Properly

Some of the afore-mentioned configuration issues I've run into were in large part due to another team not feeling comfortable with branching, forcing us to redo about 30 XML config files by hand (that should have never happened either of course) once a month or so whenever we updated a version of the app we maintained. If you're not yet a VCS power-user, become one or hire one. Also don't let Maven, Ant, and an outdated version of Eclipse get into a 15+ XML file fight with each other. It's real ugly.

Update to Latest Versions of Tools/Frameworks/Librabries Whenever Possible

You never know when stuff is going to go out of date and suddenly a new dev has to track down something not available anymore. Stuff like that can also clobber ramp-up time, although usually this issue will be dealt by creating images of everything you need. Another issue you'll dodge is being forced to handle a series of upgrades all in one shot.


问:
Why are
,  and  tags not used much when I see sites that are in HTML 5?
I've noticed that even when a websites front end is coded in HTML 5 as evidenced by the <!DOCTYPE html>, people rarely seem to use the new HTML 5
,  and  tags.

Is it because people don't understand that you're supposed to use reusable classes for styling things within a
 instead of the full path of tag selectors to the element?

答:
First of all, using the <!DOCTYPE html> doctype doesn't imply you are using HTML5. It's a doctype without a HTML version, so it can be used for any HTML version.

I think the main reason why many sites don't use the new HTML5 elements is because HTML5 is not yet officially released:

The HTML Working Group has planned for this implementation phase to last into mid-2014, after which W3C expects to publish the final HTML5 Recommendation, available Royalty-Free to implementers under the W3C Patent Policy.

It also scares some developers off, because of the extra semantical meanings. Writing semantic HTML has been forgotten for years and learning it takes some time and thus money. People also don't understand the advantages of semantic HTML, so why should they invest time in learning it?

At last, HTML5 is not fully implemented yet, which means people have to use polyfills in order to provide browser-compatibility.

Title: Why are <section>, <header> and <footer> tags not used much when I see sites that are in HTML 5?


问:
Reassigning Ownership Automatically
Are there any software licenses that automate the reassignment of ownership?

For instance, in a usual circumstance, you have a license, and then you make all contributors sign off that by contributing they reassign ownership to the project owner.

In the sort of license I'm looking for, by just editing and redistributing the result (whether in source or binary form), the person who had made changes would not only have to redistribute the code but would also have automatically reassigned their ownership to me.

Alternatively, if that's not possible, can I add a binding clause to an existing license that makes it so?

答: IANAL, but that sounds like the whole premise the GPL is based on, by distributing a derivative work you must agree to offer it under the terms of the GPL or you forfeit your own license to use the original.  So why not have the Gimmie Public License that says by redistributing a derivative work you assign ownership rights to Joe Bob Briggs or whoever?  It would seem to be the same concept to me: by doing X you agree to do Y. If you do not do Y you lose your license to do X.</p>

Title: Reassigning Ownership Automatically


问:
How to store historical user data?
I'm trying to think of fine way to store historical data for my web application. The application has users that add photos, comment and grade them. All this is stored in relational database.

The users also have ability to delete own photos (and thus comments/grades) and own account.

I want to store those deleted entities as historical data.
The aim of it is to distinguish categories of what people like to photograph and classify  users towards those categories.

Should I store it in some NoSQL database? Or maybe in my origin database by marking it with is_deleted field? Maybe different table e.g. archived_users, archived_photos? Another database instance for only historical data?

Has anybody dealt with such task and is willing to share thoughts?

So far, I'm using is_deleted flag for photos and backup table (archived_users) for users. Why such distinction? To avoid violating unique constraint on username field.
This solution has 3 problems to me.

It is incoherent to do same thing in 2 ways. Or maybe it's ok?

It is somehow strange moving user to another table (with associations to photos). It creates some superficial fields. Or maybe it's ok?

"Living" data is mixed with historical data. Could it be a performance problem when database is really huge?

答:
Not sure why you want to maintain data the user has explicitly deleted. Given the propensity of hacks, you are leaving yourself open to all sorts of trouble by maintaining the data.

If you really want to maintain it for "historical" purposes, export them to an offline database.

Title: How to store historical user data?


问:
Is a senior programmers advice about always using books a good idea?
I am a junior developer and have only been in the industry for 5 years. At my current company there is a senior let's call him Infestus. Occasionally I am being given opportunity to shine and do something completely brand new from scratch.

One of the most recent examples was that I had to make a singleton in the multithreaded application. I have decided to use this method. As soon as Infestus saw it, he quickly proceeded to call me stupid and told me to use this approach. Upon asking him why he just brushed it off as this is better and that's how this and this book about Java says it is better.

And it is a common pattern: whenever I get a chance to do something new, I quickly get shot down by Infestus and the only reasoning why his method is better is because those books were written by famous programmers. He is always trying to give me books to read so that I may "learn" which ways to program.

I have only been programming for money for 5 years, but is it always a good idea to just blindly follow the book on best ways for solving a problem, or should I try experimenting every now and then? The constant barrage of complaints from the Infestus is starting to cause me to never try anything new and follow examples in books.

EDIT: I am utterly lost. Yes I know that following anything blindly is a bad idea. But this godlike programmer Infestus who seems to know a lot, tells me that the only way to program properly is by reading books and following everything down to a T. All the rules he imposes are the ones written in books, so I am just wondering if books are the only correct way.

EDIT2: Infestus is not my boss. He is just one of senior developers in charge of reviewing the code. And most of his comments after reviews consist of book names where such and such method is wrong.

答:
I'd say that learning programming from books only is impossible, but they good ones will provide you with a huge boost. It's like karate - you won't get black belt only reading about it ;)
I believe that in this partucular case Mr. Infestus was refering to "Effective Java" by Joshua Bloch. It's really a great book about Java development and you should definitely read it if you havent already. </p>


问:
How to prevent deep indentations?
What steps and measures can I take to prevent deep indentations in my code?</p>

答:
The best thing you can do is extract methods:</p>

```<code>int Step1(int state)
{
    if (state == 100)
    {
        return Step2(state);
    }
    else
    {
        return Step3(state);
    }
}

int Step2(int state)
{
    if (state != 100)
    {
        throw new InvalidStateException(2, state);
    }

    // ....
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to prevent deep indentations?

Body:
The best thing you can do is extract methods:

int Step1(int state)
{
    if (state == 100)
    {
        return Step2(state);
    }
    else
    {
        return Step3(state);
    }
}

int Step2(int state)
{
    if (state != 100)
    {
        throw new InvalidStateException(2, state);
    }

    // ....
}


问:
Is functional programming actually used to create applications?

Possible Duplicate:

  What are some well known applications written in F#?

I see a lot of people talking about how cool functional programming is, how awesome Lisp and Haskell and F# are, etc, but what I don't see is them actually being used.  Just about every program on my computer is written in either something in the C family, Delphi, or Python.  I see tutorials talking about how easy it is to use functional languages to do complicated math problems, but no one talking about using them to do things most people actually care about using computers for, like business applications and games.

Does anyone have any examples of actual programs that people have heard of and are using, written in a functional language?  The only one I can think of off the top of my head is Abuse, from almost 15 years ago.  (Things like Emacs, where the core program is written in C with a functional language scripting layer on top, don't count.)

答: Orbitz uses Lisp extensively for it's flight lookup engine.</p>


问:
Good guidelines and practices for mandatory code review
We are trying out mandatory code review on each commit -- nothing gets into master that hasn't been validated by at least 1 person not the author -- for a couple of sprints. We have buy in from both developers and management (which is an amazing situation to be in) and we want to get some of the benefits that it is known for:

obvious bug reduction

more awareness of changes happening around the project

the "I know someone is going to look at this so I won't be lazy"/anti-cowboy effect

increased consistency within/across projects

But we're introducing something that is known to reduce velocity, and if done wrong could create a stupid bureaucratic step in the commit pipeline that doesn't do anything but take up time. Things that I'm concerned about:

reviews devolving into just nit picking

(hyperbolically) people opening up huge architectural issues as part of a two line commit review.

I don't want to bias answers with other things.

While we're all reasonable people and we'll be doing a lot of self analysis, we could definitely use some battle-won insight into what kinds of things we should be trying to accomplish in a review session to really make reviews work for us. What are some guidelines and policies that you have found to work?

答:
We have almost like a checklist:

Show me the task description.

Walk me through the result, and show it
working. Run different scenarios (invalid input, etc).

Show me the
passing tests. What's the test coverage like?

Show me the code -
that's where we're looking for obvious inefficiencies.

Works fairly well.


问:
Python garbage collection giving me a hard time
Context: I am developing a web application using webapp2 web-framework with python to be hosted on GAE.
The web application (web-app from now on), is a chess variant. Being a first timer, I have definitely made a lot of design blunders. One of them, is what this question is regarding to, I will come to it in a short while.

The aim of the web-app was to allow quite a large number of players to play 2-player chess, such that multiple games are running in parallel. While not exceeding the free quota on GAE. (I am a student).

To do that, I thought that I would create a new game object, and store its id(game_object) along with the machine_id of the two players playing on that instance, in the datastore.

When querying the datastore with the machine_id of a player, I could get a id() value, and I thought could use that value as a key in a dictionary wherein a reference to the game_object forms the value.

Doing this, doesn't need me to write/update the datastore, hence saving on the precious writes. I could easily modify the game-state of the game_object, and it could be still referenced by the id().

But, now what happens is, this works fine for a few moves. After that the garbage collection takes place and the game_object is wiped off the memory. Raising a NameError exception.

My question is, can this be solved by creating new game_objects in a separate module where garbage collection is turned off, and then periodically/event-triggered freeing the memory? If not? How do I come around this problem?

答:
You are not running into the Python garbage collection process here. Google App Engine doesn't guarantee that all requests go to the same instance. New instances do not share memory with old instances.

Load your data into memory again when your dictionary is empty.

All that the CPython garbage collector does is break circular references so that the normal reference count mechanism can remove objects from memory when no longer used. Your process has a dictionary referring to your data, and the garbage collector would never touch that data.


答:
Is there any distinction between "source code" and "source files" in a technical context?

My interpretation of this is that a "source file" is a distinct file on a file system that contains source code. "source code" refers to a set of instructions that could be compiled into an executable program, or a library that could be used by a program.

Usually source code is contained in a source file. Cases where this might not be true are situations where a program generates source code in memory and then compiles it. The output object (.exe, .dll, whatever) might be saved to a file, but the generated code might never be saved to a file. If the code generator reads a preferences/configuration file to tell it how to generate the code, I'd call that config file a "source file", but not "source code" since it doesn't get compiled. If the generator operates via a gui and user interaction, then there might not be any source file, and the source code would only exist in memory while the program is running.

A stored procedure is another one which might be tricky: If the author doesn't save the procedure to a file in their local file system, the only other place the code exists is in the database. In Oracle, I think there's actually a table somewhere that stores the code of procedures, but I don't think that data gets stored in a separate table. So in that case, the source code of the procedure is contained in the same file as database data so I don't think you'd have a source file, just source code.

Another situation might be if you have VBA code embedded in an Excel spreadsheet. The spreadsheet contains source code, but it is more than just a source file, as it may also contain data.

Some would say that an example source file that does not contain source code might be something like a DML/DDL file for a database. I'd say they that in a strict sense, they are not source files since they don't get compiled into a program. I might prefer to call them "environment setup files".

Is there any distinction between "source code" and "source files" in a legal context?

I really think you should ask a lawyer who specializes in this area.

Title: Source code vs source files?

Body:
I'm in a situation with my company where this may be an important distinction.

Is there any distinction between "source code" and "source files" in a technical context?

Is there any distinction between "source code" and "source files" in a legal context?

Thanks.

Edit: I saw some close votes on this. I want to note that this is a possible issue between two companies - and where necessary, we'll definitely use legal counsel. I'm asking this because I'm attempting to be prepared if I'm asked for any technical definitions (as the developer role in this).


问:
What is the benefit of hypermedia (HATEOAS)?
I don't understand the benefit to HATEOAS for APIs intended for use by programs (as opposed to humans directly browsing your API).  Sure, the customer isn't bound to a URL schema but they are bound to a data schema which is the same thing in my mind.

For example, assume I want to view an item on an order, let's assume I've discovered or know the order URL already.

HATEOAS:

```<code>order = get(orderURL);
item = get(order.itemURL[5]);
</code>```

non-HATEOAS:

```<code>order = get(orderURL);
item = get(getItemURL(order,5));
</code>```

In the first model I have to know the fact that the order object has an itemURL field.  In the second model I have to know how to construct an item URL.  In both cases I have to "know" something ahead of time so what is HATEOAS actually doing for me?

答:
Explorable API:
It may sound trivial but do not underestimate the power of an explorable API. The ability to browse around the data makes it a lot easier for the client developers to build a mental model of the API and its data structures.

Inline documentation:
The use of URLs as link relations can point client developers to documentation.

Simple client logic:
A client that simply follows URLs instead of constructing them itself, should be easier to implement and maintain.

The server takes ownership of URL structures:
The use of hypermedia removes the client's hard coded knowledge of the URL structures used by the server.

Off loading content to other services:
Hypermedia is necessary when off-loading content to other servers (a CDN for instance).

Versioning with links:
Hypermedia helps versioning of APIs.

Multiple implementations of the same service:
Hypermedia is a necessity when multiple implementations of the same service exists (and one client needs to access more than one of them).

You can find an in-depth explanation of these bullet points here: http://soabits.blogspot.no/2013/12/selling-benefits-of-hypermedia.html


问:
Do I need to understand algorithms and data structures to be called a programmer?
It has been six years since I have been coding. Coding into all kinds of things like ActionScript, JavaScript, Java, PHP, Ajax, XML HTML, ASP, etc. I have used arrays, maps, linked lists, sets, etc and wherever I worked people like me. But whenever I am interviewed it is very likely that people ask me question on hashes, trees, stacks, and queues. Some questions are on juggling some sorting algorithms.  I don't know if I should really know them or should I stop calling myself a programmer. There is something in me which also tells me even if people who are asking all these questions select me, they will never be making me work of these things. Am I really required to know all this?</p>

答:
Great question. Javascript or Java or VC++ are super smart programming languages where you will never need to create a linked list or hash table from scratch. But you still need to have the ability to decide when to use one over the other, the performance penalties and bonuses each accrue etc.

I have interviewed a lot of API programmers aka code monkeys, and in most of the interviews they have routinely failed to design systems that are performance efficient and scalable. Bottom line: knowing loads of API will get you the bread, but for butter you need to start from the basics of computing.


答:
In this situation the data is really part of the algorithm. Just as changes to the code need to be version controlled and unit tested, and the data that drives it needs to go through version control, some sort of verification, and then the two parts should be integration tested.

Sounds like the people who change the reference data need to be defining what their changes are intended to achieve (acceptance criteria), and then testing for those criteria.

You should also be a part of that process, and part of the solution. How can you help them be more successful? Since you don't say anything about the people who change the reference data there is not much to go on, but I'm guessing they (and you) don't see themselves as IT people. So you'll have to help them to see the big picture, where their data and your algorithm work together to produce their required results.

PS I would also add that the code and the reference data should be regression tested separately.

Title: Software without a testable goal


问:
What exactly is my program "linking" with overall?
I have heard that my C++ programs "need to link with the C++ library/runtime". However, the C++ runtime is just the compiler inserting stack operation code in to the image, or "boilerplate" code if you will. The C++ runtime is basically intrinsic to the program itself, so "linking the runtime" is a bit illogical. Linking a library makes more sense, especially since the C++ libraries are independent objects which would otherwise need resolvement with the source program itself, and relocation.

So I wondered, besides the C++ library, what else, or how do you know what you are linking with exactly? For example, if I'm supposedly linking with the C++ library, I also need to link with the OS-specific library and API as well, or at least a wrapper of some sort that will deal directly with it.

So the linker will, in effect, link the main program file with the C++ library with the OS-API/library? That doesn't sound particularly right.

Basically, the linker will link multiple libraries together(statically, in this example, at compile/link-time)?

答:
What gets linked depends on what's in your program. Typically a program will be linked with the C runtime. If your C++ program uses STL, you may also get STL support, depending on which features you use.

You didn't say what platform you are using. Depending on the platform, you can use different tools to show what libraries your program is linked with. Program can also be linked statically or dynamically.


答:
Actually, source code and source code files have different meaning.

Source code is defined as,

the computer program code as the programmer originally writes it,
  using a particular programming language, generally written in a high
  level-language, such as BASIC, COBOL, or FORTRAN. A program in source
  code must be changed into object code before the computer can execute
  it.

Source code is a text material that can be read, printed, converted into executable using programming tool.

Source file on the other hand is just a piece of source code saved in computer system in a particular format.

Title: Source code vs source files?


答:
For any compiled language, the language specifies a run-time environment that you rely upon. For example in C and C++, you expect to be able to pass command-line arguments, that there will be standard output, standard error and standard input files. You expect execution to begin at main. The run-time library does all those things for you. It also does things that aren't obvious, such as setting up your program's memory structure or layout.

On each OS, it has to be tweeked a bit to provide that standard environment within the features / requirements of the particular operating system.

So, any time you are linking a program that will run under an OS, you'll have the run-time library linked. Separate to that you will have other libraries, such as the standard library for your language, which contains all those "normal" functions and classes you expect to see, plus any other libraries you need to use such database etc.

Title: What exactly is my program "linking" with overall?

Body:
I have heard that my C++ programs "need to link with the C++ library/runtime". However, the C++ runtime is just the compiler inserting stack operation code in to the image, or "boilerplate" code if you will. The C++ runtime is basically intrinsic to the program itself, so "linking the runtime" is a bit illogical. Linking a library makes more sense, especially since the C++ libraries are independent objects which would otherwise need resolvement with the source program itself, and relocation.

So I wondered, besides the C++ library, what else, or how do you know what you are linking with exactly? For example, if I'm supposedly linking with the C++ library, I also need to link with the OS-specific library and API as well, or at least a wrapper of some sort that will deal directly with it.

So the linker will, in effect, link the main program file with the C++ library with the OS-API/library? That doesn't sound particularly right.

Basically, the linker will link multiple libraries together(statically, in this example, at compile/link-time)?


问:
Why is a click event triggered only after mouse click and release?
Every click event on the web works on mouse click and release. Is there a way to do a action on a click event before mouse release??</p>

答: If you mouse-down on a button, move the mouse off the button surface and finally release the mouse, no mouse click event will be fired. This can save your day, if you have pressed the mouse on the delete-all-my-work-button inadvertently!</p>


问:
Text conversion - Javascript before saving to db, or php when retrieving?
Long story short, I have a social networking site I wrote a while back as a "proof of concept" to myself that I had the skills to do it.   I decided to revisit it, and "improve" a lot of the bad coding practices I had when I first wrote the thing (3 years ago).

My current situation

Users can create posts.  When posting, some bbcode-style tags are allowed, as well as lots of smileys and such.   Currently, I take the post, and store it in a mySQL database just the way it was written.   When retrieving the post, I use php & regex expressions to convert these tags and smileys in to the appropriate html.   For example, I might convert :) in to .

It works well... but then I got to thinking (probably a bad idea).

My proposed solution

I got to thinking that doing this conversion every single time the post is retrieved from the database is probably not optimal, as there is an amount of server side CPU usage to perform the all the regex substitutions.

The approach I think I would like to take is doing the conversion ahead of time, and storing the html version of the post in the database.  This way, when I retrieve it the next 100 times or more, I don't need to keep doing the conversion.   I plan on storing both the original text (to be used for editing the post) as well as the converted text (for displaying the post).

Other than taking up more space in the database (I'm now storing a raw text version as well as an HTML version, is there any downside to the approach I'm thinking of using?  Or does this sound like a reasonable optimization of the whole process?

Update

So...  after reading the comments from you guys, it sounds like there's probably not a lot of reason (okay, no reason) to try and do this client side rather than server side as I'm doing it now.   Why did I come up with such a crazy idea in the first place?

Well...  right now, I store bbcode-ish text in the database, and when creating the page, run a function replacing all that code with html.   What I want to do is show a preview box, similar to the StackExchange site, so that when the users are entering their posts, they can see what the formatted result would be.    I assume that I need to do this via Javascript, so I've basically duplicated the preg_replace I use in php with replace functions in Javascript, so I can show the preview as the user enters their text.

Soooo...   I'm now duplicating the text replacement code, once in php, once in js.   I figured maybe I should find a way to not have to write the code twice...  but after some thought, maybe it's a small trade off to handle it this way.

I just wanted to share what's rolling around in my head to put my on this path in the first place...

答:
So long as you're keeping the original for the case when something in the rendering of the bbcode changes down the road, and the extra space isn't an issue for you, there's nothing bad about that approach.  You're effectively implementing caching.  If you go this route, make sure you are using css rather than hard coded styles, this way you can adjust to the client accordingly without changing the pregenerated html.

Another option is to send the bbcode to the browser in its original form, and have client side javascript handle the text transformation.


问:
Real world usage of DelayQueue
What would be a real world usage of DelayQueue, what common problem it was designed to solve?</p>

答:
I recently used a delay queue for rate limiting.

For a limit of X events per second, place each event into a delay queue with a 1 second delay.

If there are X events on the delayQueue, take() from the queue (which blocks until at least 1 expires). That way you allow a short term burst, without exceeding any long-term limits.

Title: Real world usage of DelayQueue


问:
Writing a Compiler Compiler - Insight on Use and Features

This is part of a series of questions which focuses on the sister project to the Abstraction Project, which aims to abstract the concepts used in language design in the form of a framework.  The sister project is called OILexer, which aims to construct a parser from grammar files, without the use of code injection on matches.

Some other pages associated to these questions, related to structural typing, can be viewed here, and ease of use, found here.  The meta-topic associated to an inquiry about the framework and the proper place to post can be found here.

I'm getting to the point where I'm about to start extracting the parse tree out of a given grammar, followed by a Recursive Descent parser which uses DFA to discern forward paths (similar to ANTLR 4's LL(*)), so I figured I'd open it up to get insight.

In a parser compiler, what kinds of features are ideal?

So far here is a brief overview of what's implemented:

Templates

Look ahead prediction, knowing what's valid at a given point.

Rule 'Deliteralization' taking the literals within rules and resolving which token they're from.

Nondeterministic Automata

Deterministic Automata

Simple lexical state machine for token recognition

Token automation methods:

Scan - useful for comments: Comment := "/*" Scan("*/");

Subtract - Useful for Identifiers: Identifier := Subtract(IdentifierBody, Keywords);

Ensures the identifier doesn't accept keywords.

Encode - Encodes an automation as a series X count of base N transitions.

UnicodeEscape := "\\u" BaseEncode(IdentifierCharNoEscape, 16, 4);

Makes a unicode escape in hexadecimal, with hex 4-transitions.  The difference between this and: [0-9A-Fa-f]{4} is the resulted automation with Encode limits the allowed set of hexadecimal values to the scope of IdentifierCharNoEscape.  So if you give it \u005c, the encode version will not accept the value.  Things like this have a serious caveat: Use sparingly.  The resulted automation could be quite complex.

What isn't implemented is CST generation, I need to adjust the Deterministic automations to carry over the proper context to get this working.

For anyone interested, I've uploaded a pretty printed of the original form of the T*y♯ project.  Each file should link to every other file, I started to link in the individual rules to follow them, but it would've taken far too long (would've been simpler to automate!)

If more context is needed, please post accordingly.

Edit 5-14-2013:
I've written code to create GraphViz graphs for the state machines within a given language.  Here is a GraphViz digraph of the AssemblyPart.  The members linked in the language description should have a rulename.txt in their relative folder with the digraph for that rule.  Some of the language description has changed since I posted the example, this is due to simplifying things about the grammar.  Here's an interesting graphviz image.

答:
The grammar must not have restrictions like "don't have left recursive rules". It is ridiculous that tools widely used today have this and can only understand sucking LL grammars - almost 50 years after yacc did it right.

An example for right recursion (using yacc syntax):

```<code>list:
      elem                  { $$ = singleton($1); }
    | elem ',' list         { $$ = cons($1, $2);  }
    ;
</code>```

An example for left recursion (using yacc synatx):

```<code>funapp:
    term                    { $$ = $1; }
    | funapp term           { $$ = application($1, $2); }
    ;
</code>```

Now, this could maybe "refactored" to something else, but in both cases, the specific kind of recursion is just the "right" way to write this, as (in the example language) lists are right recursive while function application is left recursive.

One can expect from advanced tools that they support the natural way to write stuff down, instead of requiring one to "refactor" everything to be left/right recursive form the tool imposes onto one.

Body:
The grammar must not have restrictions like "don't have left recursive rules". It is ridiculous that tools widely used today have this and can only understand sucking LL grammars - almost 50 years after yacc did it right.

An example for right recursion (using yacc syntax):

list:
      elem                  { $$ = singleton($1); }
    | elem ',' list         { $$ = cons($1, $2);  }
    ;

An example for left recursion (using yacc synatx):

funapp:
    term                    { $$ = $1; }
    | funapp term           { $$ = application($1, $2); }
    ;

Now, this could maybe "refactored" to something else, but in both cases, the specific kind of recursion is just the "right" way to write this, as (in the example language) lists are right recursive while function application is left recursive.

One can expect from advanced tools that they support the natural way to write stuff down, instead of requiring one to "refactor" everything to be left/right recursive form the tool imposes onto one.


问:
Why not free memory as soon as its reference counter hits zero
A lot of languages like Java and C# have garbage collectors that free memory when that memory no longer has any reference. Yet they don't immediately free it after the reference counter hits zero but instead every once in a while they check on all the memory to see if that memory has any reference and delete it if it doesn't. What is the benefit of doing that way?

The downside to doing it that way is that you lose the destructor as you can't guarantee when it will be called.

I would imagine that it is done that way because of performance, but has there been any study that shows that a garbage collector that works like that has a better performance then std::shared_ptr found in C++?

答:
Because it would be too expensive to do it continuously.

"Mark and sweep" garbage collectors periodically sweep the memory space for objects that have been dereferenced.  Generational garbage collectors sweep those objects first that are most likely to have been disposed of recently (which turns out statistically to be the objects most recently created).  Objects that have been around for awhile get put into a second or third generation for sweeping later.

Garbage collection works very much like your trash bin: your trash man does not check your can every minute for trash, or even every day, although you might check the cans inside your house every day.  Checking every minute or every hour would be too inefficient, for both you and the trash man.


问:
How can I start testing in a testing anticulture?
I have a confession to make: Formalized automated testing was never a part of my programming background. I now work in a very large company with many developers (most of them web developers of one sort or another), and it's apparent that most of them don't test* either. (*I'm not going to keep saying formally; please infer it.)

If I wait to have the support of my organization to begin testing it will never happen. If I try to "change things from the inside" by pushing testing at management I will run out of steam before change happens. I need to start testing now.

But with TDD and its ilk I'm going to end up with lots of testing code right along with the production code. Our version control systems (all centralized) aren't organized for storing testing code. I'll have to find a place for all that on my workstation.

Is it possible to begin a personal practice of software testing in a culture that doesn't value or provide the tools for it? What techniques and tools do you use to enable you to test when the official tools and organization don't have a place for tests, frameworks and automations?

答: One idea is that you aim to write a test that proves that code that someone else has written is faulty. Should sell the concept.</p>


答:
Because in order to free memory as soon as the reference counter hits zero, you have to keep a reference counter. And that doesn't come for free. Typically, it limits your throughput.

There are generally two major strategies for implementing garbage collectors: tracing collectors and reference counting collectors. (There are others, but those are the ones in use by most mainstream automatic memory management systems.)

Typically, reference counting GCs tend to have worse throughput but better (and more predictable) latency than tracing collectors whereas tracing collectors have better throughput but higher and less predictable latency. Another big problem with (at least with simple implementations of) reference counting garbage collectors is that they can't garbage collect cycles. You typically need to run a tracing collector in conjunction with a reference counting collector anyway (that's what CPython does, for example).

Practically speaking, all modern industrial-strength high-performance automatic memory management systems (all of the collectors in Oracle JDK, Oracle JRockit and most other JVMs, Microsoft CLR, Mono, most ECMAScript implementations, all Ruby implementations, almost all Python implementations, all Smalltalk implementations, all Lisp implementations etc.) are tracing collectors, so there is a bit of a self-reinforcing feedback loop here: more money gets put into research on tracing GCs because they are popular, and they become more popular because they get better because of the money spent on their research … and so on.

Title: Why not free memory as soon as its reference counter hits zero

Body:
A lot of languages like Java and C# have garbage collectors that free memory when that memory no longer has any reference. Yet they don't immediately free it after the reference counter hits zero but instead every once in a while they check on all the memory to see if that memory has any reference and delete it if it doesn't. What is the benefit of doing that way?

The downside to doing it that way is that you lose the destructor as you can't guarantee when it will be called.

I would imagine that it is done that way because of performance, but has there been any study that shows that a garbage collector that works like that has a better performance then std::shared_ptr found in C++?


问:
Assert equality in mstest when types may differ
I've been working on some MSTest automated test infrastructure, that is testing a tool that merges data sets into SQL Server database tables. The basic structure of the test is to:

Define the incoming dataset using anonymous types

Apply the data using the reconcile tool

Read records from the output tables

Compare result rows to input data, column by column

Example input data:

```<code>public class InputData : List<dynamic> {} // Inspired by Massive etc

InputData input = new InputData()
{
    new { ExternalID = 1, PropertyName = "hello", Agent = "test" },
    new { ExternalID = (Int64)2, PropertyName = "fred", Agent = "test" } // Fixes the problem with a cast
};
</code>```

The issue I'm dealing with, is that the type inferred on my anonymous objects will be an Int32, but the corresponding column in my target table is a bigint, and hence the record will have an Int64 value. As a result, when I use Assert.AreEqual across each column, it fails on any int fields:

```<code>Assert.AreEqual failed. Expected:<1 (System.Int32)>. Actual:<1 (System.Int64)>
</code>```

You can see I have cast the int on my second anonymous object, this can be used to fix the issue. The primary aim of these tests is to make the sample data as slim and easy to read/write as possible, and I'd prefer to avoid the visual noise of all those casts.

I'm thinking about the best way to deal with the assertions. It seems like I should use dedicated assertions based on type. I guess the real question is, how aggressive should I be in converting between types automatically?

答:
Convert to strings is what I think. Strings are underestimated in test cases. Then you can write a method thats like

```<code>void AssertEqual(Object a, Object b)
{
  Assert.AreEqual(a.ToString(), b.ToString();
}
</code>```

and maybe add a parameter that is the fail message.

Body:
Convert to strings is what I think. Strings are underestimated in test cases. Then you can write a method thats like

void AssertEqual(Object a, Object b)
{
  Assert.AreEqual(a.ToString(), b.ToString();
}

and maybe add a parameter that is the fail message.


问:
Source code vs source files?
I'm in a situation with my company where this may be an important distinction.

Is there any distinction between "source code" and "source files" in a technical context?

Is there any distinction between "source code" and "source files" in a legal context?

Thanks.

Edit: I saw some close votes on this. I want to note that this is a possible issue between two companies - and where necessary, we'll definitely use legal counsel. I'm asking this because I'm attempting to be prepared if I'm asked for any technical definitions (as the developer role in this).

答: Simply speaking: yes. There are systems which don't even have files, but of course they have source code. Most Smalltalk systems, for example.

Title: Source code vs source files?


问:
Which useful alternative control structures do you know?
Similar question was closed on SO.

Sometimes when we're programming, we find that some particular control structure would be very useful to us, but is not directly available in our programming language.

What alternative control structures do you think are a useful way of organizing computation?

The goal here is to get new ways of thinking about structuring code, in order to improve chunking and reasoning.

You can create a wishful syntax/semantic not available now or cite a less known control structure on an existent programming language.

Answers should give ideas for a new programming language or enhancing an actual language.

Think of this as brainstorming, so post something you think is a crazy idea but it can be viable in some scenario.

It's about imperative programming.

答:
```<code>unless(condition) {
  // ...
}
</code>```

does the same thing as:

```<code>if(!condition) {
  // ...
}
</code>```

```<code>repeat {
  // ...
} until(condition)
</code>```

does the same thing as:

```<code>do {
  // ...
} while(!condition)
</code>```

Body:
unless(condition) {
  // ...
}

does the same thing as:

if(!condition) {
  // ...
}

repeat {
  // ...
} until(condition)

does the same thing as:

do {
  // ...
} while(!condition)


答:
On Unix and Linux, you can see which libraries are linked with the ldd command.  The output from an empty c++ program I made as a test was:

```<code>linux-gate.so.1 (0xb77ba000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb76ae000)
libm.so.6 => /usr/lib/libm.so.6 (0xb7668000)
libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0xb764c000)
libc.so.6 => /usr/lib/libc.so.6 (0xb749c000)
/lib/ld-linux.so.2 (0xb77bb000)
</code>```

linux-gate and ld-linux are treated specially by the linker.  The rest are all more or less regular libraries.  They are all open source, so you can see precisely what they do.  Search for "libstdc++ source" for example.

They basically contain implementations for anything that is too long to inline:  standard library containers, memory allocation, trigonometry, sockets, file handles, etc.  These implementations are highly specific to architecture and operating system.  They make calls into the kernel for the operating system they were compiled for.  I've had to implement several libc functions for a custom embedded operating system.

Body:
On Unix and Linux, you can see which libraries are linked with the ldd command.  The output from an empty c++ program I made as a test was:

linux-gate.so.1 (0xb77ba000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb76ae000)
libm.so.6 => /usr/lib/libm.so.6 (0xb7668000)
libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0xb764c000)
libc.so.6 => /usr/lib/libc.so.6 (0xb749c000)
/lib/ld-linux.so.2 (0xb77bb000)

linux-gate and ld-linux are treated specially by the linker.  The rest are all more or less regular libraries.  They are all open source, so you can see precisely what they do.  Search for "libstdc++ source" for example.

They basically contain implementations for anything that is too long to inline:  standard library containers, memory allocation, trigonometry, sockets, file handles, etc.  These implementations are highly specific to architecture and operating system.  They make calls into the kernel for the operating system they were compiled for.  I've had to implement several libc functions for a custom embedded operating system.


答:
I think you have totally misunderstood the concept of a runtime libray.
The runtime is an executable, it does lots of work allocating storage, opening sysout, syserr etc and setting up various traps and signals before your main is called.

Thereafter it performs all your basic IO via fopen(), fread(), etc. calls, handles any memory management via "malloc()" and much much more.

I would stress again that the runtime is an executable. Implementation varies depending on the hardware and OS involved but it is usually some sort of shared executable like a windows ".dll" which is loaded only once and shared by all the c++ programs in the system.


答:
The BCPL language had a valueof expression that could be used to turn a sequence of statements into a single expression:

```<code>foo(a, b, valueof {some series of statements; resultis v});
</code>```

Where some series of statements can be anything and the whole valueof evaluates to v.

This could be handy in Java for when you need to compute an argument for calling a this() or super() (which requires that nothing happen before it). Of course, you could just write a separate method, but that might be a pain if you need to pass in many local values for context.

If you are able to use final for variables that are needed, you can already do a valueof in Java using anonymous inner classes:

```<code>foo(a, b, new Object(){String valueof(){
    String v ...; some series of statements; return v;}}.valueof());
</code>```

Title: Which useful alternative control structures do you know?

Body:
Similar question was closed on SO.

Sometimes when we're programming, we find that some particular control structure would be very useful to us, but is not directly available in our programming language.

What alternative control structures do you think are a useful way of organizing computation?

The goal here is to get new ways of thinking about structuring code, in order to improve chunking and reasoning.

You can create a wishful syntax/semantic not available now or cite a less known control structure on an existent programming language.

Answers should give ideas for a new programming language or enhancing an actual language.

Think of this as brainstorming, so post something you think is a crazy idea but it can be viable in some scenario.

It's about imperative programming.

Body:
The BCPL language had a valueof expression that could be used to turn a sequence of statements into a single expression:

foo(a, b, valueof {some series of statements; resultis v});

Where some series of statements can be anything and the whole valueof evaluates to v.

This could be handy in Java for when you need to compute an argument for calling a this() or super() (which requires that nothing happen before it). Of course, you could just write a separate method, but that might be a pain if you need to pass in many local values for context.

If you are able to use final for variables that are needed, you can already do a valueof in Java using anonymous inner classes:

foo(a, b, new Object(){String valueof(){
    String v ...; some series of statements; return v;}}.valueof());


问:
MVC to create desktop and mobile webapps?
I'm planning the creation of a webapp with a dedicated mobile web interface and a dedicated desktop/tablet interface.

I am considering ASP.NET MVC, but it is clear to me that MVC is for separation of concerns as explained here, anyway in my case i'd like to minimize the code and to support elegantly phones and desktop (may be landscape tablet can be "desktop" too).

So is MVC a wise choice in this case or which is the 1st stop for this kind of xdevice web app?

答:
Yes MVC architecture is definitely a wise choice. AND you are considering ASP.net MVC for your solution. ASP.net MVC4 is a good option if you wish to develop one website and one mobile site for your business.

Suppose I want to develop a business solution where my devices varies as per business requirement from time to time. But the business logic behind would stay same for all devices. In that case I will go for ASP.net web API where it simply exposes API (methods to get and set data from your database) on web which any devices can consume. The data transfer between API and devices can use XML or JSON (which is configurable). Now, the view part can be written any language depending upon your devices.

Here you can have multiple views consuming the same web API on your server. This way you can save lot of code.


问:
is it really necessary for python to differentiate between tuples, lists, dicts, ordered dicts and sets?
i have been learning python over the past month or so. i like many of the things about the language, but i find the differentiation between tuples, lists, dicts, ordered dicts, and sets to be cumbersome. i know these each have their own performance benefits and tradeoffs, but it seems to me that it would be far simpler to combine them all into a single data structure - maybe a dict but which maintains the order originally specified - pretty much like json...

would this be a massive performance hit, or could the optimizer fully compensate to maintain equal performance?

i'm guessing the answer is that it could not be done more simply and efficiently any other way - otherwise the language would already have been written that way. this being the case, can anyone explain why not?

also, would there be any other downsides to replacing tuples, lists, dicts, ordered dicts and sets with a single json type data structure?

答:
There are several reasons why:

Some objects are more lightweight than others, as telastyn mentioned, performance would drop. A tuple, for example, functions much faster than a dict.

The objects behave differently, and this is deliberate. Lists are accessible through numbered indexing (basically they are in chronological order and you can get the nth element). They are also iterable. Sets, on the other hand, deliberately have no order, and the same object in the set may not be repeated twice, as in a set, any object is either in or out. Tuples are primarily for performance. Because they cannot be modified, they are "read only", they run much faster, so it is best to use them if you do not modify your group after creation. Dicts act a lot like lists, only you assign the key. This is integral to python, for example it is necessary in an object.dict. These behaviors are meant so that there is an easy way to get whatever type of group you may want, instead of having to attempt to get a single group type to behave how you want it to. This way, code is easier to read and write.

Python is object oriented (and managed), so it is very easy to make a new data structure. Because of this, it is not at all unlikely that a useful way to structure data will be included in python. It is much easier to add than a new type in C, for example.


问:
Starting point for building an iPhone app
I have one idea that I want to make an app for iPhone, I have recently bought a mac for the same purpose. I want to make small app and build on it in later versions. I work in in a small company and have 1 year of experience on working of iOS platform . I am a developer and don't have any design background so I want to know - should I take help from some designer? Or learn on my own and start coding for the app?

I would like to know before starting out, what things should I consider or give more importance to. In general how should I approach building the app, design first and code later or reverse way.

答:
Your question in rather opinion based - there are no strict guidelines weather you should start with design first or functionality of main features as separated components that could later be attached to your interface.

It is up to your judgement, skill and budget to consider learning UI design or hiring a professional designer.

I'd say - if you're interested in design, have designer skills or you're sure that you can achieve same quality as a pro in reasonable time - go for it!

About the part of what goes first - I'm not going to stress the way I prefer, it's all opinion based. But you've said you work in a company for a year now - you should know the workflow by now. Why not use same approach as the company uses - it is familiar to you so there's less chance of having mistakes you never heard about.

But let's say you're unhappy with the workflow you know by now, you want to know other ways or simply need unsure what effect your actions might have.

Let's look at a few ways an app can be created.

For the sake of an example let's say the app is a step counter with statistics. Abstract examples are harder to understand anyway.

1) Build a screen list. My favourite way. Easy to understand even for a non-developer. Make a sheet with all the screens and lines to show screen relations.

Then, when you're satisfied with workflow you can list all the features with better understanding how to implement them in the current system. It also helps to keep the code separated and clean in your head as every feature will know it's place regarding it's screen.

2) Code first. Not the official name of the approach btw :) A well working alternative - just write all the model (model as in MVC), so it's easy to know what you're working with. Then, make the controller, so you can change the state of the model. It's fun that only a true programmer will appreciate. Not much you can show to other team-members/client meanwhile, but you can see the output in the console and know it's working! Then attach the visuals, sound feedback that other parts of the View. It doesn't really matter how your View will be like - it is the engine that's important.

In both cases, if done correctly, changing a part of your app won't affect the other. Both apps can be written with any standard, guideline, framework. It's merely a way to organise it in a way more understandable to you.

There are unlimited ways to break up the app into smaller tasks to help you understand your ToDo list. I won't be able to cover them all here.

There is no rule, only guidelines, so when you're making an app, think what you want to see or do first. Have your own guideline for consistency, but try approaching every program based on what's the best solution rather sticking to only one way.


答:
[ copied from my own answer on stackoverflow ]

ignoring - To ignore exceptions occuring in a certain block of code.

```<code>try {
  foo()
} catch {
  case ex: SomeException => /* ignore */
  case ex: SomeOtherException => /* ignore */
}
</code>```

With an ignoring control construct, you could write it more concisely and more readably as:

```<code>ignoring(classOf[SomeException], classOf[SomeOtherException]) {
  foo()
}
</code>```

[ Scala provides this (and many other Exception handling control constructs) in its standard library, in util.control package. ]

Body:
[ copied from my own answer on stackoverflow ]

ignoring - To ignore exceptions occuring in a certain block of code.

try {
  foo()
} catch {
  case ex: SomeException => /* ignore */
  case ex: SomeOtherException => /* ignore */
}

With an ignoring control construct, you could write it more concisely and more readably as:

ignoring(classOf[SomeException], classOf[SomeOtherException]) {
  foo()
}

[ Scala provides this (and many other Exception handling control constructs) in its standard library, in util.control package. ]


答:
In case of the first small practice project, I would just start coding right away and try out the different things, that you can do with the iOS SDK. But since you already have one year of experience, you might as well skip that part.

Design or Code first?

Always design first and then start development.
You will likely not save any time on the design, with the code already written.

However you can save countless hours when starting with a clear vision of your design, before writing a single line of code.

Changing design is like fixing bugs: The earlier you do it, the more time you will save.

Idea before monetization

Sure, I can relate to the fact, that you will want to make some money from a project, that you put countless hours of work into.
However, to make a successful application put the user first.

Focus on what is original about your idea, not on what might make the most money.
Keep the revenue in mind, but don't make it your priority during early stages.

Clear strategy

Plan your strategy ahead. For example: If you are creating an app, that needs a backend, decide before how you are going to do it.

Are you going with a cloud service like Parse?

Are you coding it yourself? If so, are you using:
JSON or XML? Ruby on Rails, Java, php, Python or something else? REST? Lay out all of your Routes/URL Schemes before starting to work on your App.

The same thing goes for Frameworks.
The earlier you pick the right framework, the more time you are going to save. Nothing kills your productivity than fixing bugs at late stages and throwing away code, because you suddenly notice that there is a better way to do it.

And of course, even on small projects test-driven development and the use of source control are never a bad idea.

Title: Starting point for building an iPhone app

Body:
I have one idea that I want to make an app for iPhone, I have recently bought a mac for the same purpose. I want to make small app and build on it in later versions. I work in in a small company and have 1 year of experience on working of iOS platform . I am a developer and don't have any design background so I want to know - should I take help from some designer? Or learn on my own and start coding for the app?

I would like to know before starting out, what things should I consider or give more importance to. In general how should I approach building the app, design first and code later or reverse way.


问:
Are there metrics, like in other professions, that can be used to measure whether a programmer is considered experienced?
Driving instructors (at leas in Germany) often mention 100.000 km driven as a reference point where a driver is considered experienced.

Is there a similar number for programmers?

For example, how many lines of code does the average junior/senior developer have written when starting their job?

Also: after how many lines in a specific language does one usually become an expert of that language?

Of course, there are many other factors, that make up who is a good programmer and who is not, however I feel like the number of lines of code could be a pretty good indicator of hands on experience.

Update:

Originally, I asked for a number of lines of code.

Of course I am aware, that it makes a big difference, what quality of code was written, in what fields etc. I would not consider any person, that has driven over 100.000km, a good driver either.

And I am still convinced, that everybody needs a certain time of experience, to become a great programmer.
Though hours was not the measure I was looking for, the number of hours in the answer of suhit was essentially what I wanted.

A more clear version of my original question might be:
After how many lines of code has a dedicated programmer, who constantly challenges himself, likely acquired enough knowledge and skill to be considered experienced?

答:
Researchers tend to say that it takes ten years to develop a deep level of expertise. This equates to around 10,000 hours of learning the craft. How many lines of code can you type in an hour?

It is probably not so much the lines of code, but what those lines of code do. The idea is that each successive target should be a bit more complex and a bit of a stretch for your current skill set, not just writing the same style of code over and over.

Deliberative practice, where you set yourself increasing challenges, is the key.


问:
Are verb-like classes a code smell?
I do a lot of flat-file processing to extract data. The file "formats" are very unique and each file format requires a lot of format-specific code. Sometimes, the parsing code needs to maintain a lot of state while the file is being read. I've used something like this "pattern" at times:

```<code>parser = New FileTypeAParser(filename)
parser.ParseEnterFile
data = parser.ParsedData
</code>```

Or, consider a class that factors large numbers. For efficiency reason, upon being instantiated, the class would internally generate and cache list a primes. It would then be called many times with different numbers like this:

```<code>factors = factorizer.Factor(veryLargeNumber)
</code>```

Original Question

The adage is Class names should be nouns; method names should be verbs. Is it a code smell to name and use classes in the way shown in the examples? If so, how do I refactor the examples to deodorize them and remove the code smell?

Revised Question

Based on the comments, I now realize that I am using nouns. After putting more thought into it, I realized that my concern is that these classes very verb-like in substance and in name. Is this something to be concerned about?

答:
It's not "verb like", it's a state. If you have a process with sufficiently complex state, where else would you put it if not in a class.

What might be a code smell is a class with methods that have to be called in particular order. A single parse method that will return the parsed data, it is easier to use than leaving the data in the object to be picked up by separate call. Of course provided the whole operation can be done in a single step no matter how complex.

Alternatively you could have the data class with a parseFrom(File) method (which would internally create appropriate parser class (which would be internal or even inner).

Title: Are verb-like classes a code smell?


问:
What is the most elegant way to handle a loop between two systems integrated remotely by webhook events?
So I'm developing this small engine that does a remote integration between two systems in order to sync data, both systems have webhooks for create & update events, and both have APIs (one is REST one is XML), so it is an event-based integration rather than a typical batch one.

My problem is that if System A creates an entry and fires a webhook that the engine catches, if the engine doesn't find it, then it creates a comparable entry in System B which triggers a create webhook, which then the engine catches as a new request... and you see my problem.

Same scenario could happen for an update webhook (actually this one is more likely to happen).

I'm guessing I'm not the first person on the earth to encounter this problem, so I'm wondering what would be an elegant way of handling this given that I cannot modify the APIs, nor inject custom metadata in the messages that could help me catch the loop.

FYI, the integration is between two issue tracking systems.

答: Add a globally unique identifier (GUID) to every issue. Make sure both systems track these IDs. When a system receives a "New issue added" event it will first look up the GUID - if it exists in its own database then it can ignore the event.</p>


答: I think that, It's not the number of hours that the coder worked on but number of project he worked upon which consist of complex tasks and how he handled those different tasks. How he can break the complex task into small pieces and can build it up from scratch using reusable code. How much he understands programming concepts and best practices while coding. Best way to evaluate is how quickly you can solve a task or build a project. This link better explains about number of hours Can programmer experience be expressed in hours of coded like hours of flight for a pilot?</p>

Title: Are there metrics, like in other professions, that can be used to measure whether a programmer is considered experienced?

Body:
Driving instructors (at leas in Germany) often mention 100.000 km driven as a reference point where a driver is considered experienced.

Is there a similar number for programmers?

For example, how many lines of code does the average junior/senior developer have written when starting their job?

Also: after how many lines in a specific language does one usually become an expert of that language?

Of course, there are many other factors, that make up who is a good programmer and who is not, however I feel like the number of lines of code could be a pretty good indicator of hands on experience.

Update:

Originally, I asked for a number of lines of code.

Of course I am aware, that it makes a big difference, what quality of code was written, in what fields etc. I would not consider any person, that has driven over 100.000km, a good driver either.

And I am still convinced, that everybody needs a certain time of experience, to become a great programmer.
Though hours was not the measure I was looking for, the number of hours in the answer of suhit was essentially what I wanted.

A more clear version of my original question might be:
After how many lines of code has a dedicated programmer, who constantly challenges himself, likely acquired enough knowledge and skill to be considered experienced?


答:
Assuming the 10 years / 10,000 hours principle for gaining expertise,

According to The mythical man month, a professional developer writes 10 lines a day, no matter the language

According to OECD, people work 1765 hours per year

Assuming 8 working hours per working day,

This leads to 220 working days a year, and 22000 lines of code written in ten years.

(Don't take this too seriously)


问:
Why are
,  and  tags not used much when I see sites that are in HTML 5?
I've noticed that even when a websites front end is coded in HTML 5 as evidenced by the <!DOCTYPE html>, people rarely seem to use the new HTML 5
,  and  tags.

Is it because people don't understand that you're supposed to use reusable classes for styling things within a
 instead of the full path of tag selectors to the element?

答:
Some authors only switch to HTML5’s DOCTYPE without wanting to change anything else in the HTML (→ costs/effort).

Some authors don’t know/understand the new elements.

Some authors don’t care.

Some authors want to use some new features of HTML5, but are hesitant to use other features.

Some authors would use the new HTML5 elements, but not all sites need resp. could make use of them.

Some authors look for every possible way to save bytes (→ HTML5’s DOCTYPE is shorter).

Some authors would like to use the new elements, but their tools don’t allow them to.

Some authors are not aware of their HTML (→ CMS users).

Some authors have other reasons.


答:
As others in this thread have mentioned (less explicitly), there are many skills to being a developer:

refactoring: How can you shift around the logic in a program to condense and clarify the ideas?

mistakes: How many have you made? How have you learned to avoid them?

scope: What kinds of problems can you solve?  Have you spent most of your programming career solving problems in the same domain?  How would you function in a domain outside of that?

creating new ideas from little: How well can you code something from scratch or near-scratch?  Do you need code-generation tools to give you a template to modify?

contributing to large projects: How well can you navigate and contribute to larger projects in which there's no possible way you could be responsible for the whole app?

wtfs per time-unit: How many times does your code make you or someone say wtf per year?  (See-also: refactoring)

inspiration


问:
I've been on C# course and struggle to remember things?
I'm an apprentice and I've been on a couple of training courses in C#, I understood the concept of c# programming and covered inheritance etc, but when I've came to code for my coursework "I've got to make a shopping basket and save the contents into a .txt" I just seems to not know what to do, as if I've got no idea how to program. I've got a copy of the end product apart from it's altered so we can't copy it whole, so I've just been taking code and not really understanding everything that's doing on.
I just seem as if I don't want to program as if I'm in a different mind set, I just seem to go blank at the thought of creating a simple program from scratch and have no Idea where to start? Any one got any ideas for help ? :) thx</p>

答: Try to break your task into small pieces, just create a list of tasks you have to do and one by one go coding them and then integrate together. Start with a simple class with one task at the start, add methods and properties, refer OOP's concepts on how to use them and read about topics which you need to implement in project and try out some examples. Usually big task seems daunting but if you break into small things you will be able to do it quickly.  </p>


答:
Learning a language (eg, C#) and learning to program are two separate things.  Of course, it's easier to do the latter if you know the former :)

But, just knowing the ins and outs of a language isn't enough to be a programmer.  Programming is also about problem solving (and eventually code maintenance).

Like others have mentioned:  If the problem you're trying to solve seems difficult to crack, try breaking it down into logical sub-problems.  If that is still tricky don't worry.  This comes with time.  You could instead try solving smaller problems.

You only learn to be a programmer by programming.  It doesn't matter in which language.  Technically you don't even need a programming language!  You could write down a list of instructions in plain English and that would also be a program!

Title: I've been on C# course and struggle to remember things?

Body:
I'm an apprentice and I've been on a couple of training courses in C#, I understood the concept of c# programming and covered inheritance etc, but when I've came to code for my coursework "I've got to make a shopping basket and save the contents into a .txt" I just seems to not know what to do, as if I've got no idea how to program. I've got a copy of the end product apart from it's altered so we can't copy it whole, so I've just been taking code and not really understanding everything that's doing on.
I just seem as if I don't want to program as if I'm in a different mind set, I just seem to go blank at the thought of creating a simple program from scratch and have no Idea where to start? Any one got any ideas for help ? :) thx</p>


问:
Do I need to understand algorithms and data structures to be called a programmer?
It has been six years since I have been coding. Coding into all kinds of things like ActionScript, JavaScript, Java, PHP, Ajax, XML HTML, ASP, etc. I have used arrays, maps, linked lists, sets, etc and wherever I worked people like me. But whenever I am interviewed it is very likely that people ask me question on hashes, trees, stacks, and queues. Some questions are on juggling some sorting algorithms.  I don't know if I should really know them or should I stop calling myself a programmer. There is something in me which also tells me even if people who are asking all these questions select me, they will never be making me work of these things. Am I really required to know all this?</p>

答: Knowledge of algorithms allow you to confidently say how your choices Will scale!  I personally consider this to be necessary to be a senior programmer


答:
A reference in a 64-bit JVM typically use 4-bytes of memory (using compressed oops)  This means using a reference count will increase the size of memory per object, but also increase complexity of passing references around. Every time a thread anywhere has to obtain a reference to an object it need to increment and later decrement the counter, something a GC basis system doesn't need to to do.

BTW in C++ a shared pointer has two pointers (each 64-bit) one to the object and one to the reference counter. On many systems this reference counter uses 32-bytes as this is the minimum allocation cost.  In total shared pointers replace a 4-byte reference with a 16 bytes shared pointer and a 32 byte reference.  That doesn't sound very CPU cache friendly.

The problem with JVM GCs is the stop-the-world collections which are fine for throughput processing but a real pain for low latency systems.  One way around this is to use a concurrent collector, the best being Azul's Zing which is pause less (though not pauseless ;)


答:
Garbage collection based on reference counting is much slower than tracing garbage collectors (Boost shared_ptr vs other solutions, or you can find links to more scientific comparisons at the Boehm GC's website). In addition, reference counting alone is insatisfactory, because it cannot deal with reference cycles.

C++ programmers tend to think about memory as just a resource, since C++ manages memory and other resources the same way. Garbage collection is special approach that can only manage memory, which is in fact the most often used resource.

This often confuses C++ programmers - they tend to think of finalizers as a poor substitute for C++ destructors, which they are not. To release sparse resources (not memory) in a deterministic manner, use finally blocks.


问:
Design Application to "Actively" Invite Users (pretend they have privileges)
I am designing an application where users message one another privately, and may send messages to any Entity in the database (an Entity may not have a user account yet, it is a professional database). I am not sure how to best design the database and the API to allow messaging unregistered users. The application should remain secure, and data only accessed by those with correct permissions.

Messages sent to persons without user accounts serve as an invitation. The invited person should be able to view the message, act on it, and complete the user registration upon receiving an InviteMessage.

In simple terms, I have:

```<code>User
    misc user fields (email, pw, dateJoined)

Entity (large professional dataset):
   personalDetails...
   user->User (may be null)

UserMessage:
   sender->User
   recipient->User
   dateCreated
   messageContent, other fields.....

InviteMessage:
   sender->User
   recipient->Entity
   expiringUrl
   inviteeEmail
   inviteePhone
</code>```

I plan to alert the user when selecting a recipient that is not registered yet, and inform that he may send the message as an invitation by providing email, phone where we can send the invitation.

Invitations will have a unique, one-time-use URL, e.g. uuid.uuid4(). When accessed, the invitee will see the InviteMessage and details about completing his/her registration profile.

When registration is complete, InviteMessage details to a new instance of UserMessage (to not lose their data), and assign it to the newly created User.

The ability to interact with and invite persons who do not yet have accounts is a  key feature of the application, and it seems better to separate the invitation from the private, app messages (easier to keep functionality separate, better if data model changes).

Is this a reasonable, good design?

If not, what would you suggest?

Do you have any improvements?

Am I correct to choose to create a separate endpoint for creating invitations via the API?

答:
If a message can be sent to any Entity, it would make more sense to associate the message with the receiving Entity rather than with the user. If you do that, you don't need to distinguish between invitations and normal messages; instead, you can write the invitation-specific data in an own table:

```<code> User:
     misc user fields

 Entity:
     personalDetails
     user -> User (nullable)

 UserMessage:
     sender -> User
     recipient -> Entity
     dateCreated
     messageContent

 Invitation:
     content -> UserMessage
     expiringUrl
     inviteeEmail
     inviteePhone (aren't these two field part of Entity?)
</code>```

This increases maintainability: If you ever want to add an additional field to UserMessage you'd have to also change InviteMessage and the code copying an InviteMessage to a UserMessage with your approach.

Moreover, assume that an Entity has received multiple invitations. You'd want persist all of them when a new user account is created. This is also easier if you don't need to copy the message (just delete all Invitations of the Entity's messages).

Body:
If a message can be sent to any Entity, it would make more sense to associate the message with the receiving Entity rather than with the user. If you do that, you don't need to distinguish between invitations and normal messages; instead, you can write the invitation-specific data in an own table:

 User:
     misc user fields

 Entity:
     personalDetails
     user -> User (nullable)

 UserMessage:
     sender -> User
     recipient -> Entity
     dateCreated
     messageContent

 Invitation:
     content -> UserMessage
     expiringUrl
     inviteeEmail
     inviteePhone (aren't these two field part of Entity?)

This increases maintainability: If you ever want to add an additional field to UserMessage you'd have to also change InviteMessage and the code copying an InviteMessage to a UserMessage with your approach.

Moreover, assume that an Entity has received multiple invitations. You'd want persist all of them when a new user account is created. This is also easier if you don't need to copy the message (just delete all Invitations of the Entity's messages).


问:
Examples of Java APIs that demand an action sequence
As part of a research I'm working on, I'm looking for public APIs that only work correctly when you apply a certain sequence of actions on them.

For example, the java.nio.channels.SocketChannel class, from the Java standard library, only works correctly with sequences such as open() -> connect() -> read() -> read() -> close(). A more complete demonstration if how it may be used may be represented in the following graph:

Additional examples of Java standard library APIs that require certain sequences are java.io.PrintStream (very similar to the one above) and java.util.Iterator (which requires a next() call between every two remove() calls, thus enforcing a certain sequence).

So, does you favorite API for doing X also behave that way? I would very much like to know about additional APIs that require a certain method sequence for correct usage; especially classes that are not part of the Java standard library. The more complex the sequence(s) required, the better.

Some APIs require a sequence that spans across multiple classes, for example:

```<code>X x = new X();
x.setup();
Y y = x.createNewY();
Z z = new Z(y);
z.doSomething();
</code>```

These examples are also interesting, but I'm mostly looking for sequences that all appear in the same class.

EDIT added bounty for greater visibility. I'm sure many of you have encountered many APIs that will match this description - I would really appreciate some good examples.

答:
The academic paper "ESP: path-sensitive program verification in polynomial time" includes examples for opening and closing files, in addition to verifying calls to fprintf. And the concept works with general FSMs, and this may be closer to what you are looking for.

The bonus is that the ESP system verifies that you actually obey these rules. Also related to this line of research is BLAST.

If you want requirements that are more explicit in the programming language, look into Foster's Flow-Sensitive Type Qualifiers. Which can be useful, for example, to check that a "tainted" string has been cleansed before being used in a SQL query.

Depending on the nature of your project, you should look into the classic push before a peek or a pop on a stack. I'm not sure how well the above approaches could handle that case, because counting the number of calls made is important.