答:
OO is usually "defined" in terms of four basic requirements:

Abstraction means you're able to separate an objects externally visible behavior from its implementation.

Encapsulation means being able to hide the details of the implementation of an object (so closely related to abstraction that some authors treat them as one, leaving only three major requirements).

Modularity means being able to package abstractions into discrete units.

Hierarchy is a ranking or ordering of abstractions -- an ability to define the relationship between one abstraction and another.

I, for one, would consider a language object oriented if it supports these four major requirements. Supports, however, goes a bit beyond "allows" or "tolerates".

C, for example, provides enough flexibility that you can simulate each of these reasonably well. C, however, provides only a little support for abstraction or modularity, and none at all for encapsulation or hierarchy -- you can do these things if you want to badly enough, but the language doesn't really provide any direct support for them.

C++, for an obvious comparison does provide direct support for each of these requirements. Just for example, encapsulation is directly supported by making class members private and/or protected and hierarchies are supported via class inheritance.

That's still not what would normally be called a "pure" object oriented language though. In a pure OO language (e.g., Smalltalk), you not only get support for hierarchy, but you get a pre-defined hierarchy of types, and you have to define the relationship of any new type to some existing type in that hierarchy (i.e., all your code most be in classes, and each class must derive from some existing one).

Although classes and inheritance are both common to many implementations of object orientation, neither is really necessary to it. Just for example, Self and JavaScript both use exemplar-based hierarchies. Instead of a hierarchy of classes, with each object an instance of a class, these just use a hierarchy of objects, with each based on some other object, but modified to some arbitrary degree.


问:
How to minimize typos when you code?
I make a lot of typing mistakes when I program. I have a good keyboard writing speed but I try to write faster and in the process end up making typos.

I want to type faster, but make less errors. Can I do something to improve the situation?

答:
I don't recommend to widely depend on IDEs. Of course they're really good helpers but still you should be able to work within any environment as needed. So making typos is a general problem instead peculiar to coding. One should fix this problem making practices at least 30min a day. Typing won't help if you don't do it to improve yourself. You should find techniques which can help you to improve it otherwise you will end up making mistakes for the rest of your programming life. You should teach your brain how to type faster and better than that, effectively.

And I also agree with the answer mentioned here https://softwareengineering.stackexchange.com/a/140182/3613 and one should slow down when making mistakes goes crazy and make a rescan your memory, check the keyboard again and let your brain re-visualize the location of the keys and besides give yourself a break. As your brain gets tired, it will start coming off and it becomes not just typing problem and also focusing problem and it means bugs are on the way to invade your codes.

But remember sometimes focusing too much on the keys and what's coming from your brain (code statements) can hurt your brain and make you feel tired even earlier and faster so as I mentioned giving a break is a the key thing here.

ContentLicense: CC BY-SA 3.0

Title: How to minimize typos when you code?


问:
Criteria for a language to be considered "object oriented"
I had a discussion about OO programming today and by browsing the internet I found a lot of different specifications for object oriented languages.

What are the requirements for a language to be object oriented? For myself an object oriented language must have classes, inheritance and encapsulation.

Is C an object oriented language just because you can use structs and program with an object oriented design? Why/ why not?

Are there any good sites/articles about this? And please, no Wikipedia links because I've already been there.

答:
According to Rumbaugh et al., "Object-Oriented Modelling and Design", objects
are characterized by the following features:

Identity: data is quantized into discrete, distinguishable entities, called objects.

Classification: objects with the same structure and behaviour are grouped together to form classes.

Polymorphism: the same operation (an operation with the same name) may behave differently on different classes.

Inheritance: sharing of attributes and operations among classes based on a hierarchical relationship.

According to this definition, an OO-language should support these concepts natively. In C you can define struct's which share structure, but not behaviour (structure classification without behaviour classification). You can define identity by means of handles to data objects (pointers). Polymorphism and inheritance are missing altogether and must be implemented through ad-hoc techniques.

So, according to these criteria, C is not an object-oriented language. Using some ad-hoc techniques you can implemented and object-oriented design in C, but C does not have enough concepts to support it directly.


问:
Is it a waste of time to free resources before I exit a process?
Let's consider a fictional program that builds a linked list in the heap, and at the end of the program there is a loop that frees all the nodes, and then exits. For this case let's say the linked list is just 500K of memory, and no special space managing is required.

Is that a waste of time, because the OS will do that anyway?

Will there be a different behavior later?

Is that different according to the OS version?

I'm mainly interested in UNIX based systems, but any information will be appreciated. I had today my first lesson in OS course and I'm wondering about that now.

Edit: Since a lot of people here are concerned about side effects, and general 'good programming practice' and so. You are right! I agree 100% with your statements. But my question is only hypothetical, I want to know how the OS manages this. So please leave out things like 'finding other bugs when freeing all memory'.

答: Almost always yes. Free shared-memory semaphores and UDP server resources (the OS doesn't know how to notify connected UDP servers that you're done).</p>


问:
Odd company release cycle: Go Distributed Source Control?
Sorry about this long post, but I think it is worth it.

I have just started with a small .NET shop that operates quite a bit differently to other places that I have worked. Unlike any of my previous positions, the software written here is targeted at multiple customers and not every customer gets the latest release of the software at the same time. As such, there is no "current production version." When a customer does get an update, they also get all of the features added to the software since their last update, which could be a long time ago. The software is highly configurable and features can be turned on and off: so called "feature toggles." Release cycles are very tight here, in fact they are not on a schedule: when a feature is complete the software is deployed to the relevant customer.

The team only last year moved from Visual Source Safe to Team Foundation Server. The problem is they still use TFS as if it were VSS and enforce Checkout locks on a single code branch. Whenever a bug fix gets put out into the field (even for a single customer) they simply build whatever is in TFS, test the bug was fixed and deploy to the customer! (Myself coming from a pharma and medical devices software background this is unbelievable!). The result is that half baked dev code gets put into production without being even tested. Bugs are always slipping into release builds, but often a customer who just got a build will not see these bugs if they don't use the feature the bug is in. The director knows this is a problem as the company is starting to grow all of a sudden with some big clients coming on board and more smaller ones.

I have been asked to look at source control options in order to eliminate deploying of buggy or unfinished code but to not sacrifice the somewhat asynchronous nature of the teams releases.  I have used VSS, TFS, SVN and Bazaar in my career, but TFS is where most of my experience has been.

Previously most teams I have worked with use a two or three branch solution of Dev-Test-Prod, where for a month developers work directly in Dev and then changes are merged to Test then Prod, or promoted "when its done" rather than on a fixed cycle. Automated builds were used, using either Cruise Control or Team Build. In my previous job Bazaar was used sitting on top of SVN: devs worked in their own small feature branches then pushed their changes to SVN (which was tied into TeamCity). This was nice in that it was easy to isolate changes and share them with other peoples branches.

With both of these models there was a central dev and prod (and sometimes test) branch through which code was pushed (and labels were used to mark builds in prod from which releases were made...and these were made into branches for bug fixes to releases and merged back to dev). This doesn't really suit the way of working here, however: there is no order to when various features will be released, they get pushed when they are complete.

With this requirement the "continuous integration" approach as I see it breaks down. To get a new feature out with continuous integration it has to be pushed via dev-test-prod and that will capture any unfinished work in dev.

I am thinking that to overcome this we should go down a heavily feature branched model with NO dev-test-prod branches, rather the source should exist as a series of feature branches which when development work is complete are locked, tested, fixed, locked, tested and then released. Other feature branches can grab changes from other branches when they need/want, so eventually all changes get absorbed into everyone elses. This fits very much down a pure Bazaar model from what I experienced at my last job.

As flexible as this sounds it just seems odd to not have a dev trunk or prod branch somewhere, and I am worried about branches forking never to re-integrate, or small late changes made that never get pulled across to other branches and developers complaining about merge disasters...

What are peoples thoughts on this?

A second final question: I am somewhat confused about the exact definition of distributed source control: some people seem to suggest it is about just not having a central repository like TFS or SVN, some say it is about being disconnected (SVN is 90% disconnected and TFS has a perfectly functional offline mode) and others say it is about Feature Branching and ease of merging between branches with no parent-child relationship (TFS also has baseless merging!). Perhaps this is a second question!

答:
Unfortunately, there is no known solution to bugs in code :)

So you're just looking to stop unfinished checkins from being caught up in the main release, and the only answer to that is branch-work-merge for each developer. I did this in a previous company using Clearcase, it worked quite well (even though we had to have a dozen clearcase admins).

Now, I assume also that you perform bug fixing on the version of the product that each customer currently has... so you have a merge issue bringing bugfixes from version A all the way through to version Z. There's no easy way to deal with this, but you will have to have a branch for each shipped version. The best way to deal with this is to keep feature branches on the latest version only, and make customers upgrade to get the new features, at the same time, perform bugfixing directly on the release branch and merge them upwards to all the other release branches when complete.

Not too nice, but it can work remarkably well. You keep the code organised and nicely separate. Its also easy to understand for the other devs - small bugfixes directly on "the code", anything more than a couple of lines gets done on a dedicated branch where they can take as long as they like to complete it. (you will have to sort out the merge issues and reassure them that it's ok if 2 devs work on 2 features at the same time!!)

After a while you can introduce feature branches on the release branches too, where bugs are fixed then merged in, but IMHO this is typically more effort than needed. If you need to add features to old releases though, then you'll need to follow this approach - branch ff a release branch, then merge the code back onto that release, and merge the change upwards to the later releases too. That will make your test team very unhappy as releases will be heavily delayed due the need to test several versions repeatedly, and the dev team unhappy as they will have to do a lot of merging before they can start on new code (in my current company this happens, mainly due to the amount of work we have that always needs to be complete asap).

DVCS:

basically a DVCS is where everyone has their own copy of the server repo. It has some advantages (especially in distributed teams with limited commiuncation), but has some disadvantages too so check them out before you switch to a DVCS. If you're a Windows shop then you'll probably find Mercurial is the best DVCS for you.


答:
I always clean up resources on normal exit. It's a safety check that my resource allocation/deallocation calls are done right. This check has alerted me to hidden bugs on more than one occasion. It's like balancing the books of a business at the end of the day.

There may be edge cases such as @MSalter described in his comment, but even that would generally start me looking at customized memory management, rather than just letting the OS clean up and hoping for the best.

Title: Is it a waste of time to free resources before I exit a process?

Body:
Let's consider a fictional program that builds a linked list in the heap, and at the end of the program there is a loop that frees all the nodes, and then exits. For this case let's say the linked list is just 500K of memory, and no special space managing is required.

Is that a waste of time, because the OS will do that anyway?

Will there be a different behavior later?

Is that different according to the OS version?

I'm mainly interested in UNIX based systems, but any information will be appreciated. I had today my first lesson in OS course and I'm wondering about that now.

Edit: Since a lot of people here are concerned about side effects, and general 'good programming practice' and so. You are right! I agree 100% with your statements. But my question is only hypothetical, I want to know how the OS manages this. So please leave out things like 'finding other bugs when freeing all memory'.


答: The problem is that today it's a linked-list node, and tomorrow, it's a resource the OS can't clean up by itself. Is it fast and safe to leave the OS to clean up heap memory? Yes. But does that make it a good idea? Not necessarily.</p>


问:
How do I improve my ability to manipulate code quickly, not wpm?
I have seen several questions on here about touch typing and words per minute but not about improving ones ability to manipulate text using keyboard shortcuts, bindings etc.

I have tried putting a cheat sheet of keyboard shortcuts next to my monitor but I can never incorporate them in my 'flow'. I have also tried the 'just use vi and don't touch the mouse' method but that only helps me with navigating code and not editing.

I would prefer to use some application (or game) to learn text manipulation. But it looks like nothing like that exists (app idea?). I'm open to other suggestions too.

答:
I have also tried the 'just use vi and don't touch the mouse' method

For how long?  Like touch typing, it will take a while to learn.  But if you stick to it eventually you will stop thinking about individual keystrokes, and just do it.


答:
I have also tried the 'just use vi and don't touch the mouse' method but that only helps me with navigating code and not editing.

This is the most effective method.  If this method only helped you with navigating code, then you must not have tried it for long enough or for enough tasks.

Instead of highlighting a line with the mouse, use Home, Shift+End

Instead of clicking in a line to get the cursor where you want it, get to the line using up and down arrows(or page up & down) and use Ctrl+left & Ctrl+right to navigate to the desired location in the line.

Highlight sections of lines using Ctrl+Shift+left & Ctrl+Shift+right

Instead of cutting and pasting a line to move it, use Alt+up and Alt+down to move the line (this only works in some IDEs).

Memorize all of the shortcuts for things like build, run, test, find, find-in-project, find-replace and USE THEM instead of mousing through menus.

The key is to be consistent and disciplined, denying yourself the use of the mouse for a long period of time.  It will be tedious at first, but sooner or later, you'll stop reaching for it and you'll be able to edit quicker without a mouse than you ever did with it.

Title: How do I improve my ability to manipulate code quickly, not wpm?

Body:
I have seen several questions on here about touch typing and words per minute but not about improving ones ability to manipulate text using keyboard shortcuts, bindings etc.

I have tried putting a cheat sheet of keyboard shortcuts next to my monitor but I can never incorporate them in my 'flow'. I have also tried the 'just use vi and don't touch the mouse' method but that only helps me with navigating code and not editing.

I would prefer to use some application (or game) to learn text manipulation. But it looks like nothing like that exists (app idea?). I'm open to other suggestions too.


问:
What is the name of this tree?
It has a single root and each node has 0..N ordered sub-nodes . The keys represent a distinct set of paths. Two trees can only  be merged if they share a common root. It needs to support, at minimum: insert, merge, enumerate paths.

For this tree:

```
The
 +--------+----------------+
 |        |                |
cat      cow              dog
 +        +--------+       +
 |        |        |       |
drinks   jumps    moos    barks
 +
 |
milk
```

the paths would be:

The cat drinks milk

The cow jumps

The cow moos

The dog barks

It's a bit like a trie. What is it?

答:
This is very close to a Radix tree.  The primary differences are that a normal radix tree wouldn't split on words, so the 'c' in both "cat" and "cow" would be the same node, and it only splits when necessary:

```<code>The
 +-------------------------+
 |                         |
 c                        dog barks
 +---------------+
 |               |
at drinks milk   ow
                 +--------+
                 |        |
                jumps    moos
</code>```

I might describe what you have as a modified Radix tree, that is forced to use spaces as a delimiter.  Regardless, it is some sort of "tree", so that should be sufficient to describe it if you have some extra explanation as to its structure.

Title: What is the name of this tree?

Body:
This is very close to a Radix tree.  The primary differences are that a normal radix tree wouldn't split on words, so the 'c' in both "cat" and "cow" would be the same node, and it only splits when necessary:

The
 +-------------------------+
 |                         |
 c                        dog barks
 +---------------+
 |               |
at drinks milk   ow
                 +--------+
                 |        |
                jumps    moos

I might describe what you have as a modified Radix tree, that is forced to use spaces as a delimiter.  Regardless, it is some sort of "tree", so that should be sufficient to describe it if you have some extra explanation as to its structure.


答:
This is called a "rope" when applied specifically to strings, I believe.

http://en.wikipedia.org/wiki/Rope_(computer_science)

They offer vastly improved algorithmic complexity for many mutating operations over strings-as-arrays.

Title: What is the name of this tree?

Body:
It has a single root and each node has 0..N ordered sub-nodes . The keys represent a distinct set of paths. Two trees can only  be merged if they share a common root. It needs to support, at minimum: insert, merge, enumerate paths.

For this tree:

```
The
 +--------+----------------+
 |        |                |
cat      cow              dog
 +        +--------+       +
 |        |        |       |
drinks   jumps    moos    barks
 +
 |
milk
```

the paths would be:

The cat drinks milk

The cow jumps

The cow moos

The dog barks

It's a bit like a trie. What is it?


问:
What makes an application memory bandwidth bound?
This has been something that's been bothering me for a while: What makes an application memory bandwidth bound?

For example, take this monstrosity of a computer that calculated the 5 trillionth digit of pi (and later 10 trillionth digit). I was surprised that they choose the lower but faster 98 GB RAM at 1066 MHz instead of the larger but slower 144 GB at 800 MHz. This is especially surprising considering they are using 22 TB HD array to store the results from computation; more RAM means less need for hard drives.

Maybe its because I don't write applications for HPC servers, but how would RAM be the bottleneck? Are there any other non-HPC applications that usually run into this problem?

答:
The answer to that is fairly simple: main memory is glacially slow compared to the CPU.  To quote from another question in a related area, approximate speeds for a modern CPU are:

```<code>L1 CACHE hit, ~4 cycles
L2 CACHE hit, ~10 cycles
L3 CACHE hit, line unshared ~40 cycles
L3 CACHE hit, shared line in another core ~65 cycles
L3 CACHE hit, modified in another core ~75 cycles remote
L3 CACHE ~100-300 cycles
</code>```

Then, do the math against the DRAM vs a 2.5GHz CPU: for a single cycle the 800MHz you are talking ~ 3-4 CPU cycles.  Actual timing of memory access is more complex, but adds up to a lot.  The 800MHz RAM there is going to be something like 5-5-5-16, or 124 CPU cycles.

That is still in an ideal world, too: once you add in bus bandwidth, memory contention from multiple accesses to the same chips, cache overheads, and everything else you are talking about access to main memory being thirty to fifty times slower than accessing data in cache.

Disk is, of course, insanely slower.  In the analysis of this problem, the question is if the performance cost - RAM that is 75% the speed - is worth the benefit - caching ~ 70% of the data ahead of disk.

To answer the question about where else you run into this: the most common place would be your graphics card, where memory bandwidth is one of the significant constraints in overall fill rate.  Improvements there help substantially in increasing overall polygon count in games, etc.

Otherwise, you run into this every day, but only in small ways.  You pay that 30-fold cost to write data out to DRAM, and can absolutely see and measure than in all sorts of software that ends up showing a huge performance cliff as the input size increases.  Video compression and image processing are common places that this consideration can result in visible performance changes.

Body:
The answer to that is fairly simple: main memory is glacially slow compared to the CPU.  To quote from another question in a related area, approximate speeds for a modern CPU are:

L1 CACHE hit, ~4 cycles
L2 CACHE hit, ~10 cycles
L3 CACHE hit, line unshared ~40 cycles
L3 CACHE hit, shared line in another core ~65 cycles
L3 CACHE hit, modified in another core ~75 cycles remote
L3 CACHE ~100-300 cycles

Then, do the math against the DRAM vs a 2.5GHz CPU: for a single cycle the 800MHz you are talking ~ 3-4 CPU cycles.  Actual timing of memory access is more complex, but adds up to a lot.  The 800MHz RAM there is going to be something like 5-5-5-16, or 124 CPU cycles.

That is still in an ideal world, too: once you add in bus bandwidth, memory contention from multiple accesses to the same chips, cache overheads, and everything else you are talking about access to main memory being thirty to fifty times slower than accessing data in cache.

Disk is, of course, insanely slower.  In the analysis of this problem, the question is if the performance cost - RAM that is 75% the speed - is worth the benefit - caching ~ 70% of the data ahead of disk.

To answer the question about where else you run into this: the most common place would be your graphics card, where memory bandwidth is one of the significant constraints in overall fill rate.  Improvements there help substantially in increasing overall polygon count in games, etc.

Otherwise, you run into this every day, but only in small ways.  You pay that 30-fold cost to write data out to DRAM, and can absolutely see and measure than in all sorts of software that ends up showing a huge performance cliff as the input size increases.  Video compression and image processing are common places that this consideration can result in visible performance changes.


问:
Why use string.Empty over "" when assigning to a string object
I've been running StyleCop over my code and one of the recommendations SA1122 is to use string.Empty rather than "" when assigning an empty string to a value.

My question is why is this considered best practice.  Or, is this considered best practice?  I assume there is no compiler difference between the two statements so I can only think that it's a readability thing?

SO question and answer

Jon Skeet answer to question

答:
One valid reason is that it makes it clear this is not a typo or placeholder, that you really meant to use the empty string here.

I don't know if it's considered "best practice".


答:
According to some documentation I found, it has to do with what's emitted by the compiler.

A quick search reveals : http://stylecop.soyuz5.com/SA1122.html

Why it's filed under "Readability Rules" with that description is puzzling.

Title: Why use string.Empty over "" when assigning to a string object

Body:
I've been running StyleCop over my code and one of the recommendations SA1122 is to use string.Empty rather than "" when assigning an empty string to a value.

My question is why is this considered best practice.  Or, is this considered best practice?  I assume there is no compiler difference between the two statements so I can only think that it's a readability thing?

SO question and answer

Jon Skeet answer to question


问:
Inheritance versus Composition in a business application
I have a training management and tracking system, with a high level structure as follows:

We have a Role1, e.g. Manager, Shift-boss, miner, etc. and a Candidate, training for that Role. The role has a list of courses and their subjects the candidate needs to complete to qualify for the role. Candidate has a TrainingHistory attribute, containing the courses and subjects they have completed, their results, and the date completed.

Now I see it as a TrainingHistoryCourse is-a Course, extended to add DateCompleted etc. but something is nagging at me to rather use something like a TrainingHistoryRecord that has-a Course. How can I further analyse this to determine which pattern to use?

Then, a Role has a list of RoleTask definitions that the Candidate must be observed practising, and a Candidate has a history of RoleTaskObservation objects recording their performance at these tasks. This is very similar to the course/subject requirement and history pattern for the candidate, except for one less hierarchical level, but, a RoleTaskObservation clearly does not have an is-a relationship with RoleTask, unless I block my nose and rather use ObservedRoleTask.

I would prefer to use the same pattern for both subject/course and task/observation structures, but I think that would force me to adopt a composition pattern for TrainingHistoryCourse. What is the wisdom here? Always inherit where possible and validated by a solid is-a association, or always favour composition wherever possible?

1 Client specified this to be called JobTitle, but he isn't writing the app, and a JobTitle is only one attribute of a Role. Authorization roles are handled by the DevExpress framework and its customization hooks, so there would be very little little confusion between a business Role in my domain objects and an authorization role in lower level, framework code.

答:
You should feel nagged!  Inheritance should only be used if you are introducing a specialization of the parent class.  Aggregation should be used when 1 object consists of another (different) objet to make it whole.

Here is an example of inheritance using your course, as we move right to left we get more specialized.

Course <-- MathCourse <-- Geometry

In this example TrainingHistoryCourse does not make sense because it is not itself a class, rather a notation that someone took a class.

What if we tried to use inheritance?

Course<--MathCourse<--Geometry<--TrainingHistryGeometry

With this approach we would be adding a new TrainingHistory specilization of each class.

Course<--TrainingHistoryCourse<--MathCourse<--Geometry

This approach would make us create a new instance of the Geometry class everytime it is offered.  This could work but we would need a seperate instance of the GeometryClass evertime it is offered.  Which is weird because they are the same class just offerred at different times.

Skip to the chase

In this example it is better to use your TrainingHistoryRecord approach because each student is taking the same class.  You just need to record when it was taken and what their score was.

Some More Examples

You can usually "sound it out" to figure out the best approach

A car is-a vehicle   NOT a car has-a vehicle

A sedan is-a car     NOT a sedan has-a car

A car has-a engine   NOT a car is-a engine

OwnerDisplayName: ProfK


问:
Do you think that exposure to BASIC can mutilate your mind?

It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration

-- Edsger W. Dijkstra

I have deep respect to Dijkstra but I don't agree with everything he said/wrote. I disagree specially with this quote on linked paper wrote 35 years ago about the Dartmouth BASIC implementation.

Many of my coworkers or friends programmers started with BASIC, questions below have answers that indicate many programmers had their first experience on programming at BASIC. AFAIK many good programmers started at BASIC programming.

I'm not talking about Visual Basic or other "modern" dialects of BASIC running on machines full of resources. I'm talking about old times BASIC running on "toy" computer, that the programmer had to worry about saving small numbers that need not be calculated as a string to save a measly byte because the computer had only a few hundreds of them, or have to use computed goto for lack of a more powerful feature, and many other things which require the programmer to think much before doing something and forcing the programmer to be creative.

If you had experience with old time BASIC on a machine with limited resources (have in mind that a simple micro-controller today has much more resources than a computer in 1975, do you think that BASIC help your mind to find better solutions, to think like an engineer or BASIC drag you to dark side of programming and mutilated you mentally?

Is good to learn a programming language running on a computer full of resources where the novice programmer can do all wrong and the program runs without big problems? Or is it better to learn where the programmer can't go wrong?

What can you say about the BASIC have helped you to be a better/worse programmer?

Would you teach old BASIC running on a 2KB (virtual) machine to a coming programmer?

Sure, only exposure to BASIC is bad. Maybe you share my opinion that modern BASIC doesn't help too much because modern BASIC, as long other programming languages, gives facilities which allow the programmer doesn't think deeper.

Additional information: Why BASIC?

答:
BASIC's GOTO is a great way to teach the way of thinking in assembly language. It does not mutilate one's mind, it only brings one's mind further away from carbon-based synapses and closer to silicon-based transistors.

However, let's compare BASIC to LOGO. BASIC can turn young kids away from programming, because to write a simple fun program, all you could do is keep copy-typing a very, very long program printed on a magazine, whereas with LOGO a one-liner can draw very impressive graphics, which is essential in attracting kids.

ContentLicense: CC BY-SA 2.5


答:
I'd imagine there are two reasons, one for readability, and two for a minor performance boost.

Readability is easy: it's a lot quicker to spot string.Empty than "".  Searching for string.Empty is also generally going to be easier and maybe more accurate than looking for the literal.  It also clarifies intent: you didn't just make a typo or forget to finish something, you really did want empty string.

The performance reason is due to interning. You see, the runtime keeps a table of previously used strings so that it can quickly do string comparisons without actually doing a character-by-character check.  string.Empty is already an interned reference to "" where-as typing the literal may not give you the interned version, thus causing a slight performance hit.


答:
It's hard to tell what it means for a language to be object-oriented. Actually, it's hard to tell what it means for a language to be X, where X can be OO, FP, anything.

The official definition of Object-Orientation is

messaging,

local retention and protection and hiding of state-process, and

extreme late-binding of all things

But note that this describes properties of a program, not a language.

Personally, I would say that a language is object-oriented if it facilitates and encourages building programs that satisfy the above definition. Saying that a language is OO if it allows that, is pointless: every Turing-complete language allows everything. The question is: how easy is it to use?

C certainly allows functional programming. And object oriented programming. And logic programming. But none of these is easy in C, nor does C facilitate or encourage programming in those styles.

Also, note that the above definition doesn't mention anything about classes. Why would it? After all, it's called OOP, not COP. In fact, it doesn't even mention objects! Alan Kay himself says that he regrets calling it object-oriented, and that he should rather have called it message-oriented instead, since the important thing are messages, not objects (and certainly not classes).

Title: Criteria for a language to be considered "object oriented"

Body:
I had a discussion about OO programming today and by browsing the internet I found a lot of different specifications for object oriented languages.

What are the requirements for a language to be object oriented? For myself an object oriented language must have classes, inheritance and encapsulation.

Is C an object oriented language just because you can use structs and program with an object oriented design? Why/ why not?

Are there any good sites/articles about this? And please, no Wikipedia links because I've already been there.


问:
Is there such a thing as a super programmer?
Have you come across a super programmer? What identifies him or her as such, compared to "normal" experienced/great programmers?

Also. how do you deal with a person in your team who believes he is a super programmer? Both in case he actually is or if he isn't?

Edit: Interesting inputs all round, thanks. A few things can be gleaned:

A few definitions emerged. Disregarding too localised definitions (that identified the authors or their acquaintance as super programmers), I liked a couple definitions:

Thorbjørn's definition: a person who does the equivalent of a good team consistently for a long time.

Free Electron, linked from Henry's answer. A very productive person, of exceptional abilities. The explanation is a good read.

A Free Electron can do anything when it comes to code. They can write a complete application from scratch, learn a language in a weekend, and, most importantly, they can dive into a tremendous pile of spaghetti code, make sense of it, and actually getting it working. You can build an entire businesses around a Free Electron. They’re that good.

Contrasting with the last definition, is the point linked to by James about the myth of the genius programmer (video). The same idea is expressed as egoless programming in rwong's comment. They present opposite opinions as whether to optimise for such a unique programmer or for a team.

These definitions are definitely different, so I would appreciate it if you have an input as to which is better. Or add your own if you want of course, though it would help to say why it is different from those.

答: Ask the person to write a chapter of himself/herself in the Coders at Work style. Submit it to a publisher. If it gets rejected, then the person is not a super programmer.</p>


答:
cheat sheet of keyboard shortcuts

This stuff is definitely only going to come with practice. If you have to look at a cheat sheet every time you need to look up a shortcut, you'll never remember it. You have to use it lots, if you do it enough, you'll probably end up practically forgetting exactly what the shortcut is, and just do it automatically, much like a good touch typist would probably have to think for a couple of seconds if you asked where a specific character was on the keyboard, even though they'd be able to type it in 0.3s when they weren't thinking about it...

the 'just use vi and don't touch the mouse' method

If you still want to try this approach, and are just looking for a method of getting a better feel for vim editing more quickly, I'd recommend trying VimGolf. It allows you to practice your moves, and see other ways that people get the same job done.


问:
Is there any evidence that graphic interfaces tend to mess with SVN- and Git-repositories?
In my company I am faced with assertion that graphic interfaces for VCSs like SVN or (especially) Git tend to mess repositories - especially regarding branching.

Being a passionate Windows and GUI user, I have a hard time believing this is true.

For Git especially, I accept that some moves are too complex for conduction via a GUI. But what is the real background of this accusation?

答:
Each and every (with small size of assertions) GUI implement two paradigms from triad "Nice - Smart - Fast". In most cases loser is Smart. The more complex the original system loses more in GUI boundaries and metaphors. Manual for Git is a must, thus - in the Procrustean bed of GUI it lost most part of functionality, compared to other VCS.

Another side is users. Because GUIs (see above) give impression of fast start and easy usage and hide some amount of information from end-user some noobs see no need to study, RTFM and STWF: "because it works even now!" unless "SHIT HAPPENS! Oh, it's a bad program" tells lazy, stupid, illiterate and noisy "monkey with grenade" (see at most git-boys here, on SE - no RTFM, no local search)

Assertion is right from the side "GUI mess..."; and is wrong from another side: in determining the cause and effect relations and subject-object nature.

Statistically and logically not GUI, but users of... tend to mess, as they tend to mess any complex task in any area


问:
How do you track existing requirements over time?
I'm a software engineer working on a complex, ongoing website. It has a lot of moving parts and a small team of UI designers and business folks adding new features and tweaking old ones. Over the last year or so, we've added hundreds of interesting little edge cases. Planning, implementing, and testing them is not a problem.

The problem comes later, when we want to refactor or add another new feature. Nobody remembers half of the old features and edge cases from a year ago. When we want to add a new change, we notice that code does all sorts of things in there, and we're not entirely sure which things are intentional requirements and which are meaningless side effects. Did someone last year request that the login token was supposed to only be valid for 30 minutes, or did some programmers just pick a sensible default? Can we change it?

Back when the product was first envisioned, we created some documentation describing how the site worked. Since then we created a few additional documents describing new features, but nobody ever goes back and updates those documents when new features are requested, so the only authoritative documentation is the code itself. But the code provides no justification, no reason for its actions: only the how, never the why.

What do other long-running teams do to keep track of what the requirements were and why?

答:
I am hoping you have some VCS (preferably DVCS) - the commit messages and change logs are a great starting point.

Create Internal Wikis - documents are too heavy weight to be edited and maintained. (Sharepoint 2010 is an exception though, if used right). Strive to keep these updated (it doesn't take much effort) for high level design decisions.

Have a good bug/feature database like JIRA and keep that updated on current work. The best part of this is the history that is provided. Create tasks / bugs by copy pasting mails / from team meeting notes.

Add a ton of code comments, with references to the above bug database.

Review your code using a code review tool, maintaining the cr comments there. Link the JIRA task to this, hence ensuring you can remember your code decisions.

Backup everything! :)


问:
Storing images in file system and returning URLs  or virtually resizing and returning byte arrays?
I need to create a REST web service to manage user submitted images and displaying them all in a website. There are multiple websites that are going to use this service to manage and display images. The requirements are to have 5 pre-defined image sizes available.

The 2 options I see are the following:

The web service will create the 5 images, store them in the file system and and store the URL's in the database when the user submits the image. When the image is requested, the web service will return an array of URLs.

I see this option to be a little hard on the hard drive. The estimates are 10,000 users per site, and lets say, 100 sites. The heavy processing will be done when the user submits the image and each image is going to be pulled from the File System.

The web service will store just the image that the user submits in the file system and it's URL in the database. When the user request images, the web service will get the info from the DB, load the image on memory, create its 5 instances and return an object with 5 image arrays (I will probably cache the arrays).

This option is harder on the processor and memory. The heavy processing will be done when the images get requested.

A plus I see for option 2 is that it will give me the option to rewrite the URL of the image and make them site dependent (prettier) than having a image repository for all websites. But this is not a big deal.

What do you think of these options? Do you have any other suggestions?

答:
I would rather host them on image servers and link to them from databases. Databases aren't very good at handling huge blobs.

For example, if you were using AWS suite, I would say maintain your data (upto 64kb) in DynamoDB and put the actual image in S3. (You can use CDN if geographical distribution/huge availability is necessary). Depending on your database, I would find one such solution.

And yes - ensure the FS is as available as S3, and that you have thought about long term persistence / backup of these as well. When the db gets backed up / restored, the FS has to restore to the same point - else you will see very weird bugs. This is way harder to implement  in practice, if you plan to build this store on your own.


答:
I always though that GUIs encourage people to "just give it a spin" without reading the manual.

Operating svn/git without reading the manual is very akin to operate a machine gun without proper shooting range practice: collateral damages may will ensue.

There's also a problem with vcs savvy people using the command line, wanting nothing to do with the GUI, (Tortoise is so... click-menu-scroll-click-menu-scroll) and thus not helping the vcs gospel spread among the newcomers.

Then there could be an issue with new or external developers working on different platforms (those dang mac people doing iOS apps, or web developing/designing) using a different GUI from the one you use and needing some serious steady fast training that proves harder to impart than originally though.

Title: Is there any evidence that graphic interfaces tend to mess with SVN- and Git-repositories?

Body:
In my company I am faced with assertion that graphic interfaces for VCSs like SVN or (especially) Git tend to mess repositories - especially regarding branching.

Being a passionate Windows and GUI user, I have a hard time believing this is true.

For Git especially, I accept that some moves are too complex for conduction via a GUI. But what is the real background of this accusation?


问:
How can I work efficiently on a desktop sharing workflow?
I am a freelance Magento developer, based in Spain. One of my clients is a Germany based web development company and they're asking me something I think it's impossible. OK, maybe not impossible but definitely not a preferred way of doing things.

One of their clients has a Magento Entreprise installation, which is the paid (and I think proprietary) version of Magento. Their client has forbidden them to download the files from his server. My client is asking me now to study one particular module of the application in order to interact with it from a custom module I'll have to develop.

As they have a read-only ssh access to their client's server, they came up with this solution: Set up a desktop/screen sharing session between one of their developer's station and mine, alongsides with a skype conversation. Their idea is that I'll say to the developer:

show me file foo.php

The developer will then open this foo.php file in his IDE. I'll have then to ask him to show me the bar method, the parent class, etc...

Remember that it's a read-only session, so forget about putting a Zend_Debug::log() anywhere, and don't even think about a xDebug breakpoint (they don't use any kind of debugger, sic). Their client has also forbidden them to use any version control system...

My first reaction when they explained to me this was (and I actually did say it outloud to them):

Well, find another client.

but they took it as a joke from me. I understand that in a business point of view rejecting a client is not a good practice, but I think that the condition of this assignment make it impossible to complete.

At least according to my workflow. I mean, the way I work or learn a new framework/program is:

download all files and copy of db on my pc

create a git repository and a branch

run the application locally

use breakpoints

use Zend_Debug::log()

write the code and tests

commit to git repo

upload to (test/staging first if there is one, production if not) server

I have agreed to try the desktop sharing session, although I think it will be a waste of time. On one hand I don't mind, they pay me for that time, but I know me and I don't like the sensation of loosing my time. On the other hand, I have other clients for whom I can work according to my workflow.

I am about to say to them that I cannot (don't want to) do it. Well, I'll first try this desktop sharing session: maybe I'm wrong and it can actually work. But I like to consider myself as a professional, and I know that I don't know everything. So I try to keep an open mind and I am always willing to learn new stuff.

So my questions are:

Can this desktop-sharing workflow work? What should be done in order to take the most of it?

Taking into account all the obstacles (geographic locations, no local, no git), is there another way for me to work on that project?

答:
When you post a question like that... you are looking for opinions. And you must be open and ready for those opinions... I think this client or webdev company is very closed and back from many freelancers disasters...

But I am agree with you. I we want you to work with you, we must offer the best conditions and fit your minimum requirements to let you do your work as a freelancer.

OwnerDisplayName: OSdave

OwnerDisplayName: ignacioriesco


答:
I understand that in a business point of view rejecting a client is not " good practice "

As you are a freelancer, you get to decide what jobs to take. Rejecting an offer, could lead to bad reputation, but not getting an accepted job done can lead to the same.

On the one hand you have an enterprise who's not afraid to spend a boatload of money to let someone work the way they think is the only way to get the job done.

On the other hand, you sound as though you have a few other gigs, so you can choose your projects.

The question is:

appart from the workflow, can you code the module?

(I'm amazed at the amount of money an enterprise is willing to pay just to conform to compliance rules.)

Title: How can I work efficiently on a desktop sharing workflow?

Body:
I am a freelance Magento developer, based in Spain. One of my clients is a Germany based web development company and they're asking me something I think it's impossible. OK, maybe not impossible but definitely not a preferred way of doing things.

One of their clients has a Magento Entreprise installation, which is the paid (and I think proprietary) version of Magento. Their client has forbidden them to download the files from his server. My client is asking me now to study one particular module of the application in order to interact with it from a custom module I'll have to develop.

As they have a read-only ssh access to their client's server, they came up with this solution: Set up a desktop/screen sharing session between one of their developer's station and mine, alongsides with a skype conversation. Their idea is that I'll say to the developer:

show me file foo.php

The developer will then open this foo.php file in his IDE. I'll have then to ask him to show me the bar method, the parent class, etc...

Remember that it's a read-only session, so forget about putting a Zend_Debug::log() anywhere, and don't even think about a xDebug breakpoint (they don't use any kind of debugger, sic). Their client has also forbidden them to use any version control system...

My first reaction when they explained to me this was (and I actually did say it outloud to them):

Well, find another client.

but they took it as a joke from me. I understand that in a business point of view rejecting a client is not a good practice, but I think that the condition of this assignment make it impossible to complete.

At least according to my workflow. I mean, the way I work or learn a new framework/program is:

download all files and copy of db on my pc

create a git repository and a branch

run the application locally

use breakpoints

use Zend_Debug::log()

write the code and tests

commit to git repo

upload to (test/staging first if there is one, production if not) server

I have agreed to try the desktop sharing session, although I think it will be a waste of time. On one hand I don't mind, they pay me for that time, but I know me and I don't like the sensation of loosing my time. On the other hand, I have other clients for whom I can work according to my workflow.

I am about to say to them that I cannot (don't want to) do it. Well, I'll first try this desktop sharing session: maybe I'm wrong and it can actually work. But I like to consider myself as a professional, and I know that I don't know everything. So I try to keep an open mind and I am always willing to learn new stuff.

So my questions are:

Can this desktop-sharing workflow work? What should be done in order to take the most of it?

Taking into account all the obstacles (geographic locations, no local, no git), is there another way for me to work on that project?

OwnerDisplayName: Huibert Gill


答:
Always free your resources. Freeing all your resources is important because it's the only way of being able to effectively detect leaks. For the project I'm working on I've even got wrappers around malloc/realloc/free to insert canaries, track statistics, etc; simply to detect problems sooner.

However, except for leak detection, for resources that are freed at exit (not before) it is a waste of time. The OS must be able to free it (e.g. in case the process crashes, or even just freeing RAM used for the process' code); and the OS should be able to free it faster than you can from user-space because the kernel will do "wholesale" rather than "piecemeal", and there's less transitions between kernel and process involved.

Fortunately you don't have to choose one way or another. If you want to make sure your code is correct (and you do), but you also want the best possible performance, then do something like:

```<code>#ifndef FAST_EXIT
    free(stuff);
#endif
</code>```

Body:
Always free your resources. Freeing all your resources is important because it's the only way of being able to effectively detect leaks. For the project I'm working on I've even got wrappers around malloc/realloc/free to insert canaries, track statistics, etc; simply to detect problems sooner.

However, except for leak detection, for resources that are freed at exit (not before) it is a waste of time. The OS must be able to free it (e.g. in case the process crashes, or even just freeing RAM used for the process' code); and the OS should be able to free it faster than you can from user-space because the kernel will do "wholesale" rather than "piecemeal", and there's less transitions between kernel and process involved.

Fortunately you don't have to choose one way or another. If you want to make sure your code is correct (and you do), but you also want the best possible performance, then do something like:

#ifndef FAST_EXIT
    free(stuff);
#endif


问:
What are some ways to reliably test for browser support for HTML5 features such as Geolocation?
HTML5 introduces a wide variety of tools such as Geolocation. Many browsers support them, but some do not yet.

Should web developers rely on them to build professional applications for industry? The features are powerful, but not all browsers support these features.

What are some ways (perhaps Javascript libraries?) to reliably test for browser support for HTML5 features such as Geolocation?

答: Modernizr supports detection of many features in HTML5 capable browsers, including geolocation.</p>


问:
Productivity comparision FileNet versus WebSphere Process Server
On one project we are looking at where to implement workflows.

Does anyone have experience with both FileNet and WPS (or know of any studies), that could say anything about the amount of effort required to create a workflow in the 2 products?

答:
Do you mean the old Websphere Process Server or do you mean the current product: IBM Business Process Manager (aka IBM BPM)? Although the latter is the direct successor to the former, the IBM BP is much more focused on speed of development because of the functionality that was added from the Lombardi acquisition. (Disclaimer: I worked for Lombardi so I'm not unbiased in this assessment.)

I know more about IBM BPM than FileNet, but I would generally say that it would vary pretty widely on the type of process you are trying to implement. A project that is very document centric is going to be easier to develop in FileNet. A project that is very integration or human interface centric is going to be easier to develop in IBM Business Process Manager.


问:
Long term plan of attack to learn math?
I am a web-developer with a desire to expand my skill-set to mathematics relevant to programming.

As 2nd career, I am stuck in college doing some of the requirements while working.

I was hoping the my education will teach me the needed skills to apply math, however I am quickly finding it to be too much easily-testable breadth-based approach very inefficient for the time invested.

For example in my calculus 2 class, the only remotely useful mind expanding experience I had was volumes and areas under the curve.  The rest was just monotonous glorified algebra, which while comes easy to me, could be done by software like wolfram alpha within seconds.  This is not my idea of learning math.

So here I am a frustrated student looking for a way to improve my understanding of math in a way that focuses on application, understanding and maximally removed needless tedium.

However I cannot find a good long term study strategy with this approach in mind.

So for those of like mind, how would you go about learning the necessary math without worrying too much about stuff a computer can do much better?

答:
Read Steve Yegge's post on Math for Programmers.

Among his insights:

Math is a lot easier to pick up after you know how to program. In fact, if you're a halfway decent programmer, you'll find it's almost a
  snap.

They teach math all wrong in school. Way, WAY wrong. If you teach yourself math the right way, you'll learn faster, remember it longer,
  and it'll be much more valuable to you as a programmer.

Knowing even a little of the right kinds of math can enable you do write some pretty interesting programs that would otherwise be too
  hard. In other words, math is something you can pick up a little at a
  time, whenever you have free time.

Nobody knows all of math, not even the best mathematicians. The field is constantly expanding, as people invent new formalisms to
  solve their own problems. And with any given math problem, just like
  in programming, there's more than one way to do it. You can pick the
  one you like best.

Math is... actually kinda fun, if you approach it the right way.

Title: Long term plan of attack to learn math?


答:
I'm in a similar boat and so far I'm enjoying www.projecteuler.net:

Project Euler exists to encourage, challenge, and develop the skills and enjoyment of anyone with an interest in the fascinating world of mathematics.

They are problems you solve with programming, but most of the problems aim to teach you (or you have to go learn) some specific math to solve it. Helps you learn titbits of math that you can apply with programming.

Another great resource is http://www.khanacademy.org/#calculus

KhanAcademy is much more than just brilliantly done videos, he also has a whole exercise system to test you out. See http://www.khanacademy.org/about

Title: Long term plan of attack to learn math?

Body:
I am a web-developer with a desire to expand my skill-set to mathematics relevant to programming.

As 2nd career, I am stuck in college doing some of the requirements while working.

I was hoping the my education will teach me the needed skills to apply math, however I am quickly finding it to be too much easily-testable breadth-based approach very inefficient for the time invested.

For example in my calculus 2 class, the only remotely useful mind expanding experience I had was volumes and areas under the curve.  The rest was just monotonous glorified algebra, which while comes easy to me, could be done by software like wolfram alpha within seconds.  This is not my idea of learning math.

So here I am a frustrated student looking for a way to improve my understanding of math in a way that focuses on application, understanding and maximally removed needless tedium.

However I cannot find a good long term study strategy with this approach in mind.

So for those of like mind, how would you go about learning the necessary math without worrying too much about stuff a computer can do much better?


问:
Should one use a separate database for application data and user data?
I’ve been working on a project for a little while and I’m unsure which is the better architecture.  I’m interested in the consensus.  The answer to me seems fairly obvious but something about it is digging at me and I can't pick out what.

The TL;DR is:  how do you handle a program with application data and user data in the same DB which needs to be able to receive updates to the application data periodically?  One database for user data and one for application, or both in one?

The detailed version is.. if an application has a database which needs to maintain application data AND user data, and the user data all references application data, it feels more natural to me to store them in the same database.

But if there exists a need to be able to update the application data within this database periodically, should this be stripped into two databases so that one can simply download the updated application data database file as an update and replace the old one?  Or should they remain as one database, and the application data be updated via a script which inserts the new data into the existing database?  The second sounds clearly preferable to me...  but for some reason just doesn’t feel right, and I can't pick out quite why.

答:
If you ever need to move the application, independently of the user database, then you need a separate database for the application (in whatever form that takes), so that the database can travel with the application, leaving the user data intact in its original location.

It therefore follows that, if the application database is updated periodically from the vendor (that's you), then it needs to be kept separate from the user's database, so that you can distribute changes to the application database without affecting the user database.

Now, if you need to add fields or tables to the user database, that's a different story.  For that, you need a module that can accept as input a table of changes from the application database, to be applied to the user database.  Some programs do this by "converting" the user database to the new format.

Data conversion can be done by using SQL DDL to apply the field and table updates to the user's database, in a way that doesn't negatively affect the user's data.  In some advanced scenarios, data transformations might actually take place; normalization or denormalization, for example.

If you need to provide users with the ability to do a data transfer, you should use some other mechanism such as a communications conduit, or an import/export file containing the data to be transferred (perhaps in XML).


答: I dont think it really matters.  Barring other requirements, as long as you can update the application data as needed, whether its in a separate database or the same one doesnt seem too pertinent.  SQL scripts can drop/reload tables in either case.</p>

Title: Should one use a separate database for application data and user data?

Body:
I’ve been working on a project for a little while and I’m unsure which is the better architecture.  I’m interested in the consensus.  The answer to me seems fairly obvious but something about it is digging at me and I can't pick out what.

The TL;DR is:  how do you handle a program with application data and user data in the same DB which needs to be able to receive updates to the application data periodically?  One database for user data and one for application, or both in one?

The detailed version is.. if an application has a database which needs to maintain application data AND user data, and the user data all references application data, it feels more natural to me to store them in the same database.

But if there exists a need to be able to update the application data within this database periodically, should this be stripped into two databases so that one can simply download the updated application data database file as an update and replace the old one?  Or should they remain as one database, and the application data be updated via a script which inserts the new data into the existing database?  The second sounds clearly preferable to me...  but for some reason just doesn’t feel right, and I can't pick out quite why.


答:
I would look at the coupling.  Does all your data belong together, ie is all the data in the same bounded context (to use domain-driven design terminology)?  If not then you may want to split it out.

For an application the physical location doesn't matter as much as the logical but for maintenance / performance the physical is rather important.

The fact that this bothers you on some level means that the structure may not be comfortable.  Analyse the relationships between the data more closely and make a call.


答:
You're realizing the difference between mathematics and the mathematics they teach you in school.

This is excellently described in A Mathematician's Lament by Paul Lockhart. Similar sentiments are expressed by Conrad Wolfram in his TED Talk, Teaching Kids Real Math with Computers.

Most math you need in "life" was taught in elementary school (like how to calculate a tip in your head). The math you will use in your job might be taught by your university, if you're going into a field which will require calculus or other advanced mathematics - but most programmers don't use calculus everyday (as most programmers end up writing business applications, not some sort of engineering or scientific field).

Regardless, a lot of math you learn won't be applicable to you. And a lot of what you do while learning it is computation. Will it ever be fixed? That's up for you, and the rest of your generation (and all future generations) to decide.

Title: Long term plan of attack to learn math?


答:
Unit Tests are your friend.

One of the main reasons for writing unit tests is to protect your code against future changes. If you have a unit test attached to each required behaviour, then there is no chance that a future enhancement will cause the code to do "weird stuff".

Interestingly, unit tests also become the living documentation that programmers otherwise find so hard to maintain. If you have a unit test called DisableAccountAfterThreeWrongPasswords, then the requirement is captured right there. If you change it in the future to four wrong passwords (say), the test will fail and you will be forced to update it - and presumably the test name as well.

Of course, adding unit tests into a complex legacy system is not easy, and the code usually needs to be architected in a way that makes this feasible. I would start by refactoring the most "rigid" parts of your code and creating tests as you refactor, and then grow your test set as you continue to enhance the application.

Title: How do you track existing requirements over time?

Body:
I'm a software engineer working on a complex, ongoing website. It has a lot of moving parts and a small team of UI designers and business folks adding new features and tweaking old ones. Over the last year or so, we've added hundreds of interesting little edge cases. Planning, implementing, and testing them is not a problem.

The problem comes later, when we want to refactor or add another new feature. Nobody remembers half of the old features and edge cases from a year ago. When we want to add a new change, we notice that code does all sorts of things in there, and we're not entirely sure which things are intentional requirements and which are meaningless side effects. Did someone last year request that the login token was supposed to only be valid for 30 minutes, or did some programmers just pick a sensible default? Can we change it?

Back when the product was first envisioned, we created some documentation describing how the site worked. Since then we created a few additional documents describing new features, but nobody ever goes back and updates those documents when new features are requested, so the only authoritative documentation is the code itself. But the code provides no justification, no reason for its actions: only the how, never the why.

What do other long-running teams do to keep track of what the requirements were and why?


答:
I would consider the term "super programmer" only for those who can do work that usually requires a team of good programmers, and do it consistently for a long time.

This goes both for writing high quality code (documentation, tests etc) and solving very difficult problems requiring a lot of knowledge and talent to solve.

But it requires a high performance on all accounts for a long time.  For those who write tons of code nobody can understand and maintain, the term is not applicable.

How to deal with?  If you truly have such a person then do all you can to provide the scaffolding needed for the person to excel.  This means moving irrelevant stuff out of the way, and provide the resources the person needs.  Please note that I've found that very high performers tend to be humble.

It is, unfortunately, much more likely that you have a person who thinks he is a super programmer and isn't.  The way to deal with those is in my experience to make their performance measurable.  "FindBugs may not find any problems", "All code must have tests corresponding to the use cases", "Peer review".

If the code is truly hard to understand, consider weekly meetings where the not-so-super programmer explains any code the code he's written since the last meeting that anybody can request anonymously to have explained, and anybody can reject anonymously to have accepted in the code base for it to be unmaintainable.  Then at least you have shared the mindset and allowed for future maintainers to veto a piece of code.  This will also strongly indicate to the programmer which kind of code will trigger him having to do extra work.

(EDIT:  The reason for the anonymous bit, is to avoid having the not-so-super programmer retaliate upon those who oppose him).

Title: Is there such a thing as a super programmer?

Body:
Have you come across a super programmer? What identifies him or her as such, compared to "normal" experienced/great programmers?

Also. how do you deal with a person in your team who believes he is a super programmer? Both in case he actually is or if he isn't?

Edit: Interesting inputs all round, thanks. A few things can be gleaned:

A few definitions emerged. Disregarding too localised definitions (that identified the authors or their acquaintance as super programmers), I liked a couple definitions:

Thorbjørn's definition: a person who does the equivalent of a good team consistently for a long time.

Free Electron, linked from Henry's answer. A very productive person, of exceptional abilities. The explanation is a good read.

A Free Electron can do anything when it comes to code. They can write a complete application from scratch, learn a language in a weekend, and, most importantly, they can dive into a tremendous pile of spaghetti code, make sense of it, and actually getting it working. You can build an entire businesses around a Free Electron. They’re that good.

Contrasting with the last definition, is the point linked to by James about the myth of the genius programmer (video). The same idea is expressed as egoless programming in rwong's comment. They present opposite opinions as whether to optimise for such a unique programmer or for a team.

These definitions are definitely different, so I would appreciate it if you have an input as to which is better. Or add your own if you want of course, though it would help to say why it is different from those.


答:
You don't mention what kind of programming you're doing or are interested in. If you're interested in computational sciences, you'll need that calculus background, all 3 semesters, linear algebra, differential equations, numeric analysis, to name a few. Plus you'll need all the requirements for the science, physics, biology, chemistry.  There's another branch of applied mathematics in theory of communication systems. There you'll learn number theory, algebraic coding theory, cryptography, mathematical aspects of systems theory, applied fourier analysis, and there's probably others.

If you're interested in databases like I am, I'm studying Applied Math for Database Professionals. Once I'm done with that, I'll tackle whatever suites my fancy, probably something by C.J. Date, and set and group theory.

To answer your question on how to develop a study plan, research various universities and see what they offer in the areas of computer science or applied math. Universities publish the requirements for the degree. You can probably find all the courses online, usually with videos,  problem sets, and can probably find the book through Amazon. MIT has Open Courseware, Harvard and Berkeley have online courses too. Also checkout OpenStudy, there might be a study group that's formed for the class you'd like to take.

When you need the knowledge and don't want to go into debt for a Master's, self-learning is a great way to go.

Title: Long term plan of attack to learn math?


问:
x86 segmentation and threading
Is some connection between using x86 segmentation and a possible implementation a thread package? I've been told that usually x86 segmentation is implemented in operating systems these days with an identity function (0 offset, unlimited limit), but can segmentation somehow be useful when dealing with multithreading?</p>

答:
AFAIK, Windows is using one segment register to point to the thread specific variable area for the thread.

Note that what is useful here isn't the segmentation -- I think limit and protection are not really used, and IIRC that's the only thing which is now supported in 64 bits mode --, but the fact that segment registers had fell into disuse and so were available to be used simply as base register without impacting existing code.

Title: x86 segmentation and threading


问:
Is it a waste of time to free resources before I exit a process?
Let's consider a fictional program that builds a linked list in the heap, and at the end of the program there is a loop that frees all the nodes, and then exits. For this case let's say the linked list is just 500K of memory, and no special space managing is required.

Is that a waste of time, because the OS will do that anyway?

Will there be a different behavior later?

Is that different according to the OS version?

I'm mainly interested in UNIX based systems, but any information will be appreciated. I had today my first lesson in OS course and I'm wondering about that now.

Edit: Since a lot of people here are concerned about side effects, and general 'good programming practice' and so. You are right! I agree 100% with your statements. But my question is only hypothetical, I want to know how the OS manages this. So please leave out things like 'finding other bugs when freeing all memory'.

答:
Once I had to implement an algorithm using deques which were allocated dynamically. I was also wondering whether I needed to deallocate all the allocated data at exit.

I decided to implement the deallocation anyway and found out that the program crashed during deallocation. By analysing the crash, I found an error in the implementation of the main data structure and algorithms (a memory leak).

The lessons I learnt were:

Always implement deallocation for the data you allocate, this makes it more reusable in case you want to embed your code in a larger system.

Deallocation can serve as an additional check that your allocated data is in a consistent state when it is released.

Just my 2 cents.

EDIT

Small clarification: Of course all memory allocated to a process gets released when the process is terminated, so if the only requirement is to release the allocated memory, doing it explicitly is indeed a waste of time.


答:
Have you come across a super programmer? What identifies him or her as such

From the programs/projects that have create, the source code of it, the study that have done.

believes he is a super programmer

As you say he believes it, this is very difficult to make him not to believe it. The worst think is that that person have been stop to be better programmer because he is think that is all ready is super, and he stop the evolution of him. What worse than that in programming. Anyway, you can always ask for proof... and ask him with whom he/she compare him self to make the assumption that he/she is super.


问:
New Job Over Budget
I recently started a new job as a contract developer, and my non-developer boss of about two weeks ago gave me the task to re-create an app from another language and developer that he will reuse with multiple clients (replacing the front-end), that I estimated would take longer than his estimate of 12 hours.

Two weeks later, I'm 230% over-budget. I admit this was my 2nd web app, I had been a wordpress developer in the past, so I am somewhat new to code igniter, but not shabby php by any means. My boss hired me knowing this and I was clear that it would take longer than his 12 hours. He's seen me in the office on task for 2 weeks, he should be somewhat prepared for this bill.

Do I expect the full amount of hours, or do I filter against how much of learned?
Can I bill for research as a developer?

答:
Just about any application is unrealistic to do in 12 hours, no matter how simple it is. This was an unrealistic estimate given by someone who does not understand the process. This is fine as long as they can accept and learn what the actual process is about.

Do you charge the full amount? Of course you do. It was your time that you used to accomplish a task for someone else. You learned in the process which is good, but programming is a learning process. If all programmers charged only for code written, and excluded learning and research time, all of us would make almost no money.

Many projects in many professions are over budget all the time. If you don't charge the full amount for your time, you will end off out of pocket.

Don't feel guilty about it. Explain to your client. Give him the bill.

Title: New Job Over Budget


答:
http://caniuse.com/ is a good reference for browser support of specific features that you can use in deciding what is possible on the browsers that you need to support.

For specific features detection script is usually fairly easy to write, but there is no indicator of overall HTML5 support.

Another way to look at it is that you can use any feature you want as long as you don't have to support IE - the one major exception is local storage, as Mozilla and  Webkit don't agree on how a database should work.

Title: What are some ways to reliably test for browser support for HTML5 features such as Geolocation?

Body:
HTML5 introduces a wide variety of tools such as Geolocation. Many browsers support them, but some do not yet.

Should web developers rely on them to build professional applications for industry? The features are powerful, but not all browsers support these features.

What are some ways (perhaps Javascript libraries?) to reliably test for browser support for HTML5 features such as Geolocation?


问:
Why is software schedule estimation so hard?

Possible Duplicate:

  Why are software schedules so hard to define?

I often need to explain to senior management why software estimation is so hard, and why our preliminary estimates are often so far out. I suspect some want to know why it is not mathematically precise engineering, like building a bridge.

You can help me by listing a few dot points relevant to this subject. Many thanks!

答:
Software schedule estimation isn't really very hard at all once you have some experience and can base your best guesses on tasks that appear to be similar to something you have done before. So if (as I'm suggesting) it isn't hard to estimate project schedules, why does it seem so difficult?

I'll start by answering the second part of the question first. Why isn't writing software more like bridge building? It's because of the level of input by each of the stake holders, and because of the perception by all involved at the ease with which software can change mid project.  Change the design of a bridge, and you need to factor in significant material costs and the scheduling chaos that it can create organizing many individuals with a number of different skill sets.  Software by comparison seems like it should be easier because all of the software developers are meant to be similarly skilled, and there isn't usually much in the way of materials or scheduling that can't be generally overcome (IE: delay is relatively cheap compared to delayed construction projects). The reality however is that software is all about dealing with people, and creating solutions to problems for people.  When the project is so people-focused, it becomes less precise, and more affected by the problems that occur to and between people.

I believe it comes down to several factors, and the most obvious ones that come to my mind at the moment are as follows:

The developer doesn't fully understand the problem domain.

You can blame the customer all you want for "not knowing their own mind", but the real underlying problem is that the customer is generally and genuinely not able to put into words what it is that they NEED.  Wanting and needing are two very different things, and it is up to a skilled developer to draw out the customers needs, rather than merely responding to what the customer initially states as wants. When you are able to talk to the customer in their own language and have nailed what it is that the customer actually needs, then you are able to claim to fully understand the problem domain.

Limited input from team members of varying levels of experience.

Let's face facts.  Nobody works well when driven by someone else's estimates.  Every developer's experience is somewhat unique or at the very least different, and each will view a particular task from a different personal experience. If you only have one person estimating the entire project, they will only really get about 25-40% of their estimates correct, and it will be the difficult stuff that they have either no experience with, or which has been misunderstood that will end up causing the most delays. You can bet your auntie that the greatest delays will come from something a single estimator thought of as relatively trivial.  This is where group estimation is very important. You get all of the people who will actually work on the project to provide all of the estimates (A planning poker session can really help here), and basically use this process to effectively hedge your bets against possible scheduling failures in the future.

Developer hasn't tuned their Software Development Method

There has been a lot of stuff written about software development methodology over the last 20 years.  While I can't claim to have read everything, I can like most experienced people out there claim to have sampled a bit of everything, and have tried much of it. One of the reasons that I have become quite avid about being Agile is because of the emphasis it places on tuning your processes, and about being adaptable in both how you apply your practices, and in your thinking. Sometimes the method needs to be tuned to match the needs of the customer, but more often the greatest method tuning needs to be with the team itself.  Whenever a new team member joins, it is an opportunity to tweak your processes, and when the team doesn't gel, you need to tune even further. Most serious failures happen because of teams that work ineffectively as a unit, and where the method doesn't (or can't) account for the unique situation of a given team. Everything from personal issues, to office politics, fatigue, experience, all of it can have an effect, but if the process doesn't make sense to the team, if it makes them feel uninspired or if it doesn't make the team feel in control or empowered by their efforts, then it's going to fail the team, and the team will end up failing the project. Processes that help team members feel like they are achieving good results in small manageable stages, and where team members feel rewarded by the effort itself, are processes that will ultimately deliver the best results to the customer.

Plans are derailed by the most unexpected things

As any military planner will tell you, you can have the best strategy all worked out with every minute detail planned, but once you start the battle the plan will be shot all to hell. Sure, you can load your estimates with likely delays, such as people getting sick, planning their holidays, or having that massive trade fair pop up right in the middle of your planned development period, but you can't always plan for things like massive incompetence, your entire server farm going down, your entire development team simultaneously contracting the Bengal Flu, or your suppliers suddenly going bankrupt. Things can, and most certainly will go wrong, and finger pointing won't help anybody. You can however plan to handle the unforeseen by negotiating alternative release schedules, and by ensuring that every release to the customer provides them with working software that delivers business value with every release.

So by this definition, it's systemic failures that will derail projects, and not always problems with scheduling.  Scheduling itself is relatively easy compared to all the other stuff that a team needs to get right in order to deliver a successful outcome.


问:
How best do you represent a bi-directional sync in a REST api?
Assuming a system where there's a Web Application with a resource, and a reference to a remote application with another similar resource, how do you represent a bi-directional sync action which synchronizes the 'local' resource with the 'remote' resource?

Example:

I have an API that represents a todo list.

GET/POST/PUT/DELETE /todos/, etc.

That API can reference remote TODO services.

GET/POST/PUT/DELETE /todo_services/, etc.

I can manipulate todos from the remote service through my API as a proxy via

GET/POST/PUT/DELETE /todo_services/abc123/, etc.

I want the ability to do a bi-directional sync between a local set of todos and the remote set of TODOS.

In a rpc sort of way, one could do

POST /todo_services/abc123/sync/

But, in the "verbs are bad" idea, is there a better way to represent this action?

答:
You can solve the "verbs are bad" problem with a simple renaming - use "updates" instead of "sync".

The sync process is actually sending the  a list of local updates made since the last sync, and receiving a list of updates made on the server in that same time.


问:
What is message passing in OO?
I've been studying OO programming, primarily in C++, C# and Java. I thought I had a good grasp on it with my understanding of encapsulation, inheritance and polymorphism.

One frequently referenced concept when discussing OO is "message passing". Apparently, this is something that is not used whilst OO programming in today's mainstream languages, but is supported by Smalltalk.

My questions are:

What is message passing?

Is there any support for this "message passing" in C++, C# or Java?

答:
What is message passing? (Can someone give a practical example?)

Message passing simply means that (at a very abstract level) the fundamental mechanism of program execution is objects sending each other messages. The important point is that the name and structure of these messages is not necessarily fixed beforehand in the source code and can itself be additional information. This is an important part of what Alan Kay originally envisioned as "object oriented programming".

Is there any support for this "message passing" in C++, C# or Java?

These language implement a limited version of message passing through method calls. Limited because the set of messages that can be sent is limited to the methods declared in a class. The advantage of this approach is that it can be implemented very efficiently, and it enables very detailed static code analysis (which results in all kinds of useful benefits, like code completion).

Conversely, languages that implment "real" message passing often have method definitions too, as a convenient way to implement message handlers, but allow classes to implement more flexible message handlers that enable the object to recieve "method calls" with arbitrary names (not fixed at compile time).

An example in Groovy that demonstrates the power of this concept:

```<code>def xml = new MarkupBuilder(writer)
xml.records() {
  car(name:'HSV Maloo', make:'Holden', year:2006) {
    country('Australia')
    record(type:'speed', 'Production Pickup Truck with speed of 271kph')
  }
}
</code>```

will produce this XML:

```<code><records>
  <car name='HSV Maloo' make='Holden' year='2006'>
    <country>Australia</country>
    <record type='speed'>Production Pickup Truck with speed of 271kph</record>
  </car>
</records>
</code>```

Note that records, car, country and record are syntactically method calls, but there are no methods of that name defined in MarkupBuilder. Instead, it has a catchall message handler that accepts all messages and interprets the message names as the name of an XML element, parameters as attributes and closures as child elements.

ContentLicense: CC BY-SA 4.0

Title: What is message passing in OO?

Body:
What is message passing? (Can someone give a practical example?)

Message passing simply means that (at a very abstract level) the fundamental mechanism of program execution is objects sending each other messages. The important point is that the name and structure of these messages is not necessarily fixed beforehand in the source code and can itself be additional information. This is an important part of what Alan Kay originally envisioned as "object oriented programming".

Is there any support for this "message passing" in C++, C# or Java?

These language implement a limited version of message passing through method calls. Limited because the set of messages that can be sent is limited to the methods declared in a class. The advantage of this approach is that it can be implemented very efficiently, and it enables very detailed static code analysis (which results in all kinds of useful benefits, like code completion).

Conversely, languages that implment "real" message passing often have method definitions too, as a convenient way to implement message handlers, but allow classes to implement more flexible message handlers that enable the object to recieve "method calls" with arbitrary names (not fixed at compile time).

An example in Groovy that demonstrates the power of this concept:

def xml = new MarkupBuilder(writer)
xml.records() {
  car(name:'HSV Maloo', make:'Holden', year:2006) {
    country('Australia')
    record(type:'speed', 'Production Pickup Truck with speed of 271kph')
  }
}

will produce this XML:

<records>
  <car name='HSV Maloo' make='Holden' year='2006'>
    <country>Australia</country>
    <record type='speed'>Production Pickup Truck with speed of 271kph</record>
  </car>
</records>

Note that records, car, country and record are syntactically method calls, but there are no methods of that name defined in MarkupBuilder. Instead, it has a catchall message handler that accepts all messages and interprets the message names as the name of an XML element, parameters as attributes and closures as child elements.


问:
I have a stacktrace and limit of 250 characters for a bug report
I'm developing an xbox indie game and as a last-resort I have a try...catch encompassing everything.

At this point if an exception is raised I can get the user to send me a message through the xbox however the limit is 250 characters.

How can I get the most value out of my 250 characters?

I don't want to do any encoding / compressing at least initially.

Any solution to this problem could be compressed if needed as a second step anyway.

I'm thinking of doing things like turning this:

at EasyStorage.SaveDevice.VerifyIsReady()

     at EasyStorage.SaveDevice.Save(String containerName, String fileName)

into this (drop the repeated namespace/class and method parameter names):

at EasyStorage.SaveDevice.VerifyIsReady()

     at ..Save(String, String)

Or maybe even just including the inner-most method, then only line numbers up the stack etc.

TL;DR:  Given an exception with a stacktrace how would you get the most useful debugging infromation out of 250 characters?

(It will be a .net exception/stacktrace)

答: In embedded development, the error reports are limited to few integers. The best to do is to report the exact location of the error and the actual value that triggered the error (together with the expected value if it is not hardcoded). It is essential to trigger the error as soon as possible.</p>


问:
DDD and validation of aggregate root
Suppose an aggregate root : MailConfiguration (wrapping an AddressPart object). The AddressPart object is a simple immutable value object with some fields like senderAdress, recipentAddress (to make example simple).

As being an invariant object, AddressPart should logically wrap its own Validator (by the way of external a kind of AddressValidator for respecting Single Responsibility Principle)

I read some articles that claimed an aggregateRoot must validate its 'children'.
However, if we follow this principle, one could create an AddressPart with an uncohesive/invalid state.

What are your opinion? Should I move the collaborator AddressValidator(used in constructor so in order to validate immediately the cohesion of an AddressPart) from AddressPart and assign it to aggregateRoot (MailConfiguration) ?

答:
Will AddressPart ever be used elsewhere outside of your MailConfiguration aggregate?  If it is (or is likely to be) then the validation should absolutely stay with it.

Actually, I'd argue that the validation should stay wit it regardless.  Even if the parent was 'responsible', it should simply delegate that call down to the children it has.

Title: DDD and validation of aggregate root


答: You can probably reduce the size a bit more if you consider the difference between framework and user code - when an exception occurs deep in the framework code, you get a long stack trace but all you actually care about is the first line with the actual error, and the line about halfway down where your own code calls the framework code.</p>

Title: I have a stacktrace and limit of 250 characters for a bug report

Body:
I'm developing an xbox indie game and as a last-resort I have a try...catch encompassing everything.

At this point if an exception is raised I can get the user to send me a message through the xbox however the limit is 250 characters.

How can I get the most value out of my 250 characters?

I don't want to do any encoding / compressing at least initially.

Any solution to this problem could be compressed if needed as a second step anyway.

I'm thinking of doing things like turning this:

at EasyStorage.SaveDevice.VerifyIsReady()

     at EasyStorage.SaveDevice.Save(String containerName, String fileName)

into this (drop the repeated namespace/class and method parameter names):

at EasyStorage.SaveDevice.VerifyIsReady()

     at ..Save(String, String)

Or maybe even just including the inner-most method, then only line numbers up the stack etc.

TL;DR:  Given an exception with a stacktrace how would you get the most useful debugging infromation out of 250 characters?

(It will be a .net exception/stacktrace)