答:
template class is a term which should not be used, it used to designate what we are calling now a class template specialization since at least the 98 standard, but most people who are using it tend to use it as a synonym of class template (and that was true in the past as well, thus the introduction of another unambiguous term).

From the Annotated C++ Reference Manual (Ellis and Stroustrup, 1990):

A class template specifies how individual classes can be constructed.

A class generated from a class template is called a template class.

Title: Template Functions and Function templates in C++

Body:
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?


问:
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>

答:
You're missing the point.

Design Patterns inherently exist when doing software design, just like structural patterns exist in the world. Even if you don't know the name of things, you'll eventually find that certain physical structures are well suited for certain problems. You'll find that a triangle shape of wood/metal bars/etc is a very stable structure, but only on a plane. You'll find square bricks have certain advantages over round ones...

Likewise, certain software structures are in some way unique or optimal. You'll eventually find them and use them regardless if you know the names for them. That's the core of what design patterns are - they're names for these structures that experienced programmers know and use anyways. It gives programmers the ability to communicate much more uniformly and succinctly. It also lets programmers think in the concept of patterns more consciously.

So the two key points I'm trying to make:

You can't not use design patterns.

By not knowing the names for the things you're using, you'll have a difficult time working in a team.

ContentLicense: CC BY-SA 3.0


问:
Transactional Memory vs Mutex and Locks
Just found out that Intel processors now have Transactional Memory support !!!!
I learned about Transactional operations in my dB/OS class, it is a very simple concept: entire operation is executed or nothing gets executed.

How is programming under new Transactional Mem. model is different from Multithreaded model that uses locks and mutexes ? Does it mean that we will be getting rid of locks and mutexes ?

答:
Transactional Memory (TM) programming really has two elements that need to be discussed: productivity and performance.

Productivity

Compared to locks, Transactional Memory can be considered a higher-level access-control construct. The difference is akin to imperative programming vs declarative.

From a programmer's standpoint, TM is supposed to allow you to declare what needs to be executed atomically, rather than providing instructions (in the forms of locking code) on how the atomic execution should be done.

This comes with a number of promised benefits compared to locking -- easier reasoning, composability, deadlock-freedom.

Performance

Compared to locks, TM is (supposed to be --- implementations can vary here!) an optimistic access-control construct, as opposed to the pessimism of locks. The general idea of TM is that instead of requiring mutual exclusion from an atomic region, as you would with locks, the system allows multiple threads to enter the atomic region.

By tracking the state changes, and monitoring for the possibility of data races, in the case where a race does not occur, the system will allow the threads to commit. Otherwise, at least one transaction will be aborted and re-started. In the case where conflict is rare, this can be a substantial performance gain.

Caveats

Like all real systems, there's a list of caveats as long as my arm. Here's a partial set:

In an HTM, you need to worry about transactions which can't be committed --- illegal opcodes, too much state for the system to handle, etc. Which means you need a fallback path.

How to deal with atomic IO operations?

Performance goes up if conflict is rare --- but what about if it's not? Performance goes down, by wasting work retrying again and again.

How do you cooperate between threads using TM instead of locks?

Title: Transactional Memory vs Mutex and Locks


问:
shall a vector2 extends a vector3 or is it the opposite?
Perhaps the question might be tied to a theoritical or mathematical forum, but since it is for programming purpose, i ask here first:

In a computer vision context, i write a couple of interfaces intended to be the "read-only" part of vectors. So i define "IVector2R" and "IVector3R" that only contain getters. The question is:
does IVector2R extends IVector3R (and the "y getter" always returns 0), or is it the opposite: IVector3R extends IVector2R?

I would like a conception as close as possible to the mathematic/sets theory...

Thank you for your attention

答:
Interesting.

From the Liskov Substitution Principle, one could argue that a Vector3R "is a" Vector2R, but just with more stuff (a Z axis if these are dimensions, a "y getter" in your vision example).  I think from a "purist" math/sets POV this works best.  The drawback is that your class hierarchy might get messy, with eventual Vector4R, SomeSpecialVector3R, ImmutableVector3R, etc...

So, arguing that a Vector2R is a Vector3R but always returns 0 (or null, etc.) makes a bit of sense too.  And it might make your class hierarchy much less messy.  For example, you don't even need a Vector2R class.  Perhaps just an additional method, whatIsMyN().

Option#2 is how Java handles it's Collections - instead of a gazillion classes in a dense hierarchy, they are allowed to say "no" by returning 0 (actually, in their case, they do even worse, throw an exception).  Some programmers like it, and some hate it.  Drawback: It requires that your code be a bit smarter: either ask ahead of time if this "Vector3" has a y getter, or be prepared for and ready to deal with 0s coming back.

I've coded both ways.  Depends how "reasonable" it is, in your domain, for 0s to be coming back.


答:
In my opinion, neither nor: Both are n-tuples with different n. The problem with this is that most languages don't allow types to be parameterized by a value.

When deciding a certain inheritance, you should consider matrix multiplication.

```<code>/1 0\   /2\ ?  /1 0 0\   /2\
\0 1/ · |3| =  |0 1 0| · \3/
        \4/    \0 0 0/
</code>```

You are implicitly arguing that one or both multiplications work (and should possibly be equivalent). At this point every mathematician is having a heart attack, because you violated certain rules about the required dimensionality.

I think it is obvious that Vector3 can't be a subtype of Vector2, and not the other way round: You cannot generally use one in place of the other. But both have common properties. I would probably define an interface Vector with methods like component(i) which gives the i-th component (instead of getX, getY, …), size() which gives the dimensionality, and norm() which calculates the length.

If you are hell-bent on having one type inheriting from another, consider these test cases:

// failure with Vector3 <: Vector2 -- vec.z can be != 0
if (vec instanceof Vector2)
  assert vec.z == 0;

// failure with Vector3 <: Vector2 -- vec.z can be != 0
if (vec instanceof Vector2)
  assert vec.norm() == sqrt(vec.x^2 + vec.y^2); // euclidean norm - invalid in non-cartesian systems

// failure with Vector2 <: Vector3 if they are mutable (Circle-Ellipse Problem)
if (vec instanceof Vector2) {
  vec.z = 42;
  assert vec.z == 0;
}

// failures concerning dimensionality with *any* inheritance relation
// when considering matrix multiplication
```

This means that I have to grudgingly admit that having Vector2 inherit from Vector3 would work in most cases, if they are immutable and you aren't doing anything more fancy than addition or scalar multiplication.

Note On Coordinates

If you don't want to do vector algebra but just want to represent coordinates, then this answer would be different, because 2D coordinates can be viewed as a projection of 3D coordinates into a plane (or any other surface parameterizable by two numbers). In this case, every 2D coordinate would also have a 3D coordinate, but the two coordinates are from two different coordinate systems. Projection into the z = 0-plane is one very special case of this where it is possible to view the 2D-coordinate as a kind of 3D-coordinate. This is not generally the case in all 2D coordinate systems.

Title: shall a vector2 extends a vector3 or is it the opposite?

Body:
Perhaps the question might be tied to a theoritical or mathematical forum, but since it is for programming purpose, i ask here first:

In a computer vision context, i write a couple of interfaces intended to be the "read-only" part of vectors. So i define "IVector2R" and "IVector3R" that only contain getters. The question is:
does IVector2R extends IVector3R (and the "y getter" always returns 0), or is it the opposite: IVector3R extends IVector2R?

I would like a conception as close as possible to the mathematic/sets theory...

Thank you for your attention

Body:
In my opinion, neither nor: Both are n-tuples with different n. The problem with this is that most languages don't allow types to be parameterized by a value.

When deciding a certain inheritance, you should consider matrix multiplication.

/1 0\   /2\ ?  /1 0 0\   /2\
\0 1/ · |3| =  |0 1 0| · \3/
        \4/    \0 0 0/

You are implicitly arguing that one or both multiplications work (and should possibly be equivalent). At this point every mathematician is having a heart attack, because you violated certain rules about the required dimensionality.

I think it is obvious that Vector3 can't be a subtype of Vector2, and not the other way round: You cannot generally use one in place of the other. But both have common properties. I would probably define an interface Vector with methods like component(i) which gives the i-th component (instead of getX, getY, …), size() which gives the dimensionality, and norm() which calculates the length.

If you are hell-bent on having one type inheriting from another, consider these test cases:

// failure with Vector3 <: Vector2 -- vec.z can be != 0
if (vec instanceof Vector2)
  assert vec.z == 0;

// failure with Vector3 <: Vector2 -- vec.z can be != 0
if (vec instanceof Vector2)
  assert vec.norm() == sqrt(vec.x^2 + vec.y^2); // euclidean norm - invalid in non-cartesian systems

// failure with Vector2 <: Vector3 if they are mutable (Circle-Ellipse Problem)
if (vec instanceof Vector2) {
  vec.z = 42;
  assert vec.z == 0;
}

// failures concerning dimensionality with *any* inheritance relation
// when considering matrix multiplication

This means that I have to grudgingly admit that having Vector2 inherit from Vector3 would work in most cases, if they are immutable and you aren't doing anything more fancy than addition or scalar multiplication.

Note On Coordinates

If you don't want to do vector algebra but just want to represent coordinates, then this answer would be different, because 2D coordinates can be viewed as a projection of 3D coordinates into a plane (or any other surface parameterizable by two numbers). In this case, every 2D coordinate would also have a 3D coordinate, but the two coordinates are from two different coordinate systems. Projection into the z = 0-plane is one very special case of this where it is possible to view the 2D-coordinate as a kind of 3D-coordinate. This is not generally the case in all 2D coordinate systems.


问:
What do programmers "micro-optimize" for today?
Back in the "good ol' days," when we would copy shareware onto floppies for friends, we also used a fair bit of assembly. There was a common practice of "micro-optimization," where you would stare and stare at lines of assembly until you figured out a way to express it in one fewer instruction. There was even a saying, which was mathematically impossible, that "You can always remove one more instruction." Given that changing runtime performance by small constant factors isn't a major issue for (most) programming today, are programmers transferring these micro-optimization efforts elsewhere?

In other words, Can a best-practice be taken to an extreme state where it's no longer adding anything of value? And instead is wasting time?

For example: Do programmers waste time generalizing private methods that are only called from one place? Is time wasted reducing test case data? Are programmers (still) overly concerned about reducing lines of code?

There are two great examples of what I'm looking for below: (1) Spending time finding the right variable names, even renaming everything; and (2) Removing even minor and tenuous code duplication.

Note that this is different from the question "What do you optimize for?", because I'm asking what other programmers seem to maximize, with the stigma of these being "micro" optimizations, and thus not a productive use of time.

答:
I sometimes spend (waste?) time while choosing a good name for a variable or a method so that it is not only precisely descriptive but also has a good linguistic style.

It goes a little further when I attempt to put the entire works (a program) into the same linguistic style. Sometimes my opinion changes and I revise the book. :)

No that it takes that much time. It's rather rare. But I like to keep the good grammar in my programs.

ContentLicense: CC BY-SA 2.5


问:
Identifying how server is authenticating users
I'm trying to build a bot that will parse the list of classes offered by my university and let me know when the one I'm looking for is open.  The problem is that in order to get to the registration/search box, I have to log in with my university username and password.  I'm trying to figure out what protocol that my school uses to authenticate me so I can give my bot my credentials and let it log in for me so it can access the registration/search page, so how can I figure out what they are using so I can figure out how to implement it in whatever language I decide to use.  I've gone through packet captures but all I can see is the SSL syn/ack, which I guess is the point of SSL haha.

Can anyone recommend how to figure out what protocol my school uses to log in users?

答:
Two authorization mechanisms are commonly used:

Session cookies – inspect your request headers and find out which are actually relevant.

HTTP authorization – noticeable when the browser, not the website prompts you for credentials. Also, the Authorization header should be quite visible when you inspect the headers with your web browser.

E.g. in Chrome, open the developer tools and load a protected page while the “Network” tab is opened. Similar for Firefox or IE.

In most cases, it is actually easier to have your bot log into the page itself, rather than always feeding it up-to-date authorization tokens. Depending on what language you are using, you might enjoy the Selenium bindings. With Perl, Mechanize::Firefox is another good option.


答:
Understanding the point of a design pattern is more important than using it to the letter. Some patterns are, IMO, silly, at least in the language paradigms I'm accustomed to. IMO, a programmer who simply uses design patterns blindly and without really understanding them is a worse programmer than the one who would want to think through things themselves. But somebody who familiarizes themselves with the ideas and then decides for themselves whether they're worthwhile is likely to be a much stronger programmer than either.

That said, I have no !@#$ing idea what the point of flyweight is and I'm not ashamed to admit it. (see comments for another wikipedia entry that helped a lot)

I recommend wikipedia's entry on design patterns. It's very concisely and clearly written. Very helpful for getting an idea of why one might bother with a given design pattern or not. I personally tend to find the simplest ones the most useful and wouldn't think twice about modifying a given implementation of any pattern to suit my needs.

They're ideas, not blueprints. In some languages they're not very good ideas at all. In others, they're rightly seen as being kludges for overcoming a language's design weaknesses that might be better compensated for through less complexity. Regardless, it doesn't hurt to examine them and try to understand the challenges they're meant to overcome before deciding on your own preferred solutions.

What kinds of problems will you face? You might miss opportunities and spend more time on problems than you needed to unless you're a programming genius who already has it all figured out. It's important to maintain a critical eye of popular programming ideas but it never hurts to understand what it is people think they're solving because that will lend more clarity to your own preferred solutions/approaches.

Title: What if I will not use Software Design Patterns?

Body: 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>


问:
Is error suppressing bad practice?
On a SO question I asked here about some code I was unsure about, someone replied "BTW, horrible code there: it uses the error suppressing symbol (@) a lot."

Is there a reason why this is bad practice? With things like:

```<code>$db=@new mysqli($db_info) or die('Database error');
</code>```

, it allows me to display just a custom error message. Without error suppressing, then it would still display the typical PHP message of:

Warning: mysqli::mysqli(): php_network_getaddresses: getaddrinfo failed: No such host is known. in some\file\path on line 6

as well as 'Database error'.

Is error suppressing always bad, and if so, what specifically about the above is bad?

Update: the actual code that I'm using is:

```<code>or error('Datatabase error', 'An error occurred with the database' . (($debug_mode) ? '<br />MySQL reported: <b>' . $db->error . '</b><br />Error occurred on line <b>' . __LINE__ . '</b> of <b>' . __FILE__ . '</b>' : ''))
</code>```

which removes all previous output and displays an error message. So the fact that the error message doesn't include details about what specifically happened (which people seem to be suggesting as a reason why error suppressing is bad) is irrelevant.

答:
Error suppression is bad, because it does not only hide the information you already know (something went wrong). It may also hide information vital for debugging which you aren't aware of (what, where and why).

In this specific example, “Database error” isn't a very good error message. Something went wrong with the DB. Not very enlightening. The “Warning: mysqli::mysqli(): php_network_getaddresses: getaddrinfo failed: No such host is known. in some\file\path on line 6” is actually a better error message. It gives you a location and reason for the problem. You can jump right in and start debugging, because the error has already been located.

Of course, library designers sometimes have a tendency of bringing up to many irrelevant warnings. I don't know PHP sufficiently well to know if it has a way to filter warnings you are not interested in. I know that reading through a hundred-line stacktrace isn't very enlightening. But the correct response to too much information is not to reduce the amount of information to zero, but to filter out irrelevant parts at some stage. The @ operator does not have this granularity (it's motto is all or nothing), and is therefore not a suitable tool for effective error management.

There are some cases where you know that a certain error will turn up, and that fixing the actual problem is more expensive than silencing the message (and suffering potential fallout from that). This could be the case in a one-off script, but sticking your fingers into your ears and going “la la la” is not a professional response to (potential) bugs.

Title: Is error suppressing bad practice?


答:
I think you're doing the right thing by suppressing the error, because you are implementing your own error handling.

It might be easier to consider the equivalent in, say, Java.  Suppressing the error using @ is analogous to swallowing an exception.  The following code, which is similar to yours, is reasonable:

```<code>try {
    db = new MySQLi(dbInfo);
} catch (SQLException connectionFailure) {
    die("Database error");
}
</code>```

(Well, in Java, you wouldn't want the servlet engine to die, but you get the idea.)

However, this isn't acceptable:

```<code>try {
    db = new MySQLi(dbInfo);
} catch (Exception e) {
}
</code>```

Most PHP error suppression is done carelessly, analogous to the latter example, hence the knee-jerk reaction against your code.

Title: Is error suppressing bad practice?

Body:
On a SO question I asked here about some code I was unsure about, someone replied "BTW, horrible code there: it uses the error suppressing symbol (@) a lot."

Is there a reason why this is bad practice? With things like:

```<code>$db=@new mysqli($db_info) or die('Database error');
</code>```

, it allows me to display just a custom error message. Without error suppressing, then it would still display the typical PHP message of:

Warning: mysqli::mysqli(): php_network_getaddresses: getaddrinfo failed: No such host is known. in some\file\path on line 6

as well as 'Database error'.

Is error suppressing always bad, and if so, what specifically about the above is bad?

Update: the actual code that I'm using is:

```<code>or error('Datatabase error', 'An error occurred with the database' . (($debug_mode) ? '<br />MySQL reported: <b>' . $db->error . '</b><br />Error occurred on line <b>' . __LINE__ . '</b> of <b>' . __FILE__ . '</b>' : ''))
</code>```

which removes all previous output and displays an error message. So the fact that the error message doesn't include details about what specifically happened (which people seem to be suggesting as a reason why error suppressing is bad) is irrelevant.

Body:
I think you're doing the right thing by suppressing the error, because you are implementing your own error handling.

It might be easier to consider the equivalent in, say, Java.  Suppressing the error using @ is analogous to swallowing an exception.  The following code, which is similar to yours, is reasonable:

try {
    db = new MySQLi(dbInfo);
} catch (SQLException connectionFailure) {
    die("Database error");
}

(Well, in Java, you wouldn't want the servlet engine to die, but you get the idea.)

However, this isn't acceptable:

try {
    db = new MySQLi(dbInfo);
} catch (Exception e) {
}

Most PHP error suppression is done carelessly, analogous to the latter example, hence the knee-jerk reaction against your code.


问:
Better style for member variables?
```<code>class awesomeClass {
    std::list<A> myList;
    //...
    void fillList();
};

awesomeClass::awesomeClass() {
    fillList();
}

void awesomeClass::fillList(){
    //...
    foreach(A a, otherList)
        myList.push_back(a); //add to list
}
</code>```

Compared to :

```<code>awesomeClass::awesomeClass() {
    myList = fillList();
}

std::list<A>& awesomeClass::fillList() {
    //...
    std::list<A> ret;
    foreach(A a, otherList)
        ret.push_back(a); //add to list
    return ret;
}
</code>```

This is just a class with an std::list as a member variable and a function which fills this list. The first fills it inside the function and the second one returns a list and assigns it to the member list.

Which of these is better style? The one which fills the list inside the function or the one which returns a list? Or is there an even better solution?

答:
In object orientied programming, classes have

State, which is represented by instance variables, and

Methods, which change the state

So your first approach is correct where you call a method that sets the instance variable.

You should return a value only when that is not represented by any instance variable or it is a public method called by consumer, which doesn't have access to the instance variable.

OwnerDisplayName: Davlog

Title: Better style for member variables?


问:
How many strings are created in memory when concatenating strings in Java?
I was asked about immutable strings in Java. I was tasked with writing a function that concatenated a number of "a"s to a string.

What I wrote:

```<code>public String foo(int n) {
    String s = "";
    for (int i = 0; i < n; i++) {
        s = s + "a"
    }
    return s;
}
</code>```

I was then asked how many strings this program would generate, assuming garbage collection does not happen.
My thoughts for n=3 was

""

"a"

"a"

"aa"

"a"

"aaa"

"a"

Essentially 2 strings are created in each iteration of the loop. However, the answer was n2. What strings will be created in memory by this function and why is that way?

答:
As MichaelT explains in his answer, your code allocates O(n) strings. But it also allocates O(n2) bytes of memory and runs in O(n2) time.

It allocates O(n2) bytes, because the strings you're allocating have lengths 0, 1, 2, …, n-1, n, which sums to (n2 + n) / 2 = O(n2).

The time is also O(n2), because allocating i-th string requires copying of (i-1)-th string, which has length i-1. This means each allocated byte has to be copied, which will take O(n2) time.

Maybe this is what the interviewers meant?

ContentLicense: CC BY-SA 4.0


答:
I suppose I am concerned with LOCs too much. Not so much LOCs themselves, but rather number of statements and even more number of duplicate statements. I am allergic to duplicate code.
In general I love refactoring, but I suppose about 50% of what I do doesn't make the code signifficantly nicer.</p>

Title: What do programmers "micro-optimize" for today?

Body:
Back in the "good ol' days," when we would copy shareware onto floppies for friends, we also used a fair bit of assembly. There was a common practice of "micro-optimization," where you would stare and stare at lines of assembly until you figured out a way to express it in one fewer instruction. There was even a saying, which was mathematically impossible, that "You can always remove one more instruction." Given that changing runtime performance by small constant factors isn't a major issue for (most) programming today, are programmers transferring these micro-optimization efforts elsewhere?

In other words, Can a best-practice be taken to an extreme state where it's no longer adding anything of value? And instead is wasting time?

For example: Do programmers waste time generalizing private methods that are only called from one place? Is time wasted reducing test case data? Are programmers (still) overly concerned about reducing lines of code?

There are two great examples of what I'm looking for below: (1) Spending time finding the right variable names, even renaming everything; and (2) Removing even minor and tenuous code duplication.

Note that this is different from the question "What do you optimize for?", because I'm asking what other programmers seem to maximize, with the stigma of these being "micro" optimizations, and thus not a productive use of time.


答:
Supressing errors is bad because it hides the problem, which many times we are not even aware of and it may result in unexpected behavior that may prove very costly in some critical applications eg in applications that are used in financial, health and defence domains.

It is also not a good idea to have unhandled exceptions in the code and show the actual error messages to the user as it may result in security issues because error messages usually reveal a lot about your code, which may help malicious users and hackers to manipulate the system.

So the good practice is to handle the errors at different levels eg at highest level you may handle the error by just loggin the actual error and showing a simple and user friendly message to the user.

Title: Is error suppressing bad practice?


问:
Using multiple Git repositories instead of a single one containing many apps from different teams?
I am migrating a 10-years-old big CVS repository to Git. It seemed obvious to split this multiple-projects repository into several Git ones. But the decision-makers are used to CVS, therefore their point of view is influenced by CVS philosophy.

To convince them to migrate from one CVS repo to different Git repositories I need to give them some arguments.

When I speak with mates working on Git repo for years, they say that using multiple Git repo is the way to use Git. I do not know really why (they give me some ideas). I am a newbie in this field so I ask here my question.

What are the arguments to use multiple Git repositories instead of a single one containing different applications and libraries from different teams?

I have already listed:

branches/tags impact the whole Git repository files => pollutes other team projects

4GB limit Git repo size but this is wrong

git annotate may be slower on bloat Git repo...

Eamon Nerbonne has noticed the related question:

Choosing between Single or multiple projects in a git repository?

The reason the team managers finally have accepted the split: the single Git repo (550 MB) was requiring 13 minutes to be cloned on Windows (one minute on Linux).

The bloat CVS repo split in 100 Git repositories:

each dead apps in one repo

each stabilized library in one repo (source code almost never changed any longer)

related apps/libs kept together in one repo

moved large files not used for compilation (config...) to other repos (Git does not like large files)

skipped other unrelevant files (*.jar, *.pcb, *.dll, *.so, *.backup ...)

Successfully installed the repo tool used by Android Open Source Project in order to handle all these Git repos:

easy installation on Linux

more difficult on Windows because of Cygwin and NTFS native symlinks requirements

答:
They want [something that can] show their changes across all projects instead of trying to remember what project they made a change [to].

Sourcetree (a free-as-in-beer GUI Git frontend) allows you to register multiple repositories, organise them into logical groups, and then view status across all of them at once:

I am not affiliated with them in any way.


问:
How to estimate cost with very little information?
I have a client who wants a web app that will let him do the following (as he told me word for word):

User registration

Recurring payments for users

Online conference room reservation

I am supposed to give him a cost estimate very fast and I don't have any time to do any deeper requirements analysis! How would you deal with that kind of situation? Should I just give a very broad estimate and work out the exact requirements once he has accepted the estimate? At which point do you usually gather requirements, after or before getting a contract?

答:
There are some really great answers already. Here are a couple more remarks based on having made my living doing outsourced development like this for most of the last twenty years.

Without an adequate, written, agreed-upon specification, doing fixed price contracts is a fast way to lose tons of money.

My wife and I had a custom software development firm. Around 1998, we were approached to do a  port. "We don't really have a spec or even a feature list, we just need a Mac program with the same features as our Windows version." So we looked over the Windows version, proposed a price, dickered a bit, and agreed on a price. And then it turned out that not only did the liars have a feature list, but there were a ton of hidden features we hadn't noticed during our review that were very hard and time-consuming to implement. Our employees' salaries alone to complete that project cost us three times our revenue for it.

My experience has been that people who don't provide a spec, and aren't willing to pay you to write one, are either amateurs or trying to get something for nothing, and both kinds of clients are big trouble.

Don't write a specification and give it to the client for free.

It's very tempting to do that so you can get agreement from the client and protect yourself - but I used to do that, and decided it's a mistake. One time I did that, I included information in the spec about which I had particular expertise. The prospective client switched to a cheaper development team; the info in the spec filled in the missing gaps in their knowledge - and the substantial work I'd put into the spec was in the toilet.

I now consider specifications and design documents to not only be work products, but highly specialized ones for which I charge a much higher hourly rate than I do for simple programming. That way, if the client wants to put them out for bids by cheap code monkeys on eLance, no hard feelings.

Actually, in the last eight years, I've solved the problem very simply: I no longer do fixed-price projects and have an hourly rate floor I won't go below.. Since making that switch, I'm far happier, make way more money, and the skeevy clients go somewhere else.


问:
What do I benchmark before updating a web site?
I am volunteering my time to update a website for a local business. The current website they have is not up to date and it fails quite a few "web tests".

For example, the pages are too large, the images are not compressed, and the site is not mobile friendly.

All of these things are measurable - eg. the time taken to load (in seconds), bandwidth (in kb), and a list of the devices the site displays correctly on. It is my intention to note these benchmarks before starting the project, and upon completion.

My question is: what benchmarks do web developers present to their clients?

答:
SEO. Most clients don't care about technical details of a website.
They want people to come to the website so it has to appear near the
top of search result. They'd pay a lot for this. Maybe the website
doesn't need to change, just need to be advertised.

User Experience. After people visits the website, they need to be converted into customers.    This can be technical, stuff like page latency, responsive design, etc. It can also be the design itself which could require overhaul.

So, instead of benchmarks, try analyse logs and install analytics if there's not one installed yet and see if updating would improve the bottom line.


问:
Shoud I directly return a string message or rather a i18n key when dealing with JSON api?
Suppose a rest api returning this json:

```<code>{
    "status" : "fail",
    "data" : { "title" : "A title is required" }
}
</code>```

Since the client application would always adapt the error message, would it be better to return an explicit i18n key that the client would have mapped rather than "A title is required"? :

```<code>{
    "status" : "fail",
    "data" : { "title" : "error.creation.title.required" }
}
</code>```

Indeed, the point is to expect the request consumer (web application for instance) to easily translate the message regarding its localization.

答:
One way to go would be to include a flag in your request if the user wants to have an i18n key.

```<code>host/page?somrequest=somevalue&flagi18n=true
</code>```

Seeing this flag, you may then let your API return the i18n key. Otherwise, you return the message in the default language.

This way, you keep your API decoupled from the client.
For me, this is a matter of preference.

Body:
One way to go would be to include a flag in your request if the user wants to have an i18n key.

host/page?somrequest=somevalue&flagi18n=true

Seeing this flag, you may then let your API return the i18n key. Otherwise, you return the message in the default language.

This way, you keep your API decoupled from the client.
For me, this is a matter of preference.


答:
If you were defining common error format for your Api, see also "Problem Details for HTTP APIs". You don't need to say "status: fail" because it should be indicated already in status code. You can use "problemType" URI as key.

2. For clients that don't want to translate error message themselves, they should use Accept-Language header so server knows what language it needs to speak.

Title: Shoud I directly return a string message or rather a i18n key when dealing with JSON api?

Body:
Suppose a rest api returning this json:

```<code>{
    "status" : "fail",
    "data" : { "title" : "A title is required" }
}
</code>```

Since the client application would always adapt the error message, would it be better to return an explicit i18n key that the client would have mapped rather than "A title is required"? :

```<code>{
    "status" : "fail",
    "data" : { "title" : "error.creation.title.required" }
}
</code>```

Indeed, the point is to expect the request consumer (web application for instance) to easily translate the message regarding its localization.


答:
When I was writing assembly language it made sense to nitpick over bytes and cycles, but that was a long time ago and compilers have come a long way since then. I wouldn't try to manually out-optimize one now.

Similarly, when I switched to writing in C it was pretty easy to do a better job than the C compilers, but every year Borland or Microsoft or someone would release a new 'n improved one that kicked the previous one around the room. I started paying attention to the actual assembly code that the compiler was emitting and, danged if it wasn't writing some nice and tight code, unrolling loops, moving variables outside the loops, etc.

Now days I'm writing in a lot higher languages like Perl, Python and Ruby. I use some of the compiler tricks up front, like loop unrolling if it makes sense, moving static variables outside the loops, etc., but I don't worry about it nearly as much because CPUs are a weeeeee bit faster now. If an app seems to be dragging unexpectedly then I'll use a profiler and see what I can find, and then if something can be improved I'll start benchmarking various ways I can think of to do something faster, and then see how it scales up.

In general I try to be smart on how I write code, based on years of experience.


问:
How do you convince management to throw away a prototype?
I love prototyping as a fast effective way to put a UI in front of a user.

Many times though, management get their beaks in the way, and the prototype is dragged kicking and screaming into main stream development.

How do you manage management into not doing this?

答:
I used to have this problem, until, I realized it wasn't a problem but a way of liberating myself from the rather outdated development standards imposed on most shops.

So you tell your management you are writing a prototype, you pick the technologies that work best for you, for this problem area, and you then write the software in the full knowledge that it will go in to production.

You escape the tedium of "applications must be in java 1.6 using Web(insert expensive J2EE engine of managements choice)" and pointless naming standards etc.

My current prototype languages of choice are "php" (which totally scales to heavy duty production environments -- just ask Facebook) and the very elegant combination of Groovy/Java with either Tomcat or Jetty.

The groovy/java combination is great for rapid development. Groovy is nice to use quick to develop but performs like a geriatric snail, however it is trivially easy to re-factor performance critical sections in to pure Java. Wedding the application to Tomcat or Jetty means never having to deal with EJBs and other J2EE horrors again.

The main advantage of having a working prototype as opposed to a sketch as proposed by several posters is user feedback. Prototypes are a great way of getting the business truly involved in the design. Once they realize they can say things like "shouldn't that field be on the main screen" and hey presto! there it is on the main screen at the next demo they open up and get involved in the design bringing years of valuable business experience to the project.


问:
Is learning C# as a first language a mistake?
I know there are similar questions on here, which I've read, but I recently read this post by Joel Spolsky:

How can I teach a bright person, with no programming experience, how to program?

And it got me thinking about my way of learning and whether it might actually be harmful in the long run.

I've dabbled with various languages but C# is my first serious one, I've read "Head First C#" and created a few projects. But after reading the post above I've found it a bit disheartening that I may be going about it all wrong, obviously I respect Joel's opinion which is what has thrown me a bit.

I've started reading "Code" as recommended in the reading list and I'm finding it pretty hard going, although enjoyable. I feel like it's taken the shine off of my "noobish hacking about" in Visual Studio.

So now I'm unsure as to what path I should take? Should I take a step back and follow Joel's advice and start reading?

I guess my main aim is just to become a good programmer, like everyone else, but I don't want to be going into bad practice by learning a .NET language when someone who's opinion I respect thinks that it is harmful.

Thoughts?

答:
I would recommend C# or any language that offers these three things at their core:

Fully typed
Compiled
And fully object oriented..

A first language that offers these three core will teach a lot about program flow, syntax, and how to do problem solving in a more structured manner.  I live and breath inside a bunch of great languages that dont't have these attributes but if I were teaching someone a language I would pick one that had these three requirements.


问:
Designing a database with circular references for the-one-of-many case
Consider the following case: there are two models Image and User. Users have associated images and they can pick one of them as their profile image. There are essentially two ways of modeling this:

1)

```<code>User:
   id - primary key
   profile_image - nullable foreign key to Image

Image:
   id - primary key
   user - foreign key to User
</code>```

2)

```<code>User:
   id - primary key

Image:
   id - primary key
   user - foreign key to User
   profile - boolean true/false
</code>```

Both of these approaches have some problems.

In the first case:

well-known chicken-egg problem (e.g. foreign keys must be off when recovering from backup)

It can happen that profile image points outside of domain of images associated with user

There is a redundant dependency link (i.e. one more relation when compared to the first solution). That will have some impact on an application code

What if we later decide to have an ordering on images where the first one is the profile one?

The second case:

There is slight data redundancy (many times false)

true can occur more than once

slightly less intuitive (at least for me)

So my question is, which of these two solutions is better/cleaner?

答:
In the end it is an easy thing. The first case (the circular reference case) breaks separation of code in an application. Because being profile image is a feature of relationship between user and profile. It is not a separate relationship and it should not be modelled as such because doing so is hard overkill. If you do so, you get the uniqueness but at crazy price. The code is going more tightly-coupled, possibly slower and slightly duplicated at some points.

The uniqueness of the non-circular solution can be handled by partial unique index (user, profile=True). This index also makes things fast. In fact a simple lookup of user's profile image by (user_id, True) is going to be as fast and maybe even faster (cause the index is smaller) than lookup by image.id.

As a final argument, imagine that you want fetch all profile images. In the first case, you necessarily need to join with users. In the second case, you don't need to.


问:
Is it acceptable to use C11 generic macros in Objective-C to box numbers?
I was getting tired of repeating types when writing things like this:

```<code>NSDictionary* d = @{@"so": [NSNumber numberWithInt:index]),
                    @"much": [NSNumber numberWithBool:accepted]),
                    @"repeat": [NSNumber numberWithDouble:height]};
</code>```

So I defined a generic macro (a new feature in C11):

```<code>#define box(X) _Generic((X), \
char: boxChar, \
unsigned char: boxUnsignedChar, \
short: boxShort, \
unsigned short: boxUnsignedShort, \
int: boxInt, \
unsigned int: boxUnsignedInt, \
long: boxLong, \
unsigned long: boxUnsignedLong, \
long long: boxLongLong, \
unsigned long long: boxUnsignedLongLong, \
float: boxFloat, \
double: boxDouble, \
BOOL: boxBool \
)(X)

... implement type-specific box methods as well ...
</code>```

So that I could write things like this:

```<code>NSDictionary* d = @{@"so": box(index),
                    @"much": box(accepted),
                    @"shorter": box(height)};
</code>```

Is this a good idea? Can I expect others to be able to build the code? Will they hate it for not being standard?

答:
Self-answer: I didn't realize there's actually a standard syntax to do this. I'd tried @variable before, but actually I was supposed to use @(variable).

Which means that the answer to the question is: yes, they would hate it. But what exists is better anyways.


答:
What you are doing is already provided by Objective-C called Boxed Expressions

with example taken from llvm website

```<code>// numbers.
NSNumber *smallestInt = @(-INT_MAX - 1);  // [NSNumber numberWithInt:(-INT_MAX - 1)]
NSNumber *piOverTwo = @(M_PI / 2);        // [NSNumber numberWithDouble:(M_PI / 2)]

// enumerated types.
typedef enum { Red, Green, Blue } Color;
NSNumber *favoriteColor = @(Green);       // [NSNumber numberWithInt:((int)Green)]

// strings.
NSString *path = @(getenv("PATH"));       // [NSString stringWithUTF8String:(getenv("PATH"))]
NSArray *pathComponents = [path componentsSeparatedByString:@":"];
</code>```

Title: Is it acceptable to use C11 generic macros in Objective-C to box numbers?

Body:
I was getting tired of repeating types when writing things like this:

```<code>NSDictionary* d = @{@"so": [NSNumber numberWithInt:index]),
                    @"much": [NSNumber numberWithBool:accepted]),
                    @"repeat": [NSNumber numberWithDouble:height]};
</code>```

So I defined a generic macro (a new feature in C11):

```<code>#define box(X) _Generic((X), \
char: boxChar, \
unsigned char: boxUnsignedChar, \
short: boxShort, \
unsigned short: boxUnsignedShort, \
int: boxInt, \
unsigned int: boxUnsignedInt, \
long: boxLong, \
unsigned long: boxUnsignedLong, \
long long: boxLongLong, \
unsigned long long: boxUnsignedLongLong, \
float: boxFloat, \
double: boxDouble, \
BOOL: boxBool \
)(X)

... implement type-specific box methods as well ...
</code>```

So that I could write things like this:

```<code>NSDictionary* d = @{@"so": box(index),
                    @"much": box(accepted),
                    @"shorter": box(height)};
</code>```

Is this a good idea? Can I expect others to be able to build the code? Will they hate it for not being standard?

Body:
What you are doing is already provided by Objective-C called Boxed Expressions

with example taken from llvm website

// numbers.
NSNumber *smallestInt = @(-INT_MAX - 1);  // [NSNumber numberWithInt:(-INT_MAX - 1)]
NSNumber *piOverTwo = @(M_PI / 2);        // [NSNumber numberWithDouble:(M_PI / 2)]

// enumerated types.
typedef enum { Red, Green, Blue } Color;
NSNumber *favoriteColor = @(Green);       // [NSNumber numberWithInt:((int)Green)]

// strings.
NSString *path = @(getenv("PATH"));       // [NSString stringWithUTF8String:(getenv("PATH"))]
NSArray *pathComponents = [path componentsSeparatedByString:@":"];


问:
Approach to develop an inline editor for enumerated lists

Background

Looking to develop a WYSIWYG editor for ordered lists so that people can directly edit lists of instructions on a web page.

Problem

The contentEditable attribute is woefully immature for editing ordered lists (e.g.,
...
). I discovered four bugs in Firefox 25.0.1 within seconds of editing; Chromium was acceptable; IE8+ will likely border on nightmarish.

A number of inline editors exist, and I've gone through almost all of them. Even the lightest-weight editors are far too heavy, or have too many bugs, for accomplishing such a seemingly simple task.

Question

What approach would you take to developing a browser-based WYSIWYG inline editor for enumerated lists? Some of my ideas have included:

Take the most robust inline editor and trim back all needless functionality.

Build up an inline editor that meets my needs.

Both approaches will be time-consuming.

What other approaches are worth considering?

答:
This is the leanest inline example list editor example I could produce. The list item has a span with the value. The reason for the span is that the value needs to be hidden while the input is used for editing. Hope this helps. Mike.</p>

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>InlineListEditor</title>
<style>
  .editing {
    display: none;
  }
</style>
</head>
<body>
  <ul class="editable-list">
    <li class="item"><span class="value">one</span></li>
    <li class="item"><span class="value">two</span></li>
  </ul>
<script>
  console.log('loading');
  function editView (value,callBack) {
    var div = document.createElement('div'),
        input = document.createElement('input'),
        value = value;

    input.addEventListener('keydown', function (event) {
      if (event.keyCode === 13) {
        value = this.value;
        this.parentElement.removeChild(this);
        callBack.call(null,[value]);
      }
    });
    input.setAttribute('type',"text");
    input.value = value;
    div.appendChild(input);
    return div;

  }
  function dblClick (event) {
    var element = event.srcElement.parentElement,
        value,
        edit;
    if (element.tagName === "LI") {
      value = element.getElementsByClassName('value')[0];
      value.classList.toggle('editing');
      edit = editView(value.innerHTML,function (text) {
        value.innerHTML = text;
        value.classList.toggle('editing');
      });

      element.appendChild(edit);
    }
    console.dir(event.srcElement);
  }

  var el = document.getElementsByClassName('editable-list')[0];
  el.addEventListener('dblclick',dblClick,false);

 </script>
 </body>
 </html>
</code>```

Body:
This is the leanest inline example list editor example I could produce. The list item has a span with the value. The reason for the span is that the value needs to be hidden while the input is used for editing. Hope this helps. Mike.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>InlineListEditor</title>
<style>
  .editing {
    display: none;
  }
</style>
</head>
<body>
  <ul class="editable-list">
    <li class="item"><span class="value">one</span></li>
    <li class="item"><span class="value">two</span></li>
  </ul>
<script>
  console.log('loading');
  function editView (value,callBack) {
    var div = document.createElement('div'),
        input = document.createElement('input'),
        value = value;

    input.addEventListener('keydown', function (event) {
      if (event.keyCode === 13) {
        value = this.value;
        this.parentElement.removeChild(this);
        callBack.call(null,[value]);
      }
    });
    input.setAttribute('type',"text");
    input.value = value;
    div.appendChild(input);
    return div;

  }
  function dblClick (event) {
    var element = event.srcElement.parentElement,
        value,
        edit;
    if (element.tagName === "LI") {
      value = element.getElementsByClassName('value')[0];
      value.classList.toggle('editing');
      edit = editView(value.innerHTML,function (text) {
        value.innerHTML = text;
        value.classList.toggle('editing');
      });

      element.appendChild(edit);
    }
    console.dir(event.srcElement);
  }

  var el = document.getElementsByClassName('editable-list')[0];
  el.addEventListener('dblclick',dblClick,false);

 </script>
 </body>
 </html>


问:
What's wrong with circular references?
I was involved in a programming discussion today where I made some statements that basically assumed axiomatically that circular references (between modules, classes, whatever) are generally bad.  Once I got through with my pitch, my coworker asked, "what's wrong with circular references?"

I've got strong feelings on this, but it's hard for me to verbalize concisely and concretely.  Any explanation that I may come up with tends to rely on other items that I too consider axioms ("can't use in isolation, so can't test", "unknown/undefined behavior as state mutates in the participating objects", etc.), but I'd love to hear a concise reason for why circular references are bad that don't take the kinds of leaps of faith that my own brain does, having spent many hours over the years untangling them to understand, fix, and extend various bits of code.

Edit: I am not asking about homogenous circular references, like those in a doubly-linked list or pointer-to-parent.  This question is really asking about "larger scope" circular references, like libA calling libB which calls back to libA.  Substitute 'module' for 'lib' if you like.  Thanks for all of the answers so far!

答:
I'll take this question from modelling point of view.

As long as you don't add any relationships that aren't actually there, you are safe. If you do add them, you get less integrity in data (cause there is a redundancy) and more tightly coupled code.

The thing with the circular references specifically is that I haven't seen a case where they would be actually needed except one - self reference. If you model trees or graphs, you need that and it is perfectly all right because self-reference is harmless from the code-quality point of view (no dependency added).

I believe that at the moment you start to need a not-self reference, immediately you should ask if you can't model it as a graph (collapse the multiple entities into one - node). Maybe there is a case in between where you make a circular reference but modelling it as graph is not appropriate but I highly doubt that.

There is a danger that people think that they need a circular reference but in fact they don't. The most common case is "The-one-of-many case". For instance, you have got a customer with multiple addresses from which one should be marked as the primary address. It is very tempting to model this situation as two separate relationships has_address and is_primary_address_of but it is not correct. The reason is that being the primary address is not a separate relationship between users and addresses but instead it is an attribute of the relationship has address. Why is that? Because its domain is limited to the user's addresses and not to all the addresses there are. You pick one of the links and mark it as the strongest (primary).

(Going to talk about databases now) Many people opt for the two-relationships solution because they understand to "primary" as being a unique pointer and a foreign key is kind of a pointer. So foreign key should be the thing to use, right? Wrong. Foreign keys represent relationships but "primary" is not a relationship. It is a degenerated case of an ordering where one element is above all and the rest is not ordered. If you needed to model a total ordering you would of course consider it as a relationship's attribute because there is basically no other choice. But at the moment you degenerate it, there is a choice and quite a horrible one - to model something that is not a relationship as a relationship. So here it comes - relationship redundancy which is certainly not something to be underestimated. The uniqueness requirement should be imposed in another way, for instance by unique partial indexes.

So, I wouldn't allow a circular reference to occur unless it is absolutely clear that it comes from the thing I am modelling.

(note: this is slightly biased to database design but I would bet it is fairly applicable to other areas too)

Title: What's wrong with circular references?


问:
How to improve your ability to debug existing code
A common task in the working world is dealing with existing, but buggy code. What are some tips to improve your skills as a debugger?</p>

答:
Check out the very valuable book Why Programs Fail: A Guide to Systematic Debugging, by Andreas Zeller. It will introduce you to many techniques, theories, and tools, some of which are on the cutting edge of research.

The slides for the book are available online, but I find the book itself is easier to read.

The book will help get you started and make you think more scientifically about debugging, but it's no substitute for practice. You may need to be writing and debugging for 10 years before you see an order of magnitude improvement in your performance. I still remember having my jaw drop at Sun seeing senior developers, who have been programming for Unix for 30 years, find obscure multithreading or parallel bugs in minutes. Experience matters!


问:
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>

答:
What kind of problems may I face, if I won't use Software Design Patterns?

You'll have the problem of not being able to write any software.

Variables are a design pattern.

Methods are a design pattern.

Operators -- addition, subtraction, etc -- are a design pattern.

Statements are a design pattern.

Values are a design pattern.

References are a design pattern.

Expressions are a design pattern.

Classes are a design pattern.

...

Everything you do in programming at all times is a design pattern. Most of the time the pattern is so ingrained into your thinking that you've stopped thinking of it as "a design pattern". The things that you have to learn like "the singleton pattern" and so on are simply patterns that haven't (yet) been baked into whatever language you're using.

Can you tell me about the problems of approaching the design using standard object-oriented techniques?

No. I have no idea what this question means. Design patterns are "standard object-oriented techniques" -- that's what makes them design patterns. A design pattern is a standard technique for solving a particular problem, particularly (though not necessarily) in an object-oriented language.


答: The main problem you'll face is that you will be reinventing the wheel. They are called patterns because they appear often and in a predictable manner.


答:
Even if you follow the design patterns you might end up with a bad design.
Design patterns are natural and you will end up using some flavour of it in your design. You will have to try really hard not to use any of the patterns.
There is not reason to condemn design patterns, whats more important is to pick the right patterns for your needs</p>


问:
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

答:
I personally believe you can have a talent for both but....
any person claiming they are actually good in both fields I would seriously question his or her professionalism. The amount of work and dedication it takes to be good at one field...it just doesnt add for me.

Now if that person is claiming they're decent at both fields, sure I can believe that. But then again, why would you want to be just decent in programming and graphic design?


问:
How to queue work orders by date and priority?
In my organization I work on orders based on date, so earliest work orders first. We also have an option for order to be marked "priority" in which case those orders are done first but not always.

I've asked my boss some questions and I couldn't get answer that made sense...

If one order has today's date, and another order has tomorrows date but is marked priority, which order should I work on first? He said the order marked "priority".

If one order has today's date, and another order is dated 14 days from today and is marked priority, which order should I work on first? He said the one that has today's date.

So the problem is properly placing the order in queue, but it's not something they have an exact formula for.

If I was to make a class that only has two properties...

```<code>public class WorkOrder
{
    public DateTime dueDate;
    public bool isPriority;
}
</code>```

What would be the most straightforward way to put them in queue?

答:
As the priority marker doesn't always shift the items to the very front of the queue, you first need to find out by how many days the 'effective due date' shifts for priority items (my guess is that this would be somewhere between 2 and 5 days).

Once you have that information, you can have a class with three properties:

```<code>public class WorkOrder {
    public DateTime dueDate; // The real due date
    public bool isPriority;
    public DateTime effectiveDueData; // The due date adjusted for priority
}
</code>```

This class can then be stored in a Priority Queue, where the items are first ordered on effectiveDueDate and (if for the same day) isPriority, so the priority items for a given effective due date are handled first.

Body:
As the priority marker doesn't always shift the items to the very front of the queue, you first need to find out by how many days the 'effective due date' shifts for priority items (my guess is that this would be somewhere between 2 and 5 days).

Once you have that information, you can have a class with three properties:

public class WorkOrder {
    public DateTime dueDate; // The real due date
    public bool isPriority;
    public DateTime effectiveDueData; // The due date adjusted for priority
}

This class can then be stored in a Priority Queue, where the items are first ordered on effectiveDueDate and (if for the same day) isPriority, so the priority items for a given effective due date are handled first.


答:
What is the scope and lifetime of the data that you are putting into this list? Does it need to live for the entire lifetime of an instance of awesomeClass?

Are you trying to avoid re-generating the list frequently - i.e. there is value in caching the data in individual instances? Or are you just being lazy and wanting to declare all your variables in the class definition?

Lets make our theoretical member more tangible:

```<code>// 2Kb+ structure
struct Data {
    char m_vendorString[1024];
    char m_productString[1024];
    uint32_t m_vendorId;
    uint32_t m_productTypeId;
    uint32_t m_productId;
};
</code>```

Lets try a few variations of how we might encapsulate an interface that we would retrieve large numbers of this large object from, in the form of pulling them from a database:

```<code>class DatabaseA1 {
    std::vector<Data> m_productQuery;
    std::vector<Data> m_vendorQuery;
public:
    // .. various functions
    const std::vector<Data>& getVendorProducts(uint32_t vendorId);
    const std::vector<Data>& getProductVendors(uint32_t productTypeId);
};

class DatabaseA2 {
    std::vector<Data> m_results;
public:
    // .. various functions
    const std::vector<Data>& getVendorProducts(uint32_t vendorId);
    const std::vector<Data>& getProductVendors(uint32_t productTypeId);
};

class DatabaseB {
public:
    // .. various functions
    std::vector<Data> getVendorProducts(uint32_t vendorId);
    std::vector<Data> getProductVendors(uint32_t productTypeId);
};

class DatabaseC {
public:
    // .. various functions
    bool getVendorProducts(std::vector<Data>& into, uint32_t vendorId);
    bool getProductVendors(std::vector<Data>& into, uint32_t productTypeId);
};
</code>```

Consider that we do something like the following pseudo-code:

```<code>Database db(parameters);

for (possibly hours or days) {
    // get user input
    if (option == GetVendorProducts)
        getVendorProducts(id);
    else if (option == GetProductVendors)
        getProductVendors(id);
    else ...
    doOtherStuff();
}
</code>```

Lets say the result sets contain a few thousand Data items - so a few Mb of data.

That data is going to persist until it goes out of scope or until you call something to release it.

In the case of A1 you're going to have this problem for each query type - if you don't provide a mechanism to release the vectors, and someone queries products and then vendors, you're going to have 2x the number of Mbs of memory used. In the case of A2, you have forced yourself to retain information about what data you are keeping.

For A1 and A2 you're going to have to add an accessor that will tell the member(s) to release their memory, which is fiddly and increases the footprint of your API.

In the case of B, the compiler can use return value optimization (RVO) to make this efficient.

In the case of C, you avoid dependency on RVO and make it much easier to robustly re-use a vector that the end user provides.

There are times when a pattern like A1 or A2 are called for, if you conceivably might have to re-build the data a lot of times, and if your objects themselves actually depend on the data (which is not the same thing as merely having a lot of helper functions that can work with the data).

One example, of course, would be if you are specifically trying to encapsulate a set of data behind an abstraction, e.g.

```<code>class DatabaseResults {
    DatabaseQueryType m_queryType;
    std::string m_srcQuery;
    std::vector<Data> m_results;
public:
    bool populateResults(DatabaseQueryType queryType, std::string srcQuery);
    const std::vector<Data>& getResults() const { return m_results; }
};
</code>```

What is the result sets relationship to the rest of our class? If it is solely an output then we probably don't want it in the class. If we return a reference to it, what promises do we make to callers about it's lifetime.

```<code>class Fnar {
    std::list<ImportantThings> m_list;
public:
    void makeAList();
    std::list<ImportantThings>& getThings() { return m_list; }
    void mowLawn() {
         if (m_list.empty())
             crashHorribly();
         m_list.clear();
         std::cout << "lawn mowed\n";
    }
};

Fnar fnar;
fnar.makeAList();
auto& list = fnar.getThings();

// either
list.clear(); // take that, fnar.
list.mowLawn(); // horrible crash happens here.

// or
list.mowLawn(); // horrible crash happens here.
for (auto& it: list) {
    std::cout << it << "\n";
}
</code>```

Neither of those two cases works right.

If fnar never uses the list itself, then we really ought to hoist the list out and let the caller own it. If there is some other value to our retaining the list - perhaps we are persisting some concept of ownership on some down-stream data we used to build the list - then there is value in having the list in-class and providing callers with a const-only view of it:

```<code>    const std::list<ImportantThings>& getThings() const { return m_list; }
</code>```

Try to avoid empire building in classes - it's easy to throw everything into the instance so that in the debugger you can see every variable that's been used in reaching the current state or you need to serialize them later and retain all of that state.

If you don't, then only own what you absolutely need to. It'll make the code simpler and it'll help localize resources which will make their role in the code easier to understand.

Title: Better style for member variables?

Body:
```<code>class awesomeClass {
    std::list<A> myList;
    //...
    void fillList();
};

awesomeClass::awesomeClass() {
    fillList();
}

void awesomeClass::fillList(){
    //...
    foreach(A a, otherList)
        myList.push_back(a); //add to list
}
</code>```

Compared to :

```<code>awesomeClass::awesomeClass() {
    myList = fillList();
}

std::list<A>& awesomeClass::fillList() {
    //...
    std::list<A> ret;
    foreach(A a, otherList)
        ret.push_back(a); //add to list
    return ret;
}
</code>```

This is just a class with an std::list as a member variable and a function which fills this list. The first fills it inside the function and the second one returns a list and assigns it to the member list.

Which of these is better style? The one which fills the list inside the function or the one which returns a list? Or is there an even better solution?

Body:
What is the scope and lifetime of the data that you are putting into this list? Does it need to live for the entire lifetime of an instance of awesomeClass?

Are you trying to avoid re-generating the list frequently - i.e. there is value in caching the data in individual instances? Or are you just being lazy and wanting to declare all your variables in the class definition?

Lets make our theoretical member more tangible:

// 2Kb+ structure
struct Data {
    char m_vendorString[1024];
    char m_productString[1024];
    uint32_t m_vendorId;
    uint32_t m_productTypeId;
    uint32_t m_productId;
};

Lets try a few variations of how we might encapsulate an interface that we would retrieve large numbers of this large object from, in the form of pulling them from a database:

class DatabaseA1 {
    std::vector<Data> m_productQuery;
    std::vector<Data> m_vendorQuery;
public:
    // .. various functions
    const std::vector<Data>& getVendorProducts(uint32_t vendorId);
    const std::vector<Data>& getProductVendors(uint32_t productTypeId);
};

class DatabaseA2 {
    std::vector<Data> m_results;
public:
    // .. various functions
    const std::vector<Data>& getVendorProducts(uint32_t vendorId);
    const std::vector<Data>& getProductVendors(uint32_t productTypeId);
};

class DatabaseB {
public:
    // .. various functions
    std::vector<Data> getVendorProducts(uint32_t vendorId);
    std::vector<Data> getProductVendors(uint32_t productTypeId);
};

class DatabaseC {
public:
    // .. various functions
    bool getVendorProducts(std::vector<Data>& into, uint32_t vendorId);
    bool getProductVendors(std::vector<Data>& into, uint32_t productTypeId);
};

Consider that we do something like the following pseudo-code:

Database db(parameters);

for (possibly hours or days) {
    // get user input
    if (option == GetVendorProducts)
        getVendorProducts(id);
    else if (option == GetProductVendors)
        getProductVendors(id);
    else ...
    doOtherStuff();
}

Lets say the result sets contain a few thousand Data items - so a few Mb of data.

That data is going to persist until it goes out of scope or until you call something to release it.

In the case of A1 you're going to have this problem for each query type - if you don't provide a mechanism to release the vectors, and someone queries products and then vendors, you're going to have 2x the number of Mbs of memory used. In the case of A2, you have forced yourself to retain information about what data you are keeping.

For A1 and A2 you're going to have to add an accessor that will tell the member(s) to release their memory, which is fiddly and increases the footprint of your API.

In the case of B, the compiler can use return value optimization (RVO) to make this efficient.

In the case of C, you avoid dependency on RVO and make it much easier to robustly re-use a vector that the end user provides.

There are times when a pattern like A1 or A2 are called for, if you conceivably might have to re-build the data a lot of times, and if your objects themselves actually depend on the data (which is not the same thing as merely having a lot of helper functions that can work with the data).

One example, of course, would be if you are specifically trying to encapsulate a set of data behind an abstraction, e.g.

class DatabaseResults {
    DatabaseQueryType m_queryType;
    std::string m_srcQuery;
    std::vector<Data> m_results;
public:
    bool populateResults(DatabaseQueryType queryType, std::string srcQuery);
    const std::vector<Data>& getResults() const { return m_results; }
};

What is the result sets relationship to the rest of our class? If it is solely an output then we probably don't want it in the class. If we return a reference to it, what promises do we make to callers about it's lifetime.

class Fnar {
    std::list<ImportantThings> m_list;
public:
    void makeAList();
    std::list<ImportantThings>& getThings() { return m_list; }
    void mowLawn() {
         if (m_list.empty())
             crashHorribly();
         m_list.clear();
         std::cout << "lawn mowed\n";
    }
};

Fnar fnar;
fnar.makeAList();
auto& list = fnar.getThings();

// either
list.clear(); // take that, fnar.
list.mowLawn(); // horrible crash happens here.

// or
list.mowLawn(); // horrible crash happens here.
for (auto& it: list) {
    std::cout << it << "\n";
}

Neither of those two cases works right.

If fnar never uses the list itself, then we really ought to hoist the list out and let the caller own it. If there is some other value to our retaining the list - perhaps we are persisting some concept of ownership on some down-stream data we used to build the list - then there is value in having the list in-class and providing callers with a const-only view of it:

    const std::list<ImportantThings>& getThings() const { return m_list; }

Try to avoid empire building in classes - it's easy to throw everything into the instance so that in the debugger you can see every variable that's been used in reaching the current state or you need to serialize them later and retain all of that state.

If you don't, then only own what you absolutely need to. It'll make the code simpler and it'll help localize resources which will make their role in the code easier to understand.


问:
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?

答:
Here is what I have come up with for my solution.

For a start, I'm the only person who can use git properly (ish) so any command line stuff is out of the question, people just want to use github for windows as "it's pretty".

So I have the core code, with themes and everything in one repository, stable in master. When it comes to creating a new project I just copy and paste it (since you can't fork to your own account) into a new repository.

To update it, I can download the master and literally extract it over the top, so all the core files get replaced.

The master has the database file as "_database.php" so doesn't overwrite anything.

To speed up development on the front end, all CSS and JS is on a local CDN and the core calls it with a random number on the end to always fetch a non-cached copy.

I have written a script which get the latest master, extracts it and dumps it over the top of all code running the CMS which is running perfectly!

So thats it, it keeps all the code up to date, and if a client wants a completely different site it can change and not be updated again. All code is in separate repository so they can have their own master and development branches.


答: You're using design patterns all the time without realizing it. A lot of standard libraries in popular languages are designed with design patterns in mind. An example is Java's FileReader library which is designed using the decorator design pattern. Now talking about your own code, you're not forced to use design patterns (in most cases). A design pattern is a "reusable solution to a commonly occurring problem", meaning it will help you with writing cleaner more maintainable code so it's really up to you how much you want to avoid ending up with spaghetti code.


问:
Design for syncing data in Android
I have been seeing two implementations for syncing data between the server and the client on majority of the apps. This assumes no GCM is set up:-

Running an intent service periodically which downloads the data from the network and stores in the database.

Implementing a Sync Adapter which runs periodically.

Which of the above would you recommend to have in your app and why?

答:
When it comes to synching data which involves connectivity you'd want to be able to scale also. I believe the recommended way to go about it is using the Sync Adapter.

It also seems to be that way if you check out the Android traning guide: Creating a Sync Adapter

The sync adapter component in your app encapsulates the code for the tasks that transfer data between the device and a server. Based on the scheduling and triggers you provide in your app, the sync adapter framework runs the code in the sync adapter component...

Title: Design for syncing data in Android


问:
Best practices for using HTTP sessions(Java)
My Question is not about how to use HTTP session or how values are being used in session. Question is more oriented about approach.

In my current application there are few values being stored in the Session and we require those values every now and than, here are few values we fetching from session

Store

Language

Customer

few others

I can fetch these values from session like

```<code>request.getSession().getAttribute( "name" )
</code>```

I need those values not directly in my Controller, but in other layer (say Facade) so I have 2 options

Pass each required values to Facade method by  request.getSession().getAttribute( "name" ).

Create a method in each Facade Class like.

Method in Facade

```<code> private Object getSessionValue(final String key) {
    ServletRequestAttributes reqAttr = (ServletRequestAttributes) RequestContextHolder
                            .currentRequestAttributes();
            return reqAttr.getRequest().getAttribute(key);
}
</code>```

Though both are working find in my case, but with one exception, I need to have this method on each Facade Class or need to fetch each object in Controller.

Is there any other way or approach which might be more clean or my current approach is fine

答:
My personal approach would be not to use the session everywhere. I'd try to reduce its usage at the controller layer. In the controller I'd extract what I need for my business logic and the later will never know that there is a web session involved. This will make that logic portable to non-web applications, and will work with all its data in a type-safe manner that is free of boilerplate code.

If you want to avoid the boilerplate code of obtaining the request, then the session, and then the items from the session, your method approach is fine enough, and a common practice in my experience. If you are using it in Java, you can improve it a little by adding some generics:

```<code> public static <T> T getSessionValue(final String key) {
    ServletRequestAttributes reqAttr = (ServletRequestAttributes) RequestContextHolder
                        .currentRequestAttributes();
        return (T) reqAttr.getRequest().getAttribute(key);
}
</code>```

You can use it now like this:

```<code>Integer someSessionInt = SessionUtils.<Integer>getSessionValue("someSessionIntKey");
</code>```

I am assuming the method is defined in a static SessionUtils class. If you define it in a base controller class, want to use this from inside of a controller, you should call it this way:

```<code>Integer someSessionInt = this.<Integer>getSessionValue("someSessionIntKey");
</code>```

The this keyword can be substituted with super, but without it a compile error would occur due to the generics.

In addition to my suggestion above, there is another way of hiding the session usage and have a session-free and independent API/facade. By sticking to the programming-to-interfaces paradigm you can have interface implementations that use the session, but it is never shown by the interfaces you enforce in your facade/api. So, for instance you may have a general purpose authorization service, exposed trough interface, that shows you who is the currently logged user, if s/he is a guest and whether s/he has a particular permission. Your application then could use a concrete implementation of the service interface that gets the user from the session. When you use the service, the interface does not expose anything related to the session, so all usages remain session agnostic, and type safe.

Body:
My personal approach would be not to use the session everywhere. I'd try to reduce its usage at the controller layer. In the controller I'd extract what I need for my business logic and the later will never know that there is a web session involved. This will make that logic portable to non-web applications, and will work with all its data in a type-safe manner that is free of boilerplate code.

If you want to avoid the boilerplate code of obtaining the request, then the session, and then the items from the session, your method approach is fine enough, and a common practice in my experience. If you are using it in Java, you can improve it a little by adding some generics:

 public static <T> T getSessionValue(final String key) {
    ServletRequestAttributes reqAttr = (ServletRequestAttributes) RequestContextHolder
                        .currentRequestAttributes();
        return (T) reqAttr.getRequest().getAttribute(key);
}

You can use it now like this:

Integer someSessionInt = SessionUtils.<Integer>getSessionValue("someSessionIntKey");

I am assuming the method is defined in a static SessionUtils class. If you define it in a base controller class, want to use this from inside of a controller, you should call it this way:

Integer someSessionInt = this.<Integer>getSessionValue("someSessionIntKey");

The this keyword can be substituted with super, but without it a compile error would occur due to the generics.

In addition to my suggestion above, there is another way of hiding the session usage and have a session-free and independent API/facade. By sticking to the programming-to-interfaces paradigm you can have interface implementations that use the session, but it is never shown by the interfaces you enforce in your facade/api. So, for instance you may have a general purpose authorization service, exposed trough interface, that shows you who is the currently logged user, if s/he is a guest and whether s/he has a particular permission. Your application then could use a concrete implementation of the service interface that gets the user from the session. When you use the service, the interface does not expose anything related to the session, so all usages remain session agnostic, and type safe.


答: Circular references in data structures is sometimes the natural way of expressing a data model. Coding-wise, it's definitely not ideal and can be (to some extent) solved by dependency injection, pushing the problem from code to data.</p>

Title: What's wrong with circular references?

Body:
I was involved in a programming discussion today where I made some statements that basically assumed axiomatically that circular references (between modules, classes, whatever) are generally bad.  Once I got through with my pitch, my coworker asked, "what's wrong with circular references?"

I've got strong feelings on this, but it's hard for me to verbalize concisely and concretely.  Any explanation that I may come up with tends to rely on other items that I too consider axioms ("can't use in isolation, so can't test", "unknown/undefined behavior as state mutates in the participating objects", etc.), but I'd love to hear a concise reason for why circular references are bad that don't take the kinds of leaps of faith that my own brain does, having spent many hours over the years untangling them to understand, fix, and extend various bits of code.

Edit: I am not asking about homogenous circular references, like those in a doubly-linked list or pointer-to-parent.  This question is really asking about "larger scope" circular references, like libA calling libB which calls back to libA.  Substitute 'module' for 'lib' if you like.  Thanks for all of the answers so far!


问:
Why do large IT projects tend to fail or have big cost/schedule overruns?
I always read about large scale transformation or integration project that are total or almost total disaster. Even if they somehow manage to succeed  the cost and schedule blow out is enormous. What is the real reason behind large projects being more prone to failure. Can agile be used in these sort of projects or traditional approach is still the best.

One example from Australia is the Queensland Payroll project where they changed test success criteria to deliver the project.

See some more failed projects in this SO question (on Wayback Machine)

Have you got any personal experience to share?

答:
A factor that has been touched on but not addressed yet:

Just about all the dramatic failures are contracts that were bid out.  What happens to a competent company in such a situation?  They make a realistic estimate and thus are almost certainly underbid by someone who made a bad estimate.

If the company can't estimate properly is it surprising they can't build a system properly also?


问:
Is error suppressing bad practice?
On a SO question I asked here about some code I was unsure about, someone replied "BTW, horrible code there: it uses the error suppressing symbol (@) a lot."

Is there a reason why this is bad practice? With things like:

```<code>$db=@new mysqli($db_info) or die('Database error');
</code>```

, it allows me to display just a custom error message. Without error suppressing, then it would still display the typical PHP message of:

Warning: mysqli::mysqli(): php_network_getaddresses: getaddrinfo failed: No such host is known. in some\file\path on line 6

as well as 'Database error'.

Is error suppressing always bad, and if so, what specifically about the above is bad?

Update: the actual code that I'm using is:

```<code>or error('Datatabase error', 'An error occurred with the database' . (($debug_mode) ? '<br />MySQL reported: <b>' . $db->error . '</b><br />Error occurred on line <b>' . __LINE__ . '</b> of <b>' . __FILE__ . '</b>' : ''))
</code>```

which removes all previous output and displays an error message. So the fact that the error message doesn't include details about what specifically happened (which people seem to be suggesting as a reason why error suppressing is bad) is irrelevant.

答:
Yes, the error suppressing operator is generally a bad idea.

You should manage error reporting in the configuration (php.ini). So you can choose a different setting for each environment (for ex. leave warnings in development and hide them in production).

The only situation when using @ could make sense is when you develop a library for other developers. If you voluntarily choose to do something which produces a warning, and don't want to annoy the users of your library with a warning that does not depend on them, @ could be a solution.

I can't think of any other use.

Title: Is error suppressing bad practice?


问:
Find product using summation C# Problem?
I am trying to write a simple program to find the product of two numbers (X, Y) without using multiplication. Meaning that I will only use summation to find the product.

I am trying to use the "Divide-and-Conquer" technique, and am using the obviously known concept that:
5*6 = 5+5+5+5+5+5

```<code>Multiply(uint X, uint Y)
{
    if (Y < 1)
        return 23423432453; //any very big random number

    if (Y == 1)
        sum = sum + X;

    else // if (Y != 1)
    {
        halfY = Y / 2;
        if (Y % 2 == 0) // if Y is even #
            return Multiply(X, halfY);
        else //if Y is odd #
            return Multiply(X, halfY) + Multiply(X, 1);
    }
    return sum;
}
</code>```

EXPLANATION

1) I see the problem as (for example) a 5x6 grid. My idea is to keep recursively dividing the number of columns Y until I reach that Y=1 (Y=1 is the base case). When Y=1, the number of rows in each column would be simply "X" and I can just add X+X+X ... according to the #of columns Y, and save the result in the variable

```<code>sum
</code>```

, then I just return "sum" at the end.

2) In this part of the code,

```<code> else //if Y is odd #
       return Multiply(X, halfY) + Multiply(X, 1);
</code>```

I added "Multiply(X, 1)" to compensate for the "1" that will be lost due to the integer division operation.

----- As an illustration: For example 5*6, where X=5, Y=6:

```<code>                                Multiply(X,Y)                            //Y=6
                          /                       \
               Multiply(X, Y/2)                   Multiply(X, Y/2)       //Y=3, Y=3
             /         |        \               /      \          \
   Mult(X,Y/4) Mult(X,Y/4) Mult(X,1)  Mult(X,Y/4) Mult(X,Y/4) Mult(X,1) //Y=1,1,1,1,1,1
        |           |           |           |            |        |     //BASE CASE!
</code>```

sum=        X    +      X     +     X      +    X       +    X    +   X
   = 5+5+5+5+5+5
   = 30

The code seems pretty logic to me, but it won't give me the right output. Is the idea incorrect? Any help in what is wrong would be greatly appreciated. Thanks.

答:
you didn't go down the right path as you only called Multiply(X, halfY) once; you need to double the result of the recursive call: (x*y = 2*(x*y/2))

```<code>var prod = Multiply(X, halfY);
if (Y % 2 == 0) // if Y is even #
    return prod + prod ;
else //if Y is odd #
    return prod + prod  + X;
</code>```

also the global sum is unneeded just return X at that point:

```<code>if (Y == 1)
    return X;
</code>```

Body:
you didn't go down the right path as you only called Multiply(X, halfY) once; you need to double the result of the recursive call: (x*y = 2*(x*y/2))

var prod = Multiply(X, halfY);
if (Y % 2 == 0) // if Y is even #
    return prod + prod ;
else //if Y is odd #
    return prod + prod  + X;

also the global sum is unneeded just return X at that point:

if (Y == 1)
    return X;


问:
Cyclomatic complexity when calling same method multiple times
Thanks to a question over at Code Review I got into a little disagreement (which essentially is an opportunity to learn something) about what exactly the Cyclomatic Complexity is for the below code.

public static void main(String[] args) {
    try {
        thro();
        thro();
        thro();
        thro();
        thro();
        thro();
        thro();
    }
    catch (NullPointerException e) {
    }
}

private static Random random = new Random();

public static void thro() throws NullPointerException {
    if (random.nextBoolean())
        throw new NullPointerException();
    System.out.println("No crash this time");
}
```

When writing this code in Eclipse and using the Eclipse metrics plugin, it tells me that the McCabe Cyclomatic Complexity for the main method is 2, and for the thro method it says 2.

However, someone else tells me that the complexity of calling thro multiple times is number of calls * method complexity, and therefore claims that the complexity of the main method is 7 * 2 = 14.

Are we measuring different things? Can both of us be correct? Or what is the actual cyclomatic complexity here?

答:
When I understood this correctly, the Cyclomatic Complexity of main is 8 - that is the number of  linearly independent paths through the code. You either get an exception at one of the seven lines, or none, but never more than one. Each of that possible "exception points" corresponds exactly to one different path through the code.

I guess when McCabe invented that metric, he did not have programming languages with exception handling in mind.


答:
Note: Sync adapters run asynchronously, so you should use them with the expectation that they transfer data regularly and efficiently, but not instantaneously. If you need to do real-time data transfer, you should do it in an AsyncTask or an IntentService. - source.

Basically, if you need real time transfer use IntentService (the first option), else SyncAdapter. I prefer an IntentService though because it feels more customizable, but a more trivial approach would be to use a SyncAdapter.

Title: Design for syncing data in Android

Body:
I have been seeing two implementations for syncing data between the server and the client on majority of the apps. This assumes no GCM is set up:-

Running an intent service periodically which downloads the data from the network and stores in the database.

Implementing a Sync Adapter which runs periodically.

Which of the above would you recommend to have in your app and why?


答:
Being 'the other guy', I'll answer here, and be precise about what I say (which I was not particularly precise with over on other formums).

Using the code example above, I calculate the cyclomatic complexity as 8, and I have comments in the code to show how I calculate that. To describe the paths I will consider a successful loop through all the thro() calls as the 'main' 'code path' (or 'CP=1'):

```<code>public static void main(String[] args) {
  try {
             // This is the 'main' Code Path: CP = 1
    thro();  // this has a branch, can succeed CP=1 or throw CP=2
    thro();  // this has a branch, can succeed CP=1 or throw CP=3
    thro();  // this has a branch, can succeed CP=1 or throw CP=4
    thro();  // this has a branch, can succeed CP=1 or throw CP=5
    thro();  // this has a branch, can succeed CP=1 or throw CP=6
    thro();  // this has a branch, can succeed CP=1 or throw CP=7
    thro();  // this has a branch, can succeed CP=1 or throw CP=8
  }
  catch (NullPointerException e) {
  }
}
</code>```

So, I count 8 code paths in this main method, which, to me is a Cyclomatic Complexity of 8.

In Java terms, each mechanism for exiting a function counts to it's complexity, so, a method that has a success-state, and, throws, for example, possibly up to 3 exceptions, has 4 documented exit paths.

The complexity of a method which calls such a function, is:

```<code>CC(method) = 1 + sum (methodCallComplexity - 1)
</code>```

I think other things to consider, is that, in my opinion, the catch clause does not contribute to the complexity of the method, the catch is simply the target of a throws branch, and thus a catch block that is the target of multiple throws counts 1 time for each throw, and not just once for everything.

Title: Cyclomatic complexity when calling same method multiple times

Body:
Thanks to a question over at Code Review I got into a little disagreement (which essentially is an opportunity to learn something) about what exactly the Cyclomatic Complexity is for the below code.

public static void main(String[] args) {
    try {
        thro();
        thro();
        thro();
        thro();
        thro();
        thro();
        thro();
    }
    catch (NullPointerException e) {
    }
}

private static Random random = new Random();

public static void thro() throws NullPointerException {
    if (random.nextBoolean())
        throw new NullPointerException();
    System.out.println("No crash this time");
}
```

When writing this code in Eclipse and using the Eclipse metrics plugin, it tells me that the McCabe Cyclomatic Complexity for the main method is 2, and for the thro method it says 2.

However, someone else tells me that the complexity of calling thro multiple times is number of calls * method complexity, and therefore claims that the complexity of the main method is 7 * 2 = 14.

Are we measuring different things? Can both of us be correct? Or what is the actual cyclomatic complexity here?

Body:
Being 'the other guy', I'll answer here, and be precise about what I say (which I was not particularly precise with over on other formums).

Using the code example above, I calculate the cyclomatic complexity as 8, and I have comments in the code to show how I calculate that. To describe the paths I will consider a successful loop through all the thro() calls as the 'main' 'code path' (or 'CP=1'):

public static void main(String[] args) {
  try {
             // This is the 'main' Code Path: CP = 1
    thro();  // this has a branch, can succeed CP=1 or throw CP=2
    thro();  // this has a branch, can succeed CP=1 or throw CP=3
    thro();  // this has a branch, can succeed CP=1 or throw CP=4
    thro();  // this has a branch, can succeed CP=1 or throw CP=5
    thro();  // this has a branch, can succeed CP=1 or throw CP=6
    thro();  // this has a branch, can succeed CP=1 or throw CP=7
    thro();  // this has a branch, can succeed CP=1 or throw CP=8
  }
  catch (NullPointerException e) {
  }
}

So, I count 8 code paths in this main method, which, to me is a Cyclomatic Complexity of 8.

In Java terms, each mechanism for exiting a function counts to it's complexity, so, a method that has a success-state, and, throws, for example, possibly up to 3 exceptions, has 4 documented exit paths.

The complexity of a method which calls such a function, is:

CC(method) = 1 + sum (methodCallComplexity - 1)

I think other things to consider, is that, in my opinion, the catch clause does not contribute to the complexity of the method, the catch is simply the target of a throws branch, and thus a catch block that is the target of multiple throws counts 1 time for each throw, and not just once for everything.