问:
How is a "Software Developer" different from a "Software Consultant"? What makes a consultant?
I have seen a lot of people claiming themselves to be a "software consultant". These consultants do what a normal software developer does, write code, estimate tasks, fix bugs and attend meetings etc. The only difference being the financials, consultants end up earning more. Then how is a software developer different from a "consultant"?

In addition to the main question, I would like to know how can a software developer become a consultant? Are there any specific guidelines for a consultant? Do they need to amass certifications and write up research papers? Please do not confuse the software consultant with a management consultant. Software consultants I have seen are not managers.

答:
It's too bad the question is framed as it is.  I think a better question might be "How is a 'software contractor' different than a 'software consultant'?"  It is these terms that really raise the question, at least here in the U.S.

The term 'software developer' can apply across any type of employment, developer being the type of role or resource one serves.  The contractor/consultant issue revolves around employment issues, and again, I am speaking in reference to how it works here in the U.S.  But to really answer this question definitively (and you will see, even that is difficult to do!), first we need to define some terms and explore some history.

A software developer, regardless of how they are employed, creates software, and probably does many other tasks related to the creation of software, usually with the exception of a management role, although even that is quite common on some projects, such as team leads.  Software project and program managers rarely get involved in the nuts-and-bolts activities of creating software (aside from team leads).   Again, these are roles.

As to employment and payment, there are several types (applicable to U.S.).  The most common type of employment is regular or 'direct,' where the worker is on the payroll of the company developing the software.  They fill out a W-4 with the employer each year and receive a W-2 from that employer at the end of the year for their taxes.

Outside of direct employment, there are contractors, and (depending on definition) consultants.  The term 'contractor' is a bit misleading, however.  Technically, a contractor is an entity or person who signs a contract with the client company, in this case the one developing the software.  But the reality is, nearly all contractors in the U.S. work through a contracting company (also refered to as 'body shops' and even less complimentary terms); they do not 'contract,' per se, directly with the client.  These so-called contractors actually fill out a W-4 with the contract company -- not the client -- each year and receive a W-2 from that contract company at the end of the year for their taxes.  They are taxed the exact same way as their directly-employed brethren and sisteren.  As far as the IRS is concerned all W-2 workers are direct employees.

The point here is that it is the 'contracting company' that actually signs a contract with the client company, not the so-called contractors (the 'contract employees').  The contract employees are actually employed by the contract company, and the contract company is the party to the contract with the client.  So the contract and direct employees working on a software project are essentially the same in terms of taxation, and usually work in adjacent cubicles with no particular special status, the only major difference being that contractors are limited to a certain time they can continue working on the project for that client.  This is because the contracting company they work for is not supposed to keep them there for longer than that time or our IRS may reclassify them as direct employees, and the parties (client and contracting firm) to the contract would become liable for the difference in taxes.

In my own experience, contractors are often extended by HR trickery, re-classifying a contract employee from, say, 'contractor' to 'temp' or the like.  Clients that wanted to keep me on have done that on occasion.  The client companies do have to be careful though; the IRS may audit them to determine the true relationship of those contractors.  If the IRS finds that the client has been treating them like direct employees, keeping them on site indefinitely for instance, the client becomes liable for any benefits those (now-regular) employees were not receiving as contract employees.  And the contracting company can be liable as well.  I do not know all of the ramifications, but it can become messy.

Oh, yeah. What is a 'consultant?'  That term is kind of 'squishy' -- there have been many wars fought over that sacred territory.   It used to be, maybe 40 years ago, that 'consultant' was more-or-less synonymous with 'independent contractor,' meaning a worker who directly contracted with a client.  That is, the worker signed a contract with the client (maybe the one developing software, as above).  That worker does NOT fill out a W-4 with the client and does not receive a W-2 from the client at the end of the year.  Instead, a direct contractor (what was often referred to as a 'consultant' back then) receives a 1099 from the client.  The direct contractor usually had their own corporation that paid its taxes at corporate rates and had to obey IRS business tax rules (and of course also enjoyed benefits of being a corporation!).

Along with this very different tax arrangement, the term 'consultant' had a certain aura about it.  Consultants were generally more experienced (at least 10 years working in the field) and usually had some area of expertise that might have been difficult to locate, making them very desirable to clients, and clients were willing to pay $500 or $1000 a day (a very generous amount then) for their expert services.  Consultants ran with an elite crowd of fairly-well connected people, and it was generally hard to break into those cliques.  Membership was necessary if one was to be a successful consultant.  There was an organization, recently defunct but being revived now, called ICCA which was sort of an old-boys club for computer consultants.  Anyone could join, and I did at one point; being accepted and getting work was a different story.

There was a niche industry also, especially in places like the financial district of NYC, that specialized in brokering contracts for these consultants.  But back then, in order to get work in software -- and especially the financial sector -- one had to be well connected (I know because I had tried back then).  Today, these brokers have been swallowed up or run out of business by the big placement companies.  Independent contracting has been nearly eviscerated (it does exist, but that sector is much smaller now, nearly non-existent) by a series of legislation that has slowly and certainly destroyed independent contracting like that.

Today, the term 'consultant' is rarely used in the software development employment realm.  At least, I have rarely heard it.  Sometimes a contract software developer is referred to as a consultant, but it is hardly any distinction other than, perhaps, some attempt to flatter or compliment some particular contractor for their expertise in a throw-back to that earlier tiem when the term meant something special.

I should state that there are still software project managers called "software management consultants," but almost all of them are also direct employees to some contractor company that performs the same purpose to these management contract employees as the companies that provide the W-4's to those software developer contract employees.  And, as you might imagine, sometimes they are the same contract firms.  Some clients want to deal with one source of workers for both developers and managers working on a project.

Genuine, independent software consultancy in the U.S. is mostly dead thanks to changes in federal legislation and the changing landscape of corporate America.  As companies (potential consulting clients) get larger, their HR departments become more brutally centralized, arrogantly efficient, and technologically black-boxed.  It is nearly impossible these days to contact a hiring manager to discuss an employment opportunity of any kind, direct or contract.  Part of this is corporate secrecy and employee protection, but a lot of this is the trend toward ensuring that as many workers as possible are direct employees, or at least working through a contracting company.

The alternative to this scenario, similar to that earlier time of 40 years ago or so, was quite different.  Back then, it was more difficult for employers to control the work of their contracted employees, especially the consultant type.  Control of workers has been increasingly becoming the main issue of employment in the U.S. to ensure increasing productivity which, in turn, is important for competition with nations like India and Vietnam, whose workers are even more accustomed to ever-increasing demands of productivity.

The key to understanding all of this is to understand that the independent contractor cannot be told exactly how or when to do their work.  They usually must provide their own tools.  They have to comply with about 20 of these types of constraints for the IRS to recognize them as legitimate independent contractors.  Otherwise, those legal issues I referred to above kick in, along with potential lawsuits between contract employees and their contract companies for back-benefits that would then be lawfully due to them.

Sorry for the long-winded explanation, but it really is this complex.  I am a software developer who has worked direct for companies and through contract companies.  I have many times considered going "indy" but that has become a very treacherous (and intimidating!) road to follow in recent decades.  And the corporations, plying and leveraging their influence in government, continue to tighten up this arrangement.  The American Software Consultant is dead; any remaining survivors are suffering their last breaths.


问:
In an event-driven environment, how should a "cancel" function abort all further events?
In my iOS app, things are mostly driven by events.

The user presses a button

The app listens for an external device to be connected to the iOS device

Once the device is detected (is connected), an asynchronous call is made to a web service (to check for user authenticity)

The web service returns the user's authenticity (such as a boolean)

Another asynchronous web service is called for a stage 2 authenticity

Result is returned

My question is: If I give the user a dialog box saying "Please wait, processing" and I give them a "Cancel" button, how should I (or how might I) abort everything that's happening?

One way to do this is to simply have a boolean called "userDidCancelEverything" and every event-driven method checks to see if this is true. This seems ugly though.

答: How you implement a cancel function will obviously depend on how you implement the events in your app. For example, when the user taps the button the resulting action might add a number of operations to a serial operation queue: the first operation would wait for the device to be connected, the next would call the authentication web service, and so on. If you do it that way, then your cancel button's action would call the operation queue's -cancelAllEvents method to empty the queue and then reset the state related to the operations to a known state. It'd be similar if you use some other scheme -- stop and remove any pending events and then set the app back to a known state.

ContentLicense: CC BY-SA 3.0


问:
Was classical BASIC ever used for commercial software development, and if so, how were limitations overcome?
Many of us, including me, started their programming life with programs written on home computers, something like

```<code>10 PRINT "ENTER RADIUS"
20 INPUT R
30 PRINT "CIRCUMFERENCE="; 2 * R * PI
40 PRINT "AGAIN?"
50 INPUT A$
60 IF A$="Y" THEN GOTO 10
70 END
</code>```

Of course, the line-number based BASIC was prone for creating spagetti code, also because most BASIC dialects missed structural statements like WHILE, doing everything but the FOR-loop with IF, GOTO and GOSUB. I'm talking about BASIC dialects before 1991, when QBASIC and Visual Basic appeared.

While BASIC dialects may have promoted bad style amongst aspiring programmers, were there larger commercial projects created in such a BASIC dialect? If so, how did they manage to live with and workaround the obvious shortcomings?

By "serious", I mean:

Not a game (I know some commercial games were written in BASIC, for example, Pimania)

Not freeware

Not trivial, that is, reasonably large (say: at least 1500 LOC)

Sold to several customers (not an in-house development)

"Mission critical" is a plus

答:
Any? Yes. Many? No. Educational software and record-keeping.

The BASIC era: ~1970-1990

Up until about 1990, limitations exceeded expectations and evolved with the industry needs. For the most part, needs of larger companies were analyzed by consultants and met with whatever language that fulfilled the need.

Rather like today, where companies have a more or less developed idea of what they need and have some sort of solution be built with VBA, and then learn enough to discover more competent client-server solutions, web apps, and optimized interfaces with data grooming.

In the 1970s, if a regular company could balance accounts or register production figures on the computer without the budget of a corporation, it would be a great step up from keeping books, and if you could get a diagram out, that was fantastic.

In the 1980s, if you could migrate some product drawings to the computer to make them editable, that would also be fantastic.

Both these could be done with an interpreter-based language. As computers could hold more data, complexity required compilers, because CPUs fell behind Moore's law in raw data shuffling performance from around 1977 to around 1987.

But up until the end of the 1980s when expectations demanded more, the languages established in the 1970s (complemented in rare cases by Assembler and/or custom hardware like FPU boards) did all the serious, commercial work in companies with few exceptions. Cobol and Fortran was the still the ticket on mainframes. Only corporations could afford such, and serious companies did what serious work they could with in-house BASIC programs, and for a while this was enough.

Standalone software packages for general use such as word processors or diagram plotters came along at around this time, when operating systems had matured on affordable computers as targets for compilers, and storage emerged that could hold "company size" documents and data.

Pascal was a major contender here. Previously, almost all such had been written in Assembler. Finally C came over from Unix and started being used on PCs.


问:
How much of original code is left in modern software products?
Many of you out there work for large companies that ship well-known software. I was wondering, how much of original code (basically, code that was "v1.0" release) is left in modern massive applications, such as, say, Firefox, Photoshop, Windows, Linux, etc? I'd really prefer first-hand experience and real-world war stories.

Thanks for satisfying my curiosity.

EDIT

Turns out there's a degree of misunderstanding. What I'm after is basically as follows: when you blame/annotate source code, are there any parts or even whole files untouched since the initial 1.0 release.

答:
"If they did their job exceedingly well from the start, a large part, otherwise a small part."

Strict languages display this trait. Very little has had to change in Nicklaus Wirth's languages, because they were planned with precision. (This has actually changed lately for Delphi, and will change more with the upcoming universal deploy version.)

There is also a flip-side to this, of course. Being deciding that the original code is good enough, such as in the case of Microsoft Windows, or lovely applications like ACDSee, text editors, or the well-known "spirit of Linux" command line applications.

Even though these applications may seem clunky to those who perhaps didn't love them in the first place, they display a well-planned trait as well as a well-defined featureset; even if they don't have bells and whistles, that may be preferred; they do what's on the tin, backward compatibility is great, and are likely to continue to function well in future.

Photoshop would have 90% the same code since 5.0, if you'd go by the featureset. ;P Does it? No. Why? Selling updates. You can't really do more with it today.

The featureset of a file manager, up to the point where it wants to do FTP, web, and cloud is largely the same for any platform for decennia. The only reason such an application still isn't at 1.0 is due to bad planning, whim, an urge to update - and atleast to a small extent the world changing around the application.

The answer is that some gems stay at 1.0 or 1.0.x because the developer has decided on the featureset, completed a bug-free program, and either does not profit from endlessly adding stuff and fixing the bugs in the added stuff, or has moved on to develop more gems.

All else is unlikely to stay anywhere near the code in 1.0. And why shouldn't you rewrite the application if you have a great idea? You should, it's fun to code! :) Except that's not what has taken place in many modern software products. Change for the sake of change (sales) and not motivated by featureset, and to a smaller extent updating to comply with changing platforms, is the order of the day.

And in this soup of interacting pieces of constantly updating software few codebases escape revisions. A few still keep to the dream of foundations and modularizing (and not releasing prematurely), but the vast majority are stuck in the release-fix-update cycle.


问:
Why different testing methods are so contradicting topic?
There are a lot of very smart and experienced people, who claim that if you don't write unit tests then your code will be buggy and God will kill all kittens. On other hand, another bunch of smart people will say that unittesting is counterproductive. So if you will write unittest then kittens will be damned too.

Also, I heard very good arguments on both sides for and against integration testings, for and against TDD.

Also, there are lot of popular open source projects. Some of them use some automated testings and some of them not.

So, why different testing methods are so contradicting topic?

Update 1

I wrote couple of examples of anti-unittesting sentiments in comments. However, just to be clear there are A LOT of very successful open source projects which doesn't have unittests. This implies that not everybody thinks that unittests are useful.

Update 2

As soon as we start discussing some particular piece of testing (as example mocking, which came up in the comments), we immediately try to distinguish between being a core value or a mean. However, testing by itself isn't a core value. It's just a way to decrease support cost, which in it's turn, just a way to increase profitability. So, as I see it - unittests are something like 4 connections aways from a profit.

Update 3

It's interesting that amount of people in "balanced" camp is quite small. Most of people have really strong opinion on this topic.

答:
I think the basic issue is that unit testing is an often-poorly-understood tradeoff.  I write a lot of unit tests, but not for everything.  There are many things I don't think should have unit tests.

The basic thing you have to understand is that unit tests are regression tests.  If a test fails, it does not mean there is a bug, and if a test passes it does not mean there isn't a bug.  If a test that was passing is now failing, it means, simply, that something changed.  It's an invitation to look and make sure that the change is correct and the test case was wrong, but it is an invitation only.  Additionally I have found that there are often many unit tests which get coded poorly and so they break in unexpected ways and one has to follow these back and find out why.  When the answer is, "We tested for the English-language OS-level message and we got a localized message from the OS in German" the correct response may, in fact be, to just get rid of that unit test since we can show it is not testing what it is supposed to test and there may not be an easy way to fix it.

In general, the more carefully spec'd out a portion of the code is, and the tighter the contract, the more important it is to unit test.  Such test failures will often show you contract violations rather than bugs.  Portions of the code which are not well spec'd out, subject to frequent change, and not part of a public API do not need as many (of in some cases any) unit tests.  Manual testing there is ideal because you get real user feedback and automated tests will give you many false positives and false negatives.

In LedgerSMB we aggressively test things like number formatting and parsing, heavily test (but not as heavily) our database routines to varying degrees depending on, of course, how well defined the desired behavior is and how complex the code is.  Something like a cash-basis income statement or a 1099 report gets a lot of testing.  Something like saving a customer record gets light testing.  The user interface layer gets light testing which amounts to "got an HTTP success and did not get an error page from the application" and test coverage there is unlikely to ever be complete.

But let me give the other side, namely LedgerSMB before the unit tests and after the fork.  We forked from a codebase (of what was then a successful open source project!) which had no unit tests, and where most of the code cannot be tested because it relies on sloppy scoping.  When we started adding unit tests the first ones we added were something simple:  rounding numbers (keep in mind this is an accounting and ERP application, where rounding numbers is important).  We got significant numbers of failures and we spent a fair bit of time correcting those failures.  That single experience taught me that not to trust code which has no unit tests at all.

Unit tests are an important tool but "you must write unit tests for everything" is counterproductive.  Similarly a lack of unit tests is an indication that there is a lack of, if you will, contract enforcement, and that behavior of some parts of the codebase might be very ill-defined.  In the end, the tradeoff of unit testing a given portion of the code needs to be better understood and articulated, and the tradeoff is really that of rigidity in contract.  There are many places where you want to test and many places where testing just gets in the way of making desired changes over development process.


问:
How to make my web app restful
I have a web application which I want to make RESTful.
Here is the structure of the app:

Top level has a bunch of search screens, they are basically tabs which search different parts of database with different parameters.

After the search is done we display search results in a new tab, inside this tab is a table with a list of results.

From the list of results we can drill down to individual details for each row (they also open in a new tab)

Inside the details there are further additional details (and some sub-searches relevant to the the item). These additional details are also open in a new tab.

So, now I want to make this app RESTful - the goal is for people to share their searches and screens easily, have simpler URLs, get rid of some information stored in session.

Is this feasible for the design we have to make it RESTful?

The main difficulty I see is that we have multiple tabs with
different searches and details, how do I reflect it in the URL?

Also, the search could be quite complex - users can enter 50
different filters and could enter multiple ids - up to a thousand at
the same time. What would be a preferred solution in this case?

If this is not quite works, then is there a way to have several tabs that correspond to different URLs in one URL?

答:
The first step in developing any REST service is identifying what kind of resources you are going to expose.

As far as I can tell, you have a few kinds of resource:

Tables of search results

Detailed views of records

Collections of mixed queries and detailed views (each user's set of "tabs")

Every kind of resource should have a URL. But what goes into your URL is not important, as long as it is unique to that resource.

Since its infeasible in your case to put all of the parameters which identify your resources into the URL, you are going to have to generate unique ids and store the parameters in a look-up table somewhere. Or you could mix both strategies:

```<code>http://myapplication/users/johnsmith/tabs
http://myapplication/query/AJEL32339?page=1
http://myapplication/details/9383721
</code>```

Once you have URLs for your resources, sharing results is easy - just provide a 'Share these results' button with the URL for those results. If somebody visits a results or details screen directly, offer to add it to their personal collection of tabs.

Title: How to make my web app restful

Body:
The first step in developing any REST service is identifying what kind of resources you are going to expose.

As far as I can tell, you have a few kinds of resource:

Tables of search results

Detailed views of records

Collections of mixed queries and detailed views (each user's set of "tabs")

Every kind of resource should have a URL. But what goes into your URL is not important, as long as it is unique to that resource.

Since its infeasible in your case to put all of the parameters which identify your resources into the URL, you are going to have to generate unique ids and store the parameters in a look-up table somewhere. Or you could mix both strategies:

http://myapplication/users/johnsmith/tabs
http://myapplication/query/AJEL32339?page=1
http://myapplication/details/9383721

Once you have URLs for your resources, sharing results is easy - just provide a 'Share these results' button with the URL for those results. If somebody visits a results or details screen directly, offer to add it to their personal collection of tabs.


问:
Can we make it easier to add data flows between distant parts of a large codebase?
When making changes to large systems, I often face the problem that some piece of functionality needs to get some data from another piece, but they're in different parts of a deep and branching call tree, possibly flowing through event listeners, deferred calls, etc. In this way a simple change can balloon quickly.

A related quote from Yossi Kreinin's blog post at http://www.yosefk.com/blog/i-want-a-struct-linker.html:

You have some kind of data structure that you pass around a lot. Soon, the most valuable thing about the structure isn't the data it keeps, but the fact that it's available all the way through some hairy flow of control.

Global variables are one classic way to let code "shout out" to distant code, but they're known to be problematic. Dynamically scoped variables are a more restricted way, but they're problematic as well.

Is there any programming language research aimed at solving this problem? Can we make it easier to add unanticipated flows of data to a large codebase, while still having static checking, easy unit testing and other goodies?

答:
The simplest way to do this over a large scale is in fact to use some sort of data encapsulation API.  This could be a NoSQL store or it could be an encapsulated RDBMS (or it could in fact be both in different times and places in the same application-- there isn't any reason why you can't have an RDBMS handling long-term storage and a NoSQL db handling short-term state control).  It could even be a series of singleton objects.

Your data structures can then be made available in some sort of neutral space, in a somewhat managed way.  This is the approach we take with LedgerSMB (but with a few semi-global variables for what are essentially stashed singletons, but again these are managed, we chose directly stashing the object because it made management of the variables a little easier but then there are all of 4 of them).

Of course any approach has tradeoffs and you cannot get around those tradeoffs.  The key is to look at what the tradeoffs are (management vs performance vs cleanliness of code vs potential coding pitfalls) and make a decision based on what is best for your application.


答:
Unit test is a good alternative

Perhaps unit testing is hard or costly, but it is a good practice that has been widely embraced by our profession for having many advantages.  Unit test:

Brings the discovery of defects to the developer sooner with less visibility of those defects to others within the organization, let alone customers.

Make developers more responsible for testing vs. a loosely defined developer test role.

Permits whitebox/glassbox testing in ways only developers can perform.

Broadens the base and diversity of people who contribute to the overall test automation used in the product.

Supports continuous integration (CI) by permitting newly introduced defects to be automatically detected at the earliest opportunity.

On this last point, I recently saw a case where a driver developer made a change that had positive impact on the driver, but components from other groups had widespread failures.  Without a pool of unit tests that ran automatically, the breakage would have been detected much later.

Software Development Thrives on Alternatives and Tools

Agile development is full of alternatives:

Iterative/incremental vs. waterfall or spiral software life cycle models.

Pair programming vs. inspections/code reviews.

Developer gathered stories vs. system engineer driven formal requirements.

More developers who unit test vs. more functional / regression testers.

As a developer embracing unit test you move against the tide of applying industrial revolution concepts like division of labor to software and instead embrace the change in which developers have a richer and more complete involvement with crafting their deliverable.  This is also true when a developer helps annotate user stories or acceptance criteria in collaboration with customers.

Evolution and Complementary Options

Often, questions on SE Programmers question the value of broadly accepted practices.  We are free to develop options by both evolving our tools and introducing new techniques.  Source control tools evolved significantly from SCCS to CVS to SVN to Git.  Software testing has as well, with test runners, assertion based testing often in conjunction with constant integration servers being one step along the way toward things that will be even more effective.

Other options that complement the benefits from unit test include:

Static checkers.

Code coverage tools.

Code inspections and reviews.

Title: Why different testing methods are so contradicting topic?

Body:
There are a lot of very smart and experienced people, who claim that if you don't write unit tests then your code will be buggy and God will kill all kittens. On other hand, another bunch of smart people will say that unittesting is counterproductive. So if you will write unittest then kittens will be damned too.

Also, I heard very good arguments on both sides for and against integration testings, for and against TDD.

Also, there are lot of popular open source projects. Some of them use some automated testings and some of them not.

So, why different testing methods are so contradicting topic?

Update 1

I wrote couple of examples of anti-unittesting sentiments in comments. However, just to be clear there are A LOT of very successful open source projects which doesn't have unittests. This implies that not everybody thinks that unittests are useful.

Update 2

As soon as we start discussing some particular piece of testing (as example mocking, which came up in the comments), we immediately try to distinguish between being a core value or a mean. However, testing by itself isn't a core value. It's just a way to decrease support cost, which in it's turn, just a way to increase profitability. So, as I see it - unittests are something like 4 connections aways from a profit.

Update 3

It's interesting that amount of people in "balanced" camp is quite small. Most of people have really strong opinion on this topic.


答:
As I have understood your question you have to make your application aware of a series of open tabs (0 or more) and of a series of search parameters.
Because a restful approach requires a finite amount of parameters and a url length not exceeding 2000 characters (see restful max url length) you have to somehow store your data in the database, assign an id and use this id in your restful application instead of the whole string length.

You therefore will first make each possible tab restful

```<code>http://myapplication/search/query=something
http://myapplication/parameters/bgcolor=fff
http://myapplication/credits/user=john.doe
</code>```

Then you create two tables in the database where you have a many to one relation with your parameters, where the one side represents your final URL and the many side represents the series of tabs.

For instance

```<code>CREATE TABLE RESTFUL_PAGE (INT id, VARCHAR page_name, PRIMARY KEY id);
CREATE TABLE RESTFUL_TABS (INT id, VARCHAR url, PRIMARY KEY id, FOREIGN KEY id REFERENCES RESTFUL_PAGE.id);
</code>```

Title: How to make my web app restful

Body:
I have a web application which I want to make RESTful.
Here is the structure of the app:

Top level has a bunch of search screens, they are basically tabs which search different parts of database with different parameters.

After the search is done we display search results in a new tab, inside this tab is a table with a list of results.

From the list of results we can drill down to individual details for each row (they also open in a new tab)

Inside the details there are further additional details (and some sub-searches relevant to the the item). These additional details are also open in a new tab.

So, now I want to make this app RESTful - the goal is for people to share their searches and screens easily, have simpler URLs, get rid of some information stored in session.

Is this feasible for the design we have to make it RESTful?

The main difficulty I see is that we have multiple tabs with
different searches and details, how do I reflect it in the URL?

Also, the search could be quite complex - users can enter 50
different filters and could enter multiple ids - up to a thousand at
the same time. What would be a preferred solution in this case?

If this is not quite works, then is there a way to have several tabs that correspond to different URLs in one URL?

Body:
As I have understood your question you have to make your application aware of a series of open tabs (0 or more) and of a series of search parameters.
Because a restful approach requires a finite amount of parameters and a url length not exceeding 2000 characters (see restful max url length) you have to somehow store your data in the database, assign an id and use this id in your restful application instead of the whole string length.

You therefore will first make each possible tab restful

http://myapplication/search/query=something
http://myapplication/parameters/bgcolor=fff
http://myapplication/credits/user=john.doe

Then you create two tables in the database where you have a many to one relation with your parameters, where the one side represents your final URL and the many side represents the series of tabs.

For instance

CREATE TABLE RESTFUL_PAGE (INT id, VARCHAR page_name, PRIMARY KEY id);
CREATE TABLE RESTFUL_TABS (INT id, VARCHAR url, PRIMARY KEY id, FOREIGN KEY id REFERENCES RESTFUL_PAGE.id);


问:
What is the better way to design flexible menus?
I would like to have a menu like this in surfdome. I don't mean the UI but the flexibility of this menu.

I will try to explain it.

I have some products. I want to match these products with some categories and have multiple type of menus based on these categories.

e.g. (in [] are the categories and in () are the products)

A menu like

```<code>[Men] -> [Shoes] -> [Running] -> (Product1)
[Men] -> [Accessories] -> [Running] -> (Product2)
[Women] -> [Shoes] -> [Running] -> (Product3)
[Women] -> [Accessories] -> [Running] -> (Product4)
</code>```

or

```<code>[Running] -> [Men] ->[Shoes] -> (Product1)
[Running] -> [Women] -> [Shoes] -> (Product3)
[Running] -> [Men] -> [Accessories] -> (Product2)
[Running] -> [Women] -> [Accessories] -> (Product4)
</code>```

or

```<code>[Shoes] -> [Men] ->[Running] -> (Product1)
[Shoes] -> [Women] -> [Running] -> (Product3)
[Accessories] -> [Men] -> [Running] -> (Product2)
[Accessories] -> [Women] -> [Running] -> (Product4)
</code>```

...

What i think it could be done with a tag system, but i would like to ask if anyone know a way to do it?

答:
yes, tagging and permuting the tags will do the the job.

you should ask yourself, if you need all the combinations, like for the single triplet Men-Shoes-Running:

```<code>[Men] -> [Shoes] -> [Running]
[Men] -> [Running] -> [Shoes]
[Shoes] -> [Men] -> [Running]
[Shoes] -> [Running] -> [Men]
[Running] -> [Men] -> [Shoes]
[Running] -> [Shoes] -> [Men]
</code>```

but beware that if you need 4 tags to describe a product, the number of combinations is probably already prohibitive for a useful user-interface (factorial 4!: 24 combinations for that product category).

to reduce this, you might define flags like top_level_category.

the other option is to use multiple trees, which will give you a more direct control but will be more difficult to maintain (especially if you have frequent changes in products and categories)

Body:
yes, tagging and permuting the tags will do the the job.

you should ask yourself, if you need all the combinations, like for the single triplet Men-Shoes-Running:

[Men] -> [Shoes] -> [Running]
[Men] -> [Running] -> [Shoes]
[Shoes] -> [Men] -> [Running]
[Shoes] -> [Running] -> [Men]
[Running] -> [Men] -> [Shoes]
[Running] -> [Shoes] -> [Men]

but beware that if you need 4 tags to describe a product, the number of combinations is probably already prohibitive for a useful user-interface (factorial 4!: 24 combinations for that product category).

to reduce this, you might define flags like top_level_category.

the other option is to use multiple trees, which will give you a more direct control but will be more difficult to maintain (especially if you have frequent changes in products and categories)


问:
Please help me understand the relationship between script file size and memory usage?
I am programming in PHP and I have an include file that I have to, well, include, as part of my script.  The include file is 400 MB, and it contains an array of objects which are nothing more than configuration settings for a larger project. Here is an example of the contents:

```<code>$obj = new obj();
    $obj->name = "myname";
    ....

$objs[$obj->name] = $obj->name;
{repeat}
....
return $objs;
</code>```

This process repeats itself 40,000 times and ultimately is 650,000 lines long (the file is generated dynamically of course.)

If I am simply trying to load a file that is 400MB, why then would memory usage increase to 6GB? Even if the file is loaded into memory, wouldn't only take up 400 MB of RAM?

答:
There's not just the file.  There's the parse tree that gets generated from parsing the file, the bytecode it gets compiled to, the memory taken up by the variables defined in it, etc.  6GB still sounds like a lot, but for a 650,000 line file it doesn't surprise me much.

At some point along the way, someone should probably have thought of using a database.  :)  Unless you're using every item in that file every time, loading half a million lines of stuff to pull out a few things is incredibly wasteful.


答:
File size is the size of the code that is executed.

Memory usage is the size of the contents of all the variables created by the execution of the code.

An algorithm computing pi may take less than 10 lines of code and need billions of bytes just to store the result.

Title: Please help me understand the relationship between script file size and memory usage?

Body:
I am programming in PHP and I have an include file that I have to, well, include, as part of my script.  The include file is 400 MB, and it contains an array of objects which are nothing more than configuration settings for a larger project. Here is an example of the contents:

```<code>$obj = new obj();
    $obj->name = "myname";
    ....

$objs[$obj->name] = $obj->name;
{repeat}
....
return $objs;
</code>```

This process repeats itself 40,000 times and ultimately is 650,000 lines long (the file is generated dynamically of course.)

If I am simply trying to load a file that is 400MB, why then would memory usage increase to 6GB? Even if the file is loaded into memory, wouldn't only take up 400 MB of RAM?


答:
I have done something similar with Apache Solr and it's facets (that's more or less like tags). It's incredibly fast for counting the number of products for any combination.

You start with assigning useful facets to your products. Those can basically come in three forms:

single value: can have only one entry for a product, like gender or age group (baby, kid, adult) or brand.

multi value: can have several entries for a product like technical descriptions. Normally those are less interesting for menues, but in this case it may be interesting to show a product in several assortments like 'men' and 'outdoor' or whatever.

hierarchical: a bit complicated first. We use them for things like car_brand -> car_model -> built_year structures.

You can the ask Solr to begin with something like: "the gender facet must be 'male'" and the retrieve counts for all other facets and show those with a count > 0 as next level options. To some extend you can do this in real time (and combine that with full text search). Though for some areas we cache those query results, since creating a very deep structure can still take some time. (Even if you need to store those counts it's still far better to get them through this query interface than to write code that does the same counts manually.)

Title: What is the better way to design flexible menus?

Body:
I would like to have a menu like this in surfdome. I don't mean the UI but the flexibility of this menu.

I will try to explain it.

I have some products. I want to match these products with some categories and have multiple type of menus based on these categories.

e.g. (in [] are the categories and in () are the products)

A menu like

```<code>[Men] -> [Shoes] -> [Running] -> (Product1)
[Men] -> [Accessories] -> [Running] -> (Product2)
[Women] -> [Shoes] -> [Running] -> (Product3)
[Women] -> [Accessories] -> [Running] -> (Product4)
</code>```

or

```<code>[Running] -> [Men] ->[Shoes] -> (Product1)
[Running] -> [Women] -> [Shoes] -> (Product3)
[Running] -> [Men] -> [Accessories] -> (Product2)
[Running] -> [Women] -> [Accessories] -> (Product4)
</code>```

or

```<code>[Shoes] -> [Men] ->[Running] -> (Product1)
[Shoes] -> [Women] -> [Running] -> (Product3)
[Accessories] -> [Men] -> [Running] -> (Product2)
[Accessories] -> [Women] -> [Running] -> (Product4)
</code>```

...

What i think it could be done with a tag system, but i would like to ask if anyone know a way to do it?


问:
Study a project to be able to maintain it in future
I've joined as a fresher (trainee) a software company developing for Windows Store. I don't know much about C#. My company has started Windows Store development recently. They didn't do .Net development before, that's why my company got an Senior .Net employee to complete the project.

Whenever he completes the project he will leave the company. I will have to maintain the project after him. So I need to study the project flow and analyze the project to be able to maintain errors in future.

Can you suggest how to start to analyze the project and what to pay attention on?

答:
Load it up in Visual Studio. Pick some small part of it, some form or page, and set breakpoints in the load events, and then step through, line by line, section by section until you begin to see a pattern emerge.

If you don't understand something, take a guess, look up syntax to see if you were right. Hovering your mouse over variable names will give you details of what's inside.

After several run-throughs, you may begin to see what the senior developer was trying to achieve, and why.

When your coffee-cup is empty, take a break. :)


答:
A script is typically a fixed size. It is read in and effectively executed line by line. This is your file size.

While the script is running, it can say to the computer "store this information which I have generated for me", and the computer dutifully gives it a bit of memory. This is your memory size.

Your script can ask repeatedly for more and more places to store the information it has generated, often storing the same or similar things in many different places. This can take up many megabytes, and even gigabytes. The amount of storage (in memory) is almost totally independent of script size, although the same script will normally use the same amount each time it is run.


问:
Implementing Glicko Rating in Python
Recently, I've been trying to implement some working version of the Glicko Rating System for fun.

However, I fail to understand how to programmatically isolate R in Step 2. As you can see R appears on both sides of the equation and for a variable number of instances. How would I programatically solve for R using python?

Thanks for any help :)

EDIT: Actually shouldn't the R in step 2 be R_0 on the right hand side of the equation? Is this a typo? Note in "The Glicko system" by Professor Mark E. Glickman, the equations are identical except for all Rs being on one side and R' being on the other.

答: Have a look at https://github.com/sublee/glicko it's a python implention of both the glicko and the glicko-2 rating system</p>

Title: Implementing Glicko Rating in Python


问:
Compiling multiple languages and Javascript
I have read numerous times that programming languages when making games or large software often use multiple languages / scripts together. I'm wondering how that works. How do they compile it? How does it work together?

Also, how does this work with web design also, i.e. How does one combine their HTML/CSS with their Javascript code and make it run?

I know these are really basic low level questions, but I cannot find information on this on google. I'm probably just not searching well enough.

答:
As for the web:
The browser is the magic that ties these things together.

It has instructions on how to turn html into pixels on the screen. It has instructions on how to read css and apply the rules in it to the html, and then update the pixels on the screen. It has instructions on how to read javascript files and do the things that it asks.

The browser is a big compiler for three different languages, as well as a program which can respond to your clicks and keypresses.

In more generic terms, and other environments: An interface is the key to allowing different languages to talk to each other.

A database is built and written using SQL. A program sits running the database, and users can ask the database questions through the interface. An interface is an agreed set of instructions that the program promises to try to respond to.

A Node.js program relies on the node executable running, and can talk through that to the file system, databases, and anything that someone has created a well defined interface to.

Even "compiled" executable programs still rely on an interface. They run on your operating system (Windows or Linux or Mac OS X, typically), and they have at least a "main" entry point that the operating system knows how to call to start your program. Operating systems are usually written in C or assembly language, because they need to be fast.

A compiler like gcc will take C source code and turn it into something that has a recognisable interface with your operating system, so that it can run on your computer.


问:
Haskell AND Lisp vs. Haskell OR Lisp
I currently code with C, C++, and Python. I'm wanting to pick up a functional programming language, and right now I'm leaning toward Haskell. I do NOT want to start a "Haskell vs Lisp" war here; what I want to know is this: if I learn Haskell primarily for exposure to functional programming, what benefits, if any, will I gain from later learning Lisp?

答:
I also come from a C/C++/Python background and have tried out FP a couple of times in the last few years.  Initially I looked at Haskell and couldn't make head or tail of it, then tried Ocaml but didn't get much further with that.  Finally I started hearing good things about Scala, tried it, and found it suited me very well (I had also done a bit of Java in the past), to the point that after a year of so of dabbling in Scala (and dispatching 161 Project Euler problems with it), Haskell seems to make much more sense.  In fact I just ordered a couple of books on Haskell and want to give it another go, although this is largely motivated by the existence of Scalaz.

So I found using a multi-paradigm language (ie Scala, but Lisp would probably fit the bill too) a good way into FP.  But if you're happy diving into Haskell (I wasn't), go for it.

Title: Haskell AND Lisp vs. Haskell OR Lisp

ContentLicense: CC BY-SA 2.5


答:
Where to begin depends on if you are familiar to the technology you're using. I don't think that you need to have a deep knowledge of the technologies, but having a firm understanding of how things work is necessary.

Start from the documentation. First read the requirements to have a clear picture of what the project should do. Than try to analyze the architecture to get an overview of the structure of the project.

When you're done, have a discussion of the architecture with the senior developer, try to understand why this or that decision was made.

And only after this dive into the codebase. Read, debug, execute, change/break the code to understand it. If anything isn't clear, don't spend to much time trying to figure out on your own. Ask questions. Take small tasks on the project and complete them.

You need to do as much as you can before the senior developer leaves. So pay special attention to the things that are most difficult to figure out on your own. Start from those things.

Title: Study a project to be able to maintain it in future

Body:
I've joined as a fresher (trainee) a software company developing for Windows Store. I don't know much about C#. My company has started Windows Store development recently. They didn't do .Net development before, that's why my company got an Senior .Net employee to complete the project.

Whenever he completes the project he will leave the company. I will have to maintain the project after him. So I need to study the project flow and analyze the project to be able to maintain errors in future.

Can you suggest how to start to analyze the project and what to pay attention on?


问:
Try to find a word in the dictionary that has most letters given
I recently came across an algorithm design problem that I'd like some help with:

Given some letters, for example a,e,o,g,z,k,l,j,w,n and a dictionary of words. Find a word in the dictionary that has most letters.

My first attempt:

Let us assume that the dictionary is in a tree. Start by finding the permutations of the given letters, here we could be using recursion, we can prune the recursion tree, by checking the letters in the dictionary. and we maintain a variable which holds the largest string formed till now.

How is this solution? Is there a better one?

答:
The best you can do is reduce the number of comparisons to the number of letters in the dictionary.

sought: a,e,o,g,z,k,l,j,w,n

make index of alphabet where sought keys have value 1, the rest: 0.

```<code>   index={a:1, b:0, c:0, d:0, e:1, f:0, g:1...}
</code>```

Iterate over each word of dictionary. Add value of the index to sum of that word. Remember word position and value if it's greater than best.

```<code>max=0;
max_index=0;

foreach(dictionary as position=>word)
{
    sum=0;
    foreach(word as letter)
    {
      sum += index[letter];
    }
    if(sum > max)
    {
        max = sum;
        max_index = position;
    }
}
</code>```

max_index points to the word with maximum of the letters.
Some optimizations may be skipping words shorter than the current max, or starting with dictionary sorted by word length and stopping once word length drops to max currently found.

This is assuming letters from the list are allowed to repeat any number of times. If they are not, make the index contain number of given type of letters, increment sum by 1 on each find of non-zero index value and decrement the index. (reset index on each line.)

In this time optimizations could be, on top of the previous ones: abort checking word if less than max-sum letters remain, abort operation if word with all letters is found.

Body:
The best you can do is reduce the number of comparisons to the number of letters in the dictionary.

sought: a,e,o,g,z,k,l,j,w,n

make index of alphabet where sought keys have value 1, the rest: 0.

   index={a:1, b:0, c:0, d:0, e:1, f:0, g:1...}

Iterate over each word of dictionary. Add value of the index to sum of that word. Remember word position and value if it's greater than best.

max=0;
max_index=0;

foreach(dictionary as position=>word)
{
    sum=0;
    foreach(word as letter)
    {
      sum += index[letter];
    }
    if(sum > max)
    {
        max = sum;
        max_index = position;
    }
}

max_index points to the word with maximum of the letters.
Some optimizations may be skipping words shorter than the current max, or starting with dictionary sorted by word length and stopping once word length drops to max currently found.

This is assuming letters from the list are allowed to repeat any number of times. If they are not, make the index contain number of given type of letters, increment sum by 1 on each find of non-zero index value and decrement the index. (reset index on each line.)

In this time optimizations could be, on top of the previous ones: abort checking word if less than max-sum letters remain, abort operation if word with all letters is found.


问:
Best practices when forking code base
I have a question as to the proper best practices revolving forking code.

I've taken code base licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 and brought significant changes to it to suit my needs. I feel as though my version could benefit others and wish to redistribute it.

I'm unsure what liberties I have for redistribution or what acceptable. Can I rename the projects? Should I start a new v.1 or continue from the original version number? What is considered giving proper attribution to the original author? Should I consult the author and ask permission before releasing (although he is already aware)?

答:
There are two paths you can take

You provide your modifications for inclusion in the original project.

You distribute your version as an alternative project.

The first option has the advantage that you won't be competing with each other and that you can share the maintenance effort. On the other hand, if the copyright of the original is held by one person/entity, they might ask you to sign over your copyright if they want to retain the ability to change the licence.

With the second option, it is advisable to release your modified version under a different name, unless the original has been abandoned and is effectively unmaintained.

If you release under a new name, you can use whatever version numbering you like. If it is a continuation of the previous project, you should continue from the version number of the original.

With the use of his licence, the original author has already given you permission to release (under certain conditions). Proper attribution would be

first and foremost, retaining the copyright statements.

stating, in the documentation (such as a README file), which project you forked from. To be sure there is no mistake, I would also include a link to the project's homepage, but I don't think that is an obligation.

Title: Best practices when forking code base


问:
How can I deal with a team member who dislikes making comments in code?
One of my team members consistently avoids making comments in his code.

His code is not self-documenting, and other programmers have a difficult time understanding his code.

I have asked him several times to comment his code, however he just gives excuses or claims that he will do it later. His concern is that adding comments will take too much time and delay the projects.

What argument can I present to him to convince him to properly document his code?

On that note, am I wrong to focus on the code comments or is this indicative of a larger problem which should be addressed?

答:
Comments have one purpose, and one purpose only:

Why does this code do this thing?

If a comment does not explain why something is the way it is, then it should be removed. Useless comments which clutter up the code are less than useless, they are actively harmful.

I have a habit of making my comments the most obvious thing in my IDE. They are highlighted with white text on a green background. The really draw your attention.

This is because the code explains what something is doing, and the comments are for why it is doing it. I can't emphasise this enough.

A good example of a comment:

```<code>/* Must instantiate clsUser before trying to encrypt a password because the code to
   encrypt passwords only uses strong encryption if that module is loaded. */
</code>```

A bad example:

```<code>/* instantiate clsUser */
</code>```

If you are using comments as "sections" of code: Chop your mammoth method up into smaller, useful named functions, and remove the comments.

If you are saying what you are doing on the next line: Make the code self-explanitory and remove the comment.

If you are using comments as warning messages: Make sure you say why.

Body:
Comments have one purpose, and one purpose only:

Why does this code do this thing?

If a comment does not explain why something is the way it is, then it should be removed. Useless comments which clutter up the code are less than useless, they are actively harmful.

I have a habit of making my comments the most obvious thing in my IDE. They are highlighted with white text on a green background. The really draw your attention.

This is because the code explains what something is doing, and the comments are for why it is doing it. I can't emphasise this enough.

A good example of a comment:

/* Must instantiate clsUser before trying to encrypt a password because the code to
   encrypt passwords only uses strong encryption if that module is loaded. */

A bad example:

/* instantiate clsUser */

If you are using comments as "sections" of code: Chop your mammoth method up into smaller, useful named functions, and remove the comments.

If you are saying what you are doing on the next line: Make the code self-explanitory and remove the comment.

If you are using comments as warning messages: Make sure you say why.


答:
The underlying data, be it for game world or the webpage (HTML) contains objects/elements - characters, items, structures - or in case of webpage, elements - DIVs (boxes) and SPANs (marked spans of text like this).

All these have various properties attached to them - looks, textures, locations, shapes, behaviors, content data, audio data, whatever makes them unique. Amongst these properties they have triggers (a.k.a. events - when something happens to the object, e.g. user hovers the cursor over it, or click it, or a clock countdown reaches zero...) and the triggers have scripts attached to them.

Now the engine - be that the web browser or a game program takes that data and renders it. Whether it's deciding a piece of text found between marks ... should be rendered like this or whether following the definition of texture and vector model a tree should be set in game environment, this is something the user will see.

Now, if the user performs an action - say, click the tree while the character is holding an axe, or click a box on the page, if there's an event defined for that action, the browser will pass the script attached to the event to its internal scripting engine and execute it as a program. Then the script may affect other objects, like add an object "piece of wood" to the player's character inventory, or open a help box in the page.

There's of course one special object - the world, or in case of webpages the document, and it can have events attached too - especially "finished loading" event, to which a whole bunch of scripts is being attached and they start just then. (there's some more caveats with that but let's keep this simple now). This, in case of WWW often performs the job of getting all other kinds of events attached to the rest of the webpage, and all different kinds of tasks.

Summing up: you have data (game data or webpage) and renderer (browser or game engine). It displays the data and performs generic actions with it, also observing events. All objects in the data can have events attached to them, and scripts attached to the events. When event occurs, engine loads up and executes the script.

And as for interface, the webpage or the game world is the environment and the language has features to interface with that environment, e.g. modify properties of other objects, create their instances or delete them. document.getElementById("title").style.border="solid red 3px" in javascript will find the title and surround it with a red frame.

Title: Compiling multiple languages and Javascript

Body:
I have read numerous times that programming languages when making games or large software often use multiple languages / scripts together. I'm wondering how that works. How do they compile it? How does it work together?

Also, how does this work with web design also, i.e. How does one combine their HTML/CSS with their Javascript code and make it run?

I know these are really basic low level questions, but I cannot find information on this on google. I'm probably just not searching well enough.

Body:
The underlying data, be it for game world or the webpage (HTML) contains objects/elements - characters, items, structures - or in case of webpage, elements - DIVs (boxes) and SPANs (marked spans of text like this).

All these have various properties attached to them - looks, textures, locations, shapes, behaviors, content data, audio data, whatever makes them unique. Amongst these properties they have triggers (a.k.a. events - when something happens to the object, e.g. user hovers the cursor over it, or click it, or a clock countdown reaches zero...) and the triggers have scripts attached to them.

Now the engine - be that the web browser or a game program takes that data and renders it. Whether it's deciding a piece of text found between marks <strike>...</strike> should be rendered like this or whether following the definition of texture and vector model a tree should be set in game environment, this is something the user will see.

Now, if the user performs an action - say, click the tree while the character is holding an axe, or click a box on the page, if there's an event defined for that action, the browser will pass the script attached to the event to its internal scripting engine and execute it as a program. Then the script may affect other objects, like add an object "piece of wood" to the player's character inventory, or open a help box in the page.

There's of course one special object - the world, or in case of webpages the document, and it can have events attached too - especially "finished loading" event, to which a whole bunch of scripts is being attached and they start just then. (there's some more caveats with that but let's keep this simple now). This, in case of WWW often performs the job of getting all other kinds of events attached to the rest of the webpage, and all different kinds of tasks.

Summing up: you have data (game data or webpage) and renderer (browser or game engine). It displays the data and performs generic actions with it, also observing events. All objects in the data can have events attached to them, and scripts attached to the events. When event occurs, engine loads up and executes the script.

And as for interface, the webpage or the game world is the environment and the language has features to interface with that environment, e.g. modify properties of other objects, create their instances or delete them. document.getElementById("title").style.border="solid red 3px" in javascript will find the title and surround it with a red frame.


问:
How do I document a communication protocol on top of message queues and channels?
I'm working on a large project at the moment and I'm trying to document the communication protocol that sits on top of a message queue middleware.

The documentation is intended for another organisation that is going to be implementing a new back end to the client.

The messages format uses protocol buffers, so I'm less interested in describing the wire format.

I'm interested in documenting the interactions between the service and client. A typical interaction might be something like:

Client subscribes to Channel1

Client pushes RequestForStream to Queue1

Service reads from Queue1 publishes StreamResponse (containing endpoint to subscribe to, Channel2) to Channel1 and if successful starts publishing notifications to Channel2

Client receives from Channel1 and subscribes to Channel2

More stuff...

How can I best document scenarios like this? Does anyone know of any examples of documented interactions with Queues and channels?

Edit: I am not writing a Message Queue. I am using a JMS-like middleware named Nirvana. I want to document the application built on top of the Message Queue system.

Edit 2: In UML how would I model a Queue or Channel? Would I show them on a sequence diagram?

答:
I am the author of pg_message_queue which is a very light-weight channel/queue system in PostgreSQL designed to facilitate database-level integration.  Messages can then be forwarded to a heavier message queue, or the like, or they can just be processed.  The use case is for things like "I want to send an email from the database" and helps solve the problem for PostgreSQL without really awkward transactional processing problems that could result.

Our documentation is at http://pgxn.org/dist/pg_message_queue/

I won't say it is the best documentation out there but it is sufficient for our use case.  Compare to http://www.rabbitmq.com/documentation.html which is the rabbitmq documentation and you will see how different the requirements of the documentation in fact are.

But like all docs, keep your audience and use case in mind, and go through it conceptually and programmatically.

Edit  Ok I see what I misunderstood.  I would suggest starting at least with an outline of technical documentation.  If you have it from someone else, great.  If not, at least come up with an outline of what a technical programmer's manual should cover.

It sounds to me like you are looking at documenting a network protocol rather than an API.  Sorry, I did read it and I missed that part.  It's still not clear to me if this is direct over TCP, or over HTTP, or something else.  To the extent you are reusing other protocols, the work is easier.

Either way, I would divide up the documentation into three sections.  The first would cover message structure generally.   This would include headers, message body specifications, etc. but would be at a general enough level to provide a reference for section 2.

Section 2 would cover the specifics for each message type.  Again it depends on what exactly you are re-using how much depth you need to go into.

Section 3 would provide examples for how the communication would work using sets of mocked up messages.


问:
When do you use float and when do you use double
Frequently, in my programming experience, I need to make a decision whether I should use float or double for my real numbers. Sometimes I go for float, sometimes I go for double, but really this feels more subjective. If I would be confronted to defend my decision, I would probably not give sound reasons.

When do you use float and when do you use double? Do you always use double, only when memory constraints are present you go for float? Or you always use float unless the precision requirement requires you to use double? Are there some substantial differences regarding the computational complexity of basic arithmetics between float and double? What are the pros and cons of using float or double? And have you even used long double?

答:
Usually, I use the float type when I don't need much precision — for example, for money — which is wrong, but is what I'm used to wrongly do.

On the other hand, I use double when I need more precision, for example for complex mathematical algorithms.

The C99 standard says this:

There are three floating point types: float, double, and long double.
  The type double provides at least as much precision as float, and the
  type long double provides at least as much precision as double. The
  set of values of the type float is a subset of the set of values of
  the type double; the set of values of the type double is a subset of
  the set of values of the type long double.

I never really used long double, but I don't use C/C++ so much. Usually I use dynamically typed languages like Python, where you don't have to care about the types.

For further information about Double vs Float, see this question at SO.

ContentLicense: CC BY-SA 4.0


答:
The default choice for a floating-point type should be double. This is also the type that you get with floating-point literals without a suffix or (in C) standard functions that operate on floating point numbers (e.g. exp, sin, etc.).

float should only be used if you need to operate on a lot of floating-point numbers (think in the order of thousands or more) and analysis of the algorithm has shown that the reduced range and accuracy don't pose a problem.

long double can be used if you need more range or accuracy than double, and if it provides this on your target platform.

In summary, float and long double should be reserved for use by the specialists, with double for "every-day" use.

Body:
Frequently, in my programming experience, I need to make a decision whether I should use float or double for my real numbers. Sometimes I go for float, sometimes I go for double, but really this feels more subjective. If I would be confronted to defend my decision, I would probably not give sound reasons.

When do you use float and when do you use double? Do you always use double, only when memory constraints are present you go for float? Or you always use float unless the precision requirement requires you to use double? Are there some substantial differences regarding the computational complexity of basic arithmetics between float and double? What are the pros and cons of using float or double? And have you even used long double?


问:
Use of `is` and `as` in multiple conditions
Quite recently, I thought about the use of as, is and direct cast in C#.

Logically, is it a better idea to use :

```<code> var castedValue = value as type;
 if (null != castedValue)
 {
     // Use castedValue.
 }
</code>```

than :

```<code>if (value is type)
{
    var castedValue = (type)value;
    // Use castedValue.
}
</code>```

But I still have issues when dealing with this kind of pattern:

```<code>if (value is Implementation1)
{
    var castedValue = (Implementation1)value;
    // Use castedValue in a first way.
}
else if (value is Implementation2)
{
    var castedValue = (Implementation2)value;
    // Use castedValue in a second way.
}
else if (value is Implementation3)
{
    var castedValue = (Implementation3)value;
    // Use castedValue in a thrid way.
}
// And so on...
</code>```

How can I improve this code to prevent casting two times when OK, and is it really necessary to cast twice?

I don't want to make the code unreadable, but the idea is not to test a cast if a previous one succeeded.

I had several ideas to fix this, but none of them seems to really satisfy the conditions...

Edit:

Here is a case I've got... There is this object that is created by a lower part of teh code I do not have control on. This object can be of several inherited types. In my layer, I do want to create a specific object depending on this type. I do have this constructor class:

```<code>public static IHighLevelObject MakeHighLevelObject(LowLevelObject lowLevelObject)
{
    IHighLevelObject highLevelObject;

    if (lowLevelObject is LowLevelObject1)
    {
        highLevelObject = new HighLevelObject1((LowLevelObject1)lowLevelObject);
    }
    else if (lowLevelObject is LowLevelObject2)
    {
        highLevelObject = new HighLevelObject2((LowLevelObject2)lowLevelObject);
    }
    else if (lowLevelObject is LowLevelObject3)
    {
        highLevelObject = new HighLevelObject3((LowLevelObject3)lowLevelObject);
    }
    // And so on...

    return highLevelObject;
}
</code>```

How do I solve this case ?

答:
This kind of code suggests design issues that you need to tackle first.

The code breaks Open-Closed Principle and Liskov substitution principle: whenever you need to add a new implementation type to extend the functionality you'll have to edit this class. You should design your solution so that logic branching is done via generalized approach, e.g. using polymorphism. Since you have provided a very general description it is hard to suggest appropriate solution for your problem.

OwnerDisplayName: clemchen

OwnerDisplayName: almaz


问:
How do I learn linking compiling, makefile quickly? Any book recommendations?
I'm very good at programming in C++ but when it gets to linking and the other important stuffs I feel very ignorant. I want to learn allegro without wasting time. So please suggest a book or a resource to learn the concepts mentioned above. Thanks a lot in advance.</p>

答:
You don't have to learn autoconf and make files and all that stuff in order to get started under Linux. You can still use an IDE such as Eclipse, which will generate all the autoconf stuff for you automatically.

Eventually, you probably will want to learn it, but you don't have to if you're just starting out. Eclipse will be able to 90% of the stuff you need via it's GUI and wizards, etc.

For example, this page explains how to get started with Allegro under Eclipse. That page does appear to make some assumptions about your knowledge of Linux, but I'm sure with a bit of googling you should be able to find some more thorough references (that was just the first page I found).


问:
Is it a good practice to have a remote branch for each developer?
Is it considered a good practice to have a remote branch for each individual developer in the project?

We're using Git with the following branches:

master

release

develop

If each developer had their own branch, they could push code into their branches and others could merge these changes into their own branches.

答:
It depends on how your development team and tasks are organized.  In my opinion, the model you specified would work best if:

Each developer works on independent tasks by themselves.

All developers are contributing to the same task.

Where this might not work well is if you have concurrent feature projects in development and they each have multiple developers working on them.

OwnerDisplayName: balanv


答:
Giving each developer their own branch can be helpful if they are all working on different things that may touch the same files. It can help prevent stepping on each others toes, but it will require every one to merge often and be responsible when managing conflicts. This is what is done in my office and it works pretty well apart from the rare day you have to manually merge half the files you edited.

If you have multiple developers working on the same feature its probably better to create branches based on the feature in development rather than the developer.

Title: Is it a good practice to have a remote branch for each developer?

Body:
Is it considered a good practice to have a remote branch for each individual developer in the project?

We're using Git with the following branches:

master

release

develop

If each developer had their own branch, they could push code into their branches and others could merge these changes into their own branches.


答:
I probably wouldn't give each developer a branch on the central server unless you have some sort of github-style infrastructure that allows them to create and destroy the branches themselves and clearly document what they are for.  Some developers will need more than one branch and some won't need any at all, but you're creating clutter for everyone to sort through and administrative overhead for yourself.

I would encourage instead the kind of organic sharing git excels at.  It's very easy to make a bare clone on your own machine, and make that folder a read-only SMB share for others to pull from.  In fact, it would surprise me very much if several of your developers are not already doing this.


答:
I have used pi-calculus to document and analysis high level processes. There isn't a standard language for pi-calculus, but for a tool I wrote I used a simple one-line per atomic step language, which would look something like:

```<code>process Client
    # initialise client process with the channel to subscribe to
    recv self Init ( channel1 : channel, queue1 : channel )
    # send request to server
    send queue1 RequestForStream ( channel1 )
    # bind channel in response to channel2
    recv channel1 StreamResponse ( channel2 : channel )

    loop:
    choice
        # either receive a notification or stop
        recv channel2 Notification ()
            goto loop
        recv channel2 Stop()
            stop

process Server
    new channel2
    # wait for request
    recv self RequestForStream ( client : channel )
    # send response to client with channel2 to send
    send client StreamResponse ( channel2 )
    # send notifications on channel2
    send channel2 Notification ()
    send channel2 Notification ()
    send channel2 Stop ()
    stop

# test
process Test
    c := start Client
    s := start Server

    send c Init ( c, s )
    stop

start Test
</code>```

the extra stop parts are there as the tool is to detect deadlocks livelocks and races.

Title: How do I document a communication protocol on top of message queues and channels?

Body:
I'm working on a large project at the moment and I'm trying to document the communication protocol that sits on top of a message queue middleware.

The documentation is intended for another organisation that is going to be implementing a new back end to the client.

The messages format uses protocol buffers, so I'm less interested in describing the wire format.

I'm interested in documenting the interactions between the service and client. A typical interaction might be something like:

Client subscribes to Channel1

Client pushes RequestForStream to Queue1

Service reads from Queue1 publishes StreamResponse (containing endpoint to subscribe to, Channel2) to Channel1 and if successful starts publishing notifications to Channel2

Client receives from Channel1 and subscribes to Channel2

More stuff...

How can I best document scenarios like this? Does anyone know of any examples of documented interactions with Queues and channels?

Edit: I am not writing a Message Queue. I am using a JMS-like middleware named Nirvana. I want to document the application built on top of the Message Queue system.

Edit 2: In UML how would I model a Queue or Channel? Would I show them on a sequence diagram?

Body:
I have used pi-calculus to document and analysis high level processes. There isn't a standard language for pi-calculus, but for a tool I wrote I used a simple one-line per atomic step language, which would look something like:

process Client
    # initialise client process with the channel to subscribe to
    recv self Init ( channel1 : channel, queue1 : channel )
    # send request to server
    send queue1 RequestForStream ( channel1 )
    # bind channel in response to channel2
    recv channel1 StreamResponse ( channel2 : channel )

    loop:
    choice
        # either receive a notification or stop
        recv channel2 Notification ()
            goto loop
        recv channel2 Stop()
            stop

process Server
    new channel2
    # wait for request
    recv self RequestForStream ( client : channel )
    # send response to client with channel2 to send
    send client StreamResponse ( channel2 )
    # send notifications on channel2
    send channel2 Notification ()
    send channel2 Notification ()
    send channel2 Stop ()
    stop

# test
process Test
    c := start Client
    s := start Server

    send c Init ( c, s )
    stop

start Test

the extra stop parts are there as the tool is to detect deadlocks livelocks and races.


答:
No! It is a good practice to have a remote branch namespace for each developer.

A single branch is often not enough, so the developer would either end up rewinding it a lot or it wouldn't be helpful much. You rather want to say that a developer can push whatever they want under their.name/. They can use it for publishing preview versions for others, giving version for somebody else to test or even for somebody else to integrate.

You can use this also for giving branches to integrator or you can use task-based names. The task-based names are usually easier to track for the integrator, but make developers think more about the naming and people don't like thinking. I don't know which will work better in practice; might even depend on the particular team.


答:
Specifically for Javascript and web development:

Web applications usually consist of at least 4 languages/elements.

HTML - this is the markup that defines the structure of the page

CSS - this is a styling language that defines the look and feel of the page

Javascript (or something that compiles to JS) - this is a scripting language that runs in the browser (IE it runs on the client side machine)

Server side code - (Java,ruby, C#, python, etc etc) Usually there are one or more languages running on the server.

How do these all work together?  The browser renders the HTML/CSS and provides an environment for the javascript to run.  The javascript can send requests to the server in order to interact with the serverside code.

The serverside code may be compiled (Java/C#) or dynamic (python).  The key is that it isn't mixed in with the client side code, its run seperately and communicates with the client side code through a series of requests and responses.


问:
How to invoke anonymous functions in testing?
Below is Java code.

I need to cover the below function. I searched for many websites, but I still have no ideas. Is there any methods to cover the override anonymous classes?

```<code>  public static void addEnterListener(Text text, final String methodName, final Object callee) {
    text.addKeyListener(new KeyListener() {
    @Override
    public void keyReleased(KeyEvent arg0) {
    if (arg0.keyCode == '\r') {
      try {
        Method method = callee.getClass().getMethod(methodName, KeyEvent.class);
        method.invoke(callee, arg0);
      } catch (Exception e) {e.printStackTrace();}
    }
  }

  @Override
  public void keyPressed(KeyEvent arg0) {
  }
});
}
</code>```

答: As a third option, refactor creation of the KeyListener into a getKeyListener method. Call that method from your test code to get a KeyListener to test. Also call it in addEnterListener to get the KeyListener to add.</p>


问:
Storage and naming of log data
I'm in the process of rewriting a small application from console mode to a GUI mode.

The input is a file with log data from a measuring device:

```<code>...
00029;00044;00076;00044;00021
00309;00032;00037;00000;65535
00013;00016;00008;00007;00005
...
</code>```

Each row of data represents 5 counters which summarize the range in which the measure fell, i.e. first column is "<40%", 2nd column is "[40-50[", and so on...

First row as example:

```<code>29 counts below 40% | 44 counts between 40% and 60% | 76 counts between 60% and 80%
44 counts between 80% and 90% | 21 counts between 90% and 100%
</code>```

In the console application I used an array of integers to store each data row, putting each row array in a list. So far, so good... The application then used a for-loop to print out the values with descriptions to the console.

My problem:  I wanted to create a GUI with WPF and apply databinding.

But I have a conceptual issue with how to create the data binding to the arrays of integers and visual elements.

I have not had problems with data binding to single properties.  The challenge is due to the arrays.

I think I should create a class like this (could also be used as a ViewModel):

```<code>public class CounterRecords
{
    public List<CounterRecord> DataRecords { get; set; }
}
</code>```

But how should I go about the CounterRecord class?

What's a clean / clear implementation of this object that I can bind to?

```<code>public class CounterRecord
{
    public int Range40 { get; set; }
    public int Range40_60 { get; set; }
    public int Range60_80 { get; set; }
    public int Range80_90 { get; set; }
    public int Range90_100 { get; set; }
}
</code>```

答:
The Model layer should reflect your data, so if your log data represents 5 separate values which indicate a counter of a range, then that's what your Model should look like.

Your CounterRecord data model looks fine to me, however some things to take into consideration when using WPF's data binding systems are:

Are you going to be modifying the CounterRecord at runtime, and does this change need to be reflected in the UI? If so, you need to implement INotifyPropertyChanged on your CounterRecord class so it notifies the UI whenever it gets updated

Are you going to be modifying the collection of CounterRecord objects at runtime, and does this change need to be reflected in the UI? If so, you will want to use an ObservableCollection instead of a List<T> for the same reasons

To bind to a collection instead of a single property, you'll want a UI control with an ItemsSource property, such as a DataGrid or an ItemsControl

```<code><DataGrid ItemsSource="{Binding DataRecords}" />
</code>```

or

```<code><ItemsControl ItemsSource="{Binding DataRecords}" />
</code>```

Basically, an ItemsSource binding will loop through your collection and create a UI element for each item in the collection. That UI element may be a DataGridRow, a TabItem, a ListBoxItem, or even some custom element that you define with an ItemTemplate.

If you're interested, my blog has a better explanation of an ItemsControl than MSDN has, and it will probably help you understand the binding process to collections a bit better.

Title: Storage and naming of log data

Body:
The Model layer should reflect your data, so if your log data represents 5 separate values which indicate a counter of a range, then that's what your Model should look like.

Your CounterRecord data model looks fine to me, however some things to take into consideration when using WPF's data binding systems are:

Are you going to be modifying the CounterRecord at runtime, and does this change need to be reflected in the UI? If so, you need to implement INotifyPropertyChanged on your CounterRecord class so it notifies the UI whenever it gets updated

Are you going to be modifying the collection of CounterRecord objects at runtime, and does this change need to be reflected in the UI? If so, you will want to use an ObservableCollection instead of a List<T> for the same reasons

To bind to a collection instead of a single property, you'll want a UI control with an ItemsSource property, such as a DataGrid or an ItemsControl

<DataGrid ItemsSource="{Binding DataRecords}" />

or

<ItemsControl ItemsSource="{Binding DataRecords}" />

Basically, an ItemsSource binding will loop through your collection and create a UI element for each item in the collection. That UI element may be a DataGridRow, a TabItem, a ListBoxItem, or even some custom element that you define with an ItemTemplate.

If you're interested, my blog has a better explanation of an ItemsControl than MSDN has, and it will probably help you understand the binding process to collections a bit better.


问:
What are you thoughts on GWT?
Since I'm learning Java in this period and I just finished with the tutorials I think I'm ready to start contributing to a project (since I know from experience this is the best way to really learn).

I've seen GWT, looks interesting so I thought I should give it a try. I'm thinking however, since GWT deploys Java applications in JavaScript why should I learn GWT when I could learn the actual thing instead (this being JavaScript).
My question: is it worth it? Wouldn't someone be better of learning JavaScript if they want to build JS applications, instead of using Java and GWT? I realize that it might be easier to build certain things with GWT but in the end is it worth it?

Thanks.

答:
The very reason GWT took Java as source language is because JS (Ecmascript) is inhumanely difficult to work with. GWT is just a nice way to bring programming to Web/browsers where it was not possible before.

Before GWT there were futile attempts to program something in browsers (Ajax, dojo, plain javascript). But forces of nature are too violent there, so everything falls apart (browsers change, they are never same, people speak different languages, people think that 15 images should be actually 15 files etc).

So answer is: If I were to code for internet ocean boiler (which is not my job), then I'd choose GWT.

P.S. Another thought. The JS is made by Netscape. The company is long dead but the language stays there unfinished and rotting

OwnerDisplayName: Anonymous Coward

Title: What are you thoughts on GWT?


问:
Why are references rarely used in PHP?
I have some C++ knowledge and know that pointers are commonly used there, but I've started to look at PHP open source code and I never see code using references in methods.

Instead, the code always uses a return value instead of passing the reference to the variable to the method, which then changes that variable's value and just returns it.

I have read that using references uses less memory, so why aren't they used in PHP?

答:
PHP is a web-oriented language.

Web-pages being served fast and should be lightweight.

Usual PHP program lives fraction of second and consume few hundred kilobytes of memory.

There is no use for such optimizations.

OwnerDisplayName: Alexander Cogneau

Title: Why are references rarely used in PHP?

OwnerDisplayName: Your Common Sense


答:
Some reasons on the fly :

PHP is a scripting language, and doesn't aim to be used as a core embedded software (basically, memory is cleared at the end of the script),

Since PHP5, pass-by-reference is implicit for object parameters (so PHP uses pass-by-reference "in your back").

Title: Why are references rarely used in PHP?

Body:
I have some C++ knowledge and know that pointers are commonly used there, but I've started to look at PHP open source code and I never see code using references in methods.

Instead, the code always uses a return value instead of passing the reference to the variable to the method, which then changes that variable's value and just returns it.

I have read that using references uses less memory, so why aren't they used in PHP?

OwnerDisplayName: PéCé


答:
I know many php functions that do so. Have a look at preg_match() for instance. $matches will be passed by reference

If you want write a function for yourself that takes arguments by reference then use the following syntax

```<code>function byref(&$a, &$b, $c) {
    $a += $c;
    $b += $c;
    return $a * $b;
}
</code>```

$a and $b are passed by reference $c is passed by value.

Title: Why are references rarely used in PHP?

Body:
I know many php functions that do so. Have a look at preg_match() for instance. $matches will be passed by reference

If you want write a function for yourself that takes arguments by reference then use the following syntax

function byref(&$a, &$b, $c) {
    $a += $c;
    $b += $c;
    return $a * $b;
}

$a and $b are passed by reference $c is passed by value.


问:
What's a nice explanation for pointers?
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.

答:
Perhaps it's just me, but I work well with analogies. So let's say you have a friend (function/class) "Foo", who wants to have someone else (different function/class), "Bar", contact you for some reason. "Foo" could take you to go see "Bar", but that's not convenient, moving all those beings (instances) around. However, "Foo" could send "Bar" your phone number (pointer). That way, no matter where you are, "Foo" knows how to contact you without having to find you.

And, let's say "Bar" has an acquaintance, "Baz", who also wants to get in touch with you. But you're protective of your phone number and you don't want everyone to have, "Baz" can call "Bar" (phone as pointer), who can then forward the call to you (another pointer). And so on and on down the chain of "Baz"'s friends and friends of friends.

Title: What's a nice explanation for pointers?


答:
I think this is just a choice of the developers, nothing to do with the language.  Plenty of PHP code (built-in and not) use references. Take a look at the array functions in PHP, lots of those use references.  preg_match uses references.

I think one of the reasons developers choose not to use references is because it can be confusing.  You call a function and one of the variables may (or may not) be updated because it was a reference.  So, when you debug, it may not be clear why the value of $x jsut magically changed.

Title: Why are references rarely used in PHP?

OwnerDisplayName: Rocket Hazmat