问:
taxonomy of software project resourcing models
I would like to understand the impact of different resourcing models for software projects.  First, I would like to identify the different resourcing approaches that are used to resource software projects. Here are some models that I can think of based in my own experiences:

Product centred resourcing

Planned resource pooling

Chaotic resource pooling

Model 1 - has resources that are product focused. In this model the project team is dedicated to a product (e.g. a SOA service). In this model, the product is the central concept and the team stays and grows with the product.  This model promotes continuous learning for the team in the product domain, and facilitates rapid development of new features because the project team is intimately knowledgeable about the product. This model seems to be very effective for evolving existing products in product centered companies.

Model 2 - pulls resources from a resource pool when starting up new projects.  This model appears to be most suitable when developing new products from scratch.  In this model team members need to acquire the domain knowledge required before starting the project.  The model does not seem to be effective for product based companies because product domain knowledge is lost when resources disband after the project completes.  This model is typical in consulting organisations.

Model 3 - is really an extension of Model 2.  In Model 3, resources are replaced with other resources mid-project.  Thus model treats resources as commodities where new project team members are expected to acquire the same knowledge as the resource that they replaced.  This model leaks the most domain knowledge, and is is characterised by low morale and low productivity. This model is usually found in organisations that are constantly fire-fighting.

Question: Is there a taxonomy of software resourcing models that I can use rather than creating my own?

答:
I'm not sure if there's a taxonomy for teams, but there are different ways of looking at teams and how they are organized and structured.

First, there are a few dimensions that you can talk about - formalization, standardization, and centralization. Formalization is the level to which rules, procedures, and written documents guide the behavior of individuals and groups. Standardization is the level to which activities are performed in a consistent manner across the organization. Centralization is the level to which the ability to make decisions is kept at the higher levels in the organization.

These three factors of discussing an organization also lead into the concept of mechanistic and organic structures. Mechanistic organizations have high degrees of standardization and formalization, often (but not necessarily) with a high degree of centralization. The end result is consistent, repeatable, and reliable performance. The other end of the spectrum is organic structures,  which give lower level employees more freedom to conduct their work how they best see fit, which often leads to more innovation at the cost of consistency and repeatability across the organization as a whole.

There are also ways of looking at the reporting structure of a team. Four views of this are the functional team structure, a lightweight team structure, a heavyweight team structure, and autonomous team structure.

In a functional team structure, everyone works in their functional departments and there is no cross-functional integration. In a lightweight team structure, everyone works within a functional department and functional managers have authority over the individuals while a project manager coordinates the functional roles with respect to an individual project. Under a heavyweight team, project managers have authority over the individuals who are provided by a functional group but will return to their functional group after their role in the project is complete. In an autonomous team, the project manager has long-term control over resources provided from functional groups.

Strategic Management of Technological Innovation by Melissa A. Schilling has a few chapters dedicated to different ways of organizing teams, specifically focusing on product development and innovation in the workplace. It's not unique to software, but may be a relevant starting point through it's citations.


问:
NT Kernel Source
Well, the first question would be: Is it legal to take hold of the NT Kernel Source? If so, proceed to the second paragraph; if not, proceed to the third.

The first thing you'd probably ask is "Why NT Kernel Source?" The answer is simply, I want to make my own OS compatible with Windows. This is of course, all a hobby, and I'm not planning any large project.

Ignore this if it's possible to get an NT Kernel Source: "ReactOS" I'm pretty sure that it uses Window's source code itself, with a few minor exceptions, so I'd like to know how they got the code.

答:
If you're a student, you may be able to access the Windows Research Kernel (source code to the core of the kernel, few if any drivers) through your school - http://www.microsoft.com/education/facultyconnection/articles/articledetails.aspx?cid=2416&c1=en-us&c2=0

If you have a ton of money, you might still be able to purchase a license to the whole thing from Microsoft. Citrix did this back in the early 90s to make WinFrame (later licensed back to Microsoft for Terminal Services).

ContentLicense: CC BY-SA 3.0

Title: NT Kernel Source


问:
An algorithm for a synchronization
I want to make a synchronization. What's the algorithm for it in a nutshell?

1) A client reads a local data and sends them to a server afterwards. The server compares them with its actual data, decides what are newer and overwrites its data with received data in case received data is newer.

or

2) A client reads data from the server first, compares them with its local data and in case data from the server is newer, overrwrites them with the server data.

And does the order matter?

答:
In a nutshell, it's a difficult problem.  Source Control doesn't solve it very well - they still require manual intervention when it doesn't know what to do.  Often using a library that implements it for you is the way to go.  Figure out what you need to provide in order for third party libraries to identify conflicts, and then determine how they may be resolved.  Some software reject conflicts outright - look at bugzilla. If an issue is edited between you receiving the bug in your browser and submitting a comment, it will flat out reject your update.

Whether or not the client or the server determines a conflict does not matter.  It will occur at some point, and you need to 1) detect it, and 2) know what you're going to do in all cases of conflict.

I should add that I cooked my own sync scheme for data, and regretted not using third party libraries.

Title: An algorithm for a synchronization


问:
CSS structure for creating responsive websites
I'm a back-end engineer who works on a small team so occasionally needs to do some front-end. I like to develop a good workflow and project structure before I start anything, so I'm wondering about creating a responsive front-end for a web app.

What's a best-practice way to strcture CSS for creating responsive websites that need to "scale down" for smaller screens? Specifically: do you create the mobile version first, then expand the code with min-width media queries in the CSS? Or do you do the opposite, creating the desktop-resolution version first?

Secondly, do you define multiple element selectors and definitions in the same media query? Or do you define a media query for each element and selector? It would seem that the second method would make for more readable code perhaps -- although it's certainly more frustrating to "tweak" a working site to create a new version with media queries rather than simple fence-off the old settings in one media query and re-style the necessary parts from the new version from scratch.

答:
I have found that creating a mobile site first is easier than making a desktop site respond to a mobile viewport.

As far as media queries, I use media queries for the typical screen sizes. Also, if there is a size that needs to have the layout tweaked, I will add another media query. So I will put multiple selectors in the same media query.

But in the end, its up to you to use the style you prefer and start with the screen size you like. Neither are wrong.


问:
Flexible / Dynamic object creation or Alternative to list of lists
I have a xlsx file, that has some tabs with different data. I want to be able to save each row of a tab in a list. The first thing that comes to mind is a list of lists, but I was wondering if there is another way. I'd like to save that information in a object, with all its benefits, but can't think of a way to generate/create such diverse objects on the fly. The data in the xlsx is diverse and ideally the program is agnostic of any content.

So instead of e.g. create a list for each row, than put that list in another list for each tab and each tab in another list, I'd like to store the information that each row represents in a single object and just have a list of different objects.

The question can be summarized as : What is an alternative to list of lists ?

A small graphic to visualize the problem :

```<code>+--------------------------------------------------------------------+
|LIST                                                                |
|                                                                    |
|    +------------------+ +------------------+ +-----------------+   |
|    | Class1           | | Class2           | | Class3          |   |
|    |------------------| |------------------| |-----------------|   |
|    | var1             | | var1             | | var5            |   |
|    | var2             | | var2             | | var6            |   |
|... | var3             | |                  | | var7            |...|
|    |                  | |                  | |                 |   |
|    |                  | |                  | |                 |   |
|    |                  | |                  | |                 |   |
|    |                  | |                  | |                 |   |
|    +------------------+ +------------------+ +-----------------+   |
|                                                                    |
+--------------------------------------------------------------------+
</code>```

答:
I assume that your worksheets contain tabular data, i.e., the first row contains field names and the following rows contain values. In such a case it would make sense to define a Table class whose instances would each contain the contents of one worksheet. This Table object could hold general information regarding one worksheet, if necessary, like the name of the worksheet tab.

It could also have a list holding the column names or a dictionary holding the column indexes with the column names as a key. If you define a Column class for this purpose (instead of just a string for the column name), it allows you to store additional information regarding a column, like its type (numeric, text, date) and display format.

Even if you don't need this kind of infrastructure right now, having such classes allows you to add this kind of functionality much easier later.

The Table class would also contain a list of rows. Here again, having a Row class can have advantages. However, it would be ok to represent one row as an array of strings, for instance. Since each row of the table has the same length, a list is not necessary here.

Instead of using strings to store the values, having a Value class or struct can also have advantages. Such a type could automatically convert strings to an appropriate type, could perform comparisons between values of the same type etc.

Without knowing more about your data and the kind of logic you want to apply to it, it is difficult to give you an answer tailored to fit your needs.


问:
How do I prepare for an 'aptitude for programming' test?
I have a job interview tomorrow and it's for a junior web developer role. I am really excited about it because I really want to get my foot in the door in this industry.

I have been told how the interview will pan out. It will consist of a 45 minute interview with two of their developers and an 'aptitude for programming' test.

I am really worried about the 'aptitude for programming' test.

Questions I am hoping the stack community can help me out with is:

What exactly is this? (as far as I understand it is a written test using a fictional programming language).

If you have done this before, either as the interviewer or interviewee, can you give me any advice, hints or help?

Are there any online sources that may help with this, i.e. blogs, websites, places I can practice a few online?

答:
These aptitude for programming tests evaluate the skills and abilities required in programming.

These tests usually include,

Logical reasoning

Numerical problem solving

Ability to follow complex procedures

Programming structures in pseudocode (for experienced person)

Besides above we also need to evaluate,

Ability to learn new skills

Time management

Teamwork


问:
Add behavior without changing existing class
I have a class Container, which represents wrapper around std::list.
This class contains following public methods:

void add(Shape *item)

void next()

void setBegin()

Shape* curr()

and protected variables

std::list <Shape*> _container

std::list <Shape*>::iterator _iter

Now I need add sorting of Container without changing existing class code.

Which pattern should I use? I think, that Decorator is most appropriate pattern in this case.
Should I redesign class Container?

答:
Container as it stands is both a list and an iterator, so I would actually suggest breaking it into two classes - one for each of the responsibilities. You can then make an alternative implementation of the list container that is sortable.

e.g.

```<code>class UnorderedContainer : Container
{
}

class SortableContainer : Container
{
    void Sort();
}

abstract class Container
{
    void Add(Shape *item);
    Iterator GetIterator();
}

class Iterator
{
    Shape* Current();
    void Next();
}
</code>```

I'd also carefully consider whether the list is mutable while you are using next() to iterate through it. It's not at all obvious what would happens when you call next() after a sort() - can it revisit items that you have already stepped through? If you break out the iterator into its own class you could have it act on an immutable copy of the list taken at the point where you began the iteration.

Body:
Container as it stands is both a list and an iterator, so I would actually suggest breaking it into two classes - one for each of the responsibilities. You can then make an alternative implementation of the list container that is sortable.

e.g.

class UnorderedContainer : Container
{
}

class SortableContainer : Container
{
    void Sort();
}

abstract class Container
{
    void Add(Shape *item);
    Iterator GetIterator();
}

class Iterator
{
    Shape* Current();
    void Next();
}

I'd also carefully consider whether the list is mutable while you are using next() to iterate through it. It's not at all obvious what would happens when you call next() after a sort() - can it revisit items that you have already stepped through? If you break out the iterator into its own class you could have it act on an immutable copy of the list taken at the point where you began the iteration.


问:
how do you style content when querying a data structure nested n-levels deep?
This question has come up while writing a simple text adventure game where your character has an inventory, which can include containers that also have things in them. I want a clean way to style the inventory output, like so:

```<code>You are carrying:
    a bag containing:
        a ring
    a backpack containing:
        a loaf of bread
</code>```

Currently I just include the formatting in the result returned by the query, all in one shot. For example,

```<code>DoInventoryCommand():
    result = QueryInventory(...recursively checks inventory adding multiples of tabs depending on nesting level...)
    print(result)
</code>```

What I would like is a cleaner separation between content and presentation so that the query would just return a data structure that a separate pass could style.

But how should the styling pass handle the n-levels deep data structure? Just for example, how would a styling tool like CSS handle it? Do you need to procedurally generate the CSS once you have the data structure?

答:
Your data structure should be recursive, like this:

```<code>public class Node
{
    public string Value { get; set; }
    public List<Node> Children { get; set; }

    public override string GetString()
    {
        return this.Value;
    }
}
</code>```

Add four spaces to the beginning of the display line for each new recursion level.  You can maintain a "level" variable that you pass along during the recursion (or make it static), increment it during each recursive call, and decrement it during each recursive return.

```<code>int indent = 0;
public string GetDisplayString()
{
    var s = new StringBuilder(new string(' ', indent) + node.ToString());
    if (node.Children != null)
        foreach (var child in node.Children)
        {
            indent += 4;
            s.Append(GetString(child));
            indent -= 4;
        }
    return s.ToString();
}
</code>```

Body:
Your data structure should be recursive, like this:

public class Node
{
    public string Value { get; set; }
    public List<Node> Children { get; set; }

    public override string GetString()
    {
        return this.Value;
    }
}

Add four spaces to the beginning of the display line for each new recursion level.  You can maintain a "level" variable that you pass along during the recursion (or make it static), increment it during each recursive call, and decrement it during each recursive return.

int indent = 0;
public string GetDisplayString()
{
    var s = new StringBuilder(new string(' ', indent) + node.ToString());
    if (node.Children != null)
        foreach (var child in node.Children)
        {
            indent += 4;
            s.Append(GetString(child));
            indent -= 4;
        }
    return s.ToString();
}


答:
You can create a sub class of Container class eg SortedContainer and add sorted functionality in the derived class. It will satisfies both principles, mentioned below.

Open Close Principle

Liskov Substituion Principle

Title: Add behavior without changing existing class

Body:
I have a class Container, which represents wrapper around std::list.
This class contains following public methods:

void add(Shape *item)

void next()

void setBegin()

Shape* curr()

and protected variables

std::list <Shape*> _container

std::list <Shape*>::iterator _iter

Now I need add sorting of Container without changing existing class code.

Which pattern should I use? I think, that Decorator is most appropriate pattern in this case.
Should I redesign class Container?


问:
Why do many languages not support named parameters?
I was just thinking how much easier it would be to read code if, when calling a function, you could write:

```<code>doFunction(param1=something, param2=somethingElse);
</code>```

I can't think of any drawbacks and it would make code a lot more readable. I know you could pass an array as the only argument and have the array keys as the parameter names, however that would still not be as readable.

Is there a disadvantage of this that I'm missing? If not, why do many languages not allow this?

答:
Named parameters are a solution to a problem in refactoring source code and not intended to  make source code more readable. Named parameters are used to assist the compiler/parser in resolving default values for function calls. If you want to make code more readable, than add meaningful comments.

Languages that are difficult to refactor often support named parameters, because foo(1) is going to break when the signature of foo() changes, but foo(name:1) is less likely to break requiring less effort from the programmer to make changes to foo.

What do you do when you have to introduce a new parameter to the following function, and there are hundreds or thousands of lines of code calling that function?

```<code>foo(int weight, int height, int age = 0);
</code>```

Most programmers will do the following.

```<code>foo(int weight, int height, int age = 0, string gender = null);
</code>```

Now, no refactoring is required and the function can execute in legacy mode when gender is null.

To specific gender a value is now HARDCODED into the call for age. As this example:

```<code> foo(10,10,0,"female");
</code>```

The programmer looked at the function definition, saw that age has a default value of 0 and used that value.

Now the default value for age in the function definition is completely useless.

Named parameters allow you to avoid this problem.

```<code>foo(weight: 10, height: 10, gender: "female");
</code>```

New parameters can be added to foo and you don't have to worry about the order they were added in and you can change default values knowing that the default you set is really it's true default value.

Body:
Named parameters are a solution to a problem in refactoring source code and not intended to  make source code more readable. Named parameters are used to assist the compiler/parser in resolving default values for function calls. If you want to make code more readable, than add meaningful comments.

Languages that are difficult to refactor often support named parameters, because foo(1) is going to break when the signature of foo() changes, but foo(name:1) is less likely to break requiring less effort from the programmer to make changes to foo.

What do you do when you have to introduce a new parameter to the following function, and there are hundreds or thousands of lines of code calling that function?

foo(int weight, int height, int age = 0);

Most programmers will do the following.

foo(int weight, int height, int age = 0, string gender = null);

Now, no refactoring is required and the function can execute in legacy mode when gender is null.

To specific gender a value is now HARDCODED into the call for age. As this example:

 foo(10,10,0,"female");

The programmer looked at the function definition, saw that age has a default value of 0 and used that value.

Now the default value for age in the function definition is completely useless.

Named parameters allow you to avoid this problem.

foo(weight: 10, height: 10, gender: "female");

New parameters can be added to foo and you don't have to worry about the order they were added in and you can change default values knowing that the default you set is really it's true default value.


答:
If you are creating the structure for future web app development then go with mobile first approach. For the second question, I work it out as (just a snippet from my work):

```<code>@media all and (max-width: 420px) {
    section, aside, .col1, .col2, .col3 {
        float: none;
        width: auto;
    }
}
@media all and (max-width: 978px) {
    header, footer {
        display: none;
    }
}
</code>```

You can further style it as per the requirement.

If the styles are common across multiple elements then I combine them as that reduces bytes for processing and then follow that with CSS specificity rules to generate element specific style.

Title: CSS structure for creating responsive websites

Body:
I'm a back-end engineer who works on a small team so occasionally needs to do some front-end. I like to develop a good workflow and project structure before I start anything, so I'm wondering about creating a responsive front-end for a web app.

What's a best-practice way to strcture CSS for creating responsive websites that need to "scale down" for smaller screens? Specifically: do you create the mobile version first, then expand the code with min-width media queries in the CSS? Or do you do the opposite, creating the desktop-resolution version first?

Secondly, do you define multiple element selectors and definitions in the same media query? Or do you define a media query for each element and selector? It would seem that the second method would make for more readable code perhaps -- although it's certainly more frustrating to "tweak" a working site to create a new version with media queries rather than simple fence-off the old settings in one media query and re-style the necessary parts from the new version from scratch.

Body:
If you are creating the structure for future web app development then go with mobile first approach. For the second question, I work it out as (just a snippet from my work):

@media all and (max-width: 420px) {
    section, aside, .col1, .col2, .col3 {
        float: none;
        width: auto;
    }
}
@media all and (max-width: 978px) {
    header, footer {
        display: none;
    }
}

You can further style it as per the requirement.

If the styles are common across multiple elements then I combine them as that reduces bytes for processing and then follow that with CSS specificity rules to generate element specific style.


问:
Should a class know about its subclasses?
Should a class know about its subclasses? Should a class do something that is specific for a given subclass for instance?

My instincts tells me that is a bad design, it seems like an anti-pattern of some sort.

答:
The simple answer is No.

It makes code brittle and voilates two basic principles of object oriented programming.

Liskov Substitution principle

Open Close principle


问:
How is machine learning incorporated into search engine design?
I am currently building a small in-house search engine based on Apache Lucene. Its purpose is simple - based on some keywords, it will suggest some articles written internally within our company. I am using a fairly standard TF-IDF scoring as a base metric and built my own scoring mechanism on top it. All of these seem to be working excellent except for some corner cases where the ranking seems messed up.

So what I am planning on doing is to add a small Relevant/Not Relevant link to the search results page so that users can click on one of those depending on their perception of whether that result should have been included in the first place.

My Idea

Treat these Relevant/Not Relevant as labels and create a training data.

Use this data to train a classifier (such as SVM)

Incorporate this model into the search engine i.e., every new result will pass through the classifier and will be assigned a label on whether it is relevant or not.

This approach seems intuitive to me but am not sure whether it will work in practice. I have two specific questions:

What all features should I extract?

Is there a better way to integrate the machine learning component into the search engine? My final goal is to "learn" the ranking function based on both business logic as well as user feedback.

答:
(1) What all features should I extract?

First, realize that you're not classifying documents. You're classifying (document, query) pairs, so you should extract features that express how well they match.

The standard approach in learning to rank is to run the query against various search engine setups (e.g. tf-idf, BM-25, etc.) and then train a model on the similarity scores, but for a small, domain-specific SE, you could have features such as

For each term, a boolean that indicates whether the term occurs in both the query and the document. Or maybe not a boolean, but the tf-idf weights of those query terms that actually occur in the document.

Various overlap metrics such as Jaccard or Tanimoto.

(2) Is there a better way to integrate the machine learning component into the search engine? My final goal is to "learn" the ranking function based on both business logic as well as user feedback.

This is a very broad question, and the answer depends on how much effort you want to put in. The first improvement that comes to mind is that you should use not the binary relevance judgements from the classifier, but its real-valued decision function, so that you can actually do ranking instead of just filtering. For an SVM, the decision function is the signed distance to the hyperplane. Good machine learning packages have an interface for getting the value of that.

Beyond that, look into pairwise and listwise learning to rank; what you're suggesting is the so-called pointwise approach. IIRC, pairwise works a lot better in practice. The reason is that with pairwise ranking, you need much fewer clicks: instead of having users label documents as relevant/irrelevant, you only give them the "relevant" button. Then you learn a binary classifier on triples (document1, document2, query) that tells whether document1 is more relevant to the query than document2, or vice versa. When a user labels, say, document 4 in the ranking as relevant, that gives you six samples to learn from:

document4 > document3

document4 > document2

document4 > document1

document1 < document4

document2 < document4

document3 < document4

so you get the negatives for free.

(These are all just suggestions, I haven't tried any of this. I just happen to have worked in a research group where people investigated learning to rank. I did do a presentation of someone else's paper for a reading group once, maybe the slides can be of help.)

OwnerDisplayName: Legend


问:
Is it Typical for Large Software Companies to Not Document or Refactor Code?
I have begun working at a large software company and was assigned to a project that is over a million and a half lines of code. It's part of a program suite that is sold to clients (not an in-house project) and the source code can be purchased if they desire (although given the extra fees associated with it, this seems rare). They've been doing software design for years and their current products are intended to be continued for the foreseeable future.

To my surprise, the million and a half lines of code are almost completely lacking in documentation. Moreover, there are some areas of code that are incredibly messy to follow or could use some refactoring to become much easier to understand (for instance, an improvement in the programming language came out 10 or so years ago that would make large portions of code much cleaner, not to mention less prone to bugs). There doesn't seem to be any efforts to rectify this and my offers to do so for the parts I'm working with have met with resistance, for which I've never really gotten a clear answer.

Are these practices common in a large business in the software industry? Or is my company unique in its lack of refactoring and documentation?

Addendum: Based on some of the comments, I'd like to clarify what I'm looking for. I understand that my company has technical debt and this is bad. I'm not looking to determine whether or not my company is worse off because of this, I am just wanting to know whether or not this lack of documentation and resistance to refactoring is a fact of life within the programming world that I'll have to deal with if I continue working in it.

答:
There are a number of reasons why companies fail to invest in making their programs "better," from a technical debt perspective:

Reducing technical debt doesn't add any new features to the software.  It is therefore perceived by management as having no monetary value (to a certain extent justifiably)

The nature of the software business awards first-to-market, not best.

I could go on, but all the other reasons are just variants of these two.  They all basically add up to short-term thinking, focusing on immediate profits instead of long-term viability.

All companies with non-trivial, active software projects have some degree of technical debt.  No company is completely debt-free.

Every software project I've ever worked on has accrued Technical Debt over time -- Jeff Atwood.

Regarding documentation specifically, the less there is, the better.  Dollar for dollar, you get more return by making the software simpler to use and easier to maintain than you do writing more documentation for it.

There are some informal surveys about technical debt, and how companies manage it; all you have to do is look for them.  Here's one:

Or this one:

It seems fairly apparent that your company is not the only one that has this problem.  It may not even be in the minority.

Further Reading

Third International Workshop on Managing Technical Debt - Overview

Managing Technical Debt in Software-Reliant Systems


答:
Yes. Based on the 50 or so companies I have personally encountered, as an employee or consultant, and the 200 or so more companies I know of via colleagues.

The kind of product (1.5 million lines) you describe took years to build, and many of the original devs have moved on (or become managers).

The senior management and major continuing clients want only small incremental change: they want stability. What we technical people think are improvements are in their eyes risks. Even if we can show the new version still behaves the same as the old one, they see a risk because the old system has exactly the characteristic you describe: it's undocumented. To them, there could be undocumented behavior that clients rely upon.

From their perspective: it ain't broke, so don't fix it. You are also seeing that there is a corporate culture to that effect. The people who are resisting your "improvements" probably did the same as you when they started.

Do not expect to "win". This is a cultural issue, and cannot be changed except by change at the CEO level.

Title: Is it Typical for Large Software Companies to Not Document or Refactor Code?

Body:
I have begun working at a large software company and was assigned to a project that is over a million and a half lines of code. It's part of a program suite that is sold to clients (not an in-house project) and the source code can be purchased if they desire (although given the extra fees associated with it, this seems rare). They've been doing software design for years and their current products are intended to be continued for the foreseeable future.

To my surprise, the million and a half lines of code are almost completely lacking in documentation. Moreover, there are some areas of code that are incredibly messy to follow or could use some refactoring to become much easier to understand (for instance, an improvement in the programming language came out 10 or so years ago that would make large portions of code much cleaner, not to mention less prone to bugs). There doesn't seem to be any efforts to rectify this and my offers to do so for the parts I'm working with have met with resistance, for which I've never really gotten a clear answer.

Are these practices common in a large business in the software industry? Or is my company unique in its lack of refactoring and documentation?

Addendum: Based on some of the comments, I'd like to clarify what I'm looking for. I understand that my company has technical debt and this is bad. I'm not looking to determine whether or not my company is worse off because of this, I am just wanting to know whether or not this lack of documentation and resistance to refactoring is a fact of life within the programming world that I'll have to deal with if I continue working in it.


问:
Boolean properties in Class A control availability of members in Class B: Design Pattern?
Given the following code:

```<code>class AnimalDescriptor {
    String species;
    boolean hasLegs;
    boolean hasTeeth;
    boolean hasHair;

    public AnimalDescriptor(String species, boolean hasLegs,
                            boolean hasTeeth, boolean hasHair) {
        this.species = species;
        this.hasLegs = hasLegs;
        this.hasTeeth = hasTeeth;
        this.hasHair = hasHair;
}

class Animal {
    AnimalDescriptor control;
    String name;
    int numberOfLegs;
    int numberOfTeeth;
    String colorOfHair;
}

class doStuff {
    public void go() {
        AnimalDescriptor dog = new AnimalDescriptor("dog", true, true, true);
        AnimalDescriptor pirahna = new AnimalDescriptor("pirahna", false, true, false);

        Animal fido = new Animal();
        fido.control = dog;
        fido.name = "Fido";
        fido.numberOfLegs = 4;
        fido.numberOfTeeth = 42;
        fido.colorOfHair = "black"; //All good here

        Animal bob = new Animal();
        bob.control = pirahna;
        bob.name = "Bob";
        bob.numberOfTeeth = 42; //So far so good
        bob.numberOfLegs = 2; //This should pass compilation, but fail
                              //validation at run-time, since it is
                              //nonsensical
}
</code>```

Is there a pattern name for what I'm doing here? I've tried searching variations on my question title but haven't gotten anywhere.

Obviously, this is an extremely simple and abbreviated example, AnimalDescriptor should have a bool .validate(Animal a) method, as well, and Animal should have an .isPropertyAvailable(String propertyName) method, among other additions. I didn't want to bog everything down with a 500-line minimal-case example.

There's no way that I'm the first or only person to do this, and I'm mainly looking for something I can latch on to for further research into best practices, implementation pitfalls, etc.

EDIT: To provide a little more clarity, in my system, there are ~20 booleans in the "control" class (AnimalDescriptor). I'm tracking ~106 items (Animals) in ~103 categories (AnimalDescriptors) that share a pool of common properties, but each item only has the properties that are designated by its "control" configuration. Plus, the system should be able to expand to, say, 104 categories (AnimalDescriptors) over the next 5 years. We have a functional (if ugly) implementation, so I don't need validation or exception how-tos -- I'm more interested in how this problem has been approached in other domains/applications, benefits of implementation in a functional (as opposed to object-oriented) context, best practices, etc. It seems like there should be a name for this, but I don't know what it is.

答:
You seem to be describing the prototype pattern, where some of the properties of your items are determined based on some other object accessible in the system.  In fact, the particular use you're describing, wherein some runtime validation code will access the properties of a particular object's prototype, is very close to how JavaScript manages its prototype based inheritance model.

If you want to different this pattern to express the variable requirements of your items from the more general prototype pattern, you might want to refer to this model as a prototype driven schema.

You could also probably just call it a schema, since the fact that you're only testing for if a particular property is allowable or not is a mere implementation detail rather than a useful feature of the pattern.  (If you really wanted to prevent a pirana from having legs, you'd do what @aaron-kurtzhals suggested and just make a Pirana class.)


问:
When to favor ASP.NET WebForms over MVC
I know that Microsoft has said

ASP.NET MVC is not a replacement for WebForms.

And some developers say WebForms is faster to develop on than MVC.  But I believe speed of coding comes down to comfort level with the technology so I don't want any answers in that vein.

Given that ASP.NET MVC gives a developer more control over their application, why isn't WebForms considered obsolete?  Alternatively, when should I favor WebForms over MVC for new development?

答:
The only reason why I would choose the WebForms instead of MVC is because you have much more 3rd party UI controls for WebForms than MVC. I choose MVC because I worked too much with WebForms and I want to work with something fresh / new, but still from MS shop :)

Basically, nothing prevents you to turn off the viewstate in WebForms and use ViewModels and if/for loops instead of model binding and server side controls.

Is this WebForms or MVC code:

```<code><% foreach (var item in Model.Items) { %>
<p><%: item.Name %></p>
<% } %>
</code>```

The only limitation I found in WebForms is that if you use Dependency Injection / Inversion of Control, you can't have constructor injection since WebForms pages must have parameterless constructor, so you have to use property injection. Is this really such a big deal?

Title: When to favor ASP.NET WebForms over MVC

Body:
The only reason why I would choose the WebForms instead of MVC is because you have much more 3rd party UI controls for WebForms than MVC. I choose MVC because I worked too much with WebForms and I want to work with something fresh / new, but still from MS shop :)

Basically, nothing prevents you to turn off the viewstate in WebForms and use ViewModels and if/for loops instead of model binding and server side controls.

Is this WebForms or MVC code:

<% foreach (var item in Model.Items) { %>
<p><%: item.Name %></p>
<% } %>

The only limitation I found in WebForms is that if you use Dependency Injection / Inversion of Control, you can't have constructor injection since WebForms pages must have parameterless constructor, so you have to use property injection. Is this really such a big deal?


答:
Is it legal to take hold of the NT Kernel Source?

That depends what you mean by "take hold of". You can buy it from Microsoft. If you are an academic, you can get an academic license from Microsoft. If you are a government agency, you can get a government license.

In all cases, you need to abide by the terms of the license, of course.

The developers of the Xen Hypervisor, for example, back when it was still a research project, created a modified version of Windows XP that ran on Xen. They were never allowed to distribute this, of course, nor where they allowed to publish any benchmark results, but they were allowed to make under the rules of Microsoft's academic license for NT.

ReactOS is a fully independent implementation of the Windows APIs, it does not share a single line of code with NT.

Title: NT Kernel Source

Body:
Well, the first question would be: Is it legal to take hold of the NT Kernel Source? If so, proceed to the second paragraph; if not, proceed to the third.

The first thing you'd probably ask is "Why NT Kernel Source?" The answer is simply, I want to make my own OS compatible with Windows. This is of course, all a hobby, and I'm not planning any large project.

Ignore this if it's possible to get an NT Kernel Source: "ReactOS" I'm pretty sure that it uses Window's source code itself, with a few minor exceptions, so I'd like to know how they got the code.


答:
A perspective which I don't believe has been covered in other answers (yet) is the cost of change in three areas:

testing

re-familiarization

opportunity cost

A company with a large product will need to test all changes. These test procedures need to be tracked over multiple axes: different platforms, different workloads, different perspectives (performance, functional, usability, backward compatibility).

The people who work in the areas of code that you are changing will also need to then re-familiarize themselves with the code, and it becomes especially cumbersome with multiple versions being supported ("sorry, what version is that? Ahh, that's the new code and you need to speak to Bob for that"). In a similar vein, changing code just to make it pretty tends to make things like change-logs (diffs, patches, etc.) very complicated to read... and tracking issues back to a particular point in time when the bug was introduced can be very challenging if there's something in the code history that changes everything. Additionally, if a bug is long-standing (these things happen) it may be in multiple supported versions of your code, and now you have to fix the old, and the new code, in potentially very different ways.

Finally, often the decision has to be made where to spend time and money. This is more than just your time, but rather what you should rather be doing with your time (and the impact it has on down-stream resources). Would it be preferable to spend your dev-team's time on features that can produce more sales, gain new market share, and generate profit, or should the time/money be spent on things that end-users will not notice, cannot be put on marketing material ("hey, our existing code sucks, but we have made it better") and is pure cost (no profit).

Bottom line, money. Always (well, almost always).


问:
Is it possible to be good at both programming and graphic design?
The stereotypical view of a programmer can't do graphics very well, from what I've read and seen. However, I love programming (preferably OOP, PHP, C++, Objective-C) and can't deny the fact I have a unique taste in web design and others have said I am doing well at it (CSS). I thought to myself "Hey, wait, I'm a programmer - how can I design well?". Question is: is it possible to be good at programming and designing? Does anyone here feel the same?

For the record: actual images I have created have been called programmer art several times before by friends

答:
Yes, it is possible.

Are programming and graphic extremes to each other?

I am both an artist and programmer, I spent 5 years self-studying programming, 1 year at manga, 4 years at Web design and less than 1 year at optical illusions.

Some people are talented at art, but decided to learn programming all the time and let talent guide his designs.

The problem for learning both is not only time, but your brain may be re-wired to be optimized at art but not programming, please be aware of.

There is "programmer art", but why there is no "artist's program"? That is the stereotype.

See also: https://gamedev.stackexchange.com/search?q=programmer+art

ContentLicense: CC BY-SA 2.5


问:
Algorithm to calculate estimated future usage of a defined value
I am looking for the name of a computer algorithm. I'm fairly sure that one should exist which will help me, but I can't for the life of me figure out what to search for.

If you have implementations of the algorithm, that'd be awesome - but I'm really just researching this because I'd like to figure out how to build it myself.

Basically, I'm looking for an algorithm that can calculate future usage of some set of data based on my previous usage. For example, my electricity supplier knows how much power I've used for the previous 20 days of a 30 day month, so they can extrapolate that out and predict how quickly I will run out of money on my power account. I'd like to know if there's an algorithm out there that can tell me in how long I'm likely to run out.

What I'm looking for is something that given the following inputs:

A range (e.g. 30 days)

A period of time through that range (e.g. 4, never smaller than zero, never greater than the max of the range)

Some values for previous time periods - either the previous days, or the same days from previous months)

A total value for this range (e.g. 300)

Can give me a date range in which I'm likely to run out of the total value (300). What I'd like at the other end would be something simple - e.g. "Based on previous usage, you're going to run out in 2 days."

I've done the usual Google searches, but haven't come up with anything particular that even looks close - yet as far as I can see it's a reasonably common algorithm used all over the place.

答:
Linear regression is one answer, but it might not be the correct answer.  The appropriate extrapolation method to use depends on the nature of the data itself.

For example, electricity demand is often cyclical, with daily, weekly, and yearly patterns superimposed on each other.  Linear extrapolation would fail to take such patterns into account; seasonal adjustment may be called for.

As an extreme example, financial markets are chaotic.  Many smart people have tried to write programs to predict the markets, sometimes successfully, sometimes not.

Anyway, only you can decide what method of extrapolation is appropriate.  It could be extrapolation based on linear regression, some other kind of regression, or not reasonable at all.


问:
adding array pointer in c
I am having problems understanding how this equation works in c:

```<code>char *sum(char *a, int b) {
    return &a[b];
}

printf("%d", sum(5, 4));
</code>```

I understand how arrays work, and I understand how to reference and de-reference a variable to a memory location, but I don't understand where the addition comes in to play here.

It makes sense to me that return &a[4] for example would just return a de-referenced non-existent memory location and cause an error.

Can someone explain this to me in easy terminology?

答:
You are nearly there. &a[4] returns a + 4 times sizeof(type of elements in a) (in this case char). This is then returned, in you case as 5+4 = 9.

The value is valid, but the deference to invalid memory only happens if you use it to access memory, so at this point nothing "bad" has happened.

```<code>char *a = sum(5,4)
printf ("%d",a);       is OK and prints 9
printf ("%d", *a);     all bets off.....
</code>```

another example to think about : char *x = NULL;
x is NULL, but you do not get a Null pointer exception thrown till you do something with it such as *x = y ;

I also suggest you compile this code with -Wall and study the warnings.

Title: adding array pointer in c

Body:
You are nearly there. &a[4] returns a + 4 times sizeof(type of elements in a) (in this case char). This is then returned, in you case as 5+4 = 9.

The value is valid, but the deference to invalid memory only happens if you use it to access memory, so at this point nothing "bad" has happened.

char *a = sum(5,4)
printf ("%d",a);       is OK and prints 9
printf ("%d", *a);     all bets off.....

another example to think about : char *x = NULL;
x is NULL, but you do not get a Null pointer exception thrown till you do something with it such as *x = y ;

I also suggest you compile this code with -Wall and study the warnings.


答:
It will return the address of b char units in memory from the pointer to a.

As it will return an address to memory, you can find whatever in that address, a NULL or any other character.

So if you have sum(5,4), the first parameter will be taken as an address (the starting point) and it will return 4 char units in memory from 5.

If the machine defines a char as 1 byte, then it will return 9.

If the machine defines a char as 2 bytes, then it will return 5 + 2 + 2 + 2 + 2 = 13.

And so on.

Title: adding array pointer in c

Body:
I am having problems understanding how this equation works in c:

```<code>char *sum(char *a, int b) {
    return &a[b];
}

printf("%d", sum(5, 4));
</code>```

I understand how arrays work, and I understand how to reference and de-reference a variable to a memory location, but I don't understand where the addition comes in to play here.

It makes sense to me that return &a[4] for example would just return a de-referenced non-existent memory location and cause an error.

Can someone explain this to me in easy terminology?


问:
High Level Configuration of Constructor Injection in C++
My questions are specifically dealing with dependency injection through the constructor. I understand the pros/cons of service locator pattern, constructor/setter injection, and their flavors, however there is something I can't seem to get past after choosing pure constructor injection. After reading many materials for testable design, including a thorough perusing of Miško Hevery's blog (specifically this post) I'm at the following situation:

Assume I'm writing a C++ program, and I have correctly injected my dependencies through their constructors. For readability I have given myself a high-level object which has a single Execute() function called from main:

```<code>int main(int argc, char* argv[]) {
    MyAwesomeProgramObject object(argc, argv);
    return object.Execute();
}
</code>```

Execute()'s responsibility is to simply wire up all required objects and kick off the highest level object. The highest level object requires a couple dependencies and those objects required a few objects and so on and so on, implying a function that looks like this:

```<code>MyAwesomeProgramObject::Execute() {
    DependencyOne one;
    DependencyTwo two;
    DependencyThree three;

    MidLevelOne mid_one(one);
    MidLevelTwo mid_two(two, three);

    // ...

    MidLevelN mid_n(mid_dependencyI, mid_dependencyJ, mid_dependencyK);

    // ...

    HighLevelObject1 high_one(mid_one, mid_n);
    HighLevelObject2 high_two(mid_two);

    ProgramObject object(high_one, high_two);
    return object.Go();
}
</code>```

From what I take from Miško's blog (and I would ask him, but figured he wouldn't have time to get back to me), this is the only way to satisfy pure constructor injection of dependencies.

In the blog post mentioned, he states we should have factories on a per object lifetime level, but this is essentially what Execute is doing, making my code look identical to his example:

```<code>AuditRecord audit = new AuditRecord();
Database database = new Database(audit);
Captcha captcha = new Captcha();
Authenticator authenticator =
    new Authenticator(database, captcha, audit);
LoginPage = new LoginPage(audit, authenticator);
</code>```

Questions:

Is this the standard approach?

Is this a pattern that I'm not aware of (seems similar to Maven's context.xml)?

For pure constructor injection, do I simply suffer the cost of "upfront" allocation?

答:
Is this the standard approach?

There is no such thing as a "standard approach", in particular in C++.
Really, this kind of choice is specific to the design you need to solve your problems.

Basically, what you need to ask is "when do I need to initialize this dependency?" and you need to ask that for each dependency. If you can intialize everything on construction, then nice, you might avoid unnecessary new/delete calls, which makes your program easier to deal with.
If you really need to have some dependencies initialized only on the execution call, then you don't have a choice, do it at this moment.

However, I would suggest avoiding new/delete as much as possible if you can, for example by putting your late-initialization dependencies into another object which would represent their lifetime, maybe called "ExecutionDependencies" or something, managed by a smart pointed (std::unique_ptr is certainly the best choice).
It's equivalent to having several new/delete calls but you do only once for the whole object holding all execution dependencies.
It's then easy later to release dependencies only needed for execution and keep dependencies needed for the whold program lifetime.

That being said, it might not be very important so frankly I would just write the most simpler way first, then refactor later if it's bothering me. Except if initialization and termination are actually an important problem in your program.

I would avoid factories in general, until you have a very specific need for it, which is not necessary here.

Is this a pattern that I'm not aware of (seems similar to Maven's
  context.xml)?

A pattern is not a way to implement a solution, it's just an example of design. Don't assume it's a different pattern than Dependency Injection, really it's another way of doing the same.

For pure constructor injection, do I simply suffer the cost of
  "upfront" allocation?

I'm not sure what you mean by that: allocating everything first is a good way to avoid memory fragmentation. However, it imply that you avoid as many new/delete calls as you can, grouping things together if you want to optimize space and execution time, so my suggestion of grouping dependencies (when they are needed only in the execution call) is spot on if it's your concern.


答:
In C, the array index operation a[b] is implicitly treated by the compiler as *(a + b).

This property means that you can write, for example:

```<code>assert(5["A string"] == 'i');
</code>```

And it is true.

Because C also performs implicit conversions from int to a pointer type, your example is evaluated like this:

```<code>sum(5,4) -> char *a = 5, b = 4
return &a[b]; -> return &(*(a + b)); -> return &(*((char*)5 + 4));
</code>```

Because there is no memory access, (the value of a[b] is not inspected or assigned) the & and * operators are canceled out, and the inner sum (5+4) is cast to char* returned as-is.

The particular location of a in memory is irrelevant, and the value in a is irrelevant because no memory access is performed.

Title: adding array pointer in c

Body:
In C, the array index operation a[b] is implicitly treated by the compiler as *(a + b).

This property means that you can write, for example:

assert(5["A string"] == 'i');

And it is true.

Because C also performs implicit conversions from int to a pointer type, your example is evaluated like this:

sum(5,4) -> char *a = 5, b = 4
return &a[b]; -> return &(*(a + b)); -> return &(*((char*)5 + 4));

Because there is no memory access, (the value of a[b] is not inspected or assigned) the & and * operators are canceled out, and the inner sum (5+4) is cast to char* returned as-is.

The particular location of a in memory is irrelevant, and the value in a is irrelevant because no memory access is performed.


问:
Clearing the lowest set bit of a number
I can see in this tutorial on bit manipulation, under the heading "Extracting every last bit", that -

Suppose we wish to find the lowest set bit of x (which is known to be
  non-zero). If we subtract 1 from x then this bit is cleared, but all
  the other one bits in x remain set.

I don't understand how this statement is true.

If we take x = 110, subtracting 1 would give 101.

Here, the lowest set bit is not cleared. Can anyone tell me how I'm approaching this problem in a wrong way?

答:
After subtracting 1, you need to & the two values.  e.g.

int bitremoved = x & (x-1);

In your example you end up with binary 100.

Title: Clearing the lowest set bit of a number


答: At work I work with WPF, I don't have a copy of Photoshop and I hate GIMP.. so what do I do when I need icons? I write them in XAML and use them in a VisualBrush. So not only can you do both and be good at both, you can do it at the same time!</p>

Title: Is it possible to be good at both programming and graphic design?

Body:
The stereotypical view of a programmer can't do graphics very well, from what I've read and seen. However, I love programming (preferably OOP, PHP, C++, Objective-C) and can't deny the fact I have a unique taste in web design and others have said I am doing well at it (CSS). I thought to myself "Hey, wait, I'm a programmer - how can I design well?". Question is: is it possible to be good at programming and designing? Does anyone here feel the same?

For the record: actual images I have created have been called programmer art several times before by friends


问:
In agile environment, how is bug tracking and iteration tracking consolidated.
This topic stemmed from my other question about management-imposed waterfall-like schedule. From the responses in the other thread, I gathered this much about what is generally advised:

Each story should be completed with no bugs.  Story is not closed until all bugs have been addressed.  No news there and I think we can all agree with this.

If at a later date QA (or worse yet a customer) finds a bug, the report goes into a bug tracking database and also becomes a story which should be prioritized just like all other work.

Does this sum up general handling of bugs in agile environment?

If yes, the part I'm curious about is how do teams handle tracking in two different systems? (unless most teams don't have different systems).

I've read a lot of advice (including Joel's blog) on software development in general and specifically on importance of a good bug tracking tool. At the same time when you read books on agile methodology, none of them seem to cover this topic because in "pure" agile, you finish iteration with no bugs. Feels like there's a hole there somewhere.

So how do real teams operate? To track iterations you'd use (whiteboard, Rally...), to track bugs you'd use something from another set of products (if you are lucky enough, you might even get stuck with HP Quality Center).  Should there be 2 separate systems? If they are separate, do teams spend time creating import/sync functionality between them? What have you done in your company? Is bug tracking software even used? Or do you just go straight to creating a story?

答:
Where I work we also have the principle, almost as an "article of faith", that defects are not raised during an iteration but simply that development is not complete until all issues are addressed. An issue can be anyting from a missing requirement to ambiguity in how the technology should be implemented to a good old fashioned bug in the code. Because, in true Agile fashion, our user stories are not specifications but rather "placeholders for a conversation" it is considered to be beneficial that requirements are finalised with Product Owners during development so that neither they or the developers are railroaded into a solution by upfront requirements specifications.

If and when an "issue" is identified, the encouraged practice is to track it by creating a new task on the project radiator board and in Rally. This serves to remind Product Owners to provide requirements, developers to implement it and QAs to incorporate it into their test plan. If an issue cannot be addressed in the time frame for development then it is upto to the Product Owner (not the QA) to accept the story with caveat that the issue will be become part of a new story or raised as a defect.

This is all great and works well on small projects with fairly small co-located teams who communicate face to face on a daily basis. However in my experience it becomes problematic on bigger projects where third parties and/or offshore teams are involved. This is because tasks on the board or in Rally do not have the benefits of formal defect reports, let us remind ourselves of those benefits;
1. A common frame of reference for the issue with a unique identifier (number).
2. Steps to recreate the issue with actual vs expected results so there can be no ambiguity as to what the issue actually is.
3. A searchable repository of known issues so that team members do not have constantly ask around if some purported bug they have found has already been reported.
4. Accountability; if we rely on word of mouth and/or email chains to report issues then things are bound to be missed, ignored, or forgotten especially when issues start mounting up.

As a QA I definitely believe there is room for some method of tracking issues during development. However whenever I try to raise this at work I am usually slapped down and told that "I do not understand Agile" or words to that effect. Interestingly it is usually programmers who raise such objections. This is understandable because programmers do not have the potential headache of reporting and tracking numerous issues. So I recommend that any discussion about this subject involves BAs and Project Managers as well as QAs because it is something we all have to work with on a daily basis. By contrast, a programmers' experience of a defect is usually just as an individual discrete piece of work that they have to fix within a given area of code.


问:
Handling one code base for multiple clients, with their own custom code
I am working on a CMS, in which we have multiple clients that use it, so the code is stored on their servers. Each client has the default code (user manager, pages manager etc), but every client also has it's own set of code (themes, scripts, custom modules).

I am trying to figure out a way to maintain an up-to-date code base for all the clients without having to make every single change to the core to every single client.

We are using GitHub for version control, so I was think of having all the clients as different branches, but how can I keep the core up to date with the master?

Am I think about this all wrong?

What are my options?

答:
Branches are the wrong solution here. Branches are for when the code (temporarily) needs to change from the common base.

The problem with branches is that changes made to one branch stay on that one branch until you explicitly merge them onto another branch. This effectively means that if you have a change in the common code, you need to apply that change to each 'client-branch' individually, which is exactly what you don't want.

I am not fully up to date with git terminology, but the better solution is to have several repositories/sub-modules. You then create one repository for each client and an extra repository for the common code. The client's repository can then include the common repository as an external reference or sub-module and any change made to the common code is then immediately available to all clients repositories without additional work.


问:
Difference between Singleton pattern and auto_ptr<> resp. unique_ptr<>
I'm maintaining some legacy code of a physical simulation. The calculation object is build as a singleton, to ensure there is only one instance. A co-worker told me, that singleton are completely out-of-date and I should instantiate it through a smartpointer. But I think it is not the same, because the initialization by a smartpointer doesn't garanties me, that there is only one instance of this object, right?

If I wanna have one single instance of an object in my code, which way is preferable:

To use the singleton pattern or the initialize the object through one of this smartpointers (auto_ptr<> or unique_ptr<>).

答:
If you want to enforce that there is only a single instance of some class, then you must use the Singleton pattern. (aside from the question if your analysis is correct that you will only ever need a single instance.)

The C++ smart pointers auto_ptr<> and unique_ptr<> enforce a completely different contract, namely that there is only one reference (or pointer) to a given instance.

For example, this code is perfectly legal, but there are clearly two instances of Resource:

```<code>class Resource {
// ...
};

std::unique_ptr<Resource> instance1(new Resource());
std::unique_ptr<Resource> instance2(new Resource());
</code>```

Body:
If you want to enforce that there is only a single instance of some class, then you must use the Singleton pattern. (aside from the question if your analysis is correct that you will only ever need a single instance.)

The C++ smart pointers auto_ptr<> and unique_ptr<> enforce a completely different contract, namely that there is only one reference (or pointer) to a given instance.

For example, this code is perfectly legal, but there are clearly two instances of Resource:

class Resource {
// ...
};

std::unique_ptr<Resource> instance1(new Resource());
std::unique_ptr<Resource> instance2(new Resource());


答:
In C++ 11 the "singleton pattern" is just nothing more than a static variable inside a fucntion body:

If you want to prevent an object to be instantiated just do

```<code>class Object
{
private:
   Object() = default;
   Object(const Object&) = delete;
public:
   static Object& instance() { static Object z; return z; }
};
</code>```

Title: Difference between Singleton pattern and auto_ptr<> resp. unique_ptr<>

Body:
I'm maintaining some legacy code of a physical simulation. The calculation object is build as a singleton, to ensure there is only one instance. A co-worker told me, that singleton are completely out-of-date and I should instantiate it through a smartpointer. But I think it is not the same, because the initialization by a smartpointer doesn't garanties me, that there is only one instance of this object, right?

If I wanna have one single instance of an object in my code, which way is preferable:

To use the singleton pattern or the initialize the object through one of this smartpointers (auto_ptr<> or unique_ptr<>).

Body:
In C++ 11 the "singleton pattern" is just nothing more than a static variable inside a fucntion body:

If you want to prevent an object to be instantiated just do

class Object
{
private:
   Object() = default;
   Object(const Object&) = delete;
public:
   static Object& instance() { static Object z; return z; }
};


答: There are lot of issues when you have different code files for each client with each own module, theme etc. All this code is actually a different code base, probably with similar or identical logic to another client code base. Apart from the initial development time, which is something that I personally fall in with a lot of times in the past, maintaining and refactoring such code will definitely be  a daunting task. To my mind, you should have a single codebase with all client customizations, if you don't want to changes to every single client code.</p>

Title: Handling one code base for multiple clients, with their own custom code

Body:
I am working on a CMS, in which we have multiple clients that use it, so the code is stored on their servers. Each client has the default code (user manager, pages manager etc), but every client also has it's own set of code (themes, scripts, custom modules).

I am trying to figure out a way to maintain an up-to-date code base for all the clients without having to make every single change to the core to every single client.

We are using GitHub for version control, so I was think of having all the clients as different branches, but how can I keep the core up to date with the master?

Am I think about this all wrong?

What are my options?


问:
Evaluate all pair combinations in an array for a condition in n log n time complexity
Task - Consider an array of n elements. Count the number of pairs that satisfy condition X (sum of the two elements < an arbitrary number, k) .

The basic approach I could think of would be O(n^2), where I evaluate all n*(n-1)/2 pairs. How can I solve the problem in a better time frame i.e., O(n log n) or less?

The best approach so far was to sort the array, find where a+b smaller than k then add indice of a to solution. But the process still has to go through n-1 'b's to check for each of them. It's better but still doesn't improve the worst case.

Also, this isn't homework. I came across this while preparing for a competition.

答:
In that general way you explain it: no, can't be done.

As soon as you need to evaluate all pair combinations you pretty much have a O(n2) runtime.

If there is some way to exclude some combinations (for example for a given item, you know that no combination will fulfill the condition), then you can get better runtime behaviour.

For example, if you know the smallest number in your array to be min, then skipping all element e where e + min > k can help you get a better effective runtime (but it won't reduce the worst case).

Another approach that's useful if you don't need the best solution, but "good enough" is enough, is to use a heuristic. For example, if you can "guess" that a given item is unlikely to be in the ideal combination, you can skip it. This again will improve performance but can lead to you missing the ideal combination.


答:
if you need ALL results on an arbitrary condition (say C(a,b) = (sha1(a~c)^sha1(c~a))%2 == 0 with ~ as concatenation) then there are n*(n-1)/2 values you need to output that are all independent; so no there is no better way,

but if the result of one pair tells you something about the result of another pair then that information can be used to speed things up. like in your example if sum > k then you sort and for each number you check each in order (forwards or backwards). On the first true result you add the numbers still remaining. This will be O(n log n + r) with r number of true results.

edit: on second thought you can use a binary search each on each number a find the first number that is larger than k-a reducing it to a O(n log n) completely

Title: Evaluate all pair combinations in an array for a condition in n log n time complexity

Body:
Task - Consider an array of n elements. Count the number of pairs that satisfy condition X (sum of the two elements < an arbitrary number, k) .

The basic approach I could think of would be O(n^2), where I evaluate all n*(n-1)/2 pairs. How can I solve the problem in a better time frame i.e., O(n log n) or less?

The best approach so far was to sort the array, find where a+b smaller than k then add indice of a to solution. But the process still has to go through n-1 'b's to check for each of them. It's better but still doesn't improve the worst case.

Also, this isn't homework. I came across this while preparing for a competition.


答:
Given an array A of length n and a bound k find all indices
  (i,j) such that A[i] + A[j] < k.

This can actually be solved in O(n log n).

The set I of indices (i,j) you are looking for has some structure
when the array is sorted in increasing order.  Indeed if (i₀,j₀)
belongs to I then, whenever i ≤ i₀ and j ≤ j₀ the indice pair
(i,j) also belongs to I.  This means that I looks like this:

```<code>...........
++*........
+++........
+++........
+++........
+++........
+++++*.....
++++++.....
++++++++*..
+++++++++..
</code>```

where a dot . denotes a pair that does not belong to I while a
plus + or a star * denotes a pair belonging to I.  As you see,
the presence of an indice denoted + is implied by the presence of
some indice denoted by a star * so only the latter need to be
searched.

Sort the array in O(n log n)

Set i to the largest indice so that A[i] ≤ k in O(n) and set
j to 1 if you use Pascal or 0 if you use another language, this
latter operation is O(1).

If A[i] + A[j] is greater than k then decrease i and try 3.
again, otherwise go to 4.

If A[i] + A[j+1] is smaller than k then increase j and try 4. again.

We have found a point marked with a * add it to I and decrease
i.

If A[i] + A[j+1] is greater than k then decrease i and try 6. again.

Go to 4.

Do not forget to fix the algorithm and add boundary checking and
adequate exit conditions. In the repetitive part 3.-7. the algorithm
only visits indices that are on the frontier between I and its
complement.  This frontier has length at most 2n so the overall cost
of this exploration is O(n).  The repetitive part 3.-7. is just a contrived way to say: visit that frontier, remembering whenever you have to change direction.

The total cost of the algorithm is then O(n log n) + O(n) + O(1) +
O(n) = O(n log n).

P.S.: Actually the picture should be symmetric around the first diagonal and the algorithm can stop exploring the frontier when it meets the diagonal.  These are small details.

P.P.S.: Of course, if your condition does not have structure, you must explore all combinations.

Body:
Given an array A of length n and a bound k find all indices
  (i,j) such that A[i] + A[j] < k.

This can actually be solved in O(n log n).

The set I of indices (i,j) you are looking for has some structure
when the array is sorted in increasing order.  Indeed if (i₀,j₀)
belongs to I then, whenever i ≤ i₀ and j ≤ j₀ the indice pair
(i,j) also belongs to I.  This means that I looks like this:

...........
++*........
+++........
+++........
+++........
+++........
+++++*.....
++++++.....
++++++++*..
+++++++++..

where a dot . denotes a pair that does not belong to I while a
plus + or a star * denotes a pair belonging to I.  As you see,
the presence of an indice denoted + is implied by the presence of
some indice denoted by a star * so only the latter need to be
searched.

Sort the array in O(n log n)

Set i to the largest indice so that A[i] ≤ k in O(n) and set
j to 1 if you use Pascal or 0 if you use another language, this
latter operation is O(1).

If A[i] + A[j] is greater than k then decrease i and try 3.
again, otherwise go to 4.

If A[i] + A[j+1] is smaller than k then increase j and try 4. again.

We have found a point marked with a * add it to I and decrease
i.

If A[i] + A[j+1] is greater than k then decrease i and try 6. again.

Go to 4.

Do not forget to fix the algorithm and add boundary checking and
adequate exit conditions. In the repetitive part 3.-7. the algorithm
only visits indices that are on the frontier between I and its
complement.  This frontier has length at most 2n so the overall cost
of this exploration is O(n).  The repetitive part 3.-7. is just a contrived way to say: visit that frontier, remembering whenever you have to change direction.

The total cost of the algorithm is then O(n log n) + O(n) + O(1) +
O(n) = O(n log n).

P.S.: Actually the picture should be symmetric around the first diagonal and the algorithm can stop exploring the frontier when it meets the diagonal.  These are small details.

P.P.S.: Of course, if your condition does not have structure, you must explore all combinations.


问:
anonymous checkout
Working on a E-commerce solution where I need to handle checkout based on anonymous customer and as of now I am not able to think properly how best this can be implemented.

Our ShoppingCart is being saved in database and and every update/ edit in ShoppingCart is being updated in database.

Now I need to take care about creating an anonymous customer and than assign this cart to that customer so that add to cart and well checkout can be associated with this customer.

Can anyone suggest me what can be the right way to go for this?

Should I create one anonymous user in database and use it everytime a request for new customer (anonymous ) is being created.

Place that user in current user session.

Perform any operation on cart with respect to the current session

答:
I think there are some challenges in your approach.  For example, what's going to happen when you have two users shopping before they have signed in?  From your current suggestion, it sounds like there could be problems with keeping the carts separate and making sure they can't see each other's cart.  Or what happens when a previous anonymous session has ended and a new one comes in afterwards?  Will they inadvertently receive the previous anonymous person's cart?

You don't need to associate the cart with anything except the session or a cookie until the user chooses to checkout.  So I would throw out the first part of your suggestion with creating an anonymous user and assigning that to the session.  It's okay to leave the user as null at this point in time.

For your second step, I would create a new cart and session instead of placing them in a current user session.  The exception would be if you have something persistent, such as a cookie, to tie the anonymous user to a particular cart.

The key difference is changing your point of view on how you look at users, sessions, and carts.

Currently, I think you're seeing it as: a user has a session which may have a cart.

What I'm suggesting is you see it as: a session may have a cart and may also have a user.

Taking that approach will change up your object hierarchy and help you view things in a  more flexible manner in supporting anonymous shopping sessions.

Title: anonymous checkout


问:
Semantic versioning when fixing an important bug
I currently manage a library which has a lot of public usage, and I had a question about semantic versioning. I want to refactor one fairly important part of the library which is implemented incorrectly - and has always been implemented incorrectly. But doing this would mean changes to the public API, which is a major decision.

The change I want to make revolves around how iterators are used. Currently, users have to do this:

```<code>while ($element = $iterator->next()) {
   // ...
}
</code>```

Which is incorrect, at least in PHP's native Iterator interface. I want to replace with this:

```<code>while ($iterator->valid()) {
   $element = $iterator->current();
   // ...
   $iterator->next();
}
</code>```

which is analogous to:

```<code>foreach ($iterator as $element) {
    // ...
}
</code>```

If you look at Tom's guide to semantic versioning, he clearly states that any changes to the public API (i.e. those which are not backward compatible), should justify a major release. So the library would jump from 1.7.3 to 2.0.0 which, for me, is a step too far. We're only talking about one feature being fixed.

I do have plans to eventually release 2.0.0, but I thought this was when you completely rewrote the library and implemented numerous public API changes. Does the introduction of this refactoring warrant a major version release? I really can't see how it does - I feel more comfortable releasing it as 1.8.0 or 1.7.4. Does anybody have some advice?

答:
Stick with Tom's guide to semantic versioning.

Any significant change to a public API must be done at either of the two points:

Never

At a major release update

My vote, by the way, is for the first.  But I acknowledge it's only appropriate for trifling things.

The problem is maintaining backwards compatibility and making sure you don't break things for the previous users of your API.

In essence, you are creating an indexing error for your users who are unaware of the change.  Forcing a change like this forces all of your users to do the following:

Code the fix to use the new approach

Validate the fix and make sure it didn't break anything

Ship new releases of their product to their end users

That can potentially be a lot of effort, especially when you consider just how few projects have test cases in place in order to validate changes like this.  The amount of effort compounds when you consider the number of downstream users from your users who will also need to update their installations.

For something this small, I'd let it go and not bother with it.

If it really bothers you (which apparently it does or you wouldn't have asked) then I would do the following.

Create the v2.0.0 branch in your code tree

Make the first contribution to the v2.0.0 branch, which is this change

Send out a preview Release Notes ahead of time broadcasting that the change is coming

And then be patient as it will take a while to accumulate other things that justify upgrading the version number to a new major release.  The advanced notification (part 3) gives you time to receive feedback from end users to find out just how much of an impact that change is going to be.

An alternative solution is to add a new function that operates in the way that you want.

If you have foo() then you would create fooCorrect() in order to provide the fix but also fully preserve backwards compatibility.  And at some point you can deprecate foo() to let others know not to use it.

The challenge there is that you'll find something else within fooCorrect() which necessitates it's update and you end up with fooCorrectedCorrect() or some other silly nonsense.

If you really want this fixed now, this alternative approach is probably the best route.  Be aware of and wary of creating lots of extra functions this way as it makes the API harder to work with.  And that awareness may be enough to prevent the worst of these types of problems.

But this might be the "least bad" approach to consider for something small.


答:
You hesitate because you don't want to make semantic versioning, you want to make "advertisement supporting versioning". You expect a version number "2.0" to tell the world that you have a bunch of new cool features in your library now, not that you changed the API. That's ok (many software companies and/or developers do that). IMHO you have the following options:

stick to semantic versioning and live with the fact that you have to change the version number to 2.0.0

change your versioning scheme to 4 numbers.   "1.1.7.3" is your version now, "1.2.0.0" the  next one after changing the API, and "2.0.0.0" the first one of the "completely new 2.x product family"

make your fix backwards compatible (so don't change the functionality of next, just add the valid and current functions). Then you can use "1.8.0" as the next version number. If you think changing the behaviour of next is really important, do it in 2.0.0.

Title: Semantic versioning when fixing an important bug

Body:
I currently manage a library which has a lot of public usage, and I had a question about semantic versioning. I want to refactor one fairly important part of the library which is implemented incorrectly - and has always been implemented incorrectly. But doing this would mean changes to the public API, which is a major decision.

The change I want to make revolves around how iterators are used. Currently, users have to do this:

```<code>while ($element = $iterator->next()) {
   // ...
}
</code>```

Which is incorrect, at least in PHP's native Iterator interface. I want to replace with this:

```<code>while ($iterator->valid()) {
   $element = $iterator->current();
   // ...
   $iterator->next();
}
</code>```

which is analogous to:

```<code>foreach ($iterator as $element) {
    // ...
}
</code>```

If you look at Tom's guide to semantic versioning, he clearly states that any changes to the public API (i.e. those which are not backward compatible), should justify a major release. So the library would jump from 1.7.3 to 2.0.0 which, for me, is a step too far. We're only talking about one feature being fixed.

I do have plans to eventually release 2.0.0, but I thought this was when you completely rewrote the library and implemented numerous public API changes. Does the introduction of this refactoring warrant a major version release? I really can't see how it does - I feel more comfortable releasing it as 1.8.0 or 1.7.4. Does anybody have some advice?


问:
How to update User interface form through database update
I have a client server application. Assume I work as a Support executive, resolving customer tickets. We(our support team) have got two tickets to work on.

Ticket 1: Client "Liver" raised a ticket to update his phone number.

Ticket 2: Same Client "Liver" raised a second ticket to update his email ID.

I am working on ticket 1:

Opened application, clicked edit Customer Info buttton, entered new phone number. I did not save the form(Edit form). In between, I left for CUPPA.

My colleague is looking at ticket 2: He has edited the Customer information and updated with new email id:  Its persisted in database.

When, I come back and save my ticket with phone number update, it would overwrite his changes i.e.., his email ID change is lost or not updated for that Customer "Liver".

Is there a way that when a get back to my work/page after CUPPA break, can I see the email ID with updated value?

How to prevent this? What is the approach? Possible design ideas?
How to ensure that there is no data loss?

答:
The two easiest ways of preventing this from happening are

Use a form of (user-level) locking on the database.

When you load the information of the client "Liver" into the form, a marker is placed in the database that client "Liver" is currently being edited (and possibly by whom). When your colleague tries to load client "Liver" as well, he would then be informed that you (or someone) are already editing client "Liver" and that he can't access the data for that reason. When you finally submit your changes, then the 'editing flag' would be removed from the database.

Use versioning of the data.

In this scheme, each data-set in the database gets a revision number that is incremented with each update. In the described scenario, both you and your colleague would start with the data of revision 42 of client "Liver". As your colleague is first with saving, his changes are accepted immediately and the become revision 43.
When you try to save, the database layer would notice that your changes are based on revision 42, but the current revision is 43, so your changes are rejected. Then the application can retrieve version 43, try to merge your changes into that version and inform you that someone else already made changes. You can then double check if your change is still valid and try to save again.

The main difference with what you asked for is that the update of the form on your side is delayed until you try to save.


问:
Intranet application platform decisions wamp vs node
I have a client/server java application with a firebirdsql backend. This is a pain because I have to install java and the client on every workstation, etc

So it is now time to rewrite the application, and I am deciding what technology to use.
My strengths are php/js/C#

The application can be single user or multiuser (I don't however want to force the users to install a full multiuser database service if possible)

It needs to work off-grid (some of the locations it will be used have no internet access)

It will primarily be deployed on windows desktop pc's and accessed remotely via ipads/laptops.

I would like to be able to run the whole app off a usb key, with no installation required.

My initial thoughts are just a wamp stack, although I am not sure how easy it will be to bundle it into an easily deployable application. I also need to have a background task running "aka cronjob", and I am not sure how to trigger that from within the application itself short of writing a windows service.

My second thought is to look at node+database (which database I am not sure, preferably embedded or standalone). The good thing i see here is that i can handle "cronjob type" tasks relatively easily.

The bit where i am stuck is in the database choice. I have looked at sqlite, but the drivers don't seem all that robust.

So 3 questions really.

what is a good embedded/standalone (non-server) relational databases that can be used with node.

has anyone got experience doing a similar project, and any issues they encountered with either node or wamp stacks

Are there better technology stacks I could use in this scenario

I for one have found that WAMP performs terribly over the network but flies on localhost, and I haven't been able to determine the problem.

答:
It sounds like you are trying to deploy what is now called an appliance. If so, why not just make a VM and distribute that. You can pretty easily build the file so it can be run in multiple hypervisors -- from something like the very cross-platform VirtualBox that can be run on a desktop to being able to plug in to enterprise hypervisors like VMWare and Hyper-V so it can scale to most environments.

From a development perspective it eases your pain significantly -- node isn't exactly straightforward to setup across platforms, because you are defining the platform and configuration of the platform this is no longer a problem. This also means you can make a more traditional database source than having to find something that will work cross-platform because whatever the database is it becomes embedded.

From an offline perspective you can ship the client all the necessary materials on the VM -- both the hypervisor and the machine with the code / data can all come on the same usb stick.

Finally, this makes customization for particular clients easy -- just make a client X and a client Y VM as necessary.

For an idea of what one can do with virtual appliances check out turnkey linux; they also have a turnkey core box that is a great basis for changes.


问:
What if I will not use Software Design Patterns?
What kind of problems may I face, if I won't use Software Design Patterns? Can you tell me about the problems of approaching the design using standard object-oriented techniques?</p>

答:
Those who cannot remember the past are condemned to repeat it.

You will not face any specific problems other than the ones raised by your design. And in time you will end up using the patterns without being aware, you just spent time figuring them out by yourself. Knowing the patterns beforehand makes them easier to spot in the design and bear the major advantage that they are proven by a number of individuals.

Everything that's being developed today is based largely on previous knowledge, it would make no sense to ignore it. Imagine building a skyscraper today without knowing the problems faced by the people who built cathedrals some hundreds years ago.


问:
A design pattern for data binding an object (with subclasses) to asp.net user control
I have an abstract class called Address and I am  deriving three classes ; HomeAddress, Work Address, NextOfKin address.

My idea is to bind this to a usercontrol and based on the type of Address it should bind properly to the ASP.NET user control.

My idea is the user control doesn't know which address it is going to present and based on the type it will parse accordingly.

How can I design such a setup, based on the fact that, the user control can take any type of address and bind accordingly.

I know of one method like :- Declare class objects for all the three types (Home,Work,NextOfKin). Declare an enum to hold these types and based on the type of this enum passed to user control, instantiate the appropriate object based on setter injection.

As a part of my generic design, I just created a class structure like this :-

I know I am missing a lot of pieces in design. Can anybody give me an idea of how to approach this in proper way.

答:
I think your best bet would be to define an abstract class that represents an address and the type of address:

```<code>public abstract class Address
{
    public abstract string Type { get; }
    public abstract IEnumerable<string> FieldLabels { get; }
    public abstract IEnumerable<string> FieldValues { get; }
};
</code>```

which you might derive from like this:

```<code>public class HomeAddress : Address
{
    public string FirstLine { get; set; }
    public string ZipCode { get; set; }
    public override string Type { get { return "HomeAddress"; } }
    public override IEnumerable<string> FieldLabels
    {
        get
        {
            List<string> tmp = new List<string>();
            tmp.Add("First Line");
            tmp.Add("Zip Code");
            return tmp;
        }
    }
    public override IEnumerable<string> FieldValues
    {
        get
        {
            List<string> tmp = new List<string>();
            tmp.Add(FirstLine);
            tmp.Add(ZipCode);
            return tmp;
        }
    }
};
</code>```

Any GUI element can then simply be passed an object as a base class pointer, and retrieve and display the address type and address fields.

If there are fields that always appear in all address types then they could be defined in the base class with only optional/variably present fields retrived through the IEnumerable properties.

Body:
I think your best bet would be to define an abstract class that represents an address and the type of address:

public abstract class Address
{
    public abstract string Type { get; }
    public abstract IEnumerable<string> FieldLabels { get; }
    public abstract IEnumerable<string> FieldValues { get; }
};

which you might derive from like this:

public class HomeAddress : Address
{
    public string FirstLine { get; set; }
    public string ZipCode { get; set; }
    public override string Type { get { return "HomeAddress"; } }
    public override IEnumerable<string> FieldLabels
    {
        get
        {
            List<string> tmp = new List<string>();
            tmp.Add("First Line");
            tmp.Add("Zip Code");
            return tmp;
        }
    }
    public override IEnumerable<string> FieldValues
    {
        get
        {
            List<string> tmp = new List<string>();
            tmp.Add(FirstLine);
            tmp.Add(ZipCode);
            return tmp;
        }
    }
};

Any GUI element can then simply be passed an object as a base class pointer, and retrieve and display the address type and address fields.

If there are fields that always appear in all address types then they could be defined in the base class with only optional/variably present fields retrived through the IEnumerable properties.


答:
For drupal and wordpress we have a similar problem -- there is a core which gets updated from one direction and then some site-specific files which come from another direction. The solution we came up with was a combination of effectively forked repositories and sub-repositories.

First, for the repositories what we do is create a template project / site incorporating our project layout and configuration scripts and bits with the default application setup in our project. This is setup in a branch -- say wp-default for wordpress -- rather than in master. To spin up a new project, we init a new repo and pull from the default project. We then merge the wp-base branch into the repo making master have a clean copy of our site's setup. We don't actually fork things as the updates aren't going to ever flow back, rather the concrete project will pull updates in from time to time.

For your theme and other customizations, they would just land in the project normally from here on out. When there is an update to the core, you pull changes in from that default project and then merge them into your working copy.

The subrepos kick in for content -- we put the sites content and databases into a subrepo, mainly because we've seen content kill repositories so we want separability and also it makes it easy to automatically update an independent repo. A script copies them into appropriate places or forcibly restores things.

This will work brilliantly so long as your theme and customizations are happening in separate files and things are not horribly intermingled. Having a fully independent end-repo makes it possible to jam in any hacks you need on the pointy end -- we have had to hack the drupal / wordpress core a few times for good and bad reasons.


问:
Template Functions and Function templates in C++
I came across a question which asked the difference between Function Templates and Template Functions in C++ and also Template Classes and Class Templates.

I was under the impression that Function Templates and Template Functions were the same thing. Is there any difference between the two, if so what is it?

答:
```<code>template <class T> T abs(T n) //function template
{
    return (n<0) ? -n : n;
}

int main()
{
    int int1 = -10;
    cout << “\nabs(“ << int << “)=” << abs(int1);  //calling the abs function for type int
}
</code>```

When the compiler sees such a function call, it knows that the type to use is int because that’s the type of the argument int1. So it generates a specific version of the abs() function for type int, substituting int wherever it sees the name T in the function template.

This is called instantiating the function template, and each instantiated version of the function is called a template function. That is, a template function is a specific instance of a function template

Body:
template <class T> T abs(T n) //function template
{
    return (n<0) ? -n : n;
}

int main()
{
    int int1 = -10;
    cout << “\nabs(“ << int << “)=” << abs(int1);  //calling the abs function for type int
}

When the compiler sees such a function call, it knows that the type to use is int because that’s the type of the argument int1. So it generates a specific version of the abs() function for type int, substituting int wherever it sees the name T in the function template.

This is called instantiating the function template, and each instantiated version of the function is called a template function. That is, a template function is a specific instance of a function template