问:
Do I need to understand the Internals of a programming language?
I am beginner to Python and I really like it so far.
One question that comes to my mind very often is if I need to understand and therefore learn the Internals of a programming language (as in my case Python). As you might know, Python itself is written in C.

So my question is: How deep do have to dive into a programming language to be proficient or fluent in this language. I compare this question to "natural" languages. I don't know every detail in grammar in my mother language but I am able to express myself with no problems in that language. This is when I say I am fluent in a language. Does that apply to programming languages too?

答:
I'd define "proficient" with a language as:

Understand the majority of the syntax, and sufficient knowledge to research any new features you find in other people's code.

Working knowledge of any standard libraries and/or frameworks, and the ability to find, read, and understand official documentation on anything new you need to use.

Understanding of and ability to use common idioms and naming conventions for the language.

Notice that how the language works is not on this list, but there is a great deal of "ability to learn".  Having at least a cursory understanding of the internals can be helpful, but is not necessary to be proficient.  However, knowing enough about them that you will be able to understand any references in the documentation you're reading is a very good idea.

For example: I know that both VB.NET and C# is compiled to .NET's IL (Intermediate Language), which is then compiled for the target framework.  I don't know much about IL, but I know enough to recognize it when I see it, and understand in a general sense how it handles certain things.  I consider myself proficient in C#, but not in VB.NET, even though the "internals" are the same, and my understanding of them is not deep.


问:
Publish/subscribe, observer pattern implementation question
I'm developing desktop application in java/swing.

I have a component that is registered as a subscriber to many panels and gets messages (my custom event) from them. That component is something like message tray. When there is a validation error or some kind of info message it's delivered from panel to that tray by my "publish" method.

But now I'm facing a problem.
I have window that consist my message tray and internal panel.
in this internal panel there are some components and other Panel.
And in this Panel there are panels that implements Publisher interface but
they are being created on the fly from metadata and I don't have access to them to register subscriber.

So I cannot directly register my message tray as subscriber to panels because:

I don't have access to them

they are created dynamically from metadata and can change.

Is it ok to set my subscriber object reference in the middle (between) panels, and when creating dynamically my publisher panels register that reference to them?

Is it ok with the observer pattern because now other classes have reference to the object that they don't strictly need.

Maybe this object should be injected in other way?
or maybe it is all OK and I just messed my mind today ;)

答:
There are two possibilities:

Pass the "message tray" to whatever component needs it

Make each component that can have controls implement the "tray" interface. That way, the holder of the internal panels is also a tray and it can dispatch the messages to it's parent tray (if any).

I like more #2 because it allows you to be more flexible in how the controls hierarchy looks like (aka, a control that is tray might decide that only some messages are passed to parents). Also, in this design, each child has only a reference to the parent and the parent decides what to do with the incoming messages.

ContentLicense: CC BY-SA 3.0


答:
You don't need to know anything about the internals of a programming language, in order to write programs in that language.  However, the better you understand the language, the better your programs are going to be.

Knowledge of data structures and algorithms will help you choose the data structures that are most appropriate for your particular task.  Some languages possess these data structures internally.

Understanding the "culture" of the language helps you write programs that follow "best practices," making them easier to understand, more maintainable, and better performing.

Writing a compiler for that language (or a compiler for another language in that language) can give you a deep understanding of the language, and improve your programs beyond being merely average.

Being proficient in other languages (especially those of a different paradigm) makes you a better programmer in your primary language, because you can bring those skills and tools to bear in your primary language.

As a corollary, you don't need to know anything about your computer to write programs on it.  But knowing how your computer works makes you better at writing programs for it.

Title: Do I need to understand the Internals of a programming language?

Body:
I am beginner to Python and I really like it so far.
One question that comes to my mind very often is if I need to understand and therefore learn the Internals of a programming language (as in my case Python). As you might know, Python itself is written in C.

So my question is: How deep do have to dive into a programming language to be proficient or fluent in this language. I compare this question to "natural" languages. I don't know every detail in grammar in my mother language but I am able to express myself with no problems in that language. This is when I say I am fluent in a language. Does that apply to programming languages too?


答:
I don't know every detail in grammar in my mother language but I am able to express myself with no problems in that language. This is when I say I am fluent in a language. Does that apply to programming languages too?

Simply put, yes. As long as you can express yourself (and understand others) well, then you are considered fluent in the language.

That said, simply being fluent isn't enough for some jobs. Certain sorts of authors, jobs that require exemplary public speaking skills and some academics that focus on the language need to know it "better than fluent". Likewise, some programmer specialties require knowledge of the language internals, but for most people knowing the programming language equivalent of how to ask for her number or order a cheeseburger is sufficient.


问:
When making responsive design how many versions of account for?
I am learning how to make responsive layouts for sites and web applications.  It's said we need to use media queries to find out the width(resolution) and then select the layout(wireframe) for that screen.

I would like to know how many layouts(wireframe) should I make for?

Please advice as per your experience.

For example:

960x

480x

800x

答:
You should be aware of the various resolutions and the sorts of devices people will use to view your site, and make that part of your test plan.

Unless you're in a position to have regular releases targeting the current crop of popular devices in your market (that was my job for many years!) your design is going to outlive the resolution/power status quo.  So you want to make sure that core design adapts gracefully to its conditions so that viewing it next year on a new smartphone that has twice the resolution of your desktop monitor is OK, or that if it's loaded up on a legacy tablet that struggles with javascript performance the user can still more or less get their job done.

But given a responsive design, you want to check it on devices that you have reason to believe people are going to view it on, and use your understanding of your market/userbase to prioritise bugs that turn up.  So in most cases, if you load up your site in a PC browser window and it breaks when you resize it, that's a bug and you'll have to fix it.  If it doesn't look quite right on a few different popular smartphones and tablets going back a couple of years, those are probably a bugs and you'll probably want to fix them.  If you get an opportunity to test on a Samsung A411 and it's all broken to hell, that is probably not worth fixing unless you have reason to believe a lot of people amongst your potential users will be using cheap legacy devices (but there was a time when that was 60% of my users, so I absolutely had to fix those bugs!).

The rabbit hole of device variability goes down forever, and there's no timeless answers there: it's going to depend on your market, your priorities, the time you release, and those are all things you'll have to figure out for yourself from whatever information you can get.  But in general if you think responsive at design time and specific resolutions/devices at test time you should be OK.  Just watch out for things that may not be as responsive as CSS/HTML, such as video or particularly demanding javascript.


问:
What design do I follow to convert my classic ASP pages to a Java Enterprise Web Application?
There are so many Java technologies that it is difficult for me to know where to start.  I understand JSP and Servlets.  I know what http servers to use.  Real basic stuff.  What I don't understand is what I do after that?

I don't want to create a bunch of jsp and servlets.  That's not very different than what I have.

I need to query various databases.  Some are direct hits.  Some have webservices I need to consume.  I will have to create a login system that hits active directly.

Aren't I supposed to do more to make a "big java" enterprise application?

答:
As @MichaelT pointed out, the overall architecture of an ASP.NET and J2EE application are basically the same. J2EE applications don't have to be big huge Java applications, you can whip something up in a few hours that works quite well and can be deployed.

The earlier implementations of J2EE were terrible and clunky and involved loads of XML configuration to wire up components of the application but that isn't the case any more. The canonical J2EE framework is Spring and its associated packages. With Java 1.5+ you can use annotations in lieu of configuration files and other tools and frameworks (e.g. Maven) make dependency management rather simple. I won't go into which tool/framework is better/worse here as (with all other things) they each have their place.

I found this link which provides a decent comparison of ASP.NET and J2EE and basically says they're the same. Which means you will be creating a bunch of JSPs and Servlets, that's what a Java web application is.

In terms of "what design do I follow?" my suggestion is to refactor/redesign your implementation when porting over to Java. Use things such as Spring, Hibernate, etc. if you're not already using the .NET equivalents. It isn't often you get a chance to redevelop a legacy system in a new language - so take the opportunity to improve it.


问:
What are non-programming mistakes that a programmer should avoid?
People make mistakes, even in the real life... Which should we, geeky programmers, avoid?</p>

答: Not learning as much about the business domain, users, content you are writing software for.</p>

ContentLicense: CC BY-SA 2.5


问:
What are the downfalls of MVC?
I've been using MVC/MV* since I started actually organizing my code years ago. I've been using it so long that I can't even think of any other way to structure my code and every job I've had after being an intern was MVC based.

My question is, what are the downfalls of MVC? In what cases would MVC be a bad choice for a project and what would be the (more) correct choice? When I look up MVC alternatives, nearly every result is just different types of MVC.

To narrow down the scope so this doesn't get closed, let say for web applications. I do work on the backend and front-end for different projects, so I can't say just front-end or backend.

答:
My understanding of applying MVC/MV* is following the principle of Separation of Concerns (SoC) - separating program/codes into distinct sections/pieces so that each section could address a separate concern (Ref: http://en.wikipedia.org/wiki/Separation_of_concerns)

there are a lot of benefits when separating concerns: one won't affect another and developers could work on a unit without impacting the rest, etc. & etc... MVC is not the only pattern that follows SoC, basically, OOP itself is a great concept to break things into units.

MVC/MV* are very useful when you handling UI related development, while underneath there could be more patterns - factory, singleton, facade and etc. Majority of big projects consist of multiple layers handling different aspects, but UI might not be a must for some cases. You may see MVC a lot - that's because a lot of projects have UI elements.

thus, While talking about the drawbacks of MVC, it really depends the projects you are doing - does it have UI? does it require great scalability/extensibility? does it have many interactions between UI and behind-system? for example, a simple information web page does not require MVC at all, unless you plan to extend it to a great interactive page in the future.

so in order to evaluate MVC (or more general - a design pattern), give it a context and think about complexity, scalability, testablity, maintenance, time constraint, etc. & etc.

Title: What are the downfalls of MVC?


问:
ASP.NET tags best practices
I'm working on my first ASP.NET project and I'm torn between using asp tags (<asp:SomeElement) everywhere or use some regular HTML for simple things that need no code behind, like fixed divs, static text, etc.

I think it would be best to use ASP tags only for code behind and other dynamic stuff, whereas static elements can be in vanilla HTML, but that's assuming I won't ever need to turn them into ASP.NET in the future. Is there a best practice/recommended approach for this?

答:
Microsoft first introduced server controls in an attempt to make web development seem as much like VB6 windows development as possible.  It enabled developers who had very little knowledge of HTML and the web, to build web pages by dragging controls onto a design surface.

In the early days of .NET, this (arguably) made a lot of sense, but as the web has matured, and developers in general are more knowledgeable and comfortable with rolling their own HTML, the server control model seems stale, and developments like MVC come along which align more closely with the way web devs are used to working nowadays.

That said, if you are comfortable putting the HTML directly into the page, then go for it. You have more control over the page's rendering, and as Joe stated it's much easier to troubleshoot layout issues.

Title: ASP.NET tags best practices


问:
Do we need to use JCA while connecting to db from inside EJB
While writing an EJB (deployed on WAS) that connects to a db, i have never needed to use JCA. But apparently JCA is the standard for connection to thrid party EIS (which includes database).
So does the WAS implement JCA internally? Under what situation would the app develoepr need to use JCA related classes?</p>

答:
JCA is the standard for connection to thrid party EIS (which includes
  database)

JCA  (Java Connector Architecture) is intended as a generic architecture for connecting to legacy systems. JDBC (Java Database Connectivity) is the standard for connecting to databases.

It is possible to connect to a database using JCA only if the database vendor (or a third party) has provided a JCA resource adapter which can talk to the database. This JCA adapter would be deployed on the application server and your application would talk to the database using the standard JCA interfaces.

Having said that, the more common way for database connectivity is JDBC, and that is what you should use unless there's a specific requirement to use JCA only and you have a JCA adapter for the database.


问:
What are the characteristics or features of production-quality code?
This is the first time I will be delivering code for a freelance project (web-app), and, since I don't have much experience shipping code, I am having a hard time deciding whether my program is ready for deployment or not.

My understanding is that a production-level code must have the following characteristics:

Fault tolerance: ability to survive uncaught exceptions

Data redundancy: never lose user data

Scalability: Handling extra load should not require re-writing the app

Test Coverage: a "decent" amount of code tested

Some of these characteristics are specific to the program itself, while others are more environment-related (whether using multiple clusters). However, even the environment-dependent characteristics do affect the way the program is designed.

My question then is: What are the other characteristics that make production-code so different than code not meant for production?

Just to reduce the scope of the question, please focus only on web apps.

Edit: I will try to narrow down the scope by asking for characteristics specific to my situation. As a freelancer, I was responsible of everything from purchasing a VPS, to configuring it, to writing the code, to deploying it. Although the project and its setup are well documented, the customer will not be able to maintain it. The app is not complex, but depends on a lot of external components, which makes it really prone to breaking if these components change/disappear. The goal is to set up a service that would be able to last as long as possible without the customer's intervention.

答:
"production-quality code" is whatever another user, who is not you, is...

able to use with no or minimal support.  If every action is met with a bug, your software will go into the garbage

able to understand how to use with minimal support or documentation. If your user can't understand how to use your software, it will go into the garbage.

willing to use because it adds value.  If your software adds enough value, maybe they'll even give you money for it. If it doesn't add enough value for you to give it away for free, your software will go into the garbage.

THAT IS IT.

Some people need absolute fault tolerance. Others don't mind as much if some data gets lost when there is a crash... assuming they see crashes very infrequently. There are no hard set qualities or requirements.  And no customer cares about test coverage, what they care about is the three above points. Test coverage is a tool (one of many) you can use in order to get there, but plenty of software, some of it even good, has been built with nothing but manual testing.

Whatever software you build, the requirements are between you and your customer and if you are building software for general consumption, then pick one or few target groups and don't try to be everything to everybody.  Trying to come up with some kind of generic mold seems to me rather silly.

Instead, of trying to predict or guess when your software will be production-ready, why don't you work with your customer?  Give them a preview but explain that it is not production ready. Publish it on your own server and ask them to use it, poke around and give you feedback. Continue working with them until they are happy with what you gave them.    In other words, they will tell you when it is production ready.


问:
Does having more classes necessarily increase the memory requirements of the app?
When we add .edmx files to a DLL, the physical size of the DLL increases.  DLL's are loaded into memory.  However, the .NET infrastructure with functionality such as JIT compilation and the GAC complicates things.  Is it true that having a larger DLL  automatically increase the memory requirements of an application?

In other words, are memory concerns a good reason to split generated code such as entity framework into N DLL's?

答:
Of course, the more code you have in the application, the more memory it requires to load all that code when running the application. But

In other words, are memory concerns a good reason to split generated code such as entity framework into N DLL's?

I would say no. Modern day computer should have more that enough memory to load all the executable code at once. There could be an issue with run-time memory, e.g. if you were to try to cache all the data for an enterprise application in memory. But not the executable code, IMHO.

And splitting it up into several DLLs would not help a lot. You would still require to load all the executable code in order for the application to work. Except if you would load/unload code on demand.

And trying to load/unload code on demand does add extra complexity to the project. This complexity adds cost and risk (which is more cost). E.g. you cannot simply unload a dll in .NET. You have to load it into a separate AppDomain. Then you can unload the AppDomain.

If you really was hitting the memory limit for executable code, upgrading the memory on the computers running the application would most probably be cheaper than implementing loading/unloading of code at runtime.


问:
I feel lost among the various web technologies and I'm looking for pointers
In the last 3-5 months I was thinking about which web programming language I should use. PHP? Ruby? C#? Python? Perl? And you know what? Every time I keep changing my mind like crazy! I learn some things about each one of them and then move to another.  Now I'm totally lost, totally lost guys. :)

What I want form you is to help me to decide, not to decide for me, and give me some recommendations. It would be more than helpful if you can tell me a short story about yourself, how you got started, where you are now and what web programming technologies you are using.

答:
I learnt Java at college but dropped out in my third year because I felt like it was slowing me down. So I really wanted to get into web programming and build an application, 2 of them in fact. The first application I decided to learn PHP with OOP because this was one of the popular languages and if I needed help I could easily find it and because it was my first I wanted to start on something easy enough, you know once you jump in the pool the water's cold at first but your body adjusts to it eventually and then you can swim around. This is what I believe you need to work out, first of all find out what you want to do and then pick a language. Right so for the past two months I've been busy away making my application and im fairly confident at it by now i believe though i recognize there's still a lot more to learn but that's exciting right.

Now that I have my foot in the door of web programming so to speak I can now move onto more advanced languages and for my next project im going to build it in Java/JavaServerFaces and maybe a Framework like Struts. It's probably not even more advanced than PHP i dont really know nor do i care. Im just going with my gut feeling and I think thats what you need to do too. You can sit down, figure out a project, work out the pros and cons think about it for months and months while not even considering asking yourself a very simple questions like: what do you want to do? What is your preference? Why spend so many months thinking about it, why not just do it? Is it anxiety? Is it perfectionism? Afraid of failure? I dont know, these are just questions that maybe you should ask yourself? So c'mon jump in the pool it's a lot of fun in here what are you waiting for! :P


问:
What is global mutable variable behaviour in dynamically-linked libraries?
When a dynamically linked library includes a global mutable variable, such as a container for state initialised when loading the library, how do references to that variable behave when running an application that links against it?

Obviously the application cannot alter memory allocated to the dynamically-linked library by the OS, as that would have implications on the other applications using it, so one must assume references to the global mutable variables are rewritten to refer to some R/W memory space owned by the application. But exactly how do the compiler and linker collude to accomplish this?

答:
Most operating systems support a concept called "sections" in their executable file format (possibly using a different name). These sections can be given different attributes (like, read-only, read/write, executable, etc.) and can be loaded into different parts of an application's address space. For example, the section with the code could go to the lower part of the address space, while the globals are placed in the upper part (with everything in between available for stack and heap).

With dynamically loaded libraries, the same principles can be used to have a section with code that gets shared between the different applications, and a section with variables that gets loaded separately for each application.

One additional feature that is needed to make this work is the use of virtual addresses. With virtual addresses, there is no fixed correspondence between the addresses as seen by an application and the cells of physical memory. This allows the OS to swap pages of memory in and out of the RAM, but it also provides the means to share pages of physical memory between processes (even if they don't correspond to identical virtual addresses in those processes) and to have identical virtual addresses in two processes refer to different physical locations.

Thus, most of the work in making dynamically loaded libraries work is done by the OS. The compiler and linker just have to put everything in the appropriate sections, so the unmodifiable stuff can be shared between processes, while the variables get allocated separately for each process.


问:
What are examples of comments that tell you why instead of how or what?
First of all, in this question I'd like to stay away from the polemic on whether source code commenting is good or bad. I'm just trying to understand more clearly what people mean when they talk about comments that tell you WHY, WHAT or HOW.

We often see guidelines like "Comments should tell you WHY; code itself should tell you HOW". It is easy to agree with the statement on an abstract level. However, people usually drop this like a dogma, and leave the room without further explanation. I've seen this used in so many different places and contexts, that it looks like people can agree on the catchphrase, but they seem to be talking about different things entirely.

So, back to the question: if comments should tell you WHY, what is this WHY we are talking about? Is this the reason why that piece of code exists in the first place? Is this what that piece code should be doing? I would really appreciate if someone could give a clear explanation, and then add some good examples (bad examples are not really needed, but fell free to add them for contrast).

There are many questions on whether comments are good or bad, but no one that addresses the specific question of what are good examples of comments that tell you WHY.

答:
Not all my comments are of the 'why' type, but many are.

These are examples from one (Delphi) source file:

```<code>// For easier access to the custom properties:

function GetPrivate: Integer;   // It's an integer field in the external program so let's treat it like that here

// The below properties depend on the ones above or are calculated fields.
// They are kept up-to-date in the OnEventModified event of the TTSynchronizerStorage
// or in the ClientDataSet.OnCalcFields of the TcxDBSchedulerStorage.DataSource.DataSet
property IsModified       : Boolean   read GetIsModified   write SetIsModified;
property IsCatTT          : Boolean   read GetIsCatTT      write SetIsCatTT;
property IsSynced         : Boolean   read GetIsSynced     write SetIsSynced;

lLeftPos := pos(' - [',ASubject); // Were subject and [shiftnaam:act,project,cust] concatenated with a dash?

// Things that were added behing the ] we will append to the subject:

// In the storage the custom value must also be set for:
Self.SetCustomFieldValueByname(cCustFldIsCatTT,Result);

// When we show the custom fields in a grid, the Getters are not executed,
// because the DevEx code does not know about our class helpers.
// So we have two keep both properties synchronized ourselves:

// lNewMasterEvent was set to usUpdated, overwrite because we added:
if ARepair then
  lNewMasterEvent.CustUpdateStatus := usRecreated

// The source occurrence date may have bee changed. Using GetOriginalDate we can retrieve the original date,
// then use that for creating a target occurrence (and update its date):

lNewTTOccurrence.CustSyncEntryID := cSyncEntryID0;    // Backward compatibility with old sync methode

// Single event became recurring or vice versa; replace entire event

// In contradiction to CopySingleEventToTimeTell, CopyMasterEventToTimeTell does not have a ANewStatus parameter
// because master events are always added.
</code>```

Note that (my) why comments usually precede the code that is going to do it (hence end with a colon).

I do some have comments explaining only what is happening, e.g. when a process has many steps which have a logical grouping (and the code is not refactored to show that automatically), I will comment like:

```<code>// Step 1. Initialization
</code>```

Body:
Not all my comments are of the 'why' type, but many are.

These are examples from one (Delphi) source file:

// For easier access to the custom properties:

function GetPrivate: Integer;   // It's an integer field in the external program so let's treat it like that here

// The below properties depend on the ones above or are calculated fields.
// They are kept up-to-date in the OnEventModified event of the TTSynchronizerStorage
// or in the ClientDataSet.OnCalcFields of the TcxDBSchedulerStorage.DataSource.DataSet
property IsModified       : Boolean   read GetIsModified   write SetIsModified;
property IsCatTT          : Boolean   read GetIsCatTT      write SetIsCatTT;
property IsSynced         : Boolean   read GetIsSynced     write SetIsSynced;

lLeftPos := pos(' - [',ASubject); // Were subject and [shiftnaam:act,project,cust] concatenated with a dash?

// Things that were added behing the ] we will append to the subject:

// In the storage the custom value must also be set for:
Self.SetCustomFieldValueByname(cCustFldIsCatTT,Result);

// When we show the custom fields in a grid, the Getters are not executed,
// because the DevEx code does not know about our class helpers.
// So we have two keep both properties synchronized ourselves:

// lNewMasterEvent was set to usUpdated, overwrite because we added:
if ARepair then
  lNewMasterEvent.CustUpdateStatus := usRecreated

// The source occurrence date may have bee changed. Using GetOriginalDate we can retrieve the original date,
// then use that for creating a target occurrence (and update its date):

lNewTTOccurrence.CustSyncEntryID := cSyncEntryID0;    // Backward compatibility with old sync methode

// Single event became recurring or vice versa; replace entire event

// In contradiction to CopySingleEventToTimeTell, CopyMasterEventToTimeTell does not have a ANewStatus parameter
// because master events are always added.

Note that (my) why comments usually precede the code that is going to do it (hence end with a colon).

I do some have comments explaining only what is happening, e.g. when a process has many steps which have a logical grouping (and the code is not refactored to show that automatically), I will comment like:

// Step 1. Initialization


答:
I tend to reduce comments to either references where a certain functionality/code is explained more thoroughly or to explain why a certain way of programming is chosen.

Considering that other programmers with similar skills use or read your code, it is important to comment if you use a different-than-expected way of achieving something. So you can explain in a comment why you choose this way.

For instance, if you can make use of two different sensors on an Android device and one of them does not suit your needs, you can explain in the comment why you chose the other one.

So the 'why' should give a rationale on your choices made.

Title: What are examples of comments that tell you why instead of how or what?

Body:
First of all, in this question I'd like to stay away from the polemic on whether source code commenting is good or bad. I'm just trying to understand more clearly what people mean when they talk about comments that tell you WHY, WHAT or HOW.

We often see guidelines like "Comments should tell you WHY; code itself should tell you HOW". It is easy to agree with the statement on an abstract level. However, people usually drop this like a dogma, and leave the room without further explanation. I've seen this used in so many different places and contexts, that it looks like people can agree on the catchphrase, but they seem to be talking about different things entirely.

So, back to the question: if comments should tell you WHY, what is this WHY we are talking about? Is this the reason why that piece of code exists in the first place? Is this what that piece code should be doing? I would really appreciate if someone could give a clear explanation, and then add some good examples (bad examples are not really needed, but fell free to add them for contrast).

There are many questions on whether comments are good or bad, but no one that addresses the specific question of what are good examples of comments that tell you WHY.


答:
Your design doesn't really violate the Observer pattern, because the pattern does not specify how subscribers get registered with the publisher. But you are violating the Single Responsibility Principle for those middle panels, because they are given the added responsibility of helping in getting the message tray subscribed.

A better design would be to use a second incarnation of the Observer pattern between the message tray and the component that dynamically creates those Panels. Through this subscription, the message tray can be informed that a new Panel has been created (along with a handle/reference/pointer to that Panel), so it can subscribe with that Panel for messages.

Title: Publish/subscribe, observer pattern implementation question

Body:
I'm developing desktop application in java/swing.

I have a component that is registered as a subscriber to many panels and gets messages (my custom event) from them. That component is something like message tray. When there is a validation error or some kind of info message it's delivered from panel to that tray by my "publish" method.

But now I'm facing a problem.
I have window that consist my message tray and internal panel.
in this internal panel there are some components and other Panel.
And in this Panel there are panels that implements Publisher interface but
they are being created on the fly from metadata and I don't have access to them to register subscriber.

So I cannot directly register my message tray as subscriber to panels because:

I don't have access to them

they are created dynamically from metadata and can change.

Is it ok to set my subscriber object reference in the middle (between) panels, and when creating dynamically my publisher panels register that reference to them?

Is it ok with the observer pattern because now other classes have reference to the object that they don't strictly need.

Maybe this object should be injected in other way?
or maybe it is all OK and I just messed my mind today ;)


答:
I would like to start my answer with a quote made by Jeff Atwood in his Blog post Code Tells You How, Comments Tell You Why:

the best kind of comments are the ones you don't need

He also states that:

You should first strive to make your code as simple as possible to understand without relying on comments as a crutch. Only at the point where the code cannot be made easier to understand should you begin to add comments.

I totally agree and at this point I must add that before I can start making the code as simple as possible I make the code work and then start refactoring. So during the first run before refactoring adding why comments helps a lot.

For example if using 3 nested loops with 2 dimensional hashtables to fill a table of weekdays while parsing data, it's very easy to lose track of what was done by someone or even yourself if not looked at for a few weeks and suddenly refactoring.

```<code>[loop1]6oclock -> [loop2]Monday -> [loop3]stage 1 to 4
         -> tuesday-> stage 1 to 4
         ...
         -> Saturday -> stage 1 to 4
    7oclock -> Monday-> stage 1 to 4
        ....etc.
</code>```

The upper being an example of how 3 nested loops would work before refactoring.

Also explaining some branch conditions can help understand code much better with what one was thinking in the process:

```<code>// added a zero before the actual day in order for the days always to be 2 digits long.
if( actualDayFuture < 10 )
{
     actualDayFuture = padIfSingleDigitDate(actualDayFuture);
}
</code>```

Even simple and obvious code works well with comments. Just to make things a little more obvious, clearer or easier to understand for colleagues and even for yourself in maintaining software.

Sure xp states to have code that is self explaining, but does a one line comment hurt?

I also find the following rules from this blog to be very helpful:

Understand the material before you write

Write as though your audience is a fourth grader

Think about how readers might misinterpret you

Anyone who has to get back into their own code or someone elses or even legacy code knows that it can be a headache. So instead of being lazy or trying to be an uber-coder in not commenting anything or very little, why not make your own or some poor bugger's, who has to maintain your code, future life much easier by following the rules quoted.

Also many programming descisions made are doubted during reviews and it isn't always clear why some parts were written as they were even if some sections of code are vital for a programm to work due to a major bug found as the code was used over years. So in order to not bore you all completely with a tl;dr close with a last quote from acmqueue:

Prior, clear, and extensive documentation is a key element in creating software that can survive and adapt. Documenting to high standards will decrease development time, result in better work, and improve the bottom line. It’s hard to ask for more than that from any technique.

Body:
I would like to start my answer with a quote made by Jeff Atwood in his Blog post Code Tells You How, Comments Tell You Why:

the best kind of comments are the ones you don't need

He also states that:

You should first strive to make your code as simple as possible to understand without relying on comments as a crutch. Only at the point where the code cannot be made easier to understand should you begin to add comments.

I totally agree and at this point I must add that before I can start making the code as simple as possible I make the code work and then start refactoring. So during the first run before refactoring adding why comments helps a lot.

For example if using 3 nested loops with 2 dimensional hashtables to fill a table of weekdays while parsing data, it's very easy to lose track of what was done by someone or even yourself if not looked at for a few weeks and suddenly refactoring.

[loop1]6oclock -> [loop2]Monday -> [loop3]stage 1 to 4
         -> tuesday-> stage 1 to 4
         ...
         -> Saturday -> stage 1 to 4
    7oclock -> Monday-> stage 1 to 4
        ....etc.

The upper being an example of how 3 nested loops would work before refactoring.

Also explaining some branch conditions can help understand code much better with what one was thinking in the process:

// added a zero before the actual day in order for the days always to be 2 digits long.
if( actualDayFuture < 10 )
{
     actualDayFuture = padIfSingleDigitDate(actualDayFuture);
}

Even simple and obvious code works well with comments. Just to make things a little more obvious, clearer or easier to understand for colleagues and even for yourself in maintaining software.

Sure xp states to have code that is self explaining, but does a one line comment hurt?

I also find the following rules from this blog to be very helpful:

Understand the material before you write

Write as though your audience is a fourth grader

Think about how readers might misinterpret you

Anyone who has to get back into their own code or someone elses or even legacy code knows that it can be a headache. So instead of being lazy or trying to be an uber-coder in not commenting anything or very little, why not make your own or some poor bugger's, who has to maintain your code, future life much easier by following the rules quoted.

Also many programming descisions made are doubted during reviews and it isn't always clear why some parts were written as they were even if some sections of code are vital for a programm to work due to a major bug found as the code was used over years. So in order to not bore you all completely with a tl;dr close with a last quote from acmqueue:

Prior, clear, and extensive documentation is a key element in creating software that can survive and adapt. Documenting to high standards will decrease development time, result in better work, and improve the bottom line. It’s hard to ask for more than that from any technique.


答:
Comments should tell you what the code does not, not necessarily deliniated by WHY, HOW, or WHAT. If you have good names and have well delineated functions, it is quite possible that the code can tell you exactly what is going on. For example:

```<code>List<LightMap> maps = makeLightmaps(receivingModels);
TrianglePartitioner partition = new Octree(castingTriangles);
List<Photon> photons = firePhotons(lights, partition);

if (photons.Count > 0)
{
      PhotonPartitioner photonMap = new KDTree(photons);
      gatherPhotons(maps, photonMap, partition, lights);
}
</code>```

This code really does not need comments. The function and type names make it easy to understand.

Sometimes, however, it can be difficult or impossible to really make fluent code like the above. For example, the next code snippet is for finding a statistically random point on a sphere. The math is pretty opaque, so a comment with a link to the explanation is to help tell HOW it works. This can be wrapped in a function to tell WHAT it does without needing a comment if needed more than once, otherwise the link title also helps in that department.

```<code>double randomA = localGenerator.NextDouble();
double randomB = localGenerator.NextDouble();

//http://mathworld.wolfram.com/SpherePointPicking.html
double theta = 2 * Math.PI * randomA;
double phi = Math.Acos(2 * randomB - 1);

Vector3 randomDirection = new Vector3(Settings.ambientRayLength * (float)(Math.Cos(theta) * Math.Sin(phi)),
                                      Settings.ambientRayLength * (float)(Math.Sin(theta) * Math.Sin(phi)),
                                      Settings.ambientRayLength * (float)Math.Cos(phi));
</code>```

Another example of when comments tell you what the code does not is for explaining a decision. In the next example, the code does not lock a non-thread-local variable inside a threaded piece of code. There is a reason for this and the comment explains WHY. Without the comment, it might be considered a bug, or just not be even noticed.

```<code>Random random = new Random();
Parallel.For(0, maxPhotons, delegate(int photonIndex, ParallelLoopState state)
{
    ...
    //I don't actually care if this random number is unique between threads, threadsafty is not that big of a deal
    //  in this case and locking the random object could cause a lot of lock contention
    while (random.NextDouble() > reflectProbability)
    {
        ...
    }
    ...
}
</code>```

It could, perhaps, be improved to say why the random object is not created inside the parallel loop in the first place. If there is no reason, it could also make someone come along and realize that the whole idea is stupid and is a good place for refactoring.

Body:
Comments should tell you what the code does not, not necessarily deliniated by WHY, HOW, or WHAT. If you have good names and have well delineated functions, it is quite possible that the code can tell you exactly what is going on. For example:

List<LightMap> maps = makeLightmaps(receivingModels);
TrianglePartitioner partition = new Octree(castingTriangles);
List<Photon> photons = firePhotons(lights, partition);

if (photons.Count > 0)
{
      PhotonPartitioner photonMap = new KDTree(photons);
      gatherPhotons(maps, photonMap, partition, lights);
}

This code really does not need comments. The function and type names make it easy to understand.

Sometimes, however, it can be difficult or impossible to really make fluent code like the above. For example, the next code snippet is for finding a statistically random point on a sphere. The math is pretty opaque, so a comment with a link to the explanation is to help tell HOW it works. This can be wrapped in a function to tell WHAT it does without needing a comment if needed more than once, otherwise the link title also helps in that department.

double randomA = localGenerator.NextDouble();
double randomB = localGenerator.NextDouble();

//http://mathworld.wolfram.com/SpherePointPicking.html
double theta = 2 * Math.PI * randomA;
double phi = Math.Acos(2 * randomB - 1);

Vector3 randomDirection = new Vector3(Settings.ambientRayLength * (float)(Math.Cos(theta) * Math.Sin(phi)),
                                      Settings.ambientRayLength * (float)(Math.Sin(theta) * Math.Sin(phi)),
                                      Settings.ambientRayLength * (float)Math.Cos(phi));

Another example of when comments tell you what the code does not is for explaining a decision. In the next example, the code does not lock a non-thread-local variable inside a threaded piece of code. There is a reason for this and the comment explains WHY. Without the comment, it might be considered a bug, or just not be even noticed.

Random random = new Random();
Parallel.For(0, maxPhotons, delegate(int photonIndex, ParallelLoopState state)
{
    ...
    //I don't actually care if this random number is unique between threads, threadsafty is not that big of a deal
    //  in this case and locking the random object could cause a lot of lock contention
    while (random.NextDouble() > reflectProbability)
    {
        ...
    }
    ...
}

It could, perhaps, be improved to say why the random object is not created inside the parallel loop in the first place. If there is no reason, it could also make someone come along and realize that the whole idea is stupid and is a good place for refactoring.


答:
The most common and most distinctive example is comments around various workarounds. For example this one:

https://github.com/git/git/blob/master/compat/fopen.c:

```<code>/*
 *  The order of the following two lines is important.
 *
 *  FREAD_READS_DIRECTORIES is undefined before including git-compat-util.h
 *  to avoid the redefinition of fopen within git-compat-util.h. This is
 *  necessary since fopen is a macro on some platforms which may be set
 *  based on compiler options. For example, on AIX fopen is set to fopen64
 *  when _LARGE_FILES is defined. The previous technique of merely undefining
 *  fopen after including git-compat-util.h is inadequate in this case.
 */
#undef FREAD_READS_DIRECTORIES
#include "../git-compat-util.h"
</code>```

You'll surely find more examples in Git and Linux sources; both projects try to follow this rule.

I also recommend to follow this rule even more strictly with commit logs. For code comments it may happen that you fix the code, but forget to update the comment. With the amount of code in usual project, it is guaranteed to happen sooner or later. On the other hand the commit log is tied to the particular change and can be recalled using the "annotate"/"blame" functionality of the version control system. Again Git and Linux have some good examples.

Look e.g. at this commit. (not copying here, it's too long). It has four paragraphs taking almost whole page (and a bit over screenful) describing what exactly was wrong and why it was wrong and than goes on and and modifies all of whoping SIX lines. They use comments like this for two purposes:

All submitted changes are reviewed and the commit log is what has to explain the change to the reviewer.

When a bug is found, the relevant logs are retrieved using "pickaxe" or "blame" to avoid reverting to earlier also incorrect behaviour.

(note: it took me at most 10 minutes random browsing of the git repo to come up with these two examples, so it would sure be easy to find more there)

Body:
The most common and most distinctive example is comments around various workarounds. For example this one:

https://github.com/git/git/blob/master/compat/fopen.c:

/*
 *  The order of the following two lines is important.
 *
 *  FREAD_READS_DIRECTORIES is undefined before including git-compat-util.h
 *  to avoid the redefinition of fopen within git-compat-util.h. This is
 *  necessary since fopen is a macro on some platforms which may be set
 *  based on compiler options. For example, on AIX fopen is set to fopen64
 *  when _LARGE_FILES is defined. The previous technique of merely undefining
 *  fopen after including git-compat-util.h is inadequate in this case.
 */
#undef FREAD_READS_DIRECTORIES
#include "../git-compat-util.h"

You'll surely find more examples in Git and Linux sources; both projects try to follow this rule.

I also recommend to follow this rule even more strictly with commit logs. For code comments it may happen that you fix the code, but forget to update the comment. With the amount of code in usual project, it is guaranteed to happen sooner or later. On the other hand the commit log is tied to the particular change and can be recalled using the "annotate"/"blame" functionality of the version control system. Again Git and Linux have some good examples.

Look e.g. at this commit. (not copying here, it's too long). It has four paragraphs taking almost whole page (and a bit over screenful) describing what exactly was wrong and why it was wrong and than goes on and and modifies all of whoping SIX lines. They use comments like this for two purposes:

All submitted changes are reviewed and the commit log is what has to explain the change to the reviewer.

When a bug is found, the relevant logs are retrieved using "pickaxe" or "blame" to avoid reverting to earlier also incorrect behaviour.

(note: it took me at most 10 minutes random browsing of the git repo to come up with these two examples, so it would sure be easy to find more there)


答: Well, I started web development back in 1998 which seems like forever ago in some ways.  Back then I was working for some ex-Microsoft employees and so everything we used was from Microsoft: Visual Studio, Visual Source Safe, MS-SQL Server, IIS, etc.  Thus, I got used to the Microsoft stack in a lot of ways.  Where I work now I still use some of these like IIS and Visual Studio, though other things have changed like using Subversion instead of VSS and having things like continuous integration and unit tests that I didn't have when I started.</p>

Title: I feel lost among the various web technologies and I'm looking for pointers

Body:
In the last 3-5 months I was thinking about which web programming language I should use. PHP? Ruby? C#? Python? Perl? And you know what? Every time I keep changing my mind like crazy! I learn some things about each one of them and then move to another.  Now I'm totally lost, totally lost guys. :)

What I want form you is to help me to decide, not to decide for me, and give me some recommendations. It would be more than helpful if you can tell me a short story about yourself, how you got started, where you are now and what web programming technologies you are using.


答:
I understand the WHY as being the reason why you do something in a possibly strange or perhaps illogical way, due to the given circumstances requiring it to be done so. The HOW can be seen in the code itself, no matter how odd it is, even if the code makes no "sense". The WHAT is probably best told in the beginning of the class/function documentation. So that leaves you with adding the WHY, where you explain anything not included in the HOW and WHAT, and the peculiar ways you need to take due to reasons beyond your control.

Of course it's not always the case, outside the land of unicorns and rainbows...

HOW:

```<code>foreach($critters as $creature) {
   $creature->dance();
}
</code>```

WHAT:

```<code>/* Dancing creatures v1.0
 *
 * The purpose of this is to make all your critters do the funky dance.
 */

foreach($critters as $creature) {
  $creature->dance();
}
</code>```

WHY:

```<code>// We had to store the items in an array of objects because of _____ (reason)
foreach($critters as $creature) {
   $creature->dance();
}
</code>```

Body:
I understand the WHY as being the reason why you do something in a possibly strange or perhaps illogical way, due to the given circumstances requiring it to be done so. The HOW can be seen in the code itself, no matter how odd it is, even if the code makes no "sense". The WHAT is probably best told in the beginning of the class/function documentation. So that leaves you with adding the WHY, where you explain anything not included in the HOW and WHAT, and the peculiar ways you need to take due to reasons beyond your control.

Of course it's not always the case, outside the land of unicorns and rainbows...

HOW:

foreach($critters as $creature) {
   $creature->dance();
}

WHAT:

/* Dancing creatures v1.0
 *
 * The purpose of this is to make all your critters do the funky dance.
 */

foreach($critters as $creature) {
  $creature->dance();
}

WHY:

// We had to store the items in an array of objects because of _____ (reason)
foreach($critters as $creature) {
   $creature->dance();
}


问:
Modelling a resource that may not be part of the parent resource
I am designing an API and am having a couple of problems with certain parts of the resource modelling.

I have the notion of a SurveyItem which as a collective form a Survey:

```<code>Survey Resource Endpoint:
http://api.somewhere.com/survey

Accessing Survey Items
http://api.somewhere.com/survey/1/surveyitems
</code>```

Pretty basic and i am not overly concerned with the above.  SurveyItems cannot exist outside the context of a survey hence the hierarchy.

Where i am struggling a little is the next level down.  A SurveyItem is not necessarily one thing (bear with me)  as it is based on an interface which is implemented but you may have something like a "Simple Survey" that lets you take notes, a "Video Survey" will let you take a survey via video etc, so they are all the all part of the base implementation but could potentially have different sub resources.

```<code>Image and note survey type sample endpoints
http://api.somewhere.com/survey/1/surveyitems/1/images
http://api.somewhere.com/survey/1/surveyitems/1/notes

Video Survey
http://api.somewhere.com/survey/1/surveyitems/2/videos
http://api.somewhere.com/survey/1/surveyitems/2/notes
</code>```

As you can see above a SurveyItem may have different sub endpoints depending on the type of SurveyItem it is.  I was thinking of modelling it the way above but using a HATEOAS approach of responding with a collection URLs of the available sub endpoints for each individual survey type so they are discover-able by clients.

Is this a reasonable thing to do or are there better approaches to handling things like this?

答:
Sounds perfectly reasonable.

In a hypermedia-driven service, the form of your URLs is not really important.

You could also have a flat structure:

```<code>http://api.somewhere.com/survey/1
http://api.somewhere.com/surveyitems/1
http://api.somewhere.com/videos/1
http://api.somewhere.com/notes/1
</code>```

Or just use global ids:

```<code>http://api.somewhere.com/1 (a survey)
http://api.somewhere.com/2 (a video surveyitem for survey 1)
http://api.somewhere.com/3 (a video for surveyitem 2)
http://api.somewhere.com/4 (a note)
</code>```

The hierarchy you've proposed conveys much more useful information about the identity of your resources and their relationships than either of these other options.

Moreover, it will probably be easier to implement because all of the unique identifiers in the URL will map nicely to normalised database tables.

You could give each type of SurveyItem its own URL pattern:

```<code>http://api.somewhere.com/survey/1/videosurveyitems/1
http://api.somewhere.com/survey/1/imagesurveyitems/1
</code>```

But this seems to imply that all surveys will contain distinct collections of every type of items, which doesn't seem true from your description.

If, in the future, you decide (for example) that videos are actually independent of surveys, you can always change your mind by changing your links and/or setting up a redirect:

```<code>http://api.somewhere.com/survey/1/surveyitems/1/videos/1
= HTTP 303 See Other: http://api.somewhere.com/videos/1
</code>```

Body:
Sounds perfectly reasonable.

In a hypermedia-driven service, the form of your URLs is not really important.

You could also have a flat structure:

http://api.somewhere.com/survey/1
http://api.somewhere.com/surveyitems/1
http://api.somewhere.com/videos/1
http://api.somewhere.com/notes/1

Or just use global ids:

http://api.somewhere.com/1 (a survey)
http://api.somewhere.com/2 (a video surveyitem for survey 1)
http://api.somewhere.com/3 (a video for surveyitem 2)
http://api.somewhere.com/4 (a note)

The hierarchy you've proposed conveys much more useful information about the identity of your resources and their relationships than either of these other options.

Moreover, it will probably be easier to implement because all of the unique identifiers in the URL will map nicely to normalised database tables.

You could give each type of SurveyItem its own URL pattern:

http://api.somewhere.com/survey/1/videosurveyitems/1
http://api.somewhere.com/survey/1/imagesurveyitems/1

But this seems to imply that all surveys will contain distinct collections of every type of items, which doesn't seem true from your description.

If, in the future, you decide (for example) that videos are actually independent of surveys, you can always change your mind by changing your links and/or setting up a redirect:

http://api.somewhere.com/survey/1/surveyitems/1/videos/1
= HTTP 303 See Other: http://api.somewhere.com/videos/1


答:
Reverse the focus of your thinking - if you are still contemplating what language to learn, stop contemplating languages and think about what you want to build or what problem(s) you have to solve. Once you have some idea of what your end product is going to be, start thinking about what of these three major factors are important in the project:
-budget/cost
-quality
-time

Revisit your language list again. Which one do you feel might fit the measures of these factors that are required for this project the best? Try to eliminate one at least. Now think about the individual requirements for the project. Are there any items which one language lends itself to more? Revisit your language list again. Try to get it down to one or two.

If you are still on the fence...think about other items. Do you know anyone who's an expert in one of those languages or will someone be working with you who prefers one to the other? Does one language have a better community than the other?

Its not about picking a language itself, its about picking the right language for the job.

My story short and sweet: Sometimes I have projects which lend themselves to C#, and sometimes I have projects which lend themselves to PHP. I pick the one that gets it done the way I need it to.


问:
Why there is no markdown for underline?
I am wondering why there is no markdown syntax for underline?  I know that basic html tags can be embedded to achieve this but I am trying to understand why underline got omitted when bold and italics exists

答:
There are no mention of "bold" or "italics" in the markdown syntax document. What there is, is an emphasis section, which describes how the use of underscore and asterix -marked spans (*, _, **, __) should produce code wrapped in  and  tags.

The reason for this, I presume, is that markdown is a markup language, like html, and should not be concerned with how the text is presented (that's the job of the styling/CSS), but to provide semantic meaning to the text. This is particularly useful for people who use non-graphical browsers, where the emphasis can be conveyed in other ways (Think about how a screen-reader could add emphasis when it encounters an  tag, or really add lots of emphasis in the case of the  tag).

I could well use CSS to style my emphasised text with underlines, rather than italics, but this is not the browser default in most cases.

Title: Why there is no markdown for underline?

Body:
There are no mention of "bold" or "italics" in the markdown syntax document. What there is, is an emphasis section, which describes how the use of underscore and asterix -marked spans (*, _, **, __) should produce code wrapped in <em> and <strong> tags.

The reason for this, I presume, is that markdown is a markup language, like html, and should not be concerned with how the text is presented (that's the job of the styling/CSS), but to provide semantic meaning to the text. This is particularly useful for people who use non-graphical browsers, where the emphasis can be conveyed in other ways (Think about how a screen-reader could add emphasis when it encounters an <em> tag, or really add lots of emphasis in the case of the <strong> tag).

I could well use CSS to style my emphasised text with underlines, rather than italics, but this is not the browser default in most cases.


问:
Do I need IDs in my database if the records could be identified by the date?
I am writing my first application for Android and will use the SQLite database so will be trying to limit the size as much as possible, but I think the question applies in general to database design.

I am planning to store records that will have text and the date of creation. The app is a stand-alone app, i.e. it will not link to the internet and only one user will be updating it, so there is no chance that there will be more than one entry with a given date.

Does my table still need an ID column? If so, what are the advantages of using the ID as a record identifier as opposed to the Date?

答:
Use an ID field if any of the following is true:

No natural key exist ( the date will not be unique )

The date field will be changing often

The date may not be known at the moment of insertion.

A multicolumn identifier exceeds three columns, which would make joins too verbose.

Read this question: Is there a canonical source supporting “all-surrogates”?

Edit:

Since, in my opinion, it seems none of the above holds true, you don't need to use and ID field, but you can use one if you want.


问:
changing value of a private member of a class in c++ without using member or friend function
Using pointer, I am able to modify the private value of the class in the code below.

Does it violate the C++ concept that private member can only be modified by member or friend functions?

```<code>#include<iostream>
using namespace std;

class demo
{
        private: int info;

        public:
                 demo()
                 {
                         info=10;
                 }

                 void print_info()
                 {
                       cout<<info;
                 }
};

int main()
{

     demo ob;
     int* ptr=(int*)&ob;

     *ptr=20;

     ob.print_info();

     return 0;
}
</code>```

答:
The C++ mechanism of public, protected and private members is meant to protect you from accidents, not from malicious intent.

Re-interpreting a pointer as if it points at something else (like you do with int* ptr=(int*)&ob) counts as 'malicious intent' and usually means that you are stepping beyond the C++ language. What happens is entirely up to the compiler and it does not have to be consistent in what it does.

Note that there are other ways to expose private data, for example:

```<code>class demo
{
    private: int info;

    public:
             demo()
             {
                     info=10;
             }

             int* expose_info()
             {
                    return &info;
             }
};
</code>```

This is entirely legal in C++ (although usually a bad idea). The public/protected/private mechanism works only on names (so the name info is inaccessible for outsiders), but if you can get your hands on a pointer/reference to a private member, you have full access to that member.

Body:
The C++ mechanism of public, protected and private members is meant to protect you from accidents, not from malicious intent.

Re-interpreting a pointer as if it points at something else (like you do with int* ptr=(int*)&ob) counts as 'malicious intent' and usually means that you are stepping beyond the C++ language. What happens is entirely up to the compiler and it does not have to be consistent in what it does.

Note that there are other ways to expose private data, for example:

class demo
{
    private: int info;

    public:
             demo()
             {
                     info=10;
             }

             int* expose_info()
             {
                    return &info;
             }
};

This is entirely legal in C++ (although usually a bad idea). The public/protected/private mechanism works only on names (so the name info is inaccessible for outsiders), but if you can get your hands on a pointer/reference to a private member, you have full access to that member.


答:
IMHO, using a date column as a primary key is best avoided.

I have worked on systems where a date field is used as a primary key and writing queries to pull back subsets of the data is a bit of a drag if you're working with date fields.

Some other points you might want to consider:

You might think that a point in time is unique, but that rather depends on the granularity of the date column. Is it minutes, seconds, milliseconds etc. Can you be absolutely sure that you'll never get a primary key violation?

Finally, should you wish to migrate the database to another platform, you may again, encounter problems where the granularity of the date data differs between the platforms.

You do of course have to balance the ideal with what you have to work with. If space is really that much of a concern, using the date column could be the lesser of two evils. That is a design decision you'll have to make.

Edit:

I should point out that in no way does this indicate that it a poor design decision. Just that there could be issues with the practicalities of the RDBMS in question.

Title: Do I need IDs in my database if the records could be identified by the date?

Body:
I am writing my first application for Android and will use the SQLite database so will be trying to limit the size as much as possible, but I think the question applies in general to database design.

I am planning to store records that will have text and the date of creation. The app is a stand-alone app, i.e. it will not link to the internet and only one user will be updating it, so there is no chance that there will be more than one entry with a given date.

Does my table still need an ID column? If so, what are the advantages of using the ID as a record identifier as opposed to the Date?


答:
I learned to ALWAYS write comments in C++ headerfiles (since it is not always clear WHAT a function does, even though the name gives a good hint) especially if you pass an API on to other developers or use a tool for autodoc like doxygen.

So  to me a typical comment looks something like

```<code>/*** Functionname
/*   What happens here
/*  [in] Params
/*  [out] params
/***
</code>```

The only time I used WHY comments is stuff that is hard to grasp and sometimes even to the programmer, like "DO NOT TOUCH THIS! Because ..." or "PROGRAMM WILL CRASH IF LINE IS DELETED..."

Workarounds, hacks and strange behaviour qualifies for WHY criteria in my eyes...

A very good and even hilarious example is this "workaround" for some messed up code written by some person named Richard, someone else wrapped it and explained why in the comments... https://stackoverflow.com/a/184673/979785

Unfortunately there are quite a few times, where you are forced to wrap bull**** because you can not touch the original, either because "it has always been that way" or you do not have access or... well, you do not have the time to fix the original for the purpose doesn't really qualify for the overhead.

Body:
I learned to ALWAYS write comments in C++ headerfiles (since it is not always clear WHAT a function does, even though the name gives a good hint) especially if you pass an API on to other developers or use a tool for autodoc like doxygen.

So  to me a typical comment looks something like

/*** Functionname
/*   What happens here
/*  [in] Params
/*  [out] params
/***

The only time I used WHY comments is stuff that is hard to grasp and sometimes even to the programmer, like "DO NOT TOUCH THIS! Because ..." or "PROGRAMM WILL CRASH IF LINE IS DELETED..."

Workarounds, hacks and strange behaviour qualifies for WHY criteria in my eyes...

A very good and even hilarious example is this "workaround" for some messed up code written by some person named Richard, someone else wrapped it and explained why in the comments... https://stackoverflow.com/a/184673/979785

Unfortunately there are quite a few times, where you are forced to wrap bull**** because you can not touch the original, either because "it has always been that way" or you do not have access or... well, you do not have the time to fix the original for the purpose doesn't really qualify for the overhead.


答:
Each process has its own copy of the library mapped into its virtual address space. That copy is simply part of the process's memory with little distinction from other memory. It's not special because it's part of a shared library. Modifying it doesn't affect any other process.

To preserve physical memory, that mapping is typically copy-on-write. But that's merely an optimization, the OS could give each instance a complete copy with the same semantics.

Title: What is global mutable variable behaviour in dynamically-linked libraries?

Body:
When a dynamically linked library includes a global mutable variable, such as a container for state initialised when loading the library, how do references to that variable behave when running an application that links against it?

Obviously the application cannot alter memory allocated to the dynamically-linked library by the OS, as that would have implications on the other applications using it, so one must assume references to the global mutable variables are rewritten to refer to some R/W memory space owned by the application. But exactly how do the compiler and linker collude to accomplish this?


答:
Code is supposed to specify execution plan.  That way the program follower (or the compiler) can figure out what to do, and how to do it.  The what is broken down into steps that the program follower can follow.  The primitive steps are the how.

The intent of the coder is another matter.  In simple, clear, straightforward code the intent is obvious.  Any reasonably proficient human reader will arrive at the intent of a block of code, just by reading the code.  Most code should read like this.

Occasionally, the relationship between intent and plan is obscure.  The code reveals the what and the how, but not the why.  That's when comments that reveal the intent are worthwhile.  The programer's intent is the why.


答:
Don't forget, if you're writing a program, you're not just randomly typing stuff, you're doing it because you have a model of what you want, whether it's in a formal document or just in your head.
Stuff in your head is every bit as real as software/data in a computer (and just as likely to contain bugs).

Someone reading your code may not have that model in their head, so comments can serve to tell them what the model was and how the code relates to it.
I think that is what's meant by "why".
Certainly it's good to make the code itself as self-explanatory as possible, but that's not always good enough.
Example:

```<code>// transform the x,y point location to the nearest hexagonal cell location
ix1 = (int)floor(0.5 + x + y/2);
iy1 = (int)floor(0.5 + y);
</code>```

On top of that, the model changes over time, and those changes have to be transferred to the code.
So the comments need to not only say "why" something is in the code, but just as important how to change it in response to anticipated model changes.
Example:

```<code>// to change to square cell locations, remove the "+ y/2" in the above code
</code>```

I think that purpose for comments is sometimes neglected.

Body:
Don't forget, if you're writing a program, you're not just randomly typing stuff, you're doing it because you have a model of what you want, whether it's in a formal document or just in your head.
Stuff in your head is every bit as real as software/data in a computer (and just as likely to contain bugs).

Someone reading your code may not have that model in their head, so comments can serve to tell them what the model was and how the code relates to it.
I think that is what's meant by "why".
Certainly it's good to make the code itself as self-explanatory as possible, but that's not always good enough.
Example:

// transform the x,y point location to the nearest hexagonal cell location
ix1 = (int)floor(0.5 + x + y/2);
iy1 = (int)floor(0.5 + y);

On top of that, the model changes over time, and those changes have to be transferred to the code.
So the comments need to not only say "why" something is in the code, but just as important how to change it in response to anticipated model changes.
Example:

// to change to square cell locations, remove the "+ y/2" in the above code

I think that purpose for comments is sometimes neglected.


答:
A comment that tells you why explains the reasoning behind the code - for example:

```<code>// We need to sync the values if the temp <doodad> GUID matches one of the active <doodad>'s
// GUID, as the temp <doodad> has the most recent values according to the server and said
// values might have changed since we added the <doodad>. We want a user to be able to <foo>
// the <doodad> whenever, which means those values must be accurate.
for (doodad in doodads) {
    if ([doodad guid] == [tempDoodad guid]) {
        [doodad updateFromDoodad:tempDoodad];
        break;
    }
}
</code>```

A comment that tells you how explains what the code does.

```<code>// Loop through our <doodads> and check for a GUID match. If it matches, copy the new values
// on the <doodad> that matches
for (doodad in doodads) {
    if ([doodad guid] == [tempDoodad guid]) {
        [doodad updateFromDoodad:tempDoodad];
        break;
    }
}
</code>```

The difference is a maintainer can look at the first one and say, "Oh, so this might be out of date!" In the second case, said maintainer has a comment that doesn't tell you anything the code itself doesn't reveal (assuming good variable names).

Here's a real life example of a why comment, from some iOS code I worked on where we needed to get a gateway address (or reasonable guess for it). I could have just left the comments that said things like "Initialize the receive socket," but that would only tell a maintainer (or future me) what was happening, not why I had to do this strange kludge to get the gateway address in the first place.

```<code>/*
 We're going to do something really hacky here and use a custom partial
 implementation of traceroute to get our gateway IP address.

 [rant removed - irrelevant to the point]

 There's no good way to get at the gateway address of an iDevice
 right now. So, we have two options (per https://devforums.apple.com/message/644915#644915 ):
 1. Get at and parse the routing table (like netstat -rn, or route -n)
 2. Do a traceroute and grab the IP address for the first hop

 As far as I can tell, the former requires <sys/route.h> from the Mac OS X
 header files, which doesn't seem like a good idea to me. Also, there's a
 thread on the Apple Developer forums that seems to imply that header isn't
 in iOS for a reason (https://devforums.apple.com/message/774731#774731 ).

 So when we send our request with a TTL of one it will survive a single hop
 to the router and return, triumphant, with the router's IP address!

 Viva la kludge!

 PS: Original source was the below SO question, but I've modded it since then.
 http://stackoverflow.com/questions/14304581/hops-tracing-ttl-reciveform-on-ios/14304923#14304923
 */

// Default to using Google's DNS address. We used to try checking www.google.com
// if reachability reported we had internet, but that could still hang on routers
// that had no internet connectivity - not sure why.
const char *ip_addr = [kGoogleDNS UTF8String]; // Must be const to avoid undefined behavior
struct sockaddr_in destination,fromAddr;
int recv_sock;
int send_sock;

// ... more code follows
</code>```

Body:
A comment that tells you why explains the reasoning behind the code - for example:

// We need to sync the values if the temp <doodad> GUID matches one of the active <doodad>'s
// GUID, as the temp <doodad> has the most recent values according to the server and said
// values might have changed since we added the <doodad>. We want a user to be able to <foo>
// the <doodad> whenever, which means those values must be accurate.
for (doodad in doodads) {
    if ([doodad guid] == [tempDoodad guid]) {
        [doodad updateFromDoodad:tempDoodad];
        break;
    }
}

A comment that tells you how explains what the code does.

// Loop through our <doodads> and check for a GUID match. If it matches, copy the new values
// on the <doodad> that matches
for (doodad in doodads) {
    if ([doodad guid] == [tempDoodad guid]) {
        [doodad updateFromDoodad:tempDoodad];
        break;
    }
}

The difference is a maintainer can look at the first one and say, "Oh, so this might be out of date!" In the second case, said maintainer has a comment that doesn't tell you anything the code itself doesn't reveal (assuming good variable names).

Here's a real life example of a why comment, from some iOS code I worked on where we needed to get a gateway address (or reasonable guess for it). I could have just left the comments that said things like "Initialize the receive socket," but that would only tell a maintainer (or future me) what was happening, not why I had to do this strange kludge to get the gateway address in the first place.

/*
 We're going to do something really hacky here and use a custom partial
 implementation of traceroute to get our gateway IP address.

 [rant removed - irrelevant to the point]

 There's no good way to get at the gateway address of an iDevice
 right now. So, we have two options (per https://devforums.apple.com/message/644915#644915 ):
 1. Get at and parse the routing table (like netstat -rn, or route -n)
 2. Do a traceroute and grab the IP address for the first hop

 As far as I can tell, the former requires <sys/route.h> from the Mac OS X
 header files, which doesn't seem like a good idea to me. Also, there's a
 thread on the Apple Developer forums that seems to imply that header isn't
 in iOS for a reason (https://devforums.apple.com/message/774731#774731 ).

 So when we send our request with a TTL of one it will survive a single hop
 to the router and return, triumphant, with the router's IP address!

 Viva la kludge!

 PS: Original source was the below SO question, but I've modded it since then.
 http://stackoverflow.com/questions/14304581/hops-tracing-ttl-reciveform-on-ios/14304923#14304923
 */

// Default to using Google's DNS address. We used to try checking www.google.com
// if reachability reported we had internet, but that could still hang on routers
// that had no internet connectivity - not sure why.
const char *ip_addr = [kGoogleDNS UTF8String]; // Must be const to avoid undefined behavior
struct sockaddr_in destination,fromAddr;
int recv_sock;
int send_sock;

// ... more code follows


问:
Code design: is this specific case of monkeypatching in python acceptable?
I'm using python to do some research tasks. I have a class hierarchy for "tools", where each object is an instance of a particular tool. They all share some functionality and have many similarities in their states.

Some of these tools can use one of several methods based on the tool object's current state. The specific tool I'm going to ask about actually calls functions from external modules instead of methods written in the class directly. The underlying reason for this is to break up the code into multiple files, i.e. not have any huge monster file that has all the various methods and helper functions those methods use, when all it needs at any given time is a particular very-targeted subset. I.e. when the mode of the tool is "clean_house", I would only functions like "wash_windows", "vacuum_carpet", and "ask_girlfriend_for_help", while when the mode is "do_work", I use functions like "write_code", "debug_code", and "ask_SO_question". The subsets don't intersect in any way, i.e. "write_code" would never call "ask_girlfriend_for_help", etc.

Instead of calling these functions from module scope within the class methods, it seems to me that it's a better idea to monkeypatch them to the tool's class, since there are instance methods they need to call that go further up the class hierarchy and modify some (protected) part object's state that is used later in the destructor.

I know monkeypatching is often considered poor design or last-resort practice when hot-fixes are in order (Programmer's SE post here), but is it justified in this case? Any alternative code design suggestions?

答:
You are not really monkey patching. Monkey patching is the act of using Python's dynamic nature to change third-party code. What you are doing is using that same dynamic nature to build your class. That is not the same thing, per se.

It sounds like you are delegating functionality to other modules. That sounds like a perfectly fine practice. But I don't quite see why you'd need to alter your tool to do so; your tool can pass on method calls to an underlying object that is responsible for the actual implementation, based on the current state.

Those responsible objects can still modify the state of the tool, as nothing in Python is private, really.


问:
Will high reputation in Stack Overflow help to get a good job?
In a post, Joel Spolsky mentioned that 5 digit Stack Overflow reputation can help you to earn a job paying $100k+. How much of that is real?

Would anyone like to share their success in getting a high paid job by virtue of their reputations on Stack Exchange sites?

I read somewhere that, a person got an interview offer from Google because a recruiter found his Stack Overflow reputation to be impressive. Anyone else with similar stories?

答:
Gaming the System?

Someone should do a study of whether having high rep on SO begets higher rep on SO. That is, once someone reaches critical mass of, say, over 20K rep, do their answers tend to attract more upvotes than other equally valid answers? Anecdotally speaking, I have noticed that low-ranked members will garner 1 or 2 points for answers that will garner higher-rep people (often answering later) 5 or 10 points. And I'm talking about answers that are qualitatively no different. Success begets success.


答:
Access descriptors in C++ are a static mechanism. Compliance is checked at compile time by the compiler, and no memory of the privacy level of methods or attributes is retained at run time, nor are any checks performed by then.

By using a C-style cast you are completely circumventing C++ static checks and all bets are off.

Title: changing value of a private member of a class in c++ without using member or friend function

Body:
Using pointer, I am able to modify the private value of the class in the code below.

Does it violate the C++ concept that private member can only be modified by member or friend functions?

```<code>#include<iostream>
using namespace std;

class demo
{
        private: int info;

        public:
                 demo()
                 {
                         info=10;
                 }

                 void print_info()
                 {
                       cout<<info;
                 }
};

int main()
{

     demo ob;
     int* ptr=(int*)&ob;

     *ptr=20;

     ob.print_info();

     return 0;
}
</code>```


问:
Why is the Scala Option type not called Maybe, just as in Haskell?
Why is the Scala Option type not called Maybe, just as in Haskell?

Maybe makes a lot more "semantic sense" to me, but maybe Option has different behaviour I am not aware of.

Is there any particular reason why Option in Scala was not called Maybe?

答:
Scala is also inspired by Ocaml, which uses Option.

Options are an Ocaml standard type that can be either None (undefined) or Some x where x can be any value. Options are widely used in Ocaml to represent undefined values (a little like NULL in C, but in a type and memory safe way)...

I think the name chosen is a matter of taste.


答:
This has been happening accidentally for years via buffer overflows, bad aliases, and other pointer errors. You write memory past the bounds of an array, and viola! you are corrupting the (possibly private) memory in another object. You are using a pointer that has been de-allocated elsewhere, then another process creates an object at that address and viola!, you are corrupting memory. The accessibility features of C++ are for writing contracts and separating concerns in your design for your users. Just like in C# and JAVA, it doesn't prevent anyone--most likely yourself accidentally-- from misusing pointers.

On a side note, you can also use memcpy to copy one class to another using the same exact idea. You should never actually do that in production code, but it can easily be done.


问:
How to work in localhost properly
I am using MAMP (just and example) to develop web applications without having to constantly upload and download via FTP.

I´m sure this is the correct way to test a project but I´m no sure if I´m doing it right.

After I´m satisfied with the project I have to change in every page the MySQL databases and most of the links etc.

Is there a workaround this? How should this be used?

Thanks in advance!

答:
Yet another way, in the very unlikely case that none of the above suggestions works, is to put a line in your hosts file (/etc/hosts on Unix or \windows\system32\drivers\etc\hosts on Windows) such as:

```<code>
127.0.0.100 my.server.com  # or any number in the 127/8 network.
</code>```

Just don't forget to remove it, or comment it out with a preceding "#", when you actually want to connect to my.server.com. It can be very confusing, annoying, and even dangerous if you forget. "Oh no, how did all my private data end up here on the server??? rm -rf private/. oops..."

Title: How to work in localhost properly

Body:
Yet another way, in the very unlikely case that none of the above suggestions works, is to put a line in your hosts file (/etc/hosts on Unix or \windows\system32\drivers\etc\hosts on Windows) such as:

127.0.0.100 my.server.com  # or any number in the 127/8 network.

Just don't forget to remove it, or comment it out with a preceding "#", when you actually want to connect to my.server.com. It can be very confusing, annoying, and even dangerous if you forget. "Oh no, how did all my private data end up here on the server??? rm -rf private/. oops..."


问:
Why declare final variables inside methods?
Studying some classes of Android, I realized that most of the variables of methods
are declared as final.

Example code taken from the class android.widget.ListView:

```<code>/**
* @return Whether the list needs to show the top fading edge
*/
private boolean showingTopFadingEdge() {
    final int listTop = mScrollY + mListPadding.top;
    return (mFirstPosition > 0) || (getChildAt(0).getTop() > listTop);
}

/**
 * @return Whether the list needs to show the bottom fading edge
 */
private boolean showingBottomFadingEdge() {
    final int childCount = getChildCount();
    final int bottomOfBottomChild = getChildAt(childCount - 1).getBottom();
    final int lastVisiblePosition = mFirstPosition + childCount - 1;
    final int listBottom = mScrollY + getHeight() - mListPadding.bottom;
    return (lastVisiblePosition < mItemCount - 1)
                     || (bottomOfBottomChild < listBottom);
}
</code>```

What is the intention of using the final keyword in these cases?

答:
Here the reason why:   Avoiding reassignment to local variables/parameters.
This would increase readability and avoid some stupid bugs.

http://sourcemaking.com/refactoring/remove-assignments-to-parameters

Excerpt:

Java 1.1 and later versions allow you to mark a parameter as final;
  this prevents assignment to the variable. It still allows you to
  modify the object the variable refers to. I always treat my parameters
  as final, but I confess I rarely mark them so in the parameter list.


答:
Another reason is to be able to use them in inner anonymous classes:</p>

```<code>public interface MyInterface {
    void foo();
}

void myMethod() {
    final String asdf = "tada";//if not final cannot be used in inner classes
    new MyInterface() {
        @Override
        public void foo() {
             String myNewString = asdf;//does not compile only if asdf is final
        }
    }
}
</code>```

Title: Why declare final variables inside methods?

Body:
Studying some classes of Android, I realized that most of the variables of methods
are declared as final.

Example code taken from the class android.widget.ListView:

```<code>/**
* @return Whether the list needs to show the top fading edge
*/
private boolean showingTopFadingEdge() {
    final int listTop = mScrollY + mListPadding.top;
    return (mFirstPosition > 0) || (getChildAt(0).getTop() > listTop);
}

/**
 * @return Whether the list needs to show the bottom fading edge
 */
private boolean showingBottomFadingEdge() {
    final int childCount = getChildCount();
    final int bottomOfBottomChild = getChildAt(childCount - 1).getBottom();
    final int lastVisiblePosition = mFirstPosition + childCount - 1;
    final int listBottom = mScrollY + getHeight() - mListPadding.bottom;
    return (lastVisiblePosition < mItemCount - 1)
                     || (bottomOfBottomChild < listBottom);
}
</code>```

What is the intention of using the final keyword in these cases?

Body:
Another reason is to be able to use them in inner anonymous classes:

public interface MyInterface {
    void foo();
}

void myMethod() {
    final String asdf = "tada";//if not final cannot be used in inner classes
    new MyInterface() {
        @Override
        public void foo() {
             String myNewString = asdf;//does not compile only if asdf is final
        }
    }
}


问:
How can I deal a team member who is irresponsible and shows no commitment?
I am handling a team of a few guys working on a software module in a large project. As per our estimates our module is getting delayed by a week. Since we can not have this delay, our client and our manager arrive at a decision that we need to work on few weekends (3-4) to try to finish the work.

All members of the team are aware of this and understand this and since its just a matter of 3-4 extra days, so we decide to work on weekends to meet the deadline.

But one of the team members is not following this. From last three weekends he has some or the other reason to not come on weekend.

He is not even willing to put up extra hours during weekdays. Personally I don't care about the number of hours he works as long as he/(any one) can finish their work to meet the deadline.

Please let me know how to handle this situation?

答:
You can't force someone to work overtime if its contract never stipulates it.

Unfortunately, I would see two solutions:

1) Managing to convince him to work overtime for the survival of the project.
   Drawback: Demotivation would certainly lead to bad codes, in order to quickly achieve tasks.

2) A little monetary compensation in order to motivate and provide clean code that works.


问:
Do SAS coding "best practices" exist?
At work, we develop a lot of our applications in SAS, from start to finish. One of the problems with this approach is that SAS is a very verbose language with very few language constructs; there is limited support for variables, very limited support for basic functions, and no such thing as classes. They have a concept called "macros" which essentially text substitution; you define a macro, and on invocation, it simply drops in the content of the macro.

My question is, is anyone familiar with "best coding practices" for use in developing SAS applications? Are there software design patterns for SAS? I've gone through Code Complete, and some of what he writes is applicable to SAS, but much of it is not, as the concepts don't exist in SAS. Can anyone give recommendations for writing maintainable, well-designed SAS code?

答:
I've been on the user-end of a few SAS systems, and quite frankly your description doesn't surprise me one bit.  I wound up doing a fair bit of gap programming, to pick up slack left by the primary team, who reported that the SAS code they had was difficult to edit or debug.

Given the hindrances you mention, the best practices arise from recognizing the system's limitations and enforcing a language-level separation of concerns.  Specifically:

Comment first, Code Second, Comment Last  If you're doing OOP TDD, you can jump right in and start coding a prototype, then throw on your tests, and then refactor to cleaner code.  You can't do that in SAS.  Instead, decide what you want your code to do BEFORE you write it.  Then write the code.  Then go back and edit your comments to make sure they're accurate.

Embrace the language features.  Macros seem like an excellent way to share simple code blocks between programs, either as connecting to particular data sources or performing distinct functions.  Not as good as a proper function call, but better than nothing.

Don't make SAS do what other technologies can do better.  If you're sending data to SQL server and need to archive the table, let SQL server handle that.  If you're populating data as options for a client-side program, send your rows to a common format like XML and let the client-side program worry about its internal segmentation.

Don't try and force a model that SAS doesn't support. Without classes, you can't do OOP, so don't.  SAS is closer to a set of distinct scripts or old-school mainframe programs anyway.

Simple is better than complex.  Your SAS programs, if possible, should only do one thing.  Pull the data from the client systems.  Calculate the statistics.  Store the calculated data.  Format the calculated data as a report.  Each of those steps should be a SEPARATE program file, even if you have to force them into one-time-use macros to do it.

Don't be clever.  SAS is an agnostic, meta-language that pulls from a polyglot of data sources and exports to a byzantine array of formats.  Which is all well and good if you need to access some obscure or legacy format, but is just asking for trouble if you jump to SAS's internal features without, at a minimum, leaving room for the data source to be optimized to produce your data quicker.

Don't be everything.  SAS seems like an excellent tool for enterprise-wide data aggregation and analysis.  But the same features that make it so worthwhile for that make it horrible for something like an email program, or a client-side custom calculator.

I haven't worked with SAS directly, or else I'd give you better specifics.  But the aggravation that SAS has caused me with what I have seen has left me with a pretty firm opinion that SAS is a niche language, and shouldn't be used outside of its niche.  There's nothing wrong with being a niche language -- RegEx and XSLT are both niche languages, and they're two of my favorites -- but it's a PHB-smell when a team is told to "use SAS" for everything.

Title: Do SAS coding "best practices" exist?


问:
Quickly prune and create valid data combinations
I am really struggling with a problem where I need to "prune" down available scenarios to those that a user has defined as valid. Below is a small example of the problem I am trying to solve in .Net (C#). Given the levels / values shown below, the user could pick that there are only a few valid combinations, but if you imagine the levels below being 30-40 levels of data instead of the 5 I have shown, you could see my dilemma. I could need to go through millions to billions of NOT VALID combinations to get to the Valid combinations. There will be cases where all values in the level are applicable and some where only those combinations that the user has specified are.

Current Levels / Values of data:

Users have said that the valid combinations are:

```<code>*Notice all from level 4 are valid
Receiver -> Sony -> 500 -999 -> Retail
Receiver -> Sony -> 1000 - Up -> Retail
</code>```

Results expected from the given 5 levels of information:

```<code>Receiver -> Sony -> 500-999 -> Open -Box -> Retail
Receiver -> Sony -> 500-999 -> New -> Retail
Receiver -> Sony -> 1000-Up -> Open -Box -> Retail
Receiver -> Sony -> 1000-Up -> New -> Retail
</code>```

The things I have tried are performant with small sets, but if I was to have a lot of levels and big gaps in the combinations which wouldn't allow me to prune the valid combinations until I was deep into the levels, I am running into major performance problems. I am obviously not tackling the problem incorrectly.

Any other views or suggestions on tackling the problem would be greatly appreciated.

答: What you're doing is called faceted search.  There is a lot of research in that area about how to do it efficiently, but I would recommend starting with an existing solution like Apache Solr.</p>