问:
Would adding an @beta doc-comment tag be useful?
When a function has reached the end of its life, we add a @deprecated tag into its doc-comment to notify other developers that they should stop using this function, and then a couple years later it's removed.

I was just thinking about an @beta tag to signify this method is brand new and hasn't been tested in a variety of use-cases yet.

You might be thinking "you can write use-cases to ensure its correctness!" Of course you can, but its the API that concerns me, and how it behaves in edge-cases. Sometimes these decisions are not obvious until you have tried out the function in a variety of situations. Sometimes new parameters need to be added to cover more use-cases. Sometimes re-ordering them makes sense if you find that an argument is actually optional and needs to be moved to the end (or vice versa).

By adding the @beta tag, you are warning other developers that the API of this method might change yet, and they should use it with extreme caution. This gives you more granular control over your API instead of making the entire project 'beta'.

To get the most use out of this, however, IDEs and documentation-generators would need to pick up on this tag.

What do you guys think? Could you see this as being useful, is it a waste of time, or do you have other ways of dealing with this?

In the past, I have made such methods 'private' where possible, or prefixed them with an underscore.

答: You shouldn't add untested or unstable features to a stable API. Instead, add them to a beta/testing branch and when they're tested enough, add them a new stable version. Otherwise, users of your stable API will have to constantly be checking whether or not the methods they're using a stable.</p>


问:
How can you add acknowledgement functionality to a Command pattern, given the response from receiver is gotten asynchronously on Server?
I have a scenario where I will implement Command pattern like described in this article.

Actually from an Asp.Net MVC view, some user will invoke different commands/actions like Start Live Video, Start Live Image, Start Recording etc.
A Web Socket Server will then receive these commands and dispatch them to a Receiver (a Windows based application). The receiver before executing the requested command, will first acknowledge the received command and will confirm back to sender that the sent command has been received for processing.

Note: The acknowledgement and/or the actual response will be returned to the Web Socket Server always in an asynchronous manner and then accordingly dispatched to the sender. Means whole system is event driven based.

So my question is:

Given the Command pattern described in the article, now which best way I could add Command Acknowledgement to it and will the returned acknowledgment and/or actual response be also in the form of some command/message or something else?

If we are to go something different for dispatching the Acknowledgement or response, then which pattern to use for it?

答:
I think that you are on the correct path way. You could modify the command pattern to pass a callback reference which will be used to notify the Invoker for the execution of the Command.

The abstract receiver would have an added ExecuteAndNotify hook method. This method would call the already existing Execute method on the ConcreteCommand and then execute the another added method called Notify. This Notify method would use the callback reference to notify the Invoker of the succesful execution of the command.

The callback reference could be a function pointer if the Invoker and the Receiver are classes in the same application. If they are parts of another service, it could be a URL of a "service".

Hope I helped!

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Pantelis Natsiavas


问:
Does Agile (scrum) require one server environment?
Is it necessary/recommend/best practice/any other positive to use only one server environment to perform all development, unit testing and QA?

If so, is it then wise/part of Agile to then have only one staging environment before Live?

Considering that this could mean internationally distributed teams of developers and testers in different time zones is this wise?

This is something being implemented by our QA manager. The opinion put forward is that doing all the dev and testing on a single server is "Agile." The staging environment would be a second environment, and then live.

答:
Although as Bart says, Agile might not dictate an environmental set-up, the values and principles do indicate best practices where code is aggregated and tested on an ongoing basis. That practice is in direct opposition to the gatepost approach in traditional waterfall environments. Transition through the gateposts suggests an approach is waterfall. High levels of automated integration testing suggests agility. </p>

<p>Bottom Line: You've got to have essentially all of the testing done within the confines of the Sprint to meet any Agile Definition of Done. How the code is Released to Market is up to the business. They can RTM weekly, monthly or quarterly and still claim to be Agile, but they need to maintain a Staging site for code that is Done but not Released. </p>

Body:
Although as Bart says, Agile might not dictate an environmental set-up, the values and principles do indicate best practices where code is aggregated and tested on an ongoing basis. That practice is in direct opposition to the gatepost approach in traditional waterfall environments. Transition through the gateposts suggests an approach is waterfall. High levels of automated integration testing suggests agility.

Bottom Line: You've got to have essentially all of the testing done within the confines of the Sprint to meet any Agile Definition of Done. How the code is Released to Market is up to the business. They can RTM weekly, monthly or quarterly and still claim to be Agile, but they need to maintain a Staging site for code that is Done but not Released.


问:
How important is to initialize a variable
How important is it to initialize variables?

Does proper initializing avoid memory leaks or have performance advantages?

答:
Trying to use an uninitialized variable is always a bug, so it makes sense to minimize the probability of that bug occurring.

Probably the most common approach programming languages take to mitigate the problem is to automatically initialize to a default value, so at least if you forget to initialize a variable, it will be something like 0 instead of something like 0x16615c4b.

This solves a large percentage of bugs, if you happened to need a variable initialized to zero anyway.  However, using a variable that was initialized to an incorrect value is just as bad as using one that wasn't initialized at all.  In fact, sometimes it can be even worse, because the error can be more subtle and difficult to detect.

Functional programming languages solve this problem by not only disallowing uninitialized values, but by disallowing reassignment altogether.  That eliminates the problem and turns out to not be as severe a restriction as you might think.  Even in non-functional languages, if you wait to declare a variable until you have a correct value to initialize it with, your code tends to be much more robust.

As far as performance goes, it's probably negligible.  At worst with uninitialized variables, you have one extra assignment, and tie up some memory for longer than necessary.  Good compilers can optimize the differences out in a lot of cases.

Memory leaks are completely unrelated, although properly-initialized variables tend to be in scope for a shorter period of time, and therefore might be somewhat less likely for a programmer to accidentally leak.


答:
Initializing variables (implicitly or explicitly) is crucial. Not initializing a variable is always an error (they might be initialized implicitly, however. See below). Modern compliers like the C# compiler (as an example) treat this as an error and won't let you execute the code. An uninitialized variable is simply useless and harmful. Unless you are creating a random number generator, you expect from a piece of code to produce a deterministic and reproducible result. This can only be achieved if you start working with initialized variables.

The really interesting question is whether a variable is initialized automatically or whether you have to do it manually. It depends on the language used. In C# for instance, fields, i.e. "variables" at the class level, are always automatically initialized to the default value for that variable type default(T). This value corresponds to a bit pattern consisting of all zeroes. This is part of the language specification and not just a technical detail of the implementation of the language. Therefore you can safely rely on it. It is safe not to initialize a variable explicitly if (and only if) the language specification states that it is initialized implicitly. If you want another value, you must initialize the variable explicitly. However; in C# local variables, i.e. variables declared in methods, are not initialized automatically and you must always initialize the variable explicitly.

Title: How important is to initialize a variable

Body:
How important is it to initialize variables?

Does proper initializing avoid memory leaks or have performance advantages?

ContentLicense: CC BY-SA 4.0


问:
Who is responsible for updating the Java API and how can other individuals contribute?
I made a search on google to find out who are the people in Oracle responsible for updating the Java API in other words who are those responsible for adding new classes and methods to the API and updating the Java Documentation.

I could not find an answer to this question which leads me to the next question, what if I had some classes that are not found in the API which I wished to share with others, how do I get Oracle to add those classes for me?

答:
If you'd like to suggest a feature or report a bug to Oracle, you can do so via their bug report and feature request page.

Java's implementation is now managed via the OpenJDK as the official reference implementation. If you want to contribute, you'll need to follow this path, summarized from the page linked:

Find something to work on. You seem to have this step complete.

Discuss your intended change(s) with others on the project

Submit a patch. You'll need to know how to use Mercurial and how to do unit testing in order to complete this step.

You'll then need to get a sponsor who is already working as a JDK 8 update or JDK 9 committer. They'll evaluate your work and work with you to address deficiencies.

Your code gets incorporated into the JDK. Or not, mostly likely not. They recommend making sure that you really know what you are doing before you start working on this kind of a project. They also recommend hacking against the JDK 9 sources before you try to start submitting features.

All told what you ask is doable but very difficult. A better option might be to devise a library or framework that houses your classes and then put it up on Github or Bitbucket and try to attract interest in usage and improvement.


问:
Are for loops supposed to be read inward or outward?
```<code> for (i = 0; i < 3; i++)
 {
    for (j = 0; j < 4; j++)
    {
        cout << arr2d[i][j] << "\t";
    }
    cout << endl;
    .....
</code>```

Like that for example. Do you read the for loop inward-out (starting from for (j = 0; j < 4; j++)) or outward-in (starting from for (i = 0; i < 3; i++)) Just wondering. :D

答:
In earlier days programming languages like BASIC were not structured. A program consisted of numbered lines of code and you could jump from any line to any other line by using a GOTO  statement. This made it very difficult to read a program as you could not understand it by reading the lines top-down. It was also very difficult to maintain such a code.

Then the so called Structured programming was introduced. The idea behind it is that the program consists of blocks that appear in a strict top-down order. Blocks can also be nested. A loop, for instance is, a block with nested blocks that can be executed repeatedly. These nested blocks are again executed in a strict top-down order.

C++ is a structured programming language. (There is a goto statement so, which should only be used in exceptional cases.) Therefore you can read a C++ routine in a top-down order.

Nested for-loops are just a special case of a loop-block containing a nested loop-block again. Your code consists of an outer loop-block having two nested blocks that can be executed repeatedly. It happens that the first of the two nested blocks is a loop-block again. The second nested block will be executed once the first has terminated, as with any other non-loop block (or statement). Once the last nested block has been executed, the control is passed to back to the outer loop-block which in turn "decides" whether the nested blocks will be executed again.


问:
Using a web framework as python GUI
If I built some useful piece of python code to e.g. scrape a website or to calculate something big, at some point I might want to add a GUI to my project. For this I could use Tk, Qt, Pygame or any python graphic/GUI framework.

Now I also want this tool to be usable by clients without the need for a python installation. Of course I could use something like py2Exe or py2Dmg. But wouldn't it be cooler to use a python-based web framework for this? Something like Django or Pyramid.

What would be the drawbacks of doing this? Can I just use the framework to execute my code on a server and only return the result? Or will this get tricky when there are multiple users?

答:
If you use Django, I recommend looking at either of

django-tastypie. With it you can build simple REST-style interfaces to your code.

Celery. An asynchronous task framework

Since you mention calculating something bigyou are likely to need asynchronous processing. Celery is a great choice for that. It includes the ability to submit jobs via REST calls, and to check on their status.

Title: Using a web framework as python GUI


问:
is it good practice to reload a div every second
I am working on a networking site where I need to reload the notification div every second. I wanted to know is it good or bad to load it every second as there are some other divs also loading after every 3-4 seconds. Will it cause any problem like hanging, slowing down, etc?

Reloading is done by ajax:

```<code>var auto_refresh = setInterval(
    function ()  {
        $('#notif').load('notiffinder.php #NOOFFNOTIFFC').fadeIn();
        $('#jtoloadnot').load('header.php #jtoloadnot').fadeIn();
    }, 1000);
</code>```

答:
We can't tell you if it will cause problems because it entirely depends on what you are putting into that div, your internet connection, and what kind of load you have on the server.

But you need to ask yourself, do you really need to be polling multiple php scripts every second?  Is the data actually changing every second?  I suspect you probably should be investigating other techniques, such as websockets and long-polling.


问:
Naming CSS classes and IDs
I'm quite a CSS beginner. I've read some introductory books but now I came across a sort of question that isn't answered in any of them:

Let's say I have a basic HTML-based website with a standalone CSS file. Now I'm creating a new CSS class or ID and I want it to have a meaningful name of course because I'll probably come back to those lines a couple of times again. For creating a meaningful name there are two options:

I can name them hide-upper-space or small-seethrough-border - these kinds of names are very helpful when reading the HTML file, but in CSS file there will be a mess of all these classes and IDs from all HTML documents mixed together. Moreover, when I want to remove or modify one HTML document I won't be able to clear or modify the appropriate lines in the CSS file because I won't know if they affect also some other HTML documents.

On the contrary, I can name them blog-footnote or gallerythumbs-upper-left and it will make my CSS file thoroughly readable, structured and easily modifiable, but it's useless information in HTML documents - when you're reading the HTML code for the footnote of your blog then blog-footnote is just plain useless class name.

I hope you get my point.

I'd guess that one of these options is the actual way how the CSS should be used but I can't figure out which one and why. Thank you for helping me to use the CSS the proper and effective way.

答:
I'm no HTML/CSS expert so take this answer with a grain for salt but I think you are still missing the essence of why CSS exists in the first place.

Back in the day, we only had HTML so yes, you could tell exactly what the size, color, padding...etc of every element was, but this also made HTML harder to read more difficult to modify if you ever wanted to try different layouts and/or color schemes.

CSS was introduced so that you could have a very well defined and clear separation between document structure/content(HTML) and its visual appearance(CSS).  So you want  elements with names like "blog-footnote" and "gallery-thumb" because in HTML those names further help define the structure and meaning of the element.  You see the element and you know exactly what it's for.

Those names are "useless" in a sense that you still have no idea how (or even where) that element will appear on the screen, but HTML shouldn't give you that information.  That's what CSS is for.

To better understand this separation, take a look at CSS Zen Garden.  That's exactly the same HTML document (i.e. same content) but presented using different CSS styles that people have submitted.

Title: Naming CSS classes and IDs


答:
I can name them hide-upper-space or small-seethrough-border... On the contrary, I can name them blog-footnote or gallerythumbs-upper-left...

You should do neither of these.

Instead, you should favor a mobile-first CSS framework* like Bootstrap that has a semantic naming convention:

Semantic class names. Building reusable components is a challenge in designing any kind of framework, and since Bootstrap is about style we want reusable style definitions. The classes provided by Bootstrap are meaningful without being specific about presentation details. For example, classes like warning, important, info, and alert all have an obvious meaning, but they don't give away any spoilers about the background colors they'll use. You can then use these Bootstrap classes in any application and even with heavy amounts of customization, the class names still make sense.

Bootstrap's grid layout means that you can write your markup to look nice on all form factors. Classes like small-seethrough-border and gallerythumbs-upper-left are a "code smell" to me because they imply that the page was written for just one form factor.

Title: Naming CSS classes and IDs

Body:
I'm quite a CSS beginner. I've read some introductory books but now I came across a sort of question that isn't answered in any of them:

Let's say I have a basic HTML-based website with a standalone CSS file. Now I'm creating a new CSS class or ID and I want it to have a meaningful name of course because I'll probably come back to those lines a couple of times again. For creating a meaningful name there are two options:

I can name them hide-upper-space or small-seethrough-border - these kinds of names are very helpful when reading the HTML file, but in CSS file there will be a mess of all these classes and IDs from all HTML documents mixed together. Moreover, when I want to remove or modify one HTML document I won't be able to clear or modify the appropriate lines in the CSS file because I won't know if they affect also some other HTML documents.

On the contrary, I can name them blog-footnote or gallerythumbs-upper-left and it will make my CSS file thoroughly readable, structured and easily modifiable, but it's useless information in HTML documents - when you're reading the HTML code for the footnote of your blog then blog-footnote is just plain useless class name.

I hope you get my point.

I'd guess that one of these options is the actual way how the CSS should be used but I can't figure out which one and why. Thank you for helping me to use the CSS the proper and effective way.


答:
Well to start with ID's and classes are not really a CSS concept, rather, they are used to identify certain HTML elements - CSS and JavaScript both can then utilize this. Thus both are a part of HTML, and should be semantic descriptions, HTML provides structure and semantic context - not style.

So the best names describe either what the element is (ID) or what that kind of element is for (class). This is more in line with your second example. The ID's and class names are more analogous to naming variables than marking what styles you want where. If an element is the container for a comment give it the class commentCointainer, if it is the main menu bar, give it the ID menuBar.

Remember that if you make the class underlined-text then you have essentially obviated the point of external CSS, it would be simpler to just use the style attribute. Class and ID names that describe the style will also make it harder to change later. Suppose there is an area of my page that is blue, so I call it bluePart - this is descriptive of the style, but if later I want it to be red I will need to fix it in the HTML and in the CSS (even worse if it is a class that shows up in multiple places in many files).

Title: Naming CSS classes and IDs


问:
What popular "best practices" are not always best, and why?
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.

答:
User Stories / Use Cases / Personas

I understand the need for these when you are programming for an industry that you are not familiar with, but I think that when they are implemented in full force they become too corporate and become a waste of time.

ContentLicense: CC BY-SA 2.5


答:
Uninitialized variables make a program non-deterministic. Each time the program runs, it may behave differently. Unrelated changes to operating environment, time of day, phase of the moon and permutations of such affect how and when these daemons manifest. The program may run a million times before the defect presents, them may do it every time, or run another million. Many problems are put down to "glitches" and ignored, or defect reports from customers closed as "Unreproducible". How often have you rebooted a machine to 'fix' a problem? How often have you said to a  customer "Never seen that happen, let me know if you see it again" - hoping (knowing) full well they won't!

As reproduction of a defect can be next to impossible in the test environment, its next to impossible to find and fix.

It can take years for the bug to surface, commonly in code thought to be be reliable and stable. The defect is presumed to be in more recent code - tracking it down can take significantly longer. A change in compiler, a compiler switch, even adding a line of code can change the behavior.

Initializing variables has a huge performance advantage, not only because a program that works correctly is infinity faster than one that does not, but the developers spend less time finding and fixing defects that should not be there and more time doing "real" work.

The other significant advantage of initialing variables is the original author of the code must decide what to initialize them to. This is not always a trivial exercise, and when not trivial, can be an indication of a poor design.

Memory leaks are a different problem, but proper initialization can not only assist in preventing them, it can also help in detecting them and finding the source - its highly language dependent and that's really  a separate question worthy of further exploration than I am able to give in this answer.

Edit: In some languages (e.g. C#) it is not possible to use uninitialized variables, as the program will not compile, or report an error when executed, if done.  However, many languages with these characteristics have interfaces to potentially unsafe code, so care must be taken when using such interfaces no to introduce uninitialized variables.


问:
Is it better to put the JS code on the html file or in an external file?
If I'm designing a one page website, is it better to create external file for my JS code, or just put it in the html code?
Is putting it on the page faster to load?
Can I change the permissions to deny the users requests for the code, but the html page can still call the code?</p>

答:
Client side JS code has to be seen by the browser (that is, if the page needs to use JS directly) - that means it has to bee downloaded by the browser.

You cannot have a browser use JS on the page if it cannot download it.

In that respect, it doesn't make a whit of difference if you inline the JS or put it in a file, though common practice is to use a JS file (separation of concerns for one).

If you have code that you do not wish to expose through to the browser, you will need to use server side code (say node.js, php, perl, asp.net, jsp - there are so many options) and interact with it from the browser - either on initial page loads or using AJAX.


答:
You should put your JS code in a separate file because this makes it easier to test and develop. The question of how you serve the code is a different matter.

Serving the HTML and the JS separately has the advantage that a client can cache the JS. This requires you to send appropriate headers so that the client does not issue a new request each time. Caching is problematic if you want to perform an update and thus want to invalidate the client caches. One method is to include a version number in the filename, e.g. /static/mylibrary-1.12.2.js.

If the JS is in a separate file you cannot restrict access to it: It is difficult (technically: impossible) to tell if a request to a JS file was made because you referenced it on your HTML page, or because somebody wants to download it directly. You can however use cookies and refuse to serve clients that don't transmit certain cookies (but that would be silly).

Serving the JS inside the HTML increases the size of each page – but this is OK if a client is unlikely to view multiple pages. Because the client does not issue a separate request for the JS, this strategy loads the page faster – for the first time at least, but there is a break-even point where caching is better. You can include the JS e.g. via PHP.

Here the client does not need separate access to the JS file, which can be hidden if you like. But a anyone can still view the JS code inside the HTML.

Other strategies to minimize load times include

JS minification which reduces the size of the JS file you serve. As minification only happens once when deploying the code, this is a very efficient method to save bytes. OTOH this makes your code harder to understand for interested visitors.

Related to minification is the practice of combinining all your JS files in a single file. This reduces the number of necessary requests.

Compression, which adds a computational overhead for each request on both the client and the server. However the time spent (de-)compressing is usually smaller than the time spent transmitting the uncompressed data. Compression is usually handled transparently by the server software.

These techniques also apply to other resources like images.

Images can be inlined into HTML or CSS with data-URLs. This is only practical for small, simple images as the base64-encoding inflates the size. This can still be faster than another request.

Multiple small images (icons, buttons) can be combined into a single image, and then extracted as sprites.

Images can be reduced by the server to the size in which they are actually used on the website, which saves bandwidth. Compare thumbnail images.

For some graphics, text-based images like SVG can be a lot smaller.

Title: Is it better to put the JS code on the html file or in an external file?

Body:
If I'm designing a one page website, is it better to create external file for my JS code, or just put it in the html code?
Is putting it on the page faster to load?
Can I change the permissions to deny the users requests for the code, but the html page can still call the code?</p>


Body:
Well it depends on amount of code, and how serious are you about being a programmer/software engineer versus just a coder. I worked with bunch of designers who put short snippets of code directly into HTML, and while I cringed – it actually worked.

Though it's not something I would do myself, and if you do want to know best practices of software development I strongly advise you to pu everything in external *.js file and load it via <script> tags.

Regarding your second point, no you can not deny user or browser to view your code, there is something called obfuscation which will make your code harder to read, however performance will degrade.


问:
Java web application folder structure
As a beginner to J2EE, I have recently started developing my own project from scratch using the Core of J2EE : Servlets & Jsps.

I could not evaluate whether my project folder structure is right or not.
Here is my project folder structure.

Before asking question, I admit that I could not answer or neither justify if somebody asks me, why this type of folder structure.
The question: Is it a good sign to put my jsps outside of web-inf. If not, why is it so? If yes why?

Is there any standard folder structure convention for a J2EE web application, I know maven has brought up some standards but still, we can customize as per the requirement I believe.

I have done a bit of googling and found the two references
1
2

where in the answers are not on the same page, from which I couldn't draw any conclusion.

What are the points to be considered while laying out the folder structure for a J2EE web application, importantly where should the Jsps, static content should go into & why?

答:
Actually WAR application can be constructed without WEB-INF/web.xml. It is possible to make WAR application with only Java classes inside.

Source: A web.xml Deployment Descriptor Elements

With Java EE annotations, the standard web.xml deployment descriptor is optional. According to the servlet 3.0 specification at http://jcp.org/en/jsr/detail?id=315, annotations can be defined on certain Web components, such as servlets, filters, listeners, and tag handlers.

So nowadays is possible to build WAR than looks like JAR with .war extensions :)

Answering your question, WAR structure depends on your requirements.

http://en.wikipedia.org/wiki/WAR_(Sun_file_format)

Title: Java web application folder structure


答:
I'm designing a one page website

If you literally just have one page then yes, it is better (from a performance point of view) to serve everything in the one file... stylesheets, JavaScript and even images (small images inlined with data-URIs). This eliminates the additional HTTP requests required to retrieve external resources which are relatively slow.

The resulting file should be gzipped before serving, which will massively reduce the size of the all-text response.

You should still consider having large images external to the page, as there are limits to the size of data-URIs and browser compatibility. (eg. IE8 has a limit of 32KB, which equates to an actual file size of about 23KB due to the nature of the base64 encoding.)

Can I change the permissions to deny the users requests for the code, but the html page can still call the code?

No. At best the code can be obfuscated in order to "hide" it from the casual observer, but it offers no real protection.


问:
I am a beginner. Can I directly start learning C++11? or I have to learn old C++?
I'm a beginner and have only little knowledge in programming.

Would it be good if I directly learn C++ from books which cover new C++11 or should I study through the old best C++ books?

Should I have little knowledge about C++ before learning C++11? or I can start directly from there?

Would it cause problem if I directly start from C++11? If no, then suggest some books on C++11.

答:
Recent introductory books about C++ are increasingly covering C++11 as well.  I read Sam's Teach Yourself C++ after working with scripted languages but not C/C++ for almost ten years and found it really helpful.  I very quickly became conversant in the central ideas of C++ (including a lot of STL) and conscious of a great many details which are different in C++11.

As some other posters have mentioned, C++11 is in many ways easier than older standards with scripting-style additions like auto, for(int &i : m_vector){} etc.  So if your "little knowledge" comes from languages like Python or Matlab, you will find C++11 somewhat more "natural" than the earlier standards.

I would also point out that by now, compiler compatibility for C++11 is (almost) complete so having code that is "too up to date to compile" is no longer an issue.

In short, do it.


问:
What makes a language Turing-complete?
What is the minimal set of language features/structures that make it Turing-complete?</p>

答:
i know this is not the formally correct answer, but once you take the 'minimal' out of 'Turing-complete' and put 'practical' back where it belongs, you'll see the most important features that distinguish a programming language from a markup language are

variables

conditionals (if/then...)

loopage (loop/break, while...)

next come

anonymous and named functions

to test these assertions, start out with a markup language, say, HTML. we could invent an HTML+ with variables only, or conditionals only (MS did that with conditional comments), or some kind of loop construct (which in the absence of conditionals would probably end up as something like <repeat n='4'>...</repeat>). doing any of these will make HTML+ significantly (?) more powerful than plain HTML, but it would still be more of a markup than a programming language; with each new feature, you make it less of a declarative and more of an imperative language.

the quest for minimality in logic and programming sure is important and interesting, but if i had to teach n00bies young or old 'what is programming' and 'how to learn to program', i'd hardly start out with the full breadth and width of the theoretical foundations of Turing completeness. the whole essence of cooking and programming is doing stuff, in the right order, repeating until ready, as your mom did it. that about sums it up for me.

then again, i never finished my CS.

Title: What makes a language Turing-complete?


问:
Etymology of 'virtual' (method/method table/inheritance)
As far as I know, it generally refers to late or dynamic bindng. So why a word like late or dynamic wasn't used?

答:
The term late or dynamic binding describes how the identifier is resolved into the actual implementation of the method, it doesn't describe how the virtual method is used. If any of those would have been used to describe the method, something like late-bound or dynamically-bound would have been used, which is not only long-winded, but also a bit too close to how it's implemented.

Using virtual to describe the method is better as a high-level desciption. It allows you to understand the principle without the need to know how the compiler deals with it at machine level.

It also works for a language that would be implemented using only late binding, where you still want to make a difference between virtual and concrete methods.


问:
How to create html pages which don't change very much and not very often?
I have a Rails server that connects to a json API on another server to get data to build the pages dynamically. These pages, however, don't change very much and not very often.

I was thinking I could cut down the page load time, also, cut down the calls to the JSON API significantly if I just periodically called the JSON API and wrote the html files as static html pages. What is a way for building the html files in ruby / rails from scratch?

答:
What you want to do would be possible by using render_to_string and saving the result into a file. Then your controller could use this file. But it is somewhat cumbersome.

Using caching would automate this process and allow more detailed control about what part of a page is cached. Also you would not have to change much of the existing code, since the caching mechanism nicely fits into the Rails workflow.

Details are explained here: http://guides.rubyonrails.org/caching_with_rails.html

There are many different strategies possible and different levels of either caching parts of a page or even the return values of single methods. Depending on what part of the page is static and where exactly is the bottleneck (more often methods that access the database or an external API, less likely the rendering itself).

So you could maybe use fragment caching. Assuming your page as some partial that renders the content you got from an API call this would look something like this:

```<code><% cache(action: 'api_stuff') do %>
  <h1>that's it:</h1>
  <% api_source.get_data.each do |line| %>
    <%# render a line of data %>
    <%# or render a partial %>
  <% end %>
<% end %>
</code>```

This has the slight disadvantage that you need to make the api call from the view code. Not exactly the most elegant way. Rails caching is somewhat expecting ActiveRecord objects.

So you may prefer another approach and instead manually use the Rails cache. In this case the class that provides the API access would work like this:

```<code>def get_data()
    Rails.cache.fetch("some_unique_id") do
      make_api_call() # if cache fails actually retrieve from API
    end
  end
</code>```

That way Rails will try to find the data in the cache named "some_unique_id". If this fails (does not exist, was deleted or expired) it will call make_api_call() to get the data.

You can either manually delete or expire the cache (just write some script) or add an expiration interval:

```<code>Rails.cache.fetch("some_unique_id", expires_in: 24.hours) do
</code>```

Manu more variations are possible. In addition you can decide where the cache is stored, files, memory or memcached are just some of the options here.

Body:
What you want to do would be possible by using render_to_string and saving the result into a file. Then your controller could use this file. But it is somewhat cumbersome.

Using caching would automate this process and allow more detailed control about what part of a page is cached. Also you would not have to change much of the existing code, since the caching mechanism nicely fits into the Rails workflow.

Details are explained here: http://guides.rubyonrails.org/caching_with_rails.html

There are many different strategies possible and different levels of either caching parts of a page or even the return values of single methods. Depending on what part of the page is static and where exactly is the bottleneck (more often methods that access the database or an external API, less likely the rendering itself).

So you could maybe use fragment caching. Assuming your page as some partial that renders the content you got from an API call this would look something like this:

<% cache(action: 'api_stuff') do %>
  <h1>that's it:</h1>
  <% api_source.get_data.each do |line| %>
    <%# render a line of data %>
    <%# or render a partial %>
  <% end %>
<% end %>

This has the slight disadvantage that you need to make the api call from the view code. Not exactly the most elegant way. Rails caching is somewhat expecting ActiveRecord objects.

So you may prefer another approach and instead manually use the Rails cache. In this case the class that provides the API access would work like this:

def get_data()
    Rails.cache.fetch("some_unique_id") do
      make_api_call() # if cache fails actually retrieve from API
    end
  end

That way Rails will try to find the data in the cache named "some_unique_id". If this fails (does not exist, was deleted or expired) it will call make_api_call() to get the data.

You can either manually delete or expire the cache (just write some script) or add an expiration interval:

Rails.cache.fetch("some_unique_id", expires_in: 24.hours) do

Manu more variations are possible. In addition you can decide where the cache is stored, files, memory or memcached are just some of the options here.


答:
Use Singletons

When you only should have one instance of something. I cant disagree more. Never use a singleton and just allocate it once and pass around the pointer/object/reference as necessary. There is absolutely no reason not to do this.

Title: What popular "best practices" are not always best, and why?

Body:
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.


问:
What is an "abstraction layer"?
I need a very simple explanation because I'm not a professional programmer.

I found the terminology "abstraction layer" reading the documentation of mysqli extension where is described the difference among mysql, mysqli and PDO extensions in PHP. The article is this, that's where I met "abstraction layer" for the first time (referred to PDO).

Now, trying to elaborate my question, we could speak of PDO abstraction layer against mysqli extension in php. So, for example, why mysqli is not defined as abstraction layer? How an abstraction layer acts? (like PDO in php)

I would like to understand in a general way what is an"abstraction layer", I will not do particular questions about php or mysqli and PDO extensions.

So, what is an abstraction layer? And what is its difference from a common application's extension?

答:
Generally, an abstraction layer is an API (set of functions) which is hiding the underlying implementation/complexity. The purpose is to provide a clear and easier-to-use interface over an existing set of functionality.

Imagine you want to create a stack using a list. You could build a class called Stack. You'd have a private list inside it to store the elements. You'd also have methods to push and pop elements from the stack. This class is an abstraction layer over list representing a stack. It hides the implementation (how elements are stored, how they are pushed and popped) and provides a simple interface to work with a stack.

The wikipedia article about abstraction layers is a good starting point.

Regarding database abstration layers. For example, you have a MySQL database and you want to access it from your PHP program. An abstraction layer in this case would provide the funtionality of opening connetion to the database, executing queries, calling stored procedures, etc. So when working with the database from PHP code, you won't have to think about how connection is actually created or how MySQL queries are actually passed to the database, executed there and how the result is returned and parsed.

Title: What is an "abstraction layer"?


问:
Replacing static classes with global state to a series of POJOs, beginning to feel like an anti-pattern
I'm trying to refactor some code, and one of the major changes is to remove the (ab)use of static classes to give global state.

I've tried to split up some of the 'global state' functionality with POJOs that can be passed around.

But the further down the rabbit hole I go the more and more I feel like this is an Anti-Pattern.

Is holding state in POJOs and then passing them around bad form? It means the outline of my methods often look like this:

```<code>public MyPojo makeReport(int myInt, String pathToInput, MyPojo myPojo){
    ...
    if(myPojo.whatKindOfReport()==Reports.reportTypes){
        ...
    }
    ...
    myPojo.isWritingReportToFileSuccessful(true);
    ....
    return myPojo;
}
</code>```

Where the POJO 'state' is set from the GUI that the user interacts with. For instance with tickboxes for report types etc.

But this blocks other return types, and seems overly complicated.

I've taken this approach because the application has several 'paths' (see whatAmIDoing) the user can take in running it, each of which has several stages. What options the user has depends heavily on what path they pick and then from there, the result of that choice (normally, success or failure, see myPojo.isSomethingSuccessful(true)). I'm trying to encode that information in a POJO rather than a Global State Class.

Is this an anti-pattern? How can I get round this?

Edit: I think what I'm after is something like Chain of Responsibility. After looking at this answer I'm not sure.

答:
Stop thinking in terms of operations and start thinking in terms of data.

doSomething is not a static method, therefore it belongs to an object which can hold state - lets call the class of that object Foo, and say you have created an instance named foo.

Now, instead of saying that foo.doSomething needs an instance of MyPojo, you should say that foo needs to do something with MyPojo. So - you can do foo.setMyPojo(myPojo); and then you can call foo.doSomething without the MyPojo argument - because it already has it. In addition, when you call other methods of foo it already has myPojo set! And the best thing - this allows you to draw a graph of dependencies based on objects, not methods.


答:
Often an abstraction layer is commonly used to 'abstract' away detail.

Say you had a program for moving money around between different banks. There is a function for moving money to BankA, and a different function for moving money to BankB and so on. The different functions might exist because the information that different banks request varies (As a simple example maybe one requests the senders first name and surname, and another requests the senders first initial and surname).

Your functions might be:

```<code>MoveMoneyToBankA(amount, accountNo, senderFirstName, senderSurname)
{
   ... Code to move money to bank A
}

MoveMoneyToBankB(amount, accountNo, senderFirstInitial, senderSurname)
{
   ... Code to move money to bank A
}
</code>```

To abstract away all the different things a program needs to think about when communicating with different banks, an abstration layer might be implemented by adding the function 'MoveMoneyToBank'

```<code>MoveMoneyToBank(amount, accountNo, senderFirstName, senderSurname, bankName)
{
   ... If bank name = 'BankA' call MoveMoneyToBankA

   ... If bank name = 'BankB', find senderFirstInitial using senderFirstName, and call 'MoveMoneyToBankB'
}
</code>```

So what you have done here is abstracted away the detail that needs to be managed when communicating with two different banks. A programmer can now just use the general MoveMoneyToBank function, and not have to think about the different requirements of each bank.

In reality, this might not just be functions with in the same program, but even different projects within the same solution, or a new software project that draws in lots of components and deals with the complexity of working with all the separate components to achieve a common goal.

Title: What is an "abstraction layer"?

Body:
I need a very simple explanation because I'm not a professional programmer.

I found the terminology "abstraction layer" reading the documentation of mysqli extension where is described the difference among mysql, mysqli and PDO extensions in PHP. The article is this, that's where I met "abstraction layer" for the first time (referred to PDO).

Now, trying to elaborate my question, we could speak of PDO abstraction layer against mysqli extension in php. So, for example, why mysqli is not defined as abstraction layer? How an abstraction layer acts? (like PDO in php)

I would like to understand in a general way what is an"abstraction layer", I will not do particular questions about php or mysqli and PDO extensions.

So, what is an abstraction layer? And what is its difference from a common application's extension?

Body:
Often an abstraction layer is commonly used to 'abstract' away detail.

Say you had a program for moving money around between different banks. There is a function for moving money to BankA, and a different function for moving money to BankB and so on. The different functions might exist because the information that different banks request varies (As a simple example maybe one requests the senders first name and surname, and another requests the senders first initial and surname).

Your functions might be:

MoveMoneyToBankA(amount, accountNo, senderFirstName, senderSurname)
{
   ... Code to move money to bank A
}

MoveMoneyToBankB(amount, accountNo, senderFirstInitial, senderSurname)
{
   ... Code to move money to bank A
}

To abstract away all the different things a program needs to think about when communicating with different banks, an abstration layer might be implemented by adding the function 'MoveMoneyToBank'

MoveMoneyToBank(amount, accountNo, senderFirstName, senderSurname, bankName)
{
   ... If bank name = 'BankA' call MoveMoneyToBankA

   ... If bank name = 'BankB', find senderFirstInitial using senderFirstName, and call 'MoveMoneyToBankB'
}

So what you have done here is abstracted away the detail that needs to be managed when communicating with two different banks. A programmer can now just use the general MoveMoneyToBank function, and not have to think about the different requirements of each bank.

In reality, this might not just be functions with in the same program, but even different projects within the same solution, or a new software project that draws in lots of components and deals with the complexity of working with all the separate components to achieve a common goal.


答:
I think that under most circumstances, an abstraction layer serves as a simplification or gateway to a more complicated underlying layer.

Suppose you have a database layer that allows you to perform nearly all database operations you can imagine. However, such a layer or API would be fairly complicated to use due to its number of features. Especially if you just want to do something simple.

In this case, an abstraction layer might be available that only provides a subset of the functionalities in an easier to use fashion. While still using the underlying layer, this layer could then provide more intuitively named methods/functions, easier to use parameters and/or predefined parameters that should help you get started...

Often times, such abstraction layers also introduce more general or real world concepts that are more easily understood by people that are no domain experts. (To give a technical example: the database layer could return you a resultset that needs to be iterated, while the abstraction could return you a list of well defined objects that are ready to be used)

While such underlying layers provide greater functionality, they usually require more time to get something done if you are not yet familiar with it.

Title: What is an "abstraction layer"?


答:
This looks as if the doSomething method should be member of MyPojo class. Getting object as a parameter and then returning it? Definitely doesn't look good.

The way you describe your code seems to be even more indicative of some kind of class structure. Using enum as descriptor to what is done is clear smell that should be replaced with class hierarchy where each class represents one path the code can take. As described here.

And as Idan said, making the object a field of class that contains the doSomething method instead of parameter to the method itself can be better. Also, you can make the object as constructor parameter, so you can use dependency injection.

Title: Replacing static classes with global state to a series of POJOs, beginning to feel like an anti-pattern

Body:
I'm trying to refactor some code, and one of the major changes is to remove the (ab)use of static classes to give global state.

I've tried to split up some of the 'global state' functionality with POJOs that can be passed around.

But the further down the rabbit hole I go the more and more I feel like this is an Anti-Pattern.

Is holding state in POJOs and then passing them around bad form? It means the outline of my methods often look like this:

```<code>public MyPojo makeReport(int myInt, String pathToInput, MyPojo myPojo){
    ...
    if(myPojo.whatKindOfReport()==Reports.reportTypes){
        ...
    }
    ...
    myPojo.isWritingReportToFileSuccessful(true);
    ....
    return myPojo;
}
</code>```

Where the POJO 'state' is set from the GUI that the user interacts with. For instance with tickboxes for report types etc.

But this blocks other return types, and seems overly complicated.

I've taken this approach because the application has several 'paths' (see whatAmIDoing) the user can take in running it, each of which has several stages. What options the user has depends heavily on what path they pick and then from there, the result of that choice (normally, success or failure, see myPojo.isSomethingSuccessful(true)). I'm trying to encode that information in a POJO rather than a Global State Class.

Is this an anti-pattern? How can I get round this?

Edit: I think what I'm after is something like Chain of Responsibility. After looking at this answer I'm not sure.


问:
Design patterns for multi-threaded messaging server
I'm designing an instant messaging server as a personal exercise to improve my understanding and application of multi-threading and design patterns in Java. I'm still designing, there's no code yet.

My goal is to have a server that should make effective use of a multi-CPU box. I'd like the server to be distributable across multiple boxes, but wonder if that's running before I can walk.

My initial thoughts are:

ClientConnectionManager has ServerSocket object that constantly accepts client Socket connections.

ClientConnectionManager has a thread pool that spawns a new ClientProxy object when a client socket connection is accepted, handing in the client Socket object.

The ClientProxy objects represent the client app and handles sending/receiving messages across the Socket stream.

Is it correct that only one ServerSocket may bind to a Port? I take it there's no way to have a pool of objects accepting Socket connections?

I have two ideas for passing messages between ClientProxy objects. Either directly between ClientProxy objects that are "buddies" or via a central "Exchange" object, or better yet, pool of objects.

What are the Pros/Cons of the two approaches? Does the Exchange lend itself better to a distributed app?

Would the Observer and Mediator patterns, respectively, be appropriate?

答:
Is it correct that only one ServerSocket may bind to a Port? I take it there's no way to have a pool of objects accepting Socket connections?

Correct. Only one thing can bind to a particular port on a given network interface at a time. Whenever a connection is received, a new socket is automatically created for the client on a deferred/internally-routed port. This is how a single listener can spawn any number of client handlers without waiting for the previous one to disconnect.

I have two ideas for passing messages between ClientProxy objects. Either directly between ClientProxy objects that are "buddies" or via a central "Exchange" object, or better yet, pool of objects.

You can have clients receive a proxy to their their buddies' message queues whenever the buddies come online. They can then directly queue messages to each other, avoiding the need of a centralized exchange. The server would keep a reference to all of its online clients and notify the interested parties of their friends' connections/disconnections via the queue.

Scaling this to fill a single box would become a matter of adding network interfaces (or using a port range on the one interface). Scaling this across multiple boxes would require server synchronization / passing queue proxies to-and-fro willy nilly.


问:
Examples of Java APIs that demand an action sequence
As part of a research I'm working on, I'm looking for public APIs that only work correctly when you apply a certain sequence of actions on them.

For example, the java.nio.channels.SocketChannel class, from the Java standard library, only works correctly with sequences such as open() -> connect() -> read() -> read() -> close(). A more complete demonstration if how it may be used may be represented in the following graph:

Additional examples of Java standard library APIs that require certain sequences are java.io.PrintStream (very similar to the one above) and java.util.Iterator (which requires a next() call between every two remove() calls, thus enforcing a certain sequence).

So, does you favorite API for doing X also behave that way? I would very much like to know about additional APIs that require a certain method sequence for correct usage; especially classes that are not part of the Java standard library. The more complex the sequence(s) required, the better.

Some APIs require a sequence that spans across multiple classes, for example:

```<code>X x = new X();
x.setup();
Y y = x.createNewY();
Z z = new Z(y);
z.doSomething();
</code>```

These examples are also interesting, but I'm mostly looking for sequences that all appear in the same class.

EDIT added bounty for greater visibility. I'm sure many of you have encountered many APIs that will match this description - I would really appreciate some good examples.

答:
From the Spring framework

The Lifecycle interface forces the following action sequence:

```<code>start (isRunning)* stop
</code>```

which is used in just about all the principal components that make up the framework. Fortunately, this lifecycle is managed by the container.

From the Hibernate framework

The Lifecycle interface supports the following action sequence:

```<code>(onDelete, onSave, onUpdate)* onLoad
</code>```

From the Servlet API

My all-time favourite - the lifecycle of a servlet:

```<code>init service destroy
</code>```

with service delegating to the doGet, doPost operations etc.

Body:
From the Spring framework

The Lifecycle interface forces the following action sequence:

start (isRunning)* stop

which is used in just about all the principal components that make up the framework. Fortunately, this lifecycle is managed by the container.

From the Hibernate framework

The Lifecycle interface supports the following action sequence:

(onDelete, onSave, onUpdate)* onLoad

From the Servlet API

My all-time favourite - the lifecycle of a servlet:

init service destroy

with service delegating to the doGet, doPost operations etc.


问:
Little and Big endian confusion
Just to make sure if I understand this correctly. Is this right that little endian processors read the memory addresses from highest to the lowest address and where as a big endian processors suppose to read them from lowest to the highest address?

The confusion came when I thought that is it true that little endian processors read the data itself in the reserve order and not just the memory or anyway both?

I have read enough about how the data is laid out in the memory and I just want to know how does the data is interpreted by both kinds of processors?

答:
"Is this right that little endian processors read the memory addresses
  from highest to the lowest address and where as a big endian
  processors suppose to read them from lowest to the highest address?"

No, that would just be an implementation detail of the memory chip, which would not make any difference for how you use the system.

In the little endian notation a multi-byte value is stored with the smallest components at the lowest address:

```<code>The number 0x12345678 stored at address 0x10:

+--+--+--+--+
|78|56|34|12|
+--+--+--+--+
 ^        ^
 |        |
 0x10     0x13
</code>```

In the big endian notation a multi-byte value is stored with the largest components at the lowest address:

```<code>+--+--+--+--+
|12|34|56|78|
+--+--+--+--+
 ^        ^
 |        |
 0x10     0x13
</code>```

Note that endianess doesn't only apply to how data is read natively by the system. A file format stores multi-byte values in either of those notations, and if you read a file with little-endian notation on a system that uses big-endian notation, you have to swap the bytes around when you put the multi-byte values together.

Title: Little and Big endian confusion

Body:
"Is this right that little endian processors read the memory addresses
  from highest to the lowest address and where as a big endian
  processors suppose to read them from lowest to the highest address?"

No, that would just be an implementation detail of the memory chip, which would not make any difference for how you use the system.

In the little endian notation a multi-byte value is stored with the smallest components at the lowest address:

The number 0x12345678 stored at address 0x10:

+--+--+--+--+
|78|56|34|12|
+--+--+--+--+
 ^        ^
 |        |
 0x10     0x13

In the big endian notation a multi-byte value is stored with the largest components at the lowest address:

+--+--+--+--+
|12|34|56|78|
+--+--+--+--+
 ^        ^
 |        |
 0x10     0x13

Note that endianess doesn't only apply to how data is read natively by the system. A file format stores multi-byte values in either of those notations, and if you read a file with little-endian notation on a system that uses big-endian notation, you have to swap the bytes around when you put the multi-byte values together.


问:
Python: Counter for Simultaneous calls of a PHP script?
I'm trying to create a queue processing script that's purpose is to find particular files and apply actions based on specific parameters,
with the result being to call a PHP script that serves to process a list of message files that we generated and passed to it.

One of the things I need to specify in a config file the maximum number of concurrent calls to the PHP processor that can be running at a given time, and if max number of calls is >= then loop until <=

Also need to specify a timeout variable 'tOut' in seconds...

So basically it looks for the oldest file in the directory, locates a variable in that filename 'chCode', searches for the next oldest files in the directory with the same chCode and reprefix them and output file a list of those reprefixed paths.

Then using Popen or Pcall the script with run 'php /path/to/filepathlist' and if:
it returns output '00' then continue...
it returns any text other than 00 then reprefix and mv..
it returns nothing for tOut secs then reprefix and mv.

The counter is the part I'm really needing help with, as this needs to be proper accurate and high performance with batches of hundreds of thousands of outgoing text messages being sorted using this. I can confirm the counter from the PHP script but as said it needs to be accurate.

Using Python 2.7 on CentOS6.

答:
If I understand your question correctly, the calls to PHP are asynchronous but you need to throttle them, right?

Use a semaphore.

http://docs.python.org/2/library/threading.html#semaphore-objects

```<code>throttle = threading.Semaphore(NUMBER_OF_CONCURRENT_EXECUTIONS)
</code>```

Then when you call PHP, do it via

```<code>with throttle :
    ... call php, wait for timeout, etc ...
</code>```

Body:
If I understand your question correctly, the calls to PHP are asynchronous but you need to throttle them, right?

Use a semaphore.

http://docs.python.org/2/library/threading.html#semaphore-objects

throttle = threading.Semaphore(NUMBER_OF_CONCURRENT_EXECUTIONS)

Then when you call PHP, do it via

with throttle :
    ... call php, wait for timeout, etc ...


问:
Visualizing a complex software application

Question

What is a good way to go about visualizing a complex software application?

Are recommended software applications that can be used for this purpose?

Background

About 3 years ago, I started building a web data mining application. Started out as just me, but has since grown into a project with 5 developers.

I used to be able to keep track of all the parts of the application in my mind, but now it has grown in complexity such that I'm feeling the need for some sort of visual documentation of the application's structure.

I'm not really sure where to go from here. I'm thinking something that looks kind of like a flow chart. But I don't have any background, experience, or formal training in software development on this scale. I have also never served on another team where I could observe someone else architecting a complex application or managing a team. Any pointers in the right direction such as books or resources on the subject would be much appreciated!

答:
I like to use the white boards in my office and draw everything out, this allows for quick editing because you will forget stuff the first time around. White boards are not necessarily needed, you can use paper or whatever on your wall.

Make sure to encapsulate all your objects/variables in a consistent unique shape (it helps later). You also do not need to be detailed in describing variables/functions/classes, get the general concept and let your mind keep the rest.

Once I have it diagrammed out (or at least what fits) I take a picture of it and save it on my computer. Once I have done the entire application I open all the images in an image editor and cut out all the different concepts and what not into individual pictures and save them in a directory.

There are several mind mapping tools and also UML tools for free that let you use your own images. you can build complex flows that you will understand because it's using your images.

Also to address keeping the whole application in my head, I generally just need a reference point to remember whole sections of an application's code, so this really helps with swapping scope.


问:
Time-complexity of nested for loop
I have loops like this:

```<code>for(int i = 0; i < n; i++) {
    for(int j = 0; j < i; j++) {
        sum += 1;
    }
}
</code>```

It's O(n * ), but I'm not sure what the j < i loop is.

I have some tests that I ran,

```<code>n = 10, runs = 45

n = 20, runs = 190

n = 40, runs = 780

n = 80, runs = 3160

n = 10, runs = 12720
</code>```

It seems to be converging onto .5*n^2, but I'm not quite sure.

答:
You are summing up the numbers from 1 to n, incrementing the value by one each time.  This is essentially the classic Gauss sumation which is:

```<code>sum(1 .. n) = (n * n-1)/2
</code>```

This also happens to be the number of times through the loop.

```<code>(n^2 - n) / 2
(n^2)/2 - n/2
</code>```

When representing Big O, only term with the highest power is used and constants are thrown away, and thus the answer is O(n2).

More about this particular problem can be read on CS.SE at Big O: Nested For Loop With Dependence

Title: Time-complexity of nested for loop

Body:
You are summing up the numbers from 1 to n, incrementing the value by one each time.  This is essentially the classic Gauss sumation which is:

sum(1 .. n) = (n * n-1)/2

This also happens to be the number of times through the loop.

(n^2 - n) / 2
(n^2)/2 - n/2

When representing Big O, only term with the highest power is used and constants are thrown away, and thus the answer is O(n2).

More about this particular problem can be read on CS.SE at Big O: Nested For Loop With Dependence


Title: Time-complexity of nested for loop

Body:
I have loops like this:

```<code>for(int i = 0; i < n; i++) {
    for(int j = 0; j < i; j++) {
        sum += 1;
    }
}
</code>```

It's O(n * ), but I'm not sure what the j < i loop is.

I have some tests that I ran,

```<code>n = 10, runs = 45

n = 20, runs = 190

n = 40, runs = 780

n = 80, runs = 3160

n = 10, runs = 12720
</code>```

It seems to be converging onto .5*n^2, but I'm not quite sure.

Body:
if i==0   then  j ranges from 0 to -1  ==> (not possible)  0
if i==1   then  j ranges from 0 to 0   ==>                 1
if i==2   ,,     ,,             ,, 1   ==>                 2
.
.
.
if i==n-1  then  j from    0 to n-2    ==>                 n-1 iterations

summing them

It is    S = 0   + 1   + 2 + 3 +.......+ n-2  +  n-1
same as  S = n-1 + n-2 + ......        +  1   +   0

summing  2*S= (n-1) + (n-1) +.............(n-1)  //n times

==>  2*S = (n-1)*n
==>  S=    (n-1)*n/2


问:
How do you move beyond code examples without a project?
I am currently learning Scala and I find a mental blog of how to proceed to a degree where I can use Scala daily beyond the normal examples. I just do not have a particular project in mind of what I can do.

This is not really Scala specific in mind, just generally how do you get yourself proficient in a language via self learning without doing / having a project in your hand?

答:
You set yourself a small project, sometimes enlarging an existing code example, sometimes thinking about the language's strengths - e.g., if you're learning a language designed for practical extraction and reporting, you'll aim for some kind of extraction report, say, a log analyzer.

The fact is that whatever makes you pull your weight in any given language is a project. Even if the project aim is "learn me this language".

So with Scala, you might try with a simple web service producing/consuming XML packets (there are small examples for that; you can start by studying them and tying them together).

You'll want to start small because this kind of project, with a none-too-defined goal, tends to snowball; for example you might decide to develop both a web service and its client. This snowballing isn't a bad thing if you keep it under control, that is, you do not bite more than you can chew at any one time. You might be tempted to add database querying before you're sure of your "web service management" skills; if you do, you risk reaping an overwhelming crop of bugs and grow dissatisfied and disillusioned about the language and/or your own skills. Better to return mock-up data and placeholders for all the things you're not yet assured of; that will also give you a measure of how many topics you still have to cover.

This, however, is just my own point of view. You might want, or even need, to find your own way, the one that suits you best.


答:
If you already have (small) projects in another language that are also suited for you new language. Try rewrite one of those projects to your new language and then trying to follow as much as possible the best practices of your new language.

This will help illustrate the differences in thinking you need between two different approaches. And help avoid the pitfall of "programming the old way in a new language".
This helped me a lot with not using "old" contructs. Which would happen if I tried a new project in a new language.

Title: How do you move beyond code examples without a project?

Body:
I am currently learning Scala and I find a mental blog of how to proceed to a degree where I can use Scala daily beyond the normal examples. I just do not have a particular project in mind of what I can do.

This is not really Scala specific in mind, just generally how do you get yourself proficient in a language via self learning without doing / having a project in your hand?


问:
How important is to initialize a variable
How important is it to initialize variables?

Does proper initializing avoid memory leaks or have performance advantages?

答:
There is no problem with uninitializing variables.

The problem is only when you read a variable that has not been written yet.

Depending on the compiler and/or on the kind of variable, initialization is performed at application startup. Or not.

It is common usage to not rely on automatic initialization.


问:
Are the IETF BCP 47 language tags defined as enums anywhere in JDK?
Are the IETF BCP 47 language tags defined as enums anywhere in JDK?

For Locale.forLanguageTag() we pass values like fr-FR, jp-JP etc.

Are there any enums already provided by JDK for it? Or should the developer be writing a custom enum for that? How to handle it in i18n application?

答:
JDK does not contain an enum for IETF BCP 47 language tags. Inside Oracle JDK they are expressed inside a non-public string array of a sun.util.* class. You should not get them from there.

In Java 7 you can iterate over available locales and call toLanguageTag() for each one or, as you say, create your own enum.


问:
Dynamic initialization, how does it work?
I  have a question regarding dynamic initialization.

Example code

```<code>void main()
{
int a = 100;
//Statement1
//Statement2
...
float b = 6.32987; //StatementA
...
return;
}
</code>```

The StatementA allocates memory at the middle execution of program. How does process takes place and where does space gets allocated for variable b (stack  or heap)?

答:
C is not an interpreted language.

A typical C compiler will analyze the source code, during this analysis it will find all the automatic variables allocated in a function and assign them a suitable place on the stack.

In your example the variable is assigned an initial value. The compiler will generate the code to initialize all such variables every time the function is entered, this will typically take place before any of your code is executed.

The position of the definition in the source code has no effect on the code the compiler generates to reserve storage for and initialize the variable.

Also note that for many compilers using aggressive optimization many of the above steps will be optimized out of existence. For instance all initialized variables may be gathered together in a block and a single block copy used to initialize them with a single instruction.


答:
Enum would be wrong way for this in JDK API which is supposed to serve wide variety of applications.

It would be also wrong in application development, unless the application is purposedly designed to serve a fixed, limited subset of languages - subset that is known at compile time - which, in turn, would hardly qualify as related to BCP-47.

This is because substantial attribute of BCP-47 is addressing an open-ended set of values:

Language tags are used to help identify languages, whether spoken, written, signed, or otherwise signaled, for the purpose of communication.  This includes constructed and artificial languages but excludes languages not intended primarily for human communication, such as programming languages...

The ietf-languages list is an open list...

Above, in turn, makes it wrong fit for enum, which is intended to serve fixed, limited sets of values:

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time - for example, the choices on a menu, command line flags, and so on...

Body:
Are the IETF BCP 47 language tags defined as enums anywhere in JDK?

For Locale.forLanguageTag() we pass values like fr-FR, jp-JP etc.

Are there any enums already provided by JDK for it? Or should the developer be writing a custom enum for that? How to handle it in i18n application?


问:
Is it sufficient to use acceptance and integration tests instead of unit test?
Short introduction to this question. I have used now TDD and lately BDD for over one year now.  I use techniques like mocking to make writing my tests more efficiently. Lately I have started a personal project to write a little money management program for myself. Since I had no legacy code it was the perfect project to start with TDD. Unfortunate I did not experience the joy of TDD so much. It even spoiled my fun so much that I have given up on the project.

What was the problem? Well, I have used the TDD like approach to let the tests / requirements evolve the design of the program. The problem was that over one half of the development time as for writing / refactor tests. So in the end I did not want to implement any more features because I would need to refactor and write to many test.

At work I have a lot of legacy code. Here I write more and more integration and acceptance tests and less unit tests. This does not seem to be a bad approach since bugs are mostly detected by the acceptance and integration tests.

My idea was, that I could in the end write more integration and acceptance tests than unit tests. Like I said for detecting bugs the unit tests are not better than integration / acceptance tests. Unit test are also good for the design. Since I used to write a lot of them my classes are always designed to be good testable. Additionally, the approach to let the tests / requirements guide the design leads in most cases to a better design. The last advantage of unit tests is that they are faster. I have written enough integration tests to know, that they can be nearly as fast as the unit tests.

After I was looking through the web I found out that there are very similar ideas to mine mentioned here and there. What do you think of this idea?

Edit

Responding to the questions one example where the design was good,but I needed a huge refactoring for the next requirement:

At first there were some requirements to execute certain commands. I wrote an extendable command parser - which parsed commands from some kind of command prompt and called the correct one on the model. The result were represented in a view model class:

There was nothing wrong here. All classes were independent from each other and the I could easily add new commands, show new data.

The next requirement was, that every command should have its own view representation - some kind of preview of the result of the command. I redesigned the program to achieve a better design for the new requirement:

This was also good because now every command has its own view model and therefore its own preview.

The thing is, that the command parser was changed to use a token based parsing of the commands and was stripped from its ability to execute the commands. Every command got its own view model and the data view model only knows the current command view model which than knows the data which has to be shown.

All I wanted to know at this point is, if the new design did not break any existing requirement. I did not have to change ANY of my acceptance test. I had to refactor or delete nearly EVERY unit tests, which was a huge pile of work.

What I wanted to show here is a common situation which happened often during the development. There were no problem with the old or the new designs, they just changed naturally with the requirements - how I understood it, this is one advantage of TDD, that the design evolves.

Conclusion

Thanks for all the answers and discussions. In summary of this discussion I have thought of an approach which I will test with my next project.

First of all I write all tests before implementing anything like I always did.

For requirements I write at first some acceptance tests which tests the whole program. Then I write some integration tests for the components where I need to implement the requirement. If there is a component which work closely together with another component to implement this requirement I would also write some integration tests where both components are tested together. Last but not least if I have to write an algorithm or any other class with a high permutation - e.g. a serializer - I would write unit tests for this particular classes. All other classes are not tested but any unit tests.

For bugs the process can be simplified. Normally a bug is caused by one or two components. In this case I would write one integration test for the components which tests the bug. If it related to a algorithm I would only write a unit test. If it is not easy to detect the component where the bug occurs I would write an acceptance test to locate the bug - this should be an exception.

答:
It's comparing oranges and apples.

Integration tests, acceptance tests, unit tests, behaviour tests - they are all tests and they will all help you improve your code but they are also quite different.

I'm going to go over each of the different tests in my opinion and hopefully explain why you need a blend of all of them:

Integration tests:

Simply, test that different component parts of your system integrate correctly - for example - maybe you simulate a web service request and check that the result comes back. I would generally use real (ish) static data and mocked dependencies to ensure that it can be consistently verified.

Acceptance tests:

An acceptance test should directly correlate to a business use case. It can be huge ("trades are submitted correctly") or tiny ("filter successfully filters a list") - it doesn't matter; what matters is that it should be explicitly tied to a specific user requirement. I like to focus on these for test-driven development because it means we have a good reference manual of tests to user stories for dev and qa to verify.

Unit tests:

For small discrete units of functionality that may or may not make up an individual user story by itself - for example, a user story which says that we retrieve all customers when we access a specific web page can be an acceptance test (simulate hitting the web page and checking the response) but may also contain several unit tests (verify that security permissions are checked, verify that the database connection queries correctly, verify that any code limiting the number of results is executed correctly) - these are all "unit tests" that aren't a complete acceptance test.

Behaviour tests:

Define what the flow should be of an application in the case of a specific input. For example, "when connection cannot be established, verify that the system retries the connection." Again, this is unlikely to be a full acceptance test but it still allows you to verify something useful.

These are all in my opinion through much experience of writing tests; I don't like to focus on the textbook approaches - rather, focus on what gives your tests value.


问:
How should one debug a PHP web application securely without exposing secrets to competitors?
Recently I made a program. I forget to delete 2 line of codes. That mistake cost me $800 per day every day.

I was programming with PHP. If a visitor uses proxy it redirect somewhere else. Using debugger was impossible because some code contains ioncube. Because the program simply redirect somewhere else no matter what, it's hard to see which part of the code is executed.

So I put a bunch debugging info everywhere. I thought I'll delete them latter anyway.

The most natural way to debug is of course to put debugging info into a file. The problem is I often use proxy. So after I change the program, I often have to download the text file with filezilla. Often the text file does not show what I think it should show. Finally I decided to just display error on the web.

I considered having debugging mode. However, I am afraid I will forget to delete debugging info.

I considered having debugging mode if user do ?debuggingmode=1 for example. However, I was paranoid that somehow my competitor can guess the secret keyword.

I deleted most debugging info. I forget to delete one and that one only show up if users use proxy from the right country. Turns out I do not have proxy from the right country and didn't realize that. After the program works for 24 hours, I uploaded that to my main domain.

My competitor, using proxy, see the debugging code. He copy the idea and that's how I lost $800 per day.

In retrospect, I really have a hard time seeing where I went wrong. I have been super careful. Yet it happened.

How should one debug a PHP web application securely without exposing secrets to competitors?

答:
This is rarely done because the effort is not worthwhile. Even if you lose $800 a day, the effort of proving a program correct quickly becomes larger than that, which implies that there is no business case for doing it.

If being certain is worth that much (e.g. for Space Shuttle software or missile control), then you perform formal verification, exhaustive testing of all possible inputs, etc. Granted, it's also extremely difficult as well as slow and expensive. But projects with billion-dollar budgets also tend to have extremely bright people on them. (Or maybe they just used to - present-day headlines seem to contradict that rule.)


答: You can come up with a small project on your own and start doing it. Initially don't go for large or hifi projects. A small simple project will be enough. Start building it up by using more and more concepts of that language.</p>


答:
The "win" with TDD, is that once the tests have been written, they can be automated. The flip side is that it can consume a significant chunk of the development time. Whether this actually slows the whole process down is moot. The argument being that the upfront testing reduces the number of errors to be fixed at the end of the development cycle.

This is where BDD comes in as behaviours can be included within the unit testing so the process is by definition less abstract and more tangible.

Clearly, if an infinite amount of time was available, you'd do as many tests of various varieties as possible. However, time is generally limited and continual testing is only cost effective to a point.

This all leads to the conclusion that the tests that provide the most value should be at the front of the process. This in itself doesn't automatically favour one type of testing over another - more that each case has to be taken on its merits.

If you're writing a command line widget for personal use, you'd primarily be interested in unit tests. Whereas a web service say, would require a substantial amount of integration/behavioural testing.

Whilst most types of test concentrate on what could be called the "racing line" i.e. testing what is required by the business today, unit testing is excellent at weeding out subtle bugs that could surface in later development phases. Since this is a benefit that can't readily be measured, it is often overlooked.

Title: Is it sufficient to use acceptance and integration tests instead of unit test?

Body:
Short introduction to this question. I have used now TDD and lately BDD for over one year now.  I use techniques like mocking to make writing my tests more efficiently. Lately I have started a personal project to write a little money management program for myself. Since I had no legacy code it was the perfect project to start with TDD. Unfortunate I did not experience the joy of TDD so much. It even spoiled my fun so much that I have given up on the project.

What was the problem? Well, I have used the TDD like approach to let the tests / requirements evolve the design of the program. The problem was that over one half of the development time as for writing / refactor tests. So in the end I did not want to implement any more features because I would need to refactor and write to many test.

At work I have a lot of legacy code. Here I write more and more integration and acceptance tests and less unit tests. This does not seem to be a bad approach since bugs are mostly detected by the acceptance and integration tests.

My idea was, that I could in the end write more integration and acceptance tests than unit tests. Like I said for detecting bugs the unit tests are not better than integration / acceptance tests. Unit test are also good for the design. Since I used to write a lot of them my classes are always designed to be good testable. Additionally, the approach to let the tests / requirements guide the design leads in most cases to a better design. The last advantage of unit tests is that they are faster. I have written enough integration tests to know, that they can be nearly as fast as the unit tests.

After I was looking through the web I found out that there are very similar ideas to mine mentioned here and there. What do you think of this idea?

Edit

Responding to the questions one example where the design was good,but I needed a huge refactoring for the next requirement:

At first there were some requirements to execute certain commands. I wrote an extendable command parser - which parsed commands from some kind of command prompt and called the correct one on the model. The result were represented in a view model class:

There was nothing wrong here. All classes were independent from each other and the I could easily add new commands, show new data.

The next requirement was, that every command should have its own view representation - some kind of preview of the result of the command. I redesigned the program to achieve a better design for the new requirement:

This was also good because now every command has its own view model and therefore its own preview.

The thing is, that the command parser was changed to use a token based parsing of the commands and was stripped from its ability to execute the commands. Every command got its own view model and the data view model only knows the current command view model which than knows the data which has to be shown.

All I wanted to know at this point is, if the new design did not break any existing requirement. I did not have to change ANY of my acceptance test. I had to refactor or delete nearly EVERY unit tests, which was a huge pile of work.

What I wanted to show here is a common situation which happened often during the development. There were no problem with the old or the new designs, they just changed naturally with the requirements - how I understood it, this is one advantage of TDD, that the design evolves.

Conclusion

Thanks for all the answers and discussions. In summary of this discussion I have thought of an approach which I will test with my next project.

First of all I write all tests before implementing anything like I always did.

For requirements I write at first some acceptance tests which tests the whole program. Then I write some integration tests for the components where I need to implement the requirement. If there is a component which work closely together with another component to implement this requirement I would also write some integration tests where both components are tested together. Last but not least if I have to write an algorithm or any other class with a high permutation - e.g. a serializer - I would write unit tests for this particular classes. All other classes are not tested but any unit tests.

For bugs the process can be simplified. Normally a bug is caused by one or two components. In this case I would write one integration test for the components which tests the bug. If it related to a algorithm I would only write a unit test. If it is not easy to detect the component where the bug occurs I would write an acceptance test to locate the bug - this should be an exception.


答:
As others have said before me, lots of tests (unit and functional), if possible automated and with good code coverage is the key to having a mostly bug-free software.

If I understand the description of your problem well enough, the debugging information is shown on the page served by your server. If that is the case, you should consider putting that information in proper logs on your server. That way it is never shown to the end user, even if you deploy a 'verbose' version to production. This is something that is good to do whatever the project you are working on unless you have very good reasons to do otherwise.

Body:
Recently I made a program. I forget to delete 2 line of codes. That mistake cost me $800 per day every day.

I was programming with PHP. If a visitor uses proxy it redirect somewhere else. Using debugger was impossible because some code contains ioncube. Because the program simply redirect somewhere else no matter what, it's hard to see which part of the code is executed.

So I put a bunch debugging info everywhere. I thought I'll delete them latter anyway.

The most natural way to debug is of course to put debugging info into a file. The problem is I often use proxy. So after I change the program, I often have to download the text file with filezilla. Often the text file does not show what I think it should show. Finally I decided to just display error on the web.

I considered having debugging mode. However, I am afraid I will forget to delete debugging info.

I considered having debugging mode if user do ?debuggingmode=1 for example. However, I was paranoid that somehow my competitor can guess the secret keyword.

I deleted most debugging info. I forget to delete one and that one only show up if users use proxy from the right country. Turns out I do not have proxy from the right country and didn't realize that. After the program works for 24 hours, I uploaded that to my main domain.

My competitor, using proxy, see the debugging code. He copy the idea and that's how I lost $800 per day.

In retrospect, I really have a hard time seeing where I went wrong. I have been super careful. Yet it happened.

How should one debug a PHP web application securely without exposing secrets to competitors?


答:
I really have a hard time seeing where I went wrong

The major mistake was that you reinvented the wheel. Instead of using default mecanisms for logging, you invented your own, which displayed the information within the page. A logging framework would rather store logs in log files, letting you to consult those logs later by SSHing to the server.

As for the bugs, producing bug-free code implies using specific techniques such as formal proof. Given their expensiveness, those techniques are appropriate for life-critical applications such as applications which control aircraft traffic or space shuttles, but are an overkill for <s>nearly</s> every business application.

■ See They write the right stuff in Fast Company magazine.

The article describes the methodology used at NASA, as well as the cost of producing software this way.

■ See Mechanizing Proof (Mackenzie 2004).

The book summarizes the history of automated proof of software, explaining the pros and cons of such proof, as well as the reasons it's not commonly used by businesses to write reliable software.

This being said, there are a bunch of techniques used for business applications to ensure software quality. Those includes but are not limited to:

Informal code reviews,

Formal code inspections,

Testing,

Personal desk-checking of code,

etc.

■ See Code complete (McConnell 2004), Programming Productivity (Jones 1986a), Software Defect-Removal Efficiency (Jones 1996), and What We Have Learned About Fighting Defects (Shull et al. 2002).

Also, don't forget continuous integration and continuous delivery. It helps in automatically rolling back the app in production to a working version when a revised one appears to have an issue which was missed during code reviews and unit testing, but caught once the app is deployed.

■ See The Secret to Safe Continuous Deployment (video)

It explains what techniques were set up at Google to prevent bugs which couldn't be found before deployment from staying for too long in production. It also describes pdiff and how was it used to catch bugs, including ones which were unrelated to presentation layer.

Title: How should one debug a PHP web application securely without exposing secrets to competitors?


问:
Effective design analysis
Our team redesigns the legacy software and there are a lot of design meetings going on. Many of them are not very effective and lack good analysis of the proposed design. Is there any formal way to approach this kind of discussions to make them more effective? I heard about SWOT for example, but afaik it is used more for business projects.</p>

答:
Try going back to the basics:

Where are you now?

Where do you want to be?

How do you get there?

What's stopping you?

Ineffective meetings are a sign of lack of purpose and commitment. Meetings should have a clear objective and commitment by those to reach it. For some of the best examples of how to run a meeting, look to professional sports. They are some of the best run meetings in the world (on time, 100% attendance from participants, commitment, engagement, clear rules and outcomes). Where possible try to emulate that.

A lack of good analysis is normally struggling to understand the problem. If you're not addressing the root cause of the issue, you are not really creating a solution. And if you are not creating a solution, you are just creating another problem.

There is a lot of process, methodologies and diagram to help with this process. OpenUP is not a bad place to look at methodology documentation if you haven't before. That should at least provide some structure and templates to implement some of the above. Another resource I find myself coming back to is Alistair's Awesome guide to pretty much everything.With those and the rest of the internet at your finger tips, you'll be off to a great start

Title: Effective design analysis