问:
how to handle / architect soa when service becomes unavailable?
Say I've got a third-party service called Cool.io that provides a RESTful API but often goes down. My applications consume that API, but when Cool.io goes down, my app really can't do much... but it should!

Say I create a proxy to the Cool.io and this proxy stores a copy of Cool.io's data and provides RESTful endpoints for my application. Let's assume that my proxy has 100% reliability, or, at least more than Cool.io's. Let's also assume that my proxy has no problem propagating PUTs/POSTs to Cool.io, and no problems receiving the same from Cool.io (in other words, there are no data sync issues between my proxy and Cool.io).

This decouples my application's dependency on Cool.io, which goes down all the time... but it doesn't decouple the proxy from the Cool.io service. As such, when my application modifies something on the proxy, the proxy's data changes and tries to send that change to Cool.io.

But, if Cool.io is down, that request just results in an unavailability error (or a failed connection).

What's the proper way to architect something like this? How do guys like Amazon or Netflix decouple their services such that an outage doesn't affect the consumer, or if it does, it does so gracefully?

Is a message queue in order here?

Is there a simpler solution than creating a proxy to the unreliable service?

答:
Since your service is read-intensive, using a caching proxy sounds like a good idea.  But beware: the more you try to retain the semantics of the original system when the backend is down, the more complex your system becomes.  And usually, the more surprising its failure modes are to the end-user.   Both of those factors will often motivate a decision to adopt a simple read-only proxy.

Even a read-only proxy should return a timestamp with the data, to indicate when the data was last fresh.   For HTTP you can encode this with IMS or an Etag; for other systems it will depend on the protocol you are using.  Refusing to serve very unfresh data from the proxy is a choice you might but don't have to make.

In your application layer, you will need to decide what to do when the user wants to perform a mutation-like action on data of age T seconds.

I think it is normally best to just accept the change, and return an error if the (Cool.io) backend failed to process the request.   If you choose instead to decline without trying, you will have problems in which the pre-mutation check finds the backend in one state, but the attempt to actually apply the change finds it in another -- this situation is hard to test for in your system's regression test suite, so my advice is not to build a system that tries to do this.

If the backend cannot apply your change, your system could treat this error as  final or it could offer to try to apply the change when the service returns.

As a user-experience optimisation, when you know that the proxy has been unable to get service from the backend, you can display warnings on the user interface, so that they user can avoid a time-consuming data entry only to find the backend is down.

If you do offer to apply a failed change later, the changes the user wanted to apply but which could not be applied in the short term are going to need to be stored.   You can store them in a queue, but as @matthew-flynn pointed out, you will need to handle duplicate (perhaps conflicting) queued changes.   Hence you will probably need to "queue" the changes in a queryable way.   Such as in a database table of unreconciled changes.   The simple thing to do there is to reject changes to data which itself hasn't really been applied to the backend.   Otherwise, a failure to apply a certain change to the backend may require more than one user-level change to be rejected.

If it is possible for a queued change to fail to apply you are going to need to provide some kind of functionality in which the user reconciles the failed changes.

A particularly interesting case is where the backend has just come up and another user has submitted a conflicting change, live.   That is, a new change has "overtaken" a queued change.  You might consider blocking all changes by users when there are queued pending changes.   One way to achieve that is for all changes, live or deferred, to use the same queue.   If you do that, be very sure that problem changes cannot get stuck at the head of the queue.

As you will note from the above, all this this clearly requries changes in the semantics of the application.  You can't just do it invisibly in a proxy layer, unless you reject mutations that couldn't immediately be applied to the backend.  And if it makes a difference to the user whether the data is fresh or not you may need to warn them that they're looking at stale data.

You also asked how large services deal with this.   One of the popular ways is for the backends to be sharded by user-id so that if a given part of the service is down, only some users are affected.  This is easy to do for things like serving static data (which mostly won't care who you are) but much harder for services in which users have N-to-N relationships (for example things like Twitter - though in the case of Twitter the complexities around failed mutations are mostly absent).


问:
Why most job offerings are for a <language here> developer, rather than a developer in general?
In an ideal world:

In an excellent article Don't Call Yourself A Programmer, And Other Career Advice, Patrick McKenzie explains, among other things, that language doesn't matter:

A developer is a person who solves problems, in general. A developer is not a person who writes code in a specific language.

Businesses don't care about the languages you know. If they need to hire a developer for a project written in a specific language, and they have a candidate who is highly experienced but never wrote a line of code in this language, he would still be hired.

According to my experience both as a developer and as a person who had to hire other developers, the observation is very similar:

The N years experience in Java or N years experience in C# doesn't matter. What matters is that the candidate knows how to solve problems, knows the difference between spaghetti code and clean code with well-thought architecture, etc.

I don't care about the languages you used before. For a C# project, I'll rather hire a professional developer who spent his life writing Java, Python and Ruby on Rails code rather than a beginner who knows only C#, and knows it badly.

The knowledge and the experience you gain using one language is mostly reusable in any other language.

An experienced developer who used Ruby on Rails for web development and spent the rest of his career writing Java desktop applications using Oracle fits perfectly well for an ASP.NET MVC project using Microsoft SQL Server. Because this person already knows everything she need for this job, aside a few specific things and syntax differences.

On the other hand, a person who have done just a few ASP.NET MVC small websites doesn't fit at all, because she may not completely understand the MVC architecture, may know know what is SQL profiling, and may lack some other essential knowledge.

Don't tell me that I'm unable to fix a small problem with a PHP website which uses CodeIgniter just because I never used CodeIgniter before.

In practice:

In practice, when I search for freelance jobs and when I see the job offerings in general, they are very language-specific.

Some would search for a PHP developer with two years experience in Magento. Others will be searching for a person with VB.NET experience of at least three years, and if you send them a resumé mentioning that you've done C# development for six years, but with no mention of VB.NET, they will not bother to answer. If they ask for a person with an experience with Firebird, they will not listen about your ten years experience with Oracle.

Why there is such difference between the theory and what Patrick McKenzie and I describe as being common sense, and the real world of job offerings?

答:
Not all programming jobs are the same. My current job certainly fits in your model. It involves a lot of ad hoc data analysis and we pick up and put down tools as needed. I was hired in part because I had a track record of being able to quickly become productive with new tools.

On the other hand there are jobs where you are looking for specific technical expertise. Back in the 90s I was working for a small software shop, and we needed to quickly develop expertise in C++. Despite explicitly asking for expertise in C++ in our ads, most of the applicants knew less C++ than I did. "But I can learn C++ quickly!" they all said. Well yeah, I'm sure you could, but so could I, and so could the other folks already there. We were looking for somebody who already really knew C++, so we'd have an in-house source of expertise as the rest of us came up to speed. Having another beginner on the team really wouldn't have helped.

ContentLicense: CC BY-SA 3.0


问:
Are Java applets worth learning?
I'm on the way of learning Java myself. I find most of texts giving emphasis to Java applets. I got confused about the importance. Is it something widely used?  Do I need to spend more time on it?</p>

答: It all depends on what your intentions are and who your audience is.  Since you are just starting out, and if you do not have a project that requires you to project into the web/browser, I would tinker with Swing and learn how that UI paradigm works.  When the time comes, you can then learn how to wrap that into an Applet and deal with the deployment issues (security, deployment, platform compatibility, etc).  Even if you never use an Applet, or Swing in the future, the core concepts you learn to master Swing (threading, events and listeners, employing a MVC philosophy, basic behavior of UI widgets ....) are useful in almost any UX context.</p>

Title: Are Java applets worth learning?

ContentLicense: CC BY-SA 2.5


问:
Visual Studio build everytime JS and CSS changes?
I am relatively new to Visual Studio Development and I was wondering - it seems that everytime I make changes to my JS or CSS in my project - I have to "build" the project again.

Is there any way to simply refresh the browser as opposed to building everytime ? My understanding is that all the files are copied to some temporary directory but I was hoping that I can quickly debug/write JS and CSS within the solution and just refresh the browser to see the changes ?

答:
In my experience, all you need to do is save the CSS/JS files and refresh the browser (hard refresh, not using the browser cache).

The reasons this will not work can be many, but mostly to do with any processing that the files need to go through before the go to the browser - say bundling, minification, usage of ScriptManager or any such server side work (including required deployment) on the files before they are available to the browser.

After chat, we confirmed that the OP is using ScriptManager with CSS/JS, causing the issue.

It is possible that using bundling instead would solve this.


答:
In most project based work results are needed quickly and people need to generate profits as soon as possible.

People that are able to deliver these needs and are not bound to a specific language(s) are scarce and by consequence too expensive. These people only get hired by the big companies that ask for incredible skills.

People that are able to solve the problem but cannot learn a specific language fast are less scarce. They still cost a lot of money, and they have an extra cost of time needed to learn the specific language.

This extra cost of time is reduced by asking for a language specific programmer. He has already learned the required skills and can deliver results quickly.

In short, a project that needs to be done in JAVA doesn't need an expensive incredible software developer, nor does it need an average .net developer that will need time to learn the language/framework. It needs immediate results for the least amount of money, which is delivered by the guy who already has experience with JAVA and has relatively good problem solving skills.

As always, it's about money, and getting the most return on investment

Title: Why most job offerings are for a <language here> developer, rather than a developer in general?

Body:
In an ideal world:

In an excellent article Don't Call Yourself A Programmer, And Other Career Advice, Patrick McKenzie explains, among other things, that language doesn't matter:

A developer is a person who solves problems, in general. A developer is not a person who writes code in a specific language.

Businesses don't care about the languages you know. If they need to hire a developer for a project written in a specific language, and they have a candidate who is highly experienced but never wrote a line of code in this language, he would still be hired.

According to my experience both as a developer and as a person who had to hire other developers, the observation is very similar:

The N years experience in Java or N years experience in C# doesn't matter. What matters is that the candidate knows how to solve problems, knows the difference between spaghetti code and clean code with well-thought architecture, etc.

I don't care about the languages you used before. For a C# project, I'll rather hire a professional developer who spent his life writing Java, Python and Ruby on Rails code rather than a beginner who knows only C#, and knows it badly.

The knowledge and the experience you gain using one language is mostly reusable in any other language.

An experienced developer who used Ruby on Rails for web development and spent the rest of his career writing Java desktop applications using Oracle fits perfectly well for an ASP.NET MVC project using Microsoft SQL Server. Because this person already knows everything she need for this job, aside a few specific things and syntax differences.

On the other hand, a person who have done just a few ASP.NET MVC small websites doesn't fit at all, because she may not completely understand the MVC architecture, may know know what is SQL profiling, and may lack some other essential knowledge.

Don't tell me that I'm unable to fix a small problem with a PHP website which uses CodeIgniter just because I never used CodeIgniter before.

In practice:

In practice, when I search for freelance jobs and when I see the job offerings in general, they are very language-specific.

Some would search for a PHP developer with two years experience in Magento. Others will be searching for a person with VB.NET experience of at least three years, and if you send them a resumé mentioning that you've done C# development for six years, but with no mention of VB.NET, they will not bother to answer. If they ask for a person with an experience with Firebird, they will not listen about your ten years experience with Oracle.

Why there is such difference between the theory and what Patrick McKenzie and I describe as being common sense, and the real world of job offerings?


答:
I think you're simply misinterpreting the standard phrase "<language here> developer". Companies don't put that phrase in the ad to deter developers who have experience in some other language. Why would they want to deter capable developers? From the employer's point of view, the more candidates, the better. They can always not invite people they're not interested in.

The real point of the phrase is to tell you, the reader, what the job offer would entail. And that makes a lot of sense, IMHO. Would you apply for a job where you develop in Z80-assembly language? Or COBOL? Or Fortran?

And, obviously, if the company has two candidates who seem equally smart otherwise, then the one with experience in <language here> wins. Nothing more, nothing less. (There are special cases, where people are hired for a single project only, or for a project that's already late, or for the first project the company develops in <language here>, where you really need experience in that language from the start, but I don't think they're the rule.

Incidentally, my company once wrote ads like you suggested (it seems like it makes sense, after all). The results were devastating. People who really care about their work simply skipped the ad. Only the desperate, who apply to any open position applied. We never tried it again.


问:
Why did the Haskell committee choose monads to represent I/O?
The Clean language uses uniqueness types to handle I/O in a purely functional setting. Why did the Haskell committee go with monads instead? Were there other proposals for handling state that the committee investigated but decided against?

Note: I'm not looking for a holy war between monads and other forms of computing. Let's keep the topic to just the committee's choices regarding I/O.

答:
According to A History of Haskell: Being Lazy With Class (see section 7) three different models were considered initially: streams, continuations and "world passing" (I don't know much about Clean, but it sounds like this is the Clean way?).

The last paragraph of section 7.2 indicates that the uniqueness type concept wasn't developed at this time:

This “world-passing” model was never a
      serious contender for Haskell, however, because we saw no easy
      way to ensure “single-threaded” access to the world state. (The
      Clean designers eventually solved this problem through the use
      of “uniqueness types”)

The concept of monads seems to have been introduced (reused from other work) in later revisions of Haskell since it resulted in cleaner code (compared to continuations/streams):

The monadic approach rapidly dominated earlier models. The types are
  more compact, and more informative.


问:
Can functional programming be used to develop a full enterprise application?
I am just beginning to learn Functional programming (FP). I come from a OOP world, where everything are objects, and most of them are mutable. I have a hard time wrapping around the concept that  functions don't have side effects.

If something is not mutable, how are common things objects like Employee or Person represented in FP.

Can FP be used to create a full fledged enterprise application?

答:
The question is not Can be FP used in the Enterprise ? but Should we use FP in the Enterprise ?

Of course you can. You can develop any kind of application with any kind of programming language, that's why they are called "Turing complete".

Now, to the question "Should be use it in the Enterprise ?" That's up to you or your employers, FP can be really useful in some kind of applications, and in fact, it's used quite a lot: Haskell in the industry

Now, you might be asking "So why is not used more?" mainly because other Imperative/OO languages are more common, and companies refuse to change to a more "exotic" language because they are used to Java or C++.

ContentLicense: CC BY-SA 4.0


问:
Is it best practice to always capitalize class file names in PHP, and other languages?
I ask because I've seen a couple of OO PHP tutorials which do not adhere to this, but to me it just makes sense. It makes it easy to instantly see if a file is a class or not, if non-class files all use lowercase names.</p>

答:
This is a naming convention question and whilst it is a good meta question it seems to have been well covered with this StackOverflow question from Dec 2008.

Basically, some languages have prescribed naming conventions (e.g. Java) whereas others (the majority) have evolved and are mixed to the point of Programmer's Holy Wars.


问:
On developing deep programming knowledge
Occasionally I see questions about edge cases and other weirdness on Stack Overflow that are easily answered by the likes of Jon Skeet and Eric Lippert, demonstrating a deep knowledge of the language and its many intricacies, like this one:

You might think that in order to use a foreach loop, the collection
  you are iterating over must implement IEnumerable or IEnumerable<T>.
  But as it turns out, that is not actually a requirement. What is
  required is that the type of the collection must have a public method
  called GetEnumerator, and that must return some type that has a public
  property getter called Current and a public method MoveNext that
  returns a bool. If the compiler can determine that all of those
  requirements are met then the code is generated to use those methods.
  Only if those requirements are not met do we check to see if the
  object implements IEnumerable or IEnumerable<T>.

That's cool stuff to know.  I can understand why Eric knows this; he's on the compiler team, so he has to know.  But what about those who demonstrate such deep knowledge who are not insiders?

How do mere mortals (who are not on the C# compiler team) find out about stuff like this?

Specifically, are there methods these folks use to systematically root out such knowledge, explore it and internalize it (make it their own)?

答:
Deep knowledge and programming expertise means being comfortable at all abstraction levels. I.e.

libraries and APIs

language semantics

compiler optimizations

compiler internals and code generation

runtime and garbage collector behavior

architectural and instruction set issues

Everything I've seen in the last 15 years has shown that only if you really can get into the compiler and runtime do you have a chance of becoming deeply proficient. You may have to force yourself to take the step and start reasoning (and building) software at the next level of abstraction lower in the stack, but its the only way to expertise.

All we have is language for abstraction. You must understand how programming languages are designed and built to really know what the machine is doing.


问:
What strategies are you using to migrate your web site from Silverlight to HTML5 + JavaScript?
Microsoft released Silverlight 5 but there has been no news of any future versions (except service releases) being released. Combined with the increasing visibility of HTML5 and modern JavaScript libraries it now makes a lot of sense to start adopting the new and emerging technology instead of relying on Silverlight whose future is in doubt.

Given this what are the migration strategies that you are using to move away from Silverlight? Any lessons learnt so far?

答:
Yesterday it was Silverlight, today its HTML5, tomorrow who knows.

Which ever way you cut it, you will need to "port" it. Porting will always be a manual affair.

In terms of "strategy" just make sure your design is modular, clean and highly structured code. When the day comes to port. If you can see and understand the design. The porting pain is just that little less.


问:
What is the appeal of Systems Hungarian?
In a now deleted question titled "What naming guidelines do you follow?", the author says:

Also I prefer to code using hungarian notation from Charles Simonyi.

I've run in to several programmers who still prefer to use Hungarian, mostly of the Petzold/Systems Hungarian flavor.  Think dwLength = strlen(lpszName).

I've read Making Wrong Code Look Wrong, and I understand the rationale for Apps Hungarian, where domain-type information is included in the variable names.  But I don't understand the value in attatching the compiler type to the name.

Why do programmers still persist on using this style of notation?  Is it just inertia?  Are there any benefits that outweigh the decreased readability?  Do people just learn to ignore the decorators when reading the code, and if so, how do they continue to add value?

EDIT:
A lot of answers are explaining the history, or why it is no longer relevant, both of which are covered in the article I cited.

I'd really like to hear from anyone out there who still uses it.  Why do you use it?  Is it in your standard?  Would you use it if it wasn't required?  Would you use it on a new project?  What do you see as the advantages?

答:
At the moment I still use Hungarian for exactly three reasons, judiciously avoiding it for everything else:

To be consistent with an existing code base when doing maintenance.

For controls, eg. "txtFirstName". We often need to distinguish between (say) "firstName" the value and "firstName" the control. Hungarian provides a convenient way to do this. Of course, I could type "firstNameTextBox", but "txtFirstName" is just as easy to understand and is less characters. Moreover, using Hungarian means that controls of the same type are easy to find, and are often grouped by name in the IDE.

When two variables hold the same value but differ by type. For example, "strValue" for the value actually typed by the user and "intValue" for the same value once it has been parsed as in integer.

I certainly wouldn't want to set up my ideas as best practice, but I follow these rules because experience tells me that it occasional use of Hungarian benefits code maintainability but costs little. That said, I constantly review my own practice, so may well do something different as my ideas develop.

Update:

I've just read an insightful article (archive mirror) by Eric Lippert, explaining how Hungarian can help make wrong code look wrong. Well worth reading.


答:
You don't abandon a technology because there are no updates for it. If you have invested time and money to build the software and it is working well and the software publishing company is committed to it, leave your application as is. Panic if the software publishing company declares that it is not providing support on any commercial platform. By the time you migrate your application, the life time of your software could be close to an end and who knows, another flavor may come along.
In short your shop should establish a migration policy and not rewrite the software with every new technology unless there is a business need for it.</p>

Title: What strategies are you using to migrate your web site from Silverlight to HTML5 + JavaScript?

Body:
Microsoft released Silverlight 5 but there has been no news of any future versions (except service releases) being released. Combined with the increasing visibility of HTML5 and modern JavaScript libraries it now makes a lot of sense to start adopting the new and emerging technology instead of relying on Silverlight whose future is in doubt.

Given this what are the migration strategies that you are using to move away from Silverlight? Any lessons learnt so far?


问:
Should I return iterators or more sophisticated objects?
Say I have a function that creates a list of objects. If I want to return an iterator, I'll have to return iter(a_list). Should I do this, or just return the list as it is? My motivation for returning an iterator is that this would keep the interface smaller -- what kind of container I create to collect the objects is essentially an implementation detail

On the other hand, it would be wasteful if the user of my function may have to recreate the same container from the iterator which would be bad for performance.

答:
Return the list itself.   That's quite efficient (since a copy is not made).   If the caller wants an iterator, it can always call iter().

The fact that your interface returns a particular type of object isn't really a big deal in Python; duck typing often makes the exact types of objects unimportant.


问:
Cross-Platform: Develop in parallel or series?
When starting a new software project that will be used on several platforms, how do you determine the best way to start development? Do you develop for one platform and then port to the next? Do you try to develop all platforms simultaneously?

For example, I'm going to start developing a Windows Phone app in C#. Much of my code could theoretically be reused with the .NET Framework and Silverlight. However I find that as I try to develop on all platforms simultaneously, refactoring and redesign tends to be 3 times as difficult and slow.

I could try writing my app for Windows Phone and then port to other platforms, but I have no ideas what hairballs await me there, and it seems like there would be a lot of potential for design decisions to bite me in the bum only after I start porting.

So which is better: develop the code for all platforms at once, or refactor and port to new platforms one at a time? What traps await me on either road?

答:
Overview

My experience, is to work with both approaches. I will say more like "parallel", "series" & "incrementally".

Description

For example, I'm designing an app. with 10 modules, and want to migrate to 3 platforms.

So I, start with a single platform, and 3 modules, usually the most important, like "core" or "system".

Then, I try to migrate that same app. to the second platform. Sometimes, I add some stuff, refactor types name, and switch back to the original platform those changes.

Example (Using "C#" & "Plain C" as "platforms, altought, you may think in "Linux", "iOS", Windows Compact Edition):

I have a custom XML parser in C# (.NET), for practical sources, "a platform", I want to migrate it to "Plain C", as another "platform".

I have this enumeration type in C#:

```<code>enum XMLNodeType
{
  Undefined,
  Declaration,
  Comment,
  SingleTag
  StartTag,
  FinishTag,
  EntityTag,
}
</code>```

But, in "Plain C", for some reason, I need to prefix, the equivalent enumeration:

```<code>enum XMLNodeType
{
  xmlnodeUndefined,
  xmlnodeDeclaration,
  xmlnodeComment,
  xmlnodeSingleTag
  xmlnodeStartTag,
  xmlnodeFinishTag,
  xmlnodeEntityTag,
};
</code>```

So, I decide, than I go back to the "C#" code, and replace it with:

```<code>enum XMLNodeType
{
  xmlnodeUndefined,
  xmlnodeDeclaration,
  xmlnodeComment,
  xmlnodeSingleTag
  xmlnodeStartTag,
  xmlnodeFinishTag,
  xmlnodeEntityTag,
}
</code>```

When, I have those 3 modules in equivalent code, in 2 platforms, I add the migration to the third platform. Again, sometimes, I add things or refactor things, and apply those changes back to the previous platforms.

When I have the 3 platforms working, I start to add an additional module, to each platform.

Repeat the process, until all modules are available in the 3 platforms.

Summary

I don't try to do or migrate the whole app., neither "serial", neither "parallel". Only parts of of it. Add the "incremental" concept.

Even, that a section of code is working in a platform, is possible, that when migrating to another you'll change types names, and apply back those changes to the first destination.

Body:
Overview

My experience, is to work with both approaches. I will say more like "parallel", "series" & "incrementally".

Description

For example, I'm designing an app. with 10 modules, and want to migrate to 3 platforms.

So I, start with a single platform, and 3 modules, usually the most important, like "core" or "system".

Then, I try to migrate that same app. to the second platform. Sometimes, I add some stuff, refactor types name, and switch back to the original platform those changes.

Example (Using "C#" & "Plain C" as "platforms, altought, you may think in "Linux", "iOS", Windows Compact Edition):

I have a custom XML parser in C# (.NET), for practical sources, "a platform", I want to migrate it to "Plain C", as another "platform".

I have this enumeration type in C#:

enum XMLNodeType
{
  Undefined,
  Declaration,
  Comment,
  SingleTag
  StartTag,
  FinishTag,
  EntityTag,
}

But, in "Plain C", for some reason, I need to prefix, the equivalent enumeration:

enum XMLNodeType
{
  xmlnodeUndefined,
  xmlnodeDeclaration,
  xmlnodeComment,
  xmlnodeSingleTag
  xmlnodeStartTag,
  xmlnodeFinishTag,
  xmlnodeEntityTag,
};

So, I decide, than I go back to the "C#" code, and replace it with:

enum XMLNodeType
{
  xmlnodeUndefined,
  xmlnodeDeclaration,
  xmlnodeComment,
  xmlnodeSingleTag
  xmlnodeStartTag,
  xmlnodeFinishTag,
  xmlnodeEntityTag,
}

When, I have those 3 modules in equivalent code, in 2 platforms, I add the migration to the third platform. Again, sometimes, I add things or refactor things, and apply those changes back to the previous platforms.

When I have the 3 platforms working, I start to add an additional module, to each platform.

Repeat the process, until all modules are available in the 3 platforms.

Summary

I don't try to do or migrate the whole app., neither "serial", neither "parallel". Only parts of of it. Add the "incremental" concept.

Even, that a section of code is working in a platform, is possible, that when migrating to another you'll change types names, and apply back those changes to the first destination.


答:
My experience with this is C on Linux on x86 & Solaris on SPARC:

I develop on one platform and test on both as I work.  This catches more bugs more quickly.  I use only two platforms which forces me to separate platform dependent code from platform independent code.  Later, once the program is finished I begin porting it to other platforms.

I've never needed to use more than two platforms, so I don't have experience with the final step.  However this would be my plan.

Title: Cross-Platform: Develop in parallel or series?

Body:
When starting a new software project that will be used on several platforms, how do you determine the best way to start development? Do you develop for one platform and then port to the next? Do you try to develop all platforms simultaneously?

For example, I'm going to start developing a Windows Phone app in C#. Much of my code could theoretically be reused with the .NET Framework and Silverlight. However I find that as I try to develop on all platforms simultaneously, refactoring and redesign tends to be 3 times as difficult and slow.

I could try writing my app for Windows Phone and then port to other platforms, but I have no ideas what hairballs await me there, and it seems like there would be a lot of potential for design decisions to bite me in the bum only after I start porting.

So which is better: develop the code for all platforms at once, or refactor and port to new platforms one at a time? What traps await me on either road?


答:
My 2c:

If the language doesn't force any conventions, and this includes things like indentation (not just naming).  Then the important thing is consistency.  Consistency is far more important than the choice of a good convention.

The existing answer answers your actual question.

Title: Is it best practice to always capitalize class file names in PHP, and other languages?

Body: I ask because I've seen a couple of OO PHP tutorials which do not adhere to this, but to me it just makes sense. It makes it easy to instantly see if a file is a class or not, if non-class files all use lowercase names.</p>


答:
Unless you plan on drastically switching languages, I would attempt the MVC pattern here so that most of the code resides in the model and controller which only need be developed once.
After that, each platform can be a view, greatly reducing code across each platform and the cost of implementing new features and changing existing ones.

I did this with a software package I wrote to be available via a regular html5 website, an android app and a .NET desktop app.  Most of my code resided on the server exposed via ASP.NET web services that each client would interact with.  It greatly simplified the work I had to do on each client which consisted of presenting the data and available commands from the web services.

If you find yourself needing to change your storage mechanism from platform to platform, this is a great time to have an abstracted DAL that could feature any number of storage engines behind it.


答:
When I was writing code for Windows 32(x86), WinCE(arm), Linux (x86) and Linux ARM I found the only way to do it was in parallel. There were a few things that really helped:

a continuous integration system for all platforms

developer builds could be kicked for any platform from any developer box (it would rsync'd the code to the appropriate platform and execute the build)

isolating platform specific code and and creating a layer of macros and libraries to normalize the different apis


问:
How do you deal with the anxiety of not knowing enough?
I just finished college a couple of months ago and I'm taking time out to improve my knowledge. I love programming but I feel like I don't know enough to be confident if I went for an interview. Last night I was browsing through questions and came across a question that asks interviewees how to work out a linked list. I learned these at college but if I was asked on the spot how to do it I wouldn't know. So that's another thing added to the list of what to learn.

This is when the anxiety hit me because I have so much to learn in so little time (at least it feels that way). Upon introspection, I think this anxiety is related to my perfectionism even though being perfect isn't rational e.g. Shakespeare and Einstein failed 80% of the time.

So the questions are, have you felt this anxiety of not knowing enough? If so, how did you deal with it? I suppose there's a point in time when you begin to feel comfortable in your abilities?

答:
I'm surrounded with a lot of really good programmers, and I've only been programming professionally for a year, so I feel this stress.

When these guys are getting excited about learning Clojure and Scala, I can feel overwhelmed.  After all, I'm still confused about jQuery, only passable at Hibernate, and clueless with web services.

What I find important to remember is that I don't learn much at all in a day, but I can learn a lot in a month.  And as the months pile up I find that I'm turning into a knowledgeable programmer in certain areas.

As long as you are committed to continue to learn, you will surpass many of your classmates, even if you forget everything you ever knew about linked lists.


答: Unless you have the need to traverse the list multiple times, I'd most likely you a generator. As a personal preference, I tend to favor generators to lists as the entire list is not maintained in memory. Of course, if you're not dealing with a large volume of data, it wouldn't really matter which way you go.</p>

Title: Should I return iterators or more sophisticated objects?

Body:
Say I have a function that creates a list of objects. If I want to return an iterator, I'll have to return iter(a_list). Should I do this, or just return the list as it is? My motivation for returning an iterator is that this would keep the interface smaller -- what kind of container I create to collect the objects is essentially an implementation detail

On the other hand, it would be wasteful if the user of my function may have to recreate the same container from the iterator which would be bad for performance.


答:
Read The Fine Manual This is not particularly deep knowledge.  It's published in the C# language specification section 8.6.4.  You should get in the habit of at least skimming the specifications for the languages that you use, as well as skimming the documentation for all the builtin libraries.

Anyway, this not my idea of deep knowledge; it's just an uninteresting implementation detail.  It could be more interesting if the designer explained why it was done in this more dynamic way, instead of just checking that the object implements Iterable.

Title: On developing deep programming knowledge

Body:
Occasionally I see questions about edge cases and other weirdness on Stack Overflow that are easily answered by the likes of Jon Skeet and Eric Lippert, demonstrating a deep knowledge of the language and its many intricacies, like this one:

You might think that in order to use a foreach loop, the collection
  you are iterating over must implement IEnumerable or IEnumerable<T>.
  But as it turns out, that is not actually a requirement. What is
  required is that the type of the collection must have a public method
  called GetEnumerator, and that must return some type that has a public
  property getter called Current and a public method MoveNext that
  returns a bool. If the compiler can determine that all of those
  requirements are met then the code is generated to use those methods.
  Only if those requirements are not met do we check to see if the
  object implements IEnumerable or IEnumerable<T>.

That's cool stuff to know.  I can understand why Eric knows this; he's on the compiler team, so he has to know.  But what about those who demonstrate such deep knowledge who are not insiders?

How do mere mortals (who are not on the C# compiler team) find out about stuff like this?

Specifically, are there methods these folks use to systematically root out such knowledge, explore it and internalize it (make it their own)?


问:
I can write code... but can't design well. Any suggestions?
I feel that I am good at writing code in bits and pieces, but my designs really suck. The question is, how do I improve my designs - and in turn become a better designer?

I think schools and colleges do a good job of teaching people how to become good at mathematical problem solving, but let's admit the fact that most applications created at school are generally around 1000 - 2000 lines long, which means that it is mostly an academic exercise which doesn't reflect the complexity of real world software - on the order of a few hundred thousand to millions of lines of code.

This is where I believe that even projects like topcoder / project euler also won't be of much help, they might sharpen your mathematical problem solving ability - but you might become an academic programmer; someone who is more interested in the nice, clean stuff, who is utterly un-interested in the day to day mundane and hairy stuff that most application programmers deal with.

So my question is how do I improve my design skills? That is, the ability to design small/medium scale applications that will go into a few thousand of lines of code? How can I learn design skills that will help me build a better html editor kit, or some graphics program like gimp?

答: Stop designing and learn to refactor code.  Incremental development with continuous and aggressive refactoring will result in a much cleaner end product than any up-front design.</p>


问:
How should I pitch moving to an agile/iterative development cycle with mandated 3-week deployments?
I'm part of a small team of four, and I'm the unofficial team lead (I'm lead in all but title, basically).  We've largely been a "cowboy" environment, with no architecture or structure and everyone doing their own thing.  Previously, our production deployments would be every few months without being on a set schedule, as things were added/removed to the task list of each developer.  Recently, our CIO (semi-technical but not really a programmer) decided we will do deployments every three weeks; because of this I instantly thought that adopting an iterative development process (not necessarily full-blown Agile/XP, which would be a huge thing to convince everyone else to do) would go a long way towards helping manage expectations properly so there isn't this far-fetched idea that any new feature will be done in three weeks.

IMO the biggest hurdle is that we don't have ANY kind of development approach in place right now (among other things like no CI or automated tests whatsoever).  We don't even use Waterfall, we use "Tell Developer X to do a task, expect him to do everything and get it done".

Are there any pointers that would help me start to ease us towards an iterative approach and A) Get the other developers on board with it and B) Get management to understand how iterative works?  So far my idea involves trying to set up a CI server and get our build process automated (it takes about 10-20 minutes right now to simply build the application to put it on our development server), since pushing tests and/or TDD will be met with a LOT of resistance at this point, and constantly force us to break larger projects into smaller chunks that could be done iteratively in a three-week cycle; my only concern is that, unless I'm misunderstanding, an agile/iterative process may or may not release the software (depending on the project scope you might have "working" software after three weeks, but there isn't enough of it that works to let users make use of it), while I think the expectation here from management is that there will always be something "ready to go" in three weeks, and that disconnect could cause problems.

On that note, is there any literature or references that explains the agile/iterative approach from a business standpoint?  Everything I've seen only focuses on the developers, how to do it, but nothing seems to describe it from the perspective of actually getting the buy-in from the businesspeople.

答:
Craig Larman's Agile and Iterative Development: A Manager's Guide is a great manager/business based overview of agile and iterative development.  I recommend it highly.

Other than that, I second @MichaelDurrant --talk about this with your CIO.


问:
How to make sure the application source code has a proper documentation for new programmers?

Possible Duplicate:

  How much documentation is enough?

Do you know how the big IT company like IBM, Microsoft, or google make sure their application source code has proper documentation for future new programmers? What are their methods or tecniques? Do they tell the programmers to write documentation or hire a specialized technical writer to do that? Is the documenation in a separate file or in the source code itself (in form of annotation/comment)? Or is it another method that I don't know?

I ask that because in my experience, I see most of the IT companies (in my country) are very lazy to impose the application-documentation-writing culture. So the problem always happens when a new programmer comes in, he will always face a situation where he is told to read and learn big chunks of source code with no documentation. Of course, he can ask the senior programmers to explain him, but sometimes the senior programmers are too busy with their works so they reluctantly want to help you, and sometimes it could be worse that the only one programmers that understand the code has already resigned. So you are left alone with the source code :(.

Somehow I can understand the laziness of programmer to write comment or documentation, because the programmer's jobs are already arduous and tedious with their coding and testing sessions. Not mention the deadline-bell or angry boss that always haunting behind them. I can't imagine how painful and tiring for the programmer when after their long session of code-typing, they have to type again for the documentation.

For technical writers, I never had a experience with them. I doubt how technical writer can be useful, because the one who fully understand the source code is the programmer himself. In that case, the programmer must accompany the tecnical writer to explain the source code.

Note: I'm talking about source code or application development documentation, not the user documentation/guide which I think it's more properly written by system analyst or business analyst. The development documentation usually contains technical information about the development of the application such as: application features, class/function reference, class relationship diagram, database information, network information, etc. While user documentation is more about application's how-to information for the end-users.

答:
I don't like documentation. It can lie, the code can't. By all means have documentation on the higher level concepts of the application, but documenting code? That's a big sign that your code is not clear.

I do however code in a high level language (C# mainly) that is pseudo English, others using more lower level may disagree.


问:
When to do code reviews when doing continuous integration?
We are trying to switch to a continuous integration environment but are not sure when to do code reviews. From what I've read of continuous integration, we should be attempting to check in code as often as multiple times a day.  I assume, this even means for features that are not yet complete.

So the question is, when do we do the code reviews?

We can't do it before we check in the code, because that would slow down the process where we will not be able to do daily checkins, let alone multiple checkins per day.

Also, if the code we are checking in merely compiles but is not feature complete, doing a code review then is pointless, as most code reviews are best done as the feature is finalized.  Does this mean we should do code reviews when a feature is completed, but that unreviewed code will get into the repository?

答:
Decouple code review and continuous integration! </p>

<p>Why you combined them? </p>

OwnerDisplayName: SpecialEd

Body:
Decouple code review and continuous integration!

Why you combined them?


问:
Interfacing application code with unit tests
I am working on a project in which we have to implement and unit test
some new module.
I had a quite clear architecture in mind so I quickly wrote down the main
classes and methods and then we started writing unit tests.

While writing the tests we had to make quite a few modifications to
the original code, such as

Making private methods public in order to test them

Adding extra methods to access private variables

Adding extra methods to inject mock objects that should be used when the code runs inside a unit test.

Somehow I have the feeling that these are symptoms that we are doing something wrong, e.g.

the initial design was wrong (some functionalities should have been public from the beginning),

the code was not designed properly for being interfaced with unit tests (maybe due to the fact that we started to design the unit tests when quite a few classes had been designed already),

we are implementing unit tests the wrong way (e.g. unit tests should only directly test / address the public methods of an API, not the private ones),

a mixture of the above three points, and maybe some additional issues I have not thought about.

Since I have some experience with unit testing but I am far from being a guru, I would be very interested to read your thoughts regarding these issues.

Beside the above general questions, I have some more specific,
technical questions:

Question 1. Does it make sense to directly test a private method m of a class A and even make it public in order to test it? Or should I assume that m is indirectly tested by unit tests covering other, public methods that call m?

Question 2. If an instance of class A contains an instance of class B (composite aggregation), does it make sense to mock B in order to test A? My first idea was that I should not mock B because the B instance is part of the A instance, but then I started to doubt about this. My argument against mocking B is the same as for 1: B is private wrt A and only used for its implementation, therefore mocking B seems like I am exposing private details of A like in (1).
But maybe these problems indicate a design flaw: maybe we should not use composite aggregation but a plain association from A to B.

Question 3. In the above example, if we do decide to mock B, how do we inject the B instance into A? Here are some ideas we had:

Inject the B instance as an argument to the A constructor instead of creating the B instance in the A constructor.

Pass a BFactory interface as an argument to the A constructor and let A use the factory to create its private B instance.

Use a BFactory singleton that is private to A. Use a static method A::setBFactory() to set the singleton. When A wants to create the B instance it uses the factory singleton if it is set (the test scenario), it creates B directly if the singleton is not set (the production code scenario).

The first two alternatives seem cleaner to me, but they require changing
the signature of the A constructor: changing an API just to make it more testable seems awkward to me, is this a common practice?

The third one has the advantage that it does not require changing the signature of the constructor (the change to the API is less invasive), but it requires calling the static method setBFactory() before starting the test, which is IMO error-prone (implicit dependency on a method call for the tests to work properly). So I do not know which one we should choose.

答:
I think testing public methods are enough most of the time.

If you have a great deal of complexity in your private methods, then consider putting them in another class as public methods and use them as private calls to those methods in your original class. This way you can ensure both methods in your original and utility classes  work correctly.

Relying heavily on private methods is something to consider about design desicions.


问:
Scheme Stream Implementation
After working my way through SICP I decided to work though some Project Euler problems using scheme. In this particular problem I am trying to generate an infinite stream of integers however I am recieving an error from the MIT Scheme interpreter.

```<code>;Aborting!: maximum recursion depth exceeded
</code>```

This leads me to believe my stream implementation is incorrect however after comparing my code against that in the book I can not find any errors.

```<code>(define (delay x)
  (lambda ()
    (x)))

(define (force x)
  (x))

(define (cons-stream a b)
  (cons a (delay b)))

(define (car-stream s)
  (car s))

(define (cdr-stream s)
  (force (cdr s)))

(define (integers-starting-from n)
  (cons-stream n (integers-starting-from (+ n 1))))
</code>```

The error occurs when I run the following code:

```<code>(define n (integers-starting-from 1))
</code>```

Where have I gone wrong?

EDIT:

Thanks to Chris Jester-Young below I have it working now. The correct implementation of delay and stream are as follows.

```<code>(define-syntax delay
  (syntax-rules ()
    ((delay expr)
     (lambda ()
       (expr))))

(define-syntax stream
  (syntax-rules ()
    ((stream a b)
     (cons a (delay b)))))
</code>```

答:
Another way to fix your code is to embed the recursive call to integers-starting-from in a lambda:

```<code>    (define (integers-starting-from n)
      (cons-stream n (lambda () (integers-starting-from (+ n 1)))))
</code>```

This allows you to keep the definitions of delay and cons-stream as they are in SICP.

Title: Scheme Stream Implementation

Body:
Another way to fix your code is to embed the recursive call to integers-starting-from in a lambda:

    (define (integers-starting-from n)
      (cons-stream n (lambda () (integers-starting-from (+ n 1)))))

This allows you to keep the definitions of delay and cons-stream as they are in SICP.


问:
At which point do you "know" a technology enough to list it on a resume
I recently had a programmer in for an interview, who listed Python, PHP, Rails and ASP as a few of their skills. In the interview however, they interviewee didn't enough know what control structures and basic logic were, they had only followed a few demo tutorials.

So my question is this: At which point can you add a technology to your resume accurately. Is it when you can demonstrate all basic concepts, write a useful program in it, or are just comfortable using it without having to refer to the documentation every 30 seconds.

I don't believe this is overly subjective, a baseline should easily be established based on feedback.

答:
I only list skills that I have used in a project.

I don't like the idea of putting my idea of my skill in a technology on my CV, mark out of 5 etc, I've interviewed to many people who mark themselves much higher than they are.

I prefer if interviewing to ask and ask why they say that level or if being interviewed to be asked about where and why I rate myself as a 5/5.


问:
Filesystem like permissions for C++ type-members

Abstract (tl;dr)

Please read the full question, this is awfully simplified:

How can unix file permission style restrictions be applied to inter-type data/control flows, allowing fine-grained access to some class-members for some groups of classes?

Background information

If you think about unix file systems and permissions, there is a diverse way of encoding file-access privileges of users (especially if you also consider FACL). For example, if a directory contains 3 files, they could belong to several users, and different other users may have restricted permissions:

```<code>-rwxr-xr--  jean-luc  staff    engage.sh
-rw-r-----  william   crew     roster.txt
-rw-------  beverly   beverly  patients.txt
</code>```

Core idea

As you can see, depending on the groups a particular user is in, different access levels are allowed. For example, crewmembers are allowed to read roster.txt, which belongs to william, but guests who presumably do not belong to crew cannot. More importantly, the group crew can contain many people.

So I was thinking that there is some similarity to access permissions inside object oriented languages like C++ if you think of types (classes) as users. Although a function can only be executed, but not read, the rwx flags represent meaningful descriptions for class members. A data member can be read (r) and written (w) to, perhaps via accessors, while member functions may be executed (x) or not.

However, in C++ and other object oriented languages (I know of), this is more or less an all or nothing thing, if we leave out inheritance for a second; If class William makes his member Txt roster; public, everybody will see it. If he makes it private, nobody except himself will see it. He may add one or more friends, friend JeanLuc; but then they will see all his private members (the equivalent of granting user:jean-luc:rwx to all his files, in FACL lingo).

This is entirely orthogonal to inheritance -- JeanLuc and William are not part of the same hierarchy, they are not related.

So the main idea would be to allow group-based access restrictions, as a generalisation of private/public. Allowing finer grained inter-class access to member functions and member data.

I believe this idiom could help maintainability/readability, as it adds additional facets to restrict interaction permissions.
As with operating systems, where this adds an important layer of security to the system, the same familiar pattern could add safety to a C++ project.

Thoughts about representation in C++

However, I'm at a loss of thinking of a good way to represent this. You could decompose William objects into several objects of subtypes: William_Crew, William_William and so forth, representing the respective groups. This seems to be horribly ugly. Another idea could be dedicated types with forwarder functions, representing the individual groups, like this:

```<code>class Crew { // group class
  // in this group are:
  friend JeanLuc;
  friend Geordi;
  friend Beverly;
  // ...
  static Txt getRoster(William*);
};
class William {
  friend Crew; // Problem: Crew has full access (rwx)
  Txt roster;
};
</code>```

But each group would have to be tailored to a particular class to be used with, which would seem to be massively redundant, if the group is used by several users/classes.

Question

The approaches I provided are not great (to put it mildly), and I'm sure they wouldn't work as intended. I'm not sure if this is a novel/stupid/well-known idea, but I wonder how you could implement this with the features provided by the C++ language. Are there objective arguments why this would or would not be useful/helpful?

答:
Ok, I think the obvious solution is to implement visitor pattern:

```<code>struct Crew
{
    virtual void setRoster(Txt roster) = 0;
    virtual ~Crew(){}
};

class William
{
public:
    void getRoster(Crew& crew) { crew.setRoster(roster); }
private:
    Txt roster;
}
</code>```

Since somebody implement Crew, it "joins Crew group".

EDIT
if you want some more general case, you can invent some security descriptors, but I think it overcomplication:

```<code>class  CrewDescriptorRead
{
protected:
    CrewDescriptorRead(){}
    friend class User;
};

class CrewDescriptorWrite
{
protected:
    CrewDescriptorWrite(){}
    friend class User;
};

class CrewDescriptorFullAccess: public CrewDescriptorRead, public CrewDescriptorWrite
{
public:
    CrewDescriptorFullAccess(const CrewDescriptorRead&, const CrewDescriptorWrite&){}
};

class William
{
public:
    Txt getRoster(const CrewDescriptorRead& ) const {return roster;}
private:
    Txt roster;
};

struct User
{
    void f()
    {
        William w;
        w.getRoster(CrewDescriptorFullAccess(CrewDescriptorRead(), CrewDescriptorWrite()));
    }
};

struct UnAutorized
{
    void f()
    {
        William w;
        w.getRoster(CrewDescriptorFullAccess(CrewDescriptorRead(), CrewDescriptorWrite()));
        //OOps, I'm not friend
    }
};
</code>```

Or, if you absolutely paranoid,

```<code>class  CrewDescriptorRead
{
private:
    CrewDescriptorRead(){}
    friend class User;
    friend class CrewDescriptorFullAccess;
};

class CrewDescriptorWrite
{
private:
    CrewDescriptorWrite(){}
    friend class User;
    friend class CrewDescriptorFullAccess;
};

class CrewDescriptorFullAccess
{
public:
    CrewDescriptorFullAccess(const CrewDescriptorRead&, const CrewDescriptorWrite&){}
    operator CrewDescriptorRead() { return CrewDescriptorRead(); }
    operator CrewDescriptorWrite() { return CrewDescriptorWrite(); }
};
</code>```

OwnerDisplayName: bitmask

Body:
Ok, I think the obvious solution is to implement visitor pattern:

struct Crew
{
    virtual void setRoster(Txt roster) = 0;
    virtual ~Crew(){}
};

class William
{
public:
    void getRoster(Crew& crew) { crew.setRoster(roster); }
private:
    Txt roster;
}

Since somebody implement Crew, it "joins Crew group".

EDIT
if you want some more general case, you can invent some security descriptors, but I think it overcomplication:

class  CrewDescriptorRead
{
protected:
    CrewDescriptorRead(){}
    friend class User;
};

class CrewDescriptorWrite
{
protected:
    CrewDescriptorWrite(){}
    friend class User;
};

class CrewDescriptorFullAccess: public CrewDescriptorRead, public CrewDescriptorWrite
{
public:
    CrewDescriptorFullAccess(const CrewDescriptorRead&, const CrewDescriptorWrite&){}
};

class William
{
public:
    Txt getRoster(const CrewDescriptorRead& ) const {return roster;}
private:
    Txt roster;
};

struct User
{
    void f()
    {
        William w;
        w.getRoster(CrewDescriptorFullAccess(CrewDescriptorRead(), CrewDescriptorWrite()));
    }
};

struct UnAutorized
{
    void f()
    {
        William w;
        w.getRoster(CrewDescriptorFullAccess(CrewDescriptorRead(), CrewDescriptorWrite()));
        //OOps, I'm not friend
    }
};

Or, if you absolutely paranoid,

class  CrewDescriptorRead
{
private:
    CrewDescriptorRead(){}
    friend class User;
    friend class CrewDescriptorFullAccess;
};

class CrewDescriptorWrite
{
private:
    CrewDescriptorWrite(){}
    friend class User;
    friend class CrewDescriptorFullAccess;
};

class CrewDescriptorFullAccess
{
public:
    CrewDescriptorFullAccess(const CrewDescriptorRead&, const CrewDescriptorWrite&){}
    operator CrewDescriptorRead() { return CrewDescriptorRead(); }
    operator CrewDescriptorWrite() { return CrewDescriptorWrite(); }
};


答:
Rephrasing the problem a bit:

I have an instance of MySpecialObject

an instance of JLP wants to call the methods of MySpecialObject

an instance of BEV wants to read the public data of MySpecialObject

the instance of JLP shouldn't be able to read public data and the BEV shouldn't be able to call member functions

This should be as type-safe as possible.

A solution I see involves wrappers :)

you write the code for MySpecialObject as you would normally, ignoring this extra requirement

you write a wrapper for each aspect of your class you wish to restrict. Say, MySpecialObject_Read and MySpecialObject_Execute.

these wrappers forward the requests (method calls, getter/setters) to an underlying shared_ptr of MySpecialObject

your  MySpecialObject, MySpecialObject_Read and MySpecialObject_Execute classes each have (as needed) a "convert to ..."  method. This method returns an appropriate wrapper over the underlying MySpecialObject

This solution provides a type-safe accessor with the desired limitations.

Each client class can choose what kind of access it needs.
(And since you write these classes, you know what access you need.)
If that is not acceptable, you could add factories that only create wrappers with certain limitations depending on a "token". That token might be the RTTI information of the calling class instance, although this could be abused.

Does this solve the original problem?

EDIT:

Remember that since you are the programmer you can instantiate an A whenever you want. By adding your class to a friend list or whatever...

What this solution provides is a clearer interface. Removing the explicit conversions probably makes it safer but less flexible. But, since they are explicit, you can easily look for them in the code and treat them as signs your architecture has a flaw somewhere.

Specifically, you can have code like this:

```<code>shared_ptr<A> * a = new A(parameters);

A_read aRead(a);
A_execute aExec(a);
A_write aWrite(aExec);

logger->Log(aRead);
view->SetUserData(aWrite);
controller->Execute(aExec);
</code>```

Here there is an explicit conversion between an execute wrapper and a write wrapper, but you can decide on this based on your specific requirements.

But, with little effort (knowing which conversions are valid), just by looking at the call locations you can see that (with confidence!):

the logger will not change the state of your A

the view will not call methods on your A (other than setters)

This is true even if those particular method calls end up calling hundreds of other methods, more than you'd like to examine by hand.

At the cost of a few thin wrappers you gain the ability to see at a glance what a particular function call will do with the parameters you send. This may help a lot during debugging by helping you eliminate some branches from your investigation and, in general, would help people trying to understand the program.

I couldn't really find other reasons for using this ACL idea, at least ones where the costs don't outweigh the benefits. However, it does seem more intuitive than the visitor solution mentioned in the other answer.

Title: Filesystem like permissions for C++ type-members

Body:
Abstract (tl;dr)

Please read the full question, this is awfully simplified:

How can unix file permission style restrictions be applied to inter-type data/control flows, allowing fine-grained access to some class-members for some groups of classes?

Background information

If you think about unix file systems and permissions, there is a diverse way of encoding file-access privileges of users (especially if you also consider FACL). For example, if a directory contains 3 files, they could belong to several users, and different other users may have restricted permissions:

```<code>-rwxr-xr--  jean-luc  staff    engage.sh
-rw-r-----  william   crew     roster.txt
-rw-------  beverly   beverly  patients.txt
</code>```

Core idea

As you can see, depending on the groups a particular user is in, different access levels are allowed. For example, crewmembers are allowed to read roster.txt, which belongs to william, but guests who presumably do not belong to crew cannot. More importantly, the group crew can contain many people.

So I was thinking that there is some similarity to access permissions inside object oriented languages like C++ if you think of types (classes) as users. Although a function can only be executed, but not read, the rwx flags represent meaningful descriptions for class members. A data member can be read (r) and written (w) to, perhaps via accessors, while member functions may be executed (x) or not.

However, in C++ and other object oriented languages (I know of), this is more or less an all or nothing thing, if we leave out inheritance for a second; If class William makes his member Txt roster; public, everybody will see it. If he makes it private, nobody except himself will see it. He may add one or more friends, friend JeanLuc; but then they will see all his private members (the equivalent of granting user:jean-luc:rwx to all his files, in FACL lingo).

This is entirely orthogonal to inheritance -- JeanLuc and William are not part of the same hierarchy, they are not related.

So the main idea would be to allow group-based access restrictions, as a generalisation of private/public. Allowing finer grained inter-class access to member functions and member data.

I believe this idiom could help maintainability/readability, as it adds additional facets to restrict interaction permissions.
As with operating systems, where this adds an important layer of security to the system, the same familiar pattern could add safety to a C++ project.

Thoughts about representation in C++

However, I'm at a loss of thinking of a good way to represent this. You could decompose William objects into several objects of subtypes: William_Crew, William_William and so forth, representing the respective groups. This seems to be horribly ugly. Another idea could be dedicated types with forwarder functions, representing the individual groups, like this:

```<code>class Crew { // group class
  // in this group are:
  friend JeanLuc;
  friend Geordi;
  friend Beverly;
  // ...
  static Txt getRoster(William*);
};
class William {
  friend Crew; // Problem: Crew has full access (rwx)
  Txt roster;
};
</code>```

But each group would have to be tailored to a particular class to be used with, which would seem to be massively redundant, if the group is used by several users/classes.

Question

The approaches I provided are not great (to put it mildly), and I'm sure they wouldn't work as intended. I'm not sure if this is a novel/stupid/well-known idea, but I wonder how you could implement this with the features provided by the C++ language. Are there objective arguments why this would or would not be useful/helpful?

Body:
Rephrasing the problem a bit:

I have an instance of MySpecialObject

an instance of JLP wants to call the methods of MySpecialObject

an instance of BEV wants to read the public data of MySpecialObject

the instance of JLP shouldn't be able to read public data and the BEV shouldn't be able to call member functions

This should be as type-safe as possible.

A solution I see involves wrappers :)

you write the code for MySpecialObject as you would normally, ignoring this extra requirement

you write a wrapper for each aspect of your class you wish to restrict. Say, MySpecialObject_Read and MySpecialObject_Execute.

these wrappers forward the requests (method calls, getter/setters) to an underlying shared_ptr of MySpecialObject

your  MySpecialObject, MySpecialObject_Read and MySpecialObject_Execute classes each have (as needed) a "convert to ..."  method. This method returns an appropriate wrapper over the underlying MySpecialObject

This solution provides a type-safe accessor with the desired limitations.

Each client class can choose what kind of access it needs.
(And since you write these classes, you know what access you need.)
If that is not acceptable, you could add factories that only create wrappers with certain limitations depending on a "token". That token might be the RTTI information of the calling class instance, although this could be abused.

Does this solve the original problem?

EDIT:

Remember that since you are the programmer you can instantiate an A whenever you want. By adding your class to a friend list or whatever...

What this solution provides is a clearer interface. Removing the explicit conversions probably makes it safer but less flexible. But, since they are explicit, you can easily look for them in the code and treat them as signs your architecture has a flaw somewhere.

Specifically, you can have code like this:

shared_ptr<A> * a = new A(parameters);

A_read aRead(a);
A_execute aExec(a);
A_write aWrite(aExec);

logger->Log(aRead);
view->SetUserData(aWrite);
controller->Execute(aExec);

Here there is an explicit conversion between an execute wrapper and a write wrapper, but you can decide on this based on your specific requirements.

But, with little effort (knowing which conversions are valid), just by looking at the call locations you can see that (with confidence!):

the logger will not change the state of your A

the view will not call methods on your A (other than setters)

This is true even if those particular method calls end up calling hundreds of other methods, more than you'd like to examine by hand.

At the cost of a few thin wrappers you gain the ability to see at a glance what a particular function call will do with the parameters you send. This may help a lot during debugging by helping you eliminate some branches from your investigation and, in general, would help people trying to understand the program.

I couldn't really find other reasons for using this ACL idea, at least ones where the costs don't outweigh the benefits. However, it does seem more intuitive than the visitor solution mentioned in the other answer.

OwnerDisplayName: Andrei


答:
To Question 1: That depends. Typically, you start with unit tests for public methods. Sometimes you encounter a method m you want to keep private to A, but you think that it makes sense to test m in isolation either. If that's the case, you should either make m  public or make the test class TestA a friend class of A. But beware, adding a unit test for testing m makes it a little bit harder to change the signature or the behaviour of m afterwards; if you want to keep that an "implementation detail" of A, it may be better not to add a direct unit test.

Question 2: (C++ build-in) composite aggregation does not work well when it comes to mock out an instance. In fact, since the construction of the B happens implicitly in the constructor of A, you have no chance to inject the dependency from outside. If that is a problem depends on the way you want to test A: if you think it makes more sense to test A in isolation, with a mock of B instead of B, better use a plain association. If you think you can write all the needed unit tests for A without mocking out B, then a composite will probably be ok.

Question 3: changing an API to make things more testable is common as long as you don't have much code so far relying on that API. When you are doing TDD, you don't have to change you API afterwards to make things more testable, you start initially with an API designed for testability. If you want to change an API later to make things more testable, you may encounter problems, that's true. So I would go with the first or second of the alternatives you described as long as you can change your API painlessly, and use something like your third alternative (remark: this works also without the singleton pattern) only as a last resort if I must not change the API under any circumstances.

About your concerns that you might "do it wrong": every big engine or machine has maintenance openings, so IMHO the need of adding something like that to software is not too surprising.

Title: Interfacing application code with unit tests

Body:
I am working on a project in which we have to implement and unit test
some new module.
I had a quite clear architecture in mind so I quickly wrote down the main
classes and methods and then we started writing unit tests.

While writing the tests we had to make quite a few modifications to
the original code, such as

Making private methods public in order to test them

Adding extra methods to access private variables

Adding extra methods to inject mock objects that should be used when the code runs inside a unit test.

Somehow I have the feeling that these are symptoms that we are doing something wrong, e.g.

the initial design was wrong (some functionalities should have been public from the beginning),

the code was not designed properly for being interfaced with unit tests (maybe due to the fact that we started to design the unit tests when quite a few classes had been designed already),

we are implementing unit tests the wrong way (e.g. unit tests should only directly test / address the public methods of an API, not the private ones),

a mixture of the above three points, and maybe some additional issues I have not thought about.

Since I have some experience with unit testing but I am far from being a guru, I would be very interested to read your thoughts regarding these issues.

Beside the above general questions, I have some more specific,
technical questions:

Question 1. Does it make sense to directly test a private method m of a class A and even make it public in order to test it? Or should I assume that m is indirectly tested by unit tests covering other, public methods that call m?

Question 2. If an instance of class A contains an instance of class B (composite aggregation), does it make sense to mock B in order to test A? My first idea was that I should not mock B because the B instance is part of the A instance, but then I started to doubt about this. My argument against mocking B is the same as for 1: B is private wrt A and only used for its implementation, therefore mocking B seems like I am exposing private details of A like in (1).
But maybe these problems indicate a design flaw: maybe we should not use composite aggregation but a plain association from A to B.

Question 3. In the above example, if we do decide to mock B, how do we inject the B instance into A? Here are some ideas we had:

Inject the B instance as an argument to the A constructor instead of creating the B instance in the A constructor.

Pass a BFactory interface as an argument to the A constructor and let A use the factory to create its private B instance.

Use a BFactory singleton that is private to A. Use a static method A::setBFactory() to set the singleton. When A wants to create the B instance it uses the factory singleton if it is set (the test scenario), it creates B directly if the singleton is not set (the production code scenario).

The first two alternatives seem cleaner to me, but they require changing
the signature of the A constructor: changing an API just to make it more testable seems awkward to me, is this a common practice?

The third one has the advantage that it does not require changing the signature of the constructor (the change to the API is less invasive), but it requires calling the static method setBFactory() before starting the test, which is IMO error-prone (implicit dependency on a method call for the tests to work properly). So I do not know which one we should choose.


问:
how to structure MVC models and ORM models
I have some trouble getting a good folder structure in my project and i would like to know what other ways i could use to structure my files.

I'm currently working in an MVC sturctured folder.

```<code>www/
  Controllers/
  Models/
  Views/
</code>```

Nothing special so far. But i'm also using an ORM system. With it i can easily get an 'object' from my database like:

```<code>ORM::load('table');
</code>```

Now this sort of code should reside in a Model right? So i'd get something like this:

```<code><?php
class userModel
{
    public function getAllUsers ( )
    {
        return ORM::load('table');
    }

    public function getUserById ( $id )
    {
        return ORM::load('table', 'userid=?', array($id));
    }
}
?>
</code>```

Looks good so far in my opinion... But there's one more thing. I can also specify a 'model' when using the ORM system. With this model i can basically set up validation rules. Like so:

```<code>ORM::withModel('authModel');
</code>```

This lets the ORM know that before it adds a new row (or updates an existing one) to the DB, that it should check the following model first for validation rules.

```<code><?php
class authModel //Or maybe authValidation??
{
    // Method gets automatically triggered when an update is done with the ORM
    public function onUpdate ( $obj )
    {
        if ( $obj->username == '' )
            throw new \Exception('No username');
    }

    public function onInsert ( $obj )
    {
        // Validations here too.
    }
}
?>
</code>```

Now the problem is, is that i have 2 sorts of models. One where i basically use getters/setters to get and store data to the database (from my controller to my model).

And i have another model in which validation rules are set... I don't want to mix both in the same folder. So i must come up with another structure for this. Something like:

```<code>www/
  Controllers/
  Models/
    Repositories/
    Entities/
  Views/
</code>```

It's just that my model isn't a real 'repository', since it doesn't store any objects in the repo class and doesn't have a commit() method or anything like that.

I also can't store the 2nd model (for validations) in the Entities folder, because they're not Entities at all...

Any idea how i should structure this..??

答: Just rename "Repositories" "Validations" or "Rules" and it all makes sense again.</p>


答:
In one word - Process. I work in the aerospace industry, there is a process that requires certain artifacts are generated as part of the software development cycle. Yet another process within QA ensures that these artifacts are generated. A review process ensures the generated artifacts meet the required level of detail and accuracy. Yet another process emasures that success of the other processes etc.

It's far from perfect, it's not cheap, and takes a lot of effort to get anything done. It is possible for a developer to maintain a multi-million line code base without reading and understanding every line of code. I know of no other way to achieve this. The "code is gospel" coders fail miserably when faced with these life critical, real time complex systems. The documentation is not a 100% accurate reflection of what the code does, but it is closer description of what the code should do than the code. Therefore, if the code does not do what the doc say it should, the code is probably wrong.

We do not use tech writers; however, I believe we should - programmers are not always good writers of English, and empolying a tech writer to turn clumsy technobable into concise English would be a small investment for large gains IMHO.

Title: How to make sure the application source code has a proper documentation for new programmers?

Body:
Possible Duplicate:

  How much documentation is enough?

Do you know how the big IT company like IBM, Microsoft, or google make sure their application source code has proper documentation for future new programmers? What are their methods or tecniques? Do they tell the programmers to write documentation or hire a specialized technical writer to do that? Is the documenation in a separate file or in the source code itself (in form of annotation/comment)? Or is it another method that I don't know?

I ask that because in my experience, I see most of the IT companies (in my country) are very lazy to impose the application-documentation-writing culture. So the problem always happens when a new programmer comes in, he will always face a situation where he is told to read and learn big chunks of source code with no documentation. Of course, he can ask the senior programmers to explain him, but sometimes the senior programmers are too busy with their works so they reluctantly want to help you, and sometimes it could be worse that the only one programmers that understand the code has already resigned. So you are left alone with the source code :(.

Somehow I can understand the laziness of programmer to write comment or documentation, because the programmer's jobs are already arduous and tedious with their coding and testing sessions. Not mention the deadline-bell or angry boss that always haunting behind them. I can't imagine how painful and tiring for the programmer when after their long session of code-typing, they have to type again for the documentation.

For technical writers, I never had a experience with them. I doubt how technical writer can be useful, because the one who fully understand the source code is the programmer himself. In that case, the programmer must accompany the tecnical writer to explain the source code.

Note: I'm talking about source code or application development documentation, not the user documentation/guide which I think it's more properly written by system analyst or business analyst. The development documentation usually contains technical information about the development of the application such as: application features, class/function reference, class relationship diagram, database information, network information, etc. While user documentation is more about application's how-to information for the end-users.


答:
I'm not aware of anyone using tech writers for purely internal documentation, the problem, especially for lower level stuff, with written documentation is keeping it in sync with what the code actually does, therefore written documentation is best target at the areas which are going to change the least i.e. the high level concepts of what the software does and why? what assumptions have been made, and what alternative designs have been discarded. Tests can be used to document the low level stuff and running them will tell you if they are in sync with the code.

For low level understanding of how a function/ method or class is meant to work unit tests are the best form of documentation for the simple reason that running them tells you whether they are in sync with the current code base or not. not something you can check with comments or text based documentation. automated unit tests are pretty much a must for many reasons anyway.

Integration and system tests can help document other things, how is the system envisaged to be used? what is the workflow an operator will use? automated integration and system tests are nice to have, but at the very least you want scripted manual tests. You may also need some additional description around this level if/when it is not possible to test every case, you then need to capture the intent some other way.

There are things that tests are not so good at documenting, architecture springs to mind. Architecture can be reasonably documented with UML, though in a low process shop 5 minutes with a whiteboard and an experienced dev is probably good enough.


答:
You should look up Dependency Injection and Inversion of Control. Misko Hevery explains a lot of it on his blog. DI and IoC is effectively a design pattern for making code that is easy to unit test and mock.

Question 1: No, do not make private methods public to test them. If the method is sufficiently complex, you can create a collaborator class that contains just that method, and inject it (pass into the constructor) into your other class. 1

Question 2: Who constructs A in this case? If you have a factory/builder class that constructs A, then there is no harm in passing the collaborator B into the constructor. If A is in a separate package/namespace from the code that uses it, you can even make the constructor package-private and make it so the factory/builder is the only class that can construct it.

Question 3: I answered this in Question 2. Some extra notes though:

Using a builder/factory pattern allows you to do dependency injection as much as you want, without having to worry about making code using your class difficult to use.

It separates object construction time from object use time which means that code using your API can be simpler.

1 This is the C#/Java answer - C++ may have extra features that facilitate this

As an answer to your comments:

What I meant was that your production code would be changed from (please forgive my pseudo-C++):

```<code>void MyClass::MyUseOfA()
{
  A* a = new A();
  a->SomeMethod();
}

A::A()
{
  m_b = new B();
}
</code>```

to:

```<code>void MyClass::MyUseOfA()
{
  A* a = AFactory.NewA();
  a->SomeMethod();
}

A* AFactory::NewA()
{
  // Construct dependencies
  B* b = new B();
  return new A(b);
}

A::A(B* b)
{
  m_b = b;
}
</code>```

Then your test can be:

```<code>void MyTest::TestA()
{
  MockB* b = new MockB();
  b->SetSomethingInteresting(somethingInteresting);

  A* a = new A(b);

  a->DoSomethingInteresting();

  b->DidSomethingInterestingHappen();
}
</code>```

In this way, you don't need to pass the factory around, the code calling A doesn't need to know how to construct A, and the test can custom-construct A to allow behaviour to be tested.

In your other comment, you asked about nested dependencies. So, for example, if your dependencies were:

A -> C -> D -> B

The first question to ask is if A uses C and D. If they aren't, why are they included in A? Assuming they are used, then perhaps it is necessary to pass in C in your factory, and have your test construct a MockC that returns a MockB, allowing you to test all possible interactions.

If this is starting to get complicated, it might be a sign that your design is perhaps coupled too tightly. If you can loosen the coupling and keep cohesion high then this kind of DI becomes easier to implement.

Body:
You should look up Dependency Injection and Inversion of Control. Misko Hevery explains a lot of it on his blog. DI and IoC is effectively a design pattern for making code that is easy to unit test and mock.

Question 1: No, do not make private methods public to test them. If the method is sufficiently complex, you can create a collaborator class that contains just that method, and inject it (pass into the constructor) into your other class. 1

Question 2: Who constructs A in this case? If you have a factory/builder class that constructs A, then there is no harm in passing the collaborator B into the constructor. If A is in a separate package/namespace from the code that uses it, you can even make the constructor package-private and make it so the factory/builder is the only class that can construct it.

Question 3: I answered this in Question 2. Some extra notes though:

Using a builder/factory pattern allows you to do dependency injection as much as you want, without having to worry about making code using your class difficult to use.

It separates object construction time from object use time which means that code using your API can be simpler.

1 This is the C#/Java answer - C++ may have extra features that facilitate this

As an answer to your comments:

What I meant was that your production code would be changed from (please forgive my pseudo-C++):

void MyClass::MyUseOfA()
{
  A* a = new A();
  a->SomeMethod();
}

A::A()
{
  m_b = new B();
}

to:

void MyClass::MyUseOfA()
{
  A* a = AFactory.NewA();
  a->SomeMethod();
}

A* AFactory::NewA()
{
  // Construct dependencies
  B* b = new B();
  return new A(b);
}

A::A(B* b)
{
  m_b = b;
}

Then your test can be:

void MyTest::TestA()
{
  MockB* b = new MockB();
  b->SetSomethingInteresting(somethingInteresting);

  A* a = new A(b);

  a->DoSomethingInteresting();

  b->DidSomethingInterestingHappen();
}

In this way, you don't need to pass the factory around, the code calling A doesn't need to know how to construct A, and the test can custom-construct A to allow behaviour to be tested.

In your other comment, you asked about nested dependencies. So, for example, if your dependencies were:

A -> C -> D -> B

The first question to ask is if A uses C and D. If they aren't, why are they included in A? Assuming they are used, then perhaps it is necessary to pass in C in your factory, and have your test construct a MockC that returns a MockB, allowing you to test all possible interactions.

If this is starting to get complicated, it might be a sign that your design is perhaps coupled too tightly. If you can loosen the coupling and keep cohesion high then this kind of DI becomes easier to implement.


问:
Grouping numbers to minimize group-means
I need to find a way or an algorithm that groups members of a given data set (of positive integers) so that the difference between group means is minimized (not maximized, as usual).

There are two constraints:

The number of groups should not exceed log(N) base 2. N is the input array size. Let us assume that N = 16, always.

The size of the group should be at least log(N) base 2. In the below example, the size of the group should be at least 4.

By searching on the WEB, I have found the following greedy algorithm. Please also see below example.

sort the numbers in the descending order

take the first K elements and put them into different groups. Here, K is the number of groups.

for the next (N - K) elements, put them in the group with the lowest sum. repeat this until completion of all the numbers.

Can we get a better algorithm in terms of time complexity? Guidance toward a  better solution to this problem is appreciated.

Example:

```<code>for input array = (11, 11, 14, 16, 17, 18, 18, 19, 20, 21, 22, 25, 25, 26, 28, 31)

The solution:  (where sd: standard deviation, cv: coefficient of variation)

    group           mean    sd  cv
(31, 20, 17, 11)    19.8    8.4 0.4
(28, 21, 18, 11)    19.5    7.1 0.4
(26, 21, 19, 14)    20.0    5.0 0.3
(25, 22, 18, 16)    20.3    4.0 0.2
</code>```

答:
Intuitively, even though your constaints are relaxed, I think your problem is an instance of the bin packing problem, which is NP-hard. Perhaps you should ask the CS Theory group whether this is an instance of BPP/generalized BPP.

Your greedy algorithm works in linearithmic complexity (sorting in O(n log n), binning in O(n log log n), assuming using heaps, because your number of bins is ~ log n), but it is not optimal (easy to find sequences which trick it).

You can do a best-fit greedy in O(n log log n) - find the mean of the numbers in linear time (without sorting), and then for each number try to fit it in a bin such that current average stays as close as possible to the total average - this should be a log-logarithmic operation with respect to n. Whether this is an appropriate solution for your problem depends on how far from optimal you can afford to be.

However, note that you can't go better than this O(n log log n) - because whatever clever scheme you use, you will need to pick each element up, and bin it.


答:
I don’t share your appraisal of the benefits, and I suspect that this is the reason why it isn’t done: it would make the object system vastly more complex, for very little benefits.

But in general, permissions (r, w, x) are made explicit through the use of methods: rather than having a publicly accessible member, you provide explicit read or write access through getters and setters.

Of course, this doesn’t allow modelling users or groups (other than making one object a friend). Other programming languages allow restricting access to other classes within the same package (Java, default) or within the same assembly (C#, friend). A similar restriction is achieved in C++ by separating the project into different compilation units and using the compiler firewall (aka PIMPL) to restrict access of some aspects of a class to that compilation unit.

So in a way you do have different access modes, as well as different “user” groups. They are just not available in a unified model with terminiology similar to FACL, but you get the same effect.


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答:
I'm Italian and always use English, for names and comments. But many other Italian programmers use Italian language, or more often a strange English-Italian mix (something like IsUtenteCopy).

A real life code sample:

```<code>// Trovo la foto collegata al verbale
tblVerbali rsVerbale;
hr = rsVerbale.OpenByID(GetDBConn(), m_idVerbale);
if( FAILED(hr) )
    throw CErrorHR(hr);
hr = rsVerbale.MoveFirst();
if( S_OK != hr )
    throw CError(_T("Record del verbale non trovato."));
</code>```

By the way, the Visual Studio MFC wizard creates a skeleton application with localized comments:

```<code>BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
    if( !CMDIFrameWndEx::PreCreateWindow(cs) )
        return FALSE;
    // TODO: modificare la classe o gli stili Window modificando
    //  la struttura CREATESTRUCT

    return TRUE;
}
</code>```

Body:
I'm Italian and always use English, for names and comments. But many other Italian programmers use Italian language, or more often a strange English-Italian mix (something like IsUtenteCopy).

A real life code sample:

// Trovo la foto collegata al verbale
tblVerbali rsVerbale;
hr = rsVerbale.OpenByID(GetDBConn(), m_idVerbale);
if( FAILED(hr) )
    throw CErrorHR(hr);
hr = rsVerbale.MoveFirst();
if( S_OK != hr )
    throw CError(_T("Record del verbale non trovato."));

By the way, the Visual Studio MFC wizard creates a skeleton application with localized comments:

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
    if( !CMDIFrameWndEx::PreCreateWindow(cs) )
        return FALSE;
    // TODO: modificare la classe o gli stili Window modificando
    //  la struttura CREATESTRUCT

    return TRUE;
}


答:
Developers at big corporations like IBM, Microsoft, and Google follow code conventions to ensure well-written code and conduct code reviews to discover poorly-written code. Poorly-documented code qualifies as poorly-written code.

The primary source of technical documentation for software is the source code, any other documentation is secondary. Technical writers are typically employed to convey technical (and possibly marketing) info to users (brochures, manuals, and tutorials). Developers should be satisfied with well-written source code (and API documentation).

A well-practiced programmer should have mastered a habit of documenting their code during and not after coding (in the same manner that scientists document their experiments during-not-after). Code documentation should be correct, clear, and simple. Code itself should be self-explaining to reduce the need for long paragraphs of explanation.

There are tools you can use to generate API documentation from source files for popular programming languages like Java (javadoc), PHP (phpdoc), Python (pydoc), and Ruby (rdoc). And also tools that you can use to analyze your code for common coding mistakes including lack of documentation.