答:
This sounds to me like an Opportunity.

It's clear that you already can see lots of problems in how things are done and managed. You can either complain that it's all rubbish and that you can't do anything, OR you can use this as a golden opportunity to really show your employer your worth.

Now, it's not going to help you if you march up to your employer and tell him that everything needs to change.  So the trick is to play along for a while, ask LOTS of questions, and when you are required to write code you'll need to play by their rules with all of the comments etc, as you are going to need to keep other developers informed using whichever system they presently prefer, while at the same time you can introduce sensible refactorings that won't risk you anything. You can extract a couple of methods, and if your language supports it, introduce a few unit tests.  When asked why you've done it this way, or if told you're doing something "wrong", avoid getting defensive or argumentative while making a sound presentation of your position for your preferred style of coding.  For example, you can refer to books such as Bob Martin's Clean Code, or you can refer to other books, articles, or even questions and answers that you have come across on Programmers.SE.  Anything that you can find helpful to support your position with facts that might be beyond your experience in the eyes of the people you are working with.

With regards to the excessive commenting, some of this can be cleared up if you were to add in a few descriptive names for the variables and methods, but you might also be able to make a case for a good version control system, and using that to keep the record of the changes and dates etc, and for the use of a tool to compare the different versions of your source files if one doesn't already come with your chosen VCS.

Like I said, this is an opportunity to contribute to the improvement of a development team that sounds like it's kind of lost its way so to speak.  You have the opportunity to stand out as skilled and knowledgeable, and as someone who can lead by example. These are all good things to help you later as your career progresses.


问:
Strategies for avoiding SQL in your Controllers... or how many methods should I have in my Models?
So a situation I run into reasonably often is one where my models start to either:

Grow into monsters with tons and tons of methods

OR

Allow you to pass pieces of SQL to them, so that they are flexible enough to not require a million different methods

For example, say we have a "widget" model. We start with some basic methods:

get($id)

insert($record)

update($id, $record)

delete($id)

getList()  // get a list of Widgets

That's all fine and dandy, but then we need some reporting:

listCreatedBetween($start_date, $end_date)

listPurchasedBetween($start_date, $end_date)

listOfPending()

And then the reporting starts to get complex:

listPendingCreatedBetween($start_date, $end_date)

listForCustomer($customer_id)

listPendingCreatedBetweenForCustomer($customer_id, $start_date, $end_date)

You can see where this is growing... eventually we have so many specific query requirements that I either need to implement tons and tons of methods, or some sort of "query" object that I can pass to a single ->query(query $query) method...

... or just bite the bullet, and start doing something like this:

list = MyModel->query(" start_date > X AND end_date < Y AND pending = 1 AND customer_id = Z ")

There's a certain appeal to just having one method like that instead of 50 million other more specific methods... but it feels "wrong" sometimes to stuff a pile of what's basically SQL into the controller.

Is there a "right" way to handle situations like this? Does it seem acceptable to be stuffing queries like that into a generic ->query() method?

Are there better strategies?

答:
Some ORMs allow you to construct complex queries starting from basic methods. For instance

```<code>old_purchases = (Purchase.objects
    .filter(date__lt=date.today(),type=Purchase.PRESENT).
    .excude(status=Purchase.REJECTED)
    .order_by('customer'))
</code>```

is a perfectly valid query in the Django ORM.

The idea is that you have some query builder (in this case Purchase.objects) whose internal status represents information about a query. Methods like get, filter, exclude, order_by are valid and return a new query builder with an updated status. These objects implement an iterable interface, so that when you iterate over them, the query is performed and you get the results of the query constructed so far. Although this example is taken from Django, you will see the same structure in many other ORMs.

ContentLicense: CC BY-SA 3.0

Body:
Some ORMs allow you to construct complex queries starting from basic methods. For instance

old_purchases = (Purchase.objects
    .filter(date__lt=date.today(),type=Purchase.PRESENT).
    .excude(status=Purchase.REJECTED)
    .order_by('customer'))

is a perfectly valid query in the Django ORM.

The idea is that you have some query builder (in this case Purchase.objects) whose internal status represents information about a query. Methods like get, filter, exclude, order_by are valid and return a new query builder with an updated status. These objects implement an iterable interface, so that when you iterate over them, the query is performed and you get the results of the query constructed so far. Although this example is taken from Django, you will see the same structure in many other ORMs.


问:
Reflection: Is using reflection still "bad" or "slow"? What has changed with reflection since 2002?
I've noticed when dealing with Expressions or Expression Trees I'm using reflection a lot to set and get values in properties and what have you. It has occurred to me that the use of reflection seems to be getting more and more common. Things like DataAnotations for validation, Attribute heavy ORMs, etc. Have me wondering: What has changed since the days years and years ago when I used to be told to avoid reflection if at all possible?

So what, if anything has changed? Is it just the speed of the machines? Have there been changes to the framework to speed up reflection?

Or has nothing really changed? Is it still "bad" or "slow" to use reflection?

答:
The reason people are wary of using reflection unnecessarily is not performance: yes, there is some overhead to using reflection, but often, solving the problem without it requires a different approach with comparable complexity, and even if it doesn't, the overhead is seldom significant (especially for application-level development).

Using reflection, some important assumptions one can normally make about source code are broken, and tools such as "Find All References" cease to work reliably. Reflection also basically removes most of the type safety the compiler enforces in, say, C#, and most of the programming errors that a type system would normally catch and translate into compiler errors, now become runtime errors at best or very obscure bugs at worst.

So why do people use reflection then? Simply put, because despite the problems described above, it is a very valuable tool. With reflection, some of the benefits of dynamic programming can be had in a static, strictly-typed language like C#, and dynamic programming languages have shown their merits recently, especially in the realm of web programming - PHP, Javascript, and quite prominently Python, all use dynamic typing, and have proven to be good fits for web programming. But since the language is still C#, you can choose to keep most of your application in a strictly-typed OOP idiom, and write the small part where dynamic behaviour really makes a difference with reflection.

A typical example is when you need to expose methods as web service calls (using a protocol not yet built into .NET). The strictly-typed OOP approach does work, but it is overly restrictive and clumsy. But if you use reflection to map calls to methods and key/value pairs to arguments, you can write the plumbing for such a web service once and then use it on any class you like.


问:
Using Domain name in EULA of a software rather than my name in the Licensor field
I intend to sell a software solution. I have already registered a domain but I don't have a registered company. Can I use my website/domain name (eg:myproduct.com) for the licensor field in the EULA rather than using my name?

I will renew my domain yearly if there is a problem with this. Do you know any software companies that work like this?

I'm confused about the users point of view will they find it a bit different.

答:
The usual IANAL applies - for legal advice, consult a lawyer.

That said, my understanding is that a domain name or a website are not themselves legal persons, and thus cannot close any legally binding agreements. Natural persons and corporations can, and the way these things are usually done is by defining the domain name or website URL as the legal person closing the agreement in the first section of the agreement - something like this:

John Doe, Example Way 15, Someplace 12345 ('example.com') and ____ ('licensee') hereby agree upon the following: ...

In any case, EULA's are legally tricky, especially if you consider that multiple countries with conflicting laws may be involved, so if the EULA is vital to you, by all means spend some money on actual legal consult.


问:
GPL vs plugin interfaces not designed with a specific application in mind
I am not seeking or in need of legal advice, but an interesting though experiment came to my mind.

Imagine the following situtation (I cannot really think about a concrete example and I am unsure if a real manifestation even exists): there is a free (libre) api A licensed under some permissive license or even LGPL. Non-free application B implements this api in order host plugins, but there are other free software doing the same thing. Moreover, there is plugin C acting as a plugin under api A. It links to library D, that is under GPL, so C is also under GPL. Plugins using A are loaded into hosts via a dlopen-like mechanism and use complex data structure for host-plugin communication. Neither B nor C distribute any files that may be required for A to function properly (like headers containing the structure definitions of A or dynamic libraries containing helper functions for A written by the authors of A), but such things may exist.

Now some user installs application B and plugin C on his machine, along with anything that may be required for api A to function properly. Then he proceeds and loads C into B and creates some intellectual property with B which is not a piece of software.

Did a GPL violation happend at some point, and if so, who violated GPL and why?

The authors of C violate D's license by making C possible to be used in non-free host B? This is a possibility because they can't give and exception of GPL (like one described in http://www.gnu.org/licenses/gpl-faq.html#GPLPluginsInNF or http://www.gnu.org/licenses/gpl-faq.html#LinkingOverControlledInterface) due to D's license terms.

The authors of B violate C's and D's license by making C possible to be loaded in B? This is a possibility because http://www.gnu.org/licenses/gpl-faq.html#NFUseGPLPlugins disallows the mechanisms A uses for communitation between the free and non-free modules.

The authors of A, because the api may be used (and in this case, was used) for communication between GPL'd and non-free software. This would be extremely absurd.

The user, because at the moment of loading B into C, he made a derived work of C. I think this is impossible, because he does not distribute it. But would the situation change is he decided to release a configuration file of B which makes B load C as a plugin?

Nobody, because A counts as a 'system library', and both B and C directly interact only with A, not eachother. In a sane world, this would happen...

A concrete example of A could be some kind of audio (think LADSPA) or image processing api. However, I could find no such interface (that is free software, generic and is also implemented by commercial tools). A real-world example could also be quite enlightening.

答:
Given your description, I think A and B is irrelevant to the question, what matters is C and D, and the question comes down to whether or not GPL allows dynamic linking. If anyone may violate the GPL, it is C if it is not under GPL.

After some digging around, I found that the Wikipedia GPL article has a good summary of the issue. The answer is: it is disputed. The three existing standpoints, according to this article:

Both dynamic and static linking violates1 the GPL. This is the standpoint of the makers of the GPL (the Free Software Foundation), and they created the LGPL for this reason (to allow dynamic linking without violation).

Static linking violates, but the GPL is not clear about dynamic linking: It is hard to tell since the GPL does not provide clear instruction about what is considered derivative work.

Linking is irrelevant: GPL should only apply to source code-level. In my opinion this is the most sane option, since linking to a software to access its functionality is akin to pushing a button on a GUI to do the same thing.

Since the FSF says its intention with the GPL is to disallow both, I think it is wiser to either

respect that intention and use GPL on your own work if you link to GPL, even if the wording is not clear

or stay away from GPL software

Ironically, the GPL is not as free/libre as one would think. I know there is a reason for that, but my point is: don't put GPL on your software without thinking. If you are looking for a free and permissive license, the MIT or BSD licenses might represent your intentions better.

1: when I say "violates" I mean it violates iff the "consumer" of the linking is not under GPL.


问:
Resources on concepts/theory behind GUI development?
I was wondering if there were any resources that explain concepts/theory behind GUI development. I don't mean a resource that explains how to use a GUI library, but rather how to create your own widgets. For example a resource that explains different methods on how to implement scrollable listboxes.

I ask because I have an idea for a game tool where I would like to create my own widgets and let users drag and drop them onto some kind of form.

How do GUI libraries usually draw widgets?

I'm not sure if reskinning widgets from a GUI library fits my needs, since widget behavior needs to be dynamic based on user interaction.

答:
This depends so strongly on the architecture of the widget library you're inter operating with that you're unlikely to find a one-size-fits-all high level guide. For example, some libraries separate drawing views and responding to events, others put them in the same class. In some your widget prepares a bitmap of its view that it sends to the window manager, in others your widget emits a stream of vector commands or a graphics shader.

So the answer to your question about creating a game tool is where will that game tool run? You should find out how that gui's conventions work and build something that impedance-matches those conventions.


答:
I think the general consensus is to keep as much as data access as possible in your models in MVC.
One of the other design priciple is to move some of your more generic queries (Those which are not directly related to your model) to a higher, more abstract level where you can allow it to be used by other models as well. (In RoR, we have something called framework)
There is also another thing that you have to consider and that is the maintanability of your code.
As your project grows, if you have data access in controllers, it will become increasingly difficult to track it down(We are currently facing this issue in a huge project)
Models, although cluttered with methods provide a single point of contact for any controller who might end up quering from the tables. (This may also lead to a reuse of code which is in turn beneficial)</p>

Title: Strategies for avoiding SQL in your Controllers... or how many methods should I have in my Models?

Body:
So a situation I run into reasonably often is one where my models start to either:

Grow into monsters with tons and tons of methods

OR

Allow you to pass pieces of SQL to them, so that they are flexible enough to not require a million different methods

For example, say we have a "widget" model. We start with some basic methods:

get($id)

insert($record)

update($id, $record)

delete($id)

getList()  // get a list of Widgets

That's all fine and dandy, but then we need some reporting:

listCreatedBetween($start_date, $end_date)

listPurchasedBetween($start_date, $end_date)

listOfPending()

And then the reporting starts to get complex:

listPendingCreatedBetween($start_date, $end_date)

listForCustomer($customer_id)

listPendingCreatedBetweenForCustomer($customer_id, $start_date, $end_date)

You can see where this is growing... eventually we have so many specific query requirements that I either need to implement tons and tons of methods, or some sort of "query" object that I can pass to a single ->query(query $query) method...

... or just bite the bullet, and start doing something like this:

list = MyModel->query(" start_date > X AND end_date < Y AND pending = 1 AND customer_id = Z ")

There's a certain appeal to just having one method like that instead of 50 million other more specific methods... but it feels "wrong" sometimes to stuff a pile of what's basically SQL into the controller.

Is there a "right" way to handle situations like this? Does it seem acceptable to be stuffing queries like that into a generic ->query() method?

Are there better strategies?


答:
Real world examples:

Motif API and it's various implementations Motif (proprietary), OpenMotif (Open Group Public License), LessTif (LGPL). Libraries are drop-in replacements, you can dynamically compile your code with OpenMotif and run it with LessTif or vice-versa.

Proprietary Linux drivers — in most cases to avoid licensing issue there is thin (L)GPL wrapper which loads proprietary code. Wrapper unique purpose may be separation, like example Nvidia's binary driver, or separation might be just a side effect, like for example in case of NDISwrapper.

Title: GPL vs plugin interfaces not designed with a specific application in mind

Body:
I am not seeking or in need of legal advice, but an interesting though experiment came to my mind.

Imagine the following situtation (I cannot really think about a concrete example and I am unsure if a real manifestation even exists): there is a free (libre) api A licensed under some permissive license or even LGPL. Non-free application B implements this api in order host plugins, but there are other free software doing the same thing. Moreover, there is plugin C acting as a plugin under api A. It links to library D, that is under GPL, so C is also under GPL. Plugins using A are loaded into hosts via a dlopen-like mechanism and use complex data structure for host-plugin communication. Neither B nor C distribute any files that may be required for A to function properly (like headers containing the structure definitions of A or dynamic libraries containing helper functions for A written by the authors of A), but such things may exist.

Now some user installs application B and plugin C on his machine, along with anything that may be required for api A to function properly. Then he proceeds and loads C into B and creates some intellectual property with B which is not a piece of software.

Did a GPL violation happend at some point, and if so, who violated GPL and why?

The authors of C violate D's license by making C possible to be used in non-free host B? This is a possibility because they can't give and exception of GPL (like one described in http://www.gnu.org/licenses/gpl-faq.html#GPLPluginsInNF or http://www.gnu.org/licenses/gpl-faq.html#LinkingOverControlledInterface) due to D's license terms.

The authors of B violate C's and D's license by making C possible to be loaded in B? This is a possibility because http://www.gnu.org/licenses/gpl-faq.html#NFUseGPLPlugins disallows the mechanisms A uses for communitation between the free and non-free modules.

The authors of A, because the api may be used (and in this case, was used) for communication between GPL'd and non-free software. This would be extremely absurd.

The user, because at the moment of loading B into C, he made a derived work of C. I think this is impossible, because he does not distribute it. But would the situation change is he decided to release a configuration file of B which makes B load C as a plugin?

Nobody, because A counts as a 'system library', and both B and C directly interact only with A, not eachother. In a sane world, this would happen...

A concrete example of A could be some kind of audio (think LADSPA) or image processing api. However, I could find no such interface (that is free software, generic and is also implemented by commercial tools). A real-world example could also be quite enlightening.


问:
Which open source PHP project has the 'perfect' OOP design I can learn from?
I am a newbie to OOP, and I learn best by example.

You could say this question is similar to Which Scala open source projects should I study to learn best coding practices - but in PHP.

I have heard-tell that Symfony has the best 'architecture' (I will not pretend I know what that exactly means), as well as Doctrine ORM. Is it worth it to spend many months reading the source code of these projects, trying to deduce the patterns used and learning new tricks?

I have seen equal number of web pages dissing and liking Zend's codebase (will provide links if deemed necessary).

Do you know of any other project that would make any veteran OOP developer shed tears of joy?

Please let me add that practicality and scope of use is not a concern at all here - I just want to do:

Pick a project that has a codebase deemed awesome by devs way better and greater than me.

Write code that achieves what the project does.

Compare results and try to learn what I don't know.

Basically, an academic interest codebase. Any recommendations please?

答:
Symfony 2 is probably the best large project to learn from but is pretty big.

I recently found a neat and small open source PHP project called Phrozn (static site generator).
It's code base is relatively small so you can examine it pretty fast.

UPDATE:

Phrozn is modern (uses PHP 5.3+ and relies on it heavily), it's extensible, has strict code coverage. It also re-uses code from other well written projects such as Symfony (YAML), Zend (Autoloader), PEAR and Twig.

OOP, uses namespaces and it's very well documented. I'm not saying it's perfect nor that it can be compared to a project like Symfony but it's worth a shot.


问:
How do you maintain focus when a particular aspect of programming takes 10+ seconds to complete?
I have a very difficult time focusing on what I'm doing (programming-wise) when something (compilation, startup time, etc.) takes more than just a few seconds.  Anecdotally it seems that threshold is about 10 seconds (and I recall reading about study that said the same thing, though I can't find it now).  So what typically happens is I make a change and then run the program to test it.  That takes about 30 seconds, so I start reading something else, and before I know it 20 minutes have passed, and then it takes (if I'm lucky!) another 10+ minutes to deal with the context switch to getting back into programming.

It's not an exaggeration to say that some things that should take me minutes literally take hours to complete.

I'm very curious about what other programmers do to combat this tendency (or if I'm unique and they don't have this tendency?).  Suggestions of any type at all are welcome - anything from "sit on your hands after hitting the compile button", to mental tricks, to "if it takes 30 seconds to start up something to test a change, then something's wrong with your development process!"

答:
For internet distraction during work in general, i suggest The Pomodoro Plugin if you are using Google Chrome

I personally think that you can't be productive during all your working time ! since you are compiling, it means that you made enough efforts to take a breath ... to not abuse or get out of the context, keep thinking on the next step if the compilation doesn't generate errors ... Or clean your working area : Desktop, Tabs, Explorer ...


答:
Make a plan at the beginning of each day as to how to use this "spare time".  It might involve

catching up on some documentation tasks,

working out unit test cases for the class that you're going to write next,

studying some new piece of technology that you've been meaning to learn,

writing a letter to your favourite aunt,

or just about anything really.

Have this secondary task always open in a window somewhere on your desktop.  As soon as you hit the "compile" button (or whatever it is that's taking you more than 30 seconds), switch to the secondary task, and put in enough time to actually move forwards on it, which could be a couple of minutes, or could be less.

While you're doing the secondary task, keep it in the back of your mind that this not what your brain should be focussed on.  Keep thinking about programming.  This isn't easy; you'll still suffer from the context switch more often than not.

If you do this, even if you lose context many times, your lost time isn't actually wasted time, and you've got something to show for it at the end of the day.  But the most important thing is to plan, at the beginning of the day, what the day's secondary task is going to be.

Title: How do you maintain focus when a particular aspect of programming takes 10+ seconds to complete?

Body:
I have a very difficult time focusing on what I'm doing (programming-wise) when something (compilation, startup time, etc.) takes more than just a few seconds.  Anecdotally it seems that threshold is about 10 seconds (and I recall reading about study that said the same thing, though I can't find it now).  So what typically happens is I make a change and then run the program to test it.  That takes about 30 seconds, so I start reading something else, and before I know it 20 minutes have passed, and then it takes (if I'm lucky!) another 10+ minutes to deal with the context switch to getting back into programming.

It's not an exaggeration to say that some things that should take me minutes literally take hours to complete.

I'm very curious about what other programmers do to combat this tendency (or if I'm unique and they don't have this tendency?).  Suggestions of any type at all are welcome - anything from "sit on your hands after hitting the compile button", to mental tricks, to "if it takes 30 seconds to start up something to test a change, then something's wrong with your development process!"


答:
Whatever you do don't go on any of the StackExchange sites. They will suck you in :)

More seriously, browsing the web while waiting for something to finish it's not good for the productivity (unless you're researching something related to the current task).

I usually do few minor tasks that will not take longer than 1-2 min. (cleaning something, writing comments, notes).


答:
For keeping my attention up I use doodles. I always have a pen and a notepad lying behind my keyboard and doodle away. It isn't more then scrabbling on a piece of paper without any meaning but it keeps my attention up just enough and doesn't get me distracted so I can snap right back to what I was working on.

I've done this all my life unconsciously but recently found a wiki about it: http://en.wikipedia.org/wiki/Doodle


问:
What to answer to a customer who asks which one of two equivalent technologies must be used?
As a freelancer, I am often asked by my customers what they must choose between similar elements, neither of which being better than another. Examples:

“Do I need my e-commerce website be in PHP or ASP.NET?”

“Do I need to host this ordinary web service in Cloud or use an ordinary hosting service?”

“Which one is better for my new website: MySQL or Oracle?”

etc.

There is maybe at most 1% of cases where the choice is relevant, and there is a real, objective reason to use one over another, based on the precise metrics and studies. In all other cases, it doesn't matter at all. It is totally, completely irrelevant, either because there are no implications¹, or because those implications are too small to be taken in account², or, finally, because it's impossible to predict those implications³.

If you know one thing and not another one, the answer to those questions is easy:

“You can either write the application in C# or Java, both being probably equivalent in your case. Note that I'm a C# developer, so if you choose Java, I would not be able to work on your project and you would need to find another freelancer.”

When you know both technologies, you can't answer that.

In this case, how to explain to the customer that the question he asks is subject to flamewar and has no real consequences on his project?

In other words, how to explain that you've chosen to use one technology rather than an equivalent one for the reasons related to human resources, without giving the impression to be unprofessional or to not care about the project?

¹ Example: Is MySQL better (worse?), performance-wise, compared to Oracle, for a personal website which will be accessed by, oh, let's be optimistic, two people per day?

² Example: for a given project, I was asked to asset if Windows Azure hosting would be cheaper than the hosting of the same application on a well-known ASP.NET hosting provider. The cost revealed to be exactly the same.

³ Example: your customer have an idea of a future application (the idea itself being extremely vague). There is no business plan, no requirements, nothing at all. Just an idea. You are asked if Java is better than C# for this app. What do you answer?

答:
Lots of good responses already, but one thing I noticed hasn't been mentioned: this is an excellent opportunity for full disclosure on your part.  For example,

"Now I make my living primarily from technology <foo>, so I'm not completely impartial.  However ..."

I really think you gain credibility by this kind of statement.


答:
Martin Fowler's Patterns of Enterprise Application Architecture describes a number of ORM related paterns, including use of the Query Object,  which is what I'd suggest.

Query objects let you follow the Single Responsibility principle, by separating the logic for each query into individually managed and maintained strategy objects.  Either your controller can manage their use directly, or delegate that to a secondary controller or helper object.

Will you have a lot of them?  Certainly.  Can some be grouped into generic queries?  Yes again.

Can you use dependency injection to create the objects from metadata?  That's what most ORM tools do.


答:
I guess I'll be the one to say it but you should just sit there and wait for it to finish.

You need to retrain yourself to not feel the need to be constantly on and actively doing things. This is a very detrimental issue that affects not just developers but all people. Society has become obsessed with the need for constant stimulation (visual, audio, mental). It seems no one can stand to be idle for more than 30 seconds without pulling their phone out and texting, surfing the web, checking facebook, etc.

If you hit compile and it's going to take a minute or so consider that a great opportunity to just sit and let your brain relax. Resist the urge to do something stimulating and just enjoy a moment of non activity.

With time it will become easier and you'll find you will have a much better work experience when you stop trying to keep your brain firing at 100% all day long.


问:
Attending my first software conference - any tips before I go?
My nice employer allowed me to visit a software conference in June (International PHP Conference, for those who care).

Wanting to make the most of it, I would ask the more experienced conference goers in here to give me some tips on what I could do to maximize my learning experience on the conference, and to reduce beginner mistakes.

Sorry that this question is a little ambiguous, but I think it's best to keep it a little bit more open, so I can get a wide range of Ideas, and it will be of more use to further people seeking for an answer.

答:
Review the schedule before you go.

Choose two sessions for each time slot. Some will get cancelled, some moved, some full, some you'll decide that the speaker was terrible last time, some you'll just want to hear them speak again, but you'll need options.

Take notes, however you would normally.  I prefer a notepad and pen, but make sure you use the method you are most comfortable with.  Many of these will be useless later, or at least my own notes often are, but I find I retain more and can get the gestalt, which I find the most useful.

If possible have a buddy system.  Each of you take a track relevant to your position, or employer, or where the industry or your particular use of the technology is likely to be headed.

Talk to other attendees.  I've made both interesting social and business contacts this way, in addition to the added perspective and tips on what/who to go see, especially as many sessions are offered at multiple times.

Use what you've learned.  Practice those IDE shortcuts, write up that sample application, read the mentioned reference documentation, and do it all at the end of the day, back in your room.

[Edit]
 7. (or 8. see @Ozz comment.) Give a presentation of the highlights to your team when you return.  A summation of where the technology is heading and what your company might be able to use in that future helps you recall what you learned, spreads the wealth a little bit, and reminds your boss why he, or she, paid for it.


问:
Using Clojure instead of Python for scalability (multi-core) reasons, good idea?
After reading http://clojure.org/rationale and other performance comparisons between Clojure and many languages, I started to think that, apart from ease of use, I shouldn't be coding in Python anymore, but in Clojure instead. Actually, I began to feel irresponsible for not learning Clojure, seeing it's benefits.

Does it make sense? Can't I make really efficient use of all cores using a more imperative language like Python, than a Lisp dialect or other functional language? It seems that all the benefits of it come from using immutable data, can't I do just that in Python and have all the benefits?

I once started to learn some Common Lisp, read and did almost all the exercises from a book I borrowed from my university library  (I found it to be pretty good, despite it's low popularity on Amazon). But, after a while, I found myself struggling too much to do some simple things. I think there's somethings that are more imperative in their nature, that makes it difficult to model those things in a functional way.

So is Python as powerful as Clojure for building applications that take advantage of this new multi-core future?

Note that I don't think that using semaphores, lock mechanisms or other similar concurrency mechanism are good alternatives to Clojure's 'automatic' parallelization.

答:
Python is extremely bad for applications that need multiple threads, but it's caused by deficiency in the available virtual machines, not the language itself. Python's generators would really be good candidates for implicit parallelisation. The problem is that the standard implementation, CPython, can only execute python code on one CPU, only calls in native libraries can run in parallel. The PyPy runtime plans to fix it, but is not there yet and while the Jython and IronPython implementations don't have the limitation, they are rather incomplete (they don't have much of the standard library, you have to use the standard library of the hosting environment in them).

However there are many other languages designed and implemented with parallelism. Of course parallelism is much easier in functional languages, which is why all the languages with good parallelism support are either functional, or have strong support for functional programming. I can think of:

Haskell, the most used pure, non-strict functional language. It's pure non-strict nature allows the compiler to parallelise some things implicitly.

Erlang is a strict functional language designed specifically for implementing robust parallel servers, with built-in support for distribution to clusters.

Clojure, of course. Like other lisps it is designed for functional programming, but supports imperative programming as well.

Go is a new compiled procedural language designed for concurrency, though neither the runtimes nor the language itself are very mature yet.

Rust is a new compiled procedural language designed for concurrency, low overhead and static checking of memory and concurrency safety. Not very mature yet either.


问:
When should JavaScript generate HTML?
I try to generate as little HTML from JavaScript as possible. Instead, I prefer to manipulate existing markup whenever I can and only generate HTML when I need to dynamically insert an element that isn't a good candidate for using Ajax. This, I believe, makes it far easier to maintain the code and quickly make changes to it because the markup is easier to read and trace. My rule of thumb is: HTML is for document structure, CSS is for presentation, JavaScript is for behavior.

However, I've seen a lot of JS code that generates mounds of HTML, including entire forms and content-heavy modal dialogs. In general, which method is considered best practice? In what circumstances should JavaScript be used to generate HTML and when should it not?

答:
We build single-page apps (ala Google Mail) and there is literally no server-side generation of HTML in our apps at all. Instead we're using Backbone.js to structure our client side and Handlebars to render our JSON into templates which go into the page. It works very well indeed and we're coming to the close of our first app which uses it and we'll tackle an even larger project in the future.

Any kind of fat client where the server is used only to persist data and return query results is a poster child for a time where you're going to want JavaScript to generate HTML. Just be sure to use a good template engine to make it clean and easy.

Title: When should JavaScript generate HTML?


答:
In addition to what Jan Hudec wrote I would like to mention Scala which,
beside a functional programming style, also supports an imperative /
object-oriented programming style.

Scala offers parallelism through actors (also used by Erlang).

Note that I don't think that using semaphores, lock mechanisms or other similar concurrency mechanism are good alternatives to Clojure 'automatic' parallelization.

Actors are an object-oriented way of abstracting from the underlying threads / processes: you basically only see objects running concurrently and sending messages to each other.
So, if you want an object-oriented way of implementing parallelism I would
also take a look at languages (or frameworks) supporting the actor model.

You can find some links on wikipedia, for Python there is e.g. Pykka.

Title: Using Clojure instead of Python for scalability (multi-core) reasons, good idea?

Body:
After reading http://clojure.org/rationale and other performance comparisons between Clojure and many languages, I started to think that, apart from ease of use, I shouldn't be coding in Python anymore, but in Clojure instead. Actually, I began to feel irresponsible for not learning Clojure, seeing it's benefits.

Does it make sense? Can't I make really efficient use of all cores using a more imperative language like Python, than a Lisp dialect or other functional language? It seems that all the benefits of it come from using immutable data, can't I do just that in Python and have all the benefits?

I once started to learn some Common Lisp, read and did almost all the exercises from a book I borrowed from my university library  (I found it to be pretty good, despite it's low popularity on Amazon). But, after a while, I found myself struggling too much to do some simple things. I think there's somethings that are more imperative in their nature, that makes it difficult to model those things in a functional way.

So is Python as powerful as Clojure for building applications that take advantage of this new multi-core future?

Note that I don't think that using semaphores, lock mechanisms or other similar concurrency mechanism are good alternatives to Clojure's 'automatic' parallelization.


问:
Visual Basic link to SQL output to Word
I am in need of some advice/references. I am currently trying to develop a legal document interface. There are certain fields in which I need to query out of my sql db and have those fields output into a document that can be printed. I am trying to develop a user interface where people can enter fields that will output to a document template but at the same time I need the template to be able to pull data from the SQL database. This is the reason why I think that VB might be my best choice and because it is one of the only OOP languages I am familiar with presently. Does anyone know that best way to be able to handle this type of job?

I know that you can use VBA within MS Word and have the form output variables to a word template. But, is there a way to have the word document also pull information from the SQL db? Is the best option to use VB linked to SQL and run queries to get the information from the database and then have it output to a for within VB? Is it possible for VB to be linked to a SQL db and output variables and SQL fields to a Word Template?

I have looked into Mail Merge and I see that it allows users to pull data from an Access query but I dont think it would be easy to automate and it seems that users would need to have an advanced knowledge of MS Word and Access to handle this. I am not finding much useful information online so I came here.

Any advice or references would be greatly appreciated. If there is a better way please let me know.

答:
Look into using MS Office Automation

You can automate the mail merge as well, Basically you can automate anything you can do in office.

All the objects used for creating office macros are accessible for use outside of office. So if you want to know how to do something via code, simple record a Macro then look at the code and translate it to your language of choice.

Title: Visual Basic link to SQL output to Word


答:
In addition to @Morons answer you could try a Macro to handle the more complicated bits of the Mail Merge automatically for your users so that they wouldn't need to know how to do anything except run the macro your create.  Look into Visual Basic for Applications for more information on macros.

VBA enables building user defined functions, automating processes and accessing Windows API...

Title: Visual Basic link to SQL output to Word

Body:
I am in need of some advice/references. I am currently trying to develop a legal document interface. There are certain fields in which I need to query out of my sql db and have those fields output into a document that can be printed. I am trying to develop a user interface where people can enter fields that will output to a document template but at the same time I need the template to be able to pull data from the SQL database. This is the reason why I think that VB might be my best choice and because it is one of the only OOP languages I am familiar with presently. Does anyone know that best way to be able to handle this type of job?

I know that you can use VBA within MS Word and have the form output variables to a word template. But, is there a way to have the word document also pull information from the SQL db? Is the best option to use VB linked to SQL and run queries to get the information from the database and then have it output to a for within VB? Is it possible for VB to be linked to a SQL db and output variables and SQL fields to a Word Template?

I have looked into Mail Merge and I see that it allows users to pull data from an Access query but I dont think it would be easy to automate and it seems that users would need to have an advanced knowledge of MS Word and Access to handle this. I am not finding much useful information online so I came here.

Any advice or references would be greatly appreciated. If there is a better way please let me know.


问:
What to do if a co-worker is editing your code just to change the appearance?
What should you do, if a co-worker is editing your code?

Without the purpose of adding functionality or fixing bugs, just to change how it looks...

答: Code conventions is the answer. You should have one at work. If you don't, start right now (a good starting point is google style guide) . When there are written (or at least commonly known) rules the answer to your question is trivial.

ContentLicense: CC BY-SA 2.5


问:
I can't program because the code I am using uses old coding styles. Is this normal to programmers?
I have my first real job as programmer, but I can't solve any problems because of the coding style used. The code here:

Does not have comments

Does not have functions (50, 100, 200, 300 or more lines executed in sequence)

Uses a lot of if statements with a lot of paths

Has variables that make no sense (eg.: cf_cfop, CF_Natop, lnom, r_procod)

Uses an old language (Visual FoxPro 8 from 2002), but there are new releases from 2007.

I feel like I have gone back to 1970. Is it normal for a programmer familiar with OOP, clean-code, design patterns, etc. to have trouble with coding in this old-fashion way?

EDIT: All the answers are very good. For my (un)hope, appears that there are a lot of this kind of code base around the world. A point mentioned to all answers is refactor the code. Yeah, I really like to do it. In my personal project, I always do this, but... I can't refactor the code. Programmers are only allowed to change the files in the task that they are designed for.

Every change in old code must be keep commented in the code (even with Subversion as version control), plus meta information (date, programmer, task) related to that change (this became a mess, there is code with 3 used lines and 50 old lines commented). I'm thinking that is not only a code problem, but a management of software development problem.

答:
I am going to make some comments that are different from many of the responders here. Many of my comments may be obvious to you, but need saying anyway.

Be cautious of changing code that you don't understand, until you understand it.

If you are working in a team environment, with code that your teammates work on, discuss your changes with them before making the changes. Nobody likes a "lone gunman" to come in and change code with which everyone else is familiar. This is not to say that your changes are not warranted or the "right" thing to do.

Gain adoptance for your ideas. Get everyone on board with your ideas, then you can use the skills of your team to refactor, instead of burdening yourself with the whole workload.

Gain management buy-in. They may be able to allocate funds for you to go and re-factor the code.

Speak to management in terms they understand about the benefits of re-factoring their code-base. More maintainable code means less time spent resolving bugs, adding features etc.  Which means cost-effective development. Faster turn-around time etc.

It's easy to add pure coding, best practice suggestions without understanding the politics of your environment. The people you work with may not want to change, or allocate the time to changing your code base, but try to sell the idea to everyone before jumping in and changing everything (which has inherent risks in and of itself)

Hope this helps.


问:
Do any database "styles" use discrete files for their tables?
I've been talking to some people at work who believe some versions of a database store their data in discrete tables. That is to say you might open up a folder and see one file for each table in the database then several other supporting files. They do not have a lot of experience with databases but I have only been working with them for a little over a half year so I am not a canonical source of info either.

I've been touting the benefits of SQL Server over Access (and before this, Access over Excel. Great strides have been made :) ). But, other people were of the impression that the/one of the the benefit(s) of using SQL Server over Access was that all the data was not consolidated down into one file. Yet, SQL Server packs everything into a single .mdf file (plus the log file).

My question is, is there an RDBMS which holds it's data in multiple discrete files instead of one master file? And if the answer is yes, why do it one way over the other?

edit

Thank you everyone for you're answers. This has really helped clarify the whole situation.

答: I can see no reason why you would want one file per table. In SQL server you can partition the files if you want for performance but typically you don't need to do that until you have many millions of records. </p>


问:
"Integratable" but not "integrated" GPL
There has been much debate over whether or not merely linking to a piece of code makes it a derivative work. I know FSF says "yes", so according to them I can't dynamically link a non-GPL compatible program to a GPL library and distribute the whole. But I could do that for private use, as long as no code is released to the public.

That made me wonder: what if I don't redistribute the GPL code at all? If my program can work alone (reinforcing my claim that it's not a derivative work), but can do more if the GPL library is also installed to the system, couldn't I just release my application under my own licensing terms - without including any GPL code - and post instructions for anyone interested to separately download the GPL code and do the integration "for their private use"?

I know it's against the "spirit" of the GPL, so I'm not suggesting it's a good idea to do that. However, this question is bugging me for some time, specially because of the implications of each answer:

If I can not do that:

can I write another library with a similar API? (before answering "of course you can", remember that having the same API would allow both libraries to be swapped at will by my customers - so I don't need to work too hard on my library or even make it "working". How to determine if a similar program is just similar or is a circumvention attempt?)

(Edit: as @Karl Bielefeldt pointed out, that library would be a derivative work, so this point is moot)

If I can do that:

can I also be paid to perform the service of installing the GPL library for a customer? (I sell them my program, install it in their machines, download and install the GPL library too)

(Edit: this practice would be evidence of my intent to combine both programs, reinforcing the claim that mine was conceived witht the goal of being combined - and thus is a derivative work)

can I put the two programs in the same website? In two different CDs? (I know I said the idea was not to redistribute the GPL code, I'm just thinking in excuses people could use to claim they're not redistributing even though they are)

(Edit: that would be an "aggregate", so no problem with it)

Update: having analyzed @Eli Rosencruft's and @Karl Bielefeldt's answers and links, and read some external resources, I'm getting closer to a conclusion. I made some edits to the question according to the feedback, and below I'll post a few of my findings so far:

The intrinsic qualities of both programs is a more determining factor when deciding whether or not one derives from another than the technological means to achive their integration. The intent of the authors of achieving some goal is also as relevant as the means they used to reach it (in this scenario). Quoting a blog post that - though not authoritative on the subject - I believe is relevant to the question (emphasis mine):

Since under the GPL the end-user can do whatever they want with the code (short of redistribution constraints), the end-user can always PULL various software on the Net and choose to combine and use them in any way they wish (assuming all parts are legits and legitimately obtained of course). (...) It does NOT mean that I can offer (PUSH) to the user a proprietary software that has been conceived with the goal/intent of being combined with a GPL software (whether it is deemed to be combined before or after distribution).

Whether legally significant or not, I now comprehend the motivation behind FSF's insistence on static vs dynamic linking: a non-free program that interfaces with a free one in complicated ways is de facto restricting the users' freedom over the latter, since they can't modify it substantially without breaking the integration (this also enables EEE, in case the free part is also modified to fit the non-free one). So, if one cares for the free software movement, s/he should comply to their terms or, at the very least, take the necessary measures to safeguard the receiver's freedoms.

答:
Is this a hypothetical question?  I'm only aware of one major open source library that uses the GPL instead of the LGPL, and that's mysql which also offers a commercial license to cover what you want to do.  I imagine most other GPL libraries would also offer commercial licenses, or else they would just make it LGPL.  If it's not a hypothetical question, it might be helpful to mention what library you're talking about.

I believe it's not enough that your program can work without the library.  The part of your program that uses the library must be severable and able to be distributed separately.  Take nvidia's kernel drivers as an example.  They distribute a binary library.  They also distribute an open source wrapper to that library that provides an interface between their library and the kernel headers.  To install it, you compile that wrapper.

The key here is that the kernel and their binary library can change completely independently of each other, and you just have to modify the wrapper to make it work.  Proof of this is that third parties have been able to distribute changes to that wrapper when the kernel interface changed and nvidia hadn't caught up yet in their official release.  Someone could also use that wrapper for other drivers, although to my knowledge no one has done so.

As for your other questions, writing another library with a nearly identical API is most definitely a derived work.  The GPL does not prohibit getting paid for installation or for aggregating a GPL work on a CD.

Title: "Integratable" but not "integrated" GPL


答:
First, verify that the library with which you wish to link your code really is GPL and not LGPL. As Karl Bielefeldt notes below, most of the common libraries are already either LGPL or dual licensed.

The FSF use of "derivative work" with regard to either static or dynamic linkage is problematic from a legal perspective. See "Example 3" and "Example 4" from University of Washington School of Law. Example 4, regarding plug-in technology is particularly illuminating.

But, if we assume the FSF interpretation of "derivative work" being defined by dynamic linkage, then any claim that a work is not derived when it in fact can be linked with a GPL work and such linkage provides additional features would be a specious claim.

On the other hand, who would bring action against you for this? I think that only the original copyright holders of the library against which you link could be party to an action, not your customers.

However, even reading against the GPL FAQ, and even assuming that there is no one to bring an action, do you really want to be here from a business perspective?

If your software really is going to be popular, then damage to your public image for even appearing to violate the GPL might not be worth the cost of developing your own proprietary library.

If your software will have only limited distribution and is pricey, then you should provide the software to your customers under a contract rather than a license. See Robert Pierce. Under the contract, you would provide the packaged product to the customer, along with the complete source code, as if you had developed the work for hire solely for that particular customer. You could stipulate that if the customer redistributes the product, he would do so at some agreed price from which he would pay you a percentage in royalties. It is likely that most of your customers aren't in the business of distributing or supporting software products, so this last clause would probably never be exercised. You could probably also stipulate conditions for securing the source code against disclosure risks, such as limiting access to the source code.

Title: "Integratable" but not "integrated" GPL

Body:
There has been much debate over whether or not merely linking to a piece of code makes it a derivative work. I know FSF says "yes", so according to them I can't dynamically link a non-GPL compatible program to a GPL library and distribute the whole. But I could do that for private use, as long as no code is released to the public.

That made me wonder: what if I don't redistribute the GPL code at all? If my program can work alone (reinforcing my claim that it's not a derivative work), but can do more if the GPL library is also installed to the system, couldn't I just release my application under my own licensing terms - without including any GPL code - and post instructions for anyone interested to separately download the GPL code and do the integration "for their private use"?

I know it's against the "spirit" of the GPL, so I'm not suggesting it's a good idea to do that. However, this question is bugging me for some time, specially because of the implications of each answer:

If I can not do that:

can I write another library with a similar API? (before answering "of course you can", remember that having the same API would allow both libraries to be swapped at will by my customers - so I don't need to work too hard on my library or even make it "working". How to determine if a similar program is just similar or is a circumvention attempt?)

(Edit: as @Karl Bielefeldt pointed out, that library would be a derivative work, so this point is moot)

If I can do that:

can I also be paid to perform the service of installing the GPL library for a customer? (I sell them my program, install it in their machines, download and install the GPL library too)

(Edit: this practice would be evidence of my intent to combine both programs, reinforcing the claim that mine was conceived witht the goal of being combined - and thus is a derivative work)

can I put the two programs in the same website? In two different CDs? (I know I said the idea was not to redistribute the GPL code, I'm just thinking in excuses people could use to claim they're not redistributing even though they are)

(Edit: that would be an "aggregate", so no problem with it)

Update: having analyzed @Eli Rosencruft's and @Karl Bielefeldt's answers and links, and read some external resources, I'm getting closer to a conclusion. I made some edits to the question according to the feedback, and below I'll post a few of my findings so far:

The intrinsic qualities of both programs is a more determining factor when deciding whether or not one derives from another than the technological means to achive their integration. The intent of the authors of achieving some goal is also as relevant as the means they used to reach it (in this scenario). Quoting a blog post that - though not authoritative on the subject - I believe is relevant to the question (emphasis mine):

Since under the GPL the end-user can do whatever they want with the code (short of redistribution constraints), the end-user can always PULL various software on the Net and choose to combine and use them in any way they wish (assuming all parts are legits and legitimately obtained of course). (...) It does NOT mean that I can offer (PUSH) to the user a proprietary software that has been conceived with the goal/intent of being combined with a GPL software (whether it is deemed to be combined before or after distribution).

Whether legally significant or not, I now comprehend the motivation behind FSF's insistence on static vs dynamic linking: a non-free program that interfaces with a free one in complicated ways is de facto restricting the users' freedom over the latter, since they can't modify it substantially without breaking the integration (this also enables EEE, in case the free part is also modified to fit the non-free one). So, if one cares for the free software movement, s/he should comply to their terms or, at the very least, take the necessary measures to safeguard the receiver's freedoms.


问:
How do I balance program CPU reverse compatibility whist still being able to use cutting edge features?
As I learn more about C and C++ I'm starting to wonder: How can a compiler use newer features of processors without limiting it just to people with, for example, Intel Core i7's?

Think about it: new processors come out every year with lots of new technologies. However you can't just only target them since a significant portion of the market will not upgrade to the latest and greatest processors for a long time.

I'm more or less wondering how this is handled in general by C and C++ devs and compilers. Do compilers make code similar to if SSE is supported, do this using it, else do that using the slower way or do developers have to implement their algorithm twice, or what?

More or less how do you release software that takes advantage of newer processor technologies while still keeping a low common denominator?

答:
"if SSE is supported, do this using it, else do that using the slower way": compilers could do this; e.g. x86 CPUs can report their capabilities via CPUID. Potentially, performing the check could slow down the code, so a compiler would have to ensure that the check is at least factored out of a loop, and perhaps do the check in advance and store the result in a variable (in case CPUID is slow). Another small problem is that the part of the unused version of the code will be brought into the cache (wasteful).

But MCVC does not do this; if you enable SSE2 it will emit SSE2 blindly, assuming the target processor supports it.

JIT compilers (.NET/Java) can easily support multiple architectures, since they only have to check the processor architecture once per function (or less) to decide how they will generate code. Obviously there's no need to generate multiple versions of the code in that case; the code can be tailored for the current CPU.


问:
How is the development of languages like Python and Perl funded?
The title pretty much gives you the gist of the question, but allow me elaborate a bit nevertheless. Apart from Google's involvement on Python, and Activestate's on Perl development (Strawberry AFAIK doesn't make any money on its own product) I'm interested in what are the major sources of funding of such.

Are there any texts that cover this? I tried searching, but found nothing apart from the "history of" and "it's opensource, everyone gives in" ...

答:
"It's opensource, everyone gives in" pretty much is the state of the funding for these languages.  (Aside from Google, of course.)  Your question seems to be based on the unspoken assumption that in order to develop the language, it has to be funded by someone with deep pockets, and this simply isn't true.

Development (of anything) doesn't require money, it requires time, effort and raw materials.  We've got an economy where money is commonly used to buy raw materials and motivate people to put time and effort into something, and the concept is so prevalent that so we tend to equate them, but they're separate and separable concepts.

People who contribute to an open-source programming language already have the raw materials (a computer, an Internet connection and basic development tools,) and usually have a different motivation for putting time and effort into it:  They don't do it for money, they do it because they're using the language and they want to help shape it into a better tool for whatever it is they're using it for.


问:
Strategies for avoiding SQL in your Controllers... or how many methods should I have in my Models?
So a situation I run into reasonably often is one where my models start to either:

Grow into monsters with tons and tons of methods

OR

Allow you to pass pieces of SQL to them, so that they are flexible enough to not require a million different methods

For example, say we have a "widget" model. We start with some basic methods:

get($id)

insert($record)

update($id, $record)

delete($id)

getList()  // get a list of Widgets

That's all fine and dandy, but then we need some reporting:

listCreatedBetween($start_date, $end_date)

listPurchasedBetween($start_date, $end_date)

listOfPending()

And then the reporting starts to get complex:

listPendingCreatedBetween($start_date, $end_date)

listForCustomer($customer_id)

listPendingCreatedBetweenForCustomer($customer_id, $start_date, $end_date)

You can see where this is growing... eventually we have so many specific query requirements that I either need to implement tons and tons of methods, or some sort of "query" object that I can pass to a single ->query(query $query) method...

... or just bite the bullet, and start doing something like this:

list = MyModel->query(" start_date > X AND end_date < Y AND pending = 1 AND customer_id = Z ")

There's a certain appeal to just having one method like that instead of 50 million other more specific methods... but it feels "wrong" sometimes to stuff a pile of what's basically SQL into the controller.

Is there a "right" way to handle situations like this? Does it seem acceptable to be stuffing queries like that into a generic ->query() method?

Are there better strategies?

答:
Your service layer interface may have many methods, but the call to the database can have just one.

A database has 4 major operations

Insert

Update

Delete

Query

Another optional method may be to execute some database operation that doesn't fall under the basic DB operations.  Let's call that Execute.

Insert and Updates can be combined into one operation, called Save.

Alot of your methods are query's.  So you can create a generic interface to satisfy most of the immediate needs.  Here's a sample generic interface:

```<code> public interface IDALService
    {
        DataTransferObject<T> Save<T>(DataTransferObject<T> Dto) where T : IPOCO;
        DataTransferObject<T> Search<T>(DataTransferObject<T> Dto) where T: IPOCO;
        DataTransferObject<T> Delete<T>(DataTransferObject<T> Dto) where T : IPOCO;
        DataTransferObject<T> Execute<T>(DataTransferObject<T> Dto) where T : IPOCO;
    }
</code>```

The data transfer object is generic and would have all your filters, parameters, sorting, etc. contained within it.  The data layer would be responsible for parsing and extracting this out and setting up the operation to the database via stored procedures, parameterized sql, linq etc.  So, SQL is not passed between layers.  This is typically what an ORM does, but you can roll your own and have your own mapping.

So, in your case you have Widgets.  Widgets would implement the IPOCO interface.

So, in your service layer model would have getList().

Would need a mapping layer to handle tranforming getList into

```<code>Search<Widget>(DataTransferObject<Widget> Dto)
</code>```

and vice versa.  As other have mentioned, sometime this is done via an ORM, but ultimately you end up with a lot of boilerplate type of code, especially if you have 100s of tables. The ORM magically creates parametized SQL and runs that against the database.  If rolling your own, additionally in the data layer itself, mappers would be needed to set up the SP, linq etc. (Basically the sql going to the database).

As mentioned earlier, the DTO is a object made up by composition.  Perhaps one of the objects contained within it is an object called QueryParameters.  These would be all the parameters for the query which would be set up and used by the query. Another object would be a List of returned objects from querys, updates, ext.  This is the payload.  If this case the payload would be a List of widgets List.

So, the basic strategy is:

Service Layer Calls

Transform Service Layer Call To Database using some sort of
Repository/Mapping

Database Call

In your case I think the model could have many methods, but optimally you want the database call to be generic.  You still end up with lots of boilerplate mapping code (especially with SPs) or magical ORM code that is dynamically creating the parametized SQL for you.

Body:
Your service layer interface may have many methods, but the call to the database can have just one.

A database has 4 major operations

Insert

Update

Delete

Query

Another optional method may be to execute some database operation that doesn't fall under the basic DB operations.  Let's call that Execute.

Insert and Updates can be combined into one operation, called Save.

Alot of your methods are query's.  So you can create a generic interface to satisfy most of the immediate needs.  Here's a sample generic interface:

 public interface IDALService
    {
        DataTransferObject<T> Save<T>(DataTransferObject<T> Dto) where T : IPOCO;
        DataTransferObject<T> Search<T>(DataTransferObject<T> Dto) where T: IPOCO;
        DataTransferObject<T> Delete<T>(DataTransferObject<T> Dto) where T : IPOCO;
        DataTransferObject<T> Execute<T>(DataTransferObject<T> Dto) where T : IPOCO;
    }

The data transfer object is generic and would have all your filters, parameters, sorting, etc. contained within it.  The data layer would be responsible for parsing and extracting this out and setting up the operation to the database via stored procedures, parameterized sql, linq etc.  So, SQL is not passed between layers.  This is typically what an ORM does, but you can roll your own and have your own mapping.

So, in your case you have Widgets.  Widgets would implement the IPOCO interface.

So, in your service layer model would have getList().

Would need a mapping layer to handle tranforming getList into

Search<Widget>(DataTransferObject<Widget> Dto)

and vice versa.  As other have mentioned, sometime this is done via an ORM, but ultimately you end up with a lot of boilerplate type of code, especially if you have 100s of tables. The ORM magically creates parametized SQL and runs that against the database.  If rolling your own, additionally in the data layer itself, mappers would be needed to set up the SP, linq etc. (Basically the sql going to the database).

As mentioned earlier, the DTO is a object made up by composition.  Perhaps one of the objects contained within it is an object called QueryParameters.  These would be all the parameters for the query which would be set up and used by the query. Another object would be a List of returned objects from querys, updates, ext.  This is the payload.  If this case the payload would be a List of widgets List.

So, the basic strategy is:

Service Layer Calls

Transform Service Layer Call To Database using some sort of
Repository/Mapping

Database Call

In your case I think the model could have many methods, but optimally you want the database call to be generic.  You still end up with lots of boilerplate mapping code (especially with SPs) or magical ORM code that is dynamically creating the parametized SQL for you.


答:
What you are describing is perfectly normal.

When we were doing usability studies, we would look at delays by order of magnitude. When a user clicks a button, how long do they have to wait?

0.1 sec: no perceived delay

1 sec: no change in focus

10 sec: attention lost

1 min: user switches to another task

10 min: user will get up and leave

There are plenty of exceptions, such as compound operations, like typing.

When we were doing performance work, we often asked the question "how fast should operation X be?" The answer is, as long as the user can perceive a delay, faster would be better.

In your case, you're hitting that 10s threshold, and your attention drifts away. The best thing you can do is reduce the delay. The shorter the delay, the greater your productivity. Imagine you had the code on the left side of your screen, and the running app on the right. As you edit the code, the app changes in real time. Until you're there, you have room to improve.

See also Jeff's recent blog post (the tons of good content it leads to): http://www.codinghorror.com/blog/2012/03/visualizing-code-to-fail-faster.html

If you are going to switch to something else, pick something that doesn't engage your brain in the same way as the work you were doing. Clean your desk, meditate, stretch, push-ups, art, look out the window.


答:
The thing about Office Automation on a server is that it's very heavy. I've found that working with third party tools that manipulate Word documents directly are the better route. For instance, I've successfully used SyncFusion's tools to create excel and word documents from a data-driven app. You want something that can work with word templates (that you can possibly store in the database) and can do something similar to mail-merge with your data. Funny thing, I've used this in a legal office application just as you are describing. The throughput of the syncfusion library puts office automation to shame and it produces very high quality documents.

Here is a link to samples of working with their library

Title: Visual Basic link to SQL output to Word


答:
When doing ad-hoc work in SAS, I find the following line very useful:

```<code>dm log 'postmessage "Code finished"' continue;
</code>```

This produces a pop-up dialogue box once all preceding code has finished executing. I'm sure there are equivalents in other languages. I would have posted this as a comment to retracile's answer but I don't have enough reputation.

Body:
When doing ad-hoc work in SAS, I find the following line very useful:

dm log 'postmessage "Code finished"' continue;

This produces a pop-up dialogue box once all preceding code has finished executing. I'm sure there are equivalents in other languages. I would have posted this as a comment to retracile's answer but I don't have enough reputation.


答:
I am going to strongly agree with funkymushroom's answer.  If you are a team environment make sure others know you are refactor or reorganizing code, if you ever plan to get any good future assignments.

From personal experience I know, while not your style of coding, if you are maintaining code, which other also modify and maintain, stay in the style of the existing code.  Adding comments and clarification is fine, but the basic layout and conventions should remain.  The old gurus/guns on the project expect the code to be similar to what they have been seeing for years.

When a customer is screaming about a bug, your management will go to the old guns to fix the problem as quick as possible.  If these old guns, when under pressure, find you “cleaned up the code” and so they now have to spend time figure out where you moved or renamed that one variable they know needs tweaking,  your name in the company will be changed to “mud”.

Once the crisis is over, first the old gun will blame you slowly down the critical update.  Next you will find that you get to keep maintain the cleaned up code for as long as you are at the company.  Finally, when new interesting projects become available, your managers will ask to the gurus on who should work the project, and if you have screwed them once, you will never make it to the new project, until your fodder being thrown in at the end to meet a deadline.

If you learned in college the “right” way to code, and you are now in the workforce, forget that “right” way.  These are not college assignment, these projects don’t last just a semester, they can live for years, and will have to be maintained by a group of people with different levels expertise and different levels of interest in the latest CS trend.  You have to be a team player.

You can be the biggest hot shot programming in school, but in the work place, your first job, you a newbie with zero street cred.   People who have been programming for years don’t give a hoot about your school or grades, it is how well do you play with others and how much disruption you bring to their lives.

In my 20 years, I have seem multiple ace programmers fired, mainly because they demand to do things their “right” way.    Unless you bring something very, very, very unique to the job, you are replaceable.  You may have been top of your class, but next year, someone else will be top of their class, and looking for a job.

I look at it as your primary job, is to keep your job, until you decide to change jobs.  To keep your job means you have to play nice in the playground someone else built and paid for.

I know I sound negative, but there is always hope.  As you gain experience, have success, you will gain influence, and be able to shift things to a better way.  When writing new code or on a new project, push for the changes you seek.  If it is new code, the old guns don’t expect it to be the way they left it, and when they see the advantages they might learn and adapt the new way.

Old system can change, but it takes time.  Changing something introduces risk, and business hate risk, and you have to take time and work to make the company comfortable with the change.

Title: I can't program because the code I am using uses old coding styles. Is this normal to programmers?

Body:
I have my first real job as programmer, but I can't solve any problems because of the coding style used. The code here:

Does not have comments

Does not have functions (50, 100, 200, 300 or more lines executed in sequence)

Uses a lot of if statements with a lot of paths

Has variables that make no sense (eg.: cf_cfop, CF_Natop, lnom, r_procod)

Uses an old language (Visual FoxPro 8 from 2002), but there are new releases from 2007.

I feel like I have gone back to 1970. Is it normal for a programmer familiar with OOP, clean-code, design patterns, etc. to have trouble with coding in this old-fashion way?

EDIT: All the answers are very good. For my (un)hope, appears that there are a lot of this kind of code base around the world. A point mentioned to all answers is refactor the code. Yeah, I really like to do it. In my personal project, I always do this, but... I can't refactor the code. Programmers are only allowed to change the files in the task that they are designed for.

Every change in old code must be keep commented in the code (even with Subversion as version control), plus meta information (date, programmer, task) related to that change (this became a mess, there is code with 3 used lines and 50 old lines commented). I'm thinking that is not only a code problem, but a management of software development problem.


问:
Weaknesses of 3-Strike Security
I've been reading some literature on security, specifically password security/encryption, and there's been one thing that I've been wondering: is the 3-strike rule a perfect solution to password security? That is, if the number of password attempts is limited to some small number, after which all authentication requests will not be honored, will that not protect users from intrusion? I realize gaining access or control over something doesn't always mean going through the authentication system, but doesn't this feature make dictionary/brute-force attacks obsolete? Is there something I'm missing? </p>

答:
Yes, it will make dictionary attacks impossible through the login mechanism.  (That doesn't mean much if they obtain access to the database, though.  For security there you'll need to properly hash and salt the passwords.)

It also allows the possibility of a DOS attack against a certain user.  Let's say I wanted to prevent you from logging in.  All I'd have to do is run three bogus login attempts against your account, and then do it again every time you do whatever's necessary to reset the login.  Dealing with that issue is a bit trickier.

Title: Weaknesses of 3-Strike Security


问:
Trying to wrap my head around class structure for domain-specific language
My work is mostly in embedded systems programming in C, and the proper class structure to pull this off eludes me. Currently we communicate via C# and Visual Basic with a large collection of servos, pumps, and sensors via a USB-to-CAN hid device.

Right now, it is quite cumbersome to communicate with the devices.
To read the firmware version of controller number 1 you would use:

```<code>SendCan(Controller,1,ReadFirmwareVersion) or
SendCan(8,1,71)
</code>```

This sends three bytes on the CAN bus: (8,1,71)

Connected to controllers are various sensors.

```<code>SendCan(Controller,1,PassThroughCommand,O2Sensor,2,ReadO2)
</code>```

would tell Controller number 1 to pass a command to O2 Sensor number 2 to read O2 by sending the bytes 8,1,200,16,2,0

I would like to develop a domain-specific language for this setup. Instead of commands issued like they are currently, commands would be written like this:

```<code>Controller1.SendCommand.O2Sensor2.ReadO2
</code>```

to send the bytes 8,1,200,16,0

What's the best way to do this? Some machines have 20 O2 Sensors, others have 5 controllers, so the numbers and types of controllers and sensors, pumps, etc. aren't static.

答:
Why not do something like this:

```<code>Controller.At(1).SendCommand().O2Sensor.At(2).ReadO2();
</code>```

That way you can accommodate for all of the controllers, all of the O2 sensors and it is still pretty clear.

Body:
Why not do something like this:

Controller.At(1).SendCommand().O2Sensor.At(2).ReadO2();

That way you can accommodate for all of the controllers, all of the O2 sensors and it is still pretty clear.


答:
There's a third approach.

Your specific example exhibits exponential growth in the number of methods needed as the number of required features grows: we want the ability to offer advanced queries, combining every query feature...if we do that by adding methods, we have one method for a basic query, two if we add one optional feature, four if we add two, eight if we add three, 2^n if we add n features.

That's obviously unmaintainable beyond three or four features, and there's a bad smell of a lot of closely related code that's almost copy-pasted between methods.

You could avoid that by adding a data object to hold the parameters, and have a single method that builds the query based on the set of parameters provided (or not provided). In that case, adding a new feature such as a date range is as simple as adding setters and getters for the date range to your data object, and then adding a bit of code where the parameterized query is built:

```<code>if (dataObject.getStartDate() != null) {
    query += " AND (date BETWEEN ? AND ?) "
}
</code>```

...and where the parameters are added to the query:

```<code>if (dataObject.getStartDate() != null) {
    preparedStatement.setTime(dataObject.getStartDate());
    preparedStatement.setTime(dataObject.getEndDate());
}
</code>```

This approach allows for linear code growth as features are added, without having to allow arbitrary, unparameterized queries.

Body:
There's a third approach.

Your specific example exhibits exponential growth in the number of methods needed as the number of required features grows: we want the ability to offer advanced queries, combining every query feature...if we do that by adding methods, we have one method for a basic query, two if we add one optional feature, four if we add two, eight if we add three, 2^n if we add n features.

That's obviously unmaintainable beyond three or four features, and there's a bad smell of a lot of closely related code that's almost copy-pasted between methods.

You could avoid that by adding a data object to hold the parameters, and have a single method that builds the query based on the set of parameters provided (or not provided). In that case, adding a new feature such as a date range is as simple as adding setters and getters for the date range to your data object, and then adding a bit of code where the parameterized query is built:

if (dataObject.getStartDate() != null) {
    query += " AND (date BETWEEN ? AND ?) "
}

...and where the parameters are added to the query:

if (dataObject.getStartDate() != null) {
    preparedStatement.setTime(dataObject.getStartDate());
    preparedStatement.setTime(dataObject.getEndDate());
}

This approach allows for linear code growth as features are added, without having to allow arbitrary, unparameterized queries.


答:
I would prefer to write

```<code>machine1.Controllers[1].O2Sensors[2].ReadO2();
</code>```

There is no need to have a SendCommand in there.

UPDATE

Here is my suggestion for a controller class

```<code>public class Controller
{
    private const int ReadFirmwareVersionCmd = 71;
    private const int PassThroughCommandCmd = 200;

    private int _controllerNumber;

    public Controller(int controllerNumber)
    {
        _controllerNumber = controllerNumber;
        O2Sensors = new List<O2Sensor>();
    }

    public List<O2Sensor> O2Sensors { get; private set; }

    private void SendControllerCommand(int controllerCommand)
    {
        Controller.SendCan(8, _controllerNumber, controllerCommand);
    }

    public void SendSensorCommand(int sensorType, int sensorNo, int sensorCommand)
    {
        Controller.SendCan(8, _controllerNumber, PassThroughCommandCmd, sensorType, sensorNo, sensorCommand);
    }

    private static void SendCan(int deviceType, int deviceNo, int commandNo)
    {
        // ...
    }

    private static void SendCan(int deviceType, int deviceNo, int commandNo,
                                int sensorType, int sensorNo, int sensorCommand)
    {
        // ...
    }

    public void ReadFirmwareVersion( )
    {
        SendControllerCommand(ReadFirmwareVersionCmd);
    }
}
</code>```

I would derive all the sensor types from a common base

```<code>public abstract class SensorBase
{
    protected Controller _controller;
    protected int _sensorNo;

    public SensorBase(Controller controller, int sensorNo)
    {
        _controller = controller;
        _sensorNo = sensorNo;
    }

    public abstract void Read();
}
</code>```

An O2-sensor as an example for a sensor

```<code>public class O2Sensor : SensorBase
{
    public O2Sensor(Controller controller, int sensorNo)
        : base(controller, sensorNo)
    {
    }

    public override void Read()
    {
        _controller.SendSensorCommand(16, _sensorNo, 0);
    }
}
</code>```

You can initialize a controller like this

```<code>var controller1 = new Controller(1);
controller1.O2Sensors.Add(new O2Sensor(controller1, 1));
controller1.O2Sensors.Add(new O2Sensor(controller1, 2));
</code>```

Now you can read information like this

```<code>controller1.ReadFirmwareVersion();
controller1.O2Sensors[1].Read();
</code>```

Title: Trying to wrap my head around class structure for domain-specific language

Body:
My work is mostly in embedded systems programming in C, and the proper class structure to pull this off eludes me. Currently we communicate via C# and Visual Basic with a large collection of servos, pumps, and sensors via a USB-to-CAN hid device.

Right now, it is quite cumbersome to communicate with the devices.
To read the firmware version of controller number 1 you would use:

```<code>SendCan(Controller,1,ReadFirmwareVersion) or
SendCan(8,1,71)
</code>```

This sends three bytes on the CAN bus: (8,1,71)

Connected to controllers are various sensors.

```<code>SendCan(Controller,1,PassThroughCommand,O2Sensor,2,ReadO2)
</code>```

would tell Controller number 1 to pass a command to O2 Sensor number 2 to read O2 by sending the bytes 8,1,200,16,2,0

I would like to develop a domain-specific language for this setup. Instead of commands issued like they are currently, commands would be written like this:

```<code>Controller1.SendCommand.O2Sensor2.ReadO2
</code>```

to send the bytes 8,1,200,16,0

What's the best way to do this? Some machines have 20 O2 Sensors, others have 5 controllers, so the numbers and types of controllers and sensors, pumps, etc. aren't static.

Body:
I would prefer to write

machine1.Controllers[1].O2Sensors[2].ReadO2();

There is no need to have a SendCommand in there.

UPDATE

Here is my suggestion for a controller class

public class Controller
{
    private const int ReadFirmwareVersionCmd = 71;
    private const int PassThroughCommandCmd = 200;

    private int _controllerNumber;

    public Controller(int controllerNumber)
    {
        _controllerNumber = controllerNumber;
        O2Sensors = new List<O2Sensor>();
    }

    public List<O2Sensor> O2Sensors { get; private set; }

    private void SendControllerCommand(int controllerCommand)
    {
        Controller.SendCan(8, _controllerNumber, controllerCommand);
    }

    public void SendSensorCommand(int sensorType, int sensorNo, int sensorCommand)
    {
        Controller.SendCan(8, _controllerNumber, PassThroughCommandCmd, sensorType, sensorNo, sensorCommand);
    }

    private static void SendCan(int deviceType, int deviceNo, int commandNo)
    {
        // ...
    }

    private static void SendCan(int deviceType, int deviceNo, int commandNo,
                                int sensorType, int sensorNo, int sensorCommand)
    {
        // ...
    }

    public void ReadFirmwareVersion( )
    {
        SendControllerCommand(ReadFirmwareVersionCmd);
    }
}

I would derive all the sensor types from a common base

public abstract class SensorBase
{
    protected Controller _controller;
    protected int _sensorNo;

    public SensorBase(Controller controller, int sensorNo)
    {
        _controller = controller;
        _sensorNo = sensorNo;
    }

    public abstract void Read();
}

An O2-sensor as an example for a sensor

public class O2Sensor : SensorBase
{
    public O2Sensor(Controller controller, int sensorNo)
        : base(controller, sensorNo)
    {
    }

    public override void Read()
    {
        _controller.SendSensorCommand(16, _sensorNo, 0);
    }
}

You can initialize a controller like this

var controller1 = new Controller(1);
controller1.O2Sensors.Add(new O2Sensor(controller1, 1));
controller1.O2Sensors.Add(new O2Sensor(controller1, 2));

Now you can read information like this

controller1.ReadFirmwareVersion();
controller1.O2Sensors[1].Read();


答:
That's still too verbose for my taste, because of the lack of encapsulation.  I don't know much about your topology, or the overlap of commands between sensors, but my first choice for an API for your examples would simply be:

```<code>ReadFirmwareVersion(1);
ReadO2(1, 2);
</code>```

If you needed it to be more object-oriented, and not have to pass around the controller and device addresses all the time, I would make it look something like this:

```<code>controller = new Controller(1);
controller.readFirmwareVersion();
o2Sensor = new O2Sensor(controller, 2);
o2Sensor.readO2();
</code>```

No need for a DSL here.  You should be able to simplify the API within the confines of your existing language.

Body:
That's still too verbose for my taste, because of the lack of encapsulation.  I don't know much about your topology, or the overlap of commands between sensors, but my first choice for an API for your examples would simply be:

ReadFirmwareVersion(1);
ReadO2(1, 2);

If you needed it to be more object-oriented, and not have to pass around the controller and device addresses all the time, I would make it look something like this:

controller = new Controller(1);
controller.readFirmwareVersion();
o2Sensor = new O2Sensor(controller, 2);
o2Sensor.readO2();

No need for a DSL here.  You should be able to simplify the API within the confines of your existing language.


问:
How were some language communities (eg, Ruby and Python) able to prevent fragmentation while others (eg, Lisp or ML) were not?
The term "Lisp" (or "Lisp-like") is an umbrella for lots of different languages, such as Common Lisp, Scheme, and Arc. There is similar fragmentation in other language communities, like in ML.

However, Ruby and Python have both managed to avoid this fate, where innovation occurred more on the implementation (like PyPy or YARV) instead of making changes to the language itself.

Did the Ruby and Python communities do something special to prevent language fragmentation?

答:
I would say one factor is a defining platform. For Haskell the platform is the Haskell standard and the GHC (I would imagine). For Ruby it was Ruby on Rails that "defined" the Ruby development platform. For C it was Unix.

Compare that to Lisp, where there was no original kick-ass platform that defined what the language was like. If I recall correctly each Lisp machine had slight differences depending on model and manufacturer. Common Lisp was for some reason not defining. Possibly because of too much competition and reluctance to move to another platform.

This is, of course, entirely speculation from my side. The thought came from the comment replies on Harvey's answer. However, it seems that the defining platform comes in many shapes, but the common property seems to be that it is what gains popularity from.


答:
I also agree that it makes dictionary attacks less effective as ways to gain access to an account without the proper authority. However:

This approach could turn a dictionary attack into a DOS attack against the system preventing access if implemented poorly.  For example, a server could be flooded with authentication attempts.  One way around this is to have the authenticating service control the flow of subsequent accesses to a locked-out account.  For example, if an account is locked out, present a delay before each subsequent login attempt.  One could put a delay between a login attempt and an `access denied', however, that keeps the door open to a distributed denial of service attack where an attacker launches many simultaneous authentication attempts.

As was mentioned in the other answer, this could also turn a dictionary attack into a crude DOS against the legitimate owner of the account being attacked.  Ways to mitigate the impact to the legitimate owner include:

Slowing down a run on usernames by providing no clues on whether it's the username or the password that is wrong.  This makes attacks where the culprit is guessing usernames more visible to administrators and less effective.

Instead of locking down an account after a fixed number of failed attempts, merely lock out that mode of authentication.  In other words, require a user who's account is being attacked to authenticate using a different (possibly more involved, but less easily attacked) method.  A good example is how an Android phone will require a user to use their Google Login information after failing to authenticate using a screen unlock pattern or PIN.  In theory, this is sort of like requiring an attacked user to ask for their account to be unlocked, however, it requires no immediate intervention from a system administrator.

Instead of locking down an account (or in addition to locking down an account, for this particular mode of authentication--see above) lock down attempts to authenticate from the location where the attack is originating.  For example, if the authentication is done  via a username and password, over the network, after three failed authentication attempts you could prevent further attempts from users from the same IP or subnet from logging in with a username or password.  Where there is a good chance that multiple users (including the attacker) could be using the same IP or subnet, you could merely disable username/password authentication for the IP or subnet for a period of time, leaving more involved authentication methods open for innocent users in proximity to the attacker.

If your fear is inadvertently penalizing a forgetful user as if they were an attacker, instead of controlling the flow of failed login attempts after a fixed number of failed attempts, you could use the frequency of login attempts as evidence an account is being attacked.  For example, if you see 10 authentication attempts within the span of a second, you could either use one of the methods above to prevent further similar authentication attempts.  Alternately, you could use this rapid flood of login attempts as a signal to start controlling the flow.  This method is becoming more and more popular on forums, whereas, after a certain amount of failed login attempts from a particular IP, that IP is prevented from authenticating for a short period of time.

Finally, a good way of preventing a user from being repeatedly targeted by a DOS attack is by allowing him/her to reset both his/her password and username.  In other words, treat both the username and password as secrets.  Where the username is used elsewhere (e.g. in a forum, if the username is the user's display name), simply treat this display name as something separate.  This approach is usually used by social networks where the username used in authentication is one's email address--something that can be changed, but is seldom shared--while the display name used on the site is something user-defined that may or may not be changed.

Anyway, I hope one or some combination of these approaches will come in handy.

Title: Weaknesses of 3-Strike Security

Body: I've been reading some literature on security, specifically password security/encryption, and there's been one thing that I've been wondering: is the 3-strike rule a perfect solution to password security? That is, if the number of password attempts is limited to some small number, after which all authentication requests will not be honored, will that not protect users from intrusion? I realize gaining access or control over something doesn't always mean going through the authentication system, but doesn't this feature make dictionary/brute-force attacks obsolete? Is there something I'm missing? </p>