问:
Why learn git when there are GUI apps for GitHub?
Given that GitHub provides GUI apps for both Mac and Windows, what are the benefits of learning to use git from the command line?

Currently I'm using their mac app to update my repositories, and so far it seems to cover my needs. What might I be missing out on?

答:
If all your needs are covered, awesome, no need to dig deeper into git, your time would be better spent in learning something you actually need.

git is just a tool, when you'll need to do something you can't with a GUI app, you'll know it. Just keep in mind that github != git.


问:
IIS for beginner
I have a problem understanding some functionalities in IIS. Per example I want to know when do I use "Add application", "add virtual directory" or "add website".

Currently I have around 10 websites which are located in my wwwroot/websitename directory and they automatically appear under sites in IIS.

What is the best approach?

答:
What are you trying to achieve?  Each of these has a different use:

The "Add website" is how multiple sites can be supported on the same server.  Thus you could have "www.mysite.com" and "anothersite.mysite.com" using different IPs on the same server but accessing completely different files if you so wish.

The "Add virtual directory" is how you add another folder into your current site to create a "www.mysite.com/thisfolder" routing to a particular folder.

The "Add application" is used when you want to add that folder but run it in another application pool.  This can be useful if you want to have separate processes for different parts of a site.

IIS.net would be a site about how to configure and use IIS. Scott Gu's blog is also a good resource for some points in IIS and ASP.Net if you choose to go into that realm of things.

You do understand that the physical path is asking for the root of the website, right?  Where should the site start if one is looking at the file system on the server?  The binding is what IPs, ports and host headers should be used for this site.  Is there a specific IP, port or name you intend to use? If so, this is where that gets set.  If you want 5 websites, then you create 4 additional sites besides the default one and configure as needed, perhaps you run each site on a different port.  For example, if you type in "http://localhost/site1" and "http://localhost/site2" are you getting into a couple of what you think are different sites even though both run under the localhost site?

If the admin section is in a different part of the file system, yes.  The idea of a virtual directory is to allow for the website to use files from multiple places on the system's hard drives.  For example, your website could have the "wwwroot/mysite" for its initial location and then reference another disk for where the virtual directory maps which could be on another drive if you wish.  The idea is to have "mysite/blah" "mysite/whatever" and "mysite/here" all appear to be next to each other but they don't have to be on the server side as each directory could be mapped to a different location.

The separate processes may be useful if part of your site is less stable and you don't want that application crashing to be impacting the other application pools.  Application Pools in Microsoft IIS notes:

You can run as many applications in one application pool as you
  desire.  However, for critical production applications, it is better
  to set up one application pool per application.  This allows each
  application pool to have its own memory space and errors within one
  application will not impact other applications running in other pools.

Microsoft .NET Framework does impose a limitation that each
  Application Pool can only run one version of the Microsoft .NET
  Framework.  So if you have some applications that require Microsoft
  .NET Framework 1.1 and others that require version 2.0, you must
  create two different application pools.  Note that Microsoft .NET
  Framework 3.0 and 3.5 are really Microsoft .NET Framework 2.0 from the
  perspective of all web applications.  So there is no requirement to
  separate applications using version 2.0, 3.0 or 3.5 of Microsoft .NET
  Framework into separate application pools.

Iron Speed recommends running each application in its own application
  pool.

ASP.NET Web Garden - How Many Worker Processes Do I Need? also has some answers in terms of worker process stuff that may be of some use from SO.  In a way, splitting up a website into multiple applications is like splitting up code into multiple DLLs versus having one big executable.  It takes some experimentation and what works in one place may not work in another place.

ContentLicense: CC BY-SA 3.0

Title: IIS for beginner


答:
Most of the CLI-only features only come into play when you accidentally get your repository into a weird state and want to fix it.  On the other hand, the most common way to get your repo into a weird state is to use advanced features you don't understand.  If you stick to what the GUI provides, that will cover your needs 99% of the time.

The other reason you may want to learn the CLI is that it is git's lingua franca.  That means while a lot of people use different GUIs on different platforms, if you ask for help on StackOverflow or elsewhere, the answer is most likely going to come in the form of CLI commands.  If you don't know the CLI, your options for obtaining help are going to be much more limited.

Title: Why learn git when there are GUI apps for GitHub?

Body:
Given that GitHub provides GUI apps for both Mac and Windows, what are the benefits of learning to use git from the command line?

Currently I'm using their mac app to update my repositories, and so far it seems to cover my needs. What might I be missing out on?


问:
How to write good code with new stuff?
I always try to write easily readable code that is well structured.

I face a particular problem when I am messing around with something new. I keep changing the code, structure and so many other things. In the end, I look at the code and am annoyed at how complicated it became when I was trying to do something so simple.

Once I've completed something, I refactor it heavily so that it's cleaner. This occurs after completion most of the time and it is annoying because the bigger the code the more annoying it is the rewrite it.

I am curious to know how people deal with such agony, especially on big projects shared between many people ?

答:
I detected from my practice that I write more clear and simple code when I understand problem domain completely. Unfortunately, customers often cannot exactly clarify what they want and this is a normal working situation. If you misunderstood the domain, it will be reflected in your code. And if you are a project lead, one of your main tasks is to help customer to get new sight on his business solution he wants you to implement.
So, try to give more time for a domain analysis and it helps you to write more simple and clear code.</p>

Title: How to write good code with new stuff?


问:
Should you ever re-estimate user stories?
My current project is having a 'discussion' which is split down the middle- "this story is more complex than we originally thought, we should re-estimate" vs "you should never re-estimate as you only ever estimate up and never down".

Can anyone shed some light on whether you ever should re-estimate?

IMHO I'd imagine you could bring up an entirely new card for a new requirement or story, but going back and re-estimating on backlog items seems to skew the concept of relative sizing and will only ever 'inflate' your backlog.

答:
The main reason I don't repoint is that it destroys the usefulness of your velocity.  Consider a hypothetical scrum team who estimates every story as 1 point.  They complete approximately 10 stories every iteration, for an average velocity of 10.

During a retrospective, a team member argues that in hindsight, when you look back at pretty much every iteration, one of the stories really should have been a 5 pointer, so they should repoint it to "fix" their velocity.  That brings their velocity up to 14.

The next planning, the velocity suggests they can take on four more stories.  They are pretty sure that can't be right, because chances are good that one of the future stories they estimated is really a 5 pointer.  Unfortunately, they have no idea which one.  Suddenly, they have a velocity figure that is absolutely useless for planning.

The thing is, if they had kept their velocity at 10, that takes into consideration their estimation skills.  If 10% of their stories in previous iterations were really 5 pointers, then odds are 10% of their stories in future iterations are similarly underestimated.  Over a long period of time, it all comes out in the wash.

Remember velocity has no units.  A higher number is not better than an accurate and useful one.  If you want bragging rights just multiply everything by 1000 :-)


答:
Short answer: the product owner can do anything he or she wants to a story--until the sprint where the team commits to complete it.

So, if the team wants to re-estimate a story for a future sprint, go nuts.

Once you're in the sprint, the work (and the estimate) is fixed.

I've worked this way on numerous projects and it works just fine.  If you're doing a burn-down for the product backlog, be sure to either back-update the estimate or at least visually make it clear that the change is not a case of burn-up.

Title: Should you ever re-estimate user stories?

Body:
My current project is having a 'discussion' which is split down the middle- "this story is more complex than we originally thought, we should re-estimate" vs "you should never re-estimate as you only ever estimate up and never down".

Can anyone shed some light on whether you ever should re-estimate?

IMHO I'd imagine you could bring up an entirely new card for a new requirement or story, but going back and re-estimating on backlog items seems to skew the concept of relative sizing and will only ever 'inflate' your backlog.


问:
Type of AI to tackle this problem?
I posted this on stackoverflow but want to get your recommendations as well as a user on overflow recommended I post it here.

I'm going to say from the beginning that I am not a programmer, I have a cursory knowledge of different types of AI and am just a businessman building a web app.

Anyways, the web app I am investing in to develop is for a hobby of mine. There are many part manufacturers, product manufacturers, upgrade and addon manufacturers etc. for hardware/products in this hobby's industry. Currently, I am in the process of building a crowd sourced platform for people who are knowledgeable to go in and mark up compatibility between those parts as its not always clear cut if they are for example:

Manufacturer A makes a "A" class product, and manufacturer B makes upgrade/part that generally goes with class "A" products, but is for one reason or another not compatible with Manufacturer A's particular "A" class product.

However, a good chunk (>60%-70%) of the products/parts in the database can have their compatibility inferred by their properties,

For example:

Part 1 is type "A" with "X" mm receiver and part 2 is also Type "A" with "X" mm interface and thus the two parts are compatible..

or

Part 1 is a 8mm gear, thus all bushings of 8mm from any manufacturer is compatible with part 1. Further more, all gears can only have compatibility relationships in the database with bushing and gear boxes, but there can be no meaningful compatibility between a gear and a rail, or receiver since those parts don't interface.

Now what I want is an AI to be able to learn from the decisions of the crowdsourced platform community and be able to infer compatibility for new parts/products based on their tagged attributes, what type of part they are etc.

What would be the best form of AI to tackle this? I was thinking a Expert System, but explicitly engineering all of the knowledge rules would be daunting because of the complex relations between literally tens of thousands of parts, hundreds of part types and many manufacturers.

Would a ANN (neural network) be ideal to learn from the many inputs/decisions of the crowdsource platform users?

Any help/input is much appreciated.

答:
If I understand you correctly, you essentially have a data set (crowd-)sourced from actual people, which describes the compatibility between various parts.  You would like to build something which analyses this information, and figures out the associations between the parts and the compatibility flag.

Essentially, extracting this type of information from a data set is known as Data Mining.  A variety of techniques are applied (statistical analysis, etc), to essentially identify the various traits in the data set that result in various classifications ("compatible" vs "not compatible").  These rules can then be turned into an expert system either automatically, or by hand.  It's worthwhile mentioning that several software packages exist to do this job, so you may not have to write everything yourself (although they may be pricey).  I would say that this is the most straightforward approach to what you want to do (although it would still be very difficult, involving many issues, such as dealing with incomplete data, etc).

I should also mention that you should question what you want to achieve with this, exactly.  The benefit of having an expert system is that it would be able to apply similar logic to determine compatibility on parts which are very similar to ones it already understands well.  The ability of the AI to apply itself in this way is called generalisation, and it's pretty much the only thing you will get out of it, since it will never outperform the original data for the original items.  I would definitely weigh up the implications of this.  If you are expecting a huge data set with many similar items, it may still be very worthwhile.  If, however, you will have only a few similar items in each category, the AI will be relatively useless.

Title: Type of AI to tackle this problem?


答:
I think this question is just a special case of "Why should I learn any CLI for which a GUI alternative exist?". I suspect the latter question is about as old as GUIs, and I assume there were many attempts to answer it over the years.
I could try to bumble my way through my own answer to this question, but Neal Stephenson articulated what I agree with as the 'ultimate answer' more than ten years ago in his remarkable essay In the Beginning... Was the Command Line.

While the essay touches on many aspects of computing, and while even Stephenson himself thinks that a lot of it is now obsolete, the essay explains in what ways CLIs are better GUIs in an extremely compelling manner that literally changed my life. It's a long read (~40 pages), but I can't recommend it enough to anyone who asks questions like you asked here.

Finally, though I'd answer any CLI vs GUI sort of question in similar vein, I think my answer holds especially true to your specific question since of all computer things you chose to ask about git. git is arguably the latest tool in a not-so-long list of computer tools that are truly worthy of the hole-hawg metaphor as described in Stephenson's essay. git, like several other Unix-ish things, is a reason to know CLIs all in itself. Sometimes in spite of its erratic 'porcelain'; sometimes because of it.

So yes, you can definitely be productive with github's GUI, either for OSX or even just on their website. Yes, it's actually quite sleek, I use the features of the site often. But no, you will never have that Godly feeling as your right pinky hangs above an insane git filter-branch command for an aeon or two. If I had to keep just one thing from my experience with computing -  the mental challenges, the close friendships formed in a datcenter at 2AM, the infinite ladder of competence to climb, touching users' lives and reigning over PBs of precious data, the cushy jobs and comfortable life - keep just one thing - it'd be that Godly feeling.

ContentLicense: CC BY-SA 4.0


问:
Conceptual difference between Git and GitHub
The last line of this answer prompted me to ask this question . I know to know at a conceptual level the difference between Git and GitHub .</p>

答:
Git is the distributed version control system. Git is responsible for keeping track of changes to content (usually source code files), and it provides mechanisms for sharing that content with others.

GitHub is a company that provides Git repository hosting. If your team has a shared repository on GitHub, you could conceivably use GitHub without ever looking at its website. But, the website provides a lot of value on top of the core Git repository.

GitHub also developed graphical Git clients: GitHub for Mac and GitHub for Windows. Each is an application that lets you interact with Git repositories without using the command line.

Concepts from Git: Repositories, branches, remotes, committing, pushing, pulling, merging, rebasing, reverting, and cherry-picking.

Concepts from GitHub: Pull requests, issues, wikis, forking someone else's repository, Gists, github.com.


答:
The crucial part of the story is this:

Currently, I am in the process of building a crowd sourced platform
  for people who are knowledgeable to go in and mark up compatibility
  between those parts as its not always clear cut if they are for
  example:

And this...

Now what I want is an AI to be able to learn from the decisions of the
  crowdsourced platform community and be able to inference compatibility
  for new parts/products based on their tagged attributes, what type of
  part they are etc.

This leaves me with the assumption that the database of parts will already be established, more or less.

The primary crowd sourcing aspect of the process will be to confirm or deny compatibility claims: affirming claims already made.  The secondary aspect will be to add new compatibility claims that weren't previously identified by other people, or inferred by the system.

The system could evaluate the claim including the conditions of the claim or the reliability of all associated claims, the nature of the part-to-part relationship, and identify if there is similarity in other part-to-part relationships to allow an additional claim to be inferred.

The conditions of the claim would be primarily being a judge of behavior, which ultimately would lead to something resembling an ANN/neural network.  However, tuning this process to adjust the weighting factors of the variables under consideration will encourage the use to some degree of Markov chaining simply because going into the project, you won't have a model to tell you which factors to weigh the strongest, and which to discard, and there will be a lot of factors you will want to consider, from both a part-to-part relationship, from the user activity profile, and system activity profile (the system in this aspect should be viewed as just another user who has made a bunch of claims).

The nature of the part-to-part relationship is tricky.   There are only a few points in a part-to-part pairing that probably need to be considered as crucial in determining if a part-to-part relationship may be a reasonable candidate for compatibility.  For this aspect, an expert system would probably fit, but it could be even a less complicated process, potentially succeeding well with a more rudimentary method of candidate identification.

The tricky part of identifying candidates would not be whether or not an expert system, or any other AI for that matter, should be used, but how strong and detailed the data model is.  The stronger the data model, the simpler the system would probably end up being, since you are only interested in a small number of potential relationship structures and corresponding values in a particular pairing, namely physical compatibility: do they bolt or plug together; if communication is a fundamental aspect of the parts, do they have the same number of wires in each side of the plug and potentially operate in the same voltage range; when pneumatic, are they both rated for safe operation in the same relative ranges and have the same port counts, shapes, and sizes, or something to that effect.

This is where your crowd sourcing could do some of the 'expert system' work for you.  Let them tag the part aspects and interfaces that are important in determining compatibility.  Essentially allow them to make two claims on the system: 1) a particular relationship is a compatible one, or not, or perhaps maybe if you are willing to allow the users to indicate uncertainty 2) this aspect or interface contributes to determining compatibility.  By doing that, and then feeding each stream of data back into the appropriate neural network, you can probably eliminate the need for an expert system.

Lastly, finding new candidates based on all the other data you have gathered, that is some kind of inference process (or often described as recommendation system).

Title: Type of AI to tackle this problem?

Body:
I posted this on stackoverflow but want to get your recommendations as well as a user on overflow recommended I post it here.

I'm going to say from the beginning that I am not a programmer, I have a cursory knowledge of different types of AI and am just a businessman building a web app.

Anyways, the web app I am investing in to develop is for a hobby of mine. There are many part manufacturers, product manufacturers, upgrade and addon manufacturers etc. for hardware/products in this hobby's industry. Currently, I am in the process of building a crowd sourced platform for people who are knowledgeable to go in and mark up compatibility between those parts as its not always clear cut if they are for example:

Manufacturer A makes a "A" class product, and manufacturer B makes upgrade/part that generally goes with class "A" products, but is for one reason or another not compatible with Manufacturer A's particular "A" class product.

However, a good chunk (>60%-70%) of the products/parts in the database can have their compatibility inferred by their properties,

For example:

Part 1 is type "A" with "X" mm receiver and part 2 is also Type "A" with "X" mm interface and thus the two parts are compatible..

or

Part 1 is a 8mm gear, thus all bushings of 8mm from any manufacturer is compatible with part 1. Further more, all gears can only have compatibility relationships in the database with bushing and gear boxes, but there can be no meaningful compatibility between a gear and a rail, or receiver since those parts don't interface.

Now what I want is an AI to be able to learn from the decisions of the crowdsourced platform community and be able to infer compatibility for new parts/products based on their tagged attributes, what type of part they are etc.

What would be the best form of AI to tackle this? I was thinking a Expert System, but explicitly engineering all of the knowledge rules would be daunting because of the complex relations between literally tens of thousands of parts, hundreds of part types and many manufacturers.

Would a ANN (neural network) be ideal to learn from the many inputs/decisions of the crowdsource platform users?

Any help/input is much appreciated.


问:
Efficient way to sort large set of numbers
I have to sort a set of 100000 integers as a part of a programming Q. The time limit is pretty restrictive, so I have to use the most time-efficient approach possible.

My current code -

```<code>#include<cstdio>
#include<algorithm>
using namespace std;

int main() {
    int n,d[100000],i;
    for(i=0;i<n;++i) {
                     scanf("%d",&d[i]);
    }
    sort(d,d+n);
    ....
}
</code>```

Would this approach be more efiicient?

```<code>int main() {
    int n,d[100000],i;
    for(i=0;i<n;++i) {
                     scanf("%d",&d[i]);
                     sort(d,d+i+1);
    }
    ....
}
</code>```

What is the most efficient way to sort a large dataset?

Note - Not homework...

答:
For maximum efficiency you only want to do the sort once, so version 2 is definitely not the way to go.

An alternative to just storing the numbers in an array in the order they are read and then sorting, is to use a data structure that will sort itself as each number is added, such as a (red/black) binary tree or a skip list. This will require additional memory for the pointer links between items, but may be faster - only an experiment can determine that.

However, efficiency of any particular sorting algorithm can often depend greatly on the initial order of the items - e.g. already sorted / inverse sorted / random.


问:
How Visual Studio could help to avoid duplicating code?
I work within a team of developers. Everyone is making their changes without carrying too much if the same thing is already implemented in the codebase. This leads to classes constantly growing and to severe duplication.

I want to add line items to class definitions from which a developer could judge what this class has.

Would it help?

How to do it in Visual Studio?

If it wouldn't help, what would be the better alternative to encourage the developers to check if something exists before implementing it?

答:
There might be several issues which are the cause.

Potential root causes

The classes are too generic/too large.

If there is a class Utils, there are chances that it will grow over time. By laziness, everything which doesn't obviously belong to another class would be put in this one. For example, if somebody writes StringToByteArray method, why bothering to find an appropriate place for it when there is a static Utils class?

When the class becomes very large, it's nearly impossible to find if something was already implemented, so people would just add their own code to it.

The code is undocumented.

No documentation = difficulty to know what is where = put a new method wherever you want.

There are no naming conventions.

Take an example of a method which converts string to byte array. If you have a naming conventions document specifying that conversions should be named X.ToY, where X is the source type and Y - the destination type, then it's pretty obvious that I should create an extension method public static ToByteArray(this string text). Before creating it, the obvious thing to do is to check (thanks IntelliSense) whether the extension method already exists.

If there are no naming conventions, you may end up with:

this.BytesFromString("Hello")

"Hello".ToBytes()

"Hello".ConvertToArrayOfBytes()

Conversions.FromStringToByteArray("Hello")

new TypeConverter<string>("Hello").Convert<byte[]>()

and tens of other variants. How would you ever find them?

Wrong architecture choices were done originally.

No need to explain more. If the architecture is a nonsense, it's difficult to follow, which means that one can hardly guess where should be a specific method.

Copy-paste is preferred to refactoring.

When, instead of refactoring, the code is copy-pasted all over the codebase, not only the maintenance is a nightmare (and finding things is a nightmare too), but when you finally refactor the code, you may find yourself moving the slightly different code to the same class, and while two methods are intended to do the same thing, you still keep both methods if they look very different and you don't have time exploring the code inside.

Poorly written code with potential bugs is frequent in the codebase.

Take again the example of a conversion from string to byte array. A developer wants to do the conversion and finds the appropriate method in the codebase: ConvertStringToByteArray. Still, the code inside this method is badly written and it seems that it fails for some strings. Since the product must be delivered in two days, the developer doesn't want to spend time exploring the code (the code inside the method and the code of the callers). Instead, this developer implements his own method, ConvertStringToByteArrayCorrectly.

There is a lack of communication between developers or issues with the management.

Imagine that a developer finds that there is a bug in ConvertStringToByteArray. He could open a ticket or talk directly to the developer who wrote the source code, but the code is written by the lead developer who is an incompetent jerk who hates when somebody notices bugs in his code, and screams every time somebody touches his code without his permission. This lead developer is a brother of the CEO of the company.

The only way for the developer is to implement his own method.

Conclusion

In all those cases, duplication is unavoidable, and Visual Studio wouldn't help you to solve the problem. The root cause should be solved first, and there are chances that the duplication will disappear.

Examples

Here are two examples which summarize what was said above.

Example 1

You start to work in a company which needs serious changes in the processes, conventions, etc. The deadline is close and everyone is stressed. You are asked to write code where you need to convert a string to an array of bytes before streaming this array to a method. You search the codebase and find four methods which seem to do what you want. They have no documentation whatsoever and are implemented very differently.

You decide to skip the first one: List<byte> ToBytes(string s, int i), because you don't understand what is i, nor why is it creating a list. The second one looks tempting, but when you test it, it "randomly" fails. You try the third one, but it throws Exception every time, this exception being trown at the line 172 of the code, deep inside three embedded loops and four ifs, just before a goto.

Finally, the fourth one looks good, but you should specify the encoding.

From Stack Overflow, you learn that you don't need an encoding for such conversion. Interesting. You decide to refactor the last method, but there are no unit tests whatsoever and the method is called dozens of times through the codebase, so you cannot be sure that it will not break existing functionality.

You decide to ask to the lead developer whether you can refactor the method, but he shouts at you that he's too busy and that you that you shouldn't disturb him with such basic questions: his time is too important for that.

Deadline is close, so you decide to write your own method. You try to understand how things should be named in the codebase, but it seems that there is no logic whatsoever. You end up giving to the new method a name which seems the most appropriate for you.

Example 2

You start to work in a company which care about their employees and the quality of the products. You're asked to write code where you should convert string to byte array.

You're a bit lost, but you know that it's ok to ask questions to your colleagues. You ask one how should you search for existent code through the huge codebase. Your colleague kindly explains that you should read the naming conventions document, and that there is also a wiki explaining the architecture.

From the naming conventions document, it appears that conversions are done through specific factories. Not a wise choice, but the document explains that there are historical reasons for that and that it's too expensive to change the whole codebase now.

You easily discover that the conversion should be done like that:

```<code>new Conversions
    .Factory
    .Create<byte[], string>()
    .Convert("Hello")`
</code>```

You also discover that there is an existent method which does the conversion. Meanwhile, you've read the related Stack Overflow article which says that you don't need to care about encodings, while the existent method deals with them.

You ask your colleagues whether you should modify the existent code. They call the lead developer who explores the code and tells you that you can effectively improve the method.

It's an easy task. The existent code is explicit enough and correctly documented. You quickly modify it and rerun the unit tests to ensure that nothing was broken by the change. Later, QA department confirms that everything is fine.

Body:
There might be several issues which are the cause.

Potential root causes

The classes are too generic/too large.

If there is a class Utils, there are chances that it will grow over time. By laziness, everything which doesn't obviously belong to another class would be put in this one. For example, if somebody writes StringToByteArray method, why bothering to find an appropriate place for it when there is a static Utils class?

When the class becomes very large, it's nearly impossible to find if something was already implemented, so people would just add their own code to it.

The code is undocumented.

No documentation = difficulty to know what is where = put a new method wherever you want.

There are no naming conventions.

Take an example of a method which converts string to byte array. If you have a naming conventions document specifying that conversions should be named X.ToY, where X is the source type and Y - the destination type, then it's pretty obvious that I should create an extension method public static ToByteArray(this string text). Before creating it, the obvious thing to do is to check (thanks IntelliSense) whether the extension method already exists.

If there are no naming conventions, you may end up with:

this.BytesFromString("Hello")

"Hello".ToBytes()

"Hello".ConvertToArrayOfBytes()

Conversions.FromStringToByteArray("Hello")

new TypeConverter<string>("Hello").Convert<byte[]>()

and tens of other variants. How would you ever find them?

Wrong architecture choices were done originally.

No need to explain more. If the architecture is a nonsense, it's difficult to follow, which means that one can hardly guess where should be a specific method.

Copy-paste is preferred to refactoring.

When, instead of refactoring, the code is copy-pasted all over the codebase, not only the maintenance is a nightmare (and finding things is a nightmare too), but when you finally refactor the code, you may find yourself moving the slightly different code to the same class, and while two methods are intended to do the same thing, you still keep both methods if they look very different and you don't have time exploring the code inside.

Poorly written code with potential bugs is frequent in the codebase.

Take again the example of a conversion from string to byte array. A developer wants to do the conversion and finds the appropriate method in the codebase: ConvertStringToByteArray. Still, the code inside this method is badly written and it seems that it fails for some strings. Since the product must be delivered in two days, the developer doesn't want to spend time exploring the code (the code inside the method and the code of the callers). Instead, this developer implements his own method, ConvertStringToByteArrayCorrectly.

There is a lack of communication between developers or issues with the management.

Imagine that a developer finds that there is a bug in ConvertStringToByteArray. He could open a ticket or talk directly to the developer who wrote the source code, but the code is written by the lead developer who is an incompetent jerk who hates when somebody notices bugs in his code, and screams every time somebody touches his code without his permission. This lead developer is a brother of the CEO of the company.

The only way for the developer is to implement his own method.

Conclusion

In all those cases, duplication is unavoidable, and Visual Studio wouldn't help you to solve the problem. The root cause should be solved first, and there are chances that the duplication will disappear.

Examples

Here are two examples which summarize what was said above.

Example 1

You start to work in a company which needs serious changes in the processes, conventions, etc. The deadline is close and everyone is stressed. You are asked to write code where you need to convert a string to an array of bytes before streaming this array to a method. You search the codebase and find four methods which seem to do what you want. They have no documentation whatsoever and are implemented very differently.

You decide to skip the first one: List<byte> ToBytes(string s, int i), because you don't understand what is i, nor why is it creating a list. The second one looks tempting, but when you test it, it "randomly" fails. You try the third one, but it throws Exception every time, this exception being trown at the line 172 of the code, deep inside three embedded loops and four ifs, just before a goto.

Finally, the fourth one looks good, but you should specify the encoding.

From Stack Overflow, you learn that you don't need an encoding for such conversion. Interesting. You decide to refactor the last method, but there are no unit tests whatsoever and the method is called dozens of times through the codebase, so you cannot be sure that it will not break existing functionality.

You decide to ask to the lead developer whether you can refactor the method, but he shouts at you that he's too busy and that you that you shouldn't disturb him with such basic questions: his time is too important for that.

Deadline is close, so you decide to write your own method. You try to understand how things should be named in the codebase, but it seems that there is no logic whatsoever. You end up giving to the new method a name which seems the most appropriate for you.

Example 2

You start to work in a company which care about their employees and the quality of the products. You're asked to write code where you should convert string to byte array.

You're a bit lost, but you know that it's ok to ask questions to your colleagues. You ask one how should you search for existent code through the huge codebase. Your colleague kindly explains that you should read the naming conventions document, and that there is also a wiki explaining the architecture.

From the naming conventions document, it appears that conversions are done through specific factories. Not a wise choice, but the document explains that there are historical reasons for that and that it's too expensive to change the whole codebase now.

You easily discover that the conversion should be done like that:

new Conversions
    .Factory
    .Create<byte[], string>()
    .Convert("Hello")`

You also discover that there is an existent method which does the conversion. Meanwhile, you've read the related Stack Overflow article which says that you don't need to care about encodings, while the existent method deals with them.

You ask your colleagues whether you should modify the existent code. They call the lead developer who explores the code and tells you that you can effectively improve the method.

It's an easy task. The existent code is explicit enough and correctly documented. You quickly modify it and rerun the unit tests to ensure that nothing was broken by the change. Later, QA department confirms that everything is fine.


问:
What are the security implications of running untrusted code on my server?
I would like to set up an app that allows users to send their code and execute it on my server. The thought of running untrusted code makes me cringe, so I am trying to set up an exhaustive list of security threats that should be addressed.

I am assuming I should strip down certain features of the language executed, like file access or (maybe) networking. I also come across terms like sandboxing or chroot. I know what they mean, but how should I actually use them?

In short: What security threats should I address before allowing users to run their code on my machine, and how do I do it?

答:
The most important concerns include:

System resources (DoS). If you allow arbitrary code execution on your systems, then it is easy to deplete system resources on that machine, on purpose or by accident. Writing code that fills the entire hdd with garbage is easy, preventing it without severely crippling the system is much harder. The same goes for other system resources, such as CPU cycles, RAM, network bandwidth, etc.

Data breaches. If other users are on the same server, and an attacker manages to read their data, you have a problem. If that data is confidential, you have an elephant-sized problem.

Network integrity. Allowing arbitrary code execution means users can initiate and accept network connections from your server, and depending on your network configuration, this may allow them to access things inside your network that aren't supposed to be reachable from the outside.

Illegal activity. A server that allows arbitrary code is an invitation for shady things: your machine could be used to store offending data, hide communication, or, more likely, perform attacks on other targets.

IMO, the easiest way to defend against these and mitigate the risks is by using virtual machines: give each user a dedicated VM with a stripped-down OS and no root access; lock down network access (ideally, the machine accepts incoming ssh connections and nothing else, and cannot initiate any outgoing connections - if you have to allow anything else, keep it as restrictive as possible), limit host resource usage, and regularly restore the machine to a blank state. Additionally, you may want to monitor VM activity from the outside.


问:
How do you use blank lines in your code?
There has been a few remarks about white space already in discussion about curly braces placements.

I myself tend to sprinkle my code with blank lines in an attempt to segregate things that go together in "logical" groups and hopefully make it easier for the next person to come by to read the code I just produced.

In fact, I would say I structure my code like I write: I make paragraphs, no longer than a few lines (definitely shorter than 10), and try to make each paragraph self-contained.

For example:

in a class, I will group methods that go together, while separating them by a blank line from the next group.

if I need to write a comment I'll usually put a blank line before the comment

in a method, I make one paragraph per step of the process

All in all, I rarely have more than 4/5 lines clustered together, meaning a very sparse code.

I don't consider all this white space a waste because I actually use it to structure the code (as I use the indentation in fact), and therefore I feel it worth the screen estate it takes.

For example:

```<code>for (int i = 0; i < 10; ++i)
{
    if (i % 3 == 0) continue;

    array[i] += 2;
}
</code>```

I consider than the two statements have clear distinct purposes and thus deserve to be separated to make it obvious.

So, how do you actually use (or not) blank lines in code ?

答:
I do but I make sure I document it by putting

(This line intentionally left blank.)

on the line

ContentLicense: CC BY-SA 2.5


问:
Is modern C++ replacing C#? Is Microsoft pushing developers to adopt C++?
I hear about modern C++ popularity and some talks about migrating back to C++ from C# or other C-like languages.

I know about C++11 features but I would like to hear your experiences, especially from developers who migrated from C# to C++.

More importantly, does Microsoft push developers to use C++? If yes, why?

答:
DXM wrote:

So the focus (at least in Microsoft's eyes) is back on C++ because now we care about battery life. Higher level code = more instructions = more juice required.

According to this words choosing Java as primary language/framework for Google's Android was a mistake. It was not. Higher level language usually means getting things done faster and I think this is the most important thing to Microsoft and Google. The more and better applications are created for the platform, the higher is profit of the OS producer.

On the other hand there is plenty of software for Windows still written in C++ so pushing those developers to switch to C#/JavaScript/anything else would be insane. Microsoft focus on giving a possibility to develop Win8 apps to as many developers as it is possible that is why in my opinion they decided to support C++ and JavaScript in Win8 development stack.


问:
Advice for Setting up an On-Call Team
I'm leading a largish development team (~35 developers). We are doing primarily Web Development work on a number of sites.

Historically the knowledge on the teams has been pretty siloed. If you worked on Site A you will know how to troubleshoot it, but you would not be a lot of help on Site B.

We also have a few cross-cutting concerns, i.e. common components used between sites which require specialized knowledge to troubleshoot.

With all this in mind, I'm trying to understand the best way to setup an on-call team.

This would be a team of programmers who would be available to deal with out-of-hours emergency issues occasionally (say one call every 2 weeks). They may be required to deploy emergency fixes.

Part of me is saying we can't have a big on-call team with shallow knowledge, instead we need a smaller team with deep knowledge who can expect to be on-call more often and remunerated as such.

Does anyone have any suggestions based on experience on how to setup this team?

Thanks in advance.

答:
Where I work, the management first asked for volunteers, and then divided the on-call times based on the amount of available people. In practice, there's three on-call periods for each person during a two month period. They run in a weekly schedule of:

Person 1: Monday 08:00 until Friday 08:00 (64 hours of on-call)

Person 2: Friday 16:00 until Monday 08:00 (64 hours of on-call)

During office hours (08:00 - 16:00) there is no on-call, of course, as calls will go directly to the on-duty phone.

During cases where the on-call person is unable to solve the issue, he can call the technical lead and the overtime hours will start running for the Technical Lead, and the on-call person continues his on-call, though usually working together with the Technical Lead until the issue is fixed.

Update:
Oh and the on-call person only handles issues related to his area of the system. If the issue goes beyond that, there is a different on-call person in another team. For example the Unix team has a separate on-call person, and the Database team has one, etc.

Title: Advice for Setting up an On-Call Team


问:
Is it important to know C/C++ for Android development?
Is it possible to use only Java (without C++ /NDK) for building good, fast, beautiful Android apps (including 3D development)?

When I look for Android developer position requirements (vacancies), I see that knowledge of C/C++/NDK is very important. Some companies even require to build their test tasks using only C++ (OpenGL).

答: It depends on how 'native' your apps are expected to go. It seems that for now, many apps need to be native in order to give the full Ux/UI that end users demand.  Will the HTML5 & Java based API abstraction become good enough to not need this going forwards?  Who knows :-)</p>


问:
Why it is necessary to to test my iPhone app on actual iPhone device
I developed one application for iPhone and now I want it on App Store. So many my iOS geek friends told me to test it on actual device i.e. on iPhone.

So I wonder that why it is necessary to to test my iPhone app on actual iPhone device though they (Apple) have given "simulator" which is near about same as my device?

答:
There are some features like PushNotification, using the camera, etc. which we can only test on a device; these are features that can't be tested on a simulator.

And testing your app on an actual device before submission to the App Store reduces the chances of app rejection; sometimes an app works fine in the simulator but it crashes on an actual device, which is the main reason for app rejections.


问:
high level design of a browser layout engine?
I'm interested in how browser layout engines like gecko, webkit and trident are architected from a high level. what are the key abstractions? how are they layered? what are the inputs/outputs for the different abstractions? Is there a diagram or article that explains this particularly well?

I am sure the implementations vary, but I'm generally curious about how all the pieces fit together. I realize webkit is open source and I can just look at the code, but I wouldn't know where to start.

答:
The following links may also be useful:

How Browsers Work: Layout - Gecko and WebKit

Gecko Overview: Layout - a bit more difficult to follow


答:
In most cases you do not need c/c++ to develop for android.

According to Android NDK Overview

II. Android NDK Non-Goals:

The NDK is not a good way to write generic native code that runs on Android devices. In particular, your applications should still be written in the Java programming language, handle Android system events appropriately to avoid the "Application Not Responding" dialog or deal with the Android application life-cycle.

however c/c++ is important if you want to use existing c/c++ libraries.

Example: Android has no build-in mp3 encoder but you can use opensource lame library.

The same might apply to 3d-imageprocessing

Title: Is it important to know C/C++ for Android development?

Body:
Is it possible to use only Java (without C++ /NDK) for building good, fast, beautiful Android apps (including 3D development)?

When I look for Android developer position requirements (vacancies), I see that knowledge of C/C++/NDK is very important. Some companies even require to build their test tasks using only C++ (OpenGL).


问:
What's a good scheme for multi-user database synchronization?
I'm working on a system to allow multiple users to collaborate on an online project.  Everything is fairly straightforward, except for keeping the users in sync.  Each user has their own local copy of the project database, which allows them to make changes and test things out, and then send the updates to the central server.  But this runs into the classic synchronization question: how do you keep two users from editing the same thing and stomping each other's work?

I've got an idea that should work, but I wonder if there's a simpler way to do it.  Here's the basic concept:

All project data is stored in a relational database.

Each row in the database has an owner.  If the current user is not the owner, he can read but not write that row. (This is enforced client-side.)

The user can send a request to the server to take ownership of a row, which will be granted if the server's copy says that the current owner is NULL, or to release ownership when they're done with it.

It is not possible to release ownership without committing changes to the server.

It is not possible to commit changes to the server without having first downloaded all outstanding changes to the server.

When any changes are made to rows you own, a trigger marks that row as Dirty.  When you commit changes, the database is scanned for all Dirty rows in all tables, and the data is serialized into an update file, which is posted to the server, and all rows are marked Clean.  The server applies the updates on its end, and keeps the file around.  When other users download changes, the server sends them the update files that they haven't already received.

So, essentially this is a reinvention of version control on a relational database. (Sort of.)  As long as taking ownership and applying updates to the server are guaranteed atomic changes, and the server verifies that some smart-aleck user didn't edit their local database so they could send an update for a row they don't have ownership of, it should be guaranteed to be correct, and with no need to worry about merges and merge conflicts.  (I think.)

Can anyone think of any problems with this scheme, or ways to do it better?  (And no, "build [insert VCS here] into your project" is not what I'm looking for. I've thought of that already.  VCSs work well with text, and not so well with other file formats, such as relational databases.)

答:
We created a very similar application several years ago and used pretty much the same approach.

The one thing that came back to bite us was that we ended up with a lot of records assigned to a user that essentially were abandoned.  Users requested ownership and then never made any changes and never released the ownership.  That lead to records in the DB that could not be assigned to other users.

Users don't always do what we expect and in this case we did not anticipate that a user would start a unit of work and then just stop.  We had to implement a process to reset the ownership to null after X time had elapsed.  That may not have been the greatest solution but it happened to fall within the desires of the business owner.


答: Another reason why the CLI might be preferable is a matter of workflow. Many frameworks are managed through the command line. Using git through the CLI let me stay focused on my project and in that project directory. For instance I might run a test and then decide to commit the new changes all from the same interface and location.</p>


问:
Is it okay to define a [] method in ruby's NilClass?
Ruby by default does not include the method [] for NilClass

For example, to check if foo["bar"] exists when foo may be nil, I have to do:

```<code>foo = something_that_may_or_may_not_return_nil
if foo && foo["bar"]
  # do something with foo["bar"] here
end
</code>```

If I define this method:

```<code>class NilClass
  def [](arg)
    nil
  end
end
</code>```

Something like that would make this possible, even if foo is nil:

```<code>if foo["bar"]
  # do something with foo["bar"]
end
</code>```

Or even:

```<code>if foo["bar"]["baz"]
  # do something with foo["bar"]["baz"] here
end
</code>```

Question:
Is this a good idea or is there some reason ruby doesn't include this functionality by default?

EDIT July 2017: My core complaint was the unwieldy foo && foo["bar"] && foo ["bar"]["baz"] idiom required to access nested values when at any point the value may be nil. As of Ruby 2.3, Array#dig and Hash#dig exist, which addresses my concern. Now I can use the following idiom!

```<code>if foo && foo.dig("bar", "baz")
  # do something
end

# Note that errors will still occur if a value isn't what you expect. e.g.
foo = { "a" => { "b" => "c" } }
foo && foo.dig("a", "b", "c") # raises TypeError: String does not have #dig method
</code>```

答:
If this is for a specific condition, and I suspect it is, then delegate the behavior.  Check that the object is defined, and then check if it is nil, and work accordingly.

It will preserve the expected behavior in core, and give you the specific changed behavior when you want it.

If later you need to modify the behavior to include False, you have one place to go to account for the needed change.

Changing core behavior for a specific need should always be considered carefully.


问:
Why learn git when there are GUI apps for GitHub?
Given that GitHub provides GUI apps for both Mac and Windows, what are the benefits of learning to use git from the command line?

Currently I'm using their mac app to update my repositories, and so far it seems to cover my needs. What might I be missing out on?

答:
Knowing the CLI comes in handy for when (not if) you're in some environment where you can't get at a GUI app.

One potential scenario:  You're asked to help out for just a couple days on a project in a closed location where it's annoyingly hard and long to get new tools into the system.  They only use CLI.  Your productivity just took a hit because you need to learn everything all over again.


答:
There are many applications in Java. Development in Java is faster and the devices are so powerful these days that efficiency does not matter when the application is mainly cool user interface for some data pulled off the net. Which is majority of applications out there. So you can certainly get a job in Android application development even without C++ knowledge.

There are however several very good reasons to choose C++ for more complex applications:

To this day C++ is still the only language portable to all platforms. Some mobile platforms have Java, some have CLI/CLR (.NET), but neither is available on all of them. Writing portable application in C++ is a lot of work, but is doable and proven by many examples.

Java has memory inefficiency built into the language. If you look at various comparisons, similar task usually takes 3-10 times more memory in Java than in C++. So if you are doing something that needs lot of data in memory, Java would not be good choice (note that situation is much better with CLI/CLR).

Dalvik, the JVM on Android, is quite a bit behind the best of breed JVMs like HotSpot. So if you are doing something that really needs raw computing power, Java is not a good choice on Android. There are however very few applications that actually need that much power. Most applications just sit there and twiddle their thumbs 99% of time waiting for user to click something and for that kind of applications Java is fine (for most of them even Python would be fine).

I think the first reason is by far the most important.


答:
I recently have to really dig into Git to be able to help with an SVN-to-Git migration. And the thing I learned is that the Git command line tools are not the complicated part to learn.

The concepts and ideas behind Git are the complex part (and that's not because they are badly designed, but simply because they are foreign to most people who come from some other, centralized VCS).

Once I've grasped the concepts, the actual command line statements became relatively easy. That means that a UI doesn't really help understand Git (except for the simplest operations).


问:
What is Declarative UI?
I keep seeing this term being thrown around in blogs about frameworks. While I understand the difference between declarative and imperative programming, how does this apply specifically to UI? Why does there appear to be a special term for it? Are these different 'things'? If so, what is the alternative to Declarative UI and why would I want to use it?</p>

答:
"Declarative UI" means you describe in some kind of language what elements you need in your UI, and to some degree how they should look, but you can leave out details like the exact position and visual style of the elements. For example, in HTML you can describe that you want an input field, but how and where this field will be placed in the UI is highly dependent on the browser you are using.

Today, the term is more often used for UI frameworks with a strict separation of the look of the UI from the behavior, which means the code reacting to UI events. For example, using XAML, you declare the look of your UI in a specific XML dialect, but you implement the behavior in separate program code.

Title: What is Declarative UI?


答: Declarative UI is a UI that's designed in a declarative way (you describe what it should be like) rather than an imperative way (you code the steps to create it.)  It's really nothing special or unusual; it's been around since at least the 1990s, when you had Visual Basic and Delphi with visual form designers that let you lay out the user interface of your program in an intuitive, WYSIWYG manner.</p>

Title: What is Declarative UI?

Body: I keep seeing this term being thrown around in blogs about frameworks. While I understand the difference between declarative and imperative programming, how does this apply specifically to UI? Why does there appear to be a special term for it? Are these different 'things'? If so, what is the alternative to Declarative UI and why would I want to use it?</p>


答: One reason to learn command-line git is that most documentation is written for that environment. Also, if you ask a question: "how do I do X with git?", chances are the answer will contain command-line commands. </p>


问:
When modeling a virtual circuit board, what is the best design pattern to check for cycles?
To make it simple assume you have only AND and OR gates. Each has two inputs and one output. The output of two inputs can be used as an input for the next gate For example:

A AND B -> E

C AND D -> F

E OR F -> G

Assuming an arbitrary number of gates, we want to check if the circuit ever connects back into itself at an earlier state? For example:

E AND F -> A

This should be illegal since it creates an endless cycle. What design pattern would best be able to check for these cycles?

答:
Looks like you are talking about building a directed graph and checking for cycles. This can be done in many ways. The most basic is a topological sort.

https://stackoverflow.com/questions/583876/how-do-i-check-if-a-directed-graph-is-acyclic

 or

https://stackoverflow.com/questions/261573/best-algorithm-for-detecting-cycles-in-a-directed-graph


问:
Can Scala be considered a functional superset of Java?
Apart from the differences in syntax, can Scala be considered a superset of Java that adds the functional paradigm to the object-oriented paradigm?

Or are there any major features in Java for which there is no direct Scala equivalent?
With major features I mean program constructs that would force me to heavily rewrite / restructure my code, e.g., if I had to port a Java program to Scala. Or can I expect that, given a Java program, I can port it to Scala almost line-by-line?

答:
I think it's not too much of an over-simplification to say, "Yes."  Look at lambdas in Java 8 - they work almost exactly like they work in Scala now, but retrofitted to be backward-compatible with the way Java works now.

All the collections and most of the APIs in Scala are immutable by default which is a nice plus.  I wish they would port that back to Java.  The Java APIs are very inconsistent in regard to immutability.  Make sure to check out Robert Harvey's link in the comments under the original question - it offers a much more detailed and nuanced answer to this question.


问:
Manager/Container class vs static class methods
Suppose I have a Widget class that is part of a framework used independently by many applications. I create Widget instances in many situations and their lifetimes vary. In addition to Widget's instance specified methods, I would like to be able to perform the follow class wide operations:

Find a single Widget instance based on a unique id

Iterate over the list of all Widgets

Remove a widget from the set of all widgets

In order support these operations, I have been considering two approaches:

Container class - Create some container or manager class, WidgetContainer, which holds a list of all Widget instances, support iteration and provides methods for Widget addition, removal and lookup. For example in C#:

```
public class WidgetContainer : IEnumerable&ltWidget>
{
  public void AddWidget(Widget);
  public Widget GetWidget(WidgetId id);
  public void RemoveWidget(WidgetId id);
}
```

Static class methods - Add static class methods to Widget. For example:

```
public class Widget
{
  public Widget(WidgetId id);

  public static Widget GetWidget(WidgetId id);
  public static void RemoveWidget(WidgetId id);
  public static IEnumerable&ltWidget> AllWidgets();
}
```

Using a container class has the added problem of how to access the container class. Make it a singleton?..yuck! Create some World object that provides access to all such container classes?

I have seen many frameworks that use the container class approach, so what is the general consensus?

答:
There is absolutely no difference between having a Singleton object and using static methods on the Widget class. Widget.GetWidget and WidgetContainer.Instance.GetWidget carry exactly the same problems.

Where and in what form are your widgets when the application isn't running? That will help solve your problem.

If they're in a database or on the filesystem then you don't need a single-instance object to access them, for example. Any number of WidgetContainer objects can get them from the file-system or database, independently. You can implement a caching system if performance is your concern.


问:
What makes a project big?
Just out of curiosity what's the difference between a small, medium and large size project? Is it measured by lines of code or complexity or what?

Im building a bartering system and so far have about 1000 lines of code for login/registration. Even though there's lots of LOC i wouldnt consider it a big project because its not that complex though this is my first project so im not sure. How is it measured?

答:
Compexity & Scope

Complexity and Scope I believe are what determines how big a project really is. However, there are several intangibles that can effect the size of a project as well.

Requirements

The biggest downfall I faced was lack of requirements. In my particular situation the sales manager was determining requirements. His focus was on the sale... gotta get the sale. In his mind what the customer was asking for didn't seem all that complicated because we had built something similar. Vague requirements lead to underpriced jobs and over committed expectations.

Lack of a CCMU

CCMU is what I call a "Coo Ca Moo" (Clear Complete Mutual Understanding). You need to have a CCMU with your customer.

If you have a small project with a poor CCMU then you can wind up doing the project 2,3,4 or more times. Thus a simple 20 hour job turns into a 60 hour project with a stressed out staff and a very dissatisfied customer.

Scope Creep

This happens more often than you think. The customer decides that since you are already doing A, B & C it shouldn't be that difficult to add D or even F. If this behavior is not checked it can also turn a small project into a medium size project. And depending on how the sales manager sold the job these scope creep expectations may seem "FREE" to the customer.

Title: What makes a project big?


答: There can be real performance differences between the actual device and the emulator. We found that only testing with the emulator resulted in a very slow app in many cases, which we didn't expect.</p>

Title: Why it is necessary to to test my iPhone app on actual iPhone device

Body:
I developed one application for iPhone and now I want it on App Store. So many my iOS geek friends told me to test it on actual device i.e. on iPhone.

So I wonder that why it is necessary to to test my iPhone app on actual iPhone device though they (Apple) have given "simulator" which is near about same as my device?


答:
This seems to be a good candidate for using an IoC (Inversion of Control) container. Instead of having to create the container yourself, you just rely on a generic container part of an IoC library which you can call upon.

For example you would define an interface:

```<code>public interface IWidgetHandler
{
   void AddWidget(IWidget widget);
   IWidget GetWidget(int widgetId);
   void RemoveWidget(int widgetId);
   IEnumerable<Widget> GetAllWidgets();
}
</code>```

Then you define a class that implements that interface.

```<code>public class WidgetHandler : IWidgetHandler
{
    public void AddWidget(IWidget widget)
    {
        throw new NotImplementedException();
    }

    public IWidget GetWidget(int widgetId)
    {
        throw new NotImplementedException();
    }

    public void RemoveWidget(int widgetId)
    {
        throw new NotImplementedException();
    }

    public IEnumerable<Widget> GetAllWidgets()
    {
        throw new NotImplementedException();
    }
}
</code>```

You would register how you should find instances of WidgetHandlers with an IoC container.

Generally, an IoC container has some sort of registration method so you can call

```<code>MyIoCContainer.Instance.Register<IWidgetHandler, WidgetHandler>();
</code>```

Now whenever you need a widget handler you just tell IoC to give you an instance of one.

```<code>IWidgetHandler widgetHandler = MyIoCContainer.Instance.Resolve<IWidgetHandler>();
</code>```

The IoC container can also control the lifetime of your objects.

Have a look at the ninject documentation if you want further details on getting up to speed with IoC. There are also a few more options out there (unity, autofac, Castle just to name a few). In fact there is a CommonServiceLocator library that provides a common interface for all, with the lowest common denominator of useful functionality (should you want to swap between them)

It allows your code to be more testable when compared to static methods classes since these can be mocked when a piece of code depends on an IWidgetHandler.
Instead of serving up a real widget handler, IoC (or the test framework) can serve up an instance of a FakeWidgetHandler which can be used to test the code that depends on this module by serving up various fake responses to the code and asserting that method parameters are passed correctly down to the IWidgetHandler dependency.

Good luck!

Title: Manager/Container class vs static class methods

Body:
Suppose I have a Widget class that is part of a framework used independently by many applications. I create Widget instances in many situations and their lifetimes vary. In addition to Widget's instance specified methods, I would like to be able to perform the follow class wide operations:

Find a single Widget instance based on a unique id

Iterate over the list of all Widgets

Remove a widget from the set of all widgets

In order support these operations, I have been considering two approaches:

Container class - Create some container or manager class, WidgetContainer, which holds a list of all Widget instances, support iteration and provides methods for Widget addition, removal and lookup. For example in C#:

```
public class WidgetContainer : IEnumerable&ltWidget>
{
  public void AddWidget(Widget);
  public Widget GetWidget(WidgetId id);
  public void RemoveWidget(WidgetId id);
}
```

Static class methods - Add static class methods to Widget. For example:

```
public class Widget
{
  public Widget(WidgetId id);

  public static Widget GetWidget(WidgetId id);
  public static void RemoveWidget(WidgetId id);
  public static IEnumerable&ltWidget> AllWidgets();
}
```

Using a container class has the added problem of how to access the container class. Make it a singleton?..yuck! Create some World object that provides access to all such container classes?

I have seen many frameworks that use the container class approach, so what is the general consensus?

Body:
This seems to be a good candidate for using an IoC (Inversion of Control) container. Instead of having to create the container yourself, you just rely on a generic container part of an IoC library which you can call upon.

For example you would define an interface:

public interface IWidgetHandler
{
   void AddWidget(IWidget widget);
   IWidget GetWidget(int widgetId);
   void RemoveWidget(int widgetId);
   IEnumerable<Widget> GetAllWidgets();
}

Then you define a class that implements that interface.

public class WidgetHandler : IWidgetHandler
{
    public void AddWidget(IWidget widget)
    {
        throw new NotImplementedException();
    }

    public IWidget GetWidget(int widgetId)
    {
        throw new NotImplementedException();
    }

    public void RemoveWidget(int widgetId)
    {
        throw new NotImplementedException();
    }

    public IEnumerable<Widget> GetAllWidgets()
    {
        throw new NotImplementedException();
    }
}

You would register how you should find instances of WidgetHandlers with an IoC container.

Generally, an IoC container has some sort of registration method so you can call

MyIoCContainer.Instance.Register<IWidgetHandler, WidgetHandler>();

Now whenever you need a widget handler you just tell IoC to give you an instance of one.

IWidgetHandler widgetHandler = MyIoCContainer.Instance.Resolve<IWidgetHandler>();

The IoC container can also control the lifetime of your objects.

Have a look at the ninject documentation if you want further details on getting up to speed with IoC. There are also a few more options out there (unity, autofac, Castle just to name a few). In fact there is a CommonServiceLocator library that provides a common interface for all, with the lowest common denominator of useful functionality (should you want to swap between them)

It allows your code to be more testable when compared to static methods classes since these can be mocked when a piece of code depends on an IWidgetHandler.
Instead of serving up a real widget handler, IoC (or the test framework) can serve up an instance of a FakeWidgetHandler which can be used to test the code that depends on this module by serving up various fake responses to the code and asserting that method parameters are passed correctly down to the IWidgetHandler dependency.

Good luck!


答:
GUI applications rely on manual interactions to perform complex behaviors. This is great for setting up projects and developing new things.

The benefits of a Command-Line Interface (CLI) come from the ability to create predetermined scripts that can be automated. All GitHub's GUI is, is some nice graphics and fancy buttons that call the git CLI.

What the GUI app won't do for you is automatically update a repo's trunk on a server daily at 1:30 AM, but a cron job that calls the git CLI is a really easy way to set that up.

Additionally, when working on a project in a team, it's convenient to set up install scripts, build scripts, deploy scripts, and the like so that teammates can focus on solving problems instead of tedious repetitious tasks.


答:
The modern consensus is that you should not do this at all.

Having a 'all instances of this class' design has proven to be troublesome in many aspects, the foremost being with regards to concurrency. Do you want all widgets, or all widgets owned by your thread? Do you really want to make that all widget list threadsafe? Remember that unit tests are almost always done in parallel, so "my app is single threaded" might not be good enough.

The other problem you run into is in your design. With the 'one and only' list of anything, be it global, static or singleton you'll quickly run into issues when you need more than one. You'll run into issues with temporary widgets or offscreen widgets if they're automatically added to the list. You'll run into errors where you forgot to add them to the list if they're not automatically handled.

Once you don't have the 'all instances of a class' requirement, then you end up with a plain old collection. Whatever consuming code is working with the widgets (even if that's some framework that is in turn consumed) can orchestrate how the collection is used and how/when the widgets get put in there. The widgets themselves should not care.


问:
Java performance of StringBuilder append chains
In Java, if I am building a significant number of strings, is there any difference in performance in the following two examples?

```<code>StringBuilder sb = new StringBuilder();

for (int i = 0; i < largeNumber; i++) {
    sb.append(var[i]);
    sb.append('=');
    sb.append(value[i]);
    sb.append(',');
}
</code>```

or

```<code>StringBuilder sb = new StringBuilder();

for (int i = 0; i < largeNumber; i++) {
    sb.append(var[i]).append('=').append(value[i]).append(',');
}
</code>```

Thanks!

答:
There is no difference in performance.

That said, first option is better because second one is what code stylists call a train wreck.

Read this article on train wrecks


答:
There is no performance difference between the two styles.

StringBuilder returns itself from all append operations making this easy (for some) to make it clear that you are still working on the same object.

The first style is more traditional and preferred by some groups as a code style.

The second style is known as method chaining.  This is a style that is preferred by groups who prefer a fluent interface.  Also give Martin Fowler's article on the fluent interface a read.

Key thing to read there is the word "preferred" and "style".  Which one you use is up to you and your group.

Title: Java performance of StringBuilder append chains

Body:
In Java, if I am building a significant number of strings, is there any difference in performance in the following two examples?

```<code>StringBuilder sb = new StringBuilder();

for (int i = 0; i < largeNumber; i++) {
    sb.append(var[i]);
    sb.append('=');
    sb.append(value[i]);
    sb.append(',');
}
</code>```

or

```<code>StringBuilder sb = new StringBuilder();

for (int i = 0; i < largeNumber; i++) {
    sb.append(var[i]).append('=').append(value[i]).append(',');
}
</code>```

Thanks!


问:
Functional Methods on Collections
I'm learning Scala and am a little bewildered by all the methods (higher-order functions) available on the collections.  Which ones produce more results than the original collection, which ones produce less, and which are most appropriate for a given problem?  Though I'm studying Scala, I think this would pertain to most modern functional languages (Clojure, Haskell) and also to Java 8 which introduces these methods on Java collections.

Specifically, right now I'm wondering about map with filter vs. fold/reduce.  I was delighted that using foldRight() can yield the same result as a map(...).filter(...) with only one traversal of the underlying collection.  But a friend pointed out that foldRight() may force sequential processing while map() is friendlier to being processed by multiple processors in parallel.  Maybe this is why mapReduce() is so popular?

More generally, I'm still sometimes surprised when I chain several of these methods together to get back a List(List()) or to pass a List(List()) and get back just a List().  For instance, when would I use:

```<code>collection.map(a => a.map(b => ...))
</code>```

vs.

```<code>collection.map(a => ...).map(b => ...)
</code>```

The for/yield command does nothing to help this confusion.  Am I asking about the difference between a "fold" and "unfold" operation?

Am I trying to jam too many questions into one?  I think there may be an underlying concept that, if I understood it, might answer all these questions, or at least tie the answers together.

答:
Fold is more general than map, reduce, and filter.  If you take a minute to think about it, their implementation in terms of a fold should be simple.  Consider using them first because it conveys more intention and limits what could happen.  A map will always produce a list of the same length, filter won't change values just possibly remove some, reduce turns a list in to a single value, with a fold all three could happen at the same time.

If you go from a List to a List of Lists, then a map(or a fold doing map like things) is returning a list somewhere. List of Lists to a List means a reduce is coming in to play somewhere.

I would also look on stack overflow at the discussions concerning them. It should help with use cases for each.

Title: Functional Methods on Collections


答:
You can roughly emulate map/filter by using foldRight (or foldLeft) with cons as the given reduction function. For example foldRight(f, L, initial) where L = [x,y,z] might be expanded to

f(x, f(y, f(z, initial)))

This means that you can't process x until you've processed f(z, initial) and then f(y, ...). You're creating a dependency that doesn't exist with map/filter.

As for map ordering...

```<code>(A) collection.map(a => a.map(b => ...))
</code>```

(A) takes a collection and then applies the map function to each element, this implies that each element is a "mappable" collection. This inner map will then return the processed list (which is a list) and so each element of collection will remain a collection. This is how you would map a function onto each element of a list of lists, and the result would again be a list of lists.

```<code>(B) collection.map(a => ...).map(b => ...)
</code>```

(B) processes each element of a list and forms those results into a new list. This list is then processed again with a second map function giving yet another list.

(A) is for processing the inner elements of a list ("sub-elements" if you like). (B) is for processing a list multiple times. If we write (B) concretely as

```<code>collection.map(a => f(a)).map(b => g(b))
</code>```

we can see it is equivalent to

```<code>collection.map(a => g(f(a)))
</code>```

It might help you to write them out as for loops. (A) will use embedded loops where as (B) will use two sequential loops.

This is not the difference between fold and unfold. Neither (A) nor (B) is a fold as the list structure present, however deeply nested, is preserved. Fold creates a scalar from a list, while unfold (not too familiar with it) takes a scalar and produces a list according to some rule.

EDIT: @Giorgio was right to suggest flatMap. It's an interesting variation on map. Let's say we're mapping a list of Xs to a list of Ys, so we pass map a function f:X->Y. Suppose we have another calculation g that takes an X but returns multiple Ys g:X->[Y]. In this case we would use flatMap. map takes the results of f and puts them into a list. flatMap takes the results of g and concatenates them together.

Ex. Say we have a list of lists L = [[1,2,3],[4,5,6]]

```<code>L.map(a => a.map(b => b * 2))
</code>```

gives [[2,4,6],[8,10,12]]. But say we want each number doubled in one list, no sub-lists. Then we would call

```<code>L.flatMap(a => a.map(b => b * 2))
</code>```

which gives [2,4,6,8,10,12]. Note that our inner function a => a.map(b => b * 2) takes and returns a list.

Title: Functional Methods on Collections

Body:
I'm learning Scala and am a little bewildered by all the methods (higher-order functions) available on the collections.  Which ones produce more results than the original collection, which ones produce less, and which are most appropriate for a given problem?  Though I'm studying Scala, I think this would pertain to most modern functional languages (Clojure, Haskell) and also to Java 8 which introduces these methods on Java collections.

Specifically, right now I'm wondering about map with filter vs. fold/reduce.  I was delighted that using foldRight() can yield the same result as a map(...).filter(...) with only one traversal of the underlying collection.  But a friend pointed out that foldRight() may force sequential processing while map() is friendlier to being processed by multiple processors in parallel.  Maybe this is why mapReduce() is so popular?

More generally, I'm still sometimes surprised when I chain several of these methods together to get back a List(List()) or to pass a List(List()) and get back just a List().  For instance, when would I use:

```<code>collection.map(a => a.map(b => ...))
</code>```

vs.

```<code>collection.map(a => ...).map(b => ...)
</code>```

The for/yield command does nothing to help this confusion.  Am I asking about the difference between a "fold" and "unfold" operation?

Am I trying to jam too many questions into one?  I think there may be an underlying concept that, if I understood it, might answer all these questions, or at least tie the answers together.

Body:
You can roughly emulate map/filter by using foldRight (or foldLeft) with cons as the given reduction function. For example foldRight(f, L, initial) where L = [x,y,z] might be expanded to

f(x, f(y, f(z, initial)))

This means that you can't process x until you've processed f(z, initial) and then f(y, ...). You're creating a dependency that doesn't exist with map/filter.

As for map ordering...

(A) collection.map(a => a.map(b => ...))

(A) takes a collection and then applies the map function to each element, this implies that each element is a "mappable" collection. This inner map will then return the processed list (which is a list) and so each element of collection will remain a collection. This is how you would map a function onto each element of a list of lists, and the result would again be a list of lists.

(B) collection.map(a => ...).map(b => ...)

(B) processes each element of a list and forms those results into a new list. This list is then processed again with a second map function giving yet another list.

(A) is for processing the inner elements of a list ("sub-elements" if you like). (B) is for processing a list multiple times. If we write (B) concretely as

collection.map(a => f(a)).map(b => g(b))

we can see it is equivalent to

collection.map(a => g(f(a)))

It might help you to write them out as for loops. (A) will use embedded loops where as (B) will use two sequential loops.

This is not the difference between fold and unfold. Neither (A) nor (B) is a fold as the list structure present, however deeply nested, is preserved. Fold creates a scalar from a list, while unfold (not too familiar with it) takes a scalar and produces a list according to some rule.

EDIT: @Giorgio was right to suggest flatMap. It's an interesting variation on map. Let's say we're mapping a list of Xs to a list of Ys, so we pass map a function f:X->Y. Suppose we have another calculation g that takes an X but returns multiple Ys g:X->[Y]. In this case we would use flatMap. map takes the results of f and puts them into a list. flatMap takes the results of g and concatenates them together.

Ex. Say we have a list of lists L = [[1,2,3],[4,5,6]]

L.map(a => a.map(b => b * 2))

gives [[2,4,6],[8,10,12]]. But say we want each number doubled in one list, no sub-lists. Then we would call

L.flatMap(a => a.map(b => b * 2))

which gives [2,4,6,8,10,12]. Note that our inner function a => a.map(b => b * 2) takes and returns a list.


问:
Best/ most efficient way to learn a programming language as a beginner
I am a student and have obtained a one year placement at a business that develops an e-commerce system using C#, HTML, WPF, javascript, ASP and more. Although I do have a little bit of knowledge, I find myself being assigned a lot of tasks that are beyond me and even when I ask for help, the response I get is often cryptic to me. I stare at as much code as possible to just try and "throw myself into it" but I often just get lost in the code

I like to consider myself a fast learner and I am damn determined to be a good programmer.

I would just like to ask if there are some tips for me to catch up as quick as possible? I don't want to be a nuisance and sit here and ask for help 24/7. I just want to crack on!

答: Read lots of code. When there's something you don't understand, use a debugger to step through the parts you don't understand. Pair programming can also help with your mentoring. Also, write little programs to explore things you don't understand or aren't very good at yet.</p>


答:
The stare at/play with code learning model has two pre-requisites:

You need at least a basic understanding of the language and framework that you are using.

You need a general understanding of the expected behavior and functionality of the system you are investigating.

If you don't have both of those, you will find it hard to make progress.  For 1, depending on how much .Net work you did in college, you need to read some introductory .Net (C#, WPF, ASP) books and play with some examples of your own.  For 2, find a subject matter expert in the company to explain what the app/system is supposed to do.

Title: Best/ most efficient way to learn a programming language as a beginner

Body:
I am a student and have obtained a one year placement at a business that develops an e-commerce system using C#, HTML, WPF, javascript, ASP and more. Although I do have a little bit of knowledge, I find myself being assigned a lot of tasks that are beyond me and even when I ask for help, the response I get is often cryptic to me. I stare at as much code as possible to just try and "throw myself into it" but I often just get lost in the code

I like to consider myself a fast learner and I am damn determined to be a good programmer.

I would just like to ask if there are some tips for me to catch up as quick as possible? I don't want to be a nuisance and sit here and ask for help 24/7. I just want to crack on!


答:
From experience, and a take off from the best voted answer:

Your fingers instead of the mouse was the largest difference when we developed Decimation X2 for the Windows Phone 7. It was coded on an emulator, as we did not have a WP7 and it was before the WP7 was released. We could have potentially received a free WP7 before release, in case that last sentence made no sense to you, as we were invited by Microsoft to  have a launch title on their phone. It turned out that, what we wanted the user to do with their fingers was very hard on the real phone, but easy with a mouse. And it had to do with screen-edge cases. Unfortunately our game required your fingers to be at the screen-edge all the time, which some phones made hard to do due to their sunken screen as well as thick cases. We actually put out a patch to fix this. This means all our first-time users were shown a bad, and potentially unusable, version of our game. :(

Different hardware speed was the next largest difference. We had to literally guess by the inaccurate method of taking our Xbox 360 version of the game and downgrading it accordingly to half the frame-rate (60fps to 30fps) and one-third the GHz (3.0GHz to 1.0GHz), and we guessed wrong. The processors were different, of course, and we knew this. Without the hardware, we were left with lame guesswork. It was not our choice as we had no WP7, but we learned the lesson I'm sharing with you now. On some phones, during the most intensive parts of the game, it dropped frames. :( Nobody seemed to care as they assumed the slowdown was appropriate for such intense parts. So it was no big deal, but the point is: Had this been a big deal, the "app" would have been broken from our lame guesswork.

Test on real hardware. And when you code for various phone hardware, test on the lower end ones if performance is an issue.


答:
One of the main problems with using a GUI versus the command line is that you are unable to have the same control over your process, in most cases.  For instance, the GitHub application is great in terms of usability for a lot of git workflows, but could still be cumbersome for advanced git processes.

As an example, here are some things that I have not figured out how to do using the GitHub application (another thing to note is that each GUI also has a learning curve).

Rebasing commits

Push/Pull/Fetch individually (in GitHub they are grouped into a single "sync" command which might cause problems some times)

Amending commits

Finally, CLIs allow for users to use these tools when scripting.


答:
As @Blrfl pointed out, feedback in logic circuits is extremely useful.  The way to deal with it in a model is to add a time component, essentially representing the propagation delay through the gate.  For example:

```<code>A AND B -> B
</code>```

The way you deal with this is to consider B at time 0 and B at time 1 as two completely different signals, like:

```<code>A[0] AND B[0] -> B[1]
</code>```

This lets you do your calculations without entering an endless loop.  Note that in this case you only have to do one iteration to determine the steady state (what it eventually settles down to).  If A is 1, B won't change from its initial value.  If A is 0, then B will also change to 0 and stay there.

Title: When modeling a virtual circuit board, what is the best design pattern to check for cycles?

Body:
To make it simple assume you have only AND and OR gates. Each has two inputs and one output. The output of two inputs can be used as an input for the next gate For example:

A AND B -> E

C AND D -> F

E OR F -> G

Assuming an arbitrary number of gates, we want to check if the circuit ever connects back into itself at an earlier state? For example:

E AND F -> A

This should be illegal since it creates an endless cycle. What design pattern would best be able to check for these cycles?

Body:
As @Blrfl pointed out, feedback in logic circuits is extremely useful.  The way to deal with it in a model is to add a time component, essentially representing the propagation delay through the gate.  For example:

A AND B -> B

The way you deal with this is to consider B at time 0 and B at time 1 as two completely different signals, like:

A[0] AND B[0] -> B[1]

This lets you do your calculations without entering an endless loop.  Note that in this case you only have to do one iteration to determine the steady state (what it eventually settles down to).  If A is 1, B won't change from its initial value.  If A is 0, then B will also change to 0 and stay there.


问:
WCF an Entity Framework connection
I have a 100+ users on a Silverlight application that uses WCF and entity framework.

Everyone has their own database and here comes my problem.

How do I make sure that only the user gets access to his database via WCF. Do I have to send the connectionstring every time I make a call to the service, or?

答: you should have some form of authentication mechanism, so you know who the user is that's connected to your back-end web service. Then you can just look up the user id against a 'global' DB configuration to get the connection string - so user "Dave" connects, you look up in the list of DBs to see that Dave's DB is "DB_001gh443a" (or whatever it is).</p>

Title: WCF an Entity Framework connection


问:
Deprecated vs. Denigrated in JavaDoc?
In the JavaDoc for X509Certificate getSubjectDN() it states:

Denigrated, replaced by getSubjectX500Principal().

I am used to seeing Deprecated in the for methods that should not be used any longer, but not Denigrated. I found a bug report about this particular case where it was closed with comment:

This isn't a bug. "Deprecated" is meant to be used only in serious
  cases.

When we are using a method that is Deprecated, the general suggested action is to stop using the method.

So what is the suggested action when a method is marked as Denigrated?

答:
After some more digging I was able to find a blog post called Deprecation in the JDK. It basically states that things marked Deprecated are considered harmful to be used, and that there are some things that are simply discouraged.

The general policy for several feature releases is that core JDK
  components are only marked as deprecated if they are actively harmful.
  If using a class or method is just ill-advised, that is usually not
  sufficient to earn the deprecated mark.

He mentioned that there currently a way to mark an item as being discouraged to use, but that they might eventually add a way to do this.

At some point, this kind of advice might be formalized with a
  less-harmful-than-deprecated "denigration" facility based a
  combination of javadoc tags and annotations to allow programmatic
  checks be made for usage of these less harmful API elements to.

While I can not find anything else specifically about a decision to use the term Denigrated this seems pretty close. And based on this it seems the action a developer should take is the same as Deprecated, do not use the method.

Title: Deprecated vs. Denigrated in JavaDoc?


答:
Merriam-Webster definition of denigrate suggests:

1: to attack the reputation of : defame <denigrate one's opponents>

  2: to deny the importance or validity of: belittle <denigrate their achievements>

Based on what is written in another related bug, defame / belittle appears to match the intent of wording used in javadocs - Bug ID: 4959744 Denigrate X509Certificate.getSubjectDN() & co:

The methods getSubjectDN() and getIssuerDN() in X509Certificate and getIssuerDN() in X509CRL are problematic. They return an unspecified class implementing the java.security.Principal interface, which has a very loose specification.

Because no additional specification is present in the getSubjectDN() and getIssuerDN() methods, it is permissible for implementations to return an arbitrary, implementation specific class. Real world experience has shown that this is the case resulting in non-portability or unreliability of the code. For compatibility reasons, the specifications for those methods cannot be changed and they must be considered unsalvageable.

Replacement methods getSubjectX500Principal() & co that return an instance of the well-defined X500Principal class were added in JDK 1.4. The implementations of those methods have been designed to avoid all problems of this sort. However, the new methods suffer from underexposure and programmers continue to use the familiar and more intuitively named getSubjectDN() & co methods.

To change this, the old getSubjectDN() and getIssuerDN() methods should be deprecated. That will ensure that developers who use this methods receive a compile time warning....

EVALUATION

...Deprecation was considered inappropriate in this case. Instead, cautionary comments were added to the JavaDoc.

The fact that reading Bug ID 5008142 has left you confused about this "denigrated" stuff looks more like a fault of developer who dealt with it.

They should have found bug 4959744 and refer it in their evaluation, instead of vague statement "meant to be used only in serious cases". They could probably even close as duplicate, with justification like "Deprecation has been considered, evaluated and rejected in favor of denigration per Bug ID 4959744".

At the very very least they could refer Bug ID 4959744 (maybe along with 4638294) in the Related Reports field (called See Also in old bugs.sun.com iirc) of their bug tracker. That this has not been done makes one suspect that they did not search for related issues at all.

Title: Deprecated vs. Denigrated in JavaDoc?

Body:
In the JavaDoc for X509Certificate getSubjectDN() it states:

Denigrated, replaced by getSubjectX500Principal().

I am used to seeing Deprecated in the for methods that should not be used any longer, but not Denigrated. I found a bug report about this particular case where it was closed with comment:

This isn't a bug. "Deprecated" is meant to be used only in serious
  cases.

When we are using a method that is Deprecated, the general suggested action is to stop using the method.

So what is the suggested action when a method is marked as Denigrated?