问:
Do companies care about university grades when hiring programmers?
Most of my fellow students that I've talked to claim that aiming for good grades is useless as the companies don't care about them when hiring programmers. To them, it's enough to have simply attended courses which may be important, and that's that.

Is this true? Are university grades useless when leaving campus, or do employers ask to see them for an interview?

答: Incorrect. Grades are important especially if you have no or little professional programming experience. It's the bulk of your resume until you have professional experience.</p>


问:
Creating public API definition for existing application
Let's say there's a successful open source application (written in PHP if it matters), which provides its users with multiple ways to extend it (think about something like Drupal or Wordpress, lots of custom plugins, etc.). Now let's say unfortunately there's no formal definition what constitutes the public API for this application, and we want to define such a public API, so that we could a) control application development and refactoring and know we don't screw up the extensions with the next version and b) give extenders some idea what they can safely use and what they better not use. So the question is - how is it best to approach this and what should be there? For example, some specific questions:

Should all classes be part of public API or should we mark those are public or mark those that aren't?

Should protected methods be part of the API (if somebody creates derived custom class, they will be relying on it) and if so - should we be explicitly marking those that we don't want others to use, or those we're allowing to use?

Should public properties be part of the API too? How about protected ones?

If we want to make change/refactoring which can't be backwards-compatible (e.g. old API was too buggy or doesn't really fit in the app anymore), how we best approach it?

If we want to remove some class/method completely, what should be the process? I imagine we want to make it deprecated first, and then remove in later versions, but for example should we give some warnings when deprecated, but still existing functionality is called? The problem here is we can't warn to aggressively as it may break the application, but if we're not agressive people would ignore the deprecated mark until we remove the old API piece and then they'd get major breakage.

Any other advice is welcome too, and references for good papers/examples/etc. on the topic.

答:
I maintain a list of API design resources, including recommended books, video tutorials and online articles here

http://theamiableapi.com/api-design-resources/

Ferenc

ContentLicense: CC BY-SA 3.0


问:
Do / how do the various flex frameworks work with Flash Builder
I have been reading about various Flex frame works, Robot Legs, Swiz, Cairgnom (spelling error) and a few others. What I am missing is how they actually work with Flex / Flash Builder. Are they simply libraries that you can use with the Flash Builder IDE? Why should I learn to use one of them instead of just using the IDE as it is?</p>

答:
We use Cairngorm in our projects as follow:

We put the compiled library Cairngorm.swc in ./libs directory of our project

Then, library is included in the build path in Flex Builder:

Right click on your Project > Properties

[Flex Build Path] tab (on the left)

[Library Path] tab (on the right)

Ensure that your libs directory is listed or add it

Like this, we are able to use Cairngorm classes com.adobe.cairngorm.*

You can do the same thing with Astra Flex and use graphical components.


问:
Planning Poker and wordy developers
My team is composed of 4 developers; all seasoned and skilled. One of them is a wordy, well intended chap who insists on defining the technical solution to our stories before we put down our estimates with Planning Poker. He refuses to estimate if he doesn't have a rough idea of the agreed technical solution (which sounds reasonable, right?).

The problem is that our estimating sessions are taking forever to finish!! In your experience, how do you deal with this kind of personality when playing the planning poker?

答: I can see where your team member is coming from, but he clearly hasn't completely grasped the concept of Agile and Planning Poker. You should start by making sure everyone understands the concepts and the reasoning behind them, and then they should do right on their own.</p>

Title: Planning Poker and wordy developers


答:
They are useful if you don't have real work experience.

If a potential employer has nothing else to go by (no work experience, open source project development, etc), then that's the only physical thing they can evaluate you by.  Typically, it doesn't matter as much as you actually knowing your stuff.  If you have a GPA of <2.0, and don't have other experience to back you up, you can expect some data structures questions to make sure you actually know that material, even if you did bad on all your tests in school.

ContentLicense: CC BY-SA 2.5

Title: Do companies care about university grades when hiring programmers?

Body:
Most of my fellow students that I've talked to claim that aiming for good grades is useless as the companies don't care about them when hiring programmers. To them, it's enough to have simply attended courses which may be important, and that's that.

Is this true? Are university grades useless when leaving campus, or do employers ask to see them for an interview?


问:
How baby are your baby-steps in TDD?
Today we were training TDD and found the following point of misunderstanding.

The task is for the input "1,2" return sum of numbers which is 3. What I have written (in C#) was:

```<code>numbers = input.Split(',');
return int.Parse(numbers[0]) + int.Parse(numbers[1]); //task said we have two numbers and input is correct
</code>```

But other guys preferred to do it other way. First, for input "1,2" they made added the following code:

```<code>if (input == "1,2")
   return 3;
</code>```

Then they introduced one more test for input "4,5" and changed implementation:

```<code>if (input == "1,2")
   return 3;
else if (input == "4,5")
   return 9;
</code>```

And after that they said "Okay, now we see the pattern" and implemented what I initially did.

I think the second approach better fits the TDD definition but... should we be so strict about it? For me it is okay to skip trivial baby steps and combine them into "twinsteps" if I am sure enough that I won't skip anything. Am I wrong?

Update. I have made a mistake by not clarifing it was not the first test. There already were some tests so "return 3" actually wasn't the simplest piece of code to satisfy the requirement.

答:
I'm agreeing with the people saying that neither is the simplest implementation.

The reason the methodology is so strict is that it obliges you to write as many relevant tests as possible. Returning a constant value for one test case and calling it a pass is fine because it forces you to go back and specify what you really want in order to get anything other than nonsense from your program. Using such a trivial case is shooting yourself in the foot in some respects, but the principle is that mistakes creep into the gaps in your specification when you try to do 'too much' and rendering down the requirement to the simplest possible implementation ensures that a test must be written for each unique aspect of behaviour that you actually want.

Title: How baby are your baby-steps in TDD?


问:
Is OOP hard because it is not natural?
One can often hear that OOP naturally corresponds to the way people think about the world. But I would strongly disagree with this statement: We (or at least I) conceptualize the world in terms of relationships between things we encounter, but the focus of OOP is designing individual classes and their hierarchies.

Note that, in everyday life, relationships and actions exist mostly between objects that would have been instances of unrelated classes in OOP. Examples of such relationships are: "my screen is on top of the table"; "I (a human being) am sitting on a chair"; "a car is on the road"; "I am typing on the keyboard"; "the coffee machine boils water", "the text is shown in the terminal window."

We think in terms of bivalent (sometimes trivalent, as, for example in, "I gave you flowers") verbs where the verb is the action (relation) that operates on two objects to produce some result/action. The focus is on action, and the two (or three) [grammatical] objects have equal importance.

Contrast that with OOP where you first have to find one object (noun) and tell it to perform some action on another object. The way of thinking is shifted from actions/verbs operating on nouns to nouns operating on nouns -- it is as if everything is being said in passive or reflexive voice, e.g., "the text is being shown by the terminal window". Or maybe "the text draws itself on the terminal window".

Not only is the focus shifted to nouns, but one of the nouns (let's call it grammatical subject) is given higher "importance" than the other (grammatical object). Thus one must decide whether one will say terminalWindow.show(someText) or someText.show(terminalWindow). But why burden people with such trivial decisions with no operational consequences when one really means show(terminalWindow, someText)? [Consequences are operationally insignificant -- in both cases the text is shown on the terminal window -- but can be very serious in the design of class hierarchies and a "wrong" choice can lead to convoluted and hard to maintain code.]

I would therefore argue that the mainstream way of doing OOP (class-based, single-dispatch) is hard because it IS UNNATURAL and does not correspond to how humans think about the world. Generic methods from CLOS are closer to my way of thinking, but, alas, this is not widespread approach.

Given these problems, how/why did it happen that the currently mainstream way of doing OOP became so popular? And what, if anything, can be done to dethrone it?

答:
I think some of the difficulty comes in when people try to use OOP to represent reality. Everybody knows that a car has four wheels and an engine. Everybody knows that cars can Start(), Move() and SoundHorn().

A light clicked on in my head when I realised I ought to stop trying to do this all the time. An object is not the thing that it shares a name with. An object is (i.e. should be) a sufficiently-detailed partition of data relevant to the scope of the problem. It ought to have exactly what the solution to the problem needs it to have, no more and no less. If making an object responsible for some behaviour results in more lines of code than the same behaviour being the job of some nebulous third party (some might call it a 'poltergeist') then the poltergeist earns its chips.

Title: Is OOP hard because it is not natural?


问:
How would one handle external dependencies in an open-source project?
When one writes an open-source project and uses Google Code or GitHub, and wants to use a library like Lua, how should one do this?

Should the dependency be included in the repository?

Should the dependency be built from within the same build script as the rest of the project, or from a separate build script?

Given that the library doesn't need installation before compilation.

答:
This may or may not apply to your use case, but what we do at work is include a "References" folder in each branch.  We place 3rd party DLLs in here.  This causes a lot of duplication of relatively unchanging binaries in source control, but storage is cheap and at any point each branch & tag has exactly the dependencies (and version!) it's expecting.

We pre-compile the dependencies ourselves and move the compiled binaries into that folder.  Our own in-house shared library is treated this way as well.  That way the same technique works for pre-compiled proprietary libraries, open-source libraries, and in-house libraries.

As far as actually answering your question now that I've re-read it, do the same thing, and just mention that your project uses a precompiled 1.3.5 version of Lua.


答:
Should the dependency be included in the repository?

I think dependencies should always be included in the repository as long as including them does not violate any terms of use. Few things are more annoying than having to find the right versions of the right dependencies manually before you can make a build. Sure, this is easy when you have automated tools to do this for you, which can find and download the right dependency, but what if you aren't connected to the web at the moment or the server is down or the project of the dependency has been discontinued completely and taken offline? Always include the dependencies if possible.

Should the dependency be built from within the same build script as
  the rest of the project, or from a separate build script?

Unless there's a good reason to compile from source, use precompiled versions.

And why not provide options in the build script? A simple switch to choose whether the dependencies should also be compiled or not. If the user chooses to compile the dependencies as well, then just invoke their very own build scripts from your product's build script. So the user can invoke the dependcies' build scripts manually or choose to create a full build of everything. But I'd just deliver the dependencies as binaries if there's not a good reason to compile them from the sources. I think in the Open Source world, some licenses require you to distribute the sources along with your product but that does not mean you can't have them precompiled.

In short: Provide a whole standalone, working package if possible. This will provide the most convenience to your users.

Title: How would one handle external dependencies in an open-source project?

Body:
When one writes an open-source project and uses Google Code or GitHub, and wants to use a library like Lua, how should one do this?

Should the dependency be included in the repository?

Should the dependency be built from within the same build script as the rest of the project, or from a separate build script?

Given that the library doesn't need installation before compilation.


答: I would highly recommend reading through Git's documentation on submodules; it addresses this very problem, assuming that all of your sources use Git. If they don't, you can always set up a git repo for the purpose of integration. The effort is trivial, and the payoff is significant.</p>


问:
What non-programming books should a programmer read to help develop programming/thinking skills?
There are a lot of questions about what programming books should be on the programmer's bookshelf. How about non-programming related books that can help you become a better programmer or developer? It would also be interesting to know why they would help.

My first choice would be Sun Tzu's "Art of War" (however cliché), because it made it obvious that the success of any project depends on the strength of its weakest link (and warfare is a big project).

答:
Don't Make Me Think! A Common Sense Approach to Web Usability

Relevant to all user interface design.

Also includes general common sense for design that every programmer should know.


答:
What is important is related to the person that will hire you.

If the guy spent most of his young life studying while others spent that same time clubbing and flirting, there are good chances that he will value university a lot...

Still today, with more than 12 years experience in the industry, people ask me what university I went to (I left school early, so the dialogue that follows is really funny sometimes).

To answer your question: you will be more likely hired by someone that is highly educated, so sure that studies will be important. If I had a time machine, I would have flirted with fewer girls and spend more time with my professors ;)

However, since there is currently higher demand than supply in the programming world, you won't be a second choice for long, even if you did not spend too much time at the university.


答:
We (or at least I) conceptualize the world in terms of relationships
  between things we encounter, but the focus of OOP is designing
  individual classes and their hierarchies.

You're starting from (IMO) a false premise. The relationships between objects are arguably more important than the objects themselves. It's the relationships that give an object oriented program structure. Inheritance, the relationship between classes, is of course important because an object's class determines what that object can do. But it's the relationships between between individual objects that determine what an object actually does within the bounds defined by the class, and therefore how the program behaves.

The object-oriented paradigm can be difficult at first not because it's difficult to think up new categories of objects, but because it's difficult to envision a graph of objects and understand what the relationships between them should be, particularly when you don't have a way to describe those relationships. This is why design patterns are so useful. Design patterns are almost entirely about the relationships between objects. Patterns give us both the building blocks that we can use to design object relationships at a higher level and a language that we can use to describe those relationships.

The same is true in creative fields that work in the physical world. Anyone could throw together a bunch of rooms and call it a building. The rooms might even be fully furnished with all the latest accoutrements, but that doesn't make the building work. The job of an architect is to optimize the relationships between those rooms with respect to the requirements of the people using those rooms and the building's environment. Getting those relationships right is what makes a building work from both functional and aesthetic perspectives.

If you're having trouble getting used to OOP, I'd encourage you to think more about how your objects fit together and how their responsibilities are arranged. If you haven't already, read about design patterns -- you'll likely realize that you've already seen the patterns you read about, but giving them names will let you see not just trees, also but stands, copses, thickets, woods, groves, woodlots, and eventually forests.

Title: Is OOP hard because it is not natural?

Body:
One can often hear that OOP naturally corresponds to the way people think about the world. But I would strongly disagree with this statement: We (or at least I) conceptualize the world in terms of relationships between things we encounter, but the focus of OOP is designing individual classes and their hierarchies.

Note that, in everyday life, relationships and actions exist mostly between objects that would have been instances of unrelated classes in OOP. Examples of such relationships are: "my screen is on top of the table"; "I (a human being) am sitting on a chair"; "a car is on the road"; "I am typing on the keyboard"; "the coffee machine boils water", "the text is shown in the terminal window."

We think in terms of bivalent (sometimes trivalent, as, for example in, "I gave you flowers") verbs where the verb is the action (relation) that operates on two objects to produce some result/action. The focus is on action, and the two (or three) [grammatical] objects have equal importance.

Contrast that with OOP where you first have to find one object (noun) and tell it to perform some action on another object. The way of thinking is shifted from actions/verbs operating on nouns to nouns operating on nouns -- it is as if everything is being said in passive or reflexive voice, e.g., "the text is being shown by the terminal window". Or maybe "the text draws itself on the terminal window".

Not only is the focus shifted to nouns, but one of the nouns (let's call it grammatical subject) is given higher "importance" than the other (grammatical object). Thus one must decide whether one will say terminalWindow.show(someText) or someText.show(terminalWindow). But why burden people with such trivial decisions with no operational consequences when one really means show(terminalWindow, someText)? [Consequences are operationally insignificant -- in both cases the text is shown on the terminal window -- but can be very serious in the design of class hierarchies and a "wrong" choice can lead to convoluted and hard to maintain code.]

I would therefore argue that the mainstream way of doing OOP (class-based, single-dispatch) is hard because it IS UNNATURAL and does not correspond to how humans think about the world. Generic methods from CLOS are closer to my way of thinking, but, alas, this is not widespread approach.

Given these problems, how/why did it happen that the currently mainstream way of doing OOP became so popular? And what, if anything, can be done to dethrone it?


问:
How do you learn Regular Expressions?
I'm not asking where to learn. I've found lots of good resources online, and books etc.

But how the heck do I tackle them. Where is the start of it, the end? When does the regexp processor advance on the text, when does it hold its stand and tries another match? etc.

I feel like trying to figure out hieroglyphs on the Egyptian pyramids.

答:
Two good other answers tell you to learn the theory behind regexes, and to practice, which are both great advice. I'd also recommend getting a good visual regex tool to help you out if you're serious.

RegexBuddy, for example, has a visual debug mode that lets you step through a regex's execution, and shows you via highlights and explanatory text what the regex engine is doing at each step. There's a video demonstrating this debugging on their site.

Title: How do you learn Regular Expressions?


答:
Where is the start of it, the end? When does the regexp processor advance on the text, when does it hold its stand and tries another match? etc.

I would start by clarifying your goals and then figuring out your learning style.

What struck me about your question is that you ask "how do I learn regular expressions?" and then immediately follow that up with the question "how does the regular expression engine work internally?"  You seem to be implying that those two things have something to do with each other, which is a telling point. Maybe you are a person who learns how something works by taking it apart, or by building it yourself.

For beginner applications, there is usually no need to understand how a tool works in order to use it effectively. You don't need to know how a drill motor works in order to put holes in wood; you need to understand how to use the drill, not how to build a drill.

So what is your goal? Are you intending to learn how to build a regular expression engine? or are you intending to learn how to effectively use regular expressions to solve business problems?  Achieving those different goals likely requires different learning techniques.

To address your specific question about how the regular expression engine works: it depends. The "classic" theoretical approach to regular expressions is to use the regular expression as a blueprint for a nondeterministic finite automaton, then build the equivalent deterministic finite automaton, and then execute that automaton against the input.

Almost no one actually does this for several reasons. First, the number of states multiplied by the number of possible input characters yields a state transition table that is freakin' enormous even for small regular expressions. Sure, most of that can be compressed, but still, it's a lot of transition rules. Second, other approaches are usually faster. Third, so-called "regular" expressions are in modern regexp libraries, nothing of the sort. They are not regular languages at all; they're often recognized by pushdown automata, not finite automata languages.

(I started writing a long series on how all this stuff works but I ran out of steam after only the first twelve articles. You might find them interesting if you would like a brief primer on the theoretical background of basic regular expressions.)

Real regular expression engines instead typically use a backtracking strategy. The regular expression engine we built for the JScript engine over a decade ago now compiles the regular expression into a bytecode language that includes primitives for recognizing sequences and backtracking to earlier states. We then built an interpreter for that bytecode language.

I would not try to understand how a regexp engine works before having a pretty solid understanding of how to use regular expressions. Concentrate on that before you start digging into the optimization strategies various different engines.

Title: How do you learn Regular Expressions?

Body:
I'm not asking where to learn. I've found lots of good resources online, and books etc.

But how the heck do I tackle them. Where is the start of it, the end? When does the regexp processor advance on the text, when does it hold its stand and tries another match? etc.

I feel like trying to figure out hieroglyphs on the Egyptian pyramids.


答:
You team member sounds an analyst personality.  Analysts need lots of information to make a decision.  The timer idea is best, but be aware, he is going to caveat the hell out of anything he gives.  Work with him to explain that it's just an early estimate based on the problem NOT the solution.  If he wants to ask questions ask him to keep it to the problem not the solution.  You may have to cut him off or annoy him for awhile when he keeps drifting to solutions.

Make sure you hold others on the team to these same rules so he doesn't feel singled out.  Analysts are a common personality in programming, so you very well may run into others like him.

Title: Planning Poker and wordy developers

Body:
My team is composed of 4 developers; all seasoned and skilled. One of them is a wordy, well intended chap who insists on defining the technical solution to our stories before we put down our estimates with Planning Poker. He refuses to estimate if he doesn't have a rough idea of the agreed technical solution (which sounds reasonable, right?).

The problem is that our estimating sessions are taking forever to finish!! In your experience, how do you deal with this kind of personality when playing the planning poker?


答: In normal development, debugging code can provide very useful insights.  Regular expressions aren't any different.  So, at the risk of sounding like an advertisement, get RegexBuddy.  It has a great tool to visually display what the engine is doing as it handles your expression and the input string.</p>

Title: How do you learn Regular Expressions?


答:
Being an Eclipse shop, we have just started using Buckminster to manage our build/assemble/deploy process.

Our first stage has been to pull out all of our existing dependent libraries and let buckminster take care of materialising the correct ones. This makes for a much quicker and smaller deployment.

The next step will to move our monolithic svn repository to a series of modular git repositories.

I don't know how well buckminster would integrate with git submodules (or mercurial subrepos for that matter), but it is nice that buckminster is agnostic with regard to the VCS used for any given component.


答:
It sounds like your colleague does not understand the difference between estimate and commitment or it hasn't been communicated to him during training.  And, since you tried to attach the problem to his personality, it's possible that your whole team doesn't yet understand it.  (But don't worry! Most of our industry doesn't understand it.  Agile is hard!)

When we say a story's size is X points, we actually mean a probability distribution.  If our estimates are correct, the story should take longer 50% of the time (and the other 50% it will take less time).  If your colleague believes that, when X units of time have elapsed, he will be asked to demo the story or else, that changes his approach to estimation.

Planning poker introduces another error: instead of trying to pin down X, we match it to a discrete scale, the Fibonacci scale (1, 2, 3, 5, 8, etc.) being the most popular.  It is saying what the size isn't as much as what it is.  When we say the story size is 3 points, we really say "it's X plus-minus some variance and X is closer to 3 than it is to 2 or 5."

Your team could benefit from understanding how imprecise this exercise is and how estimate differs from commitment.  If you want/need to study these concepts in depth, this book has that.

Title: Planning Poker and wordy developers


问:
How do you respond to "Tell me a little bit about yourself." question in interviews?
I've been asked this in a few interviews. And it always catches me off guard.My professional and academic background are already in the resumé, which the interviewer has obviously looked at. What more to tell him/her? Should I start with my hobbies? I like gardening, or looking at NSFW pictures on reddit in my free time?

What and how do you answer to this specific question? Do you have a prepared answer for it? Am I wrong if I think this question is a bit silly?

UPDATE There have been a lot of great answers to this question. I'm in pickle which to choose as the 'correct' answer, because most of them are very insightful. I found a great writing on this subject matter. It's a bit crazy for my taste, but it's interesting:

How To Introduce Yourself… I Mean Practically

答:
You say "My professional and academic background are already in the resumé, which the interviewer has obviously looked at."  Yes, that's true, but don't think that the interviewer is trying to get facts out of you.

You need to understand why the interviewer is asking this question, and what the role of it is.

The question “Tell me about yourself” serves at least five purposes.

It gives the candidate a chance to give her elevator speech, to tell about herself and what value she'll bring to the organization, and set the interview off in a given direction.

It lets the manager see how well prepared the candidate is for the interview.

It lets the candidate show how well-spoken she is.

It lets the manager get an idea of the candidate's attitude and personality.

It lets the manager compare what you tell him with what’s on the resume, to see if there are any discrepancies.

More at my blog post that this inspired: http://techworklove.com/2010/10/the-job-interview-is-not-about-collecting-factual-information/


答:
In addition to a good reference, the way you really learn is to use good learning tools. One is using the open-source Vim editor, with two options set:

:set incsearch ...as you type in a search pattern on the command line, the editor on-the-fly jumps to the first piece of text that matches and highlights exactly what is matching. If you type something that makes it no longer match anything, Vim jumps your cursor back to where you were when you started.

:set hlsearch ...this tells Vim to show a highlighted background on all text that matches the current RE search.

The other is to use a free tool call RegExCoach. You paste in text that you want to search, then in another window you develop your regular expression. Like Vim, it highlights successful matches on the fly.

Title: How do you learn Regular Expressions?


问:
What is the proper way to implement the OnClickListener interface for many buttons
My Android Activity contains multiple buttons that all need an OnClickListener.  I've seen lots of different ways of doing this such as::

Implementing the interface in activity class

Creating a separate class that implements the interface

Defining an anonymous inner class for each button.

I've seen many examples of each approach. However, its not clear to me why one approach would be used instead of another. Are the differences between these approaches stylistic or are there reasons that make one approach better?

答:
As with many things, the correct approach depends on what you are trying to do for the specific button and what else you are doing with the activity.

Activity class implements interface:

This is a good option when you only have one type of task to execute when this listener is called. An example of this would be a simple form with a number of fields and a save button. I prefer to not have my event listener check the source of the event in order to decide what actually needs to be done. I know that some may say this is a style thing, but I believe that by not requiring the listener to do this check makes the code easier to follow as you will know exactly what is being called for each event.

A different class implements interface:

As I said above, I prefer this option for when I have multiple items that can fire the same event. Extending the above example, lets add a clear button that also requires a click listener. Create one listener that that preforms the save actions and one that preforms the clear actions. Each listener is only added to the components that will produce that action.

This implementation has an additional benefit that you can utilize if you care. The benefit is that it prevents other classes from triggering the event inside of your activity class. Since the interface method must be public, anyone with a reference to the class can fire the event. If you want fine grained control over who can do what in the application, a separate class prevents anyone with a reference to the activity to trigger your form to be cleared or saved (or potentially breaking the code if the listener utilizing the source, but does not handle bad input).

An anonymous inner class implements interface:

This is really just a specific way to construct the second option of using a different class as the implementation. This option can even further restrict who has access to trigger the event as no one else can create an instance of the class. However, I think the more important factor between the two options is how much work is being done. Clearing a few text fields is a simple and straight forward operation. However, the process of saving the for can involve a number of task is you are validating the input (which you should be doing), writing to a database to store the values and triggering some post save action. In this case, making a separate class with its own file will provide a clearer divide between the input form and the data processing. This in turn keeps the form code instead of a larger file with multiple inner classes nested inside.


问:
How does thinking on design patterns and OOP practices change in dynamic and weakly-typed languages?
There is a fairly helpful question already along these lines ("Non-OOP Design Patterns?"), but I am more curious about a transitional point of view for someone just getting started with dynamic and weakly-typed languages.

That is: let's say I've been programming in C++, C#, or Java for many years, and absorbed lots of wisdom along the lines of the GoF design patterns, Fowler's Patterns of Enterprise Application Architecture, SOLID principles, etc. Now I'm dabbling in Ruby, Python, JavaScript, etc., and wondering how my knowledge applies. Presumably I could do direct translations in many cases, but almost certainly that wouldn't be taking full advantage of my new setting. Duck typing alone turns a lot of my interface-based thinking on its head.

What stays the same? What changes? Are there guiding principles like SOLID, or canonical patterns (perhaps entirely new ones) that a dynamic language newbie should know?

答:
Programming in a dynamic object oriented language uses many of the same patterns and principles, but there are certain tweaks and differences due to the environment:

Replace Interfaces with Duck Typing -- Where the Gang of Four would tell you to use an abstract base class with pure virtual functions, and you would use an interface in Java, in a dynamic language, you only need an understanding. Since you may use any object anywhere, and it will work just fine if it implements the methods that are actually called, you don't need to define a formal interface. It may be worth documenting one, so that it's clear what is actually required.

Functions are Objects Too -- There are lots of patterns that are about separating decision from action; Command, Strategy, Chain of Responsibility, etc. In a language with first-class functions, it's often reasonable to simply pass a function around instead of making objects with .doIt() methods. These patterns transform into "use a higher order function."

SOLD -- The Interface Segregation Principle takes the biggest hit here, on account of there being no interfaces. You should still consider the principle, but you can't reify it into your code. Only personal vigilance will protect you here. On the up side, the pain caused by violating this principle is much reduced in common dynamic environments.

"...in my own Particular... Idiom!" -- Each language has good practices and bad practices, and you'll have to learn them, and follow them, if you want the best code in those languages. A perfectly written iterator pattern may be laughed off in a language with built in list comprehensions, for example.


答:
I'll give you a simple answer for a simple question.  First, you need to understand what Regular Expressions (RegEx) are - what they do, what they are used for.  Then, a great tool to get started.

What Is It?
RegEx is a language for expressing pattern matching.  That is to say, using it, you can create a combination of characters that recognizes, or finds, patterns in text.  How is this useful?  In programming, you can tell computers to match text from some source (a user input, a web page, etc.) and detect whether or not specific patters of text are contained within it.  For example, a period (.) represents any character - letter or number.  Numbers in braces represent numbers of iterations, so ".{1,30}" indicates any character, repeated between 1 and 30 times - in other words, you can't have an empty string, and it can't be longer than 30 characters.  And it goes on from there.

How to get started learning?
The absolute best tool I have seen is Expresso, but it is only for Windows.  It has a very extensive GUI where you click through the elements you want to add to your expression, then a tester to check it against various input to see the results.  I haven't seen anything good on the Mac (but I am running Windows on VMWare, so don't really need a Mac version), haven't spent a lot of time looking on Linux.

Title: How do you learn Regular Expressions?


问:
"Do Whatever You Want" License With Attribution
I'm looking for an open source license that lets people do whatever they want - just like the MIT license - just as long as they attribute the original author, i.e. me.

Does a common license exist for this?  If so, what is it?

答: The GPL has a history of confusing folks and scaring them off.  The Apache License is more straightforward and probably what you want.</p>


答:
The MIT License itself says:

The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

Just make sure to put your own name in the "above copyright notice".

Title: "Do Whatever You Want" License With Attribution

Body:
I'm looking for an open source license that lets people do whatever they want - just like the MIT license - just as long as they attribute the original author, i.e. me.

Does a common license exist for this?  If so, what is it?


问:
Why aren't there automated translators from one programming language to another?
Most programming languages are Turing complete, which means that any task that can be solved in one language can be solved in another one, or even on Turing machine. Then why aren't there automatic translators that can convert programs from any given language to any other language? I've seen couple attempts for two languages, but they always work only on a limited subset of a language and can hardly be used for converting real projects.

Is it possible, at least in theory, to write 100% correct translator between all languages? What are the challenges in practice? Are there any existing translators that work?

答:
While it's not code translation per se, the concept of language workbenches shows how something akin to a 100% correct translator between all languages could be implemented.

In our current approach, the source code is stored in a textual format. During compilation, those human-readable text files are parsed into an abstract syntax tree representation, which in turn is used to generate either bytecode or machine code. This abstract representation however is temporary and internal to the compiler.

In the language workbench approach, a similar abstract syntax tree representation is the  permanent, stored artifact. Both the machine code and the textual 'source' code are generated based on this abstract representation. One of the consequences of such a method is that the abstract representation of the program is actually language-agnostic, and can be used to generate textual code in any implemented language. Meaning that one person can work on different aspects of the system freely using whichever language they see as the most appropriate, or each member of the team can work on the shared project in the language they are most familiar with.

As far as I know, the technology is still far from being usable in mainstream development, however there are several groups working on it independently. Hard to tell whether any of them will live up to their promises, but it would be interesting to see that happen.


答:
Everything we can give you is more resources to learn. This question is itself a resource.

By the way, I've learned regular expressions quite easily from this site:
http://www.regular-expressions.info/

Title: How do you learn Regular Expressions?


答:
This is done all the time.

Every compiler translates the "primary language," like C++, to the machine's native assembly language or architecture-independent bytecode in the case of interpreted languages.

I imagine that's not what you're talking about, though.  You probably want a translator that converts C++ to something like Java or Python.  What's the point of that, though?  At best, the end result will have the exact same efficiency as the original source.  (Practically, it'll be much worse.)

If you just want code to be translated so you can read it as a language you understand, such a translator would have the opposite of the desired effect.  You will be left with a slew of cryptic, unintuitive and unreadable code.

This is because only the most trivial things translate directly from one language to another.  Often, what's simple in one language requires massive libraries for another - or might be impossible altogether.  Therefore:

If the program is trivial, you might get a decent result.  But then, if it's that simple, what's even the point of running it through a translator?

If the program is nontrivial, the code will be of low quality.

In the end, the only way to write good code is to actually write it.  Computers simply can't - at least not yet - match humans on matters of readability, best-practices and elegant solutions.

In short, it's just not worth it.

Title: Why aren't there automated translators from one programming language to another?

Body:
Most programming languages are Turing complete, which means that any task that can be solved in one language can be solved in another one, or even on Turing machine. Then why aren't there automatic translators that can convert programs from any given language to any other language? I've seen couple attempts for two languages, but they always work only on a limited subset of a language and can hardly be used for converting real projects.

Is it possible, at least in theory, to write 100% correct translator between all languages? What are the challenges in practice? Are there any existing translators that work?


问:
Mobile PC Remote
If I buy a symbian(S60, nokia E51) mobile, and I want to write a program to control the PC(launch programs, control mouse/keyboard):

Is it possible to make a mobile app and a windows app which
communicates via WiFi, or its easier/faster via bluetooth?

Which framework should I choose? (symbian/java)

(other info that I might need)

答:
It's possible with both Wi-Fi and Bluetooth using native Symbian, and I expect using Qt too. I don't know about Java.

As an example, ControlFreak is an application for older S60 1st and 2nd edition phones (but not 3rd edition, like the E51) to control Winamp and the rest of your computer using Bluetooth.

Head over to Nokia Developer for SDKs, APIs and forums to ask more questions.

Title: Mobile PC Remote


答:
The Do What The Fuck You Want To Public License (or WTFPL) is very close to what you're looking for.  It is only lacking attribution.

It sounds like a joke license, but it's approved as GPL-compatible by the FSF.

You could just add a bit to the license requesting attribution, but I'm no lawyer so I don't know if that would fly in court.  What are the odds of a court case over your project?

Actually it does contain a copyright notice. and therefore attribution


问:
Do you know of any encryption techniques used to validate url redirection
I'm adding a click-tracking feature on my website to track click-thrus for my advertisers.

So, on my site, instead of having a direct link, I link to my re-direct page passing the destination url as an argument. This re-direct page then tracks the click thru and then 301 re-directs the user to the correct external url.

I want to prevent 3rd partys from harnessing this system to make it re-direct to arbitrary urls.

I'd like the code that creates the links to:

Create special token using ( destination url + secret )

Then, pass the destination url + special token arguments as query string parameters to my re-direct page in public.

Upon receiving the arguments the re-direct page will do a check:

Given ( destination url + special token + secret ), destination url is either:

good - re-direct it to destination

bad  - do not re-direct it to destination

and it should not be possible for Doctor Evil to:

Create secret using ( known valid destination url + its special token )

Ideally the re-direct page would not have to do any url-specific look-ups on data to validate the parameters - it should just be able to tell from 'the two params given + the secret + the known algorithm'.

I'm not very knowledgeable about encryption so was wondering what kind of method one would use to create and validate the parameters given the shared secret.

I'm sure this is a common technique but I have no idea what its called - thus its difficult to learn more about it.

Any help is appreciated.

答:
Yes, i've invented a method to do so. Unlike Jerry's MAC solution, I created the authentication code using public/private key encryption. If you create the authentication code with your private key, the validation only requires a public key. That means that even if your server is compromised and the public key would be obtained, it still wouldn't allow third parties to create new signed URLs.

You might want to check with a lawyer whether that patent application would be a problem for you.


问:
Ubiquitous Language - conflict between correctness and usability
A core part of Domain Driven Design is the consistent use of a ubiquitous language across the system - in conversations, code, database schema, UI, tests, etc.

I'm involved in a project in which there is a well-established domain language already, defined by an international standards organisation.

However, the work we're doing is for a public web site, and the 'correct' terms for the domain aren't necessarily how the public typically use and understand them.

The compromise we're using at the moment is to use the 'official' terms everywhere, except for in our acceptance criteria which refer to UI components, where we use the informal names.

Does this seem like a reasonable approach?

答:
Yes, that seems reasonable. If the intended audience does not understand the terms of your language or misinterprets them, then the usability for the enduser takes precedence.

A program or content that a typical user does not understand is of little value. More so, if you only want to present them a simplified tip of an iceberg because they are not and never will be domain experts.

Normally, when you talk about the domain during development then everyone understands the language because it is accurate and all people are within the domain. But if business value is created by communication of content to outsiders of the domain, then do this as simple as possible. Use wordings and languages which are the least likely to be misunderstood and use them in the UI.

Keep the accurate language in your code and for communicating with people who are concerned with the domain. These are the people who have the specs and who are the key users of the applications, the ones with whom you discuss the business logical details. In the rare case that you really discuss most of the business logical details with users who don't have much of a clue about the domain and you needn't dive deep into it, then incorporate their language in your domain language, given that they have a common, unambiguous language at all (which probably isn't the case).

But do make sure that the frontend devs know about your informal terms and their corresponding domain terms.


答:
A fourth way is to set the onClick attribute in the layout:

```<code><Button android:onClick="clickHandlerForButtonX" />
</code>```

which has this corresponding method in the Activity:

```<code>public void clickHandlerForButtonX(View v) {
    //Handle Button X here
}
</code>```

Title: What is the proper way to implement the OnClickListener interface for many buttons

Body:
My Android Activity contains multiple buttons that all need an OnClickListener.  I've seen lots of different ways of doing this such as::

Implementing the interface in activity class

Creating a separate class that implements the interface

Defining an anonymous inner class for each button.

I've seen many examples of each approach. However, its not clear to me why one approach would be used instead of another. Are the differences between these approaches stylistic or are there reasons that make one approach better?

Body:
A fourth way is to set the onClick attribute in the layout:

<Button android:onClick="clickHandlerForButtonX" />

which has this corresponding method in the Activity:

public void clickHandlerForButtonX(View v) {
    //Handle Button X here
}


答:
For me, seeing what the regexp is matching as I am building it really helps makes my life easier and has helped me better understand them.

To do this, I will open up a file with the target text in Emacs, and then use the isearch-forward-regexp command.  As you enter the regexp, Emacs shows you what it is matching (that's the "isearch" part).

To run the command, in Emacs, you can use <ESC>xisearch-forward-regexp.

Title: How do you learn Regular Expressions?


问:
Do companies care about university grades when hiring programmers?
Most of my fellow students that I've talked to claim that aiming for good grades is useless as the companies don't care about them when hiring programmers. To them, it's enough to have simply attended courses which may be important, and that's that.

Is this true? Are university grades useless when leaving campus, or do employers ask to see them for an interview?

答:
It's important to have a good grade especially applying for the first job fresh out of college. Some companies might even set a GPA threshold (for example, 3.5/4.0) and might screen off candidates with a GPA lower than that. Sure, there will always be exceptions, most likely due to leadership qualities, for example, if you are the president of the IEEE chapter of your school and have a 3.3 GPA, you might still have a shot.

Also, it doesn't hurt to explain why you have lower grades as well. If a person can show that they've improved over time (maybe a student slacked off during freshmen year, or had gone through some hard-ships, but his/her grades improved over time when life circumstances are different), it does show maturity on the candidates side to explain those circumstances to the recruiter.


答:
I think the easiest way to answer this would be to draw line exactly where you would draw it if you were presenting the UI in a completely different language.

If your end users needed to see things in Sanskrit, how would you bridge the difference between the UI and the code (and other internal communication).

Title: Ubiquitous Language - conflict between correctness and usability

Body:
A core part of Domain Driven Design is the consistent use of a ubiquitous language across the system - in conversations, code, database schema, UI, tests, etc.

I'm involved in a project in which there is a well-established domain language already, defined by an international standards organisation.

However, the work we're doing is for a public web site, and the 'correct' terms for the domain aren't necessarily how the public typically use and understand them.

The compromise we're using at the moment is to use the 'official' terms everywhere, except for in our acceptance criteria which refer to UI components, where we use the informal names.

Does this seem like a reasonable approach?


问:
How should I implement Transaction database EJB 3.0
In the CustomerTransactions entity, I have the following field to record what the customer bought:

```<code>@ManyToMany
private List<Item> listOfItemsBought;
</code>```

When I think more about this field, there's a chance it may not work because merchants are allowed to change item's information (e.g. price, discount, etc...). Hence, this field will not be able to record what the customer actually bought when the transaction occurred.

At the moment, I can only think of 2 ways to make it work.

I will record the transaction details into a String field. I feel that this way would be messy if I need to extract some information about the transaction later on.

Whenever the merchant changes an item's information, I will not update directly to that item's fields. Instead, I will create another new item with all the new information and keep the old item untouched. I feel that this way is better because I can easily extract information about the transaction later on. However, the bad side is that my Item table may contain a lot of rows.

I'd be very grateful if someone could give me an advice on how I should tackle this problem.

UPDATE: I'd like to add more information about the current design.

```<code>public class Customer implements Serializable {
    @OneToMany
    private List<CustomerTransactions> listOfTransactions;
}

public class CustomerTransactions implements Serializable {
    @ManyToMany
    private List<Item> listOfItemsBought;
}

public class Merchant implements Serializable {
    @OneToMany
    private List<Item> listOfSellingItems;
}
</code>```

答:
The best thing to do is to grab a piece of paper and a pen (or whiteboard/pen) and draw the real world relationships between the customer and the merchant and the items.  Think about what happens when you go to your local store and order a list of items.  Also think about when the items actually physically change hands as part of a transaction and whether or not those items can be changed or not....

A couple of hints:

Once I've bought the icecream and started eating it, the merchant can't change that.

The 5 tennis balls that I bought (a transaction) cannot be used in another transaction with me, I've already bought them.

Hope that gets you on your way!

OwnerDisplayName: JamesBoyZ


问:
Is there a way to automatically un-tab everything in your source file by using a command?
And then to automatically re-indent after that? I've tried copying code from one terminal screen to the other, but the tabulation got all messed up.

I didn't know what to call this functionality, so it was hard for me to find it on google (which generally returned things related to how to set tab size, which wasn't what I was looking for unfortunately).

答:
By un-tab, do you mean to change tabs to spaces? If so, substitute spaces for tabs in the entire buffer like this:

```<code>:%s/^I/    /g
</code>```

That's four spaces on the right side of the substitution, but you can make it whatever number you want. To get the literal ^I tab character, you can hit ^V followed by the Tab key.

You can re-indent with the = command. To re-indent the entire contents of the buffer, use these commands:

```<code>gg
=G
</code>```

This takes you to the top, then re-indents everything to the bottom.

Body:
By un-tab, do you mean to change tabs to spaces? If so, substitute spaces for tabs in the entire buffer like this:

:%s/^I/    /g

That's four spaces on the right side of the substitution, but you can make it whatever number you want. To get the literal ^I tab character, you can hit ^V followed by the Tab key.

You can re-indent with the = command. To re-indent the entire contents of the buffer, use these commands:

gg
=G

This takes you to the top, then re-indents everything to the bottom.


问:
How to make a GPL license with more severe penalties?
I am considering open sourcing some software, but when I read the answers on this questions, it seems like the penalty of ignoring a GPL license is rather small, compared to the costs of the suing party to document that the other party has included GPL code in their proprietary code and the costs of suing.

Therefore, I would like to know if there is a way to make a license or some kind of contract before source code is accessed, which is stricter than GPL. What I want to achieve is that a company including GPL code in their proprietary code have to GPL their whole code, and not just rewrite the GPL code. Is this possible?

答:
Yes and no. You couldn't do it in the form of a copyright license like the GPL. But you could do it in the form of an explicit contract. You would need to retain signed copies of the contract for everyone you distributed code to.

It would take some delicate wording. Simply saying that they have to open their code won't work. Specific performance is not usally an available remedy at contract law because it penalizes efficient breaches. There are ways around this, and a good lawyer will know them.

Unfortunately, if someone got their hands on your software without agreeing to the contract (and without breaking the law), you would only have the normal copyright remedies against them. There's nothing you can do about that. So you would need to prohibit anyone but you from distributing the source code.

As a practical matter, such a license would only be useful if you expected distribution of your source code to be rare. Perhaps the occasional person who might need to customize something. You can't get both widespread distribution and tight control.


答:
Vim has a retab command that allows you to tabify or untabify your document. It uses settings such as tabstop and expandtab.  So, if you want to replace tabs with spaces you could do the following:

```<code>:%retab
</code>```

See the retab documentation for full details.

Caveat Emptor: this also replaces tabs that are NOT at the beginning of a line. So if you use hard tabs in the middle of strings they will be replaced as well.

Title: Is there a way to automatically un-tab everything in your source file by using a command?

Body:
And then to automatically re-indent after that? I've tried copying code from one terminal screen to the other, but the tabulation got all messed up.

I didn't know what to call this functionality, so it was hard for me to find it on google (which generally returned things related to how to set tab size, which wasn't what I was looking for unfortunately).

Body:
Vim has a retab command that allows you to tabify or untabify your document. It uses settings such as tabstop and expandtab.  So, if you want to replace tabs with spaces you could do the following:

:%retab

See the retab documentation for full details.

Caveat Emptor: this also replaces tabs that are NOT at the beginning of a line. So if you use hard tabs in the middle of strings they will be replaced as well.


答:
I learned regular expressions by learning flex and bison, which are used to build lexical analyzers and parsers. You couldn't have a parser without regular expressions, and the book lexx and yacc is incredibly good at walking through the theory without moving too fast.

Fundamentally, practically all regex engines these days follow the same principles. They are all finite state machines and if you truly grok that, then you have a leg up on almost any code you write. It similar to learning recursion in that, once you get it, you apply it to problems instinctively. They're easy to solve with the right tool, but very hard without it.

Another thing about learning lexx and yacc, as compared to regular expressions, is you learn how they work internally. How the program does look ahead, why it finishes a match, how it holds the data, and so much more. Understanding pointers is an absolute must, but if you get lexx and yacc, and go through it from the beginning you'll learn everything you asked, and have a massively powerful tool for the rest of your career.

This question includes a bunch of resources for learning, and a flex skeleton I threw together.

Title: How do you learn Regular Expressions?


答:
To expand on @Kaleb's answer (I don't have the rep yet to comment), before executing the retab command, you will need to :set expandtab (set et).  Otherwise the retab will not replace tabs with spaces.

In additon, you may wish to specify the tabstops. Often in source code created by others, the code is written with tabstops set to 4 or even 2.  Before doing the :%retab command, experiment with different tabstops. Try

```<code>:set ts=8 (the default)
:set ts=4
:set ts=2
</code>```

to see which setting makes the most sense.

To go backwards (replacing spaces with appropriate TAB characters, use

```<code>:set noet
:%retab!
</code>```

Body:
To expand on @Kaleb's answer (I don't have the rep yet to comment), before executing the retab command, you will need to :set expandtab (set et).  Otherwise the retab will not replace tabs with spaces.

In additon, you may wish to specify the tabstops. Often in source code created by others, the code is written with tabstops set to 4 or even 2.  Before doing the :%retab command, experiment with different tabstops. Try

:set ts=8 (the default)
:set ts=4
:set ts=2

to see which setting makes the most sense.

To go backwards (replacing spaces with appropriate TAB characters, use

:set noet
:%retab!


答:
I've found learning regular expressions similar to learning the multiplication tables - yes, you need to understand the ideas behind it, but ultimately, you just have to do it often and repeatedly.

When I was learning, I would set myself a goal of doing a few regex exercises per day. In practice, this meant at least once a day, I would try to look at a string or text on my screen, and come up with a challenge - "can I get all the email addresses out of here", or "find all the occurrences of the word 'code' used as a verb rather than a noun," stuff like that.

Doing that for a few weeks really paid off - and of course, periodic reviews and refreshers are needed. I'm about due for one.

I found this online tool helpful too, as it let's me test regex in real time: http://www.gethifi.com/tools/regex

Title: How do you learn Regular Expressions?


问:
Is there a general rule for when you should use 'make clean' instead of just 'make'?
I am writing a multiple-filed program right now, and apparently running only 'make' (as one would intuitively think needs to be done in most situations) for some reason causes my program to fail. I guess I can provide more detail of the problem, but the important thing is that it does run when using 'make clean'. So I was wondering if anyone knew the general rule of thumb for running 'make clean' instead of just 'make'</p>

答:
You run make clean in two situations - when you want to package up the source code (and therefore don't need/want the built objects) OR when you have some reason to believe that the built objects are bad.

In your case, you're using 'make clean' to fix a problem that is likely the result of a buggy Makefile. Something in there is not re-compiling when it should, and that's causing the output binary to be bad.

There are many reasons that could happen, depending on the complexity of your project, and how you've used make, but the gist of it is: you need to spend some time debugging your Makefile.


答:
How the heck do I tackle them?

Like any new thing:

```<code>10 Study
20 Practice
30 goto 10
</code>```

Study

I find that most successful teachers start teaching any subject by first providing a bit of background to the subject. It's important to have a context of what you're learning and, most importantly, why you're learning it.

It's all string matching

Regular Expressions are a means of matching patterns in text. It's a declarative language itself incorporated into numerous other programming language.

I'd like to emphasize that it's a declarative language, regular expressions are useful for expressing what string to match, but they do not in any way express how the program is to go about doing the matching. For this reason it's possible to use regular expressions very quickly and very slowly in the same programming language simply by using a different RegEx parser.

The reason for creating regular expressions are the same for the creation of most programming languages: programmers found themselves performing the same complicated task over and over and decided they wanted a simpler way of writing the code.

Some will (and should) complain about my previous sentence by saying something along the lines of:

RegEx doesn't make a program simpler.

it's true

RegEx doesn't make a program any simpler, RegEx makes writing the program simpler. You still need to be thorough in your testing to be certain that all correct cases are matched correctly, and all incorrect cases are not. It's really hard to test "all", and with complicated patterns, it's really hard to test "most". At worst, you should still be testing "some" cases.

lets incorporate some examples I've obligatorily chosen JavaScript's RegEx engine because I can test it live in the browser easily and because I won't have to do any string escaping while using RegEx literals.

When you do normal string matching, you test one string value against another. They can come from anywhere, but in the end it takes two strings being compared against one-another:

```<code>if ( 'foo' == 'bar' ) doSomething();
</code>```

That example sucks because it will never do anything

```<code>if ( foo == 'bar' ) doSomething();
</code>```

Much better; now, we don't actually know ahead of time whether or not something will be done. We can now start accepting user input:

```<code>if ( prompt( 'Say "bar" to do something.' ) == 'bar' ) doSomething();
</code>```

Wonderful, now users can input bar and something will happen, until you get bug reports from users saying that "bar" isn't working, or that "BAR" isn't working, or that they've typed BRA 100 times and nothing ever happens.

Ignoring the misspellings and extra characters, 'bar' != 'BAR', and programmers need to think up a way of testing for where characters are the wrong case.

Simple solution, use toLowerCase. That works wonderfully, but what about our users who are using British English over American English when you're matching something == 'color'? Now you'll have to match something == 'color' || somthing == 'colour'.

Long story short, simple patterns turn into lots of repetitive code very quickly.

The color example can simply be matched with:

```<code>/colou?r/.test( something )
</code>```

a solid understanding of the basics of regular expressions can significantly reduce the amount of time you waste reinventing the wheel.

Where to study

Most languages that implement regular expressions have at least one resource available for the specific syntax of using Regular expressions within that language. One for JavaScript can be found on MDN

read it.

all of it.

then read it again.

It takes time to learn, think of it as an investment: an hour to learn RegEx now saves an hour the next time you need to do some string pattern matching, and then another hour the next time after that.

Practice

After reading all about RegEx, you probably wont understand most of it. That's because you're not actually doing anything with it.

I mentioned why I chose JS for this example, I urge you to mess with it in your browser. It's quick, and you can do it right in your URL bar.

JS has a few different and simple ways of using RegEx:

```<code>string.match( regex )
regex.exec( string )
regex.test( string )
</code>```

Starting with something simple like:

```<code>javascript:'color'.match(/colou?r/);
</code>```

is an easy way to get your foot in the door. Play with it, break it see what matches, and what doesn't.

When you get stuck on practice, continue to 30. You need to read to learn more, but you need to practice to truly understand what you've learned.

Title: How do you learn Regular Expressions?

Body:
How the heck do I tackle them?

Like any new thing:

10 Study
20 Practice
30 goto 10

Study

I find that most successful teachers start teaching any subject by first providing a bit of background to the subject. It's important to have a context of what you're learning and, most importantly, why you're learning it.

It's all string matching

Regular Expressions are a means of matching patterns in text. It's a declarative language itself incorporated into numerous other programming language.

I'd like to emphasize that it's a declarative language, regular expressions are useful for expressing what string to match, but they do not in any way express how the program is to go about doing the matching. For this reason it's possible to use regular expressions very quickly and very slowly in the same programming language simply by using a different RegEx parser.

The reason for creating regular expressions are the same for the creation of most programming languages: programmers found themselves performing the same complicated task over and over and decided they wanted a simpler way of writing the code.

Some will (and should) complain about my previous sentence by saying something along the lines of:

RegEx doesn't make a program simpler.

it's true

RegEx doesn't make a program any simpler, RegEx makes writing the program simpler. You still need to be thorough in your testing to be certain that all correct cases are matched correctly, and all incorrect cases are not. It's really hard to test "all", and with complicated patterns, it's really hard to test "most". At worst, you should still be testing "some" cases.

lets incorporate some examples I've obligatorily chosen JavaScript's RegEx engine because I can test it live in the browser easily and because I won't have to do any string escaping while using RegEx literals.

When you do normal string matching, you test one string value against another. They can come from anywhere, but in the end it takes two strings being compared against one-another:

if ( 'foo' == 'bar' ) doSomething();

That example sucks because it will never do anything

if ( foo == 'bar' ) doSomething();

Much better; now, we don't actually know ahead of time whether or not something will be done. We can now start accepting user input:

if ( prompt( 'Say "bar" to do something.' ) == 'bar' ) doSomething();

Wonderful, now users can input bar and something will happen, until you get bug reports from users saying that "bar" isn't working, or that "BAR" isn't working, or that they've typed BRA 100 times and nothing ever happens.

Ignoring the misspellings and extra characters, 'bar' != 'BAR', and programmers need to think up a way of testing for where characters are the wrong case.

Simple solution, use toLowerCase. That works wonderfully, but what about our users who are using British English over American English when you're matching something == 'color'? Now you'll have to match something == 'color' || somthing == 'colour'.

Long story short, simple patterns turn into lots of repetitive code very quickly.

The color example can simply be matched with:

/colou?r/.test( something )

a solid understanding of the basics of regular expressions can significantly reduce the amount of time you waste reinventing the wheel.

Where to study

Most languages that implement regular expressions have at least one resource available for the specific syntax of using Regular expressions within that language. One for JavaScript can be found on MDN

read it.

all of it.

then read it again.

It takes time to learn, think of it as an investment: an hour to learn RegEx now saves an hour the next time you need to do some string pattern matching, and then another hour the next time after that.

Practice

After reading all about RegEx, you probably wont understand most of it. That's because you're not actually doing anything with it.

I mentioned why I chose JS for this example, I urge you to mess with it in your browser. It's quick, and you can do it right in your URL bar.

JS has a few different and simple ways of using RegEx:

string.match( regex )
regex.exec( string )
regex.test( string )

Starting with something simple like:

javascript:'color'.match(/colou?r/);

is an easy way to get your foot in the door. Play with it, break it see what matches, and what doesn't.

When you get stuck on practice, continue to 30. You need to read to learn more, but you need to practice to truly understand what you've learned.


问:
Advantages of object-oriented programming
Note: this question is an edited excerpt from a blog posting I wrote a few months ago.  After placing a link to the blog in a comment on Programmers.SE someone requested that I post a question here so that they could answer it.  This posting is my most popular, as people seem to type "I don't get object-oriented programming" into Google a lot.  Feel free to answer here, or in a comment at Wordpress.

What is object-oriented programming?
  No one has given me a satisfactory
  answer.  I feel like you will not get
  a good definition from someone who
  goes around saying “object” and
  “object-oriented” with his nose in the
  air. Nor will you get a good
  definition from someone who has done
  nothing but object-oriented
  programming. No one who understands
  both procedural and object-oriented
  programming has ever given me a
  consistent idea of what an
  object-oriented program actually does.

Can someone please give me their ideas of the advantages of object-oriented programming?

答:
Think of software as a machine or assembly line that exists inside the computer. Some raw materials and components are fed into the machine, and it follows a set of procedures to process them into some final product. The procedures are set up to perform a specific operation on some raw material or component to a specific set of parameters (eg, time, temperature, distance, etc) in a particular order. If the details of the operation to be performed were incorrect, or the machine's sensors aren't correctly calibrated, or if some raw material or component wasn't within expected quality standards, it could change the operation's outcome and the product would not turn out as expected.

Such a machine is very rigid in its operation and acceptable inputs. Machines don't question the designers' intelligence nor its current operating environment. It will continue to follow procedures as long as it's directed to. Even if a change in raw materials or components could have a dramatic effect on what happened in later operations, the machine would still perform its procedures. The process would need to be reviewed to see what changes to the procedures were necessary to compensate and produce the desired result. A change to the product's design or configuration might also require a significant change to the operations performed or their order. Although those in charge of production quickly learned the importance of isolating operations as much as possible to reduce undesirable effects between them, a lot of assumptions are made of the condition components are in as they undergo processing; assumptions that might not be detected until the final product is in the hands of the user in some different operating environment.

That's what procedural programming is like.

What object-orientation provides is a way to remove the assumptions of the condition of components; thus, the operations to be performed on that component and how to integrate it into the final product. In other words, OOP is like taking the process details for dealing with some particular component and giving it to a smaller machine to do. The larger machine responsible for the process tells the component-specific machine which operation it expects to be done but leaves the details for the steps to the component-specific machine to handle.

As to the advantages of object-orientation over non-object-oriented software:

component-specific behavior - making details on how to handle a particular component the responsibility of the smaller component-specific machine ensures any time that component is handled, its machine will do so appropriately;

polymorphic expressions - because component-specific machines performs operations tailored to its particular component, the same message sent to different machines can act differently;

type abstraction - it often makes sense for several different types of components to use the same vocabulary for the operations their machines do;

separation of concerns - leaving component-specific details to their machines means the process machine only needs to handle the more general, larger concerns of its process and the data required to manage it; plus, it's less likely to be affected by changes in other components;

adaptability - components that focus on their area of speciality can be adapted to unforeseen use simply by changing the components it uses, or making it available to another process machine;

code reuse - components with a narrow focus and greater adaptability can leverage their development cost by being put to use more often.


答:
Anymore, I first try to make sure there isn't an easier way to solve the problem/"tokenize" the string.

When you can't find one, I look at it as a problem not of trying to match what you want out of the string, rather, it's a matter of NOT matching what you don't want. This is mostly because regex's are greedy. But it has served me well as an approach for getting what I want.

Here's an example:

```<code>string = "Sep 22 19:57:38 host fcron[9137]: \
          Job fbsetbg -r $HOME/backgrounds/ \
          started for user user (pid 9138)"
</code>```

to match the minute:

```<code>string.match /^\w+\s\d+\s\d+:(\d+):\d+\s\w+\s/ # correct but bad
string.match /\d+:([^:]+):\d+/                 # correct and good
</code>```

Instead of trying to find the time along with everything else, try to find the distinct boundaries.

The example is a bit contrived, but all I could come up with.

Title: How do you learn Regular Expressions?

Body:
Anymore, I first try to make sure there isn't an easier way to solve the problem/"tokenize" the string.

When you can't find one, I look at it as a problem not of trying to match what you want out of the string, rather, it's a matter of NOT matching what you don't want. This is mostly because regex's are greedy. But it has served me well as an approach for getting what I want.

Here's an example:

string = "Sep 22 19:57:38 host fcron[9137]: \
          Job fbsetbg -r $HOME/backgrounds/ \
          started for user user (pid 9138)"

to match the minute:

string.match /^\w+\s\d+\s\d+:(\d+):\d+\s\w+\s/ # correct but bad
string.match /\d+:([^:]+):\d+/                 # correct and good

Instead of trying to find the time along with everything else, try to find the distinct boundaries.

The example is a bit contrived, but all I could come up with.


答: I agree with Michael Kohne's answer in general.  I would add you need to read the installation docs to know what "make clean" actually does.  There can be different levels of clean that you might need to use, such as "make realclean" and "make distclean." There are informal conventions for these, but nothing carved in stone.</p>

Title: Is there a general rule for when you should use 'make clean' instead of just 'make'?

Body: I am writing a multiple-filed program right now, and apparently running only 'make' (as one would intuitively think needs to be done in most situations) for some reason causes my program to fail. I guess I can provide more detail of the problem, but the important thing is that it does run when using 'make clean'. So I was wondering if anyone knew the general rule of thumb for running 'make clean' instead of just 'make'</p>


答:
I start with

```<code># mcotton --version
</code>```

if that isn't enough I use

```<code># more mcotton
</code>```

And if they continue to look interested

```<code># tail -f /dev/random_thoughts
</code>```

Title: How do you respond to "Tell me a little bit about yourself." question in interviews?

Body:
I've been asked this in a few interviews. And it always catches me off guard.My professional and academic background are already in the resumé, which the interviewer has obviously looked at. What more to tell him/her? Should I start with my hobbies? I like gardening, or looking at NSFW pictures on reddit in my free time?

What and how do you answer to this specific question? Do you have a prepared answer for it? Am I wrong if I think this question is a bit silly?

UPDATE There have been a lot of great answers to this question. I'm in pickle which to choose as the 'correct' answer, because most of them are very insightful. I found a great writing on this subject matter. It's a bit crazy for my taste, but it's interesting:

How To Introduce Yourself… I Mean Practically

Body:
I start with

# mcotton --version

if that isn't enough I use

# more mcotton

And if they continue to look interested

# tail -f /dev/random_thoughts


问:
SQL Server CE 4, graphical tools for designing tables, etc.?
I thought that Visual Studio 2010 SP1 would include support for using SQL Server Compact Edition 4 inside the designer, but it seems not.

Was I wrong, or has I managed to botch up my installation somehow?

I installed SQL Server CE 4 from the download page, not through the web installer.

If Visual Studio 2010 SP1 does not, and should not, include such support, what are my choices, if any?

答:
Here's a list of 3rd party SQL CE tools, both 3.5 and (some of them) 4.0.

I've been using SQL CE Toolbox from that list which integrates with Visual Studio quite nicely.


问:
Should I sign an NDA and IP contract without an expiry date?
I work in a small software development company. I just received a NDA and IP contract to sign, but it doesn't have an expiry date.

Does this mean that it's a lifetime agreement with the corporation?

Lacking an explicit expiry date, is there an implicit date at which the contract expires?

If/when I leave the company, does the agreement still stand? If so, how long?

答:
My NDAs never had an explicit expiry date, but they always had the clause, that it's not a disclose, if the information is obvious to an outsider or if i have heard it from another source too.

And, with the timespan long enough, every technology, methodology, etc will be known Outsite the company. It may have been a company secret that apple worked on a 'new newton', but now that you can buy an iPad, it's not anymore.

So, these clauses act in combination with the relevance of the information as a de-facto expiry date.


答:
IP contracts are normally permanent (for the time of employment), you just sign off anything you create to the company as long as you are employed, but they keep the rights to it indefinitely. Don't let them take over your works created past the date of employment though ;)

NDA may be permanent if it's pretty narrow. Otherwise it may be restricting to your professional career - especially if they deem a secret something you know and use daily. So the NDA should either enumerate a short list of what you're not supposed to disclose, or have an expiry date. NDA on "any technology used within the company" will pretty much force you into a career of a hermit after leaving them.

Title: Should I sign an NDA and IP contract without an expiry date?

Body:
I work in a small software development company. I just received a NDA and IP contract to sign, but it doesn't have an expiry date.

Does this mean that it's a lifetime agreement with the corporation?

Lacking an explicit expiry date, is there an implicit date at which the contract expires?

If/when I leave the company, does the agreement still stand? If so, how long?


问:
What would be a good first functional programming project?
What would be a good first functional programming project?

I am looking to finish with a bang on my bachelor project and I want to finish it with a functional programming project. We didn't study it in school but we are encouraged to try to learn new things ourselves, and I thought learning a new paradigm not only a new language would be a great exercise for me, and probably something interesting for the teachers to see too.

The problem is I want to start a bit ahead of time on my project to take advantage of the summer holiday and get a better understanding on functional programming, and get familiar with one language.

What would you say would be a good practice project that is a bit challenging, but also lets me learn the language, paradigm etc. And then what would you think would be a good project (a more advanced one) for my bachelor project?

Suggestions for the best language to start with when going into functional programming would be appreciated too.

答:
You could also contribute to some open source project.

For example, in the Frege programming language project, there is much work to do. For instance, you could care about porting base Haskell libraries. This would make you sort of a Haskell expert while you work on it.


问:
Detecting Internet code leaks
I'm curious after reading today about a minor code leakage from a large project to some blogs & forums (to say it short: the guys forgot to anonymize the code before asking for help), all detected and (angrily) complained by the customer who reasonably wanted to protect the IP they paid for.

First of all, I know it's a good practice (correct me if I'm wrong), when required to disclose code to public sites in order to ask for help, to take appropriate anonymization measures, like renaming in all snippets something like com.thecompanyiworkfor with com.somecompany or com.bank.MortgageRiskCalculatorClass to com.somecompany.SomeGenericRiskIndicatorClass and so on...

Now, suppose I would like to find out if and where (and maybe who, but it's not important now and it's not part of the question) the originally restricted code was leaked in order to properly react (read "send all the guys an email telling either they delete/clean posts or something bad will happen to the culprit", haha).

I suppose that a good way could be googling something unique that you could find in the code. For example, if I worked for Inintech I would try to google for com.inintech to see if somebody was stupid enough to paste code full with import/using directives.

It's not a comprehensive method, it's based on the assumption that someone is better trying to protect the binding between company and code (ie. for security by obscurity reasons, public image...) rather than preventing intellectual property from being freely available to the public.

My straight questions are:

Do you know/think there are other good practices to perform such investigations? How would you do that if your boss asks to find if someone leaked the company's code? I don't think someone would ever try to google for an entire source code file in one query string :)

Do you know if there are companies performing such investigations? If so, what could you tell me about them more than their names, like the way they work?

答:
Ultimately I cant see any damage that has been done. So a small number of techie  saw your companies name is a block of code, big deal.

If you make a huge fuss over this it will alienate your staff and discorage them from using internet resources like SO. That really will damage the company.

My advice would be act as if you haven't seen it. Since it seems to bother you, if you do happen to find out exactly who is doing it then send them a private email asking them to take more care but go no further. Dont waste time and resources finding out who it is.

EDIT: This advice is only relvent if your company is developing internaly not for clients. See the comments below.

Title: Detecting Internet code leaks


问:
How granular should TDD tests be?
During TDD training based on medical software case we are implementing the following story: "When user presses Save button, system should add patient, add device and add device data records".

The final implementation will look something like this:

```<code>if (_importDialog.Show() == ImportDialogResult.SaveButtonIsPressed)
{
   AddPatient();
   AddDevice();
   AddDeviceDataRecords();
}
</code>```

We have two ways to implement it:

Three tests where each verifies one method (AddPatient, AddDevice,     AddDeviceDataRecords) was called

One test which verifies all three methods were called

In the first case if something wrong is happend to if clause condition, all three tests will fail. But in the second case if test fails, we are not sure what is exactly wrong. What way would you prefer.

答:
But in the second case if test fails, we are not sure what is exactly wrong.

I think that would largely depend on how good error messages the test produces. In general, there are different ways to verify that a method has been called; e.g. if you use a mock object, it will give you a precise error message describing which expected method was not called during the test. If you verify that the method was called via sensing the effects of the call, it is up to you to produce a descriptive error message.

In practice, the choice between options 1 and 2 also depends on the situation. If I see the code you show above in a legacy project, I choose the pragmatic approach of Case #2 just to verify that each of the 3 methods are called properly when the condition is fulfilled. If I am developing this piece of code right now, the 3 method calls would most likely be added one by one, at separate points in time (possibly days or months away from each other), so I would add a new, separate unit test to verify each call.

Note also, that either way, you should also have separate unit tests to verify that each of the individual methods do what it is supposed to do.

Title: How granular should TDD tests be?


问:
Unit testing methods that call suppliers webservices
I have a class with one public method Send() and a few private methods. It calls a couple of webservices and processes the reponse. The processing is done in private methods.

I want to unit test the code. My understanding is that unit tests should test my code in isolation (ie mock up supplier responses).

I also believe that private methods should not need to be unit tested But if I just test the Send() method my code isnt being tested in isolation and is dependent on the supplier resonse.

Should I then make my private methods public so I can test them with mock responses? It seems bad practice since I only the class should need to call them.

Apologies if its a basic question, im fairly new to unit testing.

Im using c# and VS2010

答:
You should separate the code dealing with the web services (i.e. sending and receiving data) from the code processing the results. Move the latter code into a distinct class, making the necessary methods public. Then you can easily unit test the processing logic, in isolation from the external dependencies.

By this, you also make your code conform to the Single Responsibility Principle. As a general rule of thumb, feeling the need to test private methods is often an indication that the class has too many responsibilities, thus should be refactored into multiple classes.


答:
The Granularity in your example seems to be the difference between unit- and acceptance tests.

A unittest tests a single unit of functionality, with as few dependencies as possible. In your case, there could 4 unittests

does AddPatient add a patient (i.e. calls the relevant database functions)?

does AddDevice add a device?

does AddDeviceDataRecords add the records?

does the unamend main function in your example call AddPatient, AddDevice and AddDeviceFunctions

Unittests are for the developers, so they get confidence, that their code is technically correct

The acceptance tests should test the combined functionality, from the perspective of the user. They should be modeled along the user stories, and be as high level as possible. So, you don't have to check if functions are called, but if a benefit visible to the user is achieved:

when the user enters the data, clicks ok and...

...goes to the patient list, he should see a new patient with the given name

...goes to the device list, he should see a new device

...goes to the new device's details, he should see new datarecords

acceptance tests are for the customers, or, for building a better communication with them.

To answer your question "what would you prefer": what is a bigger problem to you right now, bugs and regression (=> more unittests) or understanding and formalizing the big picture (=> more acceptance tests)

Title: How granular should TDD tests be?

Body:
During TDD training based on medical software case we are implementing the following story: "When user presses Save button, system should add patient, add device and add device data records".

The final implementation will look something like this:

```<code>if (_importDialog.Show() == ImportDialogResult.SaveButtonIsPressed)
{
   AddPatient();
   AddDevice();
   AddDeviceDataRecords();
}
</code>```

We have two ways to implement it:

Three tests where each verifies one method (AddPatient, AddDevice,     AddDeviceDataRecords) was called

One test which verifies all three methods were called

In the first case if something wrong is happend to if clause condition, all three tests will fail. But in the second case if test fails, we are not sure what is exactly wrong. What way would you prefer.


答:
We have two ways to implement it:

That's false.

Three tests where each verifies one method (AddPatient, AddDevice, AddDeviceDataRecords) was called

You must do this to be sure it works.

One test which verifies all three methods were called

You must also do this to be sure the API works.

The class -- as a unit -- must be completely tested.  Each method.

You can start with a test that covers all three methods, but it doesn't tell you much.

if test fails, we are not sure what is exactly wrong.

Correct.  That's why you test all methods.

You must test the public interface.  Since this class does three plus one things (even if they're bundled in one method because of user story) you must test all four things.  Three low-level and one bundle.

Title: How granular should TDD tests be?


问:
State machines vs threads
Alan Cox once said "A Computer is a state machine. Threads are for people who can't program state machines".

Since asking Alan directly is not an option for humble me, I'd rather ask here:  how does one achieve multi-threading functionality in high-level language, such as Java, using only one thread and state machine? For example, what if there are 2 activities to perform (doing calculations and doing I/O) and one activity can block?

Is using "state-machine only" way viable alternative to multi-threading in high-level languages?

答:
I don't think it is - sure, state machines are a very 'elegant' computing concept but as you say, they're quite complicated. And complicated things are difficult to get right. And things that are not right are just broken, so unless you're a genius of Alan Cox's presumed stature, stick with stuff you know works - leave the 'clever coding' to learning projects.

You can tell when someone has made the vain attempt to do one, as (assuming it works well) when it comes to maintain it, you find that the task is next to impossible. The original 'genius' will have moved on leaving you with the lump of barely-understandable code (as these type of developers don't tend to leave too many comments let alone technical documentation).

Some cases, a state machine will be a better choice - I'm thinking of embedded type stuff now where some state machine patterns are used, and used repeatedly and in a more formalised way (ie proper engineering :) )

Threading can be difficult to get right too, but there are patterns to help you along - mainly by reducing the need to share data between the threads.

The last point about this is that modern computers run on many cores anyway, so a state machine will not really take good advantage of the resources available. Threading can do a better job here.

Title: State machines vs threads