问:
How many copies are needed to enlarge an array?
I am reading an analysis on dynamic arrays (from the Skiena's algorithm manual).

I.e. when we have an array structure and each time we are out of space we allocate a new array of double the size of the original.

It describes the waste that occurs when the array has to be resized.

It says that (n/2)+1 through n will be moved at most once or not at all. This is clear.

Then by describing that half the elements move once, a quarter of the elements twice, and so on, the
total number of movements M is given by:

This seems to me that it adds more copies than actually happen.

E.g.

if we have the following:

```<code>array of 1 element
+--+
|a |
+--+

double the array (2 elements)
+--++--+
|a ||b |
+--++--+

double the array (4 elements)
+--++--++--++--+
|a ||b ||c ||c |
+--++--++--++--+

double the array (8 elements)
+--++--++--++--++--++--++--++--+
|a ||b ||c ||c ||x ||x ||x ||x |
+--++--++--++--++--++--++--++--+

double the array (16 elements)
+--++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--+
|a ||b ||c ||c ||x ||x ||x ||x ||  ||  ||  ||  ||  ||  ||  ||  |
+--++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--+
</code>```

We have the x element copied 4 times, c element copied 4 times, b element copied 4 times and a element copied 5 times so total is 4+4+4+5 = 17 copies/movements.

But according to formula we should have 1*(16/2)+2*(16/4)+3*(16/8)+4*(16/16)= 8+8+6+4=26 copies of elements for the enlargement of the array to 16 elements.

Is this some mistake or the aim of the formula is to provide a rough upper limit approximation? Or am I missunderstanding something here?

答:
At the lower block count levels, its unlikely that a memory allocation actually occurs.  Memory managers deal in blocks of memory and routinely allocate larger blocks of memory than the allocation request acutually asked for.

Likewise, the implementation of an array class is likely to round up allocations to allow for a few additional elements.

EDIT:

On further reflection, the actual copies are unlikely to occur as you describe them either. Processors usually have a block copy command and would use a single assmbler instruction to copy the array data as a single block of memory to the new address.


问:
Some advice in open sourcing objective-c code?
I've been working on an iPhone app for the past month and am interested in open sourcing some of its code. I built a few categories that others might find useful for generating filler data during testing and debugging, and I also made a view controller for displaying images that others might like to include in their own projects.

How do you go about packaging these types of things (categories, view controllers, etc.) for sharing? What are some naming conventions I should keep in mind? Is it standard practice to preface open source code with initials (EGOTableViewPullRefresh, MGImageUtilities, etc.)? Should I make an example xcode project which shows how they can be used? Should I make a webpage to document and/or promote these things? Is automated documentation generated from comments a good way to go? What sorts of licensing should I be considering?

答:
To be useful for other developers, OSS needs to be well-documented, and giving example code/projects is such a documentation.

If you need a webpage depends on how big your codes are. i.e. for Three20 it is necessary, while for few categories the readme or a doc folder should be enough.

About licensing: I prefer the WTF License. I released some NSArray categories under this license.

OwnerDisplayName: awfullyjohn

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: vikingosegundo


答:
I am just dealing with these issues myself, as am developing an open-source objective-c lib. I went with the naming convention thing and think you should too, since it allows users to quickly separate your code from theirs and makes the project look more uniform. Most successful projects that I see on Github, do have sample projects and I know plenty of people who want to something in action, especially if it is UI focussed, before they will use it.

Documentation is must.

The biggest issue you will face is the license, assuming you want your code to be usable on the App store. You probably are going to have to go with a more permissive BSD-esque license instead of say the GPL.

Title: Some advice in open sourcing objective-c code?

Body:
I've been working on an iPhone app for the past month and am interested in open sourcing some of its code. I built a few categories that others might find useful for generating filler data during testing and debugging, and I also made a view controller for displaying images that others might like to include in their own projects.

How do you go about packaging these types of things (categories, view controllers, etc.) for sharing? What are some naming conventions I should keep in mind? Is it standard practice to preface open source code with initials (EGOTableViewPullRefresh, MGImageUtilities, etc.)? Should I make an example xcode project which shows how they can be used? Should I make a webpage to document and/or promote these things? Is automated documentation generated from comments a good way to go? What sorts of licensing should I be considering?

OwnerDisplayName: mdominick


答:
Apple has published a Coding Guidelines for Cocoa
that explains naming and coding conventions etc. when developing a framework or public API.

GitHub is a good place to share the code and it´s free for open source projects. You can have a look at the license that is used for the other open sources there.

Hope this helps :)

OwnerDisplayName: sverrisson


答:
I really like when open source projects have SIMPLE easy to use demo projects.
I also really like when they have detailed instructions of how to get the stuff working (header files you need, frameworks you need to include, etc.)

Prefixing your classes with initials is how people get around objective-c's lack of namespaces. If you're building a REST framework and you call everything a PostRequest or a GetRequest, odds are good you'll conflict with something. So if you prefix it with your initials or your company's initials, you probably won't conflict.

OwnerDisplayName: Randall


问:
Using HBase or Cassandra for a token server
I've been trying to figure out how to use HBase/Cassandra for a token system we're re-implementing. I can probably squeeze quite a lot more from MySQL, but it just seems it has come to clinging on to the wrong tool for the task just because we know it well. Eventually will hit a wall (like happened to us in other areas). Naturally I started looking into possible NoSQL solutions. The prominent ones (at least in terms of buzz) are HBase and Cassandra.

The story is more or less like this:

A user can send a gift other users.

Each gift has a list of recipients or is public in which case limited by number or expiration date

For each gift sent we generate some token that uniquely identifies that gift.

For each gift we track the list of potential recipients and their current status relating to that gift (accepted, declinded etc).

A user can request to see all his currently pending gifts

A can request a list of users he has sent a gift to today (used to limit number of gifts sent)

Required the ability to "dump" or "ignore" expired gifts (x day old gifts are considered expired)

There are some other requirements but I believe the above covers the essentials.

How would I go and model that using HBase or Cassandra?

Well, the wall was performance. A few 10s of millions of records per day over 2 tables kept for 2 weeks (wish I could have kept it for more but there was no way). The response times kept getting slower and slower until eventually we had to start cutting down number of days we kept data. Caching helps here but it's not an ideal solution since a big part of the ops are updates.

Also, as I hinted in my original post. We use MySQL extensively. We know exactly what it can and can't do both in naive implementations followed by native partitioning and finally by horizontally sharding our dataset on the application level to reside on multiple DB nodes. It can be done, but that's not really what I'm trying to get from this. I asked a very specific question about designing a solution using a NoSQL solution since it's very hard to find examples for designs out there.

Brainlag, not trying to come off as rude. I actually appreciate it a lot that you are the only one who even bothered to respond. but I see it over and over again. People ask questions and others assume they have no idea what they're talking about and give an irrelevant answer. Ignore RDBMS please. The question is about nosql.

答:
Part of the issue of NoSQL databases is that they are newish products with very variable feature sets and useage styles.  As a result there is no one right way to use a NoSQL database.

I have some familularity with Riak, and am of the view that it would support the feature set you are talking about, including expiring your expired gifts. and supports the ability to grow request capacity nearly linearly by adding new servers.

Just one issue, On a collegues project, with some high data expiry requirements (think 100's per second), this was an issue with some NoSQL dbs in that deletes were just too slow, so model and evaluate before becomming totally commited.

OwnerDisplayName: crippy


问:
Unit testing external dependencies
When writing a program, should I write tests that ensure that the dependencies I use are working? Those might help to check my assumptions about them, and may also help when deciding to upgrade said deependencies.

Also, are there any established opinions or schools about whether or how one should go about that?

答:
Yes, you should definitely write tests to verify that your external dependencies are working. However, these aren't unit tests but integration tests.

Unit testing exercises small parts of your code in isolation - that is, isolated from external dependencies, using e.g. mocks. This way you can verify that each small part in itself works as expected. After that, you still need to verify that the whole app, in its fully assembled form, works properly. However, in those tests you exercise the whole system on the highest level, via its user interface (command line / GUI / web / whatever). So integration tests are very different from unit tests, in several ways: usually they

take much longer

are harder to automate

needn't be as detailed

In the technical sense, integration tests overlap with system / validation / acceptance / functional tests, whereas each exercises the functionality of the whole system. However, the purpose of integration tests is simply to verify that the system in its assembled form works correctly in general, so it doesn't test each and every piece of functionality down to the nittiest details. However, one can use the same tool(s) for each of these kinds of tests. These tools can be very different, depending on the UI and platform of the system. Wikipedia's Test automation page lists references to some well known tools.

Title: Unit testing external dependencies


问:
Are some languages or language features better for testing?
I am, and like being, a VB.net coder. I have a couple of largish programs in c# that I must maintain and I don't really like writing C# code while developing. It isn't horrible but I much prefer the VB.net environment for development.

However recently I have started writing all my tests in C#. I started doing this so I could use all the great tools, such as the mock libraries, available in C#.

But even after I found Teleriks extremely capable justmock free edition for VB.net I have found I still write almost all my tests in C# (now using the C# version of JustMock BTW). Even when I don't need these testing tools I find that I just like C# better for writing tests.

I think I like VB.net for general coding while solving problems as I write because:
1. Like the sugary sweetness of things like XML Literals. Plus LINQ just seem easier and more expressive in VB.
2. Don't need worry about the syntax nearly as much (casing, line terminators etc.) I can focus on my ideas. (The extra verbosity is handled by #3 below and coderush and other IDE tools)
3. Think the tight integration with IDE of Visual Studio and VB.net (background compiling for example) is just the bees knees. (Though C# is getting much better.)

But for tests I am not thinking about the big picture or really solving problems. Each test method is independent and the succinctness of C# just reinforces and aids this fact.

I initially found this surprising because I always thought a scripting type language would be better for writing tests. But after actually writing many thousands of them I don't see any benefits in using a scripting language. In fact I find Option Strict and Explicit being true (which turns of the scripty nature of vb) even more helpful in the test projects.

But maybe I am wrong and there are languages even more suited to writing tests? Would something like IronPython be good for writing test? Maybe BOO with its macros? I wouldn't think so but might a functional language bring anything to the table?

More simply, are there language features that aid in writing good tests? And if so what language has the greatest numbers of these desirable features?

答:
I think a lot depends on if you're talking about testing that's integrated with your own code or testing as a separate activity. It depends on what you're doing, how your team is made up and so on - but often a combination of the two is the most powerful.

For integrated testing (unit testing, integration testing, executable specifications written by developers, etc.) then you simply have to make sure that you're coding in a way that makes it easy to test - IMHO what this means can vary from language to language although there are some general principles (loose coupling, minimise dependencies external dependencies to things like file systems or databases). In any case the problem you're trying to solve should determine which one to choose not the testing requirements.

For external testing (e.g. executable specifications written by testers or analysts) you can use the same language that you are using to write the code, but often you'll want something a bit more interactive. Avoiding a compilation step and having a REPL can be a big win here (e.g. python).


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

答: Every programmer needs an employer who is willing to send them to conferences (and cover expenses).</p>

ContentLicense: CC BY-SA 2.5


问:
Is "White-Board-Coding" inappropriate during interviews?
This is a somewhat subjective quesiton but I'd love to hear feedback/opinions from either interviewers/interviewees on the topic.

We split our technical interview into 4 parts. Write Code, Read & Analyse Code, Design Session & Code on the white board.

For the last part what we ask interviewees to do is write a small code snippet (4-5 lines) on the whiteboard and explain as they go through it. Let me be clear the purpose is not to catch people out. We're not looking for perfect syntax. Hell it can even be pseudo-code. but the point is to give them a very simple problem and see if their brain can communicate the solution to us. By simple problems I mean "Reverse a string", "FizzBuzz" etc...

Note that we always ask for an explicit language first. We're a .NET C# house. we've only said "pseudo-code" where someone has been blanking/really struggling with the code.

My question is "Is it inappropriate / unreasonable to expect a programmer to write a code snippet on a whiteboard during an interview ?"

答: I don't find it unreasonable unless the interviewee has a bad bad handwriting(or i should say boardwriting) :-) . Besides the only difference in your approach is the use of a board and marker. In some cases interviewers do this thing but they give a paper and a pen instead. Incase there are 3-4 persons conducting the interview, i would say your approach will be much better and suited.</p>


答:
In my view, It is very appropriate.  If you are wanting a job to do a particular skill, then it is entirely appropriate to be expected to demonstrate that skill at interview.

The effect of this technique on the recruitment process is very noticeable. 90% of candidates fail this task.  but the developers recruited are good, and the developers will be respected inside the company.

If as a candidate facing this technique, first of all relax.  Its about assessing you as a programmer and your thought processes.  It is not about your perfect syntax.  If you make a syntax error then I might play the role of a compiler and tell you that the code fails to compile on a certain line, and give you an error message, and see how you respond.  Likewise if you add a ;  onto a loop or an if statement that would compile, I'd play the debugger and talk you through a single step through the code.  Again, its not about the mistake, its about how you would cope with the mistake, and are your thought processes good.

Title: Is "White-Board-Coding" inappropriate during interviews?

Body:
This is a somewhat subjective quesiton but I'd love to hear feedback/opinions from either interviewers/interviewees on the topic.

We split our technical interview into 4 parts. Write Code, Read & Analyse Code, Design Session & Code on the white board.

For the last part what we ask interviewees to do is write a small code snippet (4-5 lines) on the whiteboard and explain as they go through it. Let me be clear the purpose is not to catch people out. We're not looking for perfect syntax. Hell it can even be pseudo-code. but the point is to give them a very simple problem and see if their brain can communicate the solution to us. By simple problems I mean "Reverse a string", "FizzBuzz" etc...

Note that we always ask for an explicit language first. We're a .NET C# house. we've only said "pseudo-code" where someone has been blanking/really struggling with the code.

My question is "Is it inappropriate / unreasonable to expect a programmer to write a code snippet on a whiteboard during an interview ?"


问:
Why use sealed instead of static on a class?
Our system has several utility classes.

Some people on our team use (A) a class with all-static methods and a private constructor.

Others use (B) a class with all-static methods (these the juniors).

On code analysis, (A) and (B) raise warning CA1052, which recommends marking the class as sealed.

Included in the MSDN documentation there is the following advice:

If you are targeting .NET Framework 2.0 or earlier, a better approach is to mark the type as static.

Why does this make any sense? I would have thought the opposite; AFAIK, previous to 2.0 there was no way to mark a class as static.

答: The MSDN page is wrong; it should say "later" not "earlier".  static classes were introduced in .NET 2.0.


问:
How to deal with changes that need further testing while working on another test?
TDD means to test before you start writing production code. So I start writing a test for MyClass called MyClassTest. It fails and I start to implement the wanted functionality in MyClass.

During the implementation phase of MyClass I encounter that changes on another class (e.g. MyClassUtils) are needed to be done. MyClassUtils has a test class of its own. Following TDD I should test first before implementing any new functionality. So should I interrupt the work on MyClass for the first test and implement the needed methods in MyClassUtilsTest first? Or is it better to somehow track (e.g. writing it down on paper, TODOs in the code etc.) the test methods that need to be added and disregard "test first"?

I often encounter that problem and I am not sure what is the best way to deal with it. The first possibility leads to bigger and messed up commits with changes in at least four classes and longer time periods without commits. The second one disregards the test first principle, leads to a backlog of unimplemented tests and lowers the code coverage.

How do you deal with it? I am thankful for any advice. :)

答:
IMO this question is more about organizing one's work efficiently than about TDD.

I usually strive to organize my tasks to keep myself efficient and focused. So if I find other to-do tasks while working on a specific task, I usually make TODO notes to myself (either in the code or on a piece of paper) and keep the focus on my original task. Once I committed that, I take the next TODO until I am fully finished.

However, if the new task is required in order to properly implement the original one, I see two approaches (apart from the "big ball commit" you describe):

park the main task, implement and commit the new sub-task (but only that!), then return to the main task, or

implement the main task mocking out the expected behaviour of MyClassUtils in unit tests, commit, then follow on with the newer task.

I usually prefer the first (bottom-up) approach, as it is simpler. Note that in a good design, there are no cyclic dependencies, i.e. either MyClass depends on MyClassUtils or the other way around, but not both. This guarantees that there is a bottom-up order to implement and commit all the changes one-by-one without breaking the build at any step.

Note also that if I spend enough time on design before starting to code, I can almost always detect in advance that I would need to change / extend MyClassUtils, so I can start with that task right away. Of course, I am a human, and I make omissions every now and then (or requirements may change midway, etc.), so sometimes such sidesteps become necessary.


问:
How to you "sell" support as an career option
We find it relatively easy to hire developers to work on various projects.

The problem arises when the project is finished but still needs to be supported.

We really battle to get people to join the support team. It's seen as dead-end, career-limiting, boring, second-class etc.

Currently, we get round this by getting the project team to assign some of their team to the support team for a while. Part of the assignment is to do a "brain dump" of the project so that the support team understands it. This works as long as the assignment is only for a fixed period.

Trying to hire people to work in support full-time is a problem. There are few applications and the calibre is not particularly high.

(The financial reality though is that support can be very lucrative for a company and once you get a reputation, you get approached by other companies to do their support even though you weren't involved in the original development.)

答: I think zappos.com has shown that a job doesn't have to be crappy when you work for a good company. The worst part of being in support is not being able to help someone. If you screwed users over with service contract fine print or shipped buggy software that won't get fixed any time soon, support will suck. They need to be encouraged to find solutions to problems; sort of like programming.</p>


问:
Usefulness of Javadocs with unit testing?
I am sure some else has experienced the problem of documentation regarding unit tests. I was wondering if anyone has used javadocs with their unit testing to generate their own internal javadoc files to keep track and document their unit tests? If so, did you find it successful? Or you think this a bad way to document unit tests, please let me know. If you have any suggestion for a better way for unit test documentation, it would be greatly appreciated.</p>

答: I find it's best to write self-documenting unit-tests. The BDD approach works really well for that. I've been using RSpec in Ruby world (there certainly are some equivalent tools for Java). But even with standard JUnit simply having well-named test cases is a good substitute for explicitly documenting the tests. Often when tests need documentation they are too complex and should be simplified.</p>

OwnerDisplayName: grebwerd

OwnerDisplayName: Rene Saarsoo


问:
What type of encoding can I use to make a string shorter?
I am interested in encoding a string I have and I am curious if there is a type of encoding that can be used that will only include alpha and numeric characters and would preferably shorten the number of characters needed to represent the string.

So far I have looked at using Base64 encoding to do this but it appears to make my string longer and sometimes includes == which I would like to avoid.  Example:

test name|120101

becomes

dGVzdCBuYW1lfDEyMDEwMQ==

which goes from 16 to 24 characters and includes non-alphanumeric.

Does anyone know of a different type of encoding that I could use that will achieve my requirements?  Bonus points if it's either built into the .NET framework or there exists a third party library that will do the encoding.

答:
The final '=' or '==' in Base64 is there only to make the number of characters a multiple of 4. You can remove it, since you can always put it back later on. Note that Base64 is so called because it uses 64 distinct characters. Uppercase letters, lowercase letters, and digits, that's 62. So Base64 also uses '/' and '+', which may or may not fit your bill.

On a general basis, if you want to encode arbitrary sequences of bytes into alphanumeric characters, there is necessarily some length extension somewhere, because there are 256 possible values for a byte, and only 62 alphanumeric characters. It is sometimes called the pigeonhole principle. An encoding scheme must have an average length extension of a factor log 256 / log 62 = 1.344 (average over all sequences of bytes); otherwise, it means that some pigeons are being crushed to death somewhere and you will not get them back without damage (which means: two distinct strings encoded to the same, so decoding cannot work reliably).

Now, it is quite possible that your strings are not exactly "sequences of uniformly random bytes"; your strings have some meaning which means that most possible sequence of bytes will not occur, because they are meaningless. On that basis, you can probably devise an encoding scheme which will incur less length extension than generic Base64 (or Base62 if you need to stick to strict alphanumeric characters). This is lossless data compression. It works over a clearly defined probabilistic model of what can appear as input.

Summary: a generic scheme for encoding strings into alphanumerical sequences such that no or little length extension ever occurs, cannot exist; it is a mathematical impossibility. A specific scheme tailored for the kind of input string you expect can probably exist (but since you do not tell what kind of string you may encounter, noone can help you on this).

OwnerDisplayName: Abe Miessler

OwnerDisplayName: Tom Leek


答:
Re-encoding characters is generally done when the receiving system can't process them. For example, BASE64 is representing data using 6 bits (26, hence 64) of characters to represent longer data sequences (the sometimes-appearing "==" at the end is padding for alignment). This is because your picture file in email may have 0xFE in it and your mail server will be unhappy transmitting that (or any other traditionally non-printing character).

There is no encoding that "reduces size." Encodings are just mappings of bits to the character they represent. That said, ASCII is a 7 bit character set (encoding) that is often stored in 8 bits of space. If you limit the ranges that you accept, you can also weed out the control characters.

Using this method means you have to write things out at the bit level, and it also plays a bit of hell with machine speed & instructions because all modern machines have alignments that are multiples of 8 bits. That, for example, is why Unicode is UTF-8, UTF-16, and UTF-32.

If you're doing this for security (that's why you posted it on Security.SE, right?), just filter things out and store them normally. If you're doing this to save space, consider whether all the extra code and slower access time (because most entries will cross address boundaries) is worth the space savings.

By the by, the following is a snippet from a CS course where we had to convert ASCII from 8 bit storage to 7 bit:

```<code>    memset(dest,0x00,8);
    memcpy(dest, source, length);

    for (int i = 0; i < 8; i++) {
            if (dest[i] & 0x80) {
                    fprintf(stderr, "%s: %s\n", dest, "Illegal byte sequence");
                    exit(EILSEQ);
            }
    }

    dest[0] = 0x7F & dest[0] | 0x80 & dest[1] << 7;
    dest[1] = 0x3F & dest[1] >> 1 | 0xC0 & dest[2] << 6;
    dest[2] = 0x1F & dest[2] >> 2 | 0xE0 & dest[3] << 5;
    dest[3] = 0x0F & dest[3] >> 3 | 0xF0 & dest[4] << 4;
    dest[4] = 0x07 & dest[4] >> 4 | 0xF8 & dest[5] << 3;
    dest[5] = 0x03 & dest[5] >> 5 | 0xFC & dest[6] << 2;
    dest[6] = 0x01 & dest[6] >> 6 | 0xFE & dest[7] << 1;
    dest[7] = 0x00; //Clearing out
</code>```

Title: What type of encoding can I use to make a string shorter?

Body:
I am interested in encoding a string I have and I am curious if there is a type of encoding that can be used that will only include alpha and numeric characters and would preferably shorten the number of characters needed to represent the string.

So far I have looked at using Base64 encoding to do this but it appears to make my string longer and sometimes includes == which I would like to avoid.  Example:

test name|120101

becomes

dGVzdCBuYW1lfDEyMDEwMQ==

which goes from 16 to 24 characters and includes non-alphanumeric.

Does anyone know of a different type of encoding that I could use that will achieve my requirements?  Bonus points if it's either built into the .NET framework or there exists a third party library that will do the encoding.

Body:
Re-encoding characters is generally done when the receiving system can't process them. For example, BASE64 is representing data using 6 bits (26, hence 64) of characters to represent longer data sequences (the sometimes-appearing "==" at the end is padding for alignment). This is because your picture file in email may have 0xFE in it and your mail server will be unhappy transmitting that (or any other traditionally non-printing character).

There is no encoding that "reduces size." Encodings are just mappings of bits to the character they represent. That said, ASCII is a 7 bit character set (encoding) that is often stored in 8 bits of space. If you limit the ranges that you accept, you can also weed out the control characters.

Using this method means you have to write things out at the bit level, and it also plays a bit of hell with machine speed & instructions because all modern machines have alignments that are multiples of 8 bits. That, for example, is why Unicode is UTF-8, UTF-16, and UTF-32.

If you're doing this for security (that's why you posted it on Security.SE, right?), just filter things out and store them normally. If you're doing this to save space, consider whether all the extra code and slower access time (because most entries will cross address boundaries) is worth the space savings.

By the by, the following is a snippet from a CS course where we had to convert ASCII from 8 bit storage to 7 bit:

    memset(dest,0x00,8);
    memcpy(dest, source, length);

    for (int i = 0; i < 8; i++) {
            if (dest[i] & 0x80) {
                    fprintf(stderr, "%s: %s\n", dest, "Illegal byte sequence");
                    exit(EILSEQ);
            }
    }

    dest[0] = 0x7F & dest[0] | 0x80 & dest[1] << 7;
    dest[1] = 0x3F & dest[1] >> 1 | 0xC0 & dest[2] << 6;
    dest[2] = 0x1F & dest[2] >> 2 | 0xE0 & dest[3] << 5;
    dest[3] = 0x0F & dest[3] >> 3 | 0xF0 & dest[4] << 4;
    dest[4] = 0x07 & dest[4] >> 4 | 0xF8 & dest[5] << 3;
    dest[5] = 0x03 & dest[5] >> 5 | 0xFC & dest[6] << 2;
    dest[6] = 0x01 & dest[6] >> 6 | 0xFE & dest[7] << 1;
    dest[7] = 0x00; //Clearing out

OwnerDisplayName: Jeff Ferland


答:
My question is "Is it innappropriate / unreasonable to expect a programmer to write a code snippet on a whiteboard during an interview ?"

It's very reasonable. An alternative to a whiteboard might be a laptop and a beamer, since programmers are more used to writing code on a keyboard than on a whiteboard. Just make sure a development environment like Eclipse or VS or Idle is already running with a blank project when the candidate starts, so she doesn't have to waste time searching through your installed applications.


答:
Firstly, b is moved 3 times and a is moved 4 times, which gives a total of 4 + 4 + 3 + 4 = 15 copies.

I think the formula should be filled in with n=8: 1*(8/2) (x is copied once) + 2*(8/4) (c is copied twice) + 3*(8/8) (b is copied thrice) = 11. In other words, the formula seems to be missing a "+ log2 n + 1" term in addition to the sum itself.

What would seem to me to be a much more natural way to count the number of moves is to count the number of moved elements per copy:

sum from i = 1 to i = ceiling(log2 n): 2i-1

In your case, n = 16, so ceiling(log2 16) = 4 and the sum above is: 20+21+22+23 = 1 + 2 + 4 + 8 = 15.

I'll see if I can find this Skiena's algorithm manual to see if I got it correct.

Update: I found the part in Skiena's algorithm manual. It does seem like there there is a term missing in the sum he uses there. However, the conclusion is correct:

M = sum from i = 1 to i = ceiling(log2 n): 2i-1 = sum from i = 0 to i = ceiling(log2 n) - 1: 2i = 2ceiling(log2 n) - 1 + 1 <= (2log2 n + 1 - 1 + 1) = 2 * n

(I wish I could format these formulas in a nicer way for you)

The main point of this paragraph seems to be to give an example of amortized analysis. Methods such as the potential method would make a better (less ad hoc) argument why dynamic arrays perform very well, but this method is somewhat advanced.

If you are convinced there is an error in this book, you could consider contacting the author about this (in a constructive way of course - the book has a lot of pages, and it's hard to get every last thing correct, and there's always a chance that the book is right and we both got it wrong). I haven't found this particular one on the errata.

Title: How many copies are needed to enlarge an array?

Body:
I am reading an analysis on dynamic arrays (from the Skiena's algorithm manual).

I.e. when we have an array structure and each time we are out of space we allocate a new array of double the size of the original.

It describes the waste that occurs when the array has to be resized.

It says that (n/2)+1 through n will be moved at most once or not at all. This is clear.

Then by describing that half the elements move once, a quarter of the elements twice, and so on, the
total number of movements M is given by:

This seems to me that it adds more copies than actually happen.

E.g.

if we have the following:

```<code>array of 1 element
+--+
|a |
+--+

double the array (2 elements)
+--++--+
|a ||b |
+--++--+

double the array (4 elements)
+--++--++--++--+
|a ||b ||c ||c |
+--++--++--++--+

double the array (8 elements)
+--++--++--++--++--++--++--++--+
|a ||b ||c ||c ||x ||x ||x ||x |
+--++--++--++--++--++--++--++--+

double the array (16 elements)
+--++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--+
|a ||b ||c ||c ||x ||x ||x ||x ||  ||  ||  ||  ||  ||  ||  ||  |
+--++--++--++--++--++--++--++--++--++--++--++--++--++--++--++--+
</code>```

We have the x element copied 4 times, c element copied 4 times, b element copied 4 times and a element copied 5 times so total is 4+4+4+5 = 17 copies/movements.

But according to formula we should have 1*(16/2)+2*(16/4)+3*(16/8)+4*(16/16)= 8+8+6+4=26 copies of elements for the enlargement of the array to 16 elements.

Is this some mistake or the aim of the formula is to provide a rough upper limit approximation? Or am I missunderstanding something here?


答:
I personaly think that this is one of the best things you can do. As you said you don't look for correct syntax or something similar the most important part here is to see if someone can communicate... I have seen so many good developers who can only work alone inside their own space... Unfortunatly this isn't possible in a huge amount of cases so having a skilled guy who also is able to TELL what he thinks in a clear and concise way is a more valuble member of the team then someone who thinks:"They won't understand it anyway, I'll just do it myself and demonstrate later".

Communication, communication, communication that's something that is the foundation of every medium to big sized project (even smaller once need it)


问:
How to work in localhost properly
I am using MAMP (just and example) to develop web applications without having to constantly upload and download via FTP.

I´m sure this is the correct way to test a project but I´m no sure if I´m doing it right.

After I´m satisfied with the project I have to change in every page the MySQL databases and most of the links etc.

Is there a workaround this? How should this be used?

Thanks in advance!

答: Instead of hard coding the links, use a variable to hold the base URL, then append that as a prefix. </p>

Title: How to work in localhost properly


答:
It is not inappropriate, but know that it might NOT always reveal the true insights into the programming or problem solving abilities of the person you're interviewing. And I guess that's exactly what you're after.

Secondly, note that there's always the fear of failure, constantly nettling the person's brain. "What if I screw up?", "What if I make a silly mistake". The greater share of the person's brain is busy constantly inspecting how they're coming off -- only few can hold the nerves.

So, in this kind of situation, even the very best might end up faltering.

For the last part we ask interviewees to do is write a small code snippet (4-5 lines) on the whiteboard and explain as they go through it

That's OK. But again, just because somebody could not explain something properly does not mean they don't know it well. (Explanation is an art of speech).

If I were you, I'd do this For the last part...

Hire them for a very tiny (but realistic) project. See how they code, take decisions, assimilate the working conditions and team members, etc., and then based on that, make the final decision.


答: Not inappropriate, but remember that some people (and maybe a greater share of the programmer crowd) can be very stressed out in an interview. I think most of us know the guy from the office who is a brilliant coder and a very trustworthy person, but he would melt down in such a situation. His performance could not be measured in such a test, so don't make this a go/no go test. </p>


问:
What ESB systems work the best for .Net stack
What Enterprise Service Bus would you use and why?</p>

答:
Somewhat late to the party but I would use Shuttle ESB (http://shuttle.codeplex.com/).

Mostly because I wrote it :)

It is a distributed ESB with a highly decoupled architecture.  The core assemblies have no direct dependencies on third party assemblies although they may be incorparated by using some adapter interfaces.

IQueue 'out-of-the-box' implementations include Msmq and Sql Server.  Pub/Sub is there.  Distributor is there.  Includes a management console and health monitor.  Message Forwarding is there.  There is even CRON job scheduling.


问:
Why don't we store the syntax tree instead of the source code?
We have a lot of programming languages. Every language is parsed and syntax checked before being translated into code so an abstract syntax tree (AST) is built.

We have this abstract syntax tree, why don't we store this syntax tree instead of the source code (or next to the source code)?

By using an AST instead of the source code. Every programmer in a team can serialize this tree to any language they want (with the appropriate context free grammar) and parse back to AST when they are finished. So this would eliminate the debate about the coding style questions (where to put the { and }, where to put whitespace, indentation, etc.)

What are the pros and cons of this approach?

答:
I think the most salient points are those:

There is no benefit. You said that it would mean that everybody could use their pet language. But that’s not true – using a syntax tree representation would elide syntactical differences only, but not semantical ones. It works to some extent for very similar languages – such a VB and C#, or Java and Scala. But not even there completely.

It’s problematic. You have gained freedom of language, but you’ve lost freedom of tools. You can no longer read and edit the code in a text editor, or even any IDE – you depend on a specific tool that speaks your AST representation for both reading and editing the code. There’s nothing gained here.

To illustrate this last point, take a look at RealBasic, which is a proprietary implementation of a powerful BASIC dialect. For a time, it almost looked like the language could take off, but it was completely vendor-dependent, to the point that you could only view the code in their IDE since it was saved in a proprietary non-text format. Big mistake.


问:
Does teaching programming make you a better programmer
I consider myself an intermediate Python programmer and have been offered an opportunity to be a trainer for a beginner Python programming class.

I was wondering if this would really widen my programming repertoire. Has somebody had an enlightening experience after they successfully trained a group of people?

Does it also depend on those people -- whether they're programmers or noob students? (In my case they are intermediate .NET and Java programmers)

What should I expect from them?

One of my fears is -- what if I choked when one of them asked a tangled question. Is this normal?

答:
Many of the answers to this question have pointed out that teaching something means you have to learn it first and so you have to become better to be able to teach.  I would say that this is almost right.

If you are responsible for developing the course materials, then you will have to gain a thorough understanding of the subject matter.  Learning the material to this level will make you better, assuming you need to learn something you don't already know.

If, on the other hand, you are just a meat puppet reading off course materials prepared by someone else, then you can probably get away without knowing or understanding the subject matter.  This is especially true for introductory courses.  If you are an experienced developer teaching a beginner's class, do you really need to learn anything substantive?


问:
Any good resources for a non-technical guy to learn software project management?
There are many resources on general project management, but are there any specifically for non-technical people for software project management, covering topics such as requirements gathering, use cases and general architecture?</p>

答:
The two textbooks used in the Software Engineering Process and Project Management course that I took were Rapid Development: Taming Wild Software Schedules and Software Project Survival Guide: How to be Sure Your First Important Project Isn't Your Last. Both focus on best practices and techniques for managing software engineering projects. Both books present information from past software projects, in the form of cast-studies.

I'd also highly recommend Software Estimation: Demystifying the Black Art, which focuses on scheduling and estimating software projects. It discusses a number of topics relating to scheduling, estimation, and managing deadlines, along with tools and techniques to best come up with accurate estimates for your projects.

The book used in the software requirements engineering course was Software Requirements. There's also a companion book, with expanded information, called More About Software Requirements: Thorny Issues and Practical Advice. These books discuss multiple methods of eliciting, organizing, documenting, verifying, and validating requirements that are appropriate for plan-driven or agile teams.

All of the books I mentioned above are about general project management. Depending on your organization's processes and methods, you might also want to consider resources that discuss those specific processes.


问:
What is the possible disadvantage of putting declarations in inner blocks, instead of at beginning of function?
At the place where I work, there are explicit guidelines for placement of declarations of variables. According to that, it is required to put them at the global level and / or at the beginning of functions, and not in inner blocks (such as a for loop). Since they've been specified by persons more experienced than I am, I'm sure that there must be a good reason for it, but I cannot figure out what that might be. It would be nice to know if there are any compile time / run time advantages at having them declared at a bigger scope.</p>

答: The only advantage I have found so far is code simplicity. Youalways know where to look for variable declarations and everybody in the team adopts the same coding style. These things make code maintenance easier but I am not sure that they make writing better code any easier. I do not mean that you write worse code only that sometimes it is harder to write code as good. Nevertheless if the development team is big or its members change frequently using code standards is helpfull.</p>


答: This sounds like a decision to preserve consistency. It also prevents the use of same names for different variables in neighboring scopes and increase readability. As Gus points out, you'll also know where to look for variables. I think narrowest scope principle is better though because it prevents the variable clutter at the top. Outermost declaration is much like declaring private members of a class first IMO. </p>

Title: What is the possible disadvantage of putting declarations in inner blocks, instead of at beginning of function?

Body: At the place where I work, there are explicit guidelines for placement of declarations of variables. According to that, it is required to put them at the global level and / or at the beginning of functions, and not in inner blocks (such as a for loop). Since they've been specified by persons more experienced than I am, I'm sure that there must be a good reason for it, but I cannot figure out what that might be. It would be nice to know if there are any compile time / run time advantages at having them declared at a bigger scope.</p>


答: I Would have a configuration file, which contains the bits that you have to change every time, so that you will only have to make a few changes.</p>

Title: How to work in localhost properly

Body:
I am using MAMP (just and example) to develop web applications without having to constantly upload and download via FTP.

I´m sure this is the correct way to test a project but I´m no sure if I´m doing it right.

After I´m satisfied with the project I have to change in every page the MySQL databases and most of the links etc.

Is there a workaround this? How should this be used?

Thanks in advance!


问:
Is it OK to use dynamic typing to reduce the amount of variables in scope?
Often, when I am initializing something I have to use a temporary variable, for example:

```<code>file_str = "path/to/file"
file_file = open(file)
</code>```

or

```<code>regexp_parts = ['foo', 'bar']
regexp       = new RegExp( regexp_parts.join('|') )
</code>```

However, I like to reduce the scope my variables to the smallest scope possible so there is less places where they can be (mis-)used. For example, I try to use for(var i ...) in C++ so the loop variable is confined to the loop body.

In these initialization cases, if I am using a dynamic language, I am then often tempted to reuse the same variable in order to prevent the initial (and now useless) value from being used latter in the function.

```<code>file = "path/to/file"
file = open(file)

regexp = ['...', '...']
regexp = new RegExp( regexp.join('|') )
</code>```

The idea is that by reducing the number of variables in scope I reduce the chances to misuse them. However this sometimes makes the variable names look a little weird, as in the first example, where "file" refers to a "filename".

I think perhaps this would be a non issue if I could use non-nested scopes

```<code>begin scope1
   filename = ...
begin scope2
   file = open(filename)
end scope1
   //use file here
   //can't use filename on accident
end scope2
</code>```

but I can't think of any programming language that supports this.

What rules of thumb should I use in this situation?

When is it best to reuse the variable?

When is it best to create an extra variable?

What other ways do we solve this scope problem?

答:
Short answer: No, don't repurpose variables.

The idea is that by reducing the number of variables in scope I reduce
  the chances to misuse them.

It sounds more like you're misusing variables so that you can reduce the number of them.

Variables are cheap -- use as many as you need. Reusing variables to represent different things at different times will not be cheap in the long run; it will make your code more difficult to understand, and you or someone after you will be much more likely to create bugs trying to maintain such code.

What other ways do we solve this scope problem?

The best way is to choose descriptive names for your variables and never try to reuse one variable for two or more different concepts. The problem is not scope, the problem (as far as I can tell) is accidentally using a variable for the wrong thing. Descriptive names help in that respect.

You can always set a variable that you no longer need to a value that's harmless or invalid. This is common in languages with manual resource management, where you free/delete/release pointers when you're done with them. After doing so, it's often a good idea to set them to nil to prevent future use of that pointer. You can do similar things with other types, like setting a loop counter to -1, but in practice it's not usually necessary.

Also, don't write functions/methods that are so large that you have a hard time keeping track of all the variables you're using. If you've got dozens of variables floating around, there's a good chance that you're code is too complicated; break it down into smaller independent tasks.


答:
I see two main advantages:

Reusing variable names with a different type is prevented.

It becomes clear at an earlier time that a routine needs to be refactored. The variables at the top become a major mess fairly quickly, and this mess is easy to recognize.

Any compiler worth its salt will optimize away the scope of the variables anyway, so it's purely a formatting concern.

For my two cents, I'd still prefer the innermost declaration of the variable to transport the intent of scope to the compiler. If you intended to have a variable only accessed within a loop, you can catch any later reference at compile time when you declare the variable in the loop.


问:
Which license for commercial software?
At the moment we are writing modules for an open source cms.
We would like to sell these with a license.

But which are the best options?
Any suggestions and experiences.

答:
First off, you'll need to look at the licence for the CMS and whether it allows you to do this.

Unlike the various open-source licences (creative commons, GPL, BSD, Apache, Mozilla Public Licence, Perl...) there is no standard licencing terms avaialble off-the-shelf. Indeed, most commercial licences have explicit terms convering the licence itself - and even where that is not the case, they will be covered by copyright.

Open source licences do not prevent you from charging for the software. Some affect the users rights for redistribution / modification. Microsoft admit that piracy of their software has probably been a net benefit to them via acquiring market share. Have a google for the discussions on GPLv3.

If possible, GPLv3 will allow your software to be redistributed, but not allow other people to charge a premium for redistributing it or providing a service based on it. This of course does not preclude you from offering the product under a different licence (which you can explicitly promote via the GPV3 version).

And under most of the open-source licences you can still charge for support.

OwnerDisplayName: Frederik Heyninck

Title: Which license for commercial software?


答: There is a system built around this idea: JetBrains MPS. An editor is a little bit odd, or just different, but in general it is not such a big problem. The biggest problem is, well, that it is not a text any more, so you can't use any of the normal text-based tools - other editors, grep, sed, merge and diff tools, etc.

Title: Why don't we store the syntax tree instead of the source code?

Body:
We have a lot of programming languages. Every language is parsed and syntax checked before being translated into code so an abstract syntax tree (AST) is built.

We have this abstract syntax tree, why don't we store this syntax tree instead of the source code (or next to the source code)?

By using an AST instead of the source code. Every programmer in a team can serialize this tree to any language they want (with the appropriate context free grammar) and parse back to AST when they are finished. So this would eliminate the debate about the coding style questions (where to put the { and }, where to put whitespace, indentation, etc.)

What are the pros and cons of this approach?


答:
If the declaration is within an if clause that only rarely (if ever) gets exercised, but needs a lot of memory, your memory footprint is smaller (most of the time) than if you allocate everything at the beginning of the function.

If it is within a loop then you have to reallocate the memory repeatedly, this can be costly in performance terms.

There are reasons for doing things both ways.


答:
reducing the number of variables in scope I reduce the chances to
  misuse them

My experience says mostly the other way.

Multiple use (which eventually becomes abuse) forces people to generate multiple meaning and inconstancy of the variable. This is generally bad.
One of the classic example (your examples are still quite a departure) is this:

```<code>int err

err = some_function1()
//... some other code
if(new_condition)
   err = some_fuction2();

return err;
</code>```

Understand that when the err returns it has potentially the return value err depending on the context of new_condition this might work. However, when someone modifies the code, around either function, there is a disaster.

the other inconsistency i see in your idea is that while value of a variable is not modified or used for some time, it still need to be retained till end of scope. So in your above case -

```<code>
file = "path/to/file"
file = open(file)
//
if(file != NULL)
</code>```

The last line in if has ambiguous meaning. So now i don't know what you are referring to.

ideally i would like to treat them file.path and file.handle which helps remove top level clutter while still preserves the sanity of the work.

Last but most important is that most often variables are abused only if they are not properly named and if they are strongly named almost likely they wont get wrongly. This doesn't sound obvious to many - but when you see code to evolve for few years many would agree.

Title: Is it OK to use dynamic typing to reduce the amount of variables in scope?

Body:
Often, when I am initializing something I have to use a temporary variable, for example:

```<code>file_str = "path/to/file"
file_file = open(file)
</code>```

or

```<code>regexp_parts = ['foo', 'bar']
regexp       = new RegExp( regexp_parts.join('|') )
</code>```

However, I like to reduce the scope my variables to the smallest scope possible so there is less places where they can be (mis-)used. For example, I try to use for(var i ...) in C++ so the loop variable is confined to the loop body.

In these initialization cases, if I am using a dynamic language, I am then often tempted to reuse the same variable in order to prevent the initial (and now useless) value from being used latter in the function.

```<code>file = "path/to/file"
file = open(file)

regexp = ['...', '...']
regexp = new RegExp( regexp.join('|') )
</code>```

The idea is that by reducing the number of variables in scope I reduce the chances to misuse them. However this sometimes makes the variable names look a little weird, as in the first example, where "file" refers to a "filename".

I think perhaps this would be a non issue if I could use non-nested scopes

```<code>begin scope1
   filename = ...
begin scope2
   file = open(filename)
end scope1
   //use file here
   //can't use filename on accident
end scope2
</code>```

but I can't think of any programming language that supports this.

What rules of thumb should I use in this situation?

When is it best to reuse the variable?

When is it best to create an extra variable?

What other ways do we solve this scope problem?

Body:
reducing the number of variables in scope I reduce the chances to
  misuse them

My experience says mostly the other way.

Multiple use (which eventually becomes abuse) forces people to generate multiple meaning and inconstancy of the variable. This is generally bad.
One of the classic example (your examples are still quite a departure) is this:

int err

err = some_function1()
//... some other code
if(new_condition)
   err = some_fuction2();

return err;

Understand that when the err returns it has potentially the return value err depending on the context of new_condition this might work. However, when someone modifies the code, around either function, there is a disaster.

the other inconsistency i see in your idea is that while value of a variable is not modified or used for some time, it still need to be retained till end of scope. So in your above case -

file = "path/to/file"
file = open(file)
//
if(file != NULL)

The last line in if has ambiguous meaning. So now i don't know what you are referring to.

ideally i would like to treat them file.path and file.handle which helps remove top level clutter while still preserves the sanity of the work.

Last but most important is that most often variables are abused only if they are not properly named and if they are strongly named almost likely they wont get wrongly. This doesn't sound obvious to many - but when you see code to evolve for few years many would agree.


答:
The old C-standard of 1989 only allows variable declarations at the start of a block.

Only since C99 declarations are allowed anywhere. Maybe your place hasn't made the switch to C99 yet.


答:
Whether it is local or not, you need a development environment outside of production.

I'm no PHP expert, but every page should not have its own connection code to the database. Create a class that can be reused. Your application should be able to determine if you are on local host or example.com and connect to the appropriate database.

And for hyperlinks, look into Relative URL instead of Absolute URL.

Title: How to work in localhost properly


问:
What is the market share of programs written in .NET nowadays?
We are currently migrating our Visual Basic 6.0 program to .NET. The target audience are just normal desktop users at home. Discussing this, we realized that we cannot come up with mainstream programs that seem to be written in .NET. Are we mistaken? Is there a good reason for this?</p>

答:
Your customer don't care if your program is written in .NET or not. Therefore, if you can ensure that the vast majority of your target audience can install and run your software without problems, you are good.

It's very difficult to find accurate information about .NET Framework penetration, so you shouldn't rely on any.

Why not targeting .NET Client Profile and ensure that it is installed along with your binaries? It's easy, simple and effective.

The .NET Framework 4 Client Profile is a subset of the .NET Framework 4 that is optimized for client applications. It provides functionality for most client applications, including Windows Presentation Foundation (WPF), Windows Forms, Windows Communication Foundation (WCF), and ClickOnce features. This enables faster deployment and a smaller install package for applications that target the .NET Framework 4 Client Profile.

I see another big advantage of porting your VB6 code to .NET: the ability to create version of your software that runs on Linux and OSX using Mono. Notable example of desktop applications written in .NET and cross platforms are available here.


问:
increasing productivity - mastering a language vs. selecting efficient tools
I'm looking for advice from experienced developers on this question.

In my work there's a need for a lot of one-off code. It's tempting to just dip into the right python/perl library calls to do these little tasks as quickly as possible.

I used to be of the philosophy of - "use most efficient tool for the task". However, I'm afraid that over time, this means that I won't have a deeper experience and expertise, so recently I've been forcing myself to use C++ (w/ Boost and STL) for everything, even if I could do the task in python or perl much more quickly. I'm hoping that in the long run, this will make me a more productive developer. I hope to reach a level of familiarity that I can do things in C++ as quickly as I can in python (and also have the practice to work on bigger projects that would require C++).

Is this a good strategy towards long-term productivity and deeper skills? Or am I unnecessarily wasting time / torturing myself?

答:
Using many languages and tools increase the ability of a programmer to think beyond a particular language. If someone sticks to C alone, that person will code strings every time there is a need for a string. Not bad, but counter-productive.

Let me write from a different perspective. I have seen that computer science/engineering students turned programmers approach coding a solution different than others. They do not think of what is available in the language, but start from a generic solution and try to find ways to code it in a language. This is the concept of design before coding.

I believe your question can be answered from the same perspective. Using many different languages and tools to solve a problem enables one to realize there are ways to solve a problem beyond the traditional way, and one tries to find such constructs/libraries in every language. I believe this is an invaluable quality of a programmer that can only be built by working in different languages.


答:
Decide if there are features your market wants that you can only or more easily create in .NET. Consider that hiring new developers is another market to consider. You may or may not find more VB.NET devs that are suitable to your needs (level of experience, knowledge of domain, etc.). Do your current developers really want to make the switch?

I don't know about the home user market, but the business market is pretty heavy in .net apps.

Title: What is the market share of programs written in .NET nowadays?

Body: We are currently migrating our Visual Basic 6.0 program to .NET. The target audience are just normal desktop users at home. Discussing this, we realized that we cannot come up with mainstream programs that seem to be written in .NET. Are we mistaken? Is there a good reason for this?</p>


答:
Seems like those who made this decision are use to a time when putting declarations at the top was the norm and have chosen not to switch to a preference to declare closer to where it is being used.

I'm not sure how helful this level of consistency is. Some IDE's probably make finding things easier than others. For global variables this makes sense, but if your function is so long it makes finding variable declarations difficult, you have bigger problems.


答:
I believe having one variable with multiple meanings is much more confusing than having many variables in scope.

At any rate, if you feel overwhelmed by the number of variables in scope, chances are your method/function is doing too much and should be split.

So the answer is: No, do not reuse variables, particularly not in this way.


答:
it's a nice idea; but each language's AST is different from every other one.

the only exception I know is for VB.NET and C#, where microsoft argues that they're "the exact same language with different syntax".  Even other .NET languages (IronPython, F#, whatever) are different at the AST level.

Same thing with JVM languages, they all target the same bytecode, but the language constructs are different, making it different languages and different ASTs.

Even 'thin layer' languages, like CoffeScript and Xtend share a lot of the theory of the underlying languages (JavaScript and Java, respectively); but introduce higher level concepts that are (or should be) retained at the AST level.

if Xtend could be reconstructed from a Java AST, i think it would've been defined as a Java-to-Xtend 'uncompiler' that magically create higher level abstractions from existing Java code, don't you think?


答:
Every language might differ in the preference of style and practice.
Following is from JSF-AV-rules, which Stroustrup points to as the coding standards he prefers.

AV Rule 136

Declarations should be at the smallest feasible scope

The rationale for this is described as

This rule attempts to minimize the number of live variables that must be simultaneously considered. Furthermore, variable declarations should be postponed until enough information is available for full initialization

If you are in C++, declaring variable when you need them is preferred.

ContentLicense: CC BY-SA 4.0


答:
A Hacker's Guide to Project Management is a good book that will highlight how a lot of developers think in terms of software projects. It is written from the perspective of a guy who loved to code and learned about project management through trial by fire.

It's less formal that a lot of the texts mentioned by others here: It doesn't embrace a single framework. However, I think it will help you learn to recognize where stresses between PMs and coders come from in a lot of cases. Many coders just love to code and find the PM aspect of their work annoying. As with many PM texts, the biggest focus is on how to facilitate and manage communication, including managing expectations.

It's an older book that won't cost you much on Amazon.

Title: Any good resources for a non-technical guy to learn software project management?

Body: There are many resources on general project management, but are there any specifically for non-technical people for software project management, covering topics such as requirements gathering, use cases and general architecture?</p>


问:
How to deal with the programmer's block?

Possible Duplicate:

  Dealing with frustration when things don't work

Something I find myself coding something difficult and after hours of struggle my mind goes blank and I don't know what I am doing anymore.

I'm not sure if this happen to a lot of programmers. Does this happen to you How do you deal with it?

答:
Happens to me when I am under pressure, or have been working on the same problem for many days. I have spent days without realizing the obvious solution.

I have found  that getting up and walking away is the best way to get rid of it. If you are still stuck, talk to someone; preferably, a junior programmer, or someone who is good at lateral thinking. A second set of eyes always help.


答:
Actually, according to TIOBE, C# (a .NET language) is now the fourth most popular language in the world.

Also, I agree with another poster that clients do not care what language your app is written in, as long as it works.


答:
As in any creative endeavor, sometimes we programmers get blocked and the creative juices don't flow.  A few things that I do when I'm in such a situation:

Get up from my desk for a couple of minutes

Stretch

Start working on something unrelated

Visit the water cooler/chat with co-workers

Ask a colleague for assistance

In all of these situations, I'm attempting to do something that is unrelated to the current task-at-hand.  While my foremost activities during this time are unrelated (by design) to what I'm stuck on, my brain is still subconsciously churning away at the problem.  Often, the solution will somehow work itself out within the space of a few hours.

Title: How to deal with the programmer's block?

Body:
Possible Duplicate:

  Dealing with frustration when things don't work

Something I find myself coding something difficult and after hours of struggle my mind goes blank and I don't know what I am doing anymore.

I'm not sure if this happen to a lot of programmers. Does this happen to you How do you deal with it?


答:
If your intention is to eliminate the debate about formatting styles, then perhaps what you want is an editor that reads in a source file, formats it to your personal preference for display and editing, but when saving it, reformats to the chosen style the team uses.

It's quite easy if you use an editor like Emacs. Changing the formatting style of an entire file is a three command job.

You should also be able to build the hooks to automatically transform a file to your own style on loading, and to transform it to the team style when saving.


答:
I'd read The Mythical Man Month -- it is a classic in the field of software project management.

As for getting to understand the team, I suggest keeping up on things like reddit programming or the hacker news. Much of what is written there will go over your head, but many of the things there are written in English and can give a decent window into the mentality of developers in general.


答:
This happens to everyone.  Taking a break, going for a walk, or switching to another project always helps.  I have also read about an interesting technique in "Clean Coder" by Robert C. Martin.  It is called the "tomato timer" or "pomodoro".

You set a timer for 25 minutes.  You can use your phone, an alarm clock, Outlook, etc.  In the old days people used a kitchen timer, which would often be in the shape of a tomato, hence the name of the technique.  Then you work for 25 minutes without interruption.  Don't check your email, don't browse the web, not even StackExchange.  If you get interrupted by a phone call or a co-worker, politely ask them to call or come back after the time is up.  When the alarm sounds after 25 minutes, take a 5 minute break.  Every 4 "tomatos" or so, take a longer break.

Even though this is more of a way to manage distractions, rather than fight programmer's block, it should help with that too.  With these regular periods of concentration you get much more done.  And with the regular breaks you feel much less tired at the end of the day.  I think the breaks are also a way to let your "left brain" (or is it your "right brain"?) work on the problem, which should help you when you are stuck, or even prevent you from getting stuck in the first place.


问:
What are the common mistakes in 'tailored Scrum approaches'?
I have seen this before. Management wants to be agile and be scrummified, but does not want to step out of the status quo. My latest observation is no different; here, the Scrum is 'tailored' to the organization; specifically into a weird many-people-process.

Here http://img684.imageshack.us/img684/6175/modifiedscrum.jpg

The diagram showing the different participants.

I am putting together a document listing why this will not work. Here are the obvious ones:

1. There are product owner agents (an obvious WTF), who report to the product owner: causing dilution of decision making capability

2. There is a role that looks similar to a manager in the traditional approach - development manager: an obvious attempt at command-and-control model

3. The ScrumMaster's role includes collecting timesheets, which are used to track progress instead of burndown charts: detrimental to agile's efforts to build teams with motivated individuals

Leaving the question "how would you convince the management?", my question is more at, "what else do you see as failures in this/similar 'tailored Scrum approaches'?

EDIT: The diagram might use a few more details

1. The development manager is not part of the development team, with not very clearly defined responsibilities, except: developer performance assessemnt, recruitment, etc.,

2. There are more than two teams (with ScrumMaster+development manager+dev team) with the same product owner for all teams!

答:
The Development Manager and to some extent the ScrumMaster are variations of the traditional role of the tech lead.  I don't see the Development Manager necessarily having any more or less command and control as you put it than a typical tech lead.

The Scrum Master is a little bit more special than that though.  The Development Manager shouldn't also be the Scrum Master but there is no reason why the Scrum Master couldn't just be the PM anyway since they have the most interest in timesheets.  Tracking time on a project schedule is not disjoint with the concept of User Stories, Points and Burndown Charts.

You do kind of have a point about the Product Owner Agent role.  I don't see a person in that role having any clear unique responsibility other than being an additional link in the chain of command.

The Product Owner is ridiculously important though.  He owns the product.  I am not going to explain the importance of it but if you have ever worked on a project where there was no clear product owner because the middle managers were too chicken-$$$$ to take any ownership of the PRODUCT direction and decisions regarding the PRODUCT then you will see how it completely sabotages all projects before they even start.


问:
"Dedication of the Harvard Mark I computer, 1944 August 7"- Which text is Brooks referring to and where can I find it?
I am reading the epilogue of the Anniversary Edition of the Mythical Man Month. The author, Frederic Brooks, says

Still vivid in my mind is the wonder and delight with which I - then 13 years old - read the account of the August 7, 1944, dedication of the Harvard Mark I computer...

Which text is he referring to?

I want to be filled with wonder and delight too. Where can get hold of this text so that I can read it too?

答:
J.A.N. Lee, Department of Computer Science, Virginia Tech. writes:

Preparing for the Monday, August 7, 1944, dedication, the Harvard News Office prepared a news release titled "World's Greatest Mathematical Calculator," followed by the bold, unqualified statement that "In charge of the activity . . . is the inventor, Commander Howard H. Aiken, USNR," who "worked out the theory which made the machine possible."

(emphasis mine)

Also a good read: Aug. 7, 1944: Still a Few Bugs in the System, on Wired. I can't find anything closer to the original text, the wikipedia entries on Mark I and Howard Aiken don't reference it.

Update #1: The original text seems to be on enotes.com, but you need to subscribe to access it.

Update #2: Brooks refers to the Harvard News Office press release he read on Time Magazine, as he writes on page 137 of Makin' numbers: Howard Aiken and the computer.


问:
generic programming- where did it originate?
Im trying to work out if generic programming was a functional programming feature which was then introduced into Java, C++ and C# or did the latter copy it from the functional programming languages like Haskell, Lisp, OCaml etc?

Google is giving me lots on what generic programming is, but not where it originated. All I can see is that Ada implemented it early on.

Would you class it as a functional programming technique?

答:
According to the Wikipedia article it stems from Ada and/or CLU (both of which are object oriented programming languages):

This approach, pioneered by Ada in 1983, permits writing common functions or types that differ only in the set of types on which they operate when used,

[...]

Generic programming facilities first appeared in the 1970s in languages like CLU and Ada

OwnerDisplayName: aioobe


答:
Like for many great ideas in computing, any "first" you can identify probably wasn't the actual first use.  For example, Christopher Strachey discusses the idea (under the label "polymorphism") in his influential 1967 lecture notes without giving attributions so the idea is likely to have been well known by that time.

At that time, there was no great split between functional and object-oriented programming.

Title: generic programming- where did it originate?

Body:
Im trying to work out if generic programming was a functional programming feature which was then introduced into Java, C++ and C# or did the latter copy it from the functional programming languages like Haskell, Lisp, OCaml etc?

Google is giving me lots on what generic programming is, but not where it originated. All I can see is that Ada implemented it early on.

Would you class it as a functional programming technique?

OwnerDisplayName: ibid


答:
My personal experience is that .NET is dominant in in-house, enterprise-level development. Most of these applications are not build for public consumption and so are not a part of our everyday vocabulary.

Still, there is a very compelling reason that so many large companies have adopted these technologies: programmer productivity and happiness. C# is a wonderful, productive programming language and the .NET ecosystem is rich with existing libraries to keep us having having to reinvent wheels. Also, WCF, while astoundingly complicated at times, is a very powerful framework for building communications between different systems.

In regard to your specific circumstance, I would only undertake the porting of your application if you will be doing lots of enhancements and changes to it in the future. If it is stable and in maintenance mode, you will regret any decision besides leaving it as-is.


答:
Polymorphic data types had been around since early 1970s (with the introduction of ML language and Hindley-Milner algorithm).

A more generic form, Lisp macros, had been around since 1960s.


答:
You need them to differentiate how the company is structured and how the people in a scrum development process are structured. This is fine for an org chart.

For a very large ERP project, you could have nearly separate section that have their own product owners. They may report to someone, but from the Scrum perspective, there needs to be one product owner working with the group assigned to that part of the project.

The development manager is more the person who may do the evaluations, organizing days off schedules and other manager duties that have nothing to do with development.

Just show them how you separate the two. No reason small scrum groups can't exist in a large corporation. You have to know where people fit in both worlds.

Title: What are the common mistakes in 'tailored Scrum approaches'?

Body:
I have seen this before. Management wants to be agile and be scrummified, but does not want to step out of the status quo. My latest observation is no different; here, the Scrum is 'tailored' to the organization; specifically into a weird many-people-process.

Here http://img684.imageshack.us/img684/6175/modifiedscrum.jpg

The diagram showing the different participants.

I am putting together a document listing why this will not work. Here are the obvious ones:

1. There are product owner agents (an obvious WTF), who report to the product owner: causing dilution of decision making capability

2. There is a role that looks similar to a manager in the traditional approach - development manager: an obvious attempt at command-and-control model

3. The ScrumMaster's role includes collecting timesheets, which are used to track progress instead of burndown charts: detrimental to agile's efforts to build teams with motivated individuals

Leaving the question "how would you convince the management?", my question is more at, "what else do you see as failures in this/similar 'tailored Scrum approaches'?

EDIT: The diagram might use a few more details

1. The development manager is not part of the development team, with not very clearly defined responsibilities, except: developer performance assessemnt, recruitment, etc.,

2. There are more than two teams (with ScrumMaster+development manager+dev team) with the same product owner for all teams!


答:
It's actually not that far off. It depends on what certain people's roles are.

There can be more than one person in a team that fills the role of Product Owner (as in the decision-making entity that is responsible for requirements generation, prioritization and acceptance). On large projects one person simply cannot do it all. What is important is that there is a single communications path to and from the Product Owner, to which questions are directed and from which requirements directives come, however many people are behind them (or even in front of them) assisting with the process. In short, there should always be one guy you can call with a question, no matter who he talks to to get the answer or who he communicates the answer through. So, if the Agent is simply someone from the Product Ownership "team" who participates as a chicken in the IPMs and daily standups, and reports back to the PO, that's fine; the PO cannot be everywhere. If this is a person capable of making decisions independently of other agents or the Product Owner, or who is designed to restrict access to the PO, THAT can be a problem.

Development Manager sounds like either "Project Manager" or "Team Lead" to me. It could also be "Architect", which is the guy responsible for maintaining a good design structure and deciding the enterprise-level patterns to follow in developing certain areas. There's usually only one Architect, like there's only one Product Owner, so if this guy is a "Project Manager" or "Architect" role it should be a cross-team job, not one per.

I don't see BAs in this chart. At my last Agile job, BAs received and reviewed the raw stories, determined dependencies that would create schedule conflicts and a "critical path", and usually also did some QA. They were also the ones on the phone the most with the PO. That freed the coding teams to do what they do best - heads-down coding.

The idea of timesheets as opposed to a burndown to track progress does seem odd. It sounds like the contract was negotiated for time and materials, and they want TIME, not an estimate of time based on points complexity. That's fine, to a point, but the point of Agile is that your clients would rather pay per-point instead of per-hour; a point is a calibratable unit of work, and when its done you have a real product that should be worth that amount as a fraction of the whole project.


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

答:
• Surroundings that harmonize with him/her. This includes what has been mentioned before. Next to nothing cuts down productivity as bad as feeling like you're a rare type of lizard in a terrarium. If you feel at home, you get going ;)

• All the Software required plus some stuff to take away the hassle:

Current IDE and Equipment

Bug Tracker

Wiki

• Project leads that know their job : Have the developers develop, the help-deskers support. Period.


答:
I don't think that is is obvious that things would fail.

There are product owner agents (an obvious WTF), who report to the product owner: causing dilution of decision making capability

Assuming that someone needs to represent customer (in case where real customer is absent) this is not a goof up. However, the criteria of success is the visualization of real customer needs.

There is a role that looks similar to a manager in the traditional approach - development manager: an obvious attempt at
  command-and-control model

This happens usually where a traditional tech guy is a not senior enough (or known to be good enough to do project manager but knows most tech stuff better than most. (unless it is other way). Real difference comes on the basis as to what they actually do.

The ScrumMaster's role includes collecting timesheets, which are used to track progress instead of burndown charts: detrimental to
  agile's efforts to build teams with motivated individuals

This is sounds surprising though. However, i believe most traditional software companies cannot get rid of timesheet. Donno why. But there is no alternative to tracking the project from the point of view of

There are few criteria that will make or break things.

The real challenges in Agile is not process and accuracy with which one adheres to it. The real challenge is when you begin pure ritual rather than helping to simplify processes for developers so that they can concentrate on what they do good - programming!

Getting to know the real need and iteratively going better at it. What you need is to get clarity (and transparency) across all people and personal commitment from all to get to achieve the right targets.

Of course, there are 12 core principles that you should know. My point is stick to those core concept - you can make agile work under any organization structure.

If this basic things fail, everything will fail - else all else is good.


问:
Where to go from here, how to improve / learn more

Possible Duplicate:

  I'm graduating with a Computer Science degree but I don't feel like I know how to program

I finished University around 4 years ago double degree in Software Eng/Comp Sci. Got my first job at a startup in my final year, was with them for 2.5 years then started my own business.

So far everything is going great, lots of clients and stead work etc, but coming right out of uni and into a start up I never had any form or senior software engineer guiding my work or suggesting improvements etc...

Whats the best way for me to improve & learn more? Books? MS Exams? Other?

I develop in C#, ASP.NET/MVC.

Update
The problem isn't really with releasing products, I've released quite a few which are up and running with customers happy. It's more with quality of code, best practices, how do I know something I am code is correct, it may work but there may be ways of coding it much more efficiently or by adhering to some kind of standard

Cheers for any responses!

Matt

答:
Don't wait for senior software engineer guiding you. They are either not good or they are very busy! (if they are good).

If you genuinely want to learn something, i suggest you take up a hobby project on your own - and put it open source!

You will gain following:

With freedom and interest - you will pick a subject to learn about something.

As you try to put a whole product together - you will inevitably learn the real significance on how design and architecture work.

As you collaborate with people - you will get people's feed back on what is really important.

If you happen to built few iteration of work and release code- you will learn principles of software development process.

Of course, other rewards are all out there -if your product is some good.

EDIT:

Given your comment, i felt i have been a bit biased. But if you have been through the process of making a whole product - than it is time look something bigger and deeper. I guess, now i knew what you are asking for.

I would suggest following area to master - and leave upto you how you plan/implement your learning.

Getting to know more about broader perspective in Software Architecture - i know so many people would recommend that and i am not going to over emphasis. But i think the point i am making is to look at Architect role to visualize how things evolve when product grows big. Lots of literature are out there pick anything to start with- but this is very crucial step that will transform you.

Getting to know many other technology aspects - have you been curious about how - OS kernel, Database, Java or .NET run time, File systems, Web servers, browsers, distributed systems,  - the daily stuff we use- how does it work from inside? How is their architecture? what are the key design criteria.

Learn about technology adoption process. Many people will differ on individual opinions if you ask why would JAVA or .NET is better and why did CORBA never achieved what web-services did, and whether Android will overshadow (or kill) iPhone upcoming generations. As engineers who are so busy thinking how stuff works - we often need to get above and see deeply as to why certain things work in life and why not.

All of these would need you to pick specific topics of your interest and get little more than web crawling to get down to reading books or go deep in the subject.

I know i have give you rather broad answers than specific tips/pointers - but that's precisely the idea.


问:
Why use sealed instead of static on a class?
Our system has several utility classes.

Some people on our team use (A) a class with all-static methods and a private constructor.

Others use (B) a class with all-static methods (these the juniors).

On code analysis, (A) and (B) raise warning CA1052, which recommends marking the class as sealed.

Included in the MSDN documentation there is the following advice:

If you are targeting .NET Framework 2.0 or earlier, a better approach is to mark the type as static.

Why does this make any sense? I would have thought the opposite; AFAIK, previous to 2.0 there was no way to mark a class as static.

答: The CA1052 warning is a little off-target.  You should declare classes that contain only static members as static rather than sealed.  Classes declared static are implicitly sealed.</p>


答:
Moved from the comments...

Have you considered giving it a go and seeing how it works before lobbying against it? As long as they are open to adapting the structure over time I don't see any fatal flaws in this plan other than that it doesn't follow the Agile dogma to the letter.

Another thing to consider is that you want to incorporate enough of the business leader's ideas into the approach so they feel ownership in the Agile adoption. If they do, they will be vested in making sure it succeeds instead of disparaging it (because their approach would have been better) if things get sideways. And it will inevitably go sideways, especially at first. People are usually resistant to change and are often clumsy for a while when they are forced to adopt a new way of doing things.

Make management a partner in the process not an adversary.


答:
Here are a couple suggestions:

Co-Working: As a developer, co-working has been awesome for me.  It's essentially rented, shared, open office space (here's my local one: http://sparkplaza.com/) where you could work.  You'll find a LOT of developers that are freelance work at places like this.  It's a good way if you're working on your own to be able to work in the same office with others.  Impromptu code reviews are not uncommon, and the community there can help you talk out ideas and architectures and code.

StackOverflow: Answering questions for other people, or even looking at questions and answers will give you new perspectives on things and help you broaden what you're exposed to.

Contribute to a popular open source project - Having a few open source projects my self, and starting most of them, you don't get a lot of feedback starting your own project (unless it gets amazing traction).  You should provide a bug fix or enhancement to an existing project and one that you aren't the head of and need approval for a check-in.  This will force  feedback from the project owners, who can say "great job!" or "this bit of code right here can be better, I suggest this.."

Title: Where to go from here, how to improve / learn more

Body:
Possible Duplicate:

  I'm graduating with a Computer Science degree but I don't feel like I know how to program

I finished University around 4 years ago double degree in Software Eng/Comp Sci. Got my first job at a startup in my final year, was with them for 2.5 years then started my own business.

So far everything is going great, lots of clients and stead work etc, but coming right out of uni and into a start up I never had any form or senior software engineer guiding my work or suggesting improvements etc...

Whats the best way for me to improve & learn more? Books? MS Exams? Other?

I develop in C#, ASP.NET/MVC.

Update
The problem isn't really with releasing products, I've released quite a few which are up and running with customers happy. It's more with quality of code, best practices, how do I know something I am code is correct, it may work but there may be ways of coding it much more efficiently or by adhering to some kind of standard

Cheers for any responses!

Matt


答:
I've seen a good number of utility classes in the pre-2.0 era which have all static methods and a private default constructor to make it non-instantiable.  Even back then though, that class should have been sealed.

2.0 and later, simply mark the class as static and be done with it.

Title: Why use sealed instead of static on a class?

Body:
Our system has several utility classes.

Some people on our team use (A) a class with all-static methods and a private constructor.

Others use (B) a class with all-static methods (these the juniors).

On code analysis, (A) and (B) raise warning CA1052, which recommends marking the class as sealed.

Included in the MSDN documentation there is the following advice:

If you are targeting .NET Framework 2.0 or earlier, a better approach is to mark the type as static.

Why does this make any sense? I would have thought the opposite; AFAIK, previous to 2.0 there was no way to mark a class as static.


问:
Single Responsibility Principle Implementation
In my spare time, I've been designing a CMS in order to learn more about actual software design and architecture, etc.

Going through the SOLID principles, I already notice that ideas like "MVC", "DRY", and "KISS", pretty much fall right into place. That said, I'm still having problems deciding if one of two implementations is the best choice when it comes to the Single Responsibility Principle.

Implementation #1:

```<code>class User
    getName
    getPassword
    getEmail
    // etc...

class UserManager
    create
    read
    update
    delete

class Session
    start
    stop

class Login
    main

class Logout
    main

class Register
    main
</code>```

The idea behind this implementation is that all user-based actions are separated out into different classes (creating a possible case of the aptly-named Ravioli Code), but following the SRP to a "tee", almost literally.

But then I thought that it was a bit much, and came up with this next implementation

```<code>class UserView extends View
    getLogin //Returns the html for the login screen
    getShortLogin //Returns the html for an inline login bar
    getLogout //Returns the html for a logout button
    getRegister //Returns the html for a register page
    // etc... as needed

class UserModel extends DataModel implements IDataModel
    // Implements no new methods yet, outside of the interface methods
    // Haven't figured out anything special to go here at the moment
    // All CRUD operations are handled by DataModel
    //   through methods implemented by the interface

class UserControl extends Control implements IControl
    login
    logout
    register
    startSession
    stopSession

class User extends DataObject
    getName
    getPassword
    getEmail
    // etc...
</code>```

This is obviously still very organized, and still very "single responsibility". The User class is a data object that I can manipulate data on and then pass to the UserModel to save it to the database. All the user data rendering (what the user will see) is handled by UserView and it's methods, and all the user actions are in one space in UserControl (plus some automated stuff required by the CMS to keep a user logged in or to ensure that they stay out.) I personally can't think of anything wrong with this implementation either.

In my personal feelings I feel that both are effectively correct, but I can't decide which one would be easier to maintain and extend as life goes on (despite leaning towards Implementation #1.)

So what about you guys? What are your opinions on this? Which one is better? What basics (or otherwise, nuances) of that principle have I missed in either design?

答:
"Single Responsibility Principle" is not the same as "Single Functionality Principle"

Many a times - when we try to do this as religiously as possible - we tend to "break" classes a bit too much and we may still violate SRP somehow because now each object might need to know something about the other that becomes an extra reason for change.

I am not very clear about the intention of above classes but i guess here are few points -

I don't know if login and logout can be truely independent of each other and whether either of them can be independent of session

I don't know whether you would regard login and logout as classes or methods and why.

I don't know whether UserManager doing create is any different form  new user()

I guess i am completely wrong in many things because i have not truly understood the entire thing. The second one is a little better than first but i may still be wrong.

But that is precisely the point - by looking at the classes the intentions are note very clear - the sign that SRP is not quite working here.


答:
we cannot come up with main stream programs that seem to be written in
  .Net.

I'm pretty sure the ATI Catalyst graphics card control panel is written in .NET - so that's basically every PC which has an ATI graphics card. Big numbers of normal desktop users...

Another good example is Samsung Kies - which most people who have Samsung phones have installed..