答:
One way to do it is to write stories for your integration testing, during which you write new stories for any bugs you find, then fix the bug stories in the next iteration.

Another way to do it is to just make a story that says "Fix bugs found in integration testing."  From previous releases you should have an idea of how many issues are usually found, and how difficult they are to fix, so you can assign story points based on that knowledge.  You could maybe split it up into components if that makes it more manageable.  There's always unavoidable uncertainty in this.  Add some extra story points to account for it.

You've probably realized belatedly that the best way is to incorporate a little integration testing into every iteration if possible.  Congratulations on recognizing that and improving your process just a little bit for your next release.


问:
When you should and should not use the 'new' keyword?
I watched a Google Tech Talk presentation on Unit Testing, given by Misko Hevery, and he said to avoid using the new keyword in business logic code.

I wrote a program, and I did end up using the new keyword here and there, but they were mostly for instantiating objects that hold data (ie, they didn't have any functions or methods).

I'm wondering, did I do something wrong when I used the new keyword for my program. And where can we break that 'rule'?

答: Objects that only hold data, or DTOs (data transfer objects) are fine, create those all day long. Where you want to avoid new is on classes that perform actions, you want the consuming classes to instead program against the interface, where they can invoke that logic and consume it, but not be responsible for actually creating the instances of the classes that contain the logic. Those action-performing or logic containing classes are dependencies. Misko's talk is geared towards you injecting those dependencies and letting some other entity be responsible for actually creating them.

ContentLicense: CC BY-SA 3.0


答:
This is more guidance than hard-and-fast rule.

By using "new" in your production code, you are coupling your class with its collaborators. If someone wants to use some other collaborator, for example some kind of mock collaborator for unit testing, they can't – because the collaborator is created in your business logic.

Of course, someone needs to create these new objects, but this is often best left to one of two places: a dependency injection framework like Spring, or else in whichever class is instantiating your business logic class, injected through the constructor.

Of course, you can take this too far. If you want to return a new ArrayList, then you are probably OK – especially if this is going to be an immutable List.

The main question you should be asking yourself is "is the main responsibility of this bit of code to create objects of this type, or is this just an implementation detail I could reasonably move somewhere else?"

Title: When you should and should not use the 'new' keyword?

Body:
I watched a Google Tech Talk presentation on Unit Testing, given by Misko Hevery, and he said to avoid using the new keyword in business logic code.

I wrote a program, and I did end up using the new keyword here and there, but they were mostly for instantiating objects that hold data (ie, they didn't have any functions or methods).

I'm wondering, did I do something wrong when I used the new keyword for my program. And where can we break that 'rule'?


答:
The crux of this question is at the end: I'm wondering, did I do something wrong when I used the new keyword for my program. And where can we break that 'rule'?

If you are able to write effective unit tests for your code, then you did nothing wrong. If your use of new made it difficult or impossible to unit test your code, then you should re-evaluate your use of new. You could extend this analysis to interaction with other classes, but the ability to write solid unit tests is often a good enough proxy.


问:
Web based applications

Possible Duplicate:

  What should every programmer know about web development?

Where do I start if I want to build a web based application?
Books, tutorials, online resources.
From a quick look at the web I can see that Html, Css and JavaScript should be the subjects to learn. Do you agree? What would you recommend to a professional C++ programmer?

答:
A good place to start is by reading one of those to learn about the basics of a web page (without application logic):

The Web Standards Project (WaSP)

Web Standards Curriculum by Opera

Then start investigating about web development frameworks and pick one that fits your way of thinking. Popular options are:

Ruby on Rails

Django

ASP.NET

Google Web Toolkit

a ton of PHP frameworks

Note that there are many more options, but these seem to be the most popular.

Once you've chosen a framework (any will do, don't worry too much about choosing the best one), look at tutorials, there should be plenty about 'creating your first application'.

Once you're there, it should be fairly simple to find more information and figure out what you need to know in order to go further.

Good luck!

Title: Web based applications


答:
Others have already mentioned this point, but wanted to quote this from Uncle Bob's (Bob Martin) Clean Code because it might make it easier to understand the concept:

"A powerful mechanism for separating construction  from use is Dependency Injection (DI), the application of Inversion of Control (IoC) to dependency management. Inversion of Control moves secondary responsibilities from an object to other objects that are dedicated to the purpose, thereby supporting the Single Responsibility Principle. In the context of dependency management, an object should not take responsibility for instantiating dependencies itself. Instead, it should pass this responsibility to another "authoritative" mechanism, thereby inverting the control. Because setup is a global concern, this authoritative mechanism will usually be either the "main" routine or a special-purpose container."

I think it is always a good idea to follow this rule. Others mentioned the more important one IMO -> it decouples your class from its dependencies (collaborators). Second reason is that it makes your classes smaller and terser, easier to understand and even reuse in other contexts.


问:
Is it possible for an amateur to become a good programmer?
A professional full-time programmer can do a great job by continuously learning from their work. How can an amateur programmer train to become a good programmer? </p>

<p>** If you like to play music or sing, you can do it because it is your hobby and you are interested, and you can become a good singer or music player. But you do not need to become a professional singer or do singing for a living. Is this also true for programmers ? Any amateur programmer who is famous?</p>

答:
Is it possible for an amateur to become a good programmer?

Yes, it is possible, however it takes long time :

it takes about ten years to develop expertise in any of a wide variety of areas, including chess playing, music composition, telegraph operation, painting, piano playing, swimming, tennis, and research in neuropsychology and topology. The key is deliberative practice: not just doing it again and again, but challenging yourself with a task that is just beyond your current ability, trying it, analyzing your performance while and after doing it, and correcting any mistakes. Then repeat. And repeat again.

How can an amateur programmer train to become a good programmer?

Again from the same source :

Get interested in programming

Program

Talk with other programmers

If you want, put in four years at a college

Work on projects with other programmers

Work on projects after other programmers

Learn at least a half dozen programming languages


问:
How do you keep track of your past projects?
After having hard time trying to remember details of my past projects several years ago I was wondering how programmers usually keep track of that?

This kind of information comes handy with job interviews etc.

Do you write down technologies used, challenges faced etc to some kind of "jumbo CV"? Or do you just trust your memory?

答:
I have Folders..

```<code>Client\Project\Code

Clinet\Project\Notes

Clinet\Project\Documentation
</code>```

I also keep all previous Vers of My CV.

But, For the most part i just trust my memory. Then go back and look for details if needed. I never needed to look for details for an interview, only when looking for code that might transfer over to a new project.

Body:
I have Folders..

Client\Project\Code

Clinet\Project\Notes

Clinet\Project\Documentation

I also keep all previous Vers of My CV.

But, For the most part i just trust my memory. Then go back and look for details if needed. I never needed to look for details for an interview, only when looking for code that might transfer over to a new project.


问:
In what situations is it a bad idea to use open source code for a corporate project?
Are there any situations where it may not be a good idea to use the code of an open source project, even if your company might allow you to do so?

Some cases that I think might be valid include:

The code may be implemented in a different languages.

It is not portable

It may need some other close-source libraries

What might be some other reasons?

答:
One thing I didn't see in the other answers is auditing.

If you're making something that's going to be determine if a missile gets launched, or how often someone breathes, it's pretty important to have auditing. If you need to import 20,000 lines of code from a "general purpose" open source library, it will usually be more productive to instead write 2,000 lines of code internally for just the one special purpose you need the library for. This goes much more so where all code must have formal proofs.


答:
I have worked with 5/6 employers and all of them have different business

and almost all of them in different technologies....
so I dont think keeping any code or notes could have ever helped me.

As other pdr said I just keep removing outdated stuff from CV to keep it simple

Title: How do you keep track of your past projects?

Body:
After having hard time trying to remember details of my past projects several years ago I was wondering how programmers usually keep track of that?

This kind of information comes handy with job interviews etc.

Do you write down technologies used, challenges faced etc to some kind of "jumbo CV"? Or do you just trust your memory?


答:
I have a two-page CV and, each time I add stuff to it, I remove the least relevant stuff from it, to keep it to two pages.

I figure that anything I cannot remember, or which I have deemed less important than other things, is really not of interest to a prospective employer.


答: Just like pdr, I keep the "main" part of my CV under a specific size (2-3 pages), but I also include a one-page list of technologies with experience level (in number of years).</p>


问:
What exactly is a programming language? What enables us to write in such a language?
Alright I'm new to programming and I admit this is a fairly abstract question.

The natural language we speak every day exist because people can understand each other. How can computers understand my code written in a certain language?

Let's say Mr. A creates a new language. How is that accepted by machines? Must the creator communicate with the machine using machine language to create a new language? What guarantees that we can written in a language while getting understood by the machine properly?

答:
You can sum up pretty much the entire answer to your set of questions with the word "compiler".  A compiler is a special program whose function is to take source code as input, apply language rules determined by the language designer in order to figure out what the code means, and produce code with the same meaning in another language as output.  This is generally machine code or some form of bytecode (the "machine code" for virtual machines), although specialized compilers that translate code into other high-level languages do exist.  They're beyond the scope of this question, though.

Not all languages have a compiler.  Some of them have an interpreter instead, which does all the same things a compiler does, except that instead of producing machine code after determining what the program means, it simply executes the program immediately.  But the basic principles of parsing (reading) the code and determining what it means are the same.

Answering any more in-depth than this would get into compiler theory, which is a very broad subject.  If you're interested in the topic, you should start by reading the Wikipedia article for "compiler" and checking the links from it, and if you have specific questions, feel free to ask them on here.


问:
Which CS courses are a "must" for a web developer
My goal is to learn how to program a website with Python/Django in the next year. From what I've understood, I also have to learn HTML, CSS, JavaScript.

I understand in order to build a website, I will need to find a co-founder whose skills far exceed mine. But still, the situation will be way different if I'm a person who's closer to his/her level and has dedicated a lot of time teaching himself than every other "I have an idea, just need a tech co-founder" type of guy.

I do plan to pursue a degree in computer science, but after finishing high school last May decided to take an year off, so I am free to learn programming in the next 10 months.

For now, I have the chance to attend some college courses in a top institution. Which ones are a must for a web developer so that I don't have any gaps in my understanding of programming and write "sophisticated code"?

EDIT:Thank you all for the help!From the courses suggested I may be able to attend some/none/all of OOP(with Java),Networks and Graphics,SE-Algorithms,Discrete Math for Comp.Scientists,Databases,Information Retrieval and Data Mining.Which of those are more important for Web development with Django?

I've read a lot of times people saying that self-taught programmers had gaps in their knowledge, didn't write clear code.This is why I'm asking which CS courses can fill those gaps? Not only in practical skills,but in mindset,way of thinking.

答:
Databases and SQL!

I don't believe you will find a web development job that doesn't involve them.  Be able to write select, update, insert, and delete statements.  Understand table normalization (which refers to not storing redundant data).  Understand primary keys, foreign keys, check constraints, joins, subselects, group by, unions, indexes.  Know how to write efficient queries.  Know how to add indexes to make queries more efficient and when it will will slow down statements that write to the database.

If you want to go further, that is a good idea.  Know how to create views, materialized views (if the db accepts them), stored procedures, how to configure a database to make hot back-ups, etc.

There is a lot of talk lately of "NoSQL" but be aware that the vast majority databases are still RDBMS.  Furthermore, most web programming tends to be creating a web front end for a database.  And even if you work with NoSQL databases, you will probably still work with RDBMS as wall.  And frameworks like Hibernate that try to abstract away the databases, generally can't really work as well as you would hope.


答:
If you write a program in a programming language, a different program will convert the symbols in your program into symbols the computer understands. Sometimes this takes several steps. For example in C:

User writes program in high-level language (C) which is not understood by CPU, but is directly understood by the programmer (we hope!).

Compiler convertes C into Assmebly language, which is not directly understood by the CPU but is easy to convert into something else that is.

Assempler converts Assembly into sequence of binary codes that are directly understood by the CPU. Some compilers skip the above step (step 2) and produce the compiled binary directly from the source code.

To  guarantee that the computer understands your program, the compiler or interpreter will give you an error and usually halt if it encounters something that is not compilable, such as a syntax error. If your program cannot be compiled, it can never get to the stage where your program will try to run it and fail because it did not "understand" it.

To create a new language, you first design your high-level language and then you have to find a way to map the symbols of your new language to the assembly language commands that your CPU understands.

Title: What exactly is a programming language? What enables us to write in such a language?

Body:
Alright I'm new to programming and I admit this is a fairly abstract question.

The natural language we speak every day exist because people can understand each other. How can computers understand my code written in a certain language?

Let's say Mr. A creates a new language. How is that accepted by machines? Must the creator communicate with the machine using machine language to create a new language? What guarantees that we can written in a language while getting understood by the machine properly?


问:
Is it bad to join open-source projects as an amateur?
I've thought for about six months now that I should join an open-source iPhone or iPad project to hone my skills in Objective-C, but every time I go to do it I see thousands of lines of code on huge projects that I end up convincing myself I would never understand. I always think that my commits would just end up being a hassle for project admins and more senior contributors, so I always back out at the last second.

My question essentially is, is it a hassle when an intermediately-experienced programmer joins an open-source project?

答:
Jump in. Monitor the development lists for a while and introduce yourself when you feel comfortable. Many projects have some easier Jobs in bug-fixing or documentation which the regulars will be happy to point out to you.
Most Projects are quite friendly to new hands, and they will bring you up to scratch fast enough so that you may become a real asset to the Project.

After a while you will be familiar with the structure and the most important parts of the code base. Learning to understand code like this is a really important part of programming, and open source is a great way to learn it.


答:
No, it's not.

If the code-base of projects you look at is too daunting, consider:

Choosing a (even) smaller project to work with.

Choose a smaller task within the project:

Write an example/tutorial/demo for something

Update and fix documentation (all projects, OS or no, need better docs)

Fix many low-priority but easy to fix bugs (great exposure to code, devs are usually happy, low risk)

There are ways to contribute without commit access to the core source, such as:

Submitting patches, which can be commented on.

Forking and submitting pull requests (see above)

Forking and working away on your own, just to see where it takes you. If you're happy, ask the devs to take a look at whatever you've done to see if it makes sense.

To overcome your "fear" of not having your commits accepted, go for safe points at first. This will allow both you and the dev-team to gain confidence in your relation, and to learn each other's way of thinking. As you improve (both in skill, experience, code quality and understanding of your OS project's team and it's dynamics) you will be able to tackle greater task while introducing less hassle.

It also helps in asking for suitable starting points, and see what the team might find suitable for you.

As an example, I've contributed a bit to Buildbot over the years. I started just fixing a few small issues, then I bumped the quality of the Mercurial source steps by fixing some glaring bugs. Finally, I rewrote most of the Web-pages and swapped out html-pasting in code to a template based HTML generation solution. The latter was a few hundred commits over a few months of hard work.

I've also done some Mercurial work, but those guys are more picky and the technology is more complicated, so I haven't yet gotten any fixes into the core. I've made a few bug reports and written a few small extensions, but I haven't gotten anything bigger off there at the moment.

Hope it helps.

Title: Is it bad to join open-source projects as an amateur?

Body:
I've thought for about six months now that I should join an open-source iPhone or iPad project to hone my skills in Objective-C, but every time I go to do it I see thousands of lines of code on huge projects that I end up convincing myself I would never understand. I always think that my commits would just end up being a hassle for project admins and more senior contributors, so I always back out at the last second.

My question essentially is, is it a hassle when an intermediately-experienced programmer joins an open-source project?


答:
It is a good question. A proper answer forms a good half of what is called "Computer Science".

For starter, I'd recommend skimming through denotational and operational semantics, and then reading this book. It will give you a more or less solid understanding of what the programming language is, and how it can be formally defined.

If the above is a bit too academic, you can start with Petzold, "Code", and then come back to the semantics.


答:
Like anything else the best way to get better at something is to immerse yourself in the environment in which you wish to become good, and surround yourself with people far superior to you who are willing to tolerate you and teach you. Not easy to do, but that's what I've found is the best way to learn to be good at something the fastest.

But when it comes to being a truly gifted programmer, you have to be just that, gifted. If you're not a naturally talented violin player, you will never be as good as the masters no matter how hard you try or what instrument you buy. Likewise, if you don't have that gift that makes programmers truly genius you will never be them either.

Title: Is it possible for an amateur to become a good programmer?

Body:
A professional full-time programmer can do a great job by continuously learning from their work. How can an amateur programmer train to become a good programmer? </p>

<p>** If you like to play music or sing, you can do it because it is your hobby and you are interested, and you can become a good singer or music player. But you do not need to become a professional singer or do singing for a living. Is this also true for programmers ? Any amateur programmer who is famous?</p>


问:
Question about new buzzwords about old concepts
What is the fascination with taking old concepts coming up with a buzzword for them and pitching it as new technology complete with 800 page tome with nerd on the cover?

A long long time ago, lets say the 80's, I wrote software. It was designed reasonably well and it worked and was maintainable. It separated out different high level functions into different libraries of code and so on.

Sometime in the past 10 years, I lose track of the exact time, "Patterns" became popular. Whole encyclopedias were written about design patterns and this patterns and that patterns.

We've been doing it for decades (and I'm sure long before I started programming) yet it is suddenly new and novel.

Is this just a gimmick to sell books and educational classes? Why add so much noise to the already overcomplicated world of programming when getting things done well is really what matters.

答: Well, when the GoF wrote the book on Design Patterns, they intended to essentially document existing best practices so people didn't have to reinvent the wheel. So your criticism that these are old ideas is actually the whole point.</p>


答:
First, let's define "language" in terms of what it is. Language requires first a vocabulary (a list of words that define concepts that are the objects of communication), and then a syntax (a "primer" or set of rules that define the structure of the communication).

At this most basic level, C# isn't all that different from English. What makes C# a "programming language" is its intent, and therefore its design; it is designed to be digested into individual low-level commands. As such, the predefined vocabulary is limited, the syntax is very rigidly enforced, and the entire language is designed to be consumed in a very well-known predefined way by its "audience" (the computer; more accurately the compiler, which will digest the source code into an "intermediate language" of simple commands that can then be further translated into machine code by the "runtime"). You don't write prose or poetry in C#; you tell the computer to do a job in the most unambiguous way possible.

For computers, yes, a tool, usually called the compiler, is needed to take what you write in code and convert it to the instructions that the computer can use. Computer science, like most technology, is an inherently iterative, "layered" process. When computers were first invented, they were programmed by manually entering the binary instructions. Those instructions became standardized for each processor into hexadecimal "machine codes"; the difference is only in how the binary digits are grouped for display to humans. Then, in assembler code, the list of commands and some basic identifiers like register names were substituted for their hexadecimal codes when writing programs; ASM can still be converted 1:1 into native machine code. The quantum leap was to 3rd-generation "imperative" programming, which basically takes more human-understandable, abstract concepts like variables and logic loops and digests them into the native instructions, using patterns based on keywords and syntax. Early languages like COBOL, FORTRAN, Pascal, and C can still be "translated" by a human into a particular machine language (usually 8086 ASM). Then came the revolution of object-oriented programming, which is basically additional syntax rules that define code as being conceptually encapsulated in "objects" that have some combination of state and logic.

Nowadays, we are well into the "4th-generation" of languages, which are languages written to define communication with other programs instead of directly to the machine. Widely defined, this includes "markup" languages like XML/HTML, "scripting" languages like JavaScript and SQL, and most of the "sandbox" languages like Java and the .NET Framework (which compile into an IL that is then interpreted further by a runtime that abstracts away machine and platform-specific details). You could also say it encompasses the realm of functional programming languages, which are HEAVILY dependent upon a runtime to provide abstraction of not just machine-specific details, but of operation-specific details. These 4th-generation languages are more or less infeasible for a human to translate into native machine instructions, and the point is that it wouldn't be a worthwhile endeavor; the strength of these languages is the layered process in which they are used to eventually tell a computer what to do at the low levels.


答:
Jiggy's got a good point. In addition, there is the concept of a "paradigm"; an established way of thinking about how to solve problems. Different paradigms have different best practices. When new paradigms come around, best practices change to take advantage. Notable shifts in thinking include object-oriented vs procedural coding, event-driven programming (where the OS controls the program instead of the other way around), multithreading (computers are approaching the limit of how fast they can do one thing at a time; so, make them able to do several things at the same time), etc etc.

When things change, old patterns and practices become obsolete. If you're learning how to structure code using a C book from the 80s, you will be run out of town trying the same thing in C++. If you know C++, you will have a leg up learning Java, but there is still a world of difference, primarily in memory management (you always destroy your own objects in C++; in Java, you almost NEVER destroy your own objects). Even between Java and C#, two object-oriented memory-managed languages, there are very different ways of thinking about structuring objects in those languages (implementing the "singleton" pattern, for instance, is different based on the semantics of each language). Knowing these semantic differences, and yet still being able to tie them back to basic object-oriented concepts, as languages grow and expand their capabilities, is what keeps authors and publishers in business writing programming books.

Title: Question about new buzzwords about old concepts

Body:
What is the fascination with taking old concepts coming up with a buzzword for them and pitching it as new technology complete with 800 page tome with nerd on the cover?

A long long time ago, lets say the 80's, I wrote software. It was designed reasonably well and it worked and was maintainable. It separated out different high level functions into different libraries of code and so on.

Sometime in the past 10 years, I lose track of the exact time, "Patterns" became popular. Whole encyclopedias were written about design patterns and this patterns and that patterns.

We've been doing it for decades (and I'm sure long before I started programming) yet it is suddenly new and novel.

Is this just a gimmick to sell books and educational classes? Why add so much noise to the already overcomplicated world of programming when getting things done well is really what matters.


答:
In short, whenever you use "new", you are tightly coupling the class containing this code to the object being created; in order to instantiate one of these objects, the class doing the instantiating must know about the concrete class being instantiated. So, when using "new", you should consider whether the class in which you're placing the instantiation is a "good" place for that knowledge to reside, and you're willing to make changes in this area if the form of the object being instantiated were to change.

Tight coupling, that is an object having knowledge of another concrete class, is not always to be avoided; at some level, something, SOMEWHERE, has to know how to create this object, even if everything else deals with the object by being given a copy of it from somewhere else. However, when the class being created changes, any class that knows about the concrete implementation of that class must be updated to correctly deal with that class's changes.

The question that you should always ask is, "Will having this class know how to create this other class become a liability when maintaining the app?" Both major design methodologies (SOLID and GRASP) would usually answer "yes", for subtly different reasons. However, they are only methodologies, and both have the extreme limitation that they were not formulated based on knowledge of your unique program. As such, they can only err on the side of caution, and assume that any point of tight coupling will EVENTUALLY cause you a problem relating to making changes to either or both sides of this point. You must make a final decision knowing three things; the theoretical best practice (which is to loosely-couple everything because anything can change); the cost of implementing the theoretical best-practice (which may include several new layers of abstraction that will ease one type of change while hindering another); and the real-world probability that the type of change you are anticipating will ever be necessary.

Some general guidelines:

Avoid tight coupling between compiled code libraries. The interface between DLLs (or an EXE and its DLLs) is the main place where tight coupling will present a disadvantage. If you make a change to a class A in DLL X, and class B in the main EXE knows about class A, you have to recompile and release both binaries. Within a single binary, tighter coupling is generally more permissible because the entire binary must be rebuilt for any change anyway. Sometimes, having to rebuild multiple binaries is unavoidable, but you should structure your code so that you can avoid it where possible, especially for situations where bandwidth is at a premium (like deploying mobile apps; pushing a new DLL in an upgrade is far cheaper than pushing the entire program).

Avoid tight coupling between the major "logic centers" of your program. You can think of a well-structured program as consisting of horizontal and vertical slices. Horizontal slices may be traditional application tiers, like UI, Controller, Domain, DAO, Data; vertical slices might be defined for individual windows or views, or for individual "user stories" (like creating a new record of some basic type). When making a call that moves up, down, left or right in a well-structured system, you should generally abstract said call. For example, when validation needs to retrieve data, it should not have access to the DB directly but should make a call to an interface for data retrieval, which is backed by the actual object that knows how to do this. When some UI control needs to perform advanced logic involving another window, it should abstract the triggering of this logic via an event and/or callback; it doesn't have to know what will be done as a result, allowing you to change what will be done without changing the control that triggers it.

In any case, consider how easy or difficult a change will be to make, and how likely said change will be. If an object you are creating is only ever used from one place, and you do not foresee that changing, then tight coupling is generally more permissible, and may even be superior in this situation to loose coupling. Loose coupling requires abstraction, which is an extra layer that prevents change to dependent objects when the implementation of a dependency must change. However, if the interface itself must change (adding a new method call, or adding a parameter to an existing method call), then an interface actually increases the amount of work necessary to make the change. You have to weigh the likelihood of different types of change impacting the design, and it will be infeasible or even impossible to make a system that is closed to all types of change.


答:
As you pointed out, humans communicate via a "natural" language such as English, French, German, between each other.  They are called natural because we naturally acquire them rather than intentionally invent them (Esperanto being an exception).

A formal language is one invented for some purpose or other. A programming language such as C, for instance, is a formal language invented for the purpose of programming computers.

All languages, can be described using a grammar.  A hierarchy of grammars was described by Noam Chomsky in 1956.  It consists of the following levels:

Type-0 grammars (unrestricted grammars).  They are the most general, and are equivalent to a Turing Machine. As such, the problem of deciding whether a given string is part of an unrestricted grammar is undecidable.

Type-1 grammars (context-sensitive grammars).  Almost all natural languages such as English are context-sensitive.  An example of context-sensitivity in English are the two phrases:  "Time flies like an arrow."  and  "Fruit flies like a banana."  In general, it is difficult for computers to understand context-sensitive languages.

Type-2 grammars (context-free).  Context-free languages are the theoretical basis for the syntax of most programming languages.

Type-3 grammars (regular grammars).   The family of regular languages can be obtained by regular expressions. Regular languages are commonly used to define search patterns and the lexical structure of programming languages.

Type 2 (context-free) and type 3 (regular) grammars are most often by computers because parsers for them can be efficiently implemented.

BNF (Backus Normal Form or Backus–Naur Form) is a notation technique for context-free grammars, often used to describe the syntax of languages used in computing.

For example an identifier might be described as:

```<code><identifier> ::= <letter> { <letter> | <digit> }
</code>```

which means it must starts with a letter and can contain additional letters or digits.

Earlier, a letter is defined a 'a' | 'b' | 'c' etc., and digit is defined as '0' through '9' using the same type of notation.

A C "for" statement might be defined as:

```<code> <for_statement> ::=
    'for' '(' <expression> ';' <expression> ';' <expression> ')' <statement>
</code>```

Lexical analyzers and parsers (the first stages of a compiler or interpreter) are then constructed to accept the specific grammar described by the BNF for a particular language.  Lexical analyzers are typically used to separate out the various tokens of a language (such as a keyword, identifier or a number), and the parser is used to figure out how the tokens work together, such as how a "for" statement is constructed.

Body:
As you pointed out, humans communicate via a "natural" language such as English, French, German, between each other.  They are called natural because we naturally acquire them rather than intentionally invent them (Esperanto being an exception).

A formal language is one invented for some purpose or other. A programming language such as C, for instance, is a formal language invented for the purpose of programming computers.

All languages, can be described using a grammar.  A hierarchy of grammars was described by Noam Chomsky in 1956.  It consists of the following levels:

Type-0 grammars (unrestricted grammars).  They are the most general, and are equivalent to a Turing Machine. As such, the problem of deciding whether a given string is part of an unrestricted grammar is undecidable.

Type-1 grammars (context-sensitive grammars).  Almost all natural languages such as English are context-sensitive.  An example of context-sensitivity in English are the two phrases:  "Time flies like an arrow."  and  "Fruit flies like a banana."  In general, it is difficult for computers to understand context-sensitive languages.

Type-2 grammars (context-free).  Context-free languages are the theoretical basis for the syntax of most programming languages.

Type-3 grammars (regular grammars).   The family of regular languages can be obtained by regular expressions. Regular languages are commonly used to define search patterns and the lexical structure of programming languages.

Type 2 (context-free) and type 3 (regular) grammars are most often by computers because parsers for them can be efficiently implemented.

BNF (Backus Normal Form or Backus–Naur Form) is a notation technique for context-free grammars, often used to describe the syntax of languages used in computing.

For example an identifier might be described as:

<identifier> ::= <letter> { <letter> | <digit> }

which means it must starts with a letter and can contain additional letters or digits.

Earlier, a letter is defined a 'a' | 'b' | 'c' etc., and digit is defined as '0' through '9' using the same type of notation.

A C "for" statement might be defined as:

 <for_statement> ::=
    'for' '(' <expression> ';' <expression> ';' <expression> ')' <statement>

Lexical analyzers and parsers (the first stages of a compiler or interpreter) are then constructed to accept the specific grammar described by the BNF for a particular language.  Lexical analyzers are typically used to separate out the various tokens of a language (such as a keyword, identifier or a number), and the parser is used to figure out how the tokens work together, such as how a "for" statement is constructed.


问:
Pros/Cons for a Data Structure covering multiple databases?
I'm about to extend a system containing two separate systems. Or domains, if we see the system as a domain level.

Today

One domain is used internally. The other is public, which means it is more exposed to whatever can happen "out there". Services of some kind (few options apply) perform operations between the two separate systems. The public and internal system have separated database storages, and are not related to each other. Let's call the domains client and store.

Tomorrow

I'm into a new application that will have lots of more user-specific information at the client domain. The design may be comparable to a 'private database' that has a facebook-account-link as a key. This compares to a database that held user actions, but had no user specific data (such as address, date of birth, email and so on), just a key to the Facebook-server. On the other side, the STORE database (compared to Facebook-server in this case) doesn't know anything about the user actions.

Goal

Approximately 85-90% of the queries will be within their own domain (client if client, store if store). Though, there are some situations where the client need to get data from the STORE database and the STORE needs to create/handle users in the CLIENT database.

Questions out from my head

Is this a good way to go?

Pros/cons? Orphans? Database Performance? Problematic .NET coding?

Principles of the choice for the boundaries of data?

.. and other things you may know or think of

An example of structure

..dbStore.Users

userid (PK)

name

dateOfBirth

emailAddress
-> Wallet (another table)

..dbStore.Wallet

walletid (PK)

userid

createddate
-> BankAccount (another table, not typed)

..dbClient.users

storeUserId (unique, non-inc) <-- corresponds to dbStore.User, no restraint

accessLevel

lastLoggedIn

serviceXxEnabled

udpAccessKey

..dbClient.action

actionid (PK)

isSomething

someDate

anythingElse

..dbClient.installation

installationid (PK)

userid

We won't collect bank-account information, it just to give a picture of the data structure and its importance in keeping it in separate systems. I hope this Q is comprehensible enough.

答:
Let's think of this from the perspective of potentially splitting up one database into two, in order to highlight the differences.

The main disadvantages of a split are:

Inability to use DRI on common columns. Hardly a deal-breaker but you do need to start designing your application(s) around the possibility that an ID might not exist where you expect it to, and you need to work on good synchronization solutions.

Inability to perform efficient joins. This is actually only partially true; in some cases, if both databases reside on the same server, you can perform cross-database queries - however, even in these cases, the code can be quite awkward to write, as you can no longer rely on externalized connection strings and so on.

Distributed transactions are much more costly than single-database/single-connection transactions. In a Microsoft environment you'll need to invoke the DTC and that adds about 10x overhead.

If you use a Dependency Injection framework, there's a pretty good chance it's been written so far to assume that there will only ever be one IDbConnection, ISessionFactory, etc. Using two database might require a lot of refactoring. Not an issue long-term, but entails an up-front cost.

A bit more cognitive stress for developers as they now have to remember which database each table is in, and/or refer to some documentation for it.

Backup/restores can be more complicated, as you will likely need to restore both databases if one fails, in order to keep them in sync. Which also means that your backup plan will also need to be designed to minimize the possibility of inconsistencies (unless your application is very fault-tolerant in this regard).

That's the bad. There are also some advantages:

You can move one database to a different server in order to reduce processor/memory contention.

You can move one database onto a different drive or SAN in order to reduce I/O contention.

Potential elimination of the "single point of failure" problem. Each system should, at least in theory, be able to keep functioning reasonably well if the other one fails.

Easier to focus team efforts and have independent dev/test/release cycles for each system, if you're working on a larger team.

Potentially improved security; if one database gets compromised, private data in the other database can remain private. (Many security architectures are split into several parts for exactly this reason.)

I'd be remiss if I didn't also mention some of the alternative solutions, or compromises if you will:

Different schemas in the same database. This gives you logical separation of concerns without forcing physical separation. In fact schemas can be used to run multiple instances of the same application within the same database, and you can share common tables (e.g. configuration tables) between them.

Filegroups and files. A lot of SQL developers seem to forget that these exist; if one of your main concerns is the physical storage then it's possible physically segregate the tables for each system while still keeping them in the same logical database.

Pub/sub is an alternative to the specific performance problem of big long distributed transactions, although it will require some additional development and support to maintain, both up-front and over time.

Generally speaking, I try to keep as much transactional data as possible in a single database because of the localized performance advantages it provides; there are many ways to scale up and scale out while still having a single logical database. But ultimately it's an architectural decision that depends on your access patterns and business requirements.


答: www.bigbucket.org allows me to have and unlimited number of private repositories. All with convinient timelines. This is what I have been using of late to keep track all my projects.</p>


问:
Is it unnecessary to use Github (social coding) even if you are the only one working on a project?
I started using Github now that I'm working on a project with some guys. And I started to wonder if I should use it in my personal projects too. I'm not sure if this will help me in some way or if it is unnecesary? </p>

答:
As has been stated before, using git does not require using Github. Are you using git itself for your personal project(s)? If not, as has been stated already numerous times, I would strongly urge checking out some sort of version control package. If you don't like the syntax of Git, try Mercurial or even SVN.

The advantage of Github and similar sites, beyond version control and the already-mentioned advantage of it acting as a stable backup, is the social aspect. Unless your project is entirely closed-source, the very definition of open-source implies that you want to make your code available for others to read. If you do have an open-source project, why would you want to hide it?


问:
Need help - brainstorming php scheduler class
I've never written a php class before from scratch.  But I guess you have to start somewhere right?  I've got an idea, but need help with logic.  Please tell me what you think.  Below is shorthand obviously.  In the planning stages.</p>

```<code>Class -
 -> type (recurring, single, day)
 -> Recurring days (4,2,3,4,1,2....etc. for odd schedules- need even pairs)
 -> Shift Type (onshift, vacation, medical, etc...)
 -> Emp Id
 -> Start
 -> End
 -> Location Id
 -> Hours per day
 -> Day start time

 get schedule ( by account/location/company/unit/crew/individual )
      select single entries
      separate array into days (1 day) increments
      if single entries have linking day entries, replace array with day entry information
      return mysql array of days for the time period;

 set schedule ( dates, emp id)
      if recurring
          if already exisits || conflicts with existing
              error
          create recurring template in db table
          create single db entries using recurring days for 1 year
      if single
          if date is between dates already in db || more than 1 year out
              error
          else
              insert into db
      if day
          if no existing single range
             error
          else
             insert into db under day table, with id linking to id of existing single.

 remove recurringOnly(emp id)
      delete all entries with recurring id

 remove all entries( from this date forward, emp id )
      delete entries with start date > date

 cronUpdate( cron start / end dates)
      if cron start / end dates
           delete anything with dates bigger than nextUpdate (to make sure no errors)
           select recurring db entries with nextUpdate between cron start/ end
           insert into db the next set of "recurring days" for the employee
           update nextUpdate date for employee
      else - error
</code>```

答: The first data that you listed could be the attributes. Remember to set the attributes to private and the getters and setters method public. Then you can create the methods based on these algorithms you already got. it is a nice idea to code your class in a single file with the same name as your class to help organize your project.</p>

OwnerDisplayName: Logan Klenner


问:
How do you organize an ASP.NET MVC 3 application with potentially hundreds of views but with only a few entry points?
Assumptions:

Minimalist ASP.NET MVC 3 application for sending emails where the view represents the contents of an email.

Over 500+ email types. I would NOT like to have 500+ actions in my controller corresponding to each email type.

Email types are stored in an enum named MailType, so we could have:

MailType.ThankYouForYourPurchase, MailType.OrderShipped, etc.

The view name is the same as the mailType name:

MailType.OrderShipped would have a corresponding view: OrderShipped.cshtml

Some views would directly use an Entity while others would use a ViewModel.

So, given that I have 500+ email types, what is the best way/pattern to organize my application?

Here is what I was thinking,

Controller:

```<code>    public class MailController : Controller
    {
        public ActionResult ViewEmail(MailType mailType, int customerId)
        {
            string viewName = mailType.ToString();

            var model = _mailRepository.GetViewModel(mailType, customerId);

            return View(viewName, model);
        }

        public ActionResult SendEmail(MailType mailType, int customerId)
        {
            ...
        }
    }
</code>```

MailRepository Class:

```<code>    public class MailRepository
    {
        private readonly CustomerRepository _customerRepository;
        private readonly OrderRepository _orderRepository;

        //pretend we're using dependency injection
        public MailRepository()
        {
            _customerRepository = new CustomerRepository();
            _orderRepository = new OrderRepository();
        }

        public object GetViewModel(MailType mailType, int customerId)
        {
            switch (mailType)
            {
                case MailType.OrderShipped:
                    return OrderShipped(customerId);
                case MailType.ThankYouForYourPurchase:
                    return ThankYouForYourPurchase(customerId);
            }

            return _customerRepository.Get(customerId);
        }

        public Order OrderShipped(int customerId)
        {
            //Possibly 30 lines to build up the model...
            return _orderRepository.GetByCustomerId(customerId);
        }

        public Customer ThankYouForYourPurchase(int customerId)
        {
            return _customerRepository.Get(customerId);
        }
    }
</code>```

But then this would lead to my MailRepository class becoming extremely large unless I somehow broke it up...

答:
To avoid any one class getting too big you need to be mapping mail types to classes rather than method names - pick a naming convention like MailControllers.OrderShippedController and load the class with reflection.

I'd also note that your MailRepository seems to be behaving more like a controller - not a major issue, but something that could become confusing later.


问:
Besides Waterfall, what are other plan-driven software development methodologies?
I just read Balancing Agility and Discipline. Poor title aside, it contrasted a plan-driven project team that was employing PSP/TSP and an agile team using Extreme Programming.

When the authors provided an example of a plan-driven methodology, they used Personal Software Process/Team Software Process. Although, out-of-the-box, these are plan-driven methodologies, they are also designed to be used as process frameworks and ultimately only specify what types of things to do and not how to do them, whi
ch makes them potentially useful even in an agile environment. It's possible to be agile and still adhere to the PSP principles, and I'm not familiar enough with the TSP to say for sure, but my understanding is that it is very similar.

At one point in the book, they list a number of methodologies and rank them in terms of agility. Methods like Scrum, Lean, Crystal, and XP are at the top. The bottom (from most to least agile) consists of the Rational Unified Process, the Team Software Process, Feature-Driven Development, CMMI, Software CMM, the Personal Software Process, and Cleanroom.

Watts Humphrey, in PSP: A Self-Improvement Process for Software Engineers, dedicates a chapter to process definition, and specifically modifying the Personal Software Process. The common theme is that processes are prescriptive (they say what to do) and not descriptive (how to do it). I would surmise that the TSP is very much the same way. CMMI has also been used in conjunction with agile methods, and the SEI has a book on it (which I have not yet read).

Feature-Driven Development is often touted as an agile approach to project management, yet the authors choose to rank it as a less agile methodology.

RUP is an iterative framework. Although I'm not incredibly familiar with it, the fact that it's a framework lends me to group it with SW-CMM, CMMI, and PSP/TSP in that it could be implemented either as an agile or as a plan-driven methodology.

The only other example that the book provides that I agree with is Cleanroom Software Engineering. The key components of Cleanroom are the use of formal methods, statistical quality control, and statistically-sound testing. I don't see why these couldn't be used in an agile (iterative/incremental) method, with added the time and cost overhead.

Just to clarify what I'm looking for, the family of agile methods includes specific implementations of an abstract idea in the form of Scrum and Extreme Programming. These realize the concepts of iterative and incremental development, responding to change, people (individuals and teams), frequent delivery of working software, collaborating with the customer, and so forth. They clearly specify roles, artifacts, meetings, timeboxes, and other practices and to "do Scrum" or "do Extreme Programming" means to take the package. Even so, they allow for tailorability and the creation of new processes (but then you aren't "doing Scrum" or "doing XP"). However, I haven't found the "do X" of plan-driven methodologies - most of the work appears to be toward frameworks that could be agile or plan-driven.

So, my question: What are examples of more plan-driven software development methodologies? A number of the process frameworks (PSP/TSP, SW-CMM, CMMI, RUP) allow for plan-driven or agile development, as well, but none are descriptive. But are there any truly plan-driven methodologies, that are, for example, direct counterparts to Scrum and Extreme Programming?

答:
Honestly, I have doubts about the validity of any claim made in a book which sets Agility and Discipline off against each other. Agile methodologies require much more discipline, in my experience, than other kinds of development.

That is, if you're going to exploit the benefits of Agile processes, you must follow the enabling practices that come with them (see Martin Fowler's Is Design Dead article; he is mostly talking about XP, but it applies to all Agility, in my opinion). That takes a lot of discipline.

But, to answer your question, I think that all truly plan-driven methodologies are variations of Waterfall, such as Spiral, which takes development through multiple levels of prototyping before switching to a Waterfall approach, and Cap Gemini SDM, which is Waterfall with very distinct phases where each ends before another starts.


问:
BitBucket - what's the catch? (TANSTAAFL, right?)
The BitBucket capabilities, and pricing (up to 5 users for free) left me wondering what the catch was... there is no such thing as a free lunch, after all.

What is BitBucket getting out of my unpaid participation, besides a handsome man to freely include in their promotional materials (per the TOS)?

答:
This is the same profit model that people have been using for years, since the rash of free anti-virus software for individuals.

Basically, you will get used to using BitBucket, and when there comes a time that you are working at a company who needs a service like BitBucket, you will go straight there rather than evaluating the alternatives. Then they will make money from your participation.


问:
Why is there usually a reference to Java when when people talk about C#?
I don't know much about C# but I've been programming in Java for a few months now. I had always heard what C and C++ were, but was a little curious about where C# came from. I'm a little confused about the C# language since even though it's one of the 'C' languages (C, C++, C#), on the other hand all of my professors seem to line it up against Java, and not the others.

If anyone can clarify that would be great :)

答:
C# is a managed code (compiled to bytecode and run on a virtual machine) language developed by Microsoft to serve as one of the core languages of the .NET framework. It features garbage collection and easy integration with other languages.

It gets lined up with Java because has most of the same features, a C like syntax, managed code execution model, and an automatic garbage collector. It's also an "easy" Object Oriented Language.

It resulted from an effort by Microsoft to develop a VM for Java until Sun sued them over it. Thus that project was shelved and the .NET project took over as Microsoft's effort to do a managed code environment mainly aimed at desktop applications.

You can write a lot of things in C# and run them in a fair number of places now with the Mono framework but it still lacks the shear power of C or C++ as well as being substantially harder to massacre your ambiguously owned cloned feet.

Anything that uses the XNA framework was likely written at least in part in C#.


答: @bitbucket answered this a few times. To put it short, pretty much they like to make their income off businesses and teams who can afford it. Free users are not costing them that much, and when the time comes, a once time single user who upgraded to a team, which needs more serious support, will probably upgrade to a paid account as well. After all, IMHO, their prices are pretty reasonable.

Title: BitBucket - what's the catch? (TANSTAAFL, right?)

Body:
The BitBucket capabilities, and pricing (up to 5 users for free) left me wondering what the catch was... there is no such thing as a free lunch, after all.

What is BitBucket getting out of my unpaid participation, besides a handsome man to freely include in their promotional materials (per the TOS)?


答:
Here are some suggestions that have worked well for me:

Keep CV/resume up-to-date--never know when you might need it, and recording each new skill or accomplishment as it is fresh in your memory will help.

Record information about a project in a wiki, whether it be a team or company based wiki, or even your own personal wiki.

Write about new skills or topics of interest in a blog--this is a great way to record useful tips and ideas.


问:
Filesystems that use logging: If you're writing the data in the log (on disk), and in the actual locations themselves (also on disk) then...?
Aren't you essentially writing the same data twice, to the disk? Doesn't this cause a slowdown of a factor of ~2x?

What optimizations can be made to minimize the cost of having to write things twice?

答:
Yes, you are writing the same data twice. That is precisely the point of a journaling file system. They are intended for reliability over performance. By using write-ahead logging, they (virtually) eliminate any risk of data corruption, because if the system crashes in the middle of a data write, they can just replay the log and recover accordingly.

The best alternative I'm aware of that offers better performance is copy on write, which is sort of an "immutable" file system. It never updates in-place; instead, it writes out the new data to a new area of the disk, and only after that's been successful does it update the metadata and point new requests to the new data.  This has better performance characteristics but is also more prone to fragmentation and requires a lot of extra capacity (especially if you're writing a huge file).

If there are other techniques that have the same reliability characteristics, then I don't think that any of them are in very common use today. Mostly you just see journaling and COW.


答:
You are correct that Journalling does increase the write load, however, the cost of doing two writes like this is fairly minimal, and typically has some hardware caching involved, and can be optimized in other ways as well.

Worse than Journalling, problematically slow operations typically involve write->read->write ordered operations, as tend to occur in a RAID-5 scenario, where you need to read the non-parity sector that the data being written is paired with, in order to compute the parity sector's data.  (For this reason, RAID-1 is preferable to RAID-5 in systems that read and write many small files - but RAID-5 wins for larger files as would be used in video production, as this WRW sequence can be converted to WWW if you overwrite both data sectors AND the parity sector.)

As an alternative, ZFS in particular uses Copy-on-Write semantics, where the new file data is written out to an empty part of the disk, then the metadata sectors are updated (typically in a single operation) so that no matter when the operation is aborted, there's never an inconsistent file state.

All in all, Journalling is fairly inexpensive for the benefits it provides, but there are of course, costs to implementing it, or any other file system corruption countermeasure. YMMV.

Title: Filesystems that use logging: If you're writing the data in the log (on disk), and in the actual locations themselves (also on disk) then...?

Body:
Aren't you essentially writing the same data twice, to the disk? Doesn't this cause a slowdown of a factor of ~2x?

What optimizations can be made to minimize the cost of having to write things twice?


答:
Others have addressed why this does in fact cause a slowdown. Here are some ways to mitigate it:

Some filesystems journal everything but file contents. This means that the filesystem itself will always be in a consistent state even if the data in files is not. This gives better performance than journaling everything.

Another option is a log-structured filesystem, which essentially consists of only a journal. Writes are incredibly fast, and consistency is guaranteed. The downside is that reads are much slower, because every read is a journal replay. This also makes deletions and garbage collection more complex.


答:
@Tom Clarkson answer is good. Additionally, if you are not already doing so, you could use an IOC Container such as Spring.NET for example to declare a "MailTypeRetriever" bean. The only parameter in the constructor of this bean should be a map (dictionary) with the key being the mail type, and the value the name of the method to call.

That way your mail type configuration is not in your code, and the code for calling the right method will be short.
Of course, you don't need Spring for externalizing your mail type configuration, that's just one way of doing it.

Title: How do you organize an ASP.NET MVC 3 application with potentially hundreds of views but with only a few entry points?

Body:
Assumptions:

Minimalist ASP.NET MVC 3 application for sending emails where the view represents the contents of an email.

Over 500+ email types. I would NOT like to have 500+ actions in my controller corresponding to each email type.

Email types are stored in an enum named MailType, so we could have:

MailType.ThankYouForYourPurchase, MailType.OrderShipped, etc.

The view name is the same as the mailType name:

MailType.OrderShipped would have a corresponding view: OrderShipped.cshtml

Some views would directly use an Entity while others would use a ViewModel.

So, given that I have 500+ email types, what is the best way/pattern to organize my application?

Here is what I was thinking,

Controller:

```<code>    public class MailController : Controller
    {
        public ActionResult ViewEmail(MailType mailType, int customerId)
        {
            string viewName = mailType.ToString();

            var model = _mailRepository.GetViewModel(mailType, customerId);

            return View(viewName, model);
        }

        public ActionResult SendEmail(MailType mailType, int customerId)
        {
            ...
        }
    }
</code>```

MailRepository Class:

```<code>    public class MailRepository
    {
        private readonly CustomerRepository _customerRepository;
        private readonly OrderRepository _orderRepository;

        //pretend we're using dependency injection
        public MailRepository()
        {
            _customerRepository = new CustomerRepository();
            _orderRepository = new OrderRepository();
        }

        public object GetViewModel(MailType mailType, int customerId)
        {
            switch (mailType)
            {
                case MailType.OrderShipped:
                    return OrderShipped(customerId);
                case MailType.ThankYouForYourPurchase:
                    return ThankYouForYourPurchase(customerId);
            }

            return _customerRepository.Get(customerId);
        }

        public Order OrderShipped(int customerId)
        {
            //Possibly 30 lines to build up the model...
            return _orderRepository.GetByCustomerId(customerId);
        }

        public Customer ThankYouForYourPurchase(int customerId)
        {
            return _customerRepository.Get(customerId);
        }
    }
</code>```

But then this would lead to my MailRepository class becoming extremely large unless I somehow broke it up...


答:
Probably because Java and C# are extremely similar: They are both class-based OOP languages with single inheritance and interfaces, strong static typing, garbage collection built into the language, copy semantics that bind to types (value types vs. reference types), generics, namespace hierarchies, reflection, and they both run on a virtualized environment (JRE / .NET runtime). They also share a large part of their syntax.

The other languages from the "C-like" family are different from both Java and C# in many regards: C doesn't have classes, it is weakly-typed, it does not have garbage collection, copy semantics are explicit on use, it compiles directly to machine code, and it lacks generics (offering C Preprocessor macros and implicit casts instead). C++ does have classes, but uses multiple inheritance instead of interfaces; it also offers templates, which are superficially similar to generics but work differently under the hood; it is similar to C in most other regards. Javascript, also very similar to C in its syntax, shares garbage collection and a virtualized environment with Java and C#, but it uses dynamic typing, prototype-based OOP, and it does not use the half-way compilation approach of Java and C#.

Title: Why is there usually a reference to Java when when people talk about C#?

Body:
I don't know much about C# but I've been programming in Java for a few months now. I had always heard what C and C++ were, but was a little curious about where C# came from. I'm a little confused about the C# language since even though it's one of the 'C' languages (C, C++, C#), on the other hand all of my professors seem to line it up against Java, and not the others.

If anyone can clarify that would be great :)


问:
How to pronounce CRUD?
I was talking to a co-worker and was talking of how Database operations usually can be broken down into one of the elements of CRUD- Create, read, update and delete.

That's when I realised that I do not know how to pronounce CRUD.

So is there a definite, well accepted way to pronounce CRUD?

答: I pronounce it like I pronounce the word meaning miscellaneous and unidentified matter, "Crud". The IPA version is /kɹʌd/. </p>

Title: How to pronounce CRUD?


答: Erm - exactly as you would think... like "MUD" but with a "CR" on the front ?</p>

Title: How to pronounce CRUD?

Body:
I was talking to a co-worker and was talking of how Database operations usually can be broken down into one of the elements of CRUD- Create, read, update and delete.

That's when I realised that I do not know how to pronounce CRUD.

So is there a definite, well accepted way to pronounce CRUD?


答:
k as in kilo, r as in romeo, u pronounced as u in mud, d as in delta.

I hope this give you some idea. :-)

Title: How to pronounce CRUD?


答:
K -RUD

Its actually a term I don't use as in Belfast CRUD is slang from rubbish.

Title: How to pronounce CRUD?


答: Like Crush but with a D at the end:)</p>

Title: How to pronounce CRUD?

Body: Like Crush but with a D at the end:)


问:
Is it worth using tool agnostic concepts in a development team?
We waste a lot of time using tool specific terms when we are all really talking about the same things. The problem is that person1 is familiar with toolset1, person2 with toolset2 etc. So each uses a set of terms that they are the most comfortable with and in the end, we end up talking at cross purposes. Has anyone come across this problem in your work place? How did you resolve it? I am asking specifically about development teams here.</p>

答:
Every project I worked for had a specific vocabulary, in particular acronyms. but this was on a per project basis, not on a toolset one.

So, try to develop a unique jargon for your project and let developers translate for their own individual usage.

OwnerDisplayName: carleeto


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Those who try to build idiot-proof systems always underestimate the persistence and ingenuity of idiots.

— Anon

LastEditorDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5


问:
Why use phpunit when traditional manual testing can be used
When I make a web app I test my work on the browser to see if I receive any errors and fix them. I have made complex applications and testing this way has been easy and fast. I have watched many videos on youtube regarding phpunit and cannot find a purpose for it. Why is this library useful? Is phpunit more for php framworks like cakephp or zend? I dont use any framework just core php. Would or can phpunit be useful for me? If yes, how?

There is also xdebug but I'm not sure if it relates.

答:
Yes!

Yes. Absolutely yes.

Actually, that needs qualification. Unit testing frameworks like PHPunit are useful if you are writing and maintaining an application that other people are expected to use.

The reasons why unit testing is useful include

Regression testing for specific bugs that you've exposed, and

Running unit tests are much much faster than manual testing, and so can be much more thorough.

In the company I work for, we write unit tests before we write the code that passes them. This helps us produce sane, testable designs (because we have to think about what we will write before we do it!) and it provides an easy way of asserting that our code meets the requirements of the user.


答:
Manual testing (i.e. clicking on the application in the browser) is actually called functional testing. Functional testing and unit testing are two different methods used in QA. Why do you think you can't use them both?

Unit testing is used to test if your code is working as expected (e.g. if your web service handles error appropriately or if it returns the results as expected).

When you click on your application you are testing the functionality of your application.

Would or can phpunit be useful for me? If yes, how?

Unit testing has many benefits - it can be very useful tool when refactoring because you can confirm that the code is working as expected. Also, when someone is reading your code it can be very helpful to see the intended use of the code in the unit tests.

Title: Why use phpunit when traditional manual testing can be used

Body:
When I make a web app I test my work on the browser to see if I receive any errors and fix them. I have made complex applications and testing this way has been easy and fast. I have watched many videos on youtube regarding phpunit and cannot find a purpose for it. Why is this library useful? Is phpunit more for php framworks like cakephp or zend? I dont use any framework just core php. Would or can phpunit be useful for me? If yes, how?

There is also xdebug but I'm not sure if it relates.


答:
Would or can phpunit be useful for me? If yes, how?

Yes, definitely.

phpunit belongs to the family of xUnit test libraries. You use these libraries to create automatically executable tests which verify your application's behavior. This is important to ensure, among others, that your changes don't break existing functionality.

Listing all reasons for automated testing, the various kinds and technologies would be too much. Check out the following links to read about:

Why to write unit tests and this link

How to write good tests (also search for unit tests and xUnit test patterns)

How to test the user interfaces (also search for selenium)


答:
Has anyone come across this problem in your work place? How did you resolve it? I am asking specifically about development teams here.

On every new project, I start by creating a domain model which lists the various entities, their names and relationships. You might want to read up on domain models using the Wikipedia page. When you got the model, print it in poster size and position it somewhere where everybody can see it.

If you are in an international team, agree upon a language for the entities' names. I recently saw a poster which showed the German and Dutch translation for the most commonly used English entity names and technical terms. This helps introducing a common vocabulary.

If you are solely having problems with tool specific terms - do the same thing and create a "translation table". For instance you might all have different terms for building an application (e.g. compiling, packaging...) but in conversations you are all going to say "building". Again, print this translation table and hang it up so that nobody needs to feel ashamed for forgetting a certain term in the third month of the project :-).

Title: Is it worth using tool agnostic concepts in a development team?

Body: We waste a lot of time using tool specific terms when we are all really talking about the same things. The problem is that person1 is familiar with toolset1, person2 with toolset2 etc. So each uses a set of terms that they are the most comfortable with and in the end, we end up talking at cross purposes. Has anyone come across this problem in your work place? How did you resolve it? I am asking specifically about development teams here.</p>


问:
How do I overcome paralysis by analysis when coding?
When I start a new project, I often times immediately start thinking about the details of implementation. "Where am I gonna put the DataBaseHandler? How should I use it? Should classes that want to use it extend from some Abstract superclass..? Should I use an interface? What level of abstraction am I going to use in my class that contains methods for sending requests and parsing data?"

I end up stalling for a long time because I want to code for extensibility and reusability. But I feel it almost impossible to get past thinking about how to implement perfectly.

And then, if I try to just say "screw it, just get it done!", I hit a brick wall pretty quickly because my code isn't organized, I mixed levels of abstractions, etc.

What are some techniques/methods you have for launching into a new project while also setting up a logical/modular structure that will scale well?

-- EDIT --

Well, this is already the type of question that is difficult to accept an answer to, but wanted to get some more feedback, see if there's some consensus. TDD sounds really cool and, frankly, I've been meaning to get more up to speed on using JUnit, etc. At the same time, what do the fans of TDD think about the fact that one legitimate point with relation to TDD solving my particular issues, is that TDD doesn't really seem to address the question of design. Sure, I agree TDD will help me define what I want to do and then I can gradually work through the how, but there are many different overall design patterns/structures that could all pass through unit testing. That's just it: it tests single UNITS. I guess I'm a bit confused... I dunno. Maybe I'm just trying to procrastinate even more by trying to figure out some magical formula, but I would like to hear how some of the veterans approach this area...

Thanks!

答:
I usually start from the ground up, create the simplest prototype possible and get something running.  Use the prototype to reverse engineer the happy path test cases, the test cases to drive the interfaces and then think about pre/post contracts to help build out test coverage.

Don't worry about abstraction, optimization, or verification until the problem is fully understood.


问:
How do I unit test a web forms site?
How do I unit test a web forms site? It seems to me that as so much of it depends on state and user input it wouldn't be feasible. </p>

<p>If it's not feasible is there a valid automated alternative? </p>

答:
I am sorry for missing the "unit" part of the question...

SeleniumHQ is your friend for tests from the front end. It is not a unit test, more like a black box testing. You still need to think of valid test cases...

Title: How do I unit test a web forms site?


答:
Quite obviously, an entire web forms page is not a unit, and thus cannot be unit tested. However, there are some things you can do for automated tests:

unit test individual components of the page (any methods that perform actual logic)

unit test components used by the page (custom controls, underlying business logic, etc.)

automated functionality testing (by remote-controlling a browser, or sending HTTP requests through something like cURL)

automated penetration testing (there are tools that will try to find possible injection points, and automatically run harmless yet detectable injection attacks on your page)

load testing

checking the layout against a list of usability and house-style bullet points (although this is very hard to automate; it is usually more feasible to just do it manually every now and then)

Title: How do I unit test a web forms site?

Body:
How do I unit test a web forms site? It seems to me that as so much of it depends on state and user input it wouldn't be feasible. </p>

<p>If it's not feasible is there a valid automated alternative? </p>


问:
What is it called when you set properties on object initialization?
What is it called when you set properties on object initialization?

```<code>var customer = new Customer() {RequestID = request.ID, AddressID = 5};
</code>```

Is it considered good practice?

答:
Be wary of using Object Initializer syntax with anything other than simple values.

If you start having complex calls as part of the value initialisations it can be very hard to debug as an error in one of the value calls can be reported in the Constructor call and it's much harder to workout which value is actually causing the problem.


问:
Domain Lookup API
I am looking to incorporate a domain name lookup facility in my website to make sure if a domain is available or not. The only api I could find on the net is http://www.domaintools.com/api/docs/domain-search/ . But this is paid. Is there any other api available which might be cheaper / free.

I am working with php, query.

答:
I don't know if there is a free one, but you can always write your own. Within your code, submit a form to for example http://www.whois.net/ and scrap the resulting HTTP response. On that particular website, when the domain is free it shows "Domain name is not currently registered. Available for you now!". Look for this value in the response. If you find this string it means that the domain is already taken (then you can scrap additional information on who registered the domain), otherwise it is free. It is your choice then to either return a true/false value or more detailed information if you want to scrap more data when the domain is taken.

It's really only a few lines of code. Although if there is a free API, by all means, use it.

Title: Domain Lookup API


答:
Yes, you can. You just have to be careful to separate your concerns well. In short, you have to remove all your logic from the code-behind and put it into other classes.

There are two common ways to do this.

The simple way is to rethink all of your event handlers in terms of "What information does the system give me? What information do I need to populate on the page?" and then provide a service class which does that conversion.

In this case, the service layer should know very little about the nature of your presentation layer. You still have to take the data returned from the service and populate the correct components of the WebForm in your code-behind and this remains untested (at least by unit tests, you can still employ integration tests). But this is rarely where code goes wrong, it is much more likely to fail in the logic.

A more complicated, but more effective, way is to use the Model View Presenter pattern. When we tried that, we found that the Presenters quickly became very coupled to the framework and, the more we developed MVP, the more clear it was that MVP really wanted to be MVC but couldn't be.

That said, others have done this very successfully - there is even a webformsmvp framework available to remove the heavy lifting - so your mileage may vary.

Title: How do I unit test a web forms site?


答: You can simply do DNS queries yourself. You would just have to always start at top (so called root servers) and work your way down the domain name, to be sure it does exist. Don't know what language you're using, but most languages out there have apropriate libraries for the job. Sure it requires some knowledge about DNS system itself, but since you are querying DNS system directly, you can be sure it is and will remain free.</p>

Title: Domain Lookup API

Body:
I am looking to incorporate a domain name lookup facility in my website to make sure if a domain is available or not. The only api I could find on the net is http://www.domaintools.com/api/docs/domain-search/ . But this is paid. Is there any other api available which might be cheaper / free.

I am working with php, query.


问:
Is using goto ever worthwhile?
goto is almost universally discouraged. Is using this statement ever worthwhile?

答:
Surely it depends on the programming language. The main reason goto has been controversial is because of its ill effects that arise when the compiler lets you use it too liberally. Problems can arise, for example, if it lets you use goto in such a way that you can now access an uninitialised variable, or worse, to jump into another method and mess with the call stack. It should be the responsibility of the compiler to disallow nonsensical control flow.

Java has attempted to “solve” this problem by disallowing goto entirely. However, Java lets you use return inside a finally block and thus cause an exception to be inadvertantly swallowed. The same problem is still there: the compiler is not doing its job. Removing goto from the language hasn’t fixed it.

In C#, goto is as safe as break, continue, try/catch/finally and return. It doesn’t let you use uninitialised variables, it doesn’t let you jump out of a finally block, etc. The compiler will complain. This is because it solves the real problem, which is like I said nonsensical control flow. goto doesn’t magically cancel definite-assignment analysis and other reasonable compiler checks.

Title: Is using goto ever worthwhile?


答: The WHOIS protocol is free and a number of servers exist which you can query. I would suggest you actually start at the wikipedia page, because it's got a fairly good introduction and pointers to further information.

Title: Domain Lookup API


问:
What to do with .git folder and data in Xcode?
I am using Hg for my development. Recently, I upgraded to Lion and Xcode 4.2 and I have created a Xcode project in my source tree. The Xcode by default uses Git and created .git folder in the project folder.

Being able to do versioning in Xcode is a plus but it is sort of redundant with both Git and Hg.

The problem is, should I check in the .git (folder and files) in the Xcode project folder or not? Or should I just switch off Git in Xcode and delete .git folder?

Thanks.

答:
The second. Versioning version data doesn't make much sense, unless you want to track the state of the entire git repository in your mercurial repository. Even worse, if you also add the .hg to the git repo, both repositories will try to track each other; once you commit to hg, git will see a difference, which you should then commit, and then hg in turn sees a new difference, and so on, indefinitely.

In other words, it doesn't make sense to put the version control directory under version control. Either roll with only git, or with only mercurial. If you really want to, you can use git to interface with mercurial repositories, and vv (AFAIK both can read each other's data structures), and you can even use them alongside each other, but that would be kind of redundant and pointless.


答: .git is the folder that has the git repo of XCode. If you want to keep both your Hg and git repos in sync you can use something like hg-git

Title: What to do with .git folder and data in Xcode?

Body:
I am using Hg for my development. Recently, I upgraded to Lion and Xcode 4.2 and I have created a Xcode project in my source tree. The Xcode by default uses Git and created .git folder in the project folder.

Being able to do versioning in Xcode is a plus but it is sort of redundant with both Git and Hg.

The problem is, should I check in the .git (folder and files) in the Xcode project folder or not? Or should I just switch off Git in Xcode and delete .git folder?

Thanks.


答: Speaking from experience: Only if it's done right.  By "right" I mean minimal code-behind and something like the above-mentioned Model-View-Presenter to make the Web Form "dumb".  This usually proves to be very difficult with brownfield applications because they weren't designed with this in mind and it's a near-Herculean effort to refactor/rewrite pages to use it.

Title: How do I unit test a web forms site?


问:
What Java client+server stack to allow async client info popups and responses?
Being new to Java I'd like to use the following scenario to steer my learning and could use some advice!

First I want to build a Java server app that handles login and client settings, and based on client info pulls up random database entries and sends these random entries to the client on a timer.  This must work for many clients, each on their own private timers against the main database, and just keeps looping on timers so it's not a one-shot lookup.

Second I want the client to stay logged in all day, and to notify and maybe popup locally with the info from the server.  This popup will be a small input form which is then sent back to the server.

I can't do this as a web page because I want it to run any time the client wants to start the local app.

This could possibly be used as a calendar, meeting planner or schedule notifier for clients which are my user stories.  Suggestions on appropriate design patterns and techniques appreciated!

答:
I would suggest taking a look at running Seam on a JBoss application server.  Add Rich Faces on top of seam, and writing the application you describe should be fairly easy.  The application that I work on daily uses Seam, and it handles all day log-in's by using the users browser to ping (poll) the server that it's still alive.  Using what you described, you could use the browser to poll the server for new information.

Seems like that would be a good fit to me, and (IMHO) JSF + Seam is a pleasure to work with, JSF is much easier than JSF, and Seam removes a large amount of boiler plate.  There's a lot of "magic" with Seam, but if you can get past that, it's well worth it.


问:
How much data should be required in a request to a webservice?
When recieving data from clients how much data that you provided to them should you require back from them?

For example when clients order a product from a webservice should they just need to provide a product code? The other alternative would be to require the product code product name and product price ect.

I have alway built webservices the former way with the minimum of data returned back to me, however I have just been consuming another web service that requires the vast majority of the data returned back to them. What are the advantages of the second way?

答:
In case we are just talking about Data Services for retrieving and storing entity objects as little information as possible is nice to have. This allows you to work stateless and gives greater control over the integrity of the data (because it's all managed in the data tier).

If however we are talkin about integration services e.g which support long running transactions, the requirement for the amount of required post data might shift towards a bit more.

Situations where one might offer a client a certain price for a specific order could vary over time and per sales person but the acceptance of such an order might take a few days. In that case you want to be able to retrieve more than just the order but some other criteria as well. In that case you end up with extra data that provides enough context to reconstruct the situation.

So I guess it all comes down to being able to having enough information available to reconstruct the original situation and derive the required actions to perform.


问:
How can I start testing in a testing anticulture?
I have a confession to make: Formalized automated testing was never a part of my programming background. I now work in a very large company with many developers (most of them web developers of one sort or another), and it's apparent that most of them don't test* either. (*I'm not going to keep saying formally; please infer it.)

If I wait to have the support of my organization to begin testing it will never happen. If I try to "change things from the inside" by pushing testing at management I will run out of steam before change happens. I need to start testing now.

But with TDD and its ilk I'm going to end up with lots of testing code right along with the production code. Our version control systems (all centralized) aren't organized for storing testing code. I'll have to find a place for all that on my workstation.

Is it possible to begin a personal practice of software testing in a culture that doesn't value or provide the tools for it? What techniques and tools do you use to enable you to test when the official tools and organization don't have a place for tests, frameworks and automations?

答:
I've personally done this with considerable success. The key factors for success:

Get (tentative) management support. The advantages of automates tests are well-documented and should convince any manager to at least try it. That includes finding a spot in the VCS and a build server, because

Automated tests only provide their full value if they are run frequently and automatically so that you know about problems soon and don't have to rely on people not forgetting to run them. You need a build server that runs them at least daily. This can be an old workstation. Jenkins takes very little work to get running.

Lead by example. Write tests, talk about the benefit they're providing to you, and when they reveal errors introduced by other developers talk about it in terms of how they were protected from potentially much greater embarrassment.

Go for the low-hanging fruit. Some parts of the application will be hard to test, others easy. Some will be robust, others brittle. Writing tests for brittle, but easy to test parts provides the most value in the shortest time.

See if you can write reusable tests, e.g. that test conventions or features that all modules (web pages, REST services, whatever) must have but which is often forgotten.


问:
Why should one avoid cross-team (circular) merges in multiple-team version control?

Please excuse the artwork, I know it looks like an elongated imperial shuttle, but it's the way I visualise a multiple team (or multiple stream) version control strategy. The central core, is the trunk (or master) repository. If there were lots more streams you can imagine more planes projecting out from the trunk, in which various branching and merging is taking place within those streams (the thinner lines).

The red line shows Alice from accounting wanting to take a piece of code that Bob from the backups team has only just forged (she needs it urgently for some reason that I can't think of). Actually, it's not like a one line change that she can just do herself. Instead you can consider that accounting are heavily blocked and need a large change set from Backups to continue.

Now as I understand it, this is against best-practice, and the changes required should go through the trunk, and Alice should pick them up that way, rather than take the short cut illustrated (a version control wormhole). However, although I have seen this stated in various places, I have never seen some deep, lengthy and well-justified reasons why a cross-stream (or circular?) merge is something not to allow. The only thing I can think of is that I guess it can lead to greater manual conflict resolution.

So questions are:

Why is allowing a cross-stream merge bad? (I need some well-defined
reasons to convince my various-minded colleagues why it shouldn't be
done)

Are there any justifiable reasons to go against best-practice?

What if Alice's team is reaching a release deadline, can there be an
exception?

答:
After reading through the TFS branching and merging documentation I couldn't come up with a sensible answer for your questions. According to the doc's it's perfectly okay to have different streams of development on one product in their own branches. I guess the best arguments against this scenario are:

greater complexity in merging and conflict resolution over multiple streams to the root

possibility of overlapping work (multiple teams might resolve same issue differently)

splitting up development efforts over various teams and coordinating that effort requires good communication and change management between the teams

So when you look at it, its not a technology issue that "blocks" this scenario.


答:
When the data change, you may need to know whether the client requests the operation based on the current version. Than you can either request all the relevant data back for verification or provide a version/timestamp and request that.

If the data change in big transactions, version/timestamp is usually easier, but if various bits change independenty, than you'd have to provide many versions, so just asking the data back is easier.

Title: How much data should be required in a request to a webservice?

Body:
When recieving data from clients how much data that you provided to them should you require back from them?

For example when clients order a product from a webservice should they just need to provide a product code? The other alternative would be to require the product code product name and product price ect.

I have alway built webservices the former way with the minimum of data returned back to me, however I have just been consuming another web service that requires the vast majority of the data returned back to them. What are the advantages of the second way?


答:
watin

I find unit web tests are extremely useful, even if it's just to give a general idea of a regression bug or for new projects.

As far as state is concerned, you create your unit tests as you would with non-UI tests - they clear the database out at the start of the test and rebuild the database to contain nothing except the start state. Each unit test then encapsulates a single page, or usually a distinct task on a page.

http://watin.org/ is another web test tool but for C#/.NET. You write the tests as unit tests:

```<code>[Test]
public void SearchForWatiNOnGoogle()
{
  using (var browser = new IE("http://www.google.com"))
  {
    browser.TextField(Find.ByName("q")).TypeText("WatiN");
    browser.Button(Find.ByName("btnG")).Click();

    Assert.IsTrue(browser.ContainsText("WatiN"));
  }
}
</code>```

It's currently IE based but has some experimental support for Firefox and Chrome. You can pretty much automate anything you would do in manual tests, including Javascript interaction.

Title: How do I unit test a web forms site?

Body:
watin

I find unit web tests are extremely useful, even if it's just to give a general idea of a regression bug or for new projects.

As far as state is concerned, you create your unit tests as you would with non-UI tests - they clear the database out at the start of the test and rebuild the database to contain nothing except the start state. Each unit test then encapsulates a single page, or usually a distinct task on a page.

http://watin.org/ is another web test tool but for C#/.NET. You write the tests as unit tests:

[Test]
public void SearchForWatiNOnGoogle()
{
  using (var browser = new IE("http://www.google.com"))
  {
    browser.TextField(Find.ByName("q")).TypeText("WatiN");
    browser.Button(Find.ByName("btnG")).Click();

    Assert.IsTrue(browser.ContainsText("WatiN"));
  }
}

It's currently IE based but has some experimental support for Firefox and Chrome. You can pretty much automate anything you would do in manual tests, including Javascript interaction.