问:
Why is there no generic implementation of OrderedDictionary in .net?
Why did Microsoft not provide generic implementation of OrderedDictionary?

There are a few custom implementations I've seen, including: http://www.codeproject.com/KB/recipes/GenericOrderedDictionary.aspx

But why did Microsoft not include it in the base .net library? Surely they had a reason for not building a generic.... but what is it?

Prior to posting this message, I did see:
https://stackoverflow.com/questions/2629027/no-generic-implementation-of-ordereddictionary

But that just confirms that it does not exist. Not why it does not exist.

Thanks

答:
The OrderedDictionary overloads the indexing operation so that indexing with an integer N will get the item in position N, while indexing with an Object will retrieve the item coresponding to that object.  If one were to create an OrderedDictionary<int, string> called myDict, and added items (1,"George") and (0,"Fred") in that order, should myDict[0] return "George" or "Fred"?

Such an issue could have been resolved by imposing a class constraint on the key type.  On the other hand, much of the usefulness of generic collections stems from their ability to efficiently work with value types.  Imposing a class constraint on the key type would seem a little ugly.

If the class didn't have to be CLS compliant but merely had to work with vb.net, a sensible design might have been to used named indexed properties.  Thus, in the example above, myDict.ByKey[0] would have yielded "Fred", and myDict.BySequence[0] would have yielded "George".  Unfortunately, languages like C# do not support named indexed properties.  While one could have kludged something to allow use of the above syntax even without such properties, the unfortunate decision to wrap the fields of structures like Point and Rectangle means that for myDict.ByKey[0] = "Wally" to work, myDict.ByKey would have to return a new class object.  A struct would be more efficient, but compilers would reject what looked like a write to a read-only structure (notwithstanding that the property wouldn't modify the struct returned by ByKey, but instead modify the collection to which it holds a reference).

Personally, I think a dictionary-ish object that was specified as keeping track of the insertion order would be a nice thing to have; I'd also like to have a dictionary-ish object which could easily return the key associated with a particular key (so that, e.g. if one has a case-insensitive dictionary and has added a record with a key of "GEORGE", one could ask the dictionary what key is associated with "George" without having to search through all the KeyValuePair objects returned in an enumeration.


问:
Could it be more efficient for systems in general to do away with Stacks and just use Heap for memory management?
It seems to me that everything that can be done with a stack can be done with the heap, but not everything that can be done with the heap can be done with the stack. Is that correct? Then for simplicity's sake, and even if we do lose a little amount of performance with certain workloads, couldn't it be better to just go with one standard (ie, the heap)?

Think of the trade-off between modularity and performance. I know that isn't the best way to describe this scenario, but in general it seems that simplicity of understanding and design could be a better option even if there is a potential for better performance.

答:
Modern computers have several layers of cache memory in addition to a large, but slow, main memory system.  One can make dozens of accesses to the fastest cache memory in the time required to read or write one byte from the main memory system.  Thus, accessing one location a thousand times is much faster than accessing 1,000 (or even 100) independent locations once each.  Because most applications repeatedly allocate and deallocate small amounts of memory near the top of the stack, the locations on the top of the stack get used and re-used an enormous amount, such that the vast majority (99%+ in a typical application) of stack accesses can be handled using cache memory.

By contrast, if an application were to repeatedly create and abandon heap objects to store continuation information, every version of every stack object that was ever created would have to be written out to main memory.  Even if the vast majority of such objects would be completely useless by the time the CPU wanted to recycle the cache pages they started out in, the CPU would have no way of knowing that.  Consequently, the CPU would have to waste a lot of time performing slow memory writes of useless information.  Not exactly a recipe for speed.

Another thing to consider is that in many cases it's useful to know that an object reference passed to a routine will not be used once the routine exits.  If parameters and local variables are passed via the stack, and if inspection of the routine's code reveals that it does not persist a copy of the passed-in reference, then the code which calls the routine can be sure that if no outside reference to the object existed before the call, none will exist afterward.  By contrast, if parameters were passed via heap objects, concepts like "after a routine returns" become somewhat more nebulous, since if code kept a copy of the continuation, it would be possible for the routine to "return" more than once following a single call.

ContentLicense: CC BY-SA 3.0


问:
Refactoring obscurely commented code
In refactoring code, I came across code that had comments.  Looking closer at the comments, I could see that the code was clearly not doing what the comments said.

Without access to the coder nor documentation, and without clear direction regarding the code (i.e. defects as to the fact that the code is operating incorrectly), is the best practice to assume that the code is correct, and clean up the comments?

答:
This is where source control is helpful.  See if the code ever matched the comments.  If it did match but was changed later, see if the check-in comment and other changes made in the same check-in adequately explain the reason for the change.  If it does, then update the code comments.

If you can't get any hints from source control, you pretty much have to assume either code or comments could be wrong.  Figure out what the consequences to changing the code to match would be.  If it improves the code, then do it.  If it doesn't, then remove or change the comments.

If you can't tell on your own, your code doesn't automatically become the authoritative source on how the program should behave, your customer always retains that role.  If both behaviors look equally valid to you, ask your customer which they prefer.  Point out the existing behavior, your reasons for suspecting it may need to be changed, and the consequences for doing so.

Title: Refactoring obscurely commented code


问:
Pure C++ for iOS apps
Is it possible to use only C++ to create iOS apps? Is there any downside to that? I read somewhere that you have to use a mix of objective C and C++ if you want to use C++ that bad.</p>

答:
For the user interface on iOS you need objective C, for the remainder you can use C++. Wether or not using C++/Obj C and not pure objective C depends primarily on your C++ skills. If you are already fluent in C++, doing part of the development in that might pay off. If not, going for pure obj C is probably a better choice. See also

stackoverflow.com/questions/8759573/utilizing-c-in-ios-and-mac-os-x-applications

Title: Pure C++ for iOS apps


答:
I'll add a bit more color to the explanation given by Paul above.

There are two main areas where you must interface your c++ with ObjC to make a functional app:

You must interface with the runloop provided by UIKit to receive event notifications such as touches and app state changes.

To display content on screen, you need to either wrap UIKit / CoreAnimation or provide content via the EAGL / GLKit apis (OpenGL ES).

If you want access other capabilities of the device, they're typically only provided via an ObjC api, though sometimes they are also available at a lower level with a C API (such as audio and the address book).

In general, I tend to make most of the app ObjC, but then use C++ to help with the efficient implementation of some subsystems. In general, modern ObjC plays very well with C++ as they use both internally at Apple.

Title: Pure C++ for iOS apps

Body: Is it possible to use only C++ to create iOS apps? Is there any downside to that? I read somewhere that you have to use a mix of objective C and C++ if you want to use C++ that bad.</p>


问:
Combining template method with strategy
An assignment in my software engineering class is to design an application which can play different forms a particular game. The game in question is Mancala, some of these games are called Wari or Kalah. These games differ in some aspects but for my question it's only important to know that the games could differ in the following:

The way in which the result of a move is handled

The way in which the end of the game is determined

The way in which the winner is determined

The first thing that came to my mind to design this was to use the strategy pattern, I have a variation in algorithms (the actual rules of the game). The design could look like this:

I then thought to myself that in the game of Mancala and Wari the way the winner is determined is exactly the same and the code would be duplicated. I don't think this is by definition a violation of the 'one rule, one place' or DRY principle seeing as a change in rules for Mancala wouldn't automatically mean that rule should be changed in Wari as well. Nevertheless from the feedback I got from my professor I got the impression to find a different design.

I then came up with this:

Each game (Mancala, Wari, Kalah, ...) would just have attribute of the type of each rule's interface, i.e. WinnerDeterminer and if there's a Mancala 2.0 version which is the same as Mancala 1.0 except for how the winner is determined it can just use the Mancala versions.

I think the implementation of these rules as a strategy pattern is certainly valid. But the real problem comes when I want to design it further.

In reading about the template method pattern I immediately thought it could be applied to this problem. The actions that are done when a user makes a move are always the same, and in the same order, namely:

deposit stones in holes (this is the same for all games, so would be implemented in the template method itself)

determine the result of the move

determine if the game has finished because of the previous move

if the game has finished, determine who has won

Those three last steps are all in my strategy pattern described above. I'm having a lot of trouble combining these two. One possible solution I found would be to abandon the strategy pattern and do the following:

I don't really see the design difference between the strategy pattern and this? But I am certain I need to use a template method (although I was just as sure about having to use a strategy pattern).

I also can't determine who would be responsible for creating the TurnTemplate object, whereas with the strategy pattern I feel I have families of objects (the three rules) which I could easily create using an abstract factory pattern. I would then have a MancalaRuleFactory, WariRuleFactory, etc. and they would create the correct instances of the rules and hand me back a RuleSet object.

Let's say that I use the strategy + abstract factory pattern and I have a RuleSet object which has algorithms for the three rules in it. The only way I feel I can still use the template method pattern with this is to pass this RuleSet object to my TurnTemplate. The 'problem' that then surfaces is that I would never need my concrete implementations of the TurnTemplate, these classes would become obsolete. In my protected methods in the TurnTemplate I could just call ruleSet.determineWinner(). As a consequence, the TurnTemplate class would no longer be abstract but would have to become concrete, is it then still a template method pattern?

To summarize, am I thinking in the right way or am I missing something easy? If I'm on the right track, how do I combine a strategy pattern and a template method pattern?

答:
Let's get down to brass tacks. There is absolutely no need for any Game interface, no design patterns, no abstract classes, and no UML.

If you have a reasonable amount of support classes, like UI, simulation, and whatever, then basically all of your non-game-logic-specific code is re-used anyway. Moreover, your user does not change his game dynamically. You do not flip at 30Hz between games. You play one game for about half an hour. So your "dynamic" polymorphism is not actually dynamic at all. It's rather static.

So the sensible way to go here is to use a generic functional abstraction, like C#'s Action or C++'s std::function, create one Mancala, one Wari, and one Kalah class, and go from there.

```<code>std::unordered_map<std::string, std::function<void()>> games = {
    { "Kalah", [] { return Kalah(); } },
    { "Mancala", [] { return Mancala(); } },
    { "Wari", [] { return Wari(); } }
};
void play() {
    std::function<void()> f;
    f = games[GetChoiceFromUI()];
    f();
    if (PlayAgain()) return play();
}
int main() {
    play();
}
</code>```

Done.

You don't call Games. Games call you.

Title: Combining template method with strategy

Body:
Let's get down to brass tacks. There is absolutely no need for any Game interface, no design patterns, no abstract classes, and no UML.

If you have a reasonable amount of support classes, like UI, simulation, and whatever, then basically all of your non-game-logic-specific code is re-used anyway. Moreover, your user does not change his game dynamically. You do not flip at 30Hz between games. You play one game for about half an hour. So your "dynamic" polymorphism is not actually dynamic at all. It's rather static.

So the sensible way to go here is to use a generic functional abstraction, like C#'s Action or C++'s std::function, create one Mancala, one Wari, and one Kalah class, and go from there.

std::unordered_map<std::string, std::function<void()>> games = {
    { "Kalah", [] { return Kalah(); } },
    { "Mancala", [] { return Mancala(); } },
    { "Wari", [] { return Wari(); } }
};
void play() {
    std::function<void()> f;
    f = games[GetChoiceFromUI()];
    f();
    if (PlayAgain()) return play();
}
int main() {
    play();
}

Done.

You don't call Games. Games call you.


答: If you're being distracted by design patterns my advice to you would be to prototype the game first then patterns should just jump out at you. I don't think it's really possible or advisable to try to design a system perfectly first and then implement it (in a similar way I find it perplexing when people try to write entire programs first and then compile, rather then doing it bit by bit.) The trouble is that it's unlikely you'll think of every scenario your logic will have to deal with, and during the implementation phase you'll either lose all hope or try to stick to your original flawed design and introduce hacks, or even worse deliver nothing at all.</p>

Title: Combining template method with strategy

Body:
An assignment in my software engineering class is to design an application which can play different forms a particular game. The game in question is Mancala, some of these games are called Wari or Kalah. These games differ in some aspects but for my question it's only important to know that the games could differ in the following:

The way in which the result of a move is handled

The way in which the end of the game is determined

The way in which the winner is determined

The first thing that came to my mind to design this was to use the strategy pattern, I have a variation in algorithms (the actual rules of the game). The design could look like this:

I then thought to myself that in the game of Mancala and Wari the way the winner is determined is exactly the same and the code would be duplicated. I don't think this is by definition a violation of the 'one rule, one place' or DRY principle seeing as a change in rules for Mancala wouldn't automatically mean that rule should be changed in Wari as well. Nevertheless from the feedback I got from my professor I got the impression to find a different design.

I then came up with this:

Each game (Mancala, Wari, Kalah, ...) would just have attribute of the type of each rule's interface, i.e. WinnerDeterminer and if there's a Mancala 2.0 version which is the same as Mancala 1.0 except for how the winner is determined it can just use the Mancala versions.

I think the implementation of these rules as a strategy pattern is certainly valid. But the real problem comes when I want to design it further.

In reading about the template method pattern I immediately thought it could be applied to this problem. The actions that are done when a user makes a move are always the same, and in the same order, namely:

deposit stones in holes (this is the same for all games, so would be implemented in the template method itself)

determine the result of the move

determine if the game has finished because of the previous move

if the game has finished, determine who has won

Those three last steps are all in my strategy pattern described above. I'm having a lot of trouble combining these two. One possible solution I found would be to abandon the strategy pattern and do the following:

I don't really see the design difference between the strategy pattern and this? But I am certain I need to use a template method (although I was just as sure about having to use a strategy pattern).

I also can't determine who would be responsible for creating the TurnTemplate object, whereas with the strategy pattern I feel I have families of objects (the three rules) which I could easily create using an abstract factory pattern. I would then have a MancalaRuleFactory, WariRuleFactory, etc. and they would create the correct instances of the rules and hand me back a RuleSet object.

Let's say that I use the strategy + abstract factory pattern and I have a RuleSet object which has algorithms for the three rules in it. The only way I feel I can still use the template method pattern with this is to pass this RuleSet object to my TurnTemplate. The 'problem' that then surfaces is that I would never need my concrete implementations of the TurnTemplate, these classes would become obsolete. In my protected methods in the TurnTemplate I could just call ruleSet.determineWinner(). As a consequence, the TurnTemplate class would no longer be abstract but would have to become concrete, is it then still a template method pattern?

To summarize, am I thinking in the right way or am I missing something easy? If I'm on the right track, how do I combine a strategy pattern and a template method pattern?


问:
Selling software instead of on-demand work
Doing on-demand work stresses me out and is not good for my back.

What tips could you offer if you have experience in spotting needs and writing custom software to suit ?

答:
In my experience, customers are rarely interested in non-custom software that doesn't come with support and/or enhancements. So unless you are writing defect-free and complete software, you will end up doing "on-demand" work on your custom software to patch bugs or add critical features. That is, developing your own code doesn't do much to avoid stressful on-demand work. I suspect the scale and culture of your company is the best way to moderate stressful on-demand work.

But the software I've been involved in, even our non-customer specific is still oriented towards large sales and heavy customization. I suppose if you can avoid that, you will go further to controlling your release cycle. The more customers you have, the less they need to pay; the less they pay, the less they expect immediate fixes from you.


问:
Free cloud web service development
I am looking for a free (as in beer) combination of services, for learning "cloud SW development" and very small scale private use (say, a private streamlined web shopping&todo list with simple auth). The combination should include the full set of needed services:

DVCS service (like github)

A cloud service to run the backend code

A suitable data storage service (preferably not SQL), accessed by the backend (if not included in the backend service)

A web service, serving the web pages seen by user, to access the backend functionality

A "cloud IDE" (ideally one, two is ok too) for both backend and HTML/javascript coding

If (backend) deployment uses some CI, then that

Other points:

Backend programming language can be anything, except VB or PHP

Everything has to be in the cloud, nothing permanent on a local PC (graphics is not part of the question)

Looking for ready-to-use service combination, not a virtual server where I can set anything up myself

I don't care if service insists on displaying ads in the user web UI

"Cheap" and "free trial" are ok too, if "free" does not exist

As per example use case, storage, CPU and bandwidth quota requirements are negligible

Google finds several services of course, all requiring at least registration before testing, so I'm looking for a known-good combination, so ideal answer starts with "I use this service combo: ...", contains links to services and brief description and personal experiences.

答:
How about Heroku? It has a free plan and offers:

A cloud service to run the backend code

A web service, serving the web pages seen by user, to access the backend functionality - If you write the static file handling yourself

A suitable data storage service, accessed by the backend - Both SQL and NoSQL

Backend programming languages: Clojure, Java, Python, Scala, Ruby, Javascript

Ready-to-use service combination

No ads.

It meets just about all of your criteria, but has some pretty strict limitations. The uploaded code size is limited to 100MB (which should be plenty if you're not hosting large files)and the databases are limited to 10,000 rows or 16MB, depending on your choice.

You have a couple of criteria it doesn't meet, however:

DVCS service

A "cloud IDE" for both backend and HTML/javascript coding

Title: Free cloud web service development


问:
Steps to create a solution for a problem
I am a trainee. According to my teacher to solve a problem we should go through following steps:

Create Algorithm (optional)

Create a Datatable: By analyzing the problem, create main concepts in those problem as columns and the related issues in the main concept as rows.

Create a Flowchart based on the Datatable. (when creating flow chart, think that you are in that situation and design it in your brain)

By seeing the Flowchart, one can solve the problem easily and in efficient way.

These steps should always be considered by a programmer if he/she wants to become a Software designer (not just a programmer) because this approach gives an efficient way of finding solution to a problem even if the problem is small. According to him, this way of approach also works in real time scenario's.

My question is: Is this really an efficient way? please share also your thoughts.

Through this question I also wanted to share some thoughts of my teacher with you who is a good mentor.

答:
What your teacher is trying to do is train you to think about abstractions, abstract thinking is an extremely important problem solving technique.

The specific workflow your teacher laid out for you, the four steps, is an incredibly basic workflow and a far cry from being efficient for non trivial software development problems. However it's a good enough training methodology, and it will be efficient when you are faced with real life (but trivial) scenarios. Keep in mind that learning is mostly an incremental process, you need to learn the basics first, and that's what you are doing right now.

Further reading:

When to prefer a generalized solution over solving specific cases

Abstraction: The War between solving the problem and a general solution

How can I improve my problem-solving ability?

https://softwareengineering.stackexchange.com/questions/152668/solving-programming-problems-or-contributing-code

https://softwareengineering.stackexchange.com/questions/146913/teaching-programming-by-solving-puzzles

And a couple of relevant blog posts:

Please Learn to Think about Abstractions

General Problem Solving Strategies (for programmers)


答:
These steps should always consider by a programmer if he/she wants to become a Software designer (not programmer).

What do you mean by Software designer? I tried searching the difference between Programmer and Software Designer and I was flooded with Programmer v/s Software engineer.

Because the above approach gives an efficient way of finding solution to a problem even the problem is small. According to him, this way of approach also works in real time scenario's.

The Programmer also has to solve a problem or find its solution therefore your teacher saying that this approach (The one you mentioned in your question) is to be used by software designer and not programmer.

My question is: Is this really an efficient way? please share also your thoughts.

Don't know. As a student I have never done all these things i.e. algorithms etc. I just do my coding, make some DFD (Data flow diagram), ER diagram and some related documentation things and submit it.

As far as industries are concerned i think they have separate teams for all these things like coding team, documentation team,

Title: Steps to create a solution for a problem

Body:
I am a trainee. According to my teacher to solve a problem we should go through following steps:

Create Algorithm (optional)

Create a Datatable: By analyzing the problem, create main concepts in those problem as columns and the related issues in the main concept as rows.

Create a Flowchart based on the Datatable. (when creating flow chart, think that you are in that situation and design it in your brain)

By seeing the Flowchart, one can solve the problem easily and in efficient way.

These steps should always be considered by a programmer if he/she wants to become a Software designer (not just a programmer) because this approach gives an efficient way of finding solution to a problem even if the problem is small. According to him, this way of approach also works in real time scenario's.

My question is: Is this really an efficient way? please share also your thoughts.

Through this question I also wanted to share some thoughts of my teacher with you who is a good mentor.


答:
Teachers may encourage students to approach problems in a structured way because it breeds good habits and fosters a structured mindset, both of which are good things.

If you polled all software developers with more than two years of experience, I bet that they would all tell you that software developers do not follow any such formal, prescribed, structure, but that they can appreciate the meta-lesson that your teacher is trying to teach.

While this specific step-by-step approach isn't awful per se, I can tell you that it's missing a critical first step.

After performing a certain amount of research on your problem, your first step should be:

Ask yourself: Am I solving the right problem?

Indeed, when solving a problem, whether it be implementing a greenfield feature or fixing a bug, many software developers either fail, implement a sub-optimal solution, or simply waste time because they did not first introspect and ask themself if they were solving the right problem.

Two points about this:

The amount of preliminary research that you will need to do before you can ask yourself if you are solving the right problem will vary according to the problem.

Your ability to know if you are solving the right problem is a function of experience. So always ask yourself the question, and your ability to answer it will improve as you gain experience.


问:
good c++ editor
I'm going to teach teenagers some C++ code. I need an editor which is simple and has built in compiler. We tried CodeBlocks but when we installed it in the machines, the text got reversed, I'm not sure what the reaoson is. I would be great if the file size of the editor will not be large.

We need just simple features:

-Text highlight.

-Compile and run.

-easy to  use

-Should run on Windows XP.

答:
You can use Dev C++.

Dev-C++ is an full-featured Integrated Development Environment (IDE) for Win32. It uses GCC, Mingw or Cygwin as compiler and libraries set.

You can find this superseded by http://sourceforge.net/projects/orwelldevcpp/.

It is also licensed as GNU General Public License version 3.0.

Includes MinGW GCC 4.6.2 32bit.

Includes TDM-GCC 4.6.1 64bit.

Provides syntax highlighting for code, header and resource files.

Supports code completion and autocomplete.

Shows information about code when hovering above code.

Supports GPROF profiling.

Provides user-editable shortcuts and tools.

Supports multiple languages.

Supports GNU GDB debugging.

Supports code folding.

Supports devpak IDE extensions.

Title: good c++ editor


问:
Is there any difference between return n and exit(n) in C?
Is there any difference between return n (in the main function) and exit(n) in C? Is it defined by C or POSIX standards or it depends on OS or compiler?

答:
For C

The Standard says that a return from the initial call to main is equivalent to calling exit. However, a return from main cannot be expected to work if data local to main might be needed during cleanup.

For C++

When exit(0) is used to exit from program, destructors for locally scoped non-static objects are not called. But destructors are called if return 0 is used.

Program 1 – - uses exit(0) to exit

```<code>#include<iostream>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

class Test {
public:
  Test() {
    printf("Inside Test's Constructor\n");
  }

  ~Test(){
    printf("Inside Test's Destructor");
    getchar();
  }
};

int main() {
  Test t1;

  // using exit(0) to exit from main
  exit(0);
}
</code>```

Output:
Inside Test’s Constructor

Program 2 – uses return 0 to exit

```<code>#include<iostream>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

class Test {
public:
  Test() {
    printf("Inside Test's Constructor\n");
  }

  ~Test(){
    printf("Inside Test's Destructor");
  }
};

int main() {
  Test t1;

   // using return 0 to exit from main
  return 0;
}
</code>```

Output:
Inside Test’s Constructor

Inside Test’s Destructor

Calling destructors is sometimes important, for example, if destructor has code to release resources like closing files.

Note that static objects will be cleaned up even if we call exit(). For example, see following program.

```<code>#include<iostream>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

class Test {
public:
  Test() {
    printf("Inside Test's Constructor\n");
  }

  ~Test(){
    printf("Inside Test's Destructor");
    getchar();
  }
};

int main() {
  static Test t1;  // Note that t1 is static

  exit(0);
}
</code>```

Output:
Inside Test’s Constructor

Inside Test’s Destructor

Body:
For C

The Standard says that a return from the initial call to main is equivalent to calling exit. However, a return from main cannot be expected to work if data local to main might be needed during cleanup.

For C++

When exit(0) is used to exit from program, destructors for locally scoped non-static objects are not called. But destructors are called if return 0 is used.

Program 1 – - uses exit(0) to exit

#include<iostream>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

class Test {
public:
  Test() {
    printf("Inside Test's Constructor\n");
  }

  ~Test(){
    printf("Inside Test's Destructor");
    getchar();
  }
};

int main() {
  Test t1;

  // using exit(0) to exit from main
  exit(0);
}

Output:
Inside Test’s Constructor

Program 2 – uses return 0 to exit

#include<iostream>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

class Test {
public:
  Test() {
    printf("Inside Test's Constructor\n");
  }

  ~Test(){
    printf("Inside Test's Destructor");
  }
};

int main() {
  Test t1;

   // using return 0 to exit from main
  return 0;
}

Output:
Inside Test’s Constructor

Inside Test’s Destructor

Calling destructors is sometimes important, for example, if destructor has code to release resources like closing files.

Note that static objects will be cleaned up even if we call exit(). For example, see following program.

#include<iostream>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

class Test {
public:
  Test() {
    printf("Inside Test's Constructor\n");
  }

  ~Test(){
    printf("Inside Test's Destructor");
    getchar();
  }
};

int main() {
  static Test t1;  // Note that t1 is static

  exit(0);
}

Output:
Inside Test’s Constructor

Inside Test’s Destructor


问:
Quantifying the value of refactoring in commercial terms
Here is the classic scenario; Dev team build a prototype. Business mgmt like it and put it into production. Dev team now have to continue to deliver new features whilst at the same time pay the technical debt accrued when the code base was a prototype.

My question is this (forgive me, it's rather open ended); how can the value of the refactoring work be quantified in commercial terms?

As developers we can clearly understand and communicate the value in technical terms, such a the removal of code duplication, the simplification of an object model and so on.  But this means little to an executive focussed on the commercial elements.  What will mean something to this executive is the dev. team being able to deliver requirements at faster velocity.  Just making this statement without any metrics that clearly quantify return on investment (increased velocity in return for resource allocated to refactoring) carries little weight.

I'm interested to hear from anyone who has had experience, positive or negative, in relation to the above.

----------------- EDIT ----------------

Thanks for the responses so far, all of which I think are good.  What I want to develop is a metric that proves (or disproves!) all of these statements. A report that ties velocity to refactoring and shows a positive effect.

答:
I've had some success by explaining these advantages:

Less bugs in the future (even sales people know bugs are bad).

Easier, faster and cheaper to fix bugs in the future.

Easier, faster and cheaper to make enhancements to the product.

Easier, faster and cheaper to add entirely new features to the product.

Easier, faster and cheaper to integrate with 3rd party systems.

The earlier you can start refactoring, the less technical debt you'll carry and the better the product will be (1-5 will be easier).

I've had limited success with terms like technical debt, some commercial people get it, some think it's just the techie people trying to justify doing their own thing, it all depends on the person you're trying to explain it to.

One strategy that works well (as long as you don't let technical debt accumulate too much) is paying it off a bit at a time by doing small-medium refactorings at the start of the next enhancement/feature/change that the sales people want.

Make it part of their request, "sure, we can do that, we'll need to enhance this part of the system to support this new feature first though."

If you can get actual metrics for how much time will be saved by doing refactorings then great, personally I've found that a double-estimate works better since all commercial people know stats can be manipulated and dev stats (depending on the person) can be seen as self-serving.

By double-estimate I mean "sure, feature X will take 3 days if we fix sub-system Y, otherwise you're looking at X+Z days to work around it. Plus it'll reduce our support calls and make the planned feature W faster to add."

If people like metrics then combine the time spent on support calls about feature/product X with my double-estimate, this way you could produce a graph/spreadsheet/costings to show the cost of feature X based on on-going support calls with a reduction estimate from refactorings.

Over time, you could produce actual figures for feature X before and after the refactoring.

Getting actual figures for development costs is trickier since each feature is only implemented once (hopefully!) one idea is to keep track of how long the refactorings take and produce a double-estimate graph by adding in any refactoring costs as a "what it would have cost without refactoring", which is hopefully higher than your actual estimate, this should make the time/cost savings very obvious.

Basically with a cleaner codebase pretty much everything can be done faster and therefore cheaper than it could otherwise, which delivers extra value and a better ROI for the commercial guys.


答:
Been there many times.

There are some ways to handle it, no easy one though.

You almost said it yourself: they only care you deliver as fast as possible. Show the stakeholders a business case where a X month refactoring round will reduce the time it take to develop new rounds - and try to estimate some ROI - return of investment, after a year or so, for the refactoring.

Or, if this is very hard, there are other economical arugments that might help - "Given we are running a prototype in production, we need to hire two more engineers to maintain it. This cost can be avoided if we take on a refactoring project.".

If you have internal cost centers etc. make sure the operational people supporting this application charges more for it, than similar "production worthy" applications.

If your team has some control, it might be possible embedd refactoring in the new feature deveopment phases. Say, they want to input complex hierarchies into an already shitty data model - include refactoring as a tech requirement to even make any changes to the data model. A similar case: if you ask your plumber to change the radiator, if the pipe is too rusty to function properly, he will prob. change that too, since its his profession to know what to do. The same thing (should) goes for software devs.

If you hit the wall, gather stats for your arguments. Tag each bug/operational issue that is reported that could have been avoided by production worthy code. Then you could show a business case by reducing the bugs with so-and-so many %, and increase the uptime/stability by another %.

However, there is always a fact that software developer want to make the best possible solution, when only "good enough" will do. If you can't make up economical arguments for refactoring, it's probably not worth it and should not be done.

Title: Quantifying the value of refactoring in commercial terms

Body:
Here is the classic scenario; Dev team build a prototype. Business mgmt like it and put it into production. Dev team now have to continue to deliver new features whilst at the same time pay the technical debt accrued when the code base was a prototype.

My question is this (forgive me, it's rather open ended); how can the value of the refactoring work be quantified in commercial terms?

As developers we can clearly understand and communicate the value in technical terms, such a the removal of code duplication, the simplification of an object model and so on.  But this means little to an executive focussed on the commercial elements.  What will mean something to this executive is the dev. team being able to deliver requirements at faster velocity.  Just making this statement without any metrics that clearly quantify return on investment (increased velocity in return for resource allocated to refactoring) carries little weight.

I'm interested to hear from anyone who has had experience, positive or negative, in relation to the above.

----------------- EDIT ----------------

Thanks for the responses so far, all of which I think are good.  What I want to develop is a metric that proves (or disproves!) all of these statements. A report that ties velocity to refactoring and shows a positive effect.


答:
I find SteB's answer (which I have upvoted) very good. I would like to elaborate on one point in his answer (as an example which might be applied to other points as well).

Easier, faster and cheaper to made enhancements to the product.

How to convince management of this?

Suppose you have just had release 1 of product X.

You already know that feature Y is planned for release 2 and feature Z is almost surely required for release 3.

Then you can make an estimate (perform a grooming session with poker cards) and afterwards go to your managers and say:

With the current code, feature Y will take 8 weeks, feature Z will take 6 weeks.

With the refactored code, feature Y will take 4 weeks, feature Z will take 2 weeks. Refactoring will take 2 weeks.

So you have the following scenarios:

Release 2 with feature Y. Feature Y costs 8 weeks without refactoring, 6 weeks with refactoring.

Release 2 and 3, with both feature Y and Z. Feature Y and Z cost 12 weeks without refactoring and 8 weeks with refactoring.

This is of course just a sketch but IMO if you can produce a similar analysis you might have more chances of convincing you management: it means you have a concrete idea of the benefits of your refactoring, even though it is only an estimate.

NOTE: If you find it difficult to produce a similar analysis, ask yourself what the chances are that you ain't gonna need it.


答:
Its worth noting that C standard (C99) defines two types of execution environments, Freestanding Environment and Hosted Environment. Freestanding environment is a C environment which does not support the C libraries and is intended for embedded applications and the like. A C environment which supports the C libraries is called a Hosted environment.

C99 says, in a Freestanding environment program termination is implementation defined. So, if the implementation defines main, return n, and exit, their behaviors are as is defined in that implementation.

C99 defines Hosted environment behavior as,

If the return type of the main function is a type compatible with it, a return from the
  initial call to the main function is equivalent to calling the exit function with the value
  returned by the main function as its argument; reaching the } that terminates the main
  function returns a value of 0. If the return type is not compatible with int, the
  termination status returned to the host environment is unspecified.

Title: Is there any difference between return n and exit(n) in C?

Body: Is there any difference between return n (in the main function) and exit(n) in C? Is it defined by C or POSIX standards or it depends on OS or compiler?


问:
What does "Human Readable" mean? Is it a misnomer?
Two examples spring to mind:

One of the reasons that .Net programmers are encouraged to use .config files instead of the Windows Registry is that .config files are XML and therefore human-readable.

Similarly, JSON is sometimes considered human-readable compared with a proprietary format.

Are human-readable formats actually readable by humans? In the example of configuration data:

The format doesn't change the underlying meaning of the information - in both cases, the data represents the same thing.

Both registry and .config file are stored internally as a series 0s and 1s. To that extent, the underlying representaion is equally unreadable by humans.

Both registry and .config file require a tool to read, format and display those 0s and 1s and convert them into a format that humans can read. In the case of configuration stored in the Windows Registry, this is a Registry Editor. In the case of XML it could be a text editor or XML reader. Either way, the tool makes the data readable, not the data format.

So, what is the difference between human-readable data formats and non-human-readable formats?

答: Short answer: It means the information is entered as text, rather than binary or hex, etc.  Something that equates with a readable "language" rather than a computer "machine language".  Beyond that, the definition gets murky.</p>

ContentLicense: CC BY-SA 2.5


问:
How representative is Ohloh?
My colleague recently pointed me to Ohloh, a website providing statistics on FOSS based on versioning repositories. It's quite a fun procrastination tool, e.g. to compare programming languages by active projects:

Which makes me wonder: how representative is such a comparison? Can we draw conclusions from this such as "Javascript is the most used programming language in FOSS, followed closely by Python, Java and C++"? Or are there some big caveats to take into account?

答:
It would be a good idea to compare with Github and Google Code and anywhere else that there is a lot of FOSS development. I don't know how to do a language frequency chart for Google Code. However, Github does offer that, and they even did a blog post about it in December 2010 or early 2011.

Regardless of the results of a frequency comparison chart by language, you still need to take into account all the caveats mentioned already in the prior answers. It isn't meaningful to infer anything about popularity when aggregating without first thinking about your data. As others have mentioned, you probably want to do some or all of the following before doing a frequency comparison:

Remove data from any projects that have been inactive for one year or longer

Account for the fact that there is so much C because of Linux usage in FOSS, and not overweight that

Account for anything else that gets included but isn't actually part of the code being developed (very vague sounding, I realize, but this might be different depending on the language e.g. like function libraries)

Title: How representative is Ohloh?


答:
After looking at your designs, both your first and third iterations appear to be more elegant designs. However, you mention that you're a student and your professor gave you some feedback. Without knowing exactly what your assignment or the purpose of the class is or more information about what your professor suggested, I would take anything I say below with a grain of salt.

In your first design, you declare your RuleInterface to be an interface that defines how to handle each player's turn, how to determine if the game is over, and how to determine a winner after the game ends. It seems like that's a valid interface to a family of games that experiences variation. However, depending on the games, you might have duplicated code. I'd agree that the flexibility to change the rules of one game is a good thing, but I'd also argue that code duplication is terrible for defects. If you copy/paste defective code between implementations and one has a bug in it, you now have multiple bugs that need to be fixed in different locations. If you rewrite the implementations at different times, you could introduce defects in different locations. Neither of those is desirable.

Your second design seems rather complex, with a deep inheritance tree. At least, it's deeper than I would expect for solving this type of problem. You're also starting to break up implementation details into other classes. Ultimately, you are modeling and implementing a game. This might be an interesting approach if you were required mix-and-match your rules for determining the results of a move, the end of the game, and a winner, that doesn't seem to be in the requirements that you've mentioned. Your games are well defined sets of rules, and I'd try to encapsulate the games as much as I can into separate entities.

Your third design is one that I like the best. My only concern is that it's not at the right level of abstraction. Right now, you appear to be modeling a turn. I would recommend considering designing the game. Consider that you have players who are making moves on some kind of board, using stones. Your game requires these actors to be present. From there, your algorithm is not doTurn() but playGame(), which goes from the initial move to the final move, after which it terminates. After every player's move, it adjusts the state of the game, determines if the game is in a final state, and if it is, determines the winner.

I would recommend taking closer looks at your first and third designs and working with them. It might also help to think in terms of prototypes. What would the clients that use these interfaces look like? Does one design approach make more sense for implementing a client that's actually going to instantiate a game and play the game? You need to realize what it's interacting with. In your particular case, it's the Game class, and any other associated elements - you can't design in isolation.

Since you mention you're a student, I'd like to share a few things from a time when I was the TA for a software design course:

Patterns are simply a way of capturing things that have worked in the past, but abstracting them to a point where they can be used in other designs. Each catalog of design patterns gives a name to a pattern, explains its intentions and where it can be used, and situations where it would ultimately constrain your design.

Design comes with experience. The best way to get good at design isn't to simply focus on the modeling aspects, but realize what goes into the implementation of that model. The most elegant design is useful if it can't easily be implemented or it doesn't fit into the larger design of the system or with other systems.

Very few designs are "right" or "wrong". As long as the design fulfills the requirements of the system, it can't be wrong. Once there's a mapping from each requirement into some representation of how the system is going to meet that requirement, the design can't be wrong. It's only a qualitative at this point about concepts such as flexibility or reusability or testability or maintainability.

Title: Combining template method with strategy


答:
Putting a prototype into production is worse than a poorly design project because too many decision makers believe it is better than it really is. Throughout the prototype building process, you were reminding everyone that "This is not ready for production." The odds of getting to this point were low because they weren't sure that:

It could be built.

Anyone was going to really need/use it.

Don't focus on "I told you so" but make it clear you are not going to be able to maintain the schedule of the prototype nor can you use any of those metrics to determine how long it will take to create production ready features. They will see the product function, but remind them of problems such as:

It may not be able to handle a larger number of users

The error handling isn't enough for the typical user

It can't accomodate many of the newly requested features.

There is little to no testing

Non-technical members of upper-management aren't going to grasp the concept of refactoring. They've got it in their head this "it works" and they will not release that thought for the entire length of the project no matter how many times you say something to the contray. You're just going to have to make it part of your specifications. Technical managers may be under severe time pressure and may try and throw many of these tasks out of the project specifications. "Why are we working on features that are already completed?" Some of the other ansers provide some ways of explaining why this isn't the case.

Good luck


答:
Your confusion is justified.  The thing is that patterns aren't mutually exclusive.

Template method is the basis for a bunch of other patterns, such as Strategy and State.  Essentially, the Strategy interface contains one or more template methods, each requiring all objects implementing a strategy to have (at least) something like a doAction() method.  This allows the strategies to be substituted for one another.

In Java, an interface is nothing but a set of template methods.  Likewise, any abstract method is essentially a template method.  This pattern (among others) was well known to the designers of the language, so they built it in.

@ThomasOwens offers excellent advice on approaching your particular problem.

Title: Combining template method with strategy


答:
From the C standard's perspective, not really, other than return being a statement and exit() being a function.  Either will cause any functions registered with atexit() to be called followed by termination of the program.

There are a couple of situations you want to watch out for:

Recursion in main().  While rarely seen in practice, it is legal in C.  (C++ explicitly forbids it.)

Re-use of main().  Sometimes an existing main() will be renamed something else and be called by a new main().

The use of exit() will introduce a bug if either of those happens after you've written the code, especially if not terminating abnormally.  To avoid that, it's a good idea to be in the habit of treating main() as the function it is and using return when you want it to end.


问:
Does license matter if I host a maven repository?

If I make a maven repository available for others to use, do I have
to get permission form the authors of those software that I host in
my repository even if they are free software?

Can I host free software libraries under any license or should they
have compatible licenses?

答:
Free software can be redistributed without restrictions (other than providing the source code, which is required in some licenses, but I assume that is actually what you would be redistributing).

The license of the libraries you host does not need to be the same or compatible, for redistribution purposes. If you do not change the source code in any of those libraries (e.g. mixing them up), you should be fine.


问:
When to use DAG (Directed Acyclic Graph) in programming?
I recently found a framework named ecto.

In this framework, a basic component named "plasm", which is the ecto Directed Acyclic Graph.In ecto, plasm can be operated by ecto scheduler.

I am wondering what's the advantage of this mechanism, and in what other situations can we exploit the concept of DAG?

答:
The answer is that it doesn't have much of anything to do with programming. It has to do with problem solving.

Just like linked-lists are data structures used for certain classes of problems, graphs are useful for representing certain relationships. Linked lists, trees, graphs, and other abstract structures only have a connection to programming in that you can implement them in code. They exist at a higher level of abstraction. It's not about programming, it's about applying data structures in the solution of problems.

If still you want some relationship with programming then please consider following points:

DAG (known as Wait-For-Graphs - more technical details) are handy in detecting deadlocks as they illustrate the dependencies amongst a set of processes and resources (both are nodes in the DAG). Deadlock would happen when a cycle is detected.

Once you have the DAG in memory, you can write algorithms to:

make sure the computations are evaluated in the correct order (topological sort)

if computations can be done in parallel but each computation has a maximum execution time, you can calculate the maximum execution time of the entire set


答:
Nice Question.

Code may be represented by a DAG describing the
inputs and outputs of each of the arithmetic operations performed
within the code; this representation allows the compiler to perform
common subexpression elimination efficiently.

Most Source Control Management Systems implement the revisions as a
DAG.

Several Programming languages describe systems of values that are
related to each other by a directed acyclic graph. When one value
changes, its successors are recalculated; each value is evaluated as
a function of its predecessors in the DAG.

DAG are handy in detecting deadlocks as they illustrate the
dependencies amongst a set of processes and resources.

In many randomized algorithms in computational geometry, the
algorithm maintains a history DAG representing features of some
geometric construction that have been replaced by later finer-scale
features; point location queries may be answered, as for the above
two data structures, by following paths in this DAG.

Once we have the DAG in memory, we can write algorithms to
calculate the maximum execution time of the entire set.

While programming spreadsheet systems, the dependency graph that
connects one cell to another if the first cell stores a formula that
uses the value in the second cell must be a directed acyclic graph.
Cycles of dependencies are disallowed because they cause the cells
involved in the cycle to not have a well-defined value. Additionally,
requiring the dependencies to be acyclic allows a topological order
to be used to schedule the recalculations of cell values when the
spreadsheet is changed.

Using DAG we can write algorithms to evaluate the computations in
the correct order.

EDIT :

Ordering of formula cell evaluation when recomputing formula values
in spreadsheets can be done using DAGs

Git uses DAGs for content storage, reference pointers for heads,
object model representation, and remote protocol.

DAGs is used at Trace scheduling: the first practical approach for
global scheduling, trace scheduling tries to optimize the control
flow path that is executed most often.

Ecto is a processing framework and it uses DAG to model processing
graphs so that the graphs do ordered synchronous execution. Plasm in
Ecto is the DAG and Scheduler operates on it.

DAGs is used at software pipelining, which is a technique used to
optimize loops, in a manner that parallels hardware pipelining.

Good Resources :

http://www.biomedcentral.com/1471-2288/8/70

http://www.ncbi.nlm.nih.gov/pubmed/12453109

http://www.ericsink.com/vcbe/html/directed_acyclic_graphs.html

http://xlinux.nist.gov/dads/HTML/directAcycGraph.html

Title: When to use DAG (Directed Acyclic Graph) in programming?

Body:
I recently found a framework named ecto.

In this framework, a basic component named "plasm", which is the ecto Directed Acyclic Graph.In ecto, plasm can be operated by ecto scheduler.

I am wondering what's the advantage of this mechanism, and in what other situations can we exploit the concept of DAG?


问:
Is a university education worth it for a good programmer?
I've been doing design and programming for about as long as I can remember. If there's a programming problem, I can figure it out. (Though admittedly Stack Overflow has allowed me to skip the figuring out and get straight to the doing in many instances.) I've made games, esoteric programming languages, and widgets and gizmos galore. I'm currently working on a general-purpose programming language. There's nothing I do better than programming.

Is a university education really more than just a formality?

答:
I'm in a very similar position as you. Yes, a university education is worth it, and here is my "testimony" as to why: I've done some crazy programming stuff in the past five years and I'm now starting an iPhone app for my company, all self-taught, with the same background as yourself. Recently, I contacted a couple of highly recommended headhunters to see about making the switch from my technical job to being a full-time programmer. In both instances, the conversation with them abruptly stopped—and I mean no contact—when I had to say "No" to the question "Do you have a college degree?"

You need this more than you know, and a couple years' more hassle is going to pay dividends long after you've gotten past this.

Keep calm and carry on.


问:
How to manage a Closed Source High-Risk Project?
I am currently planning to develop a J2EE website and wish to bring in 1 developer and 1 web designer to assist me. The project is a financial app within a niche market.

I plan to keep the source closed. However, I fear that my would-be employees could easily copy the codebase and use it or sell it to a third party. The app development will take 4-6 months, perhaps more, and I may bring in additional employees after the app goes live.

But how do I keep the source to myself. Are there techniques companies use to guard their source?

I foresee disabling USB drives and DVD writers on my development machines, but uploading data or attaching the code in email would still be possible.

My question is incomplete. But programmers who have been in my situation, please advice. How should I go about this? Building a team, maintaining code-secrecy,etc.

I am looking forward to sign a secrecy contract with the employees if needed too.
(Please add relevant tags)

Update

Thank you for all the answers. I certainly won't be disabling all USB ports and DVD writers now. But I think I should be logging activity(How exactly should I do that?) I am wary of scalpers who would join and then run off with the existing code. I haven't met any, but I have been advised to be wary of them. I would include a secrecy clause, but given this is a startup with almost no funding and in a highly competitive business niche with bigger players in the field, I doubt I would be able to detect or pursue any scalpers.

How do I hire people I trust, when I don't know them personally. Their resume will be helpful but otherwise trust will develop only with time.

But finally even if they do run away with the code, it is service that matters after the sale is made. So I am not really worried for the long term.

答:
As others have mentioned, this primarily seems to be a people concern.

However, there are a number of major security vendors who market software solutions to data leaks:

http://www.symantec.com/data-leak-prevention

http://www.mcafee.com/us/products/total-protection-for-data-loss-prevention.aspx

http://www.trendmicro.com/us/enterprise/data-protection/index.html

http://www.cisco.com/en/US/netsol/ns895/index.html

http://www.emc.com/security/rsa-data-loss-prevention.htm

I can't comment to their effectiveness or appropriateness as I have limited experience with these solutions, but just thought that it might be helpful to point this out.


答:
I like to answer this through non-technical analogies.

Some examples:

You can easily build houses up to 5 stories tall with bricks.  You can easily add on a single floor.  But try and go to 20 or 30 floors and suddenly bam! the tiles are exploding because you need a better infrastructure like steel beams.  Turns out that infrastructure is important and getting it right as early as possible through 'refactoring' the initial...

You drive your gar.  All it needs to run is gas!  Well, that and... oil changes frequently.  Oh and infrequently, new tires, and occasionally other fluids and parts. Turns out that maintenance is part of being a responsible car owner...


答: Currently DAG is underrated in programming. Historically many things related to development were made with trees and hierarchies because moving something in a box is convenient for our brain to make complex things easier to manage. But if you look at events and how they depend on other events and states then you will get DAG because anything in our life and in the program can depend on anything in the past but not in the future, so you would get perfectly "acyclic" relations to be applicable to DAG concept. Although this rarely used explicitly in development, having this in mind would help to understand things better  </p>


问:
Thoughts on Development using Virtual Machines
I'll be working as a development lead for a startup and I've suggested that we use VMs for development.  I'm not talking about each developer having a desktop with VMs for testing/development, I mean having a server rack where all VMs are managed and have the developers work from a microPC (ChromeOS anyone?) locally, or even remotely from their home computer.

To me, the benefits are the fact that it's extremely scalable, cheaper in the long run, easier to manage and that we utilize the hardware its maximum potential.  As for cons, I can't think of any particular showstoppers other than we'll need someone to setup/maintain said setup.

I was hoping that some of you might of had a similar setup at your place of employment and be able to weight in with your opinions.  Thanks.

答:
I have been working on a legacy-project concerning 5 machines, each one has a role in a computation pipeline (machine 1 sends request to machine 2, ehich in turn will send request to machine 3 etc). The setting deployment on virtual machine saved us HUGE time however:
1. The system was undebuggable as devs were lazy/did not have time to encorporate testing in the design.
2. Too many setups were deployed on and I needed to consume time on arranging them in groups.

Now I use it because I work on too many projects at once. The main problem I have now are:
1. VMs are consuming way too much time to maintain.
2. VMs are consuming enormous amounts of memory to run

This kinda renders VMs hard to use when you try to use them to have order. Keep one main machine with your email and text, develop on dediacated VMs. Keeps your life neat and clean at a cost.


问:
What is the best objective way to measure language popularity trends? (What's better than TIOBE?)
The best way to get data on computer language popularity that I know is the TIOBE index.  But everyone knows that TIOBE is hopelessly flawed.  (If someone provides a link to support this, I'll add it here.)

So is there any data on programming language popularity that is generally considered meaningful?  The only other option I know is to look at the trends at indeed.com, which is inherently flawed, being based on job postings.

It isn't like I would make a future language decision solely based on an index, but it might provide a useful balance to the skewed perspective one obtains by talking to ones friends and colleagues.

To illustrate that bias, I'll point out that based on the experience of those I personally know, the only languages used professionally today (in order of popularity) are Java, C#, Groovy, JavaScript, Ruby, Objective C, and Perl.  (Though it is evident that C, C++ and PHP were used in the past.)

So my question is, everyone bashes TIOBE, but is there anything else?  If so, can anyone explain how we know the alternative has better methodology?  Thanks.

答:
As I've commented before:

"but there is no better source to measure language popularity" --
  that's because there's no need for
  one. Nobody with any sense cares about
  rankings - so long as your language is
  alive and doing what you need it to,
  there's no need to worry about a silly
  arbitrary ranking.


问:
What's the best language to use for a simple windows 7 dynamic gui desktop app
[Note: I hope I am not breaking etiquette, but I originally posted a variant on this question here, but am re-asking here because I am making this now solely a question about programming.]

I would like to program of the following simple form:

The user can produce X number of resizable frames (analogous to HTML frames).

Each frame serves as a simple text editor, which you can type into and save the whole configuration including resized windows and text.

The user should be able alternately "freeze" and present the information, and "unfreeze" and edit frames.

Thus it will be a cross between a calendar and a text editor. I don't particularly care if it is a web application or not. What languages are ideal for such a setup? I know some C and Python and Html, and am willing to learn others if need be. It seems to me this should be a relatively easy program to make, but I need a little direction before starting.

EDIT: My OS is Windows 7.

答:
You could potentially use any language out there. If you're looking for a free option, WPF would be a great choice, and you get the bonus of incredibly beautiful interfaces (provided you put enough effort and time into it).

If you're willing to sink some cash into it, Embarcadero offer C++ Builder and Delphi, both of which can take advantage of/ship with the Firemonkey framework which is similar to WPF, except it's exceptionally easy to create "custom components" via styling. If your example, you could simply composite the text box/memo inside a TSelection which would allow them to resize and move the frames around, save it inside a TStylebook, and then reference that style when you create the object (presumably at runtime, unless you want to have a specific, and small, amount of frames).

Actually saving the positions is exceptionally easy in just about any language, and the use of a TIniFile, or a TMemIniFile (due to it not being limited to 64KB file size), or even better by using JSON, would make this part very easy. "Locking and unlocking" of frames would also be done similarly across languages by simply toggling the enabled property of the frame.

You'd be able to run this application created in Firemonkey on any Windows OS from XP right up to and including 8, as well as various versions of Mac OS X. As said, you would need to sink some cash into it, but they do offer a free trial for it. I've personally used the above advice in my own applications, so i can vouch for it being possible (and very easy), but there's numerous options out there and your task is a relatively easy one.


答:
In most cases, there's no difference, but here's a C program that's likely to behave differently depending on whether it uses return 0; or exit(0);:

```<code>#include <stdio.h>
#include <stdlib.h>

static char *message;

void cleanup(void) {
    printf("message = \"%s\"\n", message);
}

int main(void) {
    char local_message[] = "hello, world";
    message = local_message;
    atexit(cleanup);
#ifdef USE_EXIT
    puts("exit(0);");
    exit(0);
#else
    puts("return 0;");
    return 0;
#endif
}
</code>```

Because of the atexit() call, either exit(0); or return 0; causes the cleanup function to be invoked. The difference is that if the program calls exit(0);, the cleanup happens while the "call" to main() is still active, so the local_message object still exists. Executing return 0;, however, immediately terminates the invocation of main() and then invokes the cleanup() function. Since cleanup() refers (via the global message pointer) to an object that's allocated locally to main, and that object no longer exists, the behavior is undefined.

Here's the behavior I see on my system:

```<code>$ gcc -DUSE_EXIT c.c -o c && ./c
exit(0);
message = "hello, world"
$ gcc c.c -o c && ./c
return 0;
message = ""
$
</code>```

Running the program without -DUSE_EXIT could do anything, including crashing or printing "hello, world" (if the memory used by local_message happens not to be clobbered).

In practice, though, this difference only shows up if objects defined locally inside main() are made visible outside main() by saving pointers to them. This could plausibly happen for argv. (Experiment on my system shows that the objects pointed to by argv and by *argv continue to exist after returning from main(), but you shouldn't depend on that.)

Body:
In most cases, there's no difference, but here's a C program that's likely to behave differently depending on whether it uses return 0; or exit(0);:

#include <stdio.h>
#include <stdlib.h>

static char *message;

void cleanup(void) {
    printf("message = \"%s\"\n", message);
}

int main(void) {
    char local_message[] = "hello, world";
    message = local_message;
    atexit(cleanup);
#ifdef USE_EXIT
    puts("exit(0);");
    exit(0);
#else
    puts("return 0;");
    return 0;
#endif
}

Because of the atexit() call, either exit(0); or return 0; causes the cleanup function to be invoked. The difference is that if the program calls exit(0);, the cleanup happens while the "call" to main() is still active, so the local_message object still exists. Executing return 0;, however, immediately terminates the invocation of main() and then invokes the cleanup() function. Since cleanup() refers (via the global message pointer) to an object that's allocated locally to main, and that object no longer exists, the behavior is undefined.

Here's the behavior I see on my system:

$ gcc -DUSE_EXIT c.c -o c && ./c
exit(0);
message = "hello, world"
$ gcc c.c -o c && ./c
return 0;
message = ""
$

Running the program without -DUSE_EXIT could do anything, including crashing or printing "hello, world" (if the memory used by local_message happens not to be clobbered).

In practice, though, this difference only shows up if objects defined locally inside main() are made visible outside main() by saving pointers to them. This could plausibly happen for argv. (Experiment on my system shows that the objects pointed to by argv and by *argv continue to exist after returning from main(), but you shouldn't depend on that.)


答:
Other people have applied DAG to data, but I think it is at least as applicable (if not more so) to code.  Mahbubur R Aaman mentions this, so really this is more of an addendum to his answer than a complete answer on its own.

It occurs to me than any imperative computer program that is free of infinite loops (thanks @AndresF.) is a Directed Acyclic Graph (DAG).  Meaning that the possible paths of execution of the code are directed (first this, then that), and acyclic (not forming infinite loops).  They are a graph because the path through any significant code is rarely as simple as a list or a tree.

I worked in XSLT for maybe 4 years.  I had a terrible time trying to explain why it was not a good general purpose programming language, but DAG is the reason.  Specifically, XSLT is a data driven language.  You define functions (yes, in the functional-programming sense) but you don't necessarily call these functions from your code.  Rather, XSLT sets up a combination of selection of, and iteration through, the nodes of an input XML document.  This lets the structure of the input data determine which functions are called and in what order.

This was very interesting and very cool until your program encountered a data condition that you didn't test for at 2:30 AM and you had to wake up and fix it.  When you let the data define the DAG, then the definition of the DAG becomes all the possible input conditions - which for any non-trivial business application are beyond incalculable; they are unimaginable.

At first I thought that functional programming may not be a DAG because execution order is sometimes not clear to, or even thought about by the programmer.  But a functional program does define dependencies.  In fact, the declarative nature of functional programming could be thought of as defining only dependencies (a^2 = b^2 + c^2) without specifying execution order (it does not matter whether 'b' or 'c' is squared first, so long as they are both squared before being added together).

But while Functional programming may be deliberately vague about order of operations at a detailed level, it is exquisitely clear about dependencies.  These are the very features that make it so amenable to concurrency.  In any case, there is still a graph of paths through the code, and that graph is still directed (dependencies must be evaluated before dependent tasks), so I think DAG applies there as well.

Nice question - thanks for posting!


答:
I am wondering what's the advantage of Plasm in Ecto...

DAG can be used to model a collection of tasks in a sequence with the constraint that certain tasks must be done before the others. Ecto is a processing framework and it uses DAG to model processing graphs so that the graphs do ordered synchronous execution. Plasm in Ecto is the DAG and Scheduler operates on it.

in what other situations can we exploit the concept of DAG?

DAWG is a data structure that represents a set of strings and allows for a query operation that tests whether a given string belongs to the set in time proportional to its length.

Git uses DAGs for content storage, reference pointers for heads, object model representation, and remote protocol.


答: As a real world example, our software is similar to an IDE where the end user can define a series of operations to be performed on an image (machine vision inspection). These inspections can have dependencies on other inspections or may have inspections dependent upon them. Since this is all configurable by the end user, we cannot make optimizations for parallel processing at design time. By representing these inspections and dependencies as a DAG, we can optimize the parallelism of the overall inspection for maximum performance at run time.</p>


答:
Can you even unambiguously define what refactoring is?  Merging two procedures is probably refactoring.  But what about changing the name of an object?  A method?  A public variable?  A private variable?  What if you change the implementation of a method without changing its signature?  What if that change makes it slow for a certain kind of input which in turn causes a change in a distant part of code?  I guess what I'm saying is that you need a really clear definition of what you are trying to measure before you can choose a way or a few ways of measuring it.

This is also hard because you don't immediately see the benefit of refactoring.  Let's say that you turned 5 objects with 12 methods into 3 objects with 5 methods.  It will save you lots of time in the future, but it doubled the time you took to deliver the current feature.  So it's a short-term loss to the business for a hypothetical long term gain.  Refactoring sometimes even makes things worse even though it often makes them better.

Let's assume that refactoring means that a change in one part of the code requires you to change another part of the code in such a way that the functionality of the entire program is (more or less) preserved, but the way that it works internally is different.  By definition then, the end user will generally not see the the effect of the refactoring (unless it improves performance or allows a simplification of the user interface which still provides the same baseline functionality to the user).

So you have to measure things in the long term to show a positive impact, and by definition it is an indirect impact.  I thought about this all day today and it reminded me of a study published in Time magazine a few years ago about what makes people live the longest.  Instead of asking people how much they smoked or drank carbonated beverages or whatever, they looked at the longest lived populations on the planet and analyzed hundreds (or thousands) of diet, lifestyle, and environmental factors to determine which ones were common among those where were long-lived and rare for people in general.

I'm sorry that I can't think of a metric that you could measure every month and show with a little graph how you are refactoring better than ever, or directly correlate refactoring to your company's bottom line.  But I think you (or a CS department at an affiliated university) could look at characteristics of successful software teams to see if refactoring is something that sets them apart or not.  I would suspect that it would, but would be extremely interested in seeing a study.  Maybe someone else on this forum can point to such a study?


问:
Why did memory-managed languages like Java, Javascript, and C# retain the `new` keyword?
The new keyword in languages like Java, Javascript, and C# creates a new instance of a class.

This syntax seems to have been inherited from C++, where new is used specifically to allocate a new instance of a class on the heap, and return a pointer to the new instance.  In C++, this is not the only way to construct an object. You can also construct an object on the stack, without using new - and in fact, this way of constructing objects is much more common in C++.

So, coming from a C++ background, the new keyword in languages like Java, Javascript, and C# seemed natural and obvious to me.  Then I started to learn Python, which doesn't have the new keyword.  In Python, an instance is constructed simply by calling the constructor, like:

```<code>f = Foo()
</code>```

At first, this seemed a bit off to me, until it occurred to me that there's no reason for Python to have new, because everything is an object so there's no need to disambiguate between various constructor syntaxes.

But then I thought - what's really the point of new in Java?  Why should we say Object o = new Object();?  Why not just Object o = Object();?  In C++ there's definitely a need for new, since we need to distinguish between allocating on the heap and allocating on the stack, but in Java all objects are constructed on the heap, so why even have the new keyword?  The same question could be asked for Javascript.  In C#, which I'm much less familiar with, I think new may have some purpose in terms of distinguishing between object types and value types, but I'm not sure.

Regardless, it seems to me that many languages which came after C++ simply "inherited" the new keyword - without really needing it.  It's almost like a vestigial keyword.  We don't seem to need it for any reason, and yet it's there.

Question: Am I correct about this?  Or is there some compelling reason that new needs to be in C++-inspired memory-managed languages like Java, Javascript and C# but not Python?

答: In C# new is important to distinguish between objects created on the stack vs. the heap. Frequently we create objects on the stack for better performance. See, when a object on the stack goes out of scope, it disappears immediately when the stack unravels, just like a primitive. There is no need for the garbage collector to keep track of it, and there is no extra overhead of the memory manager to allocate the necessary space on the heap. </p>


问:
Clarify the Single Responsibility Principle
The Single Responsibility Principle states that a class should do one and only one thing.  Some cases are pretty clear cut.  Others, though, are difficult because what looks like "one thing" when viewed at a given level of abstraction may be multiple things when viewed at a lower level.  I also fear that if the Single Responsibility Principle is honored at the lower levels, excessively decoupled, verbose ravioli code, where more lines are spent creating tiny classes for everything and plumbing information around than actually solving the problem at hand, can result.

How would you describe what "one thing" means?  What are some concrete signs that a class really does more than "one thing"?

答:
I really like the way Robert C. Martin (Uncle Bob) restates the Single Responsibility Principle (linked to PDF):

There should never be more than one reason for a class to change

It's subtly different from the traditional "should do only one thing" definition, and I like this because it forces you to change the way you think about your class. Instead of thinking about "is this doing one thing?", you instead think about what can change and how those changes affect your class. So for example, if the database changes does your class need to change? What about if the output device changes (for example a screen, or a mobile device, or a printer)? If your class needs to change because of changes from many other directions, then that's a sign that your class has too many responsibilities.

In the linked article, Uncle Bob concludes:

The SRP is one of the simplest of the principles, and one of the hardest to get right. Conjoining responsibilities is something that we do naturally. Finding and separating those
  responsibilities from one another is much of what software design is really about.

ContentLicense: CC BY-SA 4.0


问:
Big Oh notation does not mention constant value
I am a programmer and have just started reading Algorithms. I am not completely convinced with the notations namely Bog Oh, Big Omega and Big Theta. The reason is by definition of Big Oh, it states that there should be a function g(x) such that it is always greater than or equal to f(x). Or f(x) <= c.n for all values of n >n0.

Why don't we mention the constant value in the definition? For example, let's say a function 6n+4, we denote it as O(n). But it's not true that the definition holds good for all constant value. This holds good only when c >= 10 and n >= 1. For lesser values of c than 6, the value of n0 increases. So why we do not mention the constant value as a part of the definition?

答:
O(n) and other order notation is (typically) not concerned with the behavior of functions for small values. It is concerned with the behavior of functions for very large values, namely limits as n moves toward infinity.

The constants technically matter but they are typically abstracted away as once n becomes large enough, c's value is entirely irrelevant. If c's value is important we can include it in the analysis but unless the functions being compared have very large constant factors or if the efficiency is an especially important concern, they typically are not.


答:
Big O notation as per definition states that:

For a given function g(n), we denote by O(g(n)) the set of functions:

O(g(n)) = {f(n): there exist positive constants c and n' such that 0<=f(n)<=c.g(n) for all n > n'}

The Big O notation is built on the intuition that for all values n at and to the right of n', the value of f(n) is on or below c.g(n).

The constants also don't matter when you go to high valued (variable) factors (like n-square or n-cube) since they are just the constants and not the varying quantities which can become as big as those factors.

Given below is the graph of Big-O notation.

The essence of this notation is in the fact "how lower is f(n) from c.g(n) and not when it starts becoming lower".

Title: Big Oh notation does not mention constant value

Body:
I am a programmer and have just started reading Algorithms. I am not completely convinced with the notations namely Bog Oh, Big Omega and Big Theta. The reason is by definition of Big Oh, it states that there should be a function g(x) such that it is always greater than or equal to f(x). Or f(x) <= c.n for all values of n >n0.

Why don't we mention the constant value in the definition? For example, let's say a function 6n+4, we denote it as O(n). But it's not true that the definition holds good for all constant value. This holds good only when c >= 10 and n >= 1. For lesser values of c than 6, the value of n0 increases. So why we do not mention the constant value as a part of the definition?


问:
Where should I draw the line between unit tests and integration tests? Should they be separate?
I have a small MVC framework I've been working on. It's code base definitely isn't big, but it's not longer just a couple of classes. I finally decided to take the plunge and start writing tests for it(yes, I know I should've been doing that all along, but it's API was super unstable up until now)

Anyway, my plan is to make it extremely easy to test, including integration tests. An example integration test would go something along these lines:

Fake HTTP request object -> MVC framework -> HTTP response object -> check the response is correct

Because this is all doable without any state or special tools(browser automation etc), I could actually do this with ease with regular unit test frameworks(I use NUnit).

Now the big question. Where exactly should I draw the line between unit tests and integration tests? Should I only test one class at a time(as much as possible) with unit tests? Also, should integration tests be placed in the same testing project as my unit testing project?

答:
When I have small projects I just pop all the tests into the same project.  Since a bigger project would have these split I just ensure that it would be possible to tease them apart should it be necessary.

With unit tests I typically only test one class (SUT) in a file.


答:
I am with @maple_shaft's comment above:

Don't write bad code, even when prototyping. Think of your prototype code as a tracer bullet approach. Something that will become the final product even if it's not there yet.

You do not need to explain or justify refactoring to management - it should be a continuous part of the process. Just like you don't explain why you're doing a specific inheritance structure, using a specific framework, etc. These are technical details. Your customers only care about the outcome, whether they're management or end customers.

What you want to avoid is long downtimes where "nothing" happens as far as the outside world is concerned. E.g. you do not want to write a huge amount of bad code, then take 3 weeks to refactor it to make it good. First of all, it won't work very well; and secondly you might get tempted to explain that you're now taking time to refactor. Which to an outsider will sound like you're taking some sort of geek vacation.

Refactor early. If you see something is wrong, and it would be a bit of a pain to make it right: Do it.
Addendum to that: If you are not sure something is wrong, or don't know how to make it better, leave it alone until you do.


答:
In algorithm analysis, Order of Growth is the key abstraction and it gives the rate at which the running time changes as the input size changes. Let's say an algorithm has a running time f(n) = 2n + 3. Now we plug in some input size,

```<code>n = 10: 2 * 10 + 3 = 23

n = 100: 2 * 100 + 3 = 203

n = 10000: 2 * 10000 + 3 = 20003

n = 1000000: 2 * 1000000 + 3 = 2000003

n = 100000000 : 2 * 100000000 + 3 = 200000003
</code>```

As can be seen, order of growth is mainly determined by the variable n; constants 2 and 3 are less significant and as the input size grows they become even less significant in determining it. This is why in algorithm analysis constants are subsided in favor of the variable determining the order of growth of a function.

Body:
In algorithm analysis, Order of Growth is the key abstraction and it gives the rate at which the running time changes as the input size changes. Let's say an algorithm has a running time f(n) = 2n + 3. Now we plug in some input size,

n = 10: 2 * 10 + 3 = 23

n = 100: 2 * 100 + 3 = 203

n = 10000: 2 * 10000 + 3 = 20003

n = 1000000: 2 * 1000000 + 3 = 2000003

n = 100000000 : 2 * 100000000 + 3 = 200000003

As can be seen, order of growth is mainly determined by the variable n; constants 2 and 3 are less significant and as the input size grows they become even less significant in determining it. This is why in algorithm analysis constants are subsided in favor of the variable determining the order of growth of a function.


问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答:
I find the first option more readable. Never do the third as it can lead to bugs.

As with arguments over underscored_variable_names and camelCase though, the actual choice does not matter much.

Whatever the team or programming language convention is, go along with the stream and follow that convention.

If you vary from the convention it will make reading your code slightly harder, as your brain notices the difference instead of skimming along easily.


问:
creating object parameters in {}?
I am trying to decode a piece of code from a book:

```<code>List<Person> people = new List<Person>()
{
new Person {FirstName="Homer",LastName="Simpson",Age=47},
new Person {FirstName="Marge",LastName="Simpson",Age=45}
};
</code>```

Person is just a simple class they made, with a bunch of fields: Name, Last Name, etc...

What I don't understand is, don't we send parameters to a constructor of Person in non-curly brackets? I tried replicating this code, but it doesn't seem to fly, any takers?

Thanks for input.

答:
C# allows you to specify property parameters in curly braces when the object is initialized. This allows you to pick and choose which items to initialize and which to leave as defaults.

A constructor, on the other hand, runs one single block of code with a fixed set of parameters. So to get the same effect you'd have to create multiple constructors all with the various combinations of properties you might want to initialize, which could be tedious.

```<code>var x = new Person {FirstName="Homer",LastName="Simpson",Age=47};
</code>```

is exactly equivalent to this:

```<code>var x = new Person();
x.FirstName="Homer";
x.LastName="Simpson";
x.Age=47;
</code>```

Except that it's shorter and arguably easier on the eyes.

It also allows for constructs like you demonstrated in your question, which would be very tedious if you had to create temporary variables and initialize them out as I did here before adding them to the list. (Which is how you used to have to do it.) All without requiring an explicitly-defined constructor that takes your desired list of parameters, which may or may not be available.

Also, note that while a constructor can initialize properties with a private setter, this technique (as should be obvious from the provided example) will only work if you have a public setter for the property. Also note that my shortened example implicitly called the default (parameterless) constructor, which would therefore have to be present.

Title: creating object parameters in {}?

Body:
C# allows you to specify property parameters in curly braces when the object is initialized. This allows you to pick and choose which items to initialize and which to leave as defaults.

A constructor, on the other hand, runs one single block of code with a fixed set of parameters. So to get the same effect you'd have to create multiple constructors all with the various combinations of properties you might want to initialize, which could be tedious.

var x = new Person {FirstName="Homer",LastName="Simpson",Age=47};

is exactly equivalent to this:

var x = new Person();
x.FirstName="Homer";
x.LastName="Simpson";
x.Age=47;

Except that it's shorter and arguably easier on the eyes.

It also allows for constructs like you demonstrated in your question, which would be very tedious if you had to create temporary variables and initialize them out as I did here before adding them to the list. (Which is how you used to have to do it.) All without requiring an explicitly-defined constructor that takes your desired list of parameters, which may or may not be available.

Also, note that while a constructor can initialize properties with a private setter, this technique (as should be obvious from the provided example) will only work if you have a public setter for the property. Also note that my shortened example implicitly called the default (parameterless) constructor, which would therefore have to be present.


答: Just for another example, the memory management rules in Cocoa apps are made so that all strong references form a directed acyclic graph, which is done to guarantee the absence of leaks.</p>


答:
To allow 'nil'.

Along with heap based allocation, Java embraced the use of nil objects. Not just as an artifact, but as a feature.
When objects can have a nil state, then you have to separate declaration from initialisation. Hence the new keyword.

In C++ a line like

```<code>Person me;
</code>```

Would instantly call the default constructor.

Title: Why did memory-managed languages like Java, Javascript, and C# retain the `new` keyword?

Body:
The new keyword in languages like Java, Javascript, and C# creates a new instance of a class.

This syntax seems to have been inherited from C++, where new is used specifically to allocate a new instance of a class on the heap, and return a pointer to the new instance.  In C++, this is not the only way to construct an object. You can also construct an object on the stack, without using new - and in fact, this way of constructing objects is much more common in C++.

So, coming from a C++ background, the new keyword in languages like Java, Javascript, and C# seemed natural and obvious to me.  Then I started to learn Python, which doesn't have the new keyword.  In Python, an instance is constructed simply by calling the constructor, like:

```<code>f = Foo()
</code>```

At first, this seemed a bit off to me, until it occurred to me that there's no reason for Python to have new, because everything is an object so there's no need to disambiguate between various constructor syntaxes.

But then I thought - what's really the point of new in Java?  Why should we say Object o = new Object();?  Why not just Object o = Object();?  In C++ there's definitely a need for new, since we need to distinguish between allocating on the heap and allocating on the stack, but in Java all objects are constructed on the heap, so why even have the new keyword?  The same question could be asked for Javascript.  In C#, which I'm much less familiar with, I think new may have some purpose in terms of distinguishing between object types and value types, but I'm not sure.

Regardless, it seems to me that many languages which came after C++ simply "inherited" the new keyword - without really needing it.  It's almost like a vestigial keyword.  We don't seem to need it for any reason, and yet it's there.

Question: Am I correct about this?  Or is there some compelling reason that new needs to be in C++-inspired memory-managed languages like Java, Javascript and C# but not Python?

Body:
To allow 'nil'.

Along with heap based allocation, Java embraced the use of nil objects. Not just as an artifact, but as a feature.
When objects can have a nil state, then you have to separate declaration from initialisation. Hence the new keyword.

In C++ a line like

Person me;

Would instantly call the default constructor.


答:
There are several reasons, but probably the most important one is that constants are a function of the implementation of the algorithm, not the algorithm itself. The order of an algorithm is useful for comparing algorithms irrespective of their implementation.

The actual runtime of a quicksort will typically change if it's implemented in C or Python or Scala or Postscript. The same applies for bubble sort -- the runtime will vary widely based on implementation.

However, what will not change is the fact that, all else being equal, as the dataset gets larger the time required to run a bubble sort will increase faster than the time required to run quicksort in the typical case, no matter what language or machine they're implemented with, assuming a reasonably correct implementation. This simple fact allows you to make intelligent inferences about the algorithms themselves when concrete details are not availble.

The order of an algorithm filters out factors that, while important in actual real-world measurements, tend to just be noise when comparing algorithms in the abstract.