答:
I don't know if this is your team's issue but it definitely was for us when we first introduced scrum.  Our management came to us one day and said, from now on you will not be working in individual silos. Instead, you will be working as a scrum. Here's a bunch of new processes you must all follow and follow them you will.

The key is that they never came to us, the developers, and asked, how do you guys want to work? what will make you happier? more efficient?.  So what I heard was, "you no longer own any code. Anything you write, will get trampled on (you know, team ownership). You will not move or lift a finger because we will now manage your time by the hour".  Oh and now you have a boring 15-min stand up everyday where people will discuss things you don't care about and it will usually take 30 minutes and then every two weeks will have an uber boring 4 hour planning meeting that is sure to suck all life out of you.

In reality this is not Agile or Scrum, this is just moving from one style of management to a different style, where everything is still centrally controlled, and not only did this suck all life out of me, but it also gave me lots of free time to update my resume.

In the last twelve months, after I lobbied numerous times for our team manager to try something different, he actually took me up on my suggestions, and I think we've had a very successful year.

I believe the key change for us was to give developers much more voice and freedom in choosing how we want to work.  Few things we did:

Break large "agile" development team into 3 small ones so that each one only has 3-4 developers. This makes everyone engaged and individuals are not drowned out.

Make sure everyone in the same team works around the same functional area so that people care what others are talking about in stand ups and iteration plannings.

Instead of management simply picking who works on what and assigning stories/tasks, we came up with a backlog and the team itself had a lot of say in how the work is divided.

Because we had many new members, we've started with somewhat of a silo system where each person owns a primary area of responsibility. This allowed new people to focus on smaller area of an unknown product and also get a faster sense that they are not playing in someone else's sandbox.  But 6-8 months into the program, those areas started to morph as the boundaries became more gray.  Now the guys, on the teams I'm on, are fairly comfortable stepping into other's code or having other developers work in theirs.

Code reviews of all submissions were key (and this was the first thing that was skimped on when we first did Scrum):

Knowledge transfer in terms of programming techniques/methods

Was great for others to learn code they wouldn't have seen otherwise

Your team gets a chance to communicate and socialize which improves team dynamics

And I guess, code reviews will catch a bug or two, but I see their value mostly in the above aspects.

Management has to listen to the team. If the team says something doesn't work or needs to be changed, and they simply ignore that, than the team members will simply check out and let the management deal with the project.  If you want people motivated, they need to be vested and they will only be vested if they are doing what they believe is right, not what they are told to do from up top.

Title: Scrum: Handling lack of motivation


问:
Is it possible to combine programming languages?
I've been programming for a while, I've written some rudimentary programs, and I want to keep learning. I've reached that point where you just don't know what to learn next, and I'd like to ask a question for my own curiosity.

The question, in a nutshell, is if you can combine multiple programming languages into 1 result? For example, can this code be possible?

```<code><html>
cout << "Hello world!";
</html>
</code>```

or

```<code>import java.util.Scanner;
cout << "Insert a number from 1 to 10";
Scanner n = new Scanner(System.in);
System.out.println("The value you entered was" +n.newLine());
</code>```

This feels like a silly question but I can't possible know if it's possible or not, so that's why I'm asking it. In this question I notice he is using Python code in html code, if my above example is not possible, what did he do?

答:
Short Answer

Not really.

Long Answer

Embedding

Generally, a single source file contains code for exactly one programming language.  It is uncommon for multiple languages to be combined in a single file for a couple of reasons:

Parsing several syntactically-different languages at once is extremely difficult (if not outright impossible).

Different languages treat programming differently.  Haskell's notion of a function is different than C++'s.

Linking

Different programming languages that share a common application binary interface may be combined to form a single executable or library.  Getting the two languages' signatures available inside each other often takes a bit of work, but tools exist to ease the process.

Polyglots

Polyglot code is valid and equivalent in more than one language.  Stack Overflow's 404 page features one such program:

This prints "404" in Python, Perl, Ruby, C, Brainfuck and Befunge.

Conclusion

Languages are rarely mixed within files, and when they are, it is for laughs.  People even try to avoid mixing languages within projects because of the extra hassle it introduces.  So, while it can be technically possible, mixing different languages is neither common nor pragmatic.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Developing a dynamic language
I have created several hand written compilers for very simple languages but now I want to try my hand at developing a dynamic language, similar to a simplified Python or Ruby.  However, it was easy for me to wrap my head around how compilers work.  Primitive compilers just translate.  But I can't do this if the language is dynamic.  I have to write an interpreter or VM that keeps track of information at runtime and puts a lot more work on me.

In short, are there any resources I should check out considering I know how compilers work but want to migrate to creating an interpreter?  There are a few VMs out there for dynamic languages, but I have no problem with rolling my own.  This is all just for my personal experience.

I am seeking information on how to go from a compiler to an interpreter.  If I have already made a compiler for language X but now what to write an interpreter, what needs to be done and are there any resources that go over the process?

I do not want broad or abstract resources that go over how compilers or virtual machines work.  I have plenty of textbooks on the subject.  All of the resources I found online either assume you have 0 experience and thus start you off with lexical or syntactic analysis or they are extremely abstract.  I have a working compiler, but I now want to turn this into an interpreter and add dynamic features to the language.

I could not find resources on this process, it may be too limited in scope, or resources on the "back end" of an interpreter without being too theoretical which is why I posted here.

答:
First learn about implementing interpreters. I recommend PLAI (Programming Languages: Application and Interpretation). It gets to the meat of interpretation quickly without dwelling overlong on syntax.

For your language, you'll be able to reuse the compiler's front-end (parser, mostly) and run-time library (GC, data structures, primitive operations, etc).

Of course, you can also implement a dynamic language with a compiler that produces code that manipulates (some of) the same data structures that you would use in an interpreter. For example, in an interpreter you might implement global variables as a string-indexed hash table. In a compiler, you would compile global variable references into the code that does the lookup using the same table. In contrast, you could compile lexical variables into a more efficient representation ("native" arguments and closure structure references).

Title: Developing a dynamic language


答:
If you want to learn the basics of implementing an interpreter for a dynamic language, I can't imagine a better place to start than the origins of the very first dynamic, interpreted programming language: Lisp.

In his original 1960 paper, John McCarthy defined 5 primitive functions necessary to a Lisp. Of course, McCarthy only intended his paper on Lisp as an academic exercise; it was a graduate student who implmented eval in assembly and created the first Lisp interpreter. Paul Graham identifies seven primitives: quote, atom, eq, cons, car, cdr, and cond.

The thing is, you can really implement Lisp in any language; once you implement eval, it's easy to set up a REPL, and you have an interactive interpreter. People have been bored or curious enough to implement Lisps in C, Java, Ruby, Python, and many other languages. And not always on purpose; it's important to remember Greenspun's Tenth Rule:

Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.

I'm not saying your end-goal should be a Lisp implementation; but homoiconicity has its benefits when learning to implement a dynamic language; why deal with syntax issues when you can learn on a language in which the idiomatic syntax is identical toe the AST of a language that uses a lexer/parser?

Anyhow... just a suggestion. But it is with good reason that most of the great programming languages since C have at least a little of the Lisp-nature.

Title: Developing a dynamic language

Body:
I have created several hand written compilers for very simple languages but now I want to try my hand at developing a dynamic language, similar to a simplified Python or Ruby.  However, it was easy for me to wrap my head around how compilers work.  Primitive compilers just translate.  But I can't do this if the language is dynamic.  I have to write an interpreter or VM that keeps track of information at runtime and puts a lot more work on me.

In short, are there any resources I should check out considering I know how compilers work but want to migrate to creating an interpreter?  There are a few VMs out there for dynamic languages, but I have no problem with rolling my own.  This is all just for my personal experience.

I am seeking information on how to go from a compiler to an interpreter.  If I have already made a compiler for language X but now what to write an interpreter, what needs to be done and are there any resources that go over the process?

I do not want broad or abstract resources that go over how compilers or virtual machines work.  I have plenty of textbooks on the subject.  All of the resources I found online either assume you have 0 experience and thus start you off with lexical or syntactic analysis or they are extremely abstract.  I have a working compiler, but I now want to turn this into an interpreter and add dynamic features to the language.

I could not find resources on this process, it may be too limited in scope, or resources on the "back end" of an interpreter without being too theoretical which is why I posted here.


问:
How is the "Infinite Monkey Theorem" different to use than Genetic Programming to solve problems?
This might be a little open ended, but I heard an explanation of this talk on how GP could be used to fix bugs, and I wonder: How does this differ from the infinite monkey theorem?</p>

答:
Another way of looking at it is in terms of probability. Say we have a space X of configurations and a function for evaluating how good those configurations are, f. To find good solutions, elements in X that have a high value f, we need to find a way of sampling X. Two strategies for sampling the space are the Infinite Monkey (IM) and Genetic Programming (GP).

The difference is in how X is sampled. In the IM strategy, the sampling is completely uniform. In Genetic Programming, an initial set of points are taken uniformly, but then the various hills and valleys of fitness (according to f) are explored from there.


问:
Why doesn't java use a radix sort on primitives?
java.util.Arrays.sort(/* int[], char[], short[], byte[], boolean[] */) is implemented as a 'tuned quicksort' rather than a radix sort.

I did a speed comparison a while ago, and with something like n>10000, radix sort was always faster. why?

答:
I would speculate that:

Array.sort is implemented as quicksort, because quicksort can sort anything in decent time given a comparator.

Sorting a list of 10000 entries is not so common. Accessing a data-structure of 10000 or more elements is rather common. If you need to maintain order, a balanced search tree is often a better way to go than to sort your whole array every time you need the smallest element.

Sorting primitives is not so common, despite what university may teach.

The point is, it's not such a common use case, that it's optimization needs to be in the standard library. If you have written an application, that has performance issues, where you determine through profiling that sorting an array of 10000+ ints is actually the bottleneck, then you might as well write the sorting by hand or reconsider your choice of data structure in the first place.


问:
Is it a good idea to generate code with the help of your IDE?

Possible Duplicate:

  Should newbies use IDE autocomplete (Intellisense)?

Since I moved on to actual IDEs for C++, Java and Python, I noticed they automatically try to complete my code. For example if I write System.out.pr[...] I am automatically offered a list from which I can select the item I want to use.

As a beginner I avoided using this feature as I thought I should learn the syntax by typing. Was I correct in thinking that?

From a more experienced programmer's point of view, I'd see no harm in using this feature.

答:
Use it, absolutely.  It will help you learn, because sometimes you will see completions that you never thought of, or that you didn't know existed.

Also, if it saves you time, and will always save you time when you use it in the future, what are you learning by avoiding it?


答:
Yes and no. It can be very useful but there are a few things to watch out for:

Magic Thinking: if you don't understand what the IDE is doing, you could be in trouble

Failing to understand your problem and letting the IDE think for you

However if we are just talking about word completion then by all means go ahead. To be honest, I have never used that much, but I also type pretty fast and I find that when I use an IDE the little box popping up takes longer than just typing what I was thinking to start with, plus I really hate having to move my hand off of the keyboard.

Title: Is it a good idea to generate code with the help of your IDE?

Body:
Possible Duplicate:

  Should newbies use IDE autocomplete (Intellisense)?

Since I moved on to actual IDEs for C++, Java and Python, I noticed they automatically try to complete my code. For example if I write System.out.pr[...] I am automatically offered a list from which I can select the item I want to use.

As a beginner I avoided using this feature as I thought I should learn the syntax by typing. Was I correct in thinking that?

From a more experienced programmer's point of view, I'd see no harm in using this feature.


问:
What does mathematics have to do with programming?
I just started a diploma in software development. Right now we're starting out with basic Java and such (so right from the bottom you might say) - which is fine, I have no programming experience apart from knowing how to do "Hello World" in Java.

I keep hearing that mathematics is pertinent to coding, but how is it so? What general examples would show how mathematics and programming go together, or are reliant on one another?

I apologize of my question is vague, I'm barely starting to get a rough idea of the kind of world I'm stepping into as a code monkey student...

答:
Here I will tell you practical stuff where I have encountered Mathematics in solving some Computing Problems (particularly in Internet domain) :

Search Engines uses Vector Calculus for searching data.

Matrix Factorization can be used for a lot of stuff like Sentiment Analysis.

You need to know Calculus, Summations for figuring out complexity of code that you write.

Probability is heavily used in Probabilistic Information Retrieval/Search

Naive Bayes Theorem is used in Predictive Analytics.

You need to know stuff like hyper plane etc for a concept called SVM which is again used in Machine Learning for solving categorization problems.

You need to understand Entropy for doing Natural Language Processing stuff.

Latent Semantic Indexing/ Principal Component Analysis used by Search Engines relies heavily on matrix algebra.
& so on......


答:
Embedded SQL was a common way to embed SQL statements into programs of other languages.

These days it has been replaced almost entirely by easier-to-compile API-based Database access that doesn't need to modify the host language, but use its normal abilities instead.

Title: Is it possible to combine programming languages?

Body:
I've been programming for a while, I've written some rudimentary programs, and I want to keep learning. I've reached that point where you just don't know what to learn next, and I'd like to ask a question for my own curiosity.

The question, in a nutshell, is if you can combine multiple programming languages into 1 result? For example, can this code be possible?

```<code><html>
cout << "Hello world!";
</html>
</code>```

or

```<code>import java.util.Scanner;
cout << "Insert a number from 1 to 10";
Scanner n = new Scanner(System.in);
System.out.println("The value you entered was" +n.newLine());
</code>```

This feels like a silly question but I can't possible know if it's possible or not, so that's why I'm asking it. In this question I notice he is using Python code in html code, if my above example is not possible, what did he do?


答:
The thing about monkeys is most of them are terrible writers, which is why we would need an infinite number of them. Your infinite monkeys will indeed produce some  great literary works (all of them in fact), however they will also produce an awful lot of crap (both literal and figurative). Using a genetic algorithm instead will hopefully let us produce some great literary works while keeping the crap to a minimum.

We first take a (relatively) large number of monkeys distributed among various traits (perhaps hair color, tail length, or how often they throw poop at you). Then we put them all in a cage so they can reproduce. Eventually they will reproduce so much that there are more offspring than you originally had. These new monkeys are each some random combination of monkeys from previous generations. We'll also expose the monkeys to some mild to moderate radiation to add a bit more randomness for good measure.

Now that we've got a new generation of monkeys it is time to put them to the test. Give each of them a pen and paper and tell them to write you a story. Once they've finished read through their stories and keep the monkeys who produced the "best" stories and sell the rest to the circus. Continue this breeding and pruning process for several million years and you should end up with a group of super monkeys that can consistently churn out literary classics without all the crap your infinite monkeys would produce.

There is a lot of randomness here (depending on how much radiation you used) but by selecting only the best monkeys to continue on at each generation the randomness will hopefully converge on the solution you are looking for without having to deal with an infinite amount of monkeys. It's true that an infinite amount of monkeys would give you the answer you want, but then you'd need an infinite amount of time to wade through their infinite amount of crap as well.

Title: How is the "Infinite Monkey Theorem" different to use than Genetic Programming to solve problems?

Body: This might be a little open ended, but I heard an explanation of this talk on how GP could be used to fix bugs, and I wonder: How does this differ from the infinite monkey theorem?</p>


问:
Is there a problem with writing an in-memory DAL for testing the BLL/ViewModels?
Mocking the DAL/Repository that I pass to the BLL/ViewModels for testing purposes is not much different than creating an in-memory DAL. Right now I'm using an in-memory DAL in a new project instead of mocking it and it's working very well so far (even easier than setting up the mocks I'd say).

Since I haven't seen this done in online/book examples I thought I'd ask. Is there a problem with writing an in-memory DAL for testing the BLL/ViewModels?

On my architecture all components share a common library with all the relevant interfaces. Things are late bound which allows me to swap any component for another of the same interface.

答:
There isn't necessarily anything inherently wrong with choosing to use an in-memory DB instead of mocking things out, but there are some tradeoffs. The main one IMO is performance, which may or may not be a concern to you, depending on how many tests you have and how much data you need to setup.

At my company our main product has a few thousand tests, about half of which are integrated with our DB. The rest are all mocked. The DB tests take about 3-4 minutes to run, while the mocked tests take about 15 seconds. Of course, a real DB is a lot slower than an in-memory DB, but even so mocked data is faster, and if you had a goal of being able to do a compile+test loop in a minute then it could be difficult to hit that target using any database. Also, if your tests connect to a DB, it may be impossible to run them multithreaded. We use NCrunch during development to run our mocked suite in the background using all available cores, so we can get feedback while we're coding.

Mocked data most likely will require more code upfront, and may be too time consuming if you don't have good frameworks available for assisting in mock data generation. So you'll always have to consider the cost/benefits.


答: Go ahead with it as long as you understand what the IDE is doing. It is not just about the completion of method calls. For example, if you have a simple Java bean, you don't need to write getters, setters or constructors yourself (as long as they're only doing routine work). The same thing goes for refactoring. It is not difficult to understand how an IDE refactors  code to rename a variable, but it can be annoying to do it manually. By having the IDE take care of simple but tedious tasks, you can focus on more challenging aspects and be more productive.


答:
There are literally thousands of methods in the standard libraries alone, plus much more in all that frameworks you'll be using. Do you really want to memorise all that useless crap which is going to become redundant in a next version? Do you want to waste you precious limited memory capacity on something as irrelevant and boring as APIs? It is pointless.

Let the IDE and documentation browsers help you to find the required information when you really need it, and forget it immediately. APIs should never be memorised. I'd say more - even a syntax of particular programming languages should not be memorised, you'll remember the things you're using often any way, and the rest is always easy to look up.

Knowing a syntax or APIs won't make you a better programmer. Learning the programming in general, learning as many different languages as possible, learning the underlying mathematics, philosophy, design, algorithms - that matters, not a syntax or libraries.


答:
From a programmers perspective: Mathematics is a subset of programming.

Maths applied in programming:

When working with collections (arrays, lists, maps, etc) in programming, then you are dealing with real world implementations of mathematical abstractions.

Programming without maths:

If you do println("Hello World"), then the fact that some math is used to calculate the position on the screen, the length of the string, etc, is really mostly irrelevant.

Using programming for maths:

Implementing mathematics and physics in a programming language makes things like computer aided design possible.

Title: What does mathematics have to do with programming?

Body:
I just started a diploma in software development. Right now we're starting out with basic Java and such (so right from the bottom you might say) - which is fine, I have no programming experience apart from knowing how to do "Hello World" in Java.

I keep hearing that mathematics is pertinent to coding, but how is it so? What general examples would show how mathematics and programming go together, or are reliant on one another?

I apologize of my question is vague, I'm barely starting to get a rough idea of the kind of world I'm stepping into as a code monkey student...


问:
Coding Guideline : Methods shouldn't contain more than 7 statements?
I was looking through the AvSol Coding Guidelines for C# and I agree with nearly everything but I'm really curious to see what other think of one specific rule.

AV1500

Methods should not exceed 7 statements  A method that requires more
  than 7 statements is doing too much, or has too many responsibilities.
  It also requires the human mind to analyze the exact statements to
  understand what the code is doing. Break it down in multiple small and
  focused methods with self-explaining names.

Do most of you follow this rule? Even if there's little to be saved from creating a new method (Your code is still DRY) aside from greatly increasing readability?  And is your number still as low as 7?    I would tend more toward 10.

I'm not saying I violate this rule all over the place--on the contrary, my methods are 95% small and focused but saying you should never violate this rule really blew me away.

I really just want to know what everyone thinks of NEVER violating this rule (It's a '1' on the coding standard--meaning NEVER do this).  But I think you'd have trouble finding a codebase that doesn't.

答:
Pretty silly when you add exception handling into the mixture.

After "try, catch , finally" you are left with four statements per method!

Also consider a method "validateForm" for a 20 field form, even if you handle all the individual validations in separate methods you still have 20 field validation methods to invoke. According to these guidlines you would end up with some pointless split like "validateTopOfScreen", "validateMiddleOfScreen" and "validateBottomOfScreen".


问:
Program more professionally (planning, notation, ...)
I program a data-analysis framework for my company (20000LOCs by now). There are 2 programmers who help writing individual module for interfaces I have predefined. So far I haven't used much planning or tools. I basically think of new classes in my head and write them down in Python+Eclipse. As Python is good for proto-typing I can easily modify it if I overlook one aspect. However, sometimes I need to refactor some structure and I wonder if that hadn't happened if I used planning tools.

What do you think is the most important start to plan programming more professionally? The project won't become too big as it's only for data analysis, but managing which data is processed which way is also tedious. Can you suggest methods, reading or tools?

My class hierarchy is pretty flat so I don't see much use in class diagrams. However, something like call diagrams and diagrams which show how objects reference each other might help. I've learned OOP by myself, but I'm confident that once I consider all requirements I can design a nice class structure.
What about TDD? For the moment I cannot imagine how to use it since most calculation are on network-like data with objects and many object references (links). Moreover data content hasn't been a problem yet.

Yet, I suspect that some more professional approach might be more efficient. Ideas?

答:
The fact that you are sometimes refactoring code is not a bad thing; being prepared to do so shows a commitment to writing the best code you can.

It sounds like you are looking for a more rigid way to define software up front. Certainly thinking through and planning is important, but  moving too far in the direction of Big Design Up Front (BDUF) has its own problems. These include not knowing all the requirements in advance, and not being flexible enough to change the design if (when) the requirements change. Like many things that are hard it's a trade-off between two extremes of a pendulum. You might find it interesting to read about the Waterfall Method and it's problems.

The limited size of your project means a dynamic approach has more up than down sides. Refactoring your way out of any wrong turns is probably not going to be difficult.

I would encourage you to have another look at TDD. It is not that the code is proven correct (it isn't, although it will provide more evidence that it is). The main advantage is that it gives you the confidence to refactor more. The idea is the tests are green, you change the implementation and break the tests, then get them green again. If you have good tests it avoids those nasty situations where you try to change to much and get yourself into trouble and can't work out why things are broken (of course if you are using source code control rolling back is a command away).

As for it being difficult to test you can use mock objects. These allow you to isolate classes for testing which are strongly entwined (highly coupled). If you follow TDD you will find that you naturally write classes that stand alone. This makes testing easier, but happily it also makes the code better (low coupling, and high cohesion).

If you are interested in this I second the recommendation for Martin Fowlers book Refactoring: Improving the Design of Existing Code.


答:
7 is a completely arbitrary number with absolutely no significance.

Cyclomatic complexity is a bigger issue than the number of statements. I've seen code that had 100s of statements in a single method (which I thought was terrible), but it had a cyclomatic complexity of 1 and it really only did 1 thing. There were just a lot of steps. We discussed breaking it apart into smaller methods, but those methods would only be called by this one method.

While that is a fairly extreme case, the point is you need to keep the code DRY and a low cyclomatic complexity. That is more important than the number of lines in a method.

Take a switch / case statement for example. If you have more than 7 possible values do you need to break the evaluation into multiple methods? Of course not, that would be silly.

Artificially breaking code into more methods just to keep the number of statements under 7 only makes your code worse.

The guideline should be Each method should do 1 thing and keep your code DRY.

Title: Coding Guideline : Methods shouldn't contain more than 7 statements?

Body:
I was looking through the AvSol Coding Guidelines for C# and I agree with nearly everything but I'm really curious to see what other think of one specific rule.

AV1500

Methods should not exceed 7 statements  A method that requires more
  than 7 statements is doing too much, or has too many responsibilities.
  It also requires the human mind to analyze the exact statements to
  understand what the code is doing. Break it down in multiple small and
  focused methods with self-explaining names.

Do most of you follow this rule? Even if there's little to be saved from creating a new method (Your code is still DRY) aside from greatly increasing readability?  And is your number still as low as 7?    I would tend more toward 10.

I'm not saying I violate this rule all over the place--on the contrary, my methods are 95% small and focused but saying you should never violate this rule really blew me away.

I really just want to know what everyone thinks of NEVER violating this rule (It's a '1' on the coding standard--meaning NEVER do this).  But I think you'd have trouble finding a codebase that doesn't.


问:
Servicing background tasks on a large site
We're dealing with an interesting problem on StackOverflow.

We've got a whole bunch of little "needs to be done soon-ish" tasks.  An example is updating "Related Questions" lists.  What we've done in the past is to piggy-back those tasks onto some users' page loads.

This was never ideal, but it wasn't really noticeable.  Now that SO has passed the 1,000,000 question mark, those unlucky users are starting to feel it.

The natural solution is to actually push these tasks into the background.  There are two broad ways of doing this I'm considering.

1. In IIS as a custom Thread-Pool/Work-Queue

Basically, we spin up a few (non-ThreadPool, so as to not interfere with IIS) threads and have them services some collections we're shoving Funcs into.

The big pro here is simplicity.  We don't have to worry about marshaling anything, nor do we have to make sure some external service is up and responding.

We also get access to all of our common code.

The con is, well, that we shouldn't use background threads.  The objections I know of are all centered around starving IIS (if you use ThreadPool) and the threads dieing randomly (due to AppPool recycling).

We've got existing infrastructure to make the random thread death a non-issue (its possible to detect a task has been abandoned, basically), and limiting the number of threads (and using non-ThreadPool threads) isn't difficult either.

Am I missing any other objections to in IIS process thread-pooling/work-queues?

Moved to StackOverflow, as it wasn't really addressed here.

2. As a Service

Either some third-party solution, or a custom one.

Basically, we'd marshal a task across the process boundary to some service and just forget about it.  Presumably we're linking some code in, or restricted to raw SQL + a connection string.

The pro is that its the "right way" to do this.

The cons are that we're either very restricted in what we can do, or we're going to have to work out some system for keeping this service in sync with our code base.  We'll also need to hook all of our monitoring and error logging up somehow, which we get for free with the "In IIS" option.

Are there any other benefits or problems with the service approach?

In a nutshell, are there unforseen and insurmountable problems that make approach #1 unworkable and if so are there any good third-party services we should look into for approach #2?

答:
Resque is nice. Or even Kthxbye if you need to be notified of the resulting value once it's completed.

Both Redis/Ruby based tho.

Honestly, if you're doing a service-based approach, it really doesn't need to be super-integrated with your current platform, which I feel is a plus. I would hope it could be a set-and-forget system that would run (with monitoring of some kind) and complete jobs. I'm not sure it has to be run on the same platform at all since its just updating/modifying database info.

Pretty sure you could get away with a lot more for a lot less if you farmed this kinda work out to a separate entity, especially since it seems you're dealing with threading issues. Both Resque and Kthxbye move the processing out to separate processes to allow the OS to handle the concurrency.

Resque

Kthxbye

ContentLicense: CC BY-SA 2.5


问:
Users creating instances from a template - is there a software pattern that corresponds to this use case?
I am looking into designing a system where users build a template item and then create many instances based on this template.They then need to be able customise each instance but I also need for them to be able to make changes to the template and have all instances updated. These items are fairly complex, each consisting of many components that will be stored in numerous database tables.

I see two implementation paths.

Store complete copies of the templates to create the instances and
migrate updates to the instances.

Store records only for the changes and build each instance from a combination of the template and instance changes.

I believe the first option would create a lot of unneeded extra data however the 2nd way introduces complexities in querying the data.

This seems like it has probably been implemented many times before but I am having trouble finding much reading material. Are there common names for data models or pattern options used in implementations of such systems?

Any advice on benefits or pitfalls of each option, other options, or implementation guidance would be useful too.

edit:

Sorry I may not have been clear. I was looking more for a name for the general architecture not a design pattern. It is the end users who create instances not developers.

For example the system might allow users to define templates to model manufacturing processes of many items. Then at different sites where facilities or requirements are different, the end user would would use one of these templates to define a process specific for that site. Things will be added, removed and modified for each site.

I believe I will go with option two mentioned above - storing only delta changes, not complete copies.

答:
The word you are looking for is instantiating

e.g. I am Instantiating this template with this parameter.

Along with templates, also look up generics for more reading material.


问:
What's the difference between computer science and programming?
I'm new at computer science and programming, and I was wondering, is there a difference between computer science and programming? and do you get to choose to study only one of them at the university, or both of them?</p>

答:
Computer science is to programming as physics is to mechanical engineering.

Computer science is theoretical, it takes a scientific and mathematical approach to information and it's computation.

Computer programming is practical, it is the process of designing, writing, testing, debugging, and maintaining the source code of computer programs.

They are different, but related fields. Both have benefited from each other.


答:
I would use a WAS hosted WCF service listening to an MSMQ Queue.

Pro's

Fire and forget one way messages from the web app

MSMQ/WCF throttling and retry

Guaranteed delivery ;D

Dead Letter management

Distributed processing

WAS / MSMQ activation

Con's

MSMQ (it's not dead ... Yet)

The MSMQ features in WCF makes using MSMQ really nice. Yes you will bleed on the configuration but the benefits will outweigh the sacrifice.

Title: Servicing background tasks on a large site

Body:
We're dealing with an interesting problem on StackOverflow.

We've got a whole bunch of little "needs to be done soon-ish" tasks.  An example is updating "Related Questions" lists.  What we've done in the past is to piggy-back those tasks onto some users' page loads.

This was never ideal, but it wasn't really noticeable.  Now that SO has passed the 1,000,000 question mark, those unlucky users are starting to feel it.

The natural solution is to actually push these tasks into the background.  There are two broad ways of doing this I'm considering.

1. In IIS as a custom Thread-Pool/Work-Queue

Basically, we spin up a few (non-ThreadPool, so as to not interfere with IIS) threads and have them services some collections we're shoving Funcs into.

The big pro here is simplicity.  We don't have to worry about marshaling anything, nor do we have to make sure some external service is up and responding.

We also get access to all of our common code.

The con is, well, that we shouldn't use background threads.  The objections I know of are all centered around starving IIS (if you use ThreadPool) and the threads dieing randomly (due to AppPool recycling).

We've got existing infrastructure to make the random thread death a non-issue (its possible to detect a task has been abandoned, basically), and limiting the number of threads (and using non-ThreadPool threads) isn't difficult either.

Am I missing any other objections to in IIS process thread-pooling/work-queues?

Moved to StackOverflow, as it wasn't really addressed here.

2. As a Service

Either some third-party solution, or a custom one.

Basically, we'd marshal a task across the process boundary to some service and just forget about it.  Presumably we're linking some code in, or restricted to raw SQL + a connection string.

The pro is that its the "right way" to do this.

The cons are that we're either very restricted in what we can do, or we're going to have to work out some system for keeping this service in sync with our code base.  We'll also need to hook all of our monitoring and error logging up somehow, which we get for free with the "In IIS" option.

Are there any other benefits or problems with the service approach?

In a nutshell, are there unforseen and insurmountable problems that make approach #1 unworkable and if so are there any good third-party services we should look into for approach #2?

OwnerDisplayName: Adam

LastEditorDisplayName: Adam


问:
Should I use title case in URLs?
We are currently deciding on a consistent naming convention across a site with multiple web applications. Historically, I've been an advocate of the 'lowercase all the letters!' when creating URLs:

```<code>http://example.com/mysystem/account/view/1551
</code>```

However, within the last year or two, specifically since I began using ASP.NET MVC & had more dealings with REST based URLs, I've become a fan of capitalizing the first letter of each section/word within the URL as it makes it easier to read (imho).

```<code>http://example.com/MySystem/Account/View/1551
</code>```

We're not in a situation where people need to read or be able to understand the URLs, so that's not a driver per se. The main thing we are after is a consistent approach that is rational and makes sense.

Are there any standards that declare it good to do one way or another, or issues that we may run into on (at least realistically modern) setups that would choose a preference over another? What is the general consensus for this debate currently?

答:
As the choice is mainly cosmetic (ie, most systems don't differentiate between upper and lower case, and users certainly don't), then I'd suggest just going with whichever makes you happy. Consistency within the application is the key, not the manner you choose.

As you're using ASP.Net, I'd recommend going with the PascalCase approach - as that is what tends to exist within the Microsoft framework (system libraries, etc.) But there are no "best practices" other than being consistent.

Most browsers do a fairly good job of hiding the URL from the user, to such an extent that a great many people who have google as their home page, will then search for facebook and click on it - rather than entering the facebook url in their browser.

Title: Should I use title case in URLs?


答:
While TLDs are not case-sensitive and Windows paths use a combination of capital and Pascal case, our applications are sensitive to the incoming request paths, where paths, or components therein, are usually normalized to a standard case, since /format/JSON/ and /format/json/ are requests for two different formats and reference two distinct resources.

Whenever I've seen http://www.somewebsite.com/Having/URLs/That-Look-Something-Like-This/, I felt like the developer's intent was mainly to appear a bit different from the rest, but it's nothing innovating and neither does it help improve readability, especially now that you have I and l, O and 0, other letters contending for your analysis.

I'm not aware of any consensus, neither do I believe that there should be one, because something as simple as capitalizing only certain parts of a URL could have a positive impact on readability and I'm sure someone, somewhere is already coming up with interesting ideas when it comes to applying letter cases to URLs.

But, judging by the fact that most Web servers are running on Linux and that we developers always end up standardizing incoming text data because the input is case-sensitive, I'm sticking to how it's been done all along.

Title: Should I use title case in URLs?

Body:
We are currently deciding on a consistent naming convention across a site with multiple web applications. Historically, I've been an advocate of the 'lowercase all the letters!' when creating URLs:

```<code>http://example.com/mysystem/account/view/1551
</code>```

However, within the last year or two, specifically since I began using ASP.NET MVC & had more dealings with REST based URLs, I've become a fan of capitalizing the first letter of each section/word within the URL as it makes it easier to read (imho).

```<code>http://example.com/MySystem/Account/View/1551
</code>```

We're not in a situation where people need to read or be able to understand the URLs, so that's not a driver per se. The main thing we are after is a consistent approach that is rational and makes sense.

Are there any standards that declare it good to do one way or another, or issues that we may run into on (at least realistically modern) setups that would choose a preference over another? What is the general consensus for this debate currently?


问:
Developer to team leader
How much experience is considered enough for a developer to become a team leader?

For IT managment what is the measure to check if the current team member is good enough to become a team leader (technical level, interpersonal level)

updated: removed second part of the question for being duplicate (see comments)

答:
The answer of all answers: It depends!

To become a leader of a team its not only experiance in developing. More than development your skills in leadership, planning and communication are more important than this. But for sure you have to know how to develop. I know some "team leaders" who have no real experiance as a developer. They know the basics but they know how to lead a development team.

Title: Developer to team leader


答:
I liked TopShelf.  Keeps the simplicity, yet still do it the proper way running as a Windows Service.  Basically create a Console App, add about 15-20 lines of code, then it installs as a service.

http://code.google.com/p/topshelf/


答:
how much of experience is considered enough for a developer to be nominated to become a team leader

As much as the management feels is necessary. I've known people who spend a decade in a developer role, never progressing into management. I've also known one person who started an entry-level graduate programming job, and was a team leader within two months. Experience doesn't matter, only ability.

for IT managment what should be the messures to check if the current team member is good enough to become a team leader (technical level, interpersonal level)

Ideally, if promoting from within, the correct choice should be obvious. If none of the developers really stand out or push themselves forward, perhaps none of them is ready for the role. If hiring from outside, it's just a standard HR drama.

for team member what qualities should be focused at to get a step forward in becoming team leader

Be the best that you can be at your job. If a team leader role becomes available, speak to your line manager and express an interest (very rarely are people just "given" promotions). Apart from the technical side, you should take an interest in the business side of the company. Sales meetings with clients and the like.

Title: Developer to team leader

Body:
How much experience is considered enough for a developer to become a team leader?

For IT managment what is the measure to check if the current team member is good enough to become a team leader (technical level, interpersonal level)

updated: removed second part of the question for being duplicate (see comments)


问:
What are the drawbacks of elastic tabstops?
Look here: a typical holy war on tabs vs spaces.

Now look here: elastic tabstops. All problems solved, and a bunch of very useful new behaviours added.

Are elastic tabstops even mentioned in that tabs vs spaces discussion? Why not? Are there drawbacks to the elastic tabstop idea so serious that nobody has ever implemented them in a popular editor?

EDIT: I apologise for putting too much emphasis on "why aren't they mentioned". That wasn't really what I intended; that question is possibly even off topic. What I really mean is, what are the biggest drawbacks of this that prevent wider adoption of an obviously beneficial idea? (in an ideal world where everything supports it already)

(Turns out there's already a request on the Microsoft Connect for a Visual Studio implementation of elastic tabstops, and a request in Eclipse too. Plus there's a question asking about other editors that implement elastic tabstops)

答:
They're not mentioned because they're not implemented in most IDEs of text editors; they're a novelty of little real use in a project.

Spaces have been used to lay out programming since the days of punch cards. Tabs came along and someone obviously thought they were a good idea (they were mistaken :p).

In the days where most modern editors can convert tabs to spaces automatically... they are fairly pointless.

Having to install yet another tool to deal with something as trivial as tabs vs spaces certainly doesn't appeal to me, and I don't think it would to most of my colleagues.


答:
This is the first time I heard of those.  Not sure if they are a good idea but they seem of little use since we have tools (such as indent) that automatically format code already.

What happens when I open your clever elastic tabstops in vim and edit it?  Do the tab automatically clean up or are you left with a mess?

The main drawbacks, as I see them are possibly breaking diffs, version control, and not being compatible with editors that do not support them.  It maybe a lot of code modification to support them and there are more important things than "yet another tab thing to format code" feature.  After all, we can all use indent which does all the above if memory serves.

Title: What are the drawbacks of elastic tabstops?

Body:
Look here: a typical holy war on tabs vs spaces.

Now look here: elastic tabstops. All problems solved, and a bunch of very useful new behaviours added.

Are elastic tabstops even mentioned in that tabs vs spaces discussion? Why not? Are there drawbacks to the elastic tabstop idea so serious that nobody has ever implemented them in a popular editor?

EDIT: I apologise for putting too much emphasis on "why aren't they mentioned". That wasn't really what I intended; that question is possibly even off topic. What I really mean is, what are the biggest drawbacks of this that prevent wider adoption of an obviously beneficial idea? (in an ideal world where everything supports it already)

(Turns out there's already a request on the Microsoft Connect for a Visual Studio implementation of elastic tabstops, and a request in Eclipse too. Plus there's a question asking about other editors that implement elastic tabstops)


答:
I think they'd find much use if IDEs supported them (Microsoft!). Once people found they could slap their flowerboxes at the side and have them nicely readable, they will. You might more comments being added to source code suddenly (which can only be a good thing).

I suppose we could also add comment "tooltips" to the list of 'would it be good if...', so your large comment blocks could be hidden away and viewed easily when needed.
Maybe we could also have comment blocks that form part of documentation (not sandcastle type stuff, proper user-readable documentation snippets that were embedded in the code, not just the method headers)

Disadvantages: it might make your source diffs look bad if a bunch of lines looked like they were changed when really only 1 was modified (if the editor saved the file with the tabs converted to spaces). Or, if the elastic tab was implemented with a single character (or more likely, 2 tabstops) then viewing your source outside the editor could look bad.

I think I like the idea though, 'tab tab' at the end of a line elasticates the comment block and lines up all comments on subsequent lines (that have the double-tab spacing) accordingly.


问:
Arguments for Functional Programming
I've recently been learning F# for fun (I'm a VB.NET/C# dev), and I really like some of what it has to offer. Theoretically that is. But I'm having trouble thinking up of scenarios where I would choose to code in F# rather than in C#. Any ideas?</p>

答:
I'm having trouble thinking up of scenarios where I would choose to code in F# rather than in C#. Any ideas?

From here:

Asynchronous servers

Asynchronous workflows for the asynchronous IO.

Mailbox processor for the thread-safe message passing.

Union types for server state and message catalogue.

Pattern matching and tail recursion for the state machines.

Metaprogramming (e.g. parsing)

Parser generators like fslex and fsyacc.

Parser combinators like FParsec.

Active patterns for elegant hand-rolled parsers.

Algebraic datatypes to represent parse trees.

Pattern matching to manipulate trees, e.g. apply optimization stages.

Reflection for run-time generation of fast code.

Technical computing

Higher-order functions for elegant and fast algorithmic code.

Algebraic datatypes and pattern matching for symbolic manipulation.

Interoperability for wealth of .NET libraries.

Interactivity using F# interactive.

Computation expressions for massaging data.

Units of measure for improved correctness.

GUI applications

Model as asynchronous message passing between user interface code and application logic code.

Higher-order functions let you define user interfaces declaratively.

Logic programming

Persistent collections for easy backtracking.

Tail calls for reliability.

Automatic generalization for easy generic programming.

Testing

Run unit tests interactively.

BDD means writing an interpreter.

Good scripting language for writing test harnesses and visualizing results.

Performance

inline for cost-free higher-order abstraction.

Tail calls for fast state machines.

Purely functional data structures for low latency.

Metaprogramming for generation of optimized code.

Title: Arguments for Functional Programming


答: I would say NO, just because I saw and cleaned a lot of code generated by Dreamweaver. If you need the IDE to generate the code for you, you are prone to forget what the code was for or maybe you did not know in the first place. Especially as a beginner type the code. Programming is learnt by practice not by reading or code generation.


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
I was asked by the software leader of a company to do "simple, rendundant code".
It was forbidden, for example, to add a new parameter to an existing function. You instead had to duplicate the function, leaving the original untouched in order to avoid regressions. No formal testing of course (waste of time).

We were also forbidden from using merge software; each file could only be modified by one programmer at a time. Revision control software was science fiction, of course.

The happiest day of my life was when he was fired (consider that it is very, very difficult to fire someone in Italy).


问:
Does giving a developer a slower development machine result in faster/more efficient code?
Suppose I give my developers a screaming fast machine.  WPF-based VS2010 loads very quickly.  The developer then creates a WPF or WPF/e application that runs fine on his box, but much slower in the real world.

This question has two parts...

1) If I give a developer a slower machine, does that mean that the resulting code may be faster or more efficient?

2) What can I do to give my developers a fast IDE experience, while giving 'typical' runtime experiences?

Update:

For the record, I'm preparing my even-handed response to management. This isn't my idea, and you folks are helping me correct the misguided requests of my client.  Thanks for giving me more ammunition, and references to where and when to approach this.  I've +1'ed valid use cases such as:

- specific server side programming optimizations

- test labs

- the possibly buying a better server instead of top of the line graphics cards

答: My Macbook Pro at work is a few years old.  Between Linux and Windows(to test IE quirks) vms as well as couple of web browsers and terminals open, the OSX spinning wheel shows up a lot.  Guess what I do when it spins, I sit and wait.  In this case, a slow machine does slow productivity.</p>


问:
Functional Programming on the rise?
I have noticed lately that functional programming languages are gaining popularity. I recently saw how the Tiobe Index shows an increase in their popularity in comparison to the last year although most of them do not even reach the top 50 most popular languages according to this index.

And this has been the case for quite some time. Functional programming simply has not become as popular as other models (i.e., object-oriented programming).

I have seen a reborn interest in the power of functional programming, however, and now that multicores are more and more popular, developers have started to show interest in other models of concurrency already explored in the past by languages like Haskell and Erlang.

I see with great interest the fact that despite their lack of significant community acceptance, more and more languages of this sort continue to emerge. Clojure (2007), Scala (2003), F# (2002) are just three examples of the recent last decade.

I have been, myself, investing some time learning Haskell and Scala. And I find great potential in the paradigm which for me was new despite being out there for so long.

And of course, my biggest question is if any of these are going to become popular enough as to consider putting any effort in them, but this is a question that not even Mandrake could answer, despite all the fuss people is making about them.

What I do want to ask is:

In which scenarios should I consider a functional programming language better suited to do a given task? Besides the so recently popular multicore problem of parallel programming.

If I decided to switch to a functional programming language which would you consider being the biggest pitfalls that I would face? (Besides the paradigm change and the difficulty to evaluate performance due to lazy evaluation).

With so many functional programming languages out there, how would you choose the one the better suit your needs?

Any recommendations for further research will be more than welcome.

I have searched the web for opinions, and it appears the all this renew popularity come from the idea that now we're about to hit the wall of Moore's Law and functional programming languages will come and heroically save us. But if this is the case, I would say there are more probabilities of existing popular languages adapting to the paradigm.

Some of you, with more experience working every day with these languages perhaps, can offer more insight on the subject. All your opinions will be better appreciated and carefully considered.

Thanks in advance!

答:
If I decided to switch to a functional programming language which do you consider are the biggest pitfalls that I will face? (Besides the paradigm change and the difficulty to evaluate performance due to lazy evaluation).

Assuming you're a C++/C#/Java dev in industry...

Be prepared for grumpy peers who don't want to learn anything. Be prepared for pointy-haired bosses imposing bad language choices "because they were a coder once". Be prepared for pithy academics on forums patronizing you about monoids. Be prepared for endless language wars because Scala doesn't even have tail call elimination and Clojure really requires foot pedals for all the brackets and don't get me started on Erlang.

If you're a web programmer then the biggest pitfall will probably be your hair.

With so many functional programming languages out there, how would you choose the one the better suit your needs?

I'd start with platform:

OCaml is great on Linux and awful on Windows.

F# is great on Windows and awful on Linux.

Scala and Clojure are great on the JVM.

OwnerDisplayName: edalorzo

Title: Functional Programming on the rise?


问:
Do I really need a unit test framework?
Currently at my job, we have a large suite of unit tests for our C++ application. However we don't use a unit test framework. They simply utilize a C macro that basically wraps an assert and a cout. Something like:

```<code>VERIFY(cond) if (!(cond)) {std::cout << "unit test failed at " << __FILE__ << "," << __LINE__; asserst(false)}
</code>```

Then we simply create functions for each of our tests like

```<code>void CheckBehaviorYWhenXHappens()
{
    // a bunch of code to run the test
    //
    VERIFY(blah != blah2);
    // more VERIFY's as needed
}
</code>```

Our CI server picks up "unit test failed" and fails the build, emailing the message to the developers.

And if we have duplicate setup code, we simply refactor it like we would any other duplicated code we'd have in production. We wrap it behind helper functions, make some  test classes wrap setting up frequently used scenarios.

I know there's frameworks out there like CppUnit and boost unit test. I'm wondering what value do these add? Am I missing what these bring to the table? Is there something useful I could gain from them? I'm hesitant to add a dependency unless it adds real value especially since it seems what we have is dead simple and works well.

答:
Seems like you already use a framework, a home-made one.

What is the added value of more popular frameworks? I would say that the value they add is that when you have to exchange code with people outside your company, you can do it, since it's based on the framework which is known and widely used.

A home-made framework, on the other hand, forces you to either never share your code, or to provide the framework itself, which may become cumbersome with the growth of the framework itself.

If you give your code to a colleague as is, with no explanation and no unit test framework, he would not be able to compile it.

A second drawback of home-made frameworks is the compatibility. Popular unit test frameworks tend to ensure compatibility with different IDEs, version control systems, etc. For the moment, it may not be very important for you, but what will happen if one day you will need to change something in your CI server or migrate to a new IDE or a new VCS? Will you reinvent the wheel?

Last but not least, larger frameworks provide more features you may need to implement in your own framework one day. Assert.AreEqual(expected, actual) is not always enough. What if you need to:

measure precision?

```<code>Assert.AreEqual(3.1415926535897932384626433832795, actual, 25)
</code>```

void test if it runs for too long? Reimplementing a timeout may not be straightforward even in languages which facilitate asynchronous programming.

test a method which expects an exception to be thrown?

have a more elegant code?

```<code>Assert.Verify(a == null);
</code>```

is fine, but isn't it more expressive of your intent to write the next line instead?

```<code>Assert.IsNull(a);
</code>```

Title: Do I really need a unit test framework?

Body:
Seems like you already use a framework, a home-made one.

What is the added value of more popular frameworks? I would say that the value they add is that when you have to exchange code with people outside your company, you can do it, since it's based on the framework which is known and widely used.

A home-made framework, on the other hand, forces you to either never share your code, or to provide the framework itself, which may become cumbersome with the growth of the framework itself.

If you give your code to a colleague as is, with no explanation and no unit test framework, he would not be able to compile it.

A second drawback of home-made frameworks is the compatibility. Popular unit test frameworks tend to ensure compatibility with different IDEs, version control systems, etc. For the moment, it may not be very important for you, but what will happen if one day you will need to change something in your CI server or migrate to a new IDE or a new VCS? Will you reinvent the wheel?

Last but not least, larger frameworks provide more features you may need to implement in your own framework one day. Assert.AreEqual(expected, actual) is not always enough. What if you need to:

measure precision?

Assert.AreEqual(3.1415926535897932384626433832795, actual, 25)

void test if it runs for too long? Reimplementing a timeout may not be straightforward even in languages which facilitate asynchronous programming.

test a method which expects an exception to be thrown?

have a more elegant code?

Assert.Verify(a == null);

is fine, but isn't it more expressive of your intent to write the next line instead?

Assert.IsNull(a);


答:
You already have a framework even if it is a simple one.

The main advantages of a bigger framework as I see them is the ability to have many different kind of assertions (such as asserting raises), a logical order to the unit tests, and the ability to run only a sub-set of unit tests at a time.  Also, the pattern of xUnit tests are fairly nice to follow if you can -- for example the setUP() and tearDown() one.  Of course, that locks you into said framework.  Note that some frameworks have better mock integration than others -- google mock and test for example.

How long will it take you to refactor all your unit tests to a new framework?  Days or a few weeks maybe worth it but more maybe not so much.

Title: Do I really need a unit test framework?

Body:
Currently at my job, we have a large suite of unit tests for our C++ application. However we don't use a unit test framework. They simply utilize a C macro that basically wraps an assert and a cout. Something like:

```<code>VERIFY(cond) if (!(cond)) {std::cout << "unit test failed at " << __FILE__ << "," << __LINE__; asserst(false)}
</code>```

Then we simply create functions for each of our tests like

```<code>void CheckBehaviorYWhenXHappens()
{
    // a bunch of code to run the test
    //
    VERIFY(blah != blah2);
    // more VERIFY's as needed
}
</code>```

Our CI server picks up "unit test failed" and fails the build, emailing the message to the developers.

And if we have duplicate setup code, we simply refactor it like we would any other duplicated code we'd have in production. We wrap it behind helper functions, make some  test classes wrap setting up frequently used scenarios.

I know there's frameworks out there like CppUnit and boost unit test. I'm wondering what value do these add? Am I missing what these bring to the table? Is there something useful I could gain from them? I'm hesitant to add a dependency unless it adds real value especially since it seems what we have is dead simple and works well.


问:
Does anyone prefer proportional fonts?
I was reading the wikipedia article on programming style and noticed something in an argument against vertically aligned code:

Reliance on mono-spaced font; tabular
  formatting assumes that the editor
  uses a fixed-width font. Most modern
  code editors support proportional
  fonts, and the programmer may prefer
  to use a proportional font for
  readability.

To be honest, I don't think I've ever met a programmer who preferred a proportional font.  Nor can I think of any really good reasons for using them.  Why would someone prefer a proportional font?

答:
Never, ever, because monospaced fonts allow me to compare different attributes.

Compare:

name1=["William", "Shakespeare", 1564, "Poetry"]

name2=["John", "Locke",  1632,    "Philosophy"]

name3=["Jonathan", "Littell", 1967,    "Prose"]

To:

```<code>name1=["William",  "Shakespeare", 1564, "Poetry"     ]
name2=["John",     "Locke",       1632, "Philosophy" ]
name3=["Jonathan", "Littell",     1967, "Prose"      ]
</code>```

Or:

a = "iii12345"

b = "AAA12345"

c = "nnn12354"

To:

```<code>a = "iii12345"
b = "AAA12345"
c = "nnn12354" # The mistake ("354") is much easier to spot.
</code>```

The proportional fonts just can't place equivalent attributes exactly one above another.

Title: Does anyone prefer proportional fonts?

Body:
Never, ever, because monospaced fonts allow me to compare different attributes.

Compare:

name1=["William", "Shakespeare", 1564, "Poetry"]

name2=["John", "Locke",  1632,    "Philosophy"]

name3=["Jonathan", "Littell", 1967,    "Prose"]

To:

name1=["William",  "Shakespeare", 1564, "Poetry"     ]
name2=["John",     "Locke",       1632, "Philosophy" ]
name3=["Jonathan", "Littell",     1967, "Prose"      ]

Or:

a = "iii12345"

b = "AAA12345"

c = "nnn12354"

To:

a = "iii12345"
b = "AAA12345"
c = "nnn12354" # The mistake ("354") is much easier to spot.

The proportional fonts just can't place equivalent attributes exactly one above another.


答: Many times I have had to fight with a word processor to get the document to look the way I want without some hidden automatic rule controlling the placement of my words. I don't want to spend one second trying to figure out why the editor is insisting on placing those words there.</p>


答:
As others have already said, you already have your own, home made framework.

The only reason I can see for using some other test framework would be from an industry "common knowledge" point of view. New developers wouldn't have to learn your home made way (albeit, it looks very simple).

Also, other test frameworks may have more features that you could take advantage of.

Title: Do I really need a unit test framework?


问:
Is there any reason to use "plain old data" classes?
In legacy code I occasionally see classes that are nothing but wrappers for data. something like:

```<code>class Bottle {
   int height;
   int diameter;
   Cap capType;

   getters/setters, maybe a constructor
}
</code>```

My understanding of OO is that classes are structures for data and the methods of operating on that data. This seems to preclude objects of this type. To me they are nothing more than structs and kind of defeat the purpose of OO. I don't think it's necessarily evil, though it may be a code smell.

Is there a case where such objects would be necessary? If this is used often, does it make the design suspect?

答:
Agree with the Anna Lear,

Definitely not evil and not a code smell in my mind.
  Data containers are a valid OO citizen.
  Sometimes you want to encapsulate related information together.
  It's a lot better to have a method like...

Sometimes people forget to read the 1999 Java Coding Conventions which
make it very plain that this kind of programming is perfectly fine.
In fact if you avoid it, then your code will smell! (too many getters/setters)

From Java Code Conventions 1999:
One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. In other words, if you would have used a struct instead of a class (if Java supported struct), then it's appropriate to make the class's instance variables public.
http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-137265.html#177

When used correctly, PODs (plain old data structures) are better than POJOs
just like POJOs are often better than EJBs.

http://en.wikipedia.org/wiki/Plain_Old_Data_Structures


答:
There's absolutely nothing wrong with testing against an in-memory DAL as long as you realize it's integration testing as opposed to unit testing.

As soon as your BLL tests start relying on in-memory persistence, you're really testing 2 things : the in-memory DAL and the BLL. Your tests are no longer isolated and they could break for a much larger number of reasons. There can still be value in this kind of tests as they allow you to verify your system plays well with a (relatively) representative persistent storage.

However, the only way to test your BLL in isolation, in other words to assess the basic, atomic correctness of your objects, remains mocking out any external dependency.

Body:
Mocking the DAL/Repository that I pass to the BLL/ViewModels for testing purposes is not much different than creating an in-memory DAL. Right now I'm using an in-memory DAL in a new project instead of mocking it and it's working very well so far (even easier than setting up the mocks I'd say).

Since I haven't seen this done in online/book examples I thought I'd ask. Is there a problem with writing an in-memory DAL for testing the BLL/ViewModels?

On my architecture all components share a common library with all the relevant interfaces. Things are late bound which allows me to swap any component for another of the same interface.


答:
There is actually a third way in Windows to run background services, and it is very common in the UNIX world.  The third way is a CRON job that runs a piece of your infrastructure.  In Windows this is known as the task scheduler and is very common for running code on a scheduled basis.  To use this you would create a command-line app that is executed on a pre defined schedule.  The advantage of this is that you don't have to worry if the process stays up and running like a service, because if it fails for some reason, it will just start up next time.

As for marshaling specific tasks, you really just need to store these tasks in a persistent binary storage.  Until the command line app picks them out of the storage and executes them.  I have done this in the past using the Cassandra database as a Session State Provider for stuffing background tasks for specific users in the Cassandra database, and then having the commandline pick them out and execute them for the user.

This may not have been the typical marshaling solution, but it worked out very well for me and it turned out to be a very elegant solution, because the scheduled tasks survived shutdowns, network problems, and any machine could execute the task since it was centrally stored.

Shameless promotion, but this is my project and the solution I just briefly detailed is why I created the project:
http://github.com/managedfusion/fluentcassandra/


答:
Depends what you want from a team leader. Do you want a technical leader or a manager?

You can (sometimes) find both skill-sets in one person, but it should be very clear in your mind and theirs which role you are trying to fill -- ie. they should only fall back to the other role if time allows.

If you are relying on someone to manage and report to you, and their comfort-zone is technical, you will find that they hide from management problems and you won't get enough information to see that. I have seen this even at Development Director level; it's just a natural response.

If, on the other hand, you intend to continue to manage the team yourself while relying on someone to be your go-to guy for technical advice then you're going to have an epic problem if you've chosen someone whose comfort-zone is man-management. They are going to feel that you've given them management responsibility and no authority with which to do the job.

It's a very tricky line to draw.

Title: Developer to team leader


答:
Adding to what Smokefoot already said, I don't think the experience is the main factor; the set of skills change, you'll need to have deeper project management knowledge, communication abilities, etc.

Experience is important for two reasons: to be accepted as a leader by the others, and to be comfortable with the products and processes of your company. But this is a prereq, not the decision factor, which should be the former items.

And after a certain threshold experience has diminishing returns for such a position. When you move from developer to team leader you'll hardly do any coding anymore, nor you'll have time to inspect what other less experienced developers did, so if you accumulated a lot of technical experience it'll be wasted when you're in a management role. In such cases there should be a position for senior system architecht, for instance, that'd be a best fit. THAT is definitely a case in which the more experience, the better.

The measure to check such things is a difficult issue. Courses attended, standardized tests that HR of big companies and specialized consulting firms apply can help, but they won't give a definitive answer about if someone is prepared or not for a given job. Also certifications like PMI help, but don't solve 100% of the problem. One possible approach would be, if the company is big enough for that, to have each candidate temporarily as a team leader for a small project, and later collect and compare the results.

Title: Developer to team leader


问:
How to not take risks with new collaborators?
My team is going to add new team members and my manager doesn't want to take any risks. I don't think it's a large problem but my manager is concerned that a new programmer would sabotage and accidentally destroy parts of the code or the data e.g. cause data disaster. I say that probability is not very high but still I've been told that it's important to limit the rights of what new collaborators can do.

But this is not practical and we can't eat the cake and have it - adding a collaborator to source control gives the new collaborator access to all the source code and even if there was a way to only let a new member in to parts of the source code (we're using bitbucket for source control) it still wouldn't work since technically the whole project is usually needed to build it so one can't just take a part of the code and expect it to work and able to build on independently.

We're using Google App Engine and nor is it a working idea to create a clone of the app that my collaborator can build on.

I said that we are not the first ones with this problem and that a solution that works for someone else should work for us but my manager seemed not satisfied with that answer.

Can you comment on my situation or give concrete advice what could be done about the "problem" / scenario since it's just a scenario that a newly added developer accidentally deletes the whole datastore, but we don't want it to be possible.

答:
Using network credentials is your first line of defense - if the new person can't access a resource (web server, database server, authentication service etc) they can't compromise it.

This also means that you don't store passwords for your databases and other servers in source control or any place that a new person can access.

In terms of source control - since you are using it, you are protected. If the new person deletes all the code and commits - you just roll back.

As for databases - as any DBA will tell you, having good backups and restore strategy is your protection against many issues.

However, these are all technical means to mitigate a social problem. The fact is that your manager shouldn't be hiring people he can't trust. Having a penalty clause in the contract of this person is the right solution to this issue.

Update - it occurs to me that all of the above will not protect your company from you or one of your existing colleagues with full access to everything fat fingering a deletion of your full datastore. How has your manager mitigated against that???


答:
It depends on the make-up of the team and the individual leader.

An inexperienced team will need a leader with higher technical skills along with the ability, interpersonal skills, and respect to provide mentorship, make coding decisions and uphold standards.

More experienced teams may rely on a leader to handle more managerial tasks, so the others can focus on programming. A small group of highly skilled developers may operate more democratically, but when deadlocks occur, they need a leader who can mediate or just make the tough call.

The potential leader has to come to grips with giving up some of his/her personal coding time. It's a balancing act to get your work done, as well as, be availble to the team. Although no one wants to be micromanaged, it is frustrating to have a team leader so bogged-down in their work, they don't have time to be the leader when you need it.

Title: Developer to team leader


答:
Limiting access to source control does not make sense - thats why you have source control. If the new person makes a bad commit, just revert to a previous version.

I think good automatic tests and frequent code reviews with new team members are much more valuable. And if your boss is concerned about data loss on production systems, you shouldn't let developers have direct unrestricted access to those anyway.

Title: How to not take risks with new collaborators?

Body:
My team is going to add new team members and my manager doesn't want to take any risks. I don't think it's a large problem but my manager is concerned that a new programmer would sabotage and accidentally destroy parts of the code or the data e.g. cause data disaster. I say that probability is not very high but still I've been told that it's important to limit the rights of what new collaborators can do.

But this is not practical and we can't eat the cake and have it - adding a collaborator to source control gives the new collaborator access to all the source code and even if there was a way to only let a new member in to parts of the source code (we're using bitbucket for source control) it still wouldn't work since technically the whole project is usually needed to build it so one can't just take a part of the code and expect it to work and able to build on independently.

We're using Google App Engine and nor is it a working idea to create a clone of the app that my collaborator can build on.

I said that we are not the first ones with this problem and that a solution that works for someone else should work for us but my manager seemed not satisfied with that answer.

Can you comment on my situation or give concrete advice what could be done about the "problem" / scenario since it's just a scenario that a newly added developer accidentally deletes the whole datastore, but we don't want it to be possible.


答:
The way I see it, you both have the advantage, and you are at a "disadvantage" (sic).

The advantage is that you have a system that you feel comfortable with, and which works for you. You are happy that it confirms the validity of your product, and you would probably find no business value in attempting to change all of your tests for something that uses a different framework. If you can refactor your code, and your tests pick up the changes - or better yet, if you can modify your tests and your existing code fails the tests until it is refactored, then you have all of your bases covered. However...

One of the advantages of having a well designed unit testing API is that there is a lot of native support in most modern IDE's.  This won't affect the hard-core VI and emacs users out there who sneer at the Visual Studio users out there, but for those of use who make use of a good IDE, you have the ability to debug your tests and execute them within the IDE itself. This is good, however there is an even greater advantage depending on the framework you use, and that is in the language used to test your code.

When I say language, I'm not talking about a programming language, but instead I am talking about a rich set words wrapped up in a fluent syntax that makes test code read like a story. In particular, I have become an advocate for the use of BDD frameworks.  My personal favorite DotNet BDD API is StoryQ, but there are several others with the same basic purpose, which is to take a concept out of a requirements document, and write it in code in a similar way to how it is written in the spec. The really good APIs however go even further, by intercepting every individual statement within a test and indicating whether that statement executed successfully, or failed.  This is incredibly useful, as you get to see the entire test executed without returning early, which means your debugging efforts become incredibly efficient as you only need to focus your attention on the parts of the test that failed, without needing to decode the entire call sequence. The other nice thing is that the test output shows you all of this information, both in the console and also with some APIs in a nicely formatted report that you can give to management if they are interested in that sort of thing.

As an example of what I am talking about, compare the following:

Using Asserts:

```<code>Assert(variable_A == expected_value_1); // if this fails...
Assert(variable_B == expected_value_2); // ...this will not execute
Assert(variable_C == expected_value_3); // ...and nor will this!
</code>```

Using a fluent BDD API:
(Imagine that the italicized bits are basically method pointers)

```<code>WithScenario("Test Scenario")
    .Given(*AConfiguration*) // each method
    .When(*MyMethodToTestIsCalledWith*, variable_A, variable_B, variable_C) // in the
    .Then(*ExpectVariableAEquals*, expected_value_1) // Scenario will
        .And(*ExpectVariableBEquals*, expected_value_2) // indicate if it has
        .And(*ExpectVariableCEquals*, expected_value_3) // passed or failed execution.
    .Execute();
</code>```

Now granted the BDD syntax is longer, and wordier, and these examples are terribly contrived, however for very complex testing situations where a lot of things are changing in a system as a result of a given system behaviour, the BDD syntax offers you a clear description about what your are testing, and how your test configuration has been defined, and you can show this code to a non-programmer and they will instantly understand what is going on. In addition, if "variable_A" fails the test in both cases, the Asserts example would not execute past the first assert until you had fixed the problem, while the BDD API would execute every method called in the chain, in turn, and indicate which individual parts of the statement were in error.

Personally I find this approach works much better than the more traditional xUnit frameworks do in the sense that the language of testing is the same language as your customers will speak of their logical requirements. Even so, I have managed to use xUnit frameworks in a similar style without needing to invent a complete testing API to support my efforts, and while the asserts will still effectively short-circuit themselves, they read more cleanly.  For instance:

Using Nunit:

```<code>[Test]
void TestMyMethod()
{
    const int theExpectedValue = someValue;

    GivenASetupToTestMyMethod();

    var theActualValue = WhenIExecuteMyMethodToTest();

    Assert.That(theActualValue, Is.EqualTo(theExpectedValue)); // nice, but it's not BDD
}
</code>```

If you do decide to explore using a unit testing API, my advice is to experiment with a large number of different APIs for a little while, and to keep and open mind about your approach.  While I personally advocate for BDD, your own business needs may require something different for your team's circumstances.  The key however is to avoid second-guessing your existing system.  You can always support your existing tests with a few tests using another API if needed, but I certainly wouldn't recommend a huge test rewrite just to make everything the same.  As legacy code falls out of use, you can easily replace it and its tests with new code, and tests using an alternative API, and this without needing to invest in a major effort that won't necessarily give you any real business value.  As for using a unit testing API, if the syntax allows a nice natural language to be used, and if even better, the framework allows your coding/debugging efforts to become more efficient, then you probably can make a good business case for using a suitable unit testing API.

Title: Do I really need a unit test framework?

Body:
The way I see it, you both have the advantage, and you are at a "disadvantage" (sic).

The advantage is that you have a system that you feel comfortable with, and which works for you. You are happy that it confirms the validity of your product, and you would probably find no business value in attempting to change all of your tests for something that uses a different framework. If you can refactor your code, and your tests pick up the changes - or better yet, if you can modify your tests and your existing code fails the tests until it is refactored, then you have all of your bases covered. However...

One of the advantages of having a well designed unit testing API is that there is a lot of native support in most modern IDE's.  This won't affect the hard-core VI and emacs users out there who sneer at the Visual Studio users out there, but for those of use who make use of a good IDE, you have the ability to debug your tests and execute them within the IDE itself. This is good, however there is an even greater advantage depending on the framework you use, and that is in the language used to test your code.

When I say language, I'm not talking about a programming language, but instead I am talking about a rich set words wrapped up in a fluent syntax that makes test code read like a story. In particular, I have become an advocate for the use of BDD frameworks.  My personal favorite DotNet BDD API is StoryQ, but there are several others with the same basic purpose, which is to take a concept out of a requirements document, and write it in code in a similar way to how it is written in the spec. The really good APIs however go even further, by intercepting every individual statement within a test and indicating whether that statement executed successfully, or failed.  This is incredibly useful, as you get to see the entire test executed without returning early, which means your debugging efforts become incredibly efficient as you only need to focus your attention on the parts of the test that failed, without needing to decode the entire call sequence. The other nice thing is that the test output shows you all of this information, both in the console and also with some APIs in a nicely formatted report that you can give to management if they are interested in that sort of thing.

As an example of what I am talking about, compare the following:

Using Asserts:

Assert(variable_A == expected_value_1); // if this fails...
Assert(variable_B == expected_value_2); // ...this will not execute
Assert(variable_C == expected_value_3); // ...and nor will this!

Using a fluent BDD API:
(Imagine that the italicized bits are basically method pointers)

WithScenario("Test Scenario")
    .Given(*AConfiguration*) // each method
    .When(*MyMethodToTestIsCalledWith*, variable_A, variable_B, variable_C) // in the
    .Then(*ExpectVariableAEquals*, expected_value_1) // Scenario will
        .And(*ExpectVariableBEquals*, expected_value_2) // indicate if it has
        .And(*ExpectVariableCEquals*, expected_value_3) // passed or failed execution.
    .Execute();

Now granted the BDD syntax is longer, and wordier, and these examples are terribly contrived, however for very complex testing situations where a lot of things are changing in a system as a result of a given system behaviour, the BDD syntax offers you a clear description about what your are testing, and how your test configuration has been defined, and you can show this code to a non-programmer and they will instantly understand what is going on. In addition, if "variable_A" fails the test in both cases, the Asserts example would not execute past the first assert until you had fixed the problem, while the BDD API would execute every method called in the chain, in turn, and indicate which individual parts of the statement were in error.

Personally I find this approach works much better than the more traditional xUnit frameworks do in the sense that the language of testing is the same language as your customers will speak of their logical requirements. Even so, I have managed to use xUnit frameworks in a similar style without needing to invent a complete testing API to support my efforts, and while the asserts will still effectively short-circuit themselves, they read more cleanly.  For instance:

Using Nunit:

[Test]
void TestMyMethod()
{
    const int theExpectedValue = someValue;

    GivenASetupToTestMyMethod();

    var theActualValue = WhenIExecuteMyMethodToTest();

    Assert.That(theActualValue, Is.EqualTo(theExpectedValue)); // nice, but it's not BDD
}

If you do decide to explore using a unit testing API, my advice is to experiment with a large number of different APIs for a little while, and to keep and open mind about your approach.  While I personally advocate for BDD, your own business needs may require something different for your team's circumstances.  The key however is to avoid second-guessing your existing system.  You can always support your existing tests with a few tests using another API if needed, but I certainly wouldn't recommend a huge test rewrite just to make everything the same.  As legacy code falls out of use, you can easily replace it and its tests with new code, and tests using an alternative API, and this without needing to invest in a major effort that won't necessarily give you any real business value.  As for using a unit testing API, if the syntax allows a nice natural language to be used, and if even better, the framework allows your coding/debugging efforts to become more efficient, then you probably can make a good business case for using a suitable unit testing API.


问:
How close have we gotten to automating code writing?
And I don't mean Autocomplete or automatic code snippets as inserted by modern day editors, or polymorphic code. But what is the state-of-the-art in programs that can go through given inputs and types and information of the desired outputs and output a valid piece of code in a language of choice. I am aware of Genetic Programming, Gene Expression Programming but I don't know of any other efforts. Also googling doesn't turn up much.

Is anyone aware of any advancements on this front?

Edit: When i say "output a valid piece of code", I mean an AI or something similar working out the logic and the flow of control and implement it in an imperative language. Imperative language only, since that's the tough part. Nevertheless, if you know of any new languages being developed to support this kind of idea, please do mention, as maybe our current set of languages are not suitable for the kind of early AI we may first chance upon.

答:
Domain-Specific Languages are about as close as we'll ever get.

You will always have to give the computer some rules to work with. But the more those rules are defined in a manner specific to their domain, the less input there will have to be.

Domain-specific languages that target web development require less coding than languages that are more generic. Domain-specific languages that target testing require less coding than languages that don't. Domain-specific languages that target genetics require less coding than languages that don't. And so on.

Now, here comes the big question: When does a domain become big enough to justify writing a domain-specific language for it? Web development and testing are things that at least half of the development world is working on. It was inevitable that frameworks would spring up, reducing the amount of boilerplate code for these things (which is, essentially, a domain-specific language).

But how about your company's business domain? Is it worth focussing on the things that are commonly mentioned in your company and making it so that you can reference those things easily in code? I don't think we've really found that balance yet, although domain-driven design is about answering that question.


答:
Have a procedure to make sure they are paired with an experienced team member for certain operations the first few times. Source control and backups will protect you, but it can still cost several hours of labor.

As to the breaking things, the higher your score on the Joel test the easier it should be for them to correctly build and deploy the first time they have to.


问:
Convince a lone developer to use a separate build tool instead of the IDE one-click build
In my years of programming Java and more recently Scala, I've never used Ant, Maven, Gradle or any of those build tools for Java.  Everywhere I've worked there was a build manager who took care of all of that -- I'd compile locally with the IDE for development and unit testing, then check in the source code and notify the build manager who did what was necessary to compile everybody's files for the shared environment.

Now that I'm between contracts I've been working on my own self-funded project and it's getting to the point where it could be good enough to actually make money.  I even have a potential investor lined up and plan to show them a beta version in the next few weeks.

But all along I just click the build button on the IDE, and it creates the Jar file and it works just fine.  Of course, the conventional wisdom suggests that I "should" be writing my own Ant/Maven/Gradle scripts and using that instead of the IDE, but what are the concrete advantages of that in my situation (working alone)?

I've done some reading about how to use those build tools, and it just looks like I'd be writing hundreds of lines of XML (or Groovy or whatever) to do to what the IDE does in one click (the IDE-generated Ant XML for the project is over 700 lines).  It just looks error-prone and time-consuming and unnecessary for my situation.  Not to mention the learning curve, which would take away time from all the other work I'm doing to get the product ready to show people.

答:
As long as your code is in source control, using the IDE to make your distributables is fine.

As a one man shop, is your time better spent adding new features to your product, or writing build scripts? Something tells me its not writing build scripts.

OwnerDisplayName: Gigatron

OwnerDisplayName: Nate