问:
Are XML Comments Necessary Documentation?
I used to be a fan of requiring XML comments for documentation. I've since changed my mind for two main reasons:

Like good code, methods should be self-explanatory.

In practice, most XML comments are useless noise that provide no additional value.

Many times we simply use GhostDoc to generate generic comments, and this is what I mean by useless noise:

```<code>    /// <summary>
    /// Gets or sets the unit of measure.
    /// </summary>
    /// <value>
    /// The unit of measure.
    /// </value>
    public string UnitOfMeasure { get; set; }
</code>```

To me, that's obvious. Having said that, if there were special instructions to include, then we should absolutely use XML comments.

I like this excerpt from this article:

Sometimes, you will need to write comments. But, it should be the exception not the rule. Comments should only be used when they are expressing something that cannot be expressed in code. If you want to write elegant code, strive to eliminate comments and instead write self-documenting code.

Am I wrong to think we should only be using XML comments when the code isn't enough to explain itself on its own?

I believe this is a good example where XML comments make pretty code look ugly. It takes a class like this...

```<code>public class RawMaterialLabel : EntityBase
{
    public long     Id                      { get; set; }
    public string   ManufacturerId          { get; set; }
    public string   PartNumber              { get; set; }
    public string   Quantity                { get; set; }
    public string   UnitOfMeasure           { get; set; }
    public string   LotNumber               { get; set; }
    public string   SublotNumber            { get; set; }
    public int      LabelSerialNumber       { get; set; }
    public string   PurchaseOrderNumber     { get; set; }
    public string   PurchaseOrderLineNumber { get; set; }
    public DateTime ManufacturingDate       { get; set; }
    public string   LastModifiedUser        { get; set; }
    public DateTime LastModifiedTime        { get; set; }
    public Binary   VersionNumber           { get; set; }

    public ICollection<LotEquipmentScan> LotEquipmentScans { get; private set; }
}
</code>```

... And turns it into this:

```<code>/// <summary>
/// Container for properties of a raw material label
/// </summary>
public class RawMaterialLabel : EntityBase
{
    /// <summary>
    /// Gets or sets the id.
    /// </summary>
    /// <value>
    /// The id.
    /// </value>
    public long Id { get; set; }

    /// <summary>
    /// Gets or sets the manufacturer id.
    /// </summary>
    /// <value>
    /// The manufacturer id.
    /// </value>
    public string ManufacturerId { get; set; }

    /// <summary>
    /// Gets or sets the part number.
    /// </summary>
    /// <value>
    /// The part number.
    /// </value>
    public string PartNumber { get; set; }

    /// <summary>
    /// Gets or sets the quantity.
    /// </summary>
    /// <value>
    /// The quantity.
    /// </value>
    public string Quantity { get; set; }

    /// <summary>
    /// Gets or sets the unit of measure.
    /// </summary>
    /// <value>
    /// The unit of measure.
    /// </value>
    public string UnitOfMeasure { get; set; }

    /// <summary>
    /// Gets or sets the lot number.
    /// </summary>
    /// <value>
    /// The lot number.
    /// </value>
    public string LotNumber { get; set; }

    /// <summary>
    /// Gets or sets the sublot number.
    /// </summary>
    /// <value>
    /// The sublot number.
    /// </value>
    public string SublotNumber { get; set; }

    /// <summary>
    /// Gets or sets the label serial number.
    /// </summary>
    /// <value>
    /// The label serial number.
    /// </value>
    public int LabelSerialNumber { get; set; }

    /// <summary>
    /// Gets or sets the purchase order number.
    /// </summary>
    /// <value>
    /// The purchase order number.
    /// </value>
    public string PurchaseOrderNumber { get; set; }

    /// <summary>
    /// Gets or sets the purchase order line number.
    /// </summary>
    /// <value>
    /// The purchase order line number.
    /// </value>
    public string PurchaseOrderLineNumber { get; set; }

    /// <summary>
    /// Gets or sets the manufacturing date.
    /// </summary>
    /// <value>
    /// The manufacturing date.
    /// </value>
    public DateTime ManufacturingDate { get; set; }

    /// <summary>
    /// Gets or sets the last modified user.
    /// </summary>
    /// <value>
    /// The last modified user.
    /// </value>
    public string LastModifiedUser { get; set; }

    /// <summary>
    /// Gets or sets the last modified time.
    /// </summary>
    /// <value>
    /// The last modified time.
    /// </value>
    public DateTime LastModifiedTime { get; set; }

    /// <summary>
    /// Gets or sets the version number.
    /// </summary>
    /// <value>
    /// The version number.
    /// </value>
    public Binary VersionNumber { get; set; }

    /// <summary>
    /// Gets the lot equipment scans.
    /// </summary>
    /// <value>
    /// The lot equipment scans.
    /// </value>
    public ICollection<LotEquipmentScan> LotEquipmentScans { get; private set; }
}
</code>```

答:
If your comments only look like this:

```<code>/// <summary>
/// Gets or sets the sublot number.
/// </summary>
/// <value>
/// The sublot number.
/// </value>
</code>```

Then yes, they are not all that useful. If they read something like this:

```<code>/// <summary>
/// Gets or sets the sublot number.
/// Note that the sublot number is only used by the legacy inventory system.
/// Latest version of the online inventory system does not use this, so you can leave it null.
/// Some vendors require it but if you don't set it they'll send a request for it specifically.
/// </summary>
/// <value>
/// The sublot number.
/// </value>
</code>```

Then I'd say they have value. So to answer your question: Comments are necessary when they say something that the code does not say.

An exception: it is good to have comments on anything that is publicly accessible if you're writing a library/API that will be available to the public. I hate using a library and seeing a function named getAPCDGFSocket() with no explanation of what an APCDGFSocket is (I'd be happy with something as simple as This gets the Async Process Coordinator Data Generator File Socket). So in that case, I'd say use some tool to generate all comments and then manually tweak the ones that need it (and please make sure your cryptic acronyms are explained).

Also, getters/setters are generally bad examples for "are comments necessary?" because they are usually quite obvious and comments aren't necessary. Comments are more important on functions that perform some algorithm where some explanation of why things are being done they way they are could make the code much more understandable and also make it easier for future programmers to work with.

...and finally, I'm pretty sure that this question is relevant for all styles of comments, not just those that are formatted using XML (which you are using because you're working in a .NET environment).

Body:
If your comments only look like this:

/// <summary>
/// Gets or sets the sublot number.
/// </summary>
/// <value>
/// The sublot number.
/// </value>

Then yes, they are not all that useful. If they read something like this:

/// <summary>
/// Gets or sets the sublot number.
/// Note that the sublot number is only used by the legacy inventory system.
/// Latest version of the online inventory system does not use this, so you can leave it null.
/// Some vendors require it but if you don't set it they'll send a request for it specifically.
/// </summary>
/// <value>
/// The sublot number.
/// </value>

Then I'd say they have value. So to answer your question: Comments are necessary when they say something that the code does not say.

An exception: it is good to have comments on anything that is publicly accessible if you're writing a library/API that will be available to the public. I hate using a library and seeing a function named getAPCDGFSocket() with no explanation of what an APCDGFSocket is (I'd be happy with something as simple as This gets the Async Process Coordinator Data Generator File Socket). So in that case, I'd say use some tool to generate all comments and then manually tweak the ones that need it (and please make sure your cryptic acronyms are explained).

Also, getters/setters are generally bad examples for "are comments necessary?" because they are usually quite obvious and comments aren't necessary. Comments are more important on functions that perform some algorithm where some explanation of why things are being done they way they are could make the code much more understandable and also make it easier for future programmers to work with.

...and finally, I'm pretty sure that this question is relevant for all styles of comments, not just those that are formatted using XML (which you are using because you're working in a .NET environment).


答:
You are absolutely right about avoiding such useless comments. They make reading the code more difficult instead of making it easier, and are taking too much space.

In my practice people who write comments with getters/setters, tend to omit comments when those are really necessary (like building a 20-line sql-query for a component with no documentation).

I write comments when there are some other obvious solutions _ I indicate why exactly this approach has been used. Or when its hard to get the idea without knowing all of the details _ I briefly list the details that are necessary to understand the code.

The example you bring is more of writing comments to say that one writes comments rather than making others' (and theirs also) life easier.

BTW you can improve your ability of writing comments by returning to your old code and trying to comprehend it (you might even not recognize your own code in 2-3 months _ its absolutely like reading someone else's code). If you do this painlessly, than everything's just fine.

ContentLicense: CC BY-SA 3.0

Title: Are XML Comments Necessary Documentation?

Body:
I used to be a fan of requiring XML comments for documentation. I've since changed my mind for two main reasons:

Like good code, methods should be self-explanatory.

In practice, most XML comments are useless noise that provide no additional value.

Many times we simply use GhostDoc to generate generic comments, and this is what I mean by useless noise:

```<code>    /// <summary>
    /// Gets or sets the unit of measure.
    /// </summary>
    /// <value>
    /// The unit of measure.
    /// </value>
    public string UnitOfMeasure { get; set; }
</code>```

To me, that's obvious. Having said that, if there were special instructions to include, then we should absolutely use XML comments.

I like this excerpt from this article:

Sometimes, you will need to write comments. But, it should be the exception not the rule. Comments should only be used when they are expressing something that cannot be expressed in code. If you want to write elegant code, strive to eliminate comments and instead write self-documenting code.

Am I wrong to think we should only be using XML comments when the code isn't enough to explain itself on its own?

I believe this is a good example where XML comments make pretty code look ugly. It takes a class like this...

```<code>public class RawMaterialLabel : EntityBase
{
    public long     Id                      { get; set; }
    public string   ManufacturerId          { get; set; }
    public string   PartNumber              { get; set; }
    public string   Quantity                { get; set; }
    public string   UnitOfMeasure           { get; set; }
    public string   LotNumber               { get; set; }
    public string   SublotNumber            { get; set; }
    public int      LabelSerialNumber       { get; set; }
    public string   PurchaseOrderNumber     { get; set; }
    public string   PurchaseOrderLineNumber { get; set; }
    public DateTime ManufacturingDate       { get; set; }
    public string   LastModifiedUser        { get; set; }
    public DateTime LastModifiedTime        { get; set; }
    public Binary   VersionNumber           { get; set; }

    public ICollection<LotEquipmentScan> LotEquipmentScans { get; private set; }
}
</code>```

... And turns it into this:

```<code>/// <summary>
/// Container for properties of a raw material label
/// </summary>
public class RawMaterialLabel : EntityBase
{
    /// <summary>
    /// Gets or sets the id.
    /// </summary>
    /// <value>
    /// The id.
    /// </value>
    public long Id { get; set; }

    /// <summary>
    /// Gets or sets the manufacturer id.
    /// </summary>
    /// <value>
    /// The manufacturer id.
    /// </value>
    public string ManufacturerId { get; set; }

    /// <summary>
    /// Gets or sets the part number.
    /// </summary>
    /// <value>
    /// The part number.
    /// </value>
    public string PartNumber { get; set; }

    /// <summary>
    /// Gets or sets the quantity.
    /// </summary>
    /// <value>
    /// The quantity.
    /// </value>
    public string Quantity { get; set; }

    /// <summary>
    /// Gets or sets the unit of measure.
    /// </summary>
    /// <value>
    /// The unit of measure.
    /// </value>
    public string UnitOfMeasure { get; set; }

    /// <summary>
    /// Gets or sets the lot number.
    /// </summary>
    /// <value>
    /// The lot number.
    /// </value>
    public string LotNumber { get; set; }

    /// <summary>
    /// Gets or sets the sublot number.
    /// </summary>
    /// <value>
    /// The sublot number.
    /// </value>
    public string SublotNumber { get; set; }

    /// <summary>
    /// Gets or sets the label serial number.
    /// </summary>
    /// <value>
    /// The label serial number.
    /// </value>
    public int LabelSerialNumber { get; set; }

    /// <summary>
    /// Gets or sets the purchase order number.
    /// </summary>
    /// <value>
    /// The purchase order number.
    /// </value>
    public string PurchaseOrderNumber { get; set; }

    /// <summary>
    /// Gets or sets the purchase order line number.
    /// </summary>
    /// <value>
    /// The purchase order line number.
    /// </value>
    public string PurchaseOrderLineNumber { get; set; }

    /// <summary>
    /// Gets or sets the manufacturing date.
    /// </summary>
    /// <value>
    /// The manufacturing date.
    /// </value>
    public DateTime ManufacturingDate { get; set; }

    /// <summary>
    /// Gets or sets the last modified user.
    /// </summary>
    /// <value>
    /// The last modified user.
    /// </value>
    public string LastModifiedUser { get; set; }

    /// <summary>
    /// Gets or sets the last modified time.
    /// </summary>
    /// <value>
    /// The last modified time.
    /// </value>
    public DateTime LastModifiedTime { get; set; }

    /// <summary>
    /// Gets or sets the version number.
    /// </summary>
    /// <value>
    /// The version number.
    /// </value>
    public Binary VersionNumber { get; set; }

    /// <summary>
    /// Gets the lot equipment scans.
    /// </summary>
    /// <value>
    /// The lot equipment scans.
    /// </value>
    public ICollection<LotEquipmentScan> LotEquipmentScans { get; private set; }
}
</code>```


答:
The comments that look useless to users who can read the code become rather useful to users who have no access to the source. This happens when the class is used as an external API by people outside your organization: the HTMLs generated from your XML docs is their only way to learn about your classes.

That said, a comment that reiterates the method name with added spaces between the words remains useless. If your class is going to be used outside of your organization, you need to document at lest the valid ranges for your values. For example, you should say that setting UnitOfMeasure to null is illegal, that the value supplied to the setter must not contain spaces at the beginning or at the end of the string, and so on. You should also document the range of LabelSerialNumber if it differs from that of a plain Int32: perhaps it does not allow negative numbers*, or does not allow more than seven digits. Your internal users may take it for granted, because they look at serial numbers day in and day out, but the external users may be genuinely surprised to see an exception from what looks like an innocent setter.

* ...in which case uint may be a better choice


问:
help for choosing an encryption method for a database column
I'm storing some phone numbers in the database which should kept totally secret (they're supposed to access via web). BTW, because of the position of these people, I need to prevent any chance for leak of their numbers. So, the only solution I could thinking of is Encryption.

As the database could contains bunch of data, I won't encrypt the database entirely. Also, I actually prefer to use different key for each person to encrypt their phone numbers, so in the case of leaking one key, the other phone numbers should be safe at least. The problem is that other people also need to send SMS messages via the application through a web-interface and also some more privileged persons need to see these numbers, so I also need to make these numbers visible to the other privileged persons by the way.

I'm wondering of something like a public-key/private-key structure, but it's too much for just encrypting a phone number per person, and also there would be a problem for new users, because the previous numbers didn't encrypted with their public-keys.

So, is there any solution you might recommend to me? maybe I should to revise or update the structure of how I'm trying to do that, huh?

答:
For maximum security against compromise, don't store the phone numbers unless you have to.  Sounds like you don't have a choice in the matter.

Obfuscate the phone numbers prior to encrypting them.

A simple obfuscation would be to rearrange the numbers based upon a predefined pattern.

A more advanced obfuscation would be to salt the number and then obfuscate.  You would need to store this salt along with the number.

An even more advanced approach would be to generate the salt number based upon other characteristics of the user's data.

Create the obfuscation and salting routines in code outside of the database.  A stored procedure might be faster, but the stored procedure is potentially included with the compromised database.  External routines bypass that issue to some degree, and would require an additional degree of reverse engineering to find their functionality.

An additional benefit here is the ability to insert an additional authentication mechanism so you could conceivably prevent the DBAs from having access to the phone numbers since the only way to access the clear-text number is through the application you provide.

Consider using the native encryption capabilities of the database as it should simplify creating the access hierarchy that you mentioned.

I can't say I would recommend all of the public / private key pair combinations that you're suggesting.  The overhead in maintaining that will be too much.  It will also complicate the access hierarchy that you want.


问:
Using Git in Enterprise environment
Git is an excellent version control system. If we exclude the fact that, it doesn't have an excellent GUI support, it's really good and fast. But the source controls like Clearcase has large support for enterprise customers. Companies are investing huge amount for source control servers and licesense.

Of late most of the large companies like Google are adopting Git over other version control system. But this company has a strong open source group which consistently provide development and support for the tool (They might even have a custom version of Git of their own). At the same time, large companies are not really bothering about adopting open source projects and making them relevant to them.

Is Git really a reliable tool for enterprise environment, especially
on Windows Platform?

The support is in question for Git as it's an
open source product.

Are there any company that provides
solutions and support? How are the server costs compared to other
version controls like Clear-case?

答:
Is Git really a reliable tool for enterprise environment, especially for Windows Platform?

We will soon be at a strong yes with this one. Atlassian recently made big steps towards achieving this with the release of Stash 1.3.

The support is a question for Git as it's an open source version control.

There is a strong support network of knowledgeable Git users offering advice for free and various LinkedIn groups (Git Version Control System). A quick Google search can usually help with most requirements. For bigger enterprise companies there are also commercial git support options now available on the market today.

Any companies are there to provide solutions and support? How the server costs comparing to other version controls like Clear-case?

There are a number of companies now offering reliable and dedicated support for Git. Clearvision and #goGit to name one of them.

Title: Using Git in Enterprise environment


问:
Name for Osherove's modified singleton pattern?
I'm pretty well sold on the "singletons are evil" line of thought. Nevertheless, there are limited occurrences when you want to limit the creation of an object. Roy Osherove advises,

If you're planning to use a singleton in your design, separate the logic of the singleton class and the logic that makes it a singleton (the part that initializes a static variables, for example) into two separate classes. That way, you can keep the single responsibility principle (SRP) and also have a way to override singleton logic. (The Art of Unit Testing 261-262)

This pattern still perpetuates the global state. However, it does result in a testable design, so it seems to me to be a good pattern for mitigating the damage of a singleton.

However, Osherove does not give a name to this pattern; but naming a pattern, according to the Gang of Four, is important:

Naming a pattern immediately increases our design vocabulary. It lets us design at a higher level of abstraction. (3)

Is there a standard name for this pattern? It seems different enough from a standard singleton to deserve a separate name. Decoupled Singleton, perhaps?

答: It is the singleton pattern.  It's description as a design would be no different than the original singleton.  It is just an implementation variation.</p>


问:
Do ASP.Net Web Forms actually produce ADA compliant HTML? Does the ASP/AJAX toolkit undermine the goal of ADA compliance?
I'm trying to convince my employer to let us use the Microsoft ASP/AJAX toolkit since it simplifies the implementation of many controls. However they have rejected the idea on the grounds that it produces "AJAX code" which is not ADA compliant. However the same employer requires webpages to be written in ASP.NET Web Forms which, as far as I can tell from the source, is very very far from ADA compliance.

I am new to both web programming and ADA compliance.

My questions are:

Do ASP.Net Web Forms actually produce ADA compliant HTML?

Will the ASP/AJAX toolkit undermine the goal of ADA compliance?

答:
ASP.Net webforms is just a web technology.  Nothing inherent in it, or the code it generates, is ADA compliant.  While it could be compliant, Microsoft makes no guarantee of that.  At the end of the day, it's all just markup and up to the developer to ensure that it complies with ADA.  The same goes for the control toolkit.  AJAX code does mean there are more moving pieces, but there's nothing to say you can't write compliant code using it (it just could potentially make it more difficult).

This is from Microsoft's ASP.NET documentation:

ASP.NET controls are designed to be accessible by default. This means that they automatically render accessible HTML if possible, or they expose properties that you can set to make the pages accessible. For example, ASP.NET controls offer the following features to support accessibility by default:

Generate HTML that uses CSS for visual formatting.

Use tables to present data, not to arrange visual elements on a page.

Provide indications of table structure by marking header and footer rows.

Associate labels with the controls that they pertain to.

Generate client script that is device independent, such as client script that responds both to mouse clicks and to keyboard actions.

Specify tab index settings for input elements.

Provide a way to specify a text equivalent for any non-text element.

Some controls generate HTML based on templates for which you provide the HTML. In those cases you must manually configure the markup in the templates so that the generated HTML complies with accessibility guidelines.

There are some exceptional situations in which controls generate HTML that may not comply with accessibility standards. ASP.NET 4 includes many enhancements that eliminate most of the exceptions that existed in earlier versions of ASP.NET, or that provide alternatives to them. For more information, see What's New in ASP.NET 4 and Visual Web Developer.

The following sections present techniques for creating accessible Web pages that conform to each WCAG guideline by using Visual Studio and ASP.NET. For some guidelines, there are no considerations that are specific to ASP.NET. Therefore, sections devoted to those guidelines are omitted in this part of the topic.


问:
How do I speed up XML parsing operation?
I currently have a php script set up to do some xml parsing. Sometimes the script is set as an on page include and other times it is accessed via an ajax call. The problem is the load time for this particular page is very long. I started to think that the php I had written to find what I need in the XML was written poorly and my script is very resource intense. After much research and testing the problem is indeed not my scripting (well perhaps you could consider it a problem with my scripting), but it looks like it takes a long time to load the particular xml sources.

My code is like such:

```<code>$source_recent = 'my xml feed';
$source_additional = 'the other feed I need';

$xmlstr_recent = file_get_contents($source_recent);
$feed_recent = new SimpleXMLElement($xmlstr_recent);

$xmlstr_additional = file_get_contents($source_additional);
$feed_additional = new SimpleXMLElement($xmlstr_additional);
</code>```

In all my testing, the above code is what takes the time, not the additional processing I do below.

Is there anyway around this or am I at the mercy of the load time of the xml URL's?

One crazy thought I had to get around it is to load the xml contents into a db every so often, then just query the db for what I need.

Thoughts? Ideas?

答:
I also had problems with parsing large XML files. I tried Expresso XML Parser. It can parse files up to 35GB and it's really fast. It's really easy to use. You set up parsing rules on a website and test your file online and then use their client code to access your parsing rules from java or javascript.

They have a free developer version at www.sxml.com.au


问:
Inheriting projects - General Rules?

Possible Duplicate:

  When is a BIG Rewrite the answer?

  Software rewriting alternatives

  Are there any actual case studies on rewrites of software success/failure rates?

  When should you rewrite?

  We're not a software company. Is a complete re-write still a bad idea?

  Have you ever been involved in a BIG Rewrite?

This is an area of discussion I have long been curious about, but overall, I generally lack the experience to give myself an answer that I would fully trust.

We've all been there, a new client shows up with a half-complete project they are looking to finish and launch. For whatever reason, they fired their previous developer, and it's now up to you to save the day.

I am just finishing up a code review for a new client, and in my estimation is would be better to scrap what the previous developers built since and start from scratch. There's a ton of reasons why I am leaning toward this way, but it still makes me nervous since the client isn't going to want to hear "those last guys built you a big turd, and I can either polish it, or throw it in the trash".

What are your general rules for accepting these projects?

How do you determine whether it will be better to start from scratch or continue with the existing code base?

What other extra steps might you take to help control client expectations, since the previous developer may have inflated those expectations beyond a reasonable level?

Any other general advice?

答:
When a project like this comes in, my general rules are:

1) Ask to have complete access to evaluate what has been done.

2) Find out what may be usable, or usable with minimum tinkering (database architecture and design elements often fall into this category).

3) Give an estimate based on salvaging what is usable along with an estimate I would normally give from scratch. This helps me decide whether or not it's better to start from scratch.

I think it's important to be honest. If I feel that what has been done is truly substandard, I need to be able to explain why in simple terms. That's actually somewhat easier these days (not HTML 5, not a responsive design, no consideration for mobile, no use of framework, etc) as the technology has grown horizontally and the bad developers are easier to weed out.

Most of all it's important to make the potential client see what I see and give them the confidence that I not only know what's wrong, but how to fix it. If that means starting over, it's better to bite the bullet and do it now.

OwnerDisplayName: pspahn

Title: Inheriting projects - General Rules?

OwnerDisplayName: Kenzo


答:
Starting from scratch is, usually, the first approach of most people, there are many reasons for that, like different coding style, something disliked about the use of (classes/functions), to charge more, for not properly assessing of the amount of work, etc, etc.

If you can avoid rewriting everything again, is much better; but implies time to read and understand the code. Obviously, there are some situations when there is no other solution, but you should try to avoid it, for you and for the client. If the other developer used html 4.01 and you want to use html 5, that's not a good reason to scrap, if they used asp and you prefer php, that is not a good reason, unless you can't use that technology, and in that case, you have to tell the client your limitation, of course you may try to argue about quality of one over the other, but don't expect the client to care much about that.

Before accepting a project like that, or before telling the client about delivery time, you have to take your time to read.

Even if the client hates the other developer, they still expect you to do the things fast and finish soon, many times they say that they understand that this is a new project and that time has to start from zero, but inside, they are filing that the clock is ticking, that they started the project time ago and it is still not finish and then, they start putting more pressure on you. So make that point clear.

I would also ask the client about how fast they sent information to the old developer, if they say that it was always on time, I'll start to suspect a bad relation with the client. In my experience, it's uncommon to have materials and answers quick and accurate, so unless I have a more relative answer like "usually on time", "this or that was not clear but we talked about in mails and then ..." things like that, I'd very suspicious.

I'll ask if they still have the proposal from the other developer and will ask what went wrong, I'll try to get all the details.

Basically, you want to get clear if the client is difficult or not. The reason why fired the other developer is something that doesn't affect you, but you can get lot's of information from that fact and should try to use it.

Title: Inheriting projects - General Rules?

Body:
Possible Duplicate:

  When is a BIG Rewrite the answer?

  Software rewriting alternatives

  Are there any actual case studies on rewrites of software success/failure rates?

  When should you rewrite?

  We're not a software company. Is a complete re-write still a bad idea?

  Have you ever been involved in a BIG Rewrite?

This is an area of discussion I have long been curious about, but overall, I generally lack the experience to give myself an answer that I would fully trust.

We've all been there, a new client shows up with a half-complete project they are looking to finish and launch. For whatever reason, they fired their previous developer, and it's now up to you to save the day.

I am just finishing up a code review for a new client, and in my estimation is would be better to scrap what the previous developers built since and start from scratch. There's a ton of reasons why I am leaning toward this way, but it still makes me nervous since the client isn't going to want to hear "those last guys built you a big turd, and I can either polish it, or throw it in the trash".

What are your general rules for accepting these projects?

How do you determine whether it will be better to start from scratch or continue with the existing code base?

What other extra steps might you take to help control client expectations, since the previous developer may have inflated those expectations beyond a reasonable level?

Any other general advice?

OwnerDisplayName: PatomaS


答:
It's a Singleton combined with a Factory Method, such that the calling code has no idea that it is dealing with a singleton, or even the class it's dealing with. Even the class itself doesn't know it's a Singleton. The factory can be mocked out, making testing possible but, within the context of the application, it is always the same object returned.

I have seen a few sites call it a Singleton Factory, to distinguish the two.

It is common now to make this kind of decision (sometimes dangerously, as if you're no longer dealing with a true Singleton, so it doesn't matter) in the process of registering objects with an IoC container, making the name largely irrelevant.

Title: Name for Osherove's modified singleton pattern?

Body:
I'm pretty well sold on the "singletons are evil" line of thought. Nevertheless, there are limited occurrences when you want to limit the creation of an object. Roy Osherove advises,

If you're planning to use a singleton in your design, separate the logic of the singleton class and the logic that makes it a singleton (the part that initializes a static variables, for example) into two separate classes. That way, you can keep the single responsibility principle (SRP) and also have a way to override singleton logic. (The Art of Unit Testing 261-262)

This pattern still perpetuates the global state. However, it does result in a testable design, so it seems to me to be a good pattern for mitigating the damage of a singleton.

However, Osherove does not give a name to this pattern; but naming a pattern, according to the Gang of Four, is important:

Naming a pattern immediately increases our design vocabulary. It lets us design at a higher level of abstraction. (3)

Is there a standard name for this pattern? It seems different enough from a standard singleton to deserve a separate name. Decoupled Singleton, perhaps?


问:
Generic rule parser for RPG board game rules - how to do it?
I want to build a generic rule parser for pen and paper style RPG systems. A rule can involve usually 1 to N entities 1 to N roles of a dice and calculating values based on multiple attributes of an entity.

For example:

Player has STR 18, his currently equipped weapon gives him a bonus of +1 STR but a malus of DEX -1. He attacks a monster entity and the game logic now is required to run a set of rules or actions:

Player rolls the dice, if he gets for example 8 or more (base attack value he needs to pass is one of his base attributes!) his attack is successfull. The monster then rolls the dice to calculate if the attack goes through it's armor. If yes the damage is taken if not the attack was blocked.

Besides simple math rules can also have constraints like applying only to a certain class of user (warrior vs wizard for example) or any other attribute. So this is not just limited to mathematical operations.

If you're familiar with RPG systems like Dungeon and Dragons you'll know what I'm up to.

My issue is now that I have no clue how to exactly build this the best possible way. I want people to be able to set up any kind of rule and later simply do an action like selecting a player and a monster and run an action (set of rules like an attack).

I'm asking less for help with the database side of things but more about how to come up with a structure and a parser for it to keep my rules flexible. The language of choice for this is php by the way.

Edit I:

Let me refine my goal: I want to create a user friendly interface (that does not require somebody to learn a programming language) to build more or less complex game rules. The simple reason: Personal use to not need to remember all the rules all the time, we simply do not play that often and it's a stopper to look them up each time. Also: Looks like a fun task to do and learn something. :)

What I've tried so far: Just thinking about a concept instead of wasting time building a wrong architecture. So far I have the idea to allow a user to create as many attributes as they want and then assign as many attributes as they want to any kind of entity. An entity can be a player, a monster, an item, anything. Now when calculating something the data is made available to the rule parser so that the rule parser should be able to do things like if Player.base_attack + dice(1x6) > Monster.armor_check then Monster.health - 1; The question here is about how to create that parser.

Edit II:

Here is an example of pretty basic value but to calculate it properly there are lots of different things and variables to take into account:

Base Attack Bonus (Term) Your base attack bonus (commonly referred to
  as BAB by the d20 community) is an attack roll bonus derived from
  character class and level. Base attack bonuses increase at different
  rates for different character classes. A character gains a second
  attack per round when his base attack bonus reaches +6, a third with a
  base attack bonus of +11 or higher, and a fourth with a base attack
  bonus of +16 or higher. Base attack bonuses gained from different
  classes, such as for a multiclass character, stack. A character’s base
  attack bonus does not grant any more attacks after reaching +16,
  cannot be less than +0, and does not increase due to class levels
  after character level reaches 20th. A minimum base attack bonus is
  required for certain feats.

You can read it here http://www.dandwiki.com/wiki/Base_Attack_Bonus_(Term) including the links to classes and feats which have again their own rules to calculate the values that are required for the base attack.

I began to think that keeping it as generic as possible will also make it pretty hard to get a good rule parser done.

答:
What you’re asking for is essentially a domain-specific language—a small programming language for a narrow purpose, in this case defining P&P RPG rules. Designing a language is in principle not difficult, but there is a considerable amount of up-front knowledge that you must gain in order to be at all productive. Unfortunately, there is no central reference for this stuff—you’ve got to pick it up through trial, error, and lots of research.

First, find a set of primitive operations whereby other operations can be implemented. For example:

Get or set a property of the player, an NPC, or a monster

Get the result of a die roll

Evaluate arithmetic expressions

Evaluate conditional expressions

Perform conditional branching

Design a syntax that expresses your primitives. How will you represent numbers? What does a statement look like? Are statements semicolon-terminated? Newline-terminated? Is there block structure? How will you indicate it: through symbols or indentation? Are there variables? What constitutes a legal variable name? Are variables mutable? How will you access properties of objects? Are objects first-class? Can you create them yourself?

Write a parser that turns your program into an abstract syntax tree (AST). Learn about parsing statements with a recursive descent parser. Learn about how parsing arithmetic expressions with recursive descent is annoying, and a top-down operator precedence parser (Pratt parser) can make your life easier and your code shorter.

Write an interpreter that evaluates your AST. It can simply read each node in the tree and do what it says: a = b becomes new Assignment("a", "b") becomes vars["a"] = vars["b"];. If it makes your life easier, convert the AST into a simpler form before evaluation.

I recommend designing the simplest thing that will work and remain readable. Here’s an example of what a language might look like. Your design will necessarily differ based on your specific needs and preferences.

```<code>ATK = D20
if ATK >= player.ATK
    DEF = D20
    if DEF < monster.DEF
        monster.HP -= ATK
        if monster.HP < 0
            monster.ALIVE = 0
        end
    end
end
</code>```

Alternatively, learn how to embed an existing scripting language such as Python or Lua into your application, and use that. The downside of using a general-purpose language for a domain-specific task is that the abstraction is leaky: all the features and gotchas of the language are still present. The upside is you don’t have to implement it yourself—and that is a significant upside. Consider it.

Body:
What you’re asking for is essentially a domain-specific language—a small programming language for a narrow purpose, in this case defining P&P RPG rules. Designing a language is in principle not difficult, but there is a considerable amount of up-front knowledge that you must gain in order to be at all productive. Unfortunately, there is no central reference for this stuff—you’ve got to pick it up through trial, error, and lots of research.

First, find a set of primitive operations whereby other operations can be implemented. For example:

Get or set a property of the player, an NPC, or a monster

Get the result of a die roll

Evaluate arithmetic expressions

Evaluate conditional expressions

Perform conditional branching

Design a syntax that expresses your primitives. How will you represent numbers? What does a statement look like? Are statements semicolon-terminated? Newline-terminated? Is there block structure? How will you indicate it: through symbols or indentation? Are there variables? What constitutes a legal variable name? Are variables mutable? How will you access properties of objects? Are objects first-class? Can you create them yourself?

Write a parser that turns your program into an abstract syntax tree (AST). Learn about parsing statements with a recursive descent parser. Learn about how parsing arithmetic expressions with recursive descent is annoying, and a top-down operator precedence parser (Pratt parser) can make your life easier and your code shorter.

Write an interpreter that evaluates your AST. It can simply read each node in the tree and do what it says: a = b becomes new Assignment("a", "b") becomes vars["a"] = vars["b"];. If it makes your life easier, convert the AST into a simpler form before evaluation.

I recommend designing the simplest thing that will work and remain readable. Here’s an example of what a language might look like. Your design will necessarily differ based on your specific needs and preferences.

ATK = D20
if ATK >= player.ATK
    DEF = D20
    if DEF < monster.DEF
        monster.HP -= ATK
        if monster.HP < 0
            monster.ALIVE = 0
        end
    end
end

Alternatively, learn how to embed an existing scripting language such as Python or Lua into your application, and use that. The downside of using a general-purpose language for a domain-specific task is that the abstraction is leaky: all the features and gotchas of the language are still present. The upside is you don’t have to implement it yourself—and that is a significant upside. Consider it.


问:
How can I explain object-oriented programming to someone who's only coded in Fortran 77?
My mother did her college thesis in Fortran, and now (over a decade later) needs to learn c++ for fluids simulations. She is able to understand all of the procedural programming, but no matter how hard I try to explain objects to her, it doesn't stick. (I do a lot of work with Java, so I know how objects work) I think I might be explaining it in too high-level ways, so it isn't really making sense to someone who's never worked with them at all and grew up in the age of purely procedural programming.

Is there any simple way I can explain them to her that will help her understand?

答:
Once she understands structures, I think the next key point will be to recognize that object-oriented programming serves as a means of confining the set of methods to which a thing may be passed, to the set of methods which could actually be applied to that thing.

In non-object-oriented programming, if one is using separate data types for a Tree and a LinkedList, one would have to use different methods for adding a node to each.  Non-object-oriented languages would generally squawk if one tried to name both methods AddItem, since any given name can only refer to one method, thus leading one to create method names like AddTreeItem, AddLinkedListItem, RemoveTreeItem, etc.  Such an approach works, but it's a bit ugly.  Conceptually, the methods AddTreeItem and RemoveTreeItem seem to belong together, but the names don't sort that way.  One could rewrite the names as TreeAddItem, TreeRemoveItem, LinkedListAddItem, etc. but that would put a lot of "redundant noise" at the start of each method invocation.  The vast majority of method calls in a typical program will have three essential pieces of information: (1) what section of the source code contains the method; (2) which of the methods in section is being used; (3) what piece of data is being acted upon?  In many cases, the type of data being acted upon will be sufficient to identify which code section the method belongs to, so part (1) of the above is redundant.  It's easier to visually identify material at the start of a statement than material elsewhere, so a coding/naming style like TreeAddItem(myTree, whatever) ends up putting the least useful piece of information in the prime spot.

By contrast, using object-oriented programming, one would effectively name methods as Tree.AddItem, etc. and a statement like myTree.AddItem(whatever) would cause a compiler to say, essentially, "Hmm... myTree is of type Tree, so this code should invoke Tree.AddItem().  It's not necessary to specify the Tree. when calling AddItem since the compiler knows the type of myTree.  Conceptually, a statement like myTree.AddItem(whatever) is equivalent to Tree.AddItem(myTree, whatever), and some object-oriented languages may allow both forms as equivalent; in fact, most languages omit the first parameter from the function specification and instead have methods that are defined in a class like Tree implicitly take a parameter of type Tree, and assign it a name like this, self, or Me.

Object-oriented programming languages often include a variety of additional features such as inheritance, virtual functions, etc. which are very useful in many applications, but even without those features the ability to group functions according to the things they operate upon is very useful.


答:
The "singleton pattern" embodies a a couple of different concepts: (1) some sort of object is implicitly shared; (2) the object may be lazily created without changing the observable system state.  While these concepts often go together, some applications will use one without the other.

For example, a system may use a thread-static variable to hold a reference to the current database.  When each thread that will need the data base is initiated, it grabs a copy of a global "current database" setting and uses that to get a reference to the current database which it will then use until it has run to completion.  Since many methods will all use the current database, explicitly passing around a reference to it may be cumbersome, and saying "all methods operate on the thread's current database, as defined by _" may be make the code cleaner than having to explicitly pass a reference to the database with every function call.  Note that in this scenario, there is an object which is shared implicitly, but its creation alters the system state.

Alternatively, a program may have a variety of static instances of objects implementing IGetGlobalWidget with a virtual GetWidget method.  These objects, being static, are created at program startup rather than being lazily generated, and each of these objects when used will lazily (if necessary) create some sort of Widget derivative and return a reference to it.  Rather than passing around Widget references, code passes around references to implementations of IGetGlobalWidget.  Any particular IGetGlobalWidget implementation will always return the same Widget-derivative instance, and the lazy creation will not affect visible program state, but code could control which methods will share widgets, by which methods share IGetGlobalWidget objects.


答:
Object-oriented programming—in the class-oriented sense relevant here—is about coupling a data representation with the code that manipulates it. It makes sense if the following things make sense:

Coupling: defining an operation alongside the data representation it works on

Late binding: choosing a combination of data representation and behaviour at runtime

Encapsulation: ensuring that data is valid by construction and won’t be later invalidated

That’s all. Like any technology, at its heart it’s simply a convenience, from which many developments have later followed. Once you understand the basics, the rest follows in time.

Title: How can I explain object-oriented programming to someone who's only coded in Fortran 77?

Body:
My mother did her college thesis in Fortran, and now (over a decade later) needs to learn c++ for fluids simulations. She is able to understand all of the procedural programming, but no matter how hard I try to explain objects to her, it doesn't stick. (I do a lot of work with Java, so I know how objects work) I think I might be explaining it in too high-level ways, so it isn't really making sense to someone who's never worked with them at all and grew up in the age of purely procedural programming.

Is there any simple way I can explain them to her that will help her understand?


问:
How can I distribute a unique database already in production?
Let's assume a successful web Spring application running on a MySQL or PostgreSQL database. The traffic is becoming so high and the amount of data is becoming so big that a distributed database solution needs to be implemented to address scalability issue. Let's also assume this application is using Hibernate and the data access layer is cleanly separated with DAOs.

Ideally, one should be able to add or remove databases easily. A failback solution is welcome too.

What would be the best strategy to scale this database? Is it possible to minimize sharding code (Shard) in the application?

答: The best strategy might be to use an existing database sharding solution such as dbShards. This will allow you to move to a sharded solution without having to make any significant code changes to your application (dbShards will make the shards look like a single database as far as your application is concerned). While there is a cost to the software it could well be cheaper than building out your own sharding solution.</p>


问:
How to design data structures for sharding?
When designing data structures for an application, what are some best practices to make sure it can be sharded?

In particular, which of the following is better:

Creating relationships in databases

Establishing relationships in SQL queries as necessary?

答:
You would typically shard a group of tables based on a key such as customer_id. One simple approach is to use the modulus. For example if you have 4 shards then divide the customer_id by 4 and use the remainder to determine which shard to use.

However, this approach isn't very flexible when you want to change the number of shards later on.

You may want to read this database sharding whitepaper that explains the theory in much more detail.

Regards,

Andy Grove

Chief Architect

http://www.dbshards.com


答:
I would start by determining the different "Phases" of each action.

For example, a Combat Phase might involve:

```<code>GetPlayerCombatStats();
GetEnemyCombatStats();
GetDiceRoll();
CalculateDamage();
</code>```

Each of these methods would have access to some fairly generic objects, such as the Player and the Monster, and would perform some fairly generic checks that other entities can use to modify the values.

For example, you might have something that looks like this included in your GetPlayerCombatStats() method:

```<code>GetPlayerCombatStats()
{
    Stats tempStats = player.BaseStats;

    player.GetCombatStats(player, monster, tempStats);

    foreach(var item in Player.EquippedItems)
        item.GetCombatStats(player, monster, tempStats);
}
</code>```

This allows you to easily add in any entity with specific rules, such as a Player Class, monster, or Equipment piece.

As another example, suppose you wanted a Sword of Slaying Everything Except Squid, which that gives you +4 against everything, unless that thing has tentacles, in which case you have to drop your sword and get a -10 in the combat.

Your equipment class for this sword might have an GetCombatStats that looks something like this:

```<code>GetCombatStats(Player player, Monster monster, Stats tmpStats)
{
    if (monster.Type == MonsterTypes.Tentacled)
    {
        player.Equipment.Drop(this);
        tmpStats.Attack -= 10;
    }
    else
    {
        tmpStats.Attack += 4;
    }
}
</code>```

This allows you to easily modify the combat values without needing to know about the rest of the combat logic, and it allows you to easily add new pieces to the application because the details and implementation logic of your Equipment (or whatever entity it is) only need to exist in the entity class itself.

The key things to figure out is at what points can values change, and what elements influence those values. Once you have those, building out your individual components should be easy :)

Title: Generic rule parser for RPG board game rules - how to do it?

Body:
I want to build a generic rule parser for pen and paper style RPG systems. A rule can involve usually 1 to N entities 1 to N roles of a dice and calculating values based on multiple attributes of an entity.

For example:

Player has STR 18, his currently equipped weapon gives him a bonus of +1 STR but a malus of DEX -1. He attacks a monster entity and the game logic now is required to run a set of rules or actions:

Player rolls the dice, if he gets for example 8 or more (base attack value he needs to pass is one of his base attributes!) his attack is successfull. The monster then rolls the dice to calculate if the attack goes through it's armor. If yes the damage is taken if not the attack was blocked.

Besides simple math rules can also have constraints like applying only to a certain class of user (warrior vs wizard for example) or any other attribute. So this is not just limited to mathematical operations.

If you're familiar with RPG systems like Dungeon and Dragons you'll know what I'm up to.

My issue is now that I have no clue how to exactly build this the best possible way. I want people to be able to set up any kind of rule and later simply do an action like selecting a player and a monster and run an action (set of rules like an attack).

I'm asking less for help with the database side of things but more about how to come up with a structure and a parser for it to keep my rules flexible. The language of choice for this is php by the way.

Edit I:

Let me refine my goal: I want to create a user friendly interface (that does not require somebody to learn a programming language) to build more or less complex game rules. The simple reason: Personal use to not need to remember all the rules all the time, we simply do not play that often and it's a stopper to look them up each time. Also: Looks like a fun task to do and learn something. :)

What I've tried so far: Just thinking about a concept instead of wasting time building a wrong architecture. So far I have the idea to allow a user to create as many attributes as they want and then assign as many attributes as they want to any kind of entity. An entity can be a player, a monster, an item, anything. Now when calculating something the data is made available to the rule parser so that the rule parser should be able to do things like if Player.base_attack + dice(1x6) > Monster.armor_check then Monster.health - 1; The question here is about how to create that parser.

Edit II:

Here is an example of pretty basic value but to calculate it properly there are lots of different things and variables to take into account:

Base Attack Bonus (Term) Your base attack bonus (commonly referred to
  as BAB by the d20 community) is an attack roll bonus derived from
  character class and level. Base attack bonuses increase at different
  rates for different character classes. A character gains a second
  attack per round when his base attack bonus reaches +6, a third with a
  base attack bonus of +11 or higher, and a fourth with a base attack
  bonus of +16 or higher. Base attack bonuses gained from different
  classes, such as for a multiclass character, stack. A character’s base
  attack bonus does not grant any more attacks after reaching +16,
  cannot be less than +0, and does not increase due to class levels
  after character level reaches 20th. A minimum base attack bonus is
  required for certain feats.

You can read it here http://www.dandwiki.com/wiki/Base_Attack_Bonus_(Term) including the links to classes and feats which have again their own rules to calculate the values that are required for the base attack.

I began to think that keeping it as generic as possible will also make it pretty hard to get a good rule parser done.

Body:
I would start by determining the different "Phases" of each action.

For example, a Combat Phase might involve:

GetPlayerCombatStats();
GetEnemyCombatStats();
GetDiceRoll();
CalculateDamage();

Each of these methods would have access to some fairly generic objects, such as the Player and the Monster, and would perform some fairly generic checks that other entities can use to modify the values.

For example, you might have something that looks like this included in your GetPlayerCombatStats() method:

GetPlayerCombatStats()
{
    Stats tempStats = player.BaseStats;

    player.GetCombatStats(player, monster, tempStats);

    foreach(var item in Player.EquippedItems)
        item.GetCombatStats(player, monster, tempStats);
}

This allows you to easily add in any entity with specific rules, such as a Player Class, monster, or Equipment piece.

As another example, suppose you wanted a Sword of Slaying Everything Except Squid, which that gives you +4 against everything, unless that thing has tentacles, in which case you have to drop your sword and get a -10 in the combat.

Your equipment class for this sword might have an GetCombatStats that looks something like this:

GetCombatStats(Player player, Monster monster, Stats tmpStats)
{
    if (monster.Type == MonsterTypes.Tentacled)
    {
        player.Equipment.Drop(this);
        tmpStats.Attack -= 10;
    }
    else
    {
        tmpStats.Attack += 4;
    }
}

This allows you to easily modify the combat values without needing to know about the rest of the combat logic, and it allows you to easily add new pieces to the application because the details and implementation logic of your Equipment (or whatever entity it is) only need to exist in the entity class itself.

The key things to figure out is at what points can values change, and what elements influence those values. Once you have those, building out your individual components should be easy :)


答:
In my limited research of ADA compliance, the problem with AJAX was how screen-readers handled it.  If I recall, since screen-readers read the markup from the top-down they may not be able to respond to dynamic markup that is later injected into an HTML form via an AJAX call (or other dynamic change, for that matter).  So if you have a DIV that you want to use as a popup or fill with dynamic content, if the screen-reader has already parsed it, it will not necessarily 're-parse' it after you dynamically change the contents.  So your user may not know the form has changed.  Different readers had different limitations, but I do remeber thinking strict ADA compliance really restricted the convenience of AJAX.

However, ASP.NET does not force you to use AJAX, so ADA requirements should not disqualify the use of ASP.NET in any way.

Title: Do ASP.Net Web Forms actually produce ADA compliant HTML? Does the ASP/AJAX toolkit undermine the goal of ADA compliance?

Body:
I'm trying to convince my employer to let us use the Microsoft ASP/AJAX toolkit since it simplifies the implementation of many controls. However they have rejected the idea on the grounds that it produces "AJAX code" which is not ADA compliant. However the same employer requires webpages to be written in ASP.NET Web Forms which, as far as I can tell from the source, is very very far from ADA compliance.

I am new to both web programming and ADA compliance.

My questions are:

Do ASP.Net Web Forms actually produce ADA compliant HTML?

Will the ASP/AJAX toolkit undermine the goal of ADA compliance?


问:
Ways to ensure unique instances of a class?
I'm looking for different ways to ensure that each instance of a given class is a uniquely identifiable instance.

For example, I have a Name class with the field name. Once I have a Name object with name initialised to John Smith I don't want to be able to instantiate a different Name object also with the name as John Smith, or if instantiation does take place I want a reference to the orginal object to be passed back rather than a new object.

I'm aware that one way of doing this is to have a static factory that holds a Map of all the current Name objects and the factory checks that an object with John Smith as the name doesn't already exist before passing back a reference to a Name object.

Another way I could think of off the top of my head is having a static Map in the Name class and when the constructor is called throwing an exception if the value passed in for name is already in use in another object, however I'm aware throwing exceptions in a constructor is generally a bad idea.

Are there other ways of achieving this?

答:
Actually you have already answered your question. Your first way should be more effective here. Using static factory is always preferable than constructor wherever you think you can. So, you can avoid using Constructor in this case, else you would have throw some exception if an instance already exists with the given name.

So, you can create a static factory method: - getInstanceWithName(name) which will get the already available instance with that name, and if it does not exist, it will create a new instance, and make your constructor private, as it should mostly be done when dealing with static factories.

Also, for that you need to maintain a static List or Map of all the unique instances created, in your Factory class.

EDIT: -

You should certainly go through - Effective Java - Item#1 : Consider Static factories over Constructors. You can't get better explanation than that book.

OwnerDisplayName: Peanut

OwnerDisplayName: Rohit Jain


答: you should make the constructors private and create methods like getNameInstance(String), if a  object with the same name already exists (based on a static class' hastable for instance), you return that reference, else you create a new object using your private constructor and add it to the hashtable

Title: Ways to ensure unique instances of a class?

Body:
I'm looking for different ways to ensure that each instance of a given class is a uniquely identifiable instance.

For example, I have a Name class with the field name. Once I have a Name object with name initialised to John Smith I don't want to be able to instantiate a different Name object also with the name as John Smith, or if instantiation does take place I want a reference to the orginal object to be passed back rather than a new object.

I'm aware that one way of doing this is to have a static factory that holds a Map of all the current Name objects and the factory checks that an object with John Smith as the name doesn't already exist before passing back a reference to a Name object.

Another way I could think of off the top of my head is having a static Map in the Name class and when the constructor is called throwing an exception if the value passed in for name is already in use in another object, however I'm aware throwing exceptions in a constructor is generally a bad idea.

Are there other ways of achieving this?


答:
Mentions of Effective Java seems to add a lot of credibility so this answer draws on:

Effective Java Item 8: Obey the general contract when overriding equals

Effective Java Item 9: Always override the hashCode when you override equals

Effective Java Item 15: Minimise mutability

I would take a step back and question why you care if there are more than one instance of this name object.

I rarely need to do this kind of object pooling. It is my guess that the OP is doing this so they can simply compare their Name objects with ==. Or use the Name objects inside a HashMap or similar as the key.

If so this is something that can be solved through proper implementation of equals().

Like so:

```<code>public final class Name {
  private final String name;

  public Name(String name) {
    if (name == null) {
      name = ""; //or exception if you like
    }
    this.name = name;
  }

  public String getName() {
    return name;
  }

  @Override
  public boolean equals(Object o) {
    if (!(o instanceof Name)) {
      return false;
    }
    Name other = (Name) o;
    return other.name.equals(name);
  }

  @Override
  public int hashCode() {
    return name.hashCode();
  }
}
</code>```

Once done the following is true:

```<code>Name a = new Name("weston");
Name b = new Name("weston");
assert(a.equals(b)); //same but:
assert(a!=b); //not the same instance
//test out the Name instances in a hashmap:
HashMap<Name,Object> map = new HashMap<Name,Object>();
Object detailsIn = new Object();
map.put(a,detailsIn);
Object detailsOut = map.get(b);
assert(detailsIn==detailsOut); //the map returned the same details object
//even though we put with `a` and got with `b` thanks to our correct equals implementation
</code>```

I'm guessing your goal, but this way you can use the Name class in hash maps etc, and they do not have to be the exact same instance.

Body:
Mentions of Effective Java seems to add a lot of credibility so this answer draws on:

Effective Java Item 8: Obey the general contract when overriding equals

Effective Java Item 9: Always override the hashCode when you override equals

Effective Java Item 15: Minimise mutability

I would take a step back and question why you care if there are more than one instance of this name object.

I rarely need to do this kind of object pooling. It is my guess that the OP is doing this so they can simply compare their Name objects with ==. Or use the Name objects inside a HashMap or similar as the key.

If so this is something that can be solved through proper implementation of equals().

Like so:

public final class Name {
  private final String name;

  public Name(String name) {
    if (name == null) {
      name = ""; //or exception if you like
    }
    this.name = name;
  }

  public String getName() {
    return name;
  }

  @Override
  public boolean equals(Object o) {
    if (!(o instanceof Name)) {
      return false;
    }
    Name other = (Name) o;
    return other.name.equals(name);
  }

  @Override
  public int hashCode() {
    return name.hashCode();
  }
}

Once done the following is true:

Name a = new Name("weston");
Name b = new Name("weston");
assert(a.equals(b)); //same but:
assert(a!=b); //not the same instance
//test out the Name instances in a hashmap:
HashMap<Name,Object> map = new HashMap<Name,Object>();
Object detailsIn = new Object();
map.put(a,detailsIn);
Object detailsOut = map.get(b);
assert(detailsIn==detailsOut); //the map returned the same details object
//even though we put with `a` and got with `b` thanks to our correct equals implementation

I'm guessing your goal, but this way you can use the Name class in hash maps etc, and they do not have to be the exact same instance.


答:
Make Name an interface

Create an interface NameFactory with a method Name getByName(String)

Create an implementation of NameFactory with a Map<String,WeakReference<Name>> inside it

synchronize on the map by name inside the getByName method before making new instances of Name

Optionally, use a static private implementation of the Name interface inside your implementation of the NameFactory

This approach would let you ensure that:

Only a single instance of Name exists at any time,

There is no "Lingerer" memory leak in your class, when Names stick around longer than they need to,

The design remains testable with mocked objects, because you use interfaces.


问:
Is a simple iPhone app more appealing to users than a mobile website?
My client wants to do an iPhone app because she's found that people are significantly more likely to use the iPhone app over a mobile optimized site. The iPhone app is very simple - it just displays a couple images and some text. As a programmer I'd much rather do a mobile site given the simple nature of the content. From a technical perspective I feel that it's overkill to use an iPhone app in this situation.

Does it make sense to build an iPhone app when a mobile site would suffice, simply because your users would much rather it be an iPhone app? Is there anyway to easily convince users that a mobile site is just as easy to use?

答:
You're not giving your client enough information to make an informed decision.

Are they aware of the iPhone app approval process?

Are there features where users need access when they aren't connected?

Do you have to worry about sensitive information stored on the phone?

What about devices not made by Apple?

Beware of "it's easier for me to build a website" because there is compentition out there who will be more than happy to build an iphone app.


问:
Does Liskov Substitution Principle also apply to classes implementing an interface?
LSP states that classes should be substitutable for their base classes, meaning that derived and base classes should be semantically equivalent.

But does LSP also apply to classes implementing an interface? In other words, if an interface method implemented by a class is semantically different from what user expects it to be, would this be considered as a violation of LSP?

答:
if an interface method implemented by a class is semantically different from what user expects it to be, would this be considered as a violation of LSP?

If the implementation is semantically different from the behavior documented through the invariants of the interface and its methods' pre- and post-conditions, then the answer is "yes", it would be a violation of the LSP. The principle establishes the rules for the abstraction and its implementations, without requiring the abstraction side to be present in the form of a class.

However, if we talk about what users expect, the answer would be "not necessarily": the users are entitled to having wrong expectations.


问:
Is it a good idea to appoint one of the scrum team member or scrum master as Product Owner?
Lately we had a project, in which client was busy touring. As usual scrum team was formed, management decided to appoint our analyst as Product owner since Client won’t be able to participate actively. Analyst was the one who worked closely with client for requirement analysis and specification drafting.

Client doesn’t have the time to review first two releases. Everything went smoothly until, client saw third release; he wasn’t satisfied with some functionalities, and those was introduced by make shift Product Owner (our analyst).

We were told to wait till design team finished mock-up of all pages and client checked each one and approved to continue working. Scrum team is there, but no sprints – we finished work almost like classic waterfall method.

Is it a good idea to appoint scrum team member or master as product owner? Do we need to follow scrum in the absence of client/product owner participation?

答: Ideally the product owner has some level of authority and knowledge about the project. This same thing could have happened if the client assigned a lower-level employee who was then over-ruled at a later phase requiring you to nearly start over.</p>

ContentLicense: CC BY-SA 2.5


问:
Is server validation necessary with client-side validators?
I recently created a .net web app that used over 200 custom validators on one page. I wrote code for both ClientValidationFunction and OnServerValidate which results in a ton of repetitive code.

My sql statements are parameterized, I have functions that pull data from input fields and validates them before passing to the sql statements or stored procedures. And the javascript validates the fields before the page submits. So essentially the data is clean and valid before it even hits the OnServerValidate and clean after it anyways due to the aforementioned steps.

This makes me question, is OnServerValidate really needed when I validate on the clientside?

Edit:

My OnServerValidates do simple things like making sure a skip pattern is enforced or that a short appears in a text (which is enforced anyways with my code that pulls data from text fields into parameters i.e. GetShort()). And these are being place in patient surveys, which most of the time are filled out by staff members.

So it seems like if I didn't have the OnServerValidate for these basic checks and just client side the following situations are:

A user turns off javascript and cannot submit the form, which is
expected as buttons are javascript driven for postbacks.

A user forces a post. Which if this occurs my OnServerValidate
would do jack to stop whatever they are trying to do since it is
just looking at skip patterns, or would it?

Situation 2 is where I am getting lost. It seems like the user forcing a post is more than likely not to be caught by these simple OnServerValidates

答:
If I was going to skip doing validation, I'd be much more likely to do it on the client than on the server.

The problem with skipping it anywhere is that someone may open up a security hole by assuming validation is being done when it's not.


问:
Why JSP over Servlets for view?
Although servlets does the task of sending the HTML code to the client programmers weight JSP over servlets for that. Even a JSP code is compiled into servlet before giving the response to the browser then why is JSP preferred? If servlet is used then a lot of computation work can be saved.</p>

答: JSPs are preferred if you are mainly augmenting an HTML template with server-generated data (e.g., generating a table of information or filtering a collection of images/documents).  Servlets are preferred for functions that don't have UI-related work (e.g., filters and web services).  JSPs seem to becoming a little less common nowadays, with more work being done with straight web pages making AJAX calls to web services, but they can still be useful.</p>

Title: Why JSP over Servlets for view?


问:
What to do when there are no logical user stories but separate development tasks?
We need to generate a release in 3 weeks, and for the planning we are doing today we don't have coherent logical user stories from the backlog tasks. Is valid to match say each development task is equivalent to an user story?

Methodologically what is the correct way of handling this?, because anyway we are going to have standup meetings and we are going to control the progress of the project against those development tasks.

For example, we have things like:

.  Adapt ETL to process numeric lists

.  Adjust licensing component

.  Remove DTC

and so on.

So, for the planning poker and iteration planning is valid to use those tasks? if not, what is the alternative?

答:
You may want to consider a change to your process- generate development tasks from user stories, not the other way around. User stories have a business value built in.

For example, the adjustment to the licensing component: If you can express that as a story (As [a type of user], I want [some feature] because it will give me [some business value]), then go ahead and make the adjustment.

If you can't find the user and the business value, that should be a clue: don't do that work! Do something else instead.


问:
How to make the switch to C++11?
I've been programming in C++ for a while now, but mostly things centered around the low-level features of C++. By that I mean mostly working with pointers and raw arrays. I think this behavior is known as using C++ as C with classes. Despite this, I only having tried C recently for the first time. I was pleasantly surprised how languages like C# and Java hide these details away in convenient standard library classes like Dictionaries and Lists.

I'm aware that the C++ standard library has many containers like vectors, maps and strings as well and C++11 only adds to this by having std:: array and ranged loops.

How do I best learn to make use of these modern language features and which are suitable for which moments? Is it correct that software engineering in C++ nowadays is mostly free of manual memory management?

Lastly, which compiler should I use to make the most of the new standard? Visual Studio has excellent debugging tools, but even VS2012 seems to have terrible C++11 support.

答:
First, some rules of thumb:

Use std::unique_ptr as a no-overhead smart pointer. You shouldn’t need to bother with raw pointers all that often. std::shared_ptr is likewise unnecessary in most cases. A desire for shared ownership often betrays a lack of thought about ownership in the first place.

Use std::array for static-length arrays and std::vector for dynamic.

Use generic algorithms extensively, in particular:

<algorithm>

<numeric>

<iterator>

<functional>

Use auto and decltype() wherever they benefit readability. In particular, when you want to declare a thing, but of a type that you don’t care about such as an iterator or complex template type, use auto. When you want to declare a thing in terms of the type of another thing, use decltype().

Make things type-safe when you can. When you have assertions that enforce invariants on a particular kind of thing, that logic can be centralised in a type. And this doesn’t necessarily make for any runtime overhead. It should also go without saying that C-style casts ((T)x) should be avoided in favour of the more explicit (and searchable!) C++-style casts (e.g., static_cast).

Finally, know how the rule of three:

Destructor

Copy constructor

Assignment operator

Has become the rule of five with the addition of the move constructor and move assignment operator. And understand rvalue references in general and how to avoid copying.

C++ is a complex language, so it’s difficult to characterise how best to use all of it. But the practices of good C++ development haven’t changed fundamentally with C++11. You should still prefer memory-managed containers over manual memory management—smart pointers make it easy to efficiently do this.

I would say that modern C++ is indeed mostly free of manual memory management—the advantage to C++’s memory model is that it’s deterministic, not that it’s manual. Predictable deallocations make for more predictable performance.

As for a compiler, G++ and Clang are both competitive in terms of C++11 features, and rapidly catching up on their deficiencies. I don’t use Visual Studio, so I can speak neither for nor against it.

Finally, a note about std::for_each: avoid it in general.

transform, accumulate, and erase–remove_if are good old functional map, fold, and filter. But for_each is more general, and therefore less meaningful—it doesn’t express any intent other than looping. Besides that, it’s used in the same situations as range-based for, and is syntactically heavier, even when used point-free. Consider:

```<code>for (const auto i : container)
    std::cout << i << '\n';

std::for_each(container.begin(), container.end(), [](int i) {
    std::cout << i << '\n';
});

for (const auto i : container)
    frobnicate(i);

std::for_each(container.begin(), container.end(), frobnicate);
</code>```

Title: How to make the switch to C++11?

Body:
First, some rules of thumb:

Use std::unique_ptr as a no-overhead smart pointer. You shouldn’t need to bother with raw pointers all that often. std::shared_ptr is likewise unnecessary in most cases. A desire for shared ownership often betrays a lack of thought about ownership in the first place.

Use std::array for static-length arrays and std::vector for dynamic.

Use generic algorithms extensively, in particular:

<algorithm>

<numeric>

<iterator>

<functional>

Use auto and decltype() wherever they benefit readability. In particular, when you want to declare a thing, but of a type that you don’t care about such as an iterator or complex template type, use auto. When you want to declare a thing in terms of the type of another thing, use decltype().

Make things type-safe when you can. When you have assertions that enforce invariants on a particular kind of thing, that logic can be centralised in a type. And this doesn’t necessarily make for any runtime overhead. It should also go without saying that C-style casts ((T)x) should be avoided in favour of the more explicit (and searchable!) C++-style casts (e.g., static_cast).

Finally, know how the rule of three:

Destructor

Copy constructor

Assignment operator

Has become the rule of five with the addition of the move constructor and move assignment operator. And understand rvalue references in general and how to avoid copying.

C++ is a complex language, so it’s difficult to characterise how best to use all of it. But the practices of good C++ development haven’t changed fundamentally with C++11. You should still prefer memory-managed containers over manual memory management—smart pointers make it easy to efficiently do this.

I would say that modern C++ is indeed mostly free of manual memory management—the advantage to C++’s memory model is that it’s deterministic, not that it’s manual. Predictable deallocations make for more predictable performance.

As for a compiler, G++ and Clang are both competitive in terms of C++11 features, and rapidly catching up on their deficiencies. I don’t use Visual Studio, so I can speak neither for nor against it.

Finally, a note about std::for_each: avoid it in general.

transform, accumulate, and erase–remove_if are good old functional map, fold, and filter. But for_each is more general, and therefore less meaningful—it doesn’t express any intent other than looping. Besides that, it’s used in the same situations as range-based for, and is syntactically heavier, even when used point-free. Consider:

for (const auto i : container)
    std::cout << i << '\n';

std::for_each(container.begin(), container.end(), [](int i) {
    std::cout << i << '\n';
});

for (const auto i : container)
    frobnicate(i);

std::for_each(container.begin(), container.end(), frobnicate);


问:
What is JavaScript, really?
All this started when I was looking for a way to test my webpage for JavaScript conformance like the W3C HTML Validator. I have not found one yet. So let me know if you know of any...

I looked for the official JavaScript page and find ECMA Script. These people have standardized a scripting language (I do not feel like calling it JavaScript anymore!) and called it ECMA-262 (Wikipedia). Their latest work is Edition 5.1

JavaScript was developed by Mozilla Corporation and their last stable version is 1.8.5 (see this) which is based on the ECMA's edition 5.1

The Wikipedia page linked mentions dialects. Mozilla's JavaScript 1.8.5 is listed as a dialect along with JScript 9 (IE) and JavaScript (Chrome's V8[Wiki]) and a lot others. Am I to understand that JavaScript 1.8.5 is a derivative of the ECMA-262 and SpiderMonkey[Wiki] is an engine that runs it? And Chrome has its own dialect and V8 engine is the program that runs it?

With all these dialects based off ECMA-262, what I can no longer understand is "What is JavaScript"? Are there any truly cross browser scripting languages? Do the various implementers come together to agree on the dialect cross compatibility? Is this effort ECMA?

答:
Javascript is a commonly used implementation of ECMAScript. It's a very similar situation to the Scheme family. In Scheme, you have a highly formalized specification. The current version is R6RS though R5RS is by far the more commonly implemented standard as of this post. The implementations are more scattered than ECMAScript's due to Scheme's age and general philosophies.

Javascript happens to be common now largely due to the explosive growth in market share of both Mozilla's Firefox and Google's Chrome. It gained a foothold originally with Netscape Navigator which eventually turned into the Mozilla browser and then into Firefox (and Iceweasel if you run with the Scheme crowd).

Now here's where it gets a little dicey. Most of Javascript's performance comes from the parser and engine running it. This is where the real differences between browsers become apparent. Spidermonkey runs Javascript differently than V8 does. Javascript still have rough spots like the lack of a fully common library, though that's being worked on.

So if Javascript were C++, then ECMAScript would be the C++11, with UNIX and G++ being the closest to "standard" while C++ for .NET and Objective C++ lie further afield much in the way Actionscript does from ECMAScript

OwnerDisplayName: Lord Loh.

Title: What is JavaScript, really?


答:
Yes, it's valid. Tasks are stories that haven't been expressed yet.

A story represents something created by a company which gives value to a customer. Identify the customer of each task (it's ok to have an internal customer), then define the value to that customer. Define your done criteria and you have a valid story.

If you can't identify the user, and/or if you can't identify the business value, you should rethink why you are doing the work. You should always be providing some value to somebody.

Title: What to do when there are no logical user stories but separate development tasks?

Body:
We need to generate a release in 3 weeks, and for the planning we are doing today we don't have coherent logical user stories from the backlog tasks. Is valid to match say each development task is equivalent to an user story?

Methodologically what is the correct way of handling this?, because anyway we are going to have standup meetings and we are going to control the progress of the project against those development tasks.

For example, we have things like:

.  Adapt ETL to process numeric lists

.  Adjust licensing component

.  Remove DTC

and so on.

So, for the planning poker and iteration planning is valid to use those tasks? if not, what is the alternative?


答:
The simple answer is to just write stories for the tasks. This is actually an opportunity to validate (and reconsider!) the business value of each task.

For example,

As a [developer], I want to [Adapt ETL to process numeric lists], so that [numeric lists don't crash the server]

As a [developer], I want to [Adapt ETL to process numeric lists], so that [numeric lists can be imported into the data warehouse]

it's even better if some value is identified for the users other than the developers, e.g.

As a [data warehouse manager], I want [ETL to properly process numeric lists], so that [daily operational statistics can be correlated to the widget production]

If you can't find any business value/impact for a task, reconsider doing it at all.


答:
Pretty much all mature languages are defined by a specification, and compilers or interpreters attempt to follow the standard defined in that specification. But very rarely do they succeed, unless the standard is defined by the author of the language.

You can find the C++ 2003 standard, the C# 4 specification, the Java 7 specification and many more online. Many of these have ECMA or ISO standardisation numbers. These are just organisations with which you can register a standard and make it more official.

Ruby has historically done things a little differently, having an executable set of tests as a specification. So, if you want to write an interpreter and call it standard Ruby, you just had to create an interpreter that passed all of those tests. But even Ruby is likely to become a more formal specification eventually.

Javascript is no different, except possibly in the way it has evolved.

Javascript was first created by Netscape. They called it LiveScript, but it looked similar to Java and they cut a deal with Sun over the name, which benefited both the marketing of Netscape and Java. Microsoft had VBScript and (for reasons probably lost to conjecture) basically copied Javascript, but the name was owned by Sun, so they cheekily called it JScript.

But JScript, while being very similar to Javascript in syntax, made a lot of use of COM -- for example, IE5 and 6 instantiate an XMLHttpRequest object using new ActiveXObject("Microsoft.XMLHTTP");.

And so, parallel, similar but also different "dialects" of Javascript were born. Over time, various groups owning browsers with less market share than IE have tried to standardise the language, and for years Microsoft resisted. Until V8.

V8 was fast. It set a whole new market standard. It made everything else look poor.

And, through various antitrust cases against Microsoft, IE was losing market share. Suddenly, it was in Microsoft's interest to support standardisation. We're not there yet, but it's on the right track.

Meanwhile, V8 was open-source, which allowed people to start thinking up new uses for a fast Javascript parser, such as Node.JS.

But, to go back to your question: What is Javascript? It's the common (and original) name for ECMAScript, a specification for a prototypical language commonly, but not exclusively, used for navigating and manipulating the domain object model in a broswer.

ECMA-262 is just the standard definition, like ECMA-334 is the standard definition for C#. ECMAScript was the only name that all the interested parties could agree on, back in '99, when ECMA-262 was written.

Title: What is JavaScript, really?

Body:
All this started when I was looking for a way to test my webpage for JavaScript conformance like the W3C HTML Validator. I have not found one yet. So let me know if you know of any...

I looked for the official JavaScript page and find ECMA Script. These people have standardized a scripting language (I do not feel like calling it JavaScript anymore!) and called it ECMA-262 (Wikipedia). Their latest work is Edition 5.1

JavaScript was developed by Mozilla Corporation and their last stable version is 1.8.5 (see this) which is based on the ECMA's edition 5.1

The Wikipedia page linked mentions dialects. Mozilla's JavaScript 1.8.5 is listed as a dialect along with JScript 9 (IE) and JavaScript (Chrome's V8[Wiki]) and a lot others. Am I to understand that JavaScript 1.8.5 is a derivative of the ECMA-262 and SpiderMonkey[Wiki] is an engine that runs it? And Chrome has its own dialect and V8 engine is the program that runs it?

With all these dialects based off ECMA-262, what I can no longer understand is "What is JavaScript"? Are there any truly cross browser scripting languages? Do the various implementers come together to agree on the dialect cross compatibility? Is this effort ECMA?


答:
My university is still using C++ for teaching. I have programmed with C++ for 5 years and now I am a graduate student. Of course, now I am using a lot Java, Ruby etc.
I really recommend you don't too hurry about those features in language like Java. In my experience and opinion, after the low level features of C++. You should look into topics like generic programming with C/C++ like making template class, template functions, operator overritten, virtual methods, smart pointers.
For the Object Oriented Design Part, there are lots of features C++ have and Java does not, like multi-inheritance. Inheritance is powerful but dangerous too. The implementation level of object oriented design in C++ is a good topic too.
Inter-process communication, threadings, are important in C++ too.

For the compiler and debugger. I know visual studio is awesome. But I really recommend you learn GDB, Valgrind, and Make still, and be good at these tools. Microsoft is awesome, but it did too many things for you. As a student, you really need to learn those things which Microsoft did too you. For the compiler, G++ is good from GNU.

After all, after so many years, I really feel, the most important things are the low level features like raw array. Vector is really just a dynamic array.
These are my recommendations, something maybe too subjective, just take what you think is right.

Title: How to make the switch to C++11?

Body:
I've been programming in C++ for a while now, but mostly things centered around the low-level features of C++. By that I mean mostly working with pointers and raw arrays. I think this behavior is known as using C++ as C with classes. Despite this, I only having tried C recently for the first time. I was pleasantly surprised how languages like C# and Java hide these details away in convenient standard library classes like Dictionaries and Lists.

I'm aware that the C++ standard library has many containers like vectors, maps and strings as well and C++11 only adds to this by having std:: array and ranged loops.

How do I best learn to make use of these modern language features and which are suitable for which moments? Is it correct that software engineering in C++ nowadays is mostly free of manual memory management?

Lastly, which compiler should I use to make the most of the new standard? Visual Studio has excellent debugging tools, but even VS2012 seems to have terrible C++11 support.


问:
Do non-manager coders in their forties or older out there sometimes regret about not being managers?
And why do most programmers quit coding and become managers so early compared to other areas? You can work as a construction worker, a lawyer, researcher, writer, architect, movie director for decades if not your whole life, without quitting the favorite thing you are doing. And yet most programmers think being a manager, or better, a non-coding manager is a cool thing and the ultimate goal of the software career. It's so rare to see an ordinary coder in his 40s or 50s (or 60s!) in a typical software company. Why?

(And I am for being a coder for as long as you love doing it.)

答:
I'll have a try at answering the question from the other side. As a junior developer, I would like a manager/team leader who has been around awhile and can help me interface to the business side of things. In many companies IT is a support role, so I wouldn't expect for upper management to really care for what we need to work well. He should have a good bit more credibility than me!

However, I would still want a programmer for a manager. If he came up through the coding ranks he also can help me with my programming problems. What's the point of having a manager that you can't take problems to?

Incidentally, the highest I am really excited about getting to is a team leader.


问:
handling a GET error properly
I have a website that takes two primary get strings:

```<code>?type=GAME&id=SomeGameID
?type=SCENARIO&id=SomeScenarioID
</code>```

for reasons unknown, I have recently begun receiving requests for erroneous get strings from both Yandex and Baidu. They are always in the form of:

```<code>?type=GAME&id=SomeScenarioID
</code>```

None of my users are triggering these errors, so I am (sort of) confident that this is not due to an HTML template error somewhere on my part. There is also no HTTP_REFER showing up in the $_SERVER array, so I'm guessing these are direct requests from bad dbase data on their part.

I see two options for dealing with these bad requests, and would like to know which is recommended... or if there are other, better options I have not thought of:

simply 404 the request, since it is incorrect

redirect the request to ?type=SCENARIO&id=SomeScenarioID because the scenario IDs are always valid, the breakage is due to asking for the wrong type.

答:
I would stick with rejecting the request, however as the url being requested does exist, the error code 400 seems more appropriate.

From the w3 http/1.1 standards:

10.4.1 400 Bad Request

The request could not be understood by the server due to malformed
  syntax. The client SHOULD NOT repeat the request without
  modifications.

Title: handling a GET error properly