答:
Is there not a way to figure out when a object should be destroyed?

The short answer is no. It is not possible for compilers to figure out at compile time when objects need to be freed, in the general case.

Consider the following pseudo-code:

```<code>def my_function(some_input):
    A = allocate_some_object(some_input)
    B = allocate_other_object(some_input)
    if check_some_condition(A, B):
        return A
    else
        return B
</code>```

In order for the compiler to know whether A or B should be freed after this function returns, it has to know what check_some_condition(A, B) will return. That would require solving the halting problem, which is not possible in the general case.

More seriously, check_some_condition could store a reference to A somewhere else, in which case A is not garbage at the end of the function even if B is returned. The compiler would have to be able to know whether this happens with 100% certainty, and even if it did know you then have to solve the problem of flowing the information around until you find some place where A does become garbage and can be deallocated. That could be in a completely different part of the program.

Plus, deallocating every object as soon as it becomes possible isn't actually always the best option. If objects are being created and dropped all the time, and you have enough memory available, running a garbage collector every so often and deallocating the garbage in bulk can actually be more efficient than hand-tuned C-style manual memory management (despite claims that GC is always a trade off between performance and convenience).

There are techniques that can do some of this, some of the time. Escape analysis can allow the compiler to deduce that a given object cannot "escape" some section of code, so what looks like a heap allocation can be turned into a stack allocation, which is effectively memory managed by the compiler. I've read about other techniques allowing a compiler to tell that a given object must be garbage at the point another object of the same size is created, so instead of compiling an allocation of a new object it re-uses the dead value. But it simply isn't possible to completely replace garbage collection cycles with the compiler figuring out statically when every object needs to be deallocated, because the compiler can only figure that out some of the time.

Title: Is garbage collection necessary?

Body:
Is there not a way to figure out when a object should be destroyed?

The short answer is no. It is not possible for compilers to figure out at compile time when objects need to be freed, in the general case.

Consider the following pseudo-code:

def my_function(some_input):
    A = allocate_some_object(some_input)
    B = allocate_other_object(some_input)
    if check_some_condition(A, B):
        return A
    else
        return B

In order for the compiler to know whether A or B should be freed after this function returns, it has to know what check_some_condition(A, B) will return. That would require solving the halting problem, which is not possible in the general case.

More seriously, check_some_condition could store a reference to A somewhere else, in which case A is not garbage at the end of the function even if B is returned. The compiler would have to be able to know whether this happens with 100% certainty, and even if it did know you then have to solve the problem of flowing the information around until you find some place where A does become garbage and can be deallocated. That could be in a completely different part of the program.

Plus, deallocating every object as soon as it becomes possible isn't actually always the best option. If objects are being created and dropped all the time, and you have enough memory available, running a garbage collector every so often and deallocating the garbage in bulk can actually be more efficient than hand-tuned C-style manual memory management (despite claims that GC is always a trade off between performance and convenience).

There are techniques that can do some of this, some of the time. Escape analysis can allow the compiler to deduce that a given object cannot "escape" some section of code, so what looks like a heap allocation can be turned into a stack allocation, which is effectively memory managed by the compiler. I've read about other techniques allowing a compiler to tell that a given object must be garbage at the point another object of the same size is created, so instead of compiling an allocation of a new object it re-uses the dead value. But it simply isn't possible to completely replace garbage collection cycles with the compiler figuring out statically when every object needs to be deallocated, because the compiler can only figure that out some of the time.


问:
Is It OK to Develop Against a 3rd Party Library You Discover?
If you find out a way to interact with a web service API that is not publicly documented as available, and can emulate it within an application you develop, is it illegal to do so?  Furthermore is it illegal to charge for a product that you build to interact with these services (maybe all that's needed is a reference to the 3rd party)?

An example would be, lets say, Google didn't advertise how to do a search in your program, but you found out how and made it so people could do the search differently than how Google presents it, can you build against the service you discovered and sell a version of it?

答: It's dangerous.  If it's not publicly documented, then they won't have any compunction against breaking backward compatibility, or just breaking it entirely.  It may be relying on undocumented web apis that might disappear tomorrow.</p>

OwnerDisplayName: Benny

ContentLicense: CC BY-SA 3.0


问:
Object-Oriented Design of Car
While I am studying for job interview, I got this kind of OOD questions a lot. But from my TDD perspective, I think it would be reasonable to ask more about use-cases of (or requirements for) the Car. Otherwise, there are tons of way of designing car. Am I missing something here? How would you handle this sort of interview questions?</p>

答:
I'm a little confused about your question.  Why can't you ask questions about use-cases to try to understand the requirements?  If you're asked in an interview to design a car in an object oriented manner, it would be bad not to ask about details.

The point of a question like this is to make sure you understand object oriented design.  I understand that if you're just studying from a book, you can't ask questions about use cases.  In this case, you should map out which questions would be useful to ask, and then practice designing a car class in an object oriented way.  Maybe show them that you understand inheritance ("car" could derive from "vehicle", so that vehicle encompasses motorcycles, cars, etc.)

Title: Object-Oriented Design of Car


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

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

答:
You might have an interest in "Garbage Collection is Fast, but a Stack is Faster".

http://dspace.mit.edu/bitstream/handle/1721.1/6622/AIM-1462.ps.Z

If I read it correctly, these guys modified a C compiler to allocate "stack frames" on the heap, and then use garbage collection to de-allocate the frames instead of popping the stack.

Stack-allocated "stack frames" outperform heap-allocated "stack frames" decisively.


答:
I don't know if the following is going to make any sense, but here goes ...

A car, in a way, could be said to be OODed. Let's start from the designers - the drawing guys, they dream up the overall design. Then it gets to the engineers, who calculate the dimensions of the suspension, the shafts, the engine, the wheels, the rear view mirror ... Since many people work on the design of one model of a car, many people develop 3d models of its parts.

Therefore, a tire-guy can do whatever he wants with the tire, as long as it fits the diameter of the shaft which is passed to him from the shaft-guy. You might think of that part as inheritance.

The shaft guy doesn't at that time know how he's gonna do the shaft. He just knows it's gotta fit to the engine at one side, and it's gotta be round at the other side to fit the tire. Interface.

The shaft guy gets the diameter from the engine guy. He can do whatever he wants with the shaft as long as it fits the diameter. He can make it a half shaft, a full shaft ... information hiding. How the shaft is really interests neither the engine guy nor the tire guy.

Polymorphism can be illustrated on the engine and its subparts.

Title: Object-Oriented Design of Car

Body: While I am studying for job interview, I got this kind of OOD questions a lot. But from my TDD perspective, I think it would be reasonable to ask more about use-cases of (or requirements for) the Car. Otherwise, there are tons of way of designing car. Am I missing something here? How would you handle this sort of interview questions?</p>


答:
if it's an OOD question about designing a car, they're curious about your OO modeling skills - so tell them to model every part of the car that is necessary for the desired functionality.

if it's a racing simulation, it may be the body, engine, tires, and driver

if it's a manufacturing facility, it may be everything!

once they give you a context, then show off your TDD skills by asking about stories and tests (features and use-cases)

Title: Object-Oriented Design of Car


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答:
A large Whiteboard

Very handy for brainstorming and communicating ideas when working with other developers. Don't know if I could live without mine.

BTW: Those tiny velcro attached CUBE white-boards don't cut it.

ContentLicense: CC BY-SA 2.5


问:
Why do languages such as C and C++ not have garbage collection, while Java does?
Well, I know that there are things like malloc/free for C, and new/using-a-destructor for memory management in C++, but I was wondering why there aren't "new updates" to these languages that allow the user to have the option to manually manage memory, or for the system to do it automatically (garbage collection)?

Somewhat of a newb-ish question, but only been in CS for about a year.

答: Because, C & C++ are relatively low level languages meant for general purpose, even, for example, to run on a 16-bit processor with 1MB of memory in an embedded system, which couldn't afford wasting memory with gc.  </p>


答:
You ask why these languages haven't been updated to include an optional garbage collector.

The problem with optional garbage collection is that you can't mix code that uses the different models. That is, if I write code that assumes you are using a garbage collector you can't use it in your program which has garbage collection turned off. If you do, it'll leak everywhere.

Title: Why do languages such as C and C++ not have garbage collection, while Java does?

Body:
Well, I know that there are things like malloc/free for C, and new/using-a-destructor for memory management in C++, but I was wondering why there aren't "new updates" to these languages that allow the user to have the option to manually manage memory, or for the system to do it automatically (garbage collection)?

Somewhat of a newb-ish question, but only been in CS for about a year.


问:
Is garbage collection necessary?
Do any languages really need garbage collection? Is there not a way to figure out when a object should be destroyed? I haven't had leaks in C++ and i dont use smart pointers or reference counters or anything special. I confirm this by attaching something for leak detection: whether its built in to the IDE or a header that uses magic (defines) to overloads new/free.

Is garbage collection necessary, or is it possible to have a leak-free application in a language without placing the memory burden on the programmer?

答:
Do any languages really need garbage collection?

I'm going to stick to only this question (at least for now).

Others have posited that the answer is clearly no, garbage collection is never really needed (just often very convenient). I'm going to go on record as saying they're wrong, or have at least answered a question somewhat different from what was asked.

It's absolutely true that the externally visible behavior of a program written in a language that includes garbage collection can normally be imitated to an arbitrary degree of accuracy with code written in a language that does not include garbage collection.

The original question wasn't about programs though, it was about languages. Addressing that question, the answer is yes, garbage collection really is needed for some languages. Some languages (e.g., Lisp family) have had/used GC for so long that it has become completely fundamental to how that language is used. In theory, a couple of functions (or probably special forms) to allocate and free memory would be trivial to add. In reality, however, much of how most Lisp code is written depends so thoroughly on the presence of GC that if it were removed and the programmer were forced to handle such allocation and freeing manually, the result would be a language almost completely different from Lisp, that just happened to have almost the same syntax.

Title: Is garbage collection necessary?


问:
Should all developers on a team have equal role/responsibility in writing and updating software design documents
I've asked a very similar question few days ago, but because I presented too much of my company's current situation, most answers focused completely on something that I wasn't looking to answer.  So I wanted to try again...

Given just about any agile team, you always have people with varied a) knowledge of the product b) experience in producing designs and c) general level of competence.

So let's say you take an agile team and using the factors (a), (b) and (c) above you come up with an overall score for each engineers (mental exercise only). Now we sort them in ascending order and get a continuous spectrum.

So the question I wanted to ask is this: Should every single person on this spectrum be given equal responsibility as it comes to writing/updating software design specifications?

I'm not talking about coming up with software design, in agile teams that is usually done by more than one person in a more collaborative setting. But at the end of the day, someone has to go back to his desk open their favorite (and company/team approved) document editor and type it all in.

The reason I ask this question is because it seems people on high end of the spectrum tend to produce documents which are more readable, concise but have exactly the information you would want in a design specification so that future people who read it have much more benefit.  People on the opposite side of the spectrum tend to produce documents which are not nearly as useful or clear and a lot of times, even with several iterations of design reviews, their work doesn't seem nearly as helpful (so specs they produce become write only dumping ground that no one reads or trusts because of the way they are written).

I'm not proposing that the agile team be segregated and only certain individuals given certain roles that will never change. I'm asking...
1) what do you do in your teams with people who have vastly different (a)x(b)x(c) scores
2) Does it make sense to not give equal responsibility to everyone. Instead, give only smaller (or none) update tasks to those on the low end of the spectrum.  But then work with these individuals by identifying (a), (b) and (c) factors that they'd need to improve and as those get improved give them more responsibility.

Personally, I'm not sold on one way or another, I'm just curious how other teams are dealing with this.

答:
It is a good thing that you are considering documenting design specs. As you said, if writing is left to individuals, you will get varied levels of quality. One way to help raise the quality and value of this type of documentation is to design template(s) of what should be documented and good examples of what to include and not to include. Then have 1 senior person review the output (much like a code review but with fixed max. number of iterations). It is hard to get homogeneous output without doing this.

Also, please note that some technical people are not skilled in writing at all. Make sure you don't press those people for performing such tasks.
If you have a system with large number of components, most people must help with the documentation. Tasking only few skilled ones will make their development output suffer.


问:
When you should NOT use Regular Expressions?
Regular expressions are powerful tool in programmer's arsenal, but - there are some cases when they are not a best choice, or even outright harmful.

Simple example #1 is parsing HTML with regexp - a known road to numerous bugs. Probably, this also attributes to parsing in general.

But, are there other clearly no-go areas for regular expressions ?

p.s.: "The question you're asking appears subjective and is likely to be closed." - thus, I want to emphasize, that i am interested in examples where usage of regexps is known to cause problems.

答:
On stackoverflow one often sees people ask for regexes that find out whether a given string does not contain this or that. This is, IMHO, reversing the purpose of regular expression. Even if a solution exists (employing negative lookbehind assertions or such stuff), it is often much better to use the regex for what it was made for and handle the negative case with program logic.

Example:

```<code># bad
if (/complicated regex that assures the string does NOT conatin foo|bar/) {
    # do something
}

# appropriate
if (/foo|bar/) {
    # error handling
} else {
    # do something
}
</code>```

Body:
On stackoverflow one often sees people ask for regexes that find out whether a given string does not contain this or that. This is, IMHO, reversing the purpose of regular expression. Even if a solution exists (employing negative lookbehind assertions or such stuff), it is often much better to use the regex for what it was made for and handle the negative case with program logic.

Example:

# bad
if (/complicated regex that assures the string does NOT conatin foo|bar/) {
    # do something
}

# appropriate
if (/foo|bar/) {
    # error handling
} else {
    # do something
}


答:
Don't use regular expressions:

When there are parsers.

This doesn't limit to HTML. A simple valid XML cannot be reasonably parsed with a regular expression, even if you know the schema and you know it will never change.

Don't try, for example, parse C# source code. Parse it instead, to get a meaningful tree structure or the tokens.

More generally, when you have better tools to do your job.

What if you must search for a letter, both small and capital? If you love regular expressions, you'll use them. But isn't it easier/faster/readable to use two searches, one after another? Chances are in most languages you'll achieve better performance and make your code more readable.

For example the sample code in Ingo's answer is a good example when you must not use regular expressions. Just search for foo, then for bar.

When parsing human writing.

A good example is an obscenity filter. Not only it is a bad idea in general to implement it, but you may be tempted to do it using regular expressions, and you'll do it wrong. There are plenty of ways an human can write a word, a number, a sentence and will be understood by another human, but not your regular expression. So instead of catching real obscenity, your regular expression will spend her time hurting other users.

When validating some types of data.

For example, don't validate an e-mail address through a regular expression. In most cases, you'll do it wrong. In a rare case, you'll do it right and finish with a 6 343 characters length coding horror.

When you don't have the right tools or don't care about clean code.

Without the right tools, you will make mistakes. And you will notice them at the last moment, or maybe never. If you don't care about clean code, you'll write a twenty lines string with no comments, no spaces, no newlines.

When your code will be read. And then read again, and again and again, every time by different developers.

Seriously, if I take your code and must review it or modify it, I don't want to spend a week trying to understand a twenty lines long string plenty of symbols.

Title: When you should NOT use Regular Expressions?

Body:
Regular expressions are powerful tool in programmer's arsenal, but - there are some cases when they are not a best choice, or even outright harmful.

Simple example #1 is parsing HTML with regexp - a known road to numerous bugs. Probably, this also attributes to parsing in general.

But, are there other clearly no-go areas for regular expressions ?

p.s.: "The question you're asking appears subjective and is likely to be closed." - thus, I want to emphasize, that i am interested in examples where usage of regexps is known to cause problems.


答:
If it isn't documented it most probably wasn't intended for external use, certainly not by anybody else. It may be a pre-release, it may be experimental, it may simply be something meant for internal use.

I would hesitate long and hard before basing anything on such a service for my own personal use. I would hesitate even longer en harder before basing anything on it and selling that.

The service can be retracted or changed at any moment.

If you just use it for your own personal benefit, that would be a nuisance but nothing more.

If you have sold products based on that service, you have entered into a contract (explicit or implied) with your own clients. When the service is retracted or changed you are in a pickle as you can no longer deliver your side of the deal. Apart from refund claims, you may then have to deal with all kinds of liability claims. That would of course depend on your terms of service / license agreement and limitations of warranty. But keep in mind that exclusion of liability is not allowed everywhere in this world.

In short: don't use the service without asking those that developed the service and entering into a contract with them for the continued delivery of that service.

Title: Is It OK to Develop Against a 3rd Party Library You Discover?

Body:
If you find out a way to interact with a web service API that is not publicly documented as available, and can emulate it within an application you develop, is it illegal to do so?  Furthermore is it illegal to charge for a product that you build to interact with these services (maybe all that's needed is a reference to the 3rd party)?

An example would be, lets say, Google didn't advertise how to do a search in your program, but you found out how and made it so people could do the search differently than how Google presents it, can you build against the service you discovered and sell a version of it?


答:
The most important thing: when the language you are parsing is not a regular language.

HTML is not a regular language and parsing it with a regular expression is not possible (not only difficult or a road to buggy code).


答:
If it is not properly documented, it is not an API. I would recommend not using it as it may change whenever its writer want.

The better would be to contact the owner of this web service and ask him if he wants to make it public.


答: The best thing you could probably do, however I am unclear of your budget is get everyone maximum space and privacy (However these don't go well together). With this in place, programmers can create their own comfortable work environment</p>

Title: Stuff every programmer needs while working

Body:
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed


问:
Prevalence of "back end" programmer roles in ASP.NET (MVC) projects?
First, unless anyone has better definitions, let's define "back end" and "front end" according to their usage here:
Is it common to separate back-end and front-end into two positions on web development projects?.

How common is it to find programmers exclusively assigned to back end or front end roles on a team?  What's the scope of their responsibilities?

答:
In theory, the answers from question you quoted already answer your question. In a startup, it's a bad idea to have an ASP.NET developer who works only on the back end. In a large company, it can be suggested to have a dedicated developer for every task according to the skills of every person.

In practice, I never saw an ASP.NET developer working only on a back end, even on websites large enough. Also (but this is just my personal opinion), ASP.NET does a really bad job when it comes to separating work among people: it's difficult to have a dedicated C# developer and a dedicated HTML/CSS programmer; it's difficult to strictly separate a project into a front-end and a back-end.

Of course, things change when it comes to very large websites. Not only because you can't develop the whole website alone in a reasonable amount of time, but also because you'll lack the required skills or the knowledge of the overall project requirements.


答:
Writing documentation is a shared burden like everything else on an agile team.

Begin by asking your team what kind of documentation they really need, how much of it and how often it must be updated. Then coach them through that discussion keeping agile values in mind. Eventually they should agree and commit to something, and whatever they come up with is probably the correct answer in your case. It is not your place to tell them how they should do it.

It often turns out that the documentation is not used in practice and only exists because of company policies. If you find that you don't need all of it, most of the problem with writing documentation goes away. For instance, deriving knowledge from the code using comments, clean code and unit tests as specification helps a lot.

Title: Should all developers on a team have equal role/responsibility in writing and updating software design documents

Body:
I've asked a very similar question few days ago, but because I presented too much of my company's current situation, most answers focused completely on something that I wasn't looking to answer.  So I wanted to try again...

Given just about any agile team, you always have people with varied a) knowledge of the product b) experience in producing designs and c) general level of competence.

So let's say you take an agile team and using the factors (a), (b) and (c) above you come up with an overall score for each engineers (mental exercise only). Now we sort them in ascending order and get a continuous spectrum.

So the question I wanted to ask is this: Should every single person on this spectrum be given equal responsibility as it comes to writing/updating software design specifications?

I'm not talking about coming up with software design, in agile teams that is usually done by more than one person in a more collaborative setting. But at the end of the day, someone has to go back to his desk open their favorite (and company/team approved) document editor and type it all in.

The reason I ask this question is because it seems people on high end of the spectrum tend to produce documents which are more readable, concise but have exactly the information you would want in a design specification so that future people who read it have much more benefit.  People on the opposite side of the spectrum tend to produce documents which are not nearly as useful or clear and a lot of times, even with several iterations of design reviews, their work doesn't seem nearly as helpful (so specs they produce become write only dumping ground that no one reads or trusts because of the way they are written).

I'm not proposing that the agile team be segregated and only certain individuals given certain roles that will never change. I'm asking...
1) what do you do in your teams with people who have vastly different (a)x(b)x(c) scores
2) Does it make sense to not give equal responsibility to everyone. Instead, give only smaller (or none) update tasks to those on the low end of the spectrum.  But then work with these individuals by identifying (a), (b) and (c) factors that they'd need to improve and as those get improved give them more responsibility.

Personally, I'm not sold on one way or another, I'm just curious how other teams are dealing with this.


答:
Two cases:

When there is an easier way

Most languages provide a simple function like INSTR to determine if one string is a subset of another. If that's what you want to do, use the simpler function. Don't write your own regular expression.

If there is a library available for performing a complex string manipulation, use it rather than writing your own regular expression.

When regular expressions are not sufficiently powerful

If you need a parser, use a parser.


问:
How do document-oriented databases implement references?
In relational world we have Foreign Keys to reference other entities. But how do document-oriented databases like MongoDb, CouchDb, RavenDb implement references among entities?

Update. StackExchange related example. We have Question entity and its tags. Each tag, is a separate entity so it has its properties (for example, description). How can I reference tags for some Question?

答:
Easy; they don't.

If you want join abilities, you have to implement them in your client code.  Some of these APIs do it a little easier by defining a 'Key' type that makes it easy to store and use references, but you have to do a second fetch to get the referenced entity.


答: Latest generation hardware, such as solid-state drives.


问:
What is the difference between btree and rtree indexing?
I've noticed on MySQLWorkbench that you can choose how to store your indexes before forward engineering your design. The storage types are:

BTREE

RTREE

HASH

Researching this, I found some information that was pretty much over my head, so I'm looking for practical information on what the difference is between these and/or why you should choose one over another.

Also, I have never chosen a storage type before, so I assume MySQL is choosing a default storage type (BTREE?)

答:
BTree

BTree (in fact B*Tree) is an efficient ordered key-value map. Meaning:

given the key, a BTree index can quickly find a record,

a BTree can be scanned in order.

it's also easy to fetch all the keys (and records) within a range.

e.g. "all events between 9am and 5pm", "last names starting with 'R'"

RTree

RTree is a spatial index which means that it can quickly identify close values in 2 or more dimensions. It's used in geographic databases for queries such as:

all points within X meters from (x,y)

Hash

Hash is an unordered key-value map. It's even more efficient than a BTree: O(1) instead of O(log n).

But it doesn't have any concept of order so it can't be used for sort operations or to fetch ranges.

As a side note, originally, MySQL only allowed Hash indexes on MEMORY tables; but I'm not sure if that has been changed over the years.

ContentLicense: CC BY-SA 4.0


答:
There is no fixed recipe for documentation; like everything else, it highly depends on the people in a team and their personalities and abilities. Everybody can do their part, or one person can take the task to himself. Anything goes, really. I've had good results with tester writing most of the documentation, but it's maybe the best when an architect/project lead does the documentation. Each programmer doing his part can also work, but some programmers are really bad at this.

The question you should be asking is what's the best way to tackle the problem with your team, not how it should be done in an ideal world. Use people's strengths or strengthen people's abilities if they're bad at something, or even better, do both when you can.


问:
Why declare variables close to where they are used?
I have heard people say that variables should be declared as close to their usage as possible. I don't understand this.

For example, this policy would suggest I should do this:

```<code>foreach (var item in veryLongList) {
  int whereShouldIBeDeclared = item.Id;
  //...
}
</code>```

But surely this means the overheads of creating a new int are incurred on every iteration. Wouldn't it be better to use:

```<code>int whereShouldIBeDeclared;
foreach (var item in veryLongList) {
  whereShouldIBeDeclared = item.Id;
  //...
}
</code>```

Please could somebody explain?

答:
It is not a "must". It's just an opinion, I way to do something. For example, I like to declare all the vars in the first lines of the method so I can comment what I'll do with that vars (of course unless they are counters). Other people, as you heard, like to place them as close to their usage as possible (as in the second example you wrote). Anyway, the first example you provide is surely an "error" (in the sense that it will cause an overhead as you understand).

You have simply to choose your way and follow it.


答:
This is one style rule among many, and it isn't necessarily the most important rule of all the possible rules you could consider. Your example, since it includes an int, isn't super compelling, but you could certainly have an expensive-to-construct object inside that loop, and perhaps a good argument for constructing the object outside the loop. However, that doesn't make it a good argument against this rule since first, there are tons of other places it could apply that don't involve constructing expensive objects in a loop, and second, a good optimizer (and you've tagged C#, so you have a good optimizer) can hoist the initialization out of the loop.

The real reason for this rule is also the reason you don't see why it's a rule. People used to write functions that were hundreds, even thousands of lines long and they used to write them in plain text editors (think Notepad) without the kind of support Visual Studio provided. In that environment, declaring a variable hundreds of lines away from where it was used meant that the person reading

```<code>if (flag) limit += factor;
</code>```

didn't have a lot of clues about what flag, limit and factor were. Naming conventions like Hungarian notation were adopted to help with this, and so were rules like declaring things close to where they are used. Of course, these days, it's all about refactoring, and functions are generally less than a page long, making it hard to get very much distance between where things are declared and where they are used. You're operating in a range of 0-20 and quibbling that maybe 7 is ok in this particular instance, while the guy who made the rule would have LOVED to get 7 lines away and was trying to talk someone down from 700. And on top of that, in Visual Studio, you can mouse over anything and see its type, is it a member variable, and so on. That means the need to see the line declaring it is lessened.

It's still a reasonably good rule, one that's actually quite hard to break these days, and one that no-one ever advocated as a reason to write slow code. Be sensible, above all.

Title: Why declare variables close to where they are used?

Body:
I have heard people say that variables should be declared as close to their usage as possible. I don't understand this.

For example, this policy would suggest I should do this:

```<code>foreach (var item in veryLongList) {
  int whereShouldIBeDeclared = item.Id;
  //...
}
</code>```

But surely this means the overheads of creating a new int are incurred on every iteration. Wouldn't it be better to use:

```<code>int whereShouldIBeDeclared;
foreach (var item in veryLongList) {
  whereShouldIBeDeclared = item.Id;
  //...
}
</code>```

Please could somebody explain?

Body:
This is one style rule among many, and it isn't necessarily the most important rule of all the possible rules you could consider. Your example, since it includes an int, isn't super compelling, but you could certainly have an expensive-to-construct object inside that loop, and perhaps a good argument for constructing the object outside the loop. However, that doesn't make it a good argument against this rule since first, there are tons of other places it could apply that don't involve constructing expensive objects in a loop, and second, a good optimizer (and you've tagged C#, so you have a good optimizer) can hoist the initialization out of the loop.

The real reason for this rule is also the reason you don't see why it's a rule. People used to write functions that were hundreds, even thousands of lines long and they used to write them in plain text editors (think Notepad) without the kind of support Visual Studio provided. In that environment, declaring a variable hundreds of lines away from where it was used meant that the person reading

if (flag) limit += factor;

didn't have a lot of clues about what flag, limit and factor were. Naming conventions like Hungarian notation were adopted to help with this, and so were rules like declaring things close to where they are used. Of course, these days, it's all about refactoring, and functions are generally less than a page long, making it hard to get very much distance between where things are declared and where they are used. You're operating in a range of 0-20 and quibbling that maybe 7 is ok in this particular instance, while the guy who made the rule would have LOVED to get 7 lines away and was trying to talk someone down from 700. And on top of that, in Visual Studio, you can mouse over anything and see its type, is it a member variable, and so on. That means the need to see the line declaring it is lessened.

It's still a reasonably good rule, one that's actually quite hard to break these days, and one that no-one ever advocated as a reason to write slow code. Be sensible, above all.


答:
You can do the same thing as in RMDBs, you reference by identifiers. I use MongoDB, so we can talk about this from that point.

Tag:

```<code>{
  _id: ObjectId('tag id'),
  tag_name: "nosql",
  tag_description: "blahblah'
}
</code>```

Then in the Post

```<code>{
  _id: ObjectId('post id'),
  tags: [
    ObjectId('tag1 id'),
    ObjectId('tag2 id')
  ],
  title: "title",
  // etc..
}
</code>```

When you load a Post object you can either pull your tags documents as well, or you can pull them from cache. Often you use a ODM (instead of ORM) and it can often handle these references for you. For example, in Mongoid for Rails, you would just say :has_many :tags and it would figure out the rest for you. When you call post.tags it would just return an array of the tags associated with post.

Title: How do document-oriented databases implement references?

Body:
In relational world we have Foreign Keys to reference other entities. But how do document-oriented databases like MongoDb, CouchDb, RavenDb implement references among entities?

Update. StackExchange related example. We have Question entity and its tags. Each tag, is a separate entity so it has its properties (for example, description). How can I reference tags for some Question?

Body:
You can do the same thing as in RMDBs, you reference by identifiers. I use MongoDB, so we can talk about this from that point.

Tag:

{
  _id: ObjectId('tag id'),
  tag_name: "nosql",
  tag_description: "blahblah'
}

Then in the Post

{
  _id: ObjectId('post id'),
  tags: [
    ObjectId('tag1 id'),
    ObjectId('tag2 id')
  ],
  title: "title",
  // etc..
}

When you load a Post object you can either pull your tags documents as well, or you can pull them from cache. Often you use a ODM (instead of ORM) and it can often handle these references for you. For example, in Mongoid for Rails, you would just say :has_many :tags and it would figure out the rest for you. When you call post.tags it would just return an array of the tags associated with post.


答: People say as close to their usage as possible , They are not saying you should have to do that all the time,because they are some cases declaring variables in least scope will cause some overhead .The main reasons of that statement are Readability and giving variables the smallest scope you can .


答: Your two examples are functionally different code, they're not interchangeable. (Your stripped down examples leave it a distinction without a difference, but in non-trivial code it does make a difference).  The rule you site is always subordinate to scoping considerations, as indicated by "...as possible".</p>


答:
Yes

Let me answer with a counter-question:  If there was a component of the system that was particularly suited to one developer's skillset, should the team's preference be that she is the only one that works on it?  In an agile team, almost certainly not.  One of the goals of the "agile process" is to share and distribute knowledge.  If those that are bad at writing design docs don't get practice and feedback, how will they improve?

Build maintenance, writing code, compiling, design docs, debugging, testing are all parts of the software developer role in nearly every organization.  If you have a long-term interest in investing in the members of your team then you should look at improving the weaker skills, possibly by pairing them with a mentor with a strength in that skill.  It's difficult to improve without practice.

Whether or not design docs are important to an agile team is besides the point.  If a developer cannot communicate a design well, then he can't communicate well.  I've worked on teams where team members couldn't use svn.  I've worked on teams where only one person knew how to format a config file.  I personally think Microsoft Word is intentionally designed to work in direct opposition to the way I think about writing documents.  It doesn't matter.  If that's the tool my team uses, then I have to adapt to that environment to work effectively in a team.  (That's not to say there aren't ways to change the environment, but that's a different discussion).


答:
Defining the variable inside the loop makes it visibility local to that loop only. This has at least 3 advantages for the reader:

The variable definition and any related comments are easy to find

The reader knows that this variable is never used else where (no
dependency to expect)

When the code is written or edited, there is no chance that you could use the same variable name outside the loop to refer to that variable otherwise, you could get in error.

As for the efficiency bit, the compiler is smart to generate the definition outside of the loop in the optimized code generated. The variable will not be created every loop iteration.


答: a computer, a mouse, a keyboard, and a monitor, a REALLY nice chair. oh, and google.</p>


答: If you do this, you're giving that site operator control over some behavior of your app. If they're not happy with you doing it, they might change the code to return results you wouldn't want to expose your customers to, depending on how they're using it themselves.  This isn't quite the same, but similar enough to serve as a warning:  I once discovered an eBay seller hotlinking some of my old photos, and boy was his face red when he pulled up his auctions one day and found hard-core porn on them. </p>


问:
What is the name for this variation to Adapter Pattern?

Introduction

An Adapter normally wraps another object, so that it can be used in an interface it wasn't designed for, e.g., when you want to use

```<code>interface Node {
    Node parent();
    Iterable<Node> children();
}
</code>```

together with

```<code>class TreeModel {
    private Node root;
    // example method (stupid)
    Node grandparent(Node node) {
        return node.parent().parent();
    }
}
</code>```

and you're given a class like

```<code>class File {
    File getParent() {...}
    File[] listFiles() {...}
}
</code>```

you need to write some FileToNodeAdapter.

Unfortunately, it means that you need to wrap each single object and you also need both a way to get from FileToNodeAdapter to File (which is trivial, since it's embedded), but also from File to FileToNodeAdapter, which leads either to creating a new object each time or to using some Map, which must be either globally accessible or referenced in each FileToNodeAdapter.

The Pattern

Replace the interface Node by

```<code>interface NodeWorker<T> {
    T parentOf(T node);
    Iterable<T> childrenOf(T node);
}
</code>```

and modify the TreeModel like

```<code>class TreeModel<T> {
    private NodeWorker<T> nodeWorker;
    private T root;
    // example method (stupid)
    T grandparent(T node) {
        return nodeWorker.parentOf(nodeWorker.parentOf(node));
    }
    ...
}
</code>```

Does this pattern have a name?

Are there any disadvantages, besides the fact that it is little bit more verbose and only applicable when you are in charge of the TreeModel code?

答:
Sounds like it's the Strategy Pattern.

The real-world example given at dofactory seems to fit your example the best.


问:
How is Sencha Touch performing on Android in practice?
I'm just about to start a project using Sencha Touch, and just done some minor testing on my HTC desire device. All tutorial videos at Vimeo seems to be using an iPhone emulator running on a Mac. Im not sure how fast this emulator is compared to a real iPhone device or even an real Android device, but from what i have experienced, it seems that my HTC desire is not performing that nicly as this emulator.

All animations (sliding, fading, etc) seems abit laggy. You can easily notice that the FPS is much less than on the Vimeo videos.

HTC desire is a relativly new and modern Android 2.2 phone, running with decent hardware, so im wondering if Sencha Touch is "ready" for the Android platform.

Anybody with practical experience with Android and Sencha Touch ?

答:
I have done a smallish benchmark of Sencha, JQuery mobile and dojox.mobile on Android emulator and phone using phonegap for a real-life app.
The bottomline is, that dojo easily outperforms both Sencha and JQuery which is both currently so sluggish as to be completely useless even on potent hardware.

So for now I'll personally go with dojo or go native.

Easy to try it out for yourself by taking either of the 'showcases' from the various frameworks and chrome2phone them to your own device.


答:
Although it helps with readability, readability isn't the primary consideration in this case, and modern IDEs don't obviate the need for this rule.

The primary concern is uninitialized variables.  If you declare a variable too far away from its initialization, it opens you up to all kinds of potential problems.  You might find yourself accidentally working with whatever happened to be there in RAM before, or the result from a calculation higher in the function, or a dummy initialization (like 0) that someone put in just to keep the compiler from complaining.  People will insert code in between your declaration and usage without being aware of your implicit preconditions for that variable.  In the worst cases, that usage will just happen to work in your tests but fail in the field.

Declaring your variables in as small a scope as possible, and initializing them to a proper value right at the point of declaration will avoid a great many maintenance headaches.  The fact that it compels improved readability is just a nice side effect.


问:
Is the agile approach too much of a convenient excuse for cowboys
I believe that an agile approach is best for projects where the requirements are fuzzy and a lot of interaction is required to help shape the end user's ideas.

However... In my professional work, I keep ending up at companies where an "agile" approach is used as an excuse as to why no effort was put into an up front design; when the requirements are well understood.

I can't help but thinking that if the agile approach wasn't around, I'd be sitting here with a nice high-level specification and not having to revisit the same screen and functionality every second day when something else crops up or so and so hadn't thought of that.

Are the benefits of agile methodologies really enough to outweigh the excuse for being lame it gives to cowboy technical leads?

Update: Ironically I'm now a certified Scrum Master. One of the papers presented on the Scrum course observed that the best development process was one where there was a single expert or guru making the design decisions, however that has obvious weaknesses. Scrum shifts the responsibility for producing quality software to the "Team" which means a sub-standard team can get away with churning out spaghetti which I guess is no different to other Agile and non-Agile development processes.

答:
Agile is fine as long as it is working for your team.

Far too many are selling it as a way to turn a bad team into a good team, and it just doesn't work that way.   You can't take bad people and apply a process to suddenly make them useful.

I like many of the ideas behind agile, but the failure I see time and time again is that the managers are pushing a strict set of "agile processes", which flies in the face of the entire concept of agile, that teams should be self-organizing.

As far as "cowboys", I find that for all the agile teams I've been on, the processes serve to slow them down more than let them go wild. I've never experienced a situation where agile served to enable a "cowboy coder".

For good teams, it seems to work well (then again, most processes seem to work well when you have a good team, funny how that works isn't it?).

For other teams, in my experience, it never helps the bad people do better, but it
sometimes serves to bog down the productive people.

Overall, I think the important thing is to build a good team, tell them what you need, and then get out of the way.  I don't think applying any string of buzzwords is likely to solve the problem of having a bad team.

(If you haven't figured out from the above, I'm not a fan of "Capitol-A Agile" in the least.  On the other hand, I don't think it encourages cowboys either.)


问:
Why do we need a Heap if everything can be done much more efficiently on the Stack?
This is actually somewhat related to the question I asked yesterday about why both a Stack and a Heap are necessary in the applications we use today (and why we can't just go with a Heap instead of both, in order to have a simple & singular standard to go by).

However, many of the responses indicated that a Stack is irreplaceable due to the fact that is many hundreds (or thousands) of times faster than trying to allocate/reference the Heap. I know there is a problem with dynamic storage allocation if we do away with the Heap, but isn't there a way around this, or perhaps, a way to improve on the Stack so that it can handle dynamic memory allocation?

答: A stack is a LIFO (last-in-first-out) structure, to the top of which a reference pointer is kept (usually supported by hardware). Having said this, anything that you are attempting to allocate on the stack instead of the heap would have to be a local variable in every function, at the top of this stack. So, the main reason against a stack is that your main() routine would need to preallocate all the data structures that your program uses (that are intended to be around for the complete duration of your program) ahead of time as all data structures allocated within function calls will eventually be removed when those function calls return and their frames or activation records are popped-off the stack.</p>


问:
When to use C over C++, and C++ over C?
I've been introduced to Computer Science for a little over a year now, and from my experience it seems that C and C++ are both considered to be "ultrafast" languages, whereas others such as Python and such scripting languages are usually deemed somewhat slower.

But I've also seen many cases where a software project or even a small one would interleave files where a certain number n of those files would be written in C, and a certain number m of those files would be written in C++.

(I also noticed that C++ files almost always have corresponding headers, while C files not so much). But my main point of inquiry is to get a general sense of intuition on when it is appropriate to use C over C++, and when it is better to use C++ over C. Other than the facts that (1) C++ is object-oriented whereas C is not, and (2) the syntaxes are very similar, and C++ was intentionally created to resemble C in many ways, I am not sure what their differences are. It seems to me that they are (almost) perfectly interchangeable in many domains.

So it would be appreciated if someone could clear up the situation! Thanks

答:
The differences between C and C++ have already been enumerated in detail here.  While sometimes people may have legitimate reasons for choosing one or the other (C++ for OOP or C when they feel like C++'s extra features introduce undesirable overhead, for example), in my experience it usually just comes down to preference.  What do the people working on this file know better and like better?  I believe this is the reason most of the time, since it's true that these languages both tackle performance critical applications.

(Side-note: Check out Linus Torvads' rant on why he prefers C to C++.  I don't necessarily agree with his points, but it gives you insight into why people might choose C over C++.  Rather, people that agree with him might choose C for these reasons.)

Title: When to use C over C++, and C++ over C?


问:
When can you call yourself good at language X?
This goes back to a conversation I've had with my girlfriend. I tried to tell her that I simply don't feel adequate enough in my programming language (C++) to call myself good. She then asked me, "Well, when do you consider yourself good enough?"

That's an interesting question. I didn't know what to tell her. So I'm asking you.

For any programming language, framework or the like, when do you reach a point were you sit back, look at what you've done and say, "Hey, I'm actually pretty good at this."? How do you define "good" so that you can tell others, honestly, "Yeah, I'm good at X".

Additionally, do you reach these conclusions by comparing what others can do?

Additional Info

I have read the canonical paper on how it takes ten-thousand hours before you are an expert on the field. (Props to anybody that knows what this paper is called again)

I have also read various articles from Coding Horror about interviewing people. Some people, it was said, "Cannot function outside of a framework." So they may be "good" for that framework, but not otherwise in the language. Is this true?

答:
On a related note, while I think the Software Craftsmanship movement is an excellent idea to help standards improve in our discipline, I've seen a lot of people describe themselves as software craftsmen, which seems a little arrogant to me in most cases.

It's up to your peers to decide whether or not you are good at something (or a craftsman); I'm sure Einstein and Feynman didn't wander round early in their careers saying "look at me, I'm a genius!" Similarly, it's up to your peers to decide whether you are good or not.

Stackoverflow is a useful tool to decide whether you are competent. Pick some questions in your area of supposed expertise. Answer them (or if they've already been answered, answer them in your head without peeking at the posted answers). Did you think of the best answer? Did you miss anything? Were you just plain wrong?


答:
Quiet office with large windows

Good ergonomic hardware


问:
Database design for tagging system
I'm creating a system where items will have one or more tags.

Now there will be an item table that will store each item, and a tags table, that will store all tags used in the system.

My question is: What is the best design I can have that will allow me to link items to their respective tags, and record how many times an item received a particular tag from a user?

For example, I'm wondering if I should create a third table that would associate a particular item with a particular tag and how many times that tag was selected. The fields would be like this: item_id, tag_id, tag_hits - where tag_hits is the number of times the tag was used. This solutions would associate all items with their tags in a single table.

Or the other solution I'm thinking of is to create a table for each item and record each tag and the amount of the time the tag was used. So, for itemX I would create a table itemX and the fields would be: tag_id, tag_hits. For another itemY, I would create a table called itemY with the same fields. So for every item, there would be a table associating it with its tags. Now there could be hundreds of thousands of items in this system.

I suppose the developers of this website had to make similar consideration because each question is tagged. And you can browse questions by tag. My system will have similar functionality.

Can someone recommend a design solution, taking into consideration all that I have said, and performance consideration. Please indicate where you think indexing might help also. I use SQL databases in my development, but if you think a no-SQL solution would do it, please suggest a design along these lines. please be very specific.

Thanks,
Ron

答:
Go with your first approach, it is pretty much the standard way of modeling this type of relationship.  (updated to record user who added the tag)

Items

ItemID (PK)

ItemTags

ItemID (FK)

TagID (FK)

Tags

TagID (PK)

UserTags

ItemID (FK)

UserID (FK)

You could also do this by adding a UserID column to the ItemTags table and allowing duplicate rows for each tag, but the above approach his likely to be more performant.

The second approach seems like a bad idea since it wouldn't give you the flexibility to add more tags in the future and likely would make queries more difficult to write.

As for indexing: Index each of the foreign keys (the primary keys should automatically get indexed).

Use an RDBMS, a NO-SQL solution probably wouldn't give you any benefit for this type of data structure.

Whatever you do, avoid creating multi-value fields with some kind of comma or space delimited values. It is a performance killer and makes queries really hard to write.

Title: Database design for tagging system


问:
NoSQL Modify operations performance
I am working on the application which in near future (hopefully) will have to process tens or hundreds of thousands of items (item is currently one row in relational database table) per second.

If I understood it right NoSQL databases are superheroes of data retrieval thanks to map-reduce magic. But will NoSQL databases provide extra performance in comperatison to relational ones in my case?

答:
100,000's of rows (of reasonable size) is a small enough that it can probably fit in main memory of one or possibly a few compute nodes.  It's probably going to be in your best interest to design your application to operate on large chunks of the dataset at a time (shard your dataset by primary key), and use a database to persist the information periodically.

If you really need a higher level of consistency (say, you are doing financial transactions), then you don't have much choice but to use a regular database (relational or document) which provides the necessary integrity and shard your dataset at the application level.

Title: NoSQL Modify operations performance


问:
Becoming a "maintenance developer"
So I've kind of been getting angry about the current position I'm in, and I'd love to get other developers' input on this.

I've been at my current place of employment for about 11 months now. When I began, I was working on all new features. I basically worked on an entire new web project for the first 5-6 months I was here. After this, I was moved to more of a service oriented role (which was still great, all new stuff for me), and I was in this role for about the past 5-6 months. Here's where the problem comes in.

Basically, a couple of days ago I was made the support/maintenance guy. Now, we have an IT support team, so I'm not talking that kind of support, I'm talking more of a second level support guy (when the guys on the surface can't really get to the root of the issue), coupled with working on maintenance issues that have been lingering in the backlog for a while. To me, a developer with about 3 years of experience, this is kind of disheartening.

With the type of work place this is, I wouldn't be surprised if these support issues take up most of my days, and I barely make it to working on maintenance issues. Also, most of these support issues aren't even related to code, they are more or less just knowing the system architecture, working with making sure services are running/getting started properly, handling/fixing bad data, etc. I'm a developer, so this part sucks. Also, even when I do have time to work maintenance, these are basically just bug fixes/improving bad code, so this sucks as well, however at least it's related to coding.

Am I wrong for getting angry here? I don't want to really complain about it, but to be honest, I wasn't spoken to about this or anything, I was kind of just sent an e-mail letting me know I'm the guy for this type of thing, and that was that. The entire team took a few minutes to give me their "that sucks" talk, because they know how annoying it is to be on support for the type of work we do, so I know I'm not the only guy that knows it's not that great of an opportunity.

I'm just kind of on the fence about how to move forward. Obviously I'm just going to continue working for the time being, no point making a bad impression on anybody, but I'd like to know how you guys would approach this situation, or how you think I should be feeling about it/how you guys would feel.

答:
You can look at this as either a as time in limbo; or you can turn it into an opportunity to grow.

The core idea of being a maintenance developer is to put yourself out of a job.  Each time you have to fix something; take the time to understand the problem well enough so that your solution (which could come a few weeks after you put out the fire) means you (nor any other living soul) will ever have to solve that problem again.

Since it's a legacy system you're supporting, you can usually get a way with some solutions that wouldn't be "ok" for mainline products;  you can use cron to periodically restart buggy services;  You can hard-code exceptional logic for particular customers since the number of customers using that product won't increase.

Another part of it is extracting useful knowledge out of the system;  You probably don't want to do this, it's not very much fun; but by documenting what the working system does (even if it does it wrong), you can make the task of mantaining that portion of the application an order of magnitude easier (ten minutes to read two paragraphs that explain a module, instead of three days reading the module code).  Better yet, this same documentation can be used to implement the functionality in the mainline product, so you can stop supporting the legacy system altogether (for that feature, at least).

If you're the "go to guy" for a project, even if that's legacy maintenance, you probably (or at very least, you should) have considerable latitude to approach problems in your own way.  That might mean rewriting sections in your favorite language or platform, suggesting workarounds instead of solutions, or just responding to issues with "wont fix, use supported products".

Edit:  You might be misinterpreting your boss's intent;  Maintenance requires a different set of skills from other parts of the development cycle; He might be putting you on a job because he thinks, out of all of the people he has available, you are the best for this role; not because he thinks you're not skillful enough for something else.

Maintenance requires a focus on reading code, more than any other role you might have.  If you are good at reading, you will be good at maintenance.  There are lots of developers, even ones of many more years experience, that just don't have the knack for reading other people's code (or worse, their own), even if they are brilliant at other things.

When you put yourself out of the job of maintenance, you aren't 'convincing management that you would be good enough to do something more important', you are literally taking the work of maintenance away from the living.  When you stop doing that job, it's because there's nothing left to do.  All problems are solved, either because they have been migrated out of the legacy application, because manual tasks are now automated, or you have convinced the customer that they don't want or need it and never will.  If your boss interprets that as 'he's good at this, better keep him here', doing nothing at all, then he is a fool.

OwnerDisplayName: anon

Title: Becoming a "maintenance developer"


问:
Why do languages such as C and C++ not have garbage collection, while Java does?
Well, I know that there are things like malloc/free for C, and new/using-a-destructor for memory management in C++, but I was wondering why there aren't "new updates" to these languages that allow the user to have the option to manually manage memory, or for the system to do it automatically (garbage collection)?

Somewhat of a newb-ish question, but only been in CS for about a year.

答:
It's a trade off between performance and safety.

There is no guarantee that your garbage will be collected in Java, so it may be hanging around using up space for a long time, while the scanning for unreferenced objects (ie garbage) also takes longer than explicitly deleting or freeing an unused object.

The advantage is, of course, that one can build a language without pointers or without memory leaks, so one is more likely to produce correct code.

There can be a slight 'religious' edge to these debates sometimes - be warned!


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答:
Smart Colleagues Who Enjoy Debating Solutions

For me, the one thing that makes a fun and relaxing environment is the people you work with.  Surrounded with smart people who are passionate about software craftsmanship is a great way to do that.  Everything else is like dual monitors, helpful, but not vital.

I find it interesting that most answers (up to this point) are physical things no one has mentioned the benefits of collaboration.

You can develop in a cave, but its easy to lose sight of the big picture.


问:
What is the difference between 'layer of abstraction' and 'level of indirection'?
I am not sure if both terms can be used interchangeably. Maybe there is some academic distinction in computer science which is not relevant for day-to-day programming? Or can I use both term interchangeably without being wrong? Maybe it depends on the context in which I use both terms?

Edit: On reason why I find both terms possibly interchangeable is a Wikipedia entry about Abstraction layer. There you can find David Wheelers quote 'All problems in computer science can be solved by another level of indirection.'

答:
Abstraction deals with simplification, indirection deals with location.

Abstraction is a mechanism that "hides" complicated details of a object in terms of simpler, easier to manipulate terms. In programming, a good example is the  difference in details between machine code and the various tools for creating applications that are ultimately based on machine code. Consider creating a Windows Form application with the Visual Studio IDE. The IDE lets you think of the application in terms of easy-to-manipulate items in a What-You-See-Is-What-You-Get manner. The position of a screen widget is abstracted out to a visual location in a frame which you can change by dragging the widget around. Internally, the IDE manipulates the widget using another layer of abstraction such as a high level language (such as C#). C# itself is not manipulated using machine code, it is manipulated using a "Common Runtime Environment" which itself is an abstraction of a computer and operating system.

Indirection refers to making the location of an item transparent. If you know a web resource's URI, you can access the resource without knowing its precise location. You do not access the resource directly, instead you access through a channel that passes your request through a series of servers, applications and routers. Indirection may be considered to be a special type of abstraction where the location is abstracted.


问:
Why does Garbage Collection only sweep the heap?
Basically, I've learned so far that garbage collection erases forever any data structure that is not currently being pointed to. But this only checks the heap for such conditions.

Why doesn't it also check the data section (globals, constants, etc etc) or the stack as well? What is it about the heap that it's the only thing that we want to be garbage collected?

答:
What is allocated on the stack? Local variables and return addresses (in C). When a function returns, its local variables are discarded. It is not neccessary, even detrimental, to sweep the stack.

Many dynamic languages, and also Java or C# are implemented in a system programming language, often in C. You could say Java is implemented with C functions and uses C local variables and therefore that Java's garbage collector does not need to sweep the stack.

There is an interesting exception: Chicken Scheme's garbage collector does sweep the stack (in a way), because its implementation uses the stack as a garbage collection first-generation space: see Chicken Scheme Design Wikipedia.


答:
You pick C when

you need portable assembler (which is what C is, really) for whatever reason,

your platform doesn't provide C++ (a C compiler is much easier to implement),

you need to interact with other languages that can only interact with C (usually the lowest common denominator on any platform) and your code consists of little more than the interface, not making it worth to lay a C interface over C++ code,

you hack in an Open Source project (many of which, for various reasons, stick to C),

you don't know C++.

In all other cases you should pick C++.

Title: When to use C over C++, and C++ over C?

Body:
I've been introduced to Computer Science for a little over a year now, and from my experience it seems that C and C++ are both considered to be "ultrafast" languages, whereas others such as Python and such scripting languages are usually deemed somewhat slower.

But I've also seen many cases where a software project or even a small one would interleave files where a certain number n of those files would be written in C, and a certain number m of those files would be written in C++.

(I also noticed that C++ files almost always have corresponding headers, while C files not so much). But my main point of inquiry is to get a general sense of intuition on when it is appropriate to use C over C++, and when it is better to use C++ over C. Other than the facts that (1) C++ is object-oriented whereas C is not, and (2) the syntaxes are very similar, and C++ was intentionally created to resemble C in many ways, I am not sure what their differences are. It seems to me that they are (almost) perfectly interchangeable in many domains.

So it would be appreciated if someone could clear up the situation! Thanks


答:
The problem with stacks is that you can't "free" memory unless it is on top of the stack. For instance, say you allocated 3 things of varying sizes:

```<code>a = allocate(2000000); // 2000000 bytes
b = allocate(1);
c = allocate(5000000);
</code>```

The stack would have a on the bottom, b in the middle, and c on top. This becomes problematic if we want to free b:

```<code>free(b); // b is not on top! We have to wait until c is freed!
</code>```

The workaround is to move all the data after b and shift if so that it comes after a. This works, but will require 5000000 copies in this case - something that will be much slower than a heap.

This is why we have a heap. While allocation may be slower than a stack (O(log n) vs O(1)), heaps allow freeing memory at an arbitrary location to be fast - O(log n), compared to a stack's O(n)

Title: Why do we need a Heap if everything can be done much more efficiently on the Stack?

Body:
This is actually somewhat related to the question I asked yesterday about why both a Stack and a Heap are necessary in the applications we use today (and why we can't just go with a Heap instead of both, in order to have a simple & singular standard to go by).

However, many of the responses indicated that a Stack is irreplaceable due to the fact that is many hundreds (or thousands) of times faster than trying to allocate/reference the Heap. I know there is a problem with dynamic storage allocation if we do away with the Heap, but isn't there a way around this, or perhaps, a way to improve on the Stack so that it can handle dynamic memory allocation?

Body:
The problem with stacks is that you can't "free" memory unless it is on top of the stack. For instance, say you allocated 3 things of varying sizes:

a = allocate(2000000); // 2000000 bytes
b = allocate(1);
c = allocate(5000000);

The stack would have a on the bottom, b in the middle, and c on top. This becomes problematic if we want to free b:

free(b); // b is not on top! We have to wait until c is freed!

The workaround is to move all the data after b and shift if so that it comes after a. This works, but will require 5000000 copies in this case - something that will be much slower than a heap.

This is why we have a heap. While allocation may be slower than a stack (O(log n) vs O(1)), heaps allow freeing memory at an arbitrary location to be fast - O(log n), compared to a stack's O(n)


答:
Stacks work great for memory allocations that obey Last in First out (LIFO) rules, that is, you free the memory in the exact reverse order that you allocate it. LIFO is a very common, perhaps the most common, memory allocation pattern. But it's not the only pattern, or even the only common pattern. To write efficient program that can tackle a wide variety of problems we have to make allowance for the less common patterns, even if it means a more complex infratstructure.

If I can get all meta for a paragraph: you are a beginner, as a beginner you value simplicity, and black and white rules. However, as a beginner you have only a peephole view of the range of problems and constraints that have to be accommodated by computer programs. You are entering a technology that has been under active development for going on 75 years. There is nothing wrong with asking why things are the way they are, but the answer is generally going to be "Yeah, we tried the simple, straight-forward method 50 years ago, and it turned out not to work very well for entire classes of problems, so we had to do something more complicated". As a technology advances simplicity generally has to give way to efficiency and flexibility.


答:
The real answer is that the only way to make a safe, efficient garbage collection mechanism is to have language-level support for opaque references.  (Or, conversely, a lack of language-level support for direct memory manipulation.)

Java and C# can do it because they have special reference types that cannot be manipulated.  This gives the runtime the freedom to do things like move allocated objects in memory, which is crucial to a high-performance GC implementation.

For the record, no modern GC implementation uses reference counting, so that is completely a red herring.  Modern GCs use generational collection, where new allocations are treated essentially the same way that stack allocations are in a language like C++, and then periodically any newly allocated objects that are still alive are moved to a separate "survivor" space, and an entire generation of objects is deallocated at once.

This approach has pros and cons: the upside is that heap allocations in a language that supports GC are as fast as stack allocations in a language that doesn't support GC, and the downside is that objects that need to perform cleanup before being destroyed either require a separate mechanism (e.g. C#'s using keyword) or else their cleanup code runs non-deterministically.

Note that one key to a high-performance GC is that there must be language support for a special class of references.  C doesn't have this language support and never will; because C++ has operator overloading, it could emulate a GC'd pointer type, although it would have to be done carefully.  In fact, when Microsoft invented their dialect of C++ that would run under the CLR (the .NET runtime), they had to invent a new syntax for "C#-style references" (e.g. Foo^) to distinguish them from "C++-style references" (e.g. Foo&).

What C++ does have, and what is regularly used by C++ programmers, is smart pointers, which are really just a reference-counting mechanism.  I wouldn't consider reference counting to be "true" GC, but it does provide many of the same benefits, at the cost of slower performance than either manual memory management or true GC, but with the advantage of deterministic destruction.

At the end of the day, the answer really boils down to a language design feature.  C made one choice, C++ made a choice that enabled it to be backward-compatible with C while still providing alternatives that are good enough for most purposes, and Java and C# made a different choice that is incompatible with C but is also good enough for most purposes.  Unfortunately, there is no silver bullet, but being familiar with the different choices out there will help you to pick the correct one for whatever program you're currently trying to build.


答: Cowboy coders also tend to write code that is not very testable, and they tend to not like writing tests.  I think having everyone doing TDD can help reign in the cowboy attitude and make developers think about architecture a little more.  No methodology is perfect, of course.</p>

Title: Is the agile approach too much of a convenient excuse for cowboys

Body:
I believe that an agile approach is best for projects where the requirements are fuzzy and a lot of interaction is required to help shape the end user's ideas.

However... In my professional work, I keep ending up at companies where an "agile" approach is used as an excuse as to why no effort was put into an up front design; when the requirements are well understood.

I can't help but thinking that if the agile approach wasn't around, I'd be sitting here with a nice high-level specification and not having to revisit the same screen and functionality every second day when something else crops up or so and so hadn't thought of that.

Are the benefits of agile methodologies really enough to outweigh the excuse for being lame it gives to cowboy technical leads?

Update: Ironically I'm now a certified Scrum Master. One of the papers presented on the Scrum course observed that the best development process was one where there was a single expert or guru making the design decisions, however that has obvious weaknesses. Scrum shifts the responsibility for producing quality software to the "Team" which means a sub-standard team can get away with churning out spaghetti which I guess is no different to other Agile and non-Agile development processes.


答:
Bjarne Stroustrup maintains a list of applications and companies that use C++; you can argue about procedural vs OOP programming all you want, but you cannot argue with industry results over the last 20 years.

C++ is commonly used for large-scale, multi-man, complex projects where separate people need to work on modularised components. You can build and maintain modularised code in C, of course, but the inherent OOP nature of C++ leads to superior modularisation, testability, and code-reuse.

The C++ standard library (STL), in itself with just vectors and maps, is reason enough to use C++.

C is commonly used for embedded systems.

I would personally use C only if there is some library that has only a C API.

Title: When to use C over C++, and C++ over C?


答:
Don't knock it.  I've done plenty of time as a maintenance programmer.  If the product is interesting and the other developers any good, you might learn something.  And if they're bad, you'll learn what makes code unmaintainable, and you can use that experience when you're writing your own code.  And after a while there, you'll be the guy they turn to when they need to know something about the code, because you'll know all of it, not just somebody's little silo.

And after you've learned your way around the code, you'll know which parts need refactoring and can propose projects to do so, which of course you'll be perfectly poised to lead.

Title: Becoming a "maintenance developer"

Body:
So I've kind of been getting angry about the current position I'm in, and I'd love to get other developers' input on this.

I've been at my current place of employment for about 11 months now. When I began, I was working on all new features. I basically worked on an entire new web project for the first 5-6 months I was here. After this, I was moved to more of a service oriented role (which was still great, all new stuff for me), and I was in this role for about the past 5-6 months. Here's where the problem comes in.

Basically, a couple of days ago I was made the support/maintenance guy. Now, we have an IT support team, so I'm not talking that kind of support, I'm talking more of a second level support guy (when the guys on the surface can't really get to the root of the issue), coupled with working on maintenance issues that have been lingering in the backlog for a while. To me, a developer with about 3 years of experience, this is kind of disheartening.

With the type of work place this is, I wouldn't be surprised if these support issues take up most of my days, and I barely make it to working on maintenance issues. Also, most of these support issues aren't even related to code, they are more or less just knowing the system architecture, working with making sure services are running/getting started properly, handling/fixing bad data, etc. I'm a developer, so this part sucks. Also, even when I do have time to work maintenance, these are basically just bug fixes/improving bad code, so this sucks as well, however at least it's related to coding.

Am I wrong for getting angry here? I don't want to really complain about it, but to be honest, I wasn't spoken to about this or anything, I was kind of just sent an e-mail letting me know I'm the guy for this type of thing, and that was that. The entire team took a few minutes to give me their "that sucks" talk, because they know how annoying it is to be on support for the type of work we do, so I know I'm not the only guy that knows it's not that great of an opportunity.

I'm just kind of on the fence about how to move forward. Obviously I'm just going to continue working for the time being, no point making a bad impression on anybody, but I'd like to know how you guys would approach this situation, or how you think I should be feeling about it/how you guys would feel.


问:
Web Developer or Software Engineer?
A question that I have been asking myself and really confused which path to take.

So I need your guys help as to the pros and cons of these 2 professions in today's world. I love web applications development as the Web is the best thing to happen in this age and nearly everyone gets by on the World Wide Web. And also tend to keep learning about new technologies and about web services.

On the other hand I like software engineering also for the desktop applications as I have had experience with development small scale software in VB.Net, Java, C++, etc.

Which path has more scope and better future? What's your view?

Title: Web Developer or Software Engineer?

Body: penispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenispenis


答:
The constructive approach recommended by the other commenters is very good. As Token pointed out, you have a lot of leeway in that kind of position so long as the problems get solved and you don't break anything. </p>

<p>If you find that you can automate common solutions, or prevent them, you can buy yourself a lot of free time - and if the bosses' expectations of the demands on your time remain uninformed by this - to do other kinds of work that you enjoy more or that you think would be more productive for the company. My first "programming" job turned out to be a data-entry job, but I quickly discovered that a lot of the data entry was scriptable, and later, that it could be generated.  I freed up about 7/8ths of my time, and used it to re-write the data entry system from scratch, including in it all the scripts and generators and more efficient UIs. It was a dead-end government job anyway, but the experience turned out to be invaluable.  </p>

Title: Becoming a "maintenance developer"

Body:
The constructive approach recommended by the other commenters is very good. As Token pointed out, you have a lot of leeway in that kind of position so long as the problems get solved and you don't break anything.

If you find that you can automate common solutions, or prevent them, you can buy yourself a lot of free time - and if the bosses' expectations of the demands on your time remain uninformed by this - to do other kinds of work that you enjoy more or that you think would be more productive for the company. My first "programming" job turned out to be a data-entry job, but I quickly discovered that a lot of the data entry was scriptable, and later, that it could be generated.  I freed up about 7/8ths of my time, and used it to re-write the data entry system from scratch, including in it all the scripts and generators and more efficient UIs. It was a dead-end government job anyway, but the experience turned out to be invaluable.


答:
There are a few reasons to prefer C. The main one is that it tends to be more difficult to produce truly tiny executables with C++. For really small systems, you're rarely writing a lot of code anyway, and the extra ROM space that would be needed for C++ rather than C can be significant.

I should also add, however, that for really tiny systems, C has problems for exactly the same reason, and assembly language is nearly the only reasonable choice. The range of system sizes within which C really makes sense is quite small, and shrinking constantly (though I'll admit, fairly slowly).

Another time/reason to use C is to provide a set of functions that you can bind to from essentially any other language. You can write these functions in C++ by defining them as extern "C" functions, but doing so restricts those functions to presenting an essentially C-life "face" to the world -- classes, overloaded functions, templates, and member functions, etc., need not apply. This doesn't necessarily restrict development to C though -- it's perfectly reasonable to use any and all manner of C++ features internally, as long as the external interface looks like C.

At the same time, I have to say that @Toll's answers (for one obvious example) have things just about backwards in most respects. Reasonably written C++ will generally be at least as fast as C, and often at least a little faster. Readability is generally much better, if only because you don't get buried in an avalanche of all the code for even the most trivial algorithms and data structures, all the error handling, etc.

Templates don't "fix a problem with the language's type system", they simply add a number of fundamental capabilities almost completely absent from C and/or C++ without templates. One of the original intents was to provide for type-safe containers, but in reality they go far beyond that -- essentially none of which C provides at all.

Automated tools are mostly a red herring as well -- while it's true that writing a C parser is less work than writing a C++ parser, the reality is that it makes virtually no difference in the end. Very few people are willing or able to write a usable parser for either one. As such, the reasonable starting point is Clang either way.

As it happens, C and C++ are fairly frequently used together on the same projects, maintained by the same people. This allows something that's otherwise quite rare: a study that directly, objectively compares the maintainability of code written in the two languages by people who are equally competent overall (i.e., the exact same people). At least in the linked study, one conclusion was clear and unambiguous: "We found
that using C++ instead of C results in improved software quality and reduced maintenance effort..."

Title: When to use C over C++, and C++ over C?


问:
Is discoverability for developers a problem when using SOLID principles?
I do line of business apps where the all the other developers are used to doing basic CRUD apps or are focused solely on making pretty/functional interfaces and I am getting the following a lot.

"With the way we use to do it Employee would have all the things you could possibly do with an employee." And it was true. That one "Class" had thousands of lines of code and anything you could do with an employee was there. Or, even worse, there was a table of employee data and each developer figured out how to do what they wanted to do in the event handler.

All the bad things about that approach was true but at least the developer using employee could, without going to other documents, figure out how to enroll the employee in a health plan, give a pay raise, fire, hire, transfer etc. Same goes for Manager and all the other major ideas. Or, if they used the employee other needed data tables, could just do what they wanted.

Yes, there was much duplicated code. Yes it was very brittle code. Yes testing it was way more difficult than necessary. Yes changing functionality was fear inducing and Copy Paste was a natural due to the approach.

But they could at least discover what was available by creating one class or they could do what they need to get done without having to understand the difference between interfaces, abstract classes, concrete classes etc. And they didn't have to search anything other than the methods returned by intellisense or know the tables where the data resided.

I have googled/binged and even yahoo!d but I haven't found any acknowledgement of this problem.

So maybe there isn't a problem and I am just missing something. I have racked my brain trying to figure out a solution where the developer(s) that do not work the actual behavior/design can easily discover how to do something without having to reference any external documents or scan the class names in the various components/projects to find the one that sounds like it will work.

The only thing I have been able to come up with is have these, for lack of a better name, "Table of Content Class" that does nothing more that return the actual classes (and really most of them are interfaces but they don't know the difference or even care) that other developers can use to perform the actual tasks desired. Still end up with really big classes but there is almost no behavior in them.

Is there a better way that doesn't require intimate knowledge of the middle tier where the actual implementation of SOLID takes place?

Basically what I am asking is there a way to allow CRUD type developers continue to be CRUD developers in a very complex system

答:
It can be a problem. Particularly if you name things badly. But there are a number of solutions to it without resorting to complex classes. Heck, a class with too many methods can be equally difficult to navigate with Intellisense.

Try using namespaces (C#) or packages (Java), or whatever similar concept your language has (I'll refer to them all as namespaces), to simplify the problem.

Start with your company name. That limits Intellisense to only namespaces written by yourselves. Then, if you have multiple applications, use the second part of the namespace to split those up. Include a Core namespace, for stuff that exists across applications. Next break things down into types of functionality. And so on.

If you do this right, you'll end up with very discoverable items.

To take your example, if I want the User validation, I type "MyCo." and it gives me a list of application namespaces. I know the User database is used in all our apps, so I type "Core." then I get a list of types of functionality. One of those is "Validation" so that seems like an obvious choice. And there, within Validation, is "UserValidator" with all its functionality.

As it happens, for things I use a lot, I'll quickly remember the names, or at least the conventions. Because I make a lot of changes to validation rules, I will know that all my validation classes are called FooValidator, where Foo is the name of the table. So I actually won't need to traverse the namespaces. I'll just type UserValidator and let the IDE do the rest of the work.

But for things I can't remember, it's still pretty easy to find them. And when I do, I can remove the namespace prefix.


答: Headphones

Body: Headphones


答:
The people that claim that one must know the mechanics of the underlying OS and that one can do both desktop and web are most likely desktop developers.

In reality you must specialize.  Knowing css, a dozen of javascript libraries,  html, a handful of serverside languages and frameworks as well as databases can take a really long time.

I think the reason so many developers here are saying this is because they really don't understand what it takes to build a good web-application and how different it is from the desktop world.

Title: Web Developer or Software Engineer?

Body:
A question that I have been asking myself and really confused which path to take.

So I need your guys help as to the pros and cons of these 2 professions in today's world. I love web applications development as the Web is the best thing to happen in this age and nearly everyone gets by on the World Wide Web. And also tend to keep learning about new technologies and about web services.

On the other hand I like software engineering also for the desktop applications as I have had experience with development small scale software in VB.Net, Java, C++, etc.

Which path has more scope and better future? What's your view?