问:
When would someone be considered a bad programmer?
How would you consider that a programmer is bad at what he or she is doing?

If possible... How should he/she improve?

答:
One thing that distinguishes a bad programmer from a newbie programmers is stubborn insistence on implementing their favorite system in whatever language and API they are working in.

I once inherited a system where the prior developer re-implemented (in Java) a large set of the Ashton Tate DBase III+ api layered on top of custom dbf access library. None of the Java collections framework was used.

This was so he could write a Java/swing app that looked and acted like a DBase III+ (or possibly clipper) app.

The Apps he wrote in this system had lite-bar menus and would open a full window form with a row of buttons on the bottom when you navigated the lite-bar to the option. It was like a little time machine back to the 1980s.

The man was clearly a skilled developer. He knew enough that he was able to write that whole system himself in the time frame of that project. He was also able to re-use it on a few other internal systems.

But he was an awful programmer in that his code misused the features of the systems he worked on. He was more willing to spend 3 months on a custom lib of dubious benefit than learn Java/Swing/SQL.


问:
PowerShell guide or reference for .Net Framework?
I'm a java dev that is new to powershell.  I know that it's built on the .Net Framework, but I don't have much knowledge with that framework.

Is there a reference guide of some sort that shows what libraries are available in Powershell?  I found a list of Powershell 2.0 commands, but I'm pretty lost as to what library to use or what is available from the underlying framework.

答:
You can load any CLR assembly in powershell. One option is to use parts of reflection to load assemblies, such as [Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'). Powershell 2 added the Add-Type commandlet.

Once you have the assembly loaded, you can use New-Object to create instances of classes.

ContentLicense: CC BY-SA 3.0


问:
Staging environment vs Production environment
I work for a company where we build enterprise applications, and we maintain three environments: development (or dev), staging (or stage) and production (or prod).

The meaning of dev is intuitive: it's the environment used during development of the application.

What's the difference between staging and production environments?

答:
For smaller companies (it's not clear how big yours is), three environments (dev, stage, production) are common. Larger companies will often have a QA environment between dev and stage.

These normally break down as follows:

dev: Working code copy. Changes made by developers are deployed here so integration and features can be tested. This environment is rapidly updated and contains the most recent version of the application.

qa: (Not all companies will have this). Environment for quality assurance; this provides a less frequently changed version of the application which testers can perform checks against. This allows reporting on a common revision so developers know whether particular issues found by testers has already been corrected in the development code.

staging: This is the release candidate, and this environment is normally a mirror of the production environment. The staging area contains the "next" version of the application and is used for final stress testing and client/manager approvals before going live.

production: This is the currently released version of the application, accessible to the client/end users. This version preferably does not change except for during scheduled releases.


问:
Bachelor degree in Software engineering in distance (online) in Europe
Currently I wish to expand my professional skills with Bachelor degree. However, I am not able to study full time abroad, but looking for University where I could study in distance (online from home), coming just several times in a semester to the University to pass exams, complete papers and so on.

I am looking for Software Engineering or Computer Science programs. Fully in distance (online) in English in Europe, because I am living in Central Europe.

Any suggestions?

答: I know that it isn't in Europe but the FAQ page of University of Phoenix states that they accept International students for the Online campus which I guess means that there is no physical attendance requirements.</p>


问:
Why not use the word bug instead of exception?
If we refer to exceptions as bugs, why not just call it a bug in the first place instead of an exception?

If in the code it's called exception and as soon as it occurs it's called a bug. Then why not call it a bug in the first place?

Thank you for any answer or comment.

答:
Plain and simple, an exception is not (always) a bug!

An exception is thrown (or should be) when something exceptional happens. If there is a problem with my hard drive and a file cannot be written, that is not a bug. That is a failure of the hardware.

A bug is generally a result of bad programming. If an application does something that is not expected as a result of a programming error, that is a bug.


答:
Well, it's pretty simple: not all exceptions are bugs (and similarly, not all bugs manifest themselves as exceptions).

As example of an exception that's not a bug, if you're reading a file from a USB drive and someone yanks the drive out of the socket. That's going to raise an exception (in most languages that support exceptions, that is). But it's not a bug in the code.

Conversely, a bug might manifest itself as a calculation error or something. You still get an answer, it's just not the right one.

Having said that, an exception that makes its way all the way to the top of the stack likely is a bug. In my USB example above, you should be able to catch that exception and present a nice error to the user saying "We couldn't read from the file because it's no longer connected." or something. If you just present them with an IOException and some funky error code, then that's a bug. But the exception itself is not.

Title: Why not use the word bug instead of exception?

Body:
If we refer to exceptions as bugs, why not just call it a bug in the first place instead of an exception?

If in the code it's called exception and as soon as it occurs it's called a bug. Then why not call it a bug in the first place?

Thank you for any answer or comment.


答:
Exceptions are not always bug related. Think of it as something that could go wrong with what you are doing.

An example that comes to mind is InetAddress.getByName() which is used to resolve a domain name.  If something happens and an UnknownHostException is thrown its not really a code issue.


答: Exceptions and bugs are not at all related. Sure, sometimes you throw an exception and it means a bug. But sometimes it just means an exceptional, unusual circumstance, which is not necessarily a bug in the program at all. Especially in an exception-happy language like Java, where every standard operation and it's dog throws about five different exceptions- for example, opening file failed, reading file failed, etc.</p>


问:
I keep failing hands on part of the interview, suggestions?
So I have a couple of software/site in my portfolio. They make money but not a whole lot.

So I decided to get some job experience, mainly applying to Java/PHP junior development positions.

The problem is that I answer all the technical questions correctly and we schedule to do a coding "test", the final phase of the interview. I can never relax and over think things and end up doing the test very slowly. OR sometimes I just hit a block and find it very difficult to think on my feet.

I don't understand this because other stuff I had written were solving far more complex problems while the "Test" is actually brutally simple such as writing and testing palindrome.

Other times, they will give me a logic test with flows to math operations and again I won't be able to do it in the time they assign.

I know I can write sellable software/websites that can generate small revenues and find ways to solve problems but I have great difficulty with simple coding tests in interviews.

Any suggestions?

答:
It is quite common for software developers to flunk when asked to sit a coding test or to write a small piece of code on the interview. As someone has already mentioned, that is because most of us can only code when we are in our "comfort zone" and sitting in a small room, surrounded by 2-5 interviewers does not really add much of the comfort.

The answer is threefold:

practice, and practice more. try for a month do 30-40 minutes of programming with a paper and pen and you'll be surprised how easy it would become. While practising - try the sort of the programming tasks what you expect to be asked for on interview coding sessions - e.g. implement a singleton, reverse a string, etc. It is even easier with "read that piece of junk code and find what is wrong" - try printing and them analysing these printouts for a two weeks and you'll greatly improve that skill.

learn how to control your fear. if you think that the test is too hard and you can only complete 20% of it - do that 20%, don't worry about the rest. It could be that the test is unreasonably big for the time given to do it (e.g. guys on interview supposed to give you 20 minutes to finish it but they need to wrap up the interview in 5 minutes because of some production blow up, etc). It is also possible that other candidates have only managed to completed 10% test, so by having completed 20% you will still be ahead of other candidates.

When writing a code on interview - don't bother making it perfect in a first pass. just implement a "happy path aka most common scenario first" and bother with error handling later. if you are runnning out of time - just add a quick note on the bottom of the sheet outlining - what you would have done to improve the code if you had more time.

[gotta run, will edit/improve my answer later]


答:
A software bug is the common term used to describe an error, flaw, mistake, failure, or fault in a computer program or system that produces an incorrect or unexpected result, or causes it to behave in unintended ways. Might even be a spelling mistake on a label.

Exceptions are different to bugs. Each kind of exception (access violation, stack overflow, and so on) can be raised to a debugger as either a "first chance" or "second chance" exception. First chance exceptions are, by definition, non-fatal unless they are not handled properly with an error handler, at which point they are raised again as a second chance exception (which only a debugger can handle).

If no debugger handles a second chance exception, the application is shut down.


问:
Should I open up to .net, c# and visual basic?
I am a huge linux fan and have been ignoring .net, C#, and visual basic due to their relationship with Microsoft. Am I foredooming them just for their relationship?

Is there any advantage to learning them, when you are mainly a linux user?

答:
Having a familiarity with C# can't hurt you. Exposure with other technologies will allow you to make better decisions in the future about what you are good at and what tool is best suited for the job. If you decide they are not for you, that is fine if you are making an educated decision.

As an aside, if you know Java, then you will have a good feel for the basics of C#. Though, there are things that have been added in .Net 3.0/4.0 that will be different like LINQ and lambda expression that set it apart.


答:
They are fully deployable to Linux environments using the Mono framework which is not controlled by Microsoft. I'd say ignoring them because you like Linux would be a mistake. If you don't like the languages for other reasons like syntax or memory overhead or whatever, then fine but I'd not write them off because they are based on work done at Microsoft and partially supported by Microsoft.

As far as advantages to use, they have a rich ecosystem behind them even through Mono so it all just depends on what you want to do. I mean if all you do is web apps then RoR or PoD would probably suit you fine. If you want to dabble with an enterprise level language that lets you use functional programming and let's you combine freely with an even more functional language that integrates fully with it then Mono becomes an interesting alternative to the JVM or doing a C++ hydra. .NET and Mono were designed to use the Common Language Interface which was designed from the beginning with language inter-operation in mind. The JVM might have an edge in terms of running all over the place (even Smart Cards) but it's interoperability has been less "designed-in". Mostly it's going to be a matter of taste or enforced use.

Title: Should I open up to .net, c# and visual basic?

Body:
I am a huge linux fan and have been ignoring .net, C#, and visual basic due to their relationship with Microsoft. Am I foredooming them just for their relationship?

Is there any advantage to learning them, when you are mainly a linux user?


答:
I'm quite surprised that nobody has asked this yet, but how are you approaching the programming tasks?

If you're simply jumping into code, then chances are you're going to get yourself lost and end up making simple mistakes and getting yourself flustered. Take it one step at a time:

Gather requirements: What is it, exactly, that your interviewer is asking. Make sure that there are zero questions up in the air prior to coding. For example, if confronted with the age old "isPalindrome" question, ask things like "what if the string has special characters?" or "do odd length strings such as 'ada' count as palindromes?". You need to know how to clarify requirements before designing an algorithm.

Design your algorithm: Break it up into logical sections if it makes sense to. Talk about it.. Maybe write some pseudocode if you're whiteboarding. Walk your interviewer through your steps. Try running through it with a few different inputs (both valid and invalid) to ensure you get the desired results.

Now start coding: By this point, you should be very confident in what you're about to write. Essentially, you should just be going through the motions with whatever language you're familiar with. At this point, it doesn't really matter if there are syntactical errors as interviewers worth a dime will forgive those in a whiteboarding session (if you're given a PC/IDE to solve the problem on, that's a different story).

Really, when tackling coding problems, an interviewer isn't looking so much for great code.. It's more to see how you go about tackling a given problem. Diving straight into code is a bad thing, period.

You'll also find that as you're talking about the problem (requirements gathering and design), you'll get a little more comfortable and are less likely to make silly mistakes during the coding portion.

Title: I keep failing hands on part of the interview, suggestions?

Body:
So I have a couple of software/site in my portfolio. They make money but not a whole lot.

So I decided to get some job experience, mainly applying to Java/PHP junior development positions.

The problem is that I answer all the technical questions correctly and we schedule to do a coding "test", the final phase of the interview. I can never relax and over think things and end up doing the test very slowly. OR sometimes I just hit a block and find it very difficult to think on my feet.

I don't understand this because other stuff I had written were solving far more complex problems while the "Test" is actually brutally simple such as writing and testing palindrome.

Other times, they will give me a logic test with flows to math operations and again I won't be able to do it in the time they assign.

I know I can write sellable software/websites that can generate small revenues and find ways to solve problems but I have great difficulty with simple coding tests in interviews.

Any suggestions?


问:
How to manage IDE project files on a forked repository
I recently forked a Git repository, and locally I created a project in my IDE to compile with.

My IDE creates a variety of artifacts that I would like to keep saved somewhere. The obvious place would be in the VCS. If I add these files then they will be in the history for my fork. If i want send a pull request to merge upstream I wouldn't want these files included.

What would be a recommended workflow for managing these changes that I would never want to go upstream.

答:
Structure your project so that it sits in a directory (and builds all files) outside of the source directory (such as [project root]/build) and exclude that directory in .gitignore.

This is the process that CMake uses (see "out-of-source builds" in their docs). Of course, you could always introduce yourself to CMake and build it into the project's pipeline. I'm sure the authors would love you for it ;)


问:
Organising MVC App with virtual model using external API
I am creating a rails app with following constraints

It has no database

It uses a web API to store and retrieve the data

The connection to the web API is via a custom gem.

The Gem has a basic functionality to make a web API call based on the parameters given.

I have 2-3 different kinds of object that I can think of  ( or may be more precisely virtual model )

How should the structure of my program be ?

Should I incorporate all the method calls within the gem ?

Should I create models and put the api related calls  in there (then through the gem's basic method)

Should I just ignore the model and put everything in the controller . ?

The second method seems most appropriate , but then all the methods from model would be static and I would be calling all methods in essence without any objects.

答:
My gut tells me that you're correct to want to put some code into the Model. The fact of the matter is that while those are the functional/nonfunctional requirements on your application today - that could change. You could be required to implement a database on the next iteration of this project, or even worse the entire way you're storing data could get overhauled.

The fact of the matter is stuff changes. The better you modularize and abstract your code, the quicker you'll be able to adapt to change down the road. You'll also set yourself up for easier unit and integration testing, too. That's an important factor, because detecting problems before they become problems saves time and reputation.


答:
Yes. Learn them.

Languages are to programmers as hammers are to carpenters.

The overwhelming majority of my professional experience has been LAMP dev, yet my degree focuses on VB.NET - half because I figured if I'm paying for it anyway, I might as well learn something new, and half because the alternative was Java. ;)

Learning these languages for me was like learning to run backwards. It changed the way I conceptualize programmatic problems (and programmatic solutions): context, abstraction, patterns. At the very least, skills (even ones you rarely use) always confer the value of experience gained from adding them.

HTH :)


答:
There are a few reasons you may want to learn .NET:

C# is a great language.

C# is actively maintained. More actively than Java. It has some pretty features, which help a lot to be productive.

There are other languages which you may learn by curiosity, like F#.

There are also frameworks (Windows Workflow for example) or external libraries (Reactive Extensions for example) which have interesting approaches. If you're curious, just see what are they about and try to extract from them something you can use in your more familiar environment, programming languages, etc.

but also a few reasons to not learning it in your case:

There are already languages heavily used by Linux developers. The issues with those languages are known, documented and probably solved. Even with Mono, .NET languages are not very used on Linux platform, so be ready to encounter soon or later problems nobody else encountered before (or encountered, but never solved or documented).

If you're searching for a job as a PHP LAMP developer for example, I'm pretty sure the companies would simply ignore your experience in C#. It's one of the most stupid things to do when hiring a developer, but, alas, one of the most frequent as well.

I suppose you will not use Windows. This means that you will not use Visual Studio. Using the latest and the greatest version of Visual Studio is a large advantage: not only you are using a very well done IDE, but you also have an easy access to a huge amount of tools which make you more productive: code contracts, static code analysis, code metrics, etc. Missing all this makes C# a bit more "just another programming language".

I suppose there are slight differences between C# code running on Windows and a similar code running on Mono. If so, practically every piece of code available on the internet is targeting Windows, so it will hurt your productivity to constantly find that the code you find don't work on your machine.


问:
How does Ruby, Python, PHP manage without Spring?
I write enterprise Java applications and web services at work (Spring, Hibernate, Maven, RESTEasy) and PHP (CakePHP) and Python (Django) for my side projects.

While I do see the value that Inversion of Control, Aspect Oriented Programming etc. that Spring brings in, I am not sure how massive web applications that are not on the Java stack manage without a framework like Spring.

So, do the developers just have to "put up with" tightly coupled components and other grievances that Spring eliminates or am I missing something?

For those unfamiliar with Spring, the features we use the most are:

Inversion of Control container: configuration of application components and lifecycle
management of Java objects,

Aspect-oriented programming: enables implementation of cross-cutting routines,

Transaction management: unifies several transaction management APIs and coordinates transactions for Java objects.

答:
In most high level languages it's trivial to write using AOP and/or IoC design principles.

All you need to implement AOP is for the language to support higher order functions.  For example:

```<code>def log(fn):
  def wrapped_fn(*a, **kw):
    logger.log(fn_formatter(fn, a, kw))
    return fn(*a, **kw)
  return wrapped_fn

@log
def do_something(my_friend):
  return have_fun_with(my_friend)
</code>```

You can also follow general IoC or Dependency Injection principles when programming.  You don't need a particular container to provide that capability.  You can just write the code that way.

```<code>def etl(iextract, transformations, iload):
  return iload(itertools.imap(compose(*transformations), iextract()))
</code>```

Body:
In most high level languages it's trivial to write using AOP and/or IoC design principles.

All you need to implement AOP is for the language to support higher order functions.  For example:

def log(fn):
  def wrapped_fn(*a, **kw):
    logger.log(fn_formatter(fn, a, kw))
    return fn(*a, **kw)
  return wrapped_fn

@log
def do_something(my_friend):
  return have_fun_with(my_friend)

You can also follow general IoC or Dependency Injection principles when programming.  You don't need a particular container to provide that capability.  You can just write the code that way.

def etl(iextract, transformations, iload):
  return iload(itertools.imap(compose(*transformations), iextract()))


答:
A good book for learning PowerShell is Windows PowerShell in Action, published by Manning.

As for the .Net framework, MSDN is a good source of info. If you search around on MSDN, you should be able to find the Visual Studio help files download, which is basically the same as the online version.

Title: PowerShell guide or reference for .Net Framework?

Body:
I'm a java dev that is new to powershell.  I know that it's built on the .Net Framework, but I don't have much knowledge with that framework.

Is there a reference guide of some sort that shows what libraries are available in Powershell?  I found a list of Powershell 2.0 commands, but I'm pretty lost as to what library to use or what is available from the underlying framework.


问:
Does it make sense to license unit tests?
I am wondering if there are any benefits / risks of (not) putting a licence on test code which mostly consists of unit tests. What do you think?

I am particularly interested in licensing under (L)GPL, Apache, MIT and BSD.

EDIT: The assumption is that non-test code is already published under some licence, but test code is not, so the question is whether to publish it and if so whether to put the same licence on it.

答:
In commercial world, most companies charge not only for the core product but also for the support. Most often support involves any form of help by means of tool or personal assistance, to be able to make the product usable or resolve any issues related to product.

By this token, code for testing the product equally qualifies a support tool and is an intellectual property in its own right. So it does deserve a license of it's own.

OwnerDisplayName: leden


答:
IANAL, however:

If you are licensing your code under GPL, then de facto your unit tests are also GPL as they're pretty useless without the main code

If you're using Apache/BSD, the 'USE AT YOUR OWN RISK' provision. I'd slap a license file with the whole project and let the user figure out if it's for the code or the test code.

If you use a commercial license and limit access to the code, why would you publish your tests in the first place? If you want to be sure, put a 'BY READING THE TEST CODE, YOU HEREBY AGREE TO GOUGE YOUR EYES' license and you're good to go.

Title: Does it make sense to license unit tests?

Body:
I am wondering if there are any benefits / risks of (not) putting a licence on test code which mostly consists of unit tests. What do you think?

I am particularly interested in licensing under (L)GPL, Apache, MIT and BSD.

EDIT: The assumption is that non-test code is already published under some licence, but test code is not, so the question is whether to publish it and if so whether to put the same licence on it.


答:
The test code has a lot of value, since it allows the user to check if your solution works in a given environnement. In my job (embedded software) the test suite is part of the contract. You should publish it with the same licence, because usage is similar:

if someone just uses your code, then he will run the tests

if someone wants to modify the code, he will probably have to modify some tests as well


问:
What could be some pitfalls in introducing a style guide and documentation generating software in a development team?
I'm considering using appledoc, a flavor of Doxygen for use in generating Objective-C code documentation, in order to create documentation for my company's iOS apps. The idea is that a server will generate the docs on a post-commit hook, then publish the documentation on an internal network.

Right now we have very little documentation of any kind, even comments in the code itself, so I'm expecting I will have to ask people to begin writing more documentation as they code. In this vein, I will also collaborate with my team in order to create a "style guide" for Objective-C code (like Google's), which will lay down some ground rules on how to write and document code.

What are some potential pitfalls in the above plan? Are style guides effective? I see the benefits in adopting a coding standard, but will developers find it restrictive? And do documentation projects such as this one work? And if not, why do they fail?

(I've posted on Stack Overflow a few times with moderate success, but this is my first time posting here. Please let me know if I could improve my question in any way. Thanks!)

答:
Elements to take care from process and cultural point of view:

1. Ensure that expectations are well set for what should be the content in documentation
It is important to define what is expected to be written when documentation is done. Many a times it is surprising but people make internal assumptions.
Useless comments are just as bad as no comments.

2. API specific documentations is usually not all of it

Most often API specific documentations are great for black-box module to module integration and allows integration of complex system as they evolve. However, it is no substitute for key elements of documentation such as overall architecture, detailed designs or module designs, algorithms, functionality and business rules.

3. Ensure people buy in prior to enforcing it.

True success in any process is achieved only when there is a commitment from people to achieve it. It may be possible to declare it as a policy and people might even follow verbatim for the sake of it, but it wont bare fruits unless it is done with right spirit.

4. Take up people's involvement and agreement before freezing the exact standard

Coding styes always helps; and no one would deny that. However, it does call for a change when when there is a difference between what one personally follows and what the policy says. So it is best to see what most people are already fit with and define the rules where there would be least damage. Also, when people see that a certain coding guideline was selected due to majority thinking they are more likely accept the change rather than a committee imposed rules.

5. Monitor and adapt

Nothing is perfect on day one when it begins. Keep some basic expectations of what would you have expected and track if things are happening that way. When things are not tracked, even good initial successes fades away.

**
For more See this


答:
Why do you separate code and test?

I prefer a bundle of code and test. And this bundle should get the same license.

If somebody would like to get twice money, then you may make two packages - each with a license. For free software, I see no reason for two packages (unless it is a size problem).


问:
Does anyone else have a refactoring problem?
It seems like after I've written a significant amount of code I get this anxious feeling like I haven't done it in the best possible way, and I end up continuously refactoring and spending way too much time on the project, or never getting it done sometimes. Does this ever happen to anyone else, and how do you deal with this?</p>

答:
Here are a few rules to constrain this activity and make it more productive:

time-box it, e.g. set the timer to 25 minutes

do it only when you have decent test coverage.

try to make your refactoring useful to the development of next few features

ContentLicense: CC BY-SA 2.5


答:
@Dipan's answer covers the main points, but there is a thing you need to do with this kind of cultural change: start small and experiment . Start with a very small project. One with people you already have on your side. People who loves documenting, using documentation tools, and more generally trying new things. Make them debug the process, and ask them to write feedback. Once you have something working with 2-3 programmers, you can try to bring the change.

It may take time, but it is necessary in order to defing exactly what are your needs, and whether your project fits well in your environnement (tools are easy to set up and manage? are people really using the doc? Does the process of writing the doc helps people to formulate their idea? do you want other team to access your documentation? etc)

Title: What could be some pitfalls in introducing a style guide and documentation generating software in a development team?

Body:
I'm considering using appledoc, a flavor of Doxygen for use in generating Objective-C code documentation, in order to create documentation for my company's iOS apps. The idea is that a server will generate the docs on a post-commit hook, then publish the documentation on an internal network.

Right now we have very little documentation of any kind, even comments in the code itself, so I'm expecting I will have to ask people to begin writing more documentation as they code. In this vein, I will also collaborate with my team in order to create a "style guide" for Objective-C code (like Google's), which will lay down some ground rules on how to write and document code.

What are some potential pitfalls in the above plan? Are style guides effective? I see the benefits in adopting a coding standard, but will developers find it restrictive? And do documentation projects such as this one work? And if not, why do they fail?

(I've posted on Stack Overflow a few times with moderate success, but this is my first time posting here. Please let me know if I could improve my question in any way. Thanks!)


问:
API Development - Sinatra?
I've been tasked to create a mobile application as well as an accompanying website. Both the application and website will interact with the same database. To make things easy, I figure creating an API would be best that way I can separate it out from the mobile application and website.

Would this be the preferable method? I'm thinking Sinatra would be best for this situation. I'm using Ruby on Rails for the website but feel it would be overkill for the API.

I just want to validate my thoughts regarding this issue.

Thanks!

答:
Also have a look at padrino. It is built on top of Sinatra and adds much of the goodness of Rails but without the magic.

Many people love the simplicity and expressiveness of Sinatra but quickly come to miss a great deal of functionality provided by other web frameworks such as Rails when building non-trivial applications.

Our goal with Padrino is to stay true to the core principles of Sinatra while at the same time creating a standard library of tools, helpers and functions that will make Sinatra suitable for increasingly complex applications...

Title: API Development - Sinatra?


问:
Are Blocks Second-Class Citizens in Objective-C (vs. Ruby)?
Feeling slightly witty the other day, I wrote an eachWithIndex: method in a NSArray category. It has a typedef like this:

```<code>typedef void (^processItem)(id item, int index);
</code>```

and the method looks like this:

```<code>- (void)eachWithIndex:(processItem)block {
    for (int i=0; i<self.count; i++) {
        id item = [self objectAtIndex:i];
        block(item, i);
    }
}
</code>```

However, if my block contains a return at any point, it doesn't jump out of the calling method (nor the block). Consider this code in Ruby:

```<code>def blah
    %w{one two three}.each_with_index {|thing, i| puts "#{i}=#{thing}"; return "hello!" if i==1 }
    puts "blah does more stuff"
end
</code>```

when i reaches one, the blah method will end. This does not happen in Obj-C, and I feel that it should. Are blocks more integrated into Ruby than Objective-C?

答:
It isn't really a matter of integration or being second class citizens. They simply work in different ways. Blocks are separate functions in effect, so have their own scope in which return works. Return will exit the block, but not the calling method/function, just as if you called another method or function. This provides a lot of consistency

In order to stop your method you need to pass in a BOOL pointer that can be set as to YES to stop the array. Look at NSArray's enumerateObjectsUsingBlock: method that does essentially the same thing as your each with index method (and is probably better to use as it already exists and will most likely be better optimised).


问:
Are there any OS which are simple enough for learning?
I would really like to understand how an operating  system works behind the scenes. However, I think that the kernel of most open-source OSs out there are too complex for learning purposes, even for a full-time programmer to learn. Are there any "simple" OSs made for learning purposes only out there?</p>

答:
Take a look at KOS (Kid OD) and SOS (Simple OS). Both are Operating Systems designed to teach the internals of an OS. KOS is the "father" of SOS, and was built based on the experience gained from KOS.

These projects were the basis of many educational articles in Linux Magazine France.

On the KOS website, you can also find a page where you can download the sources of other simples OSs.


问:
How do you dive into large code bases?
What tools and techniques do you use for exploring and learning an unknown code base?

I am thinking of tools like grep, ctags, unit-tests, functional test, class-diagram generators, call graphs, code metrics like sloccount, and so on. I'd be interested in your experiences, the helpers you used or wrote yourself and the size of the code base with which you worked.

I realize that becoming acquainted with a code base is a process that happens over time, and familiarity can mean anything from "I'm able to summarize the code" to "I can refactor and shrink it to 30% of the size". But how to even begin?

答:
I like to do the following when I have a really large source file:

Copy the whole mess onto the clipboard

Paste into Word/textmate whatever

Reduce font size to the minimum.

Scroll down looking at the patterns in the code

You would be amazed at how oddly familiar the code looks when you get back to your normal editor.

Title: How do you dive into large code bases?


问:
Benefit of using static inner builder class
During the course of writing the code guidelines for a company I found myself recommending using the Builder pattern from Effective Java, instead of telescopic constructors.

However, after thinking about it a bit more, surely a more elegant solution is to just remove the builder class and the also remove the extra constructors with optional arguments.

So just have the one constructor with required parameters, normal getters/setters, and comment the code. When implementing just create a new instance of yr object then set values.

My original thinking was the benefit came from removing the confusion as to what paramters were optional and what were required; however the true benefit comes from using method chaining/fluent interface.

The builder pattern has benefits when you make lots of new instances as the ide can do the leg work and also if there are many (15+) optional parameters. However, is it worth the extra time coding the static inner class, would you recommend using the builder, or is it a waste of time ?

答:
I tend to follow a pattern that constructors should provide all of the mandatory values required to create a valid and consistent object.  For optional values, I try to think about what the most common default should be, so that setters are used as little as possible.

If I find that there are lots of optional values or that a larger proportion of optional values tend to be altered from their defaults, then I'll use the builder pattern (static inner builder or other similar design).

Josh generally gives pretty darn good advice - the best thing I like about him is that the advice comes from the trenches - he admits himself that he made mistakes in designing parts of Java, and Effective Java is partly kind of his 'cure' so to speak :-)


问:
BDD to replace the test teams work - how best to do it?
The system we are developing, using .NET, is extremely large, complex, and some modules are poorly written. We have a large user acceptance test team that is aiming for 100% business scenario coverage, which takes about 6 weeks.

Can we use behavior driven development to replace some of the manual tests being done by the test team?  How would that information be readable to the test teams so they can be sure it's working? Does BDD replace our integration tests?

答:
It sounds to me as if some effort should be spent on the QA side automating the user acceptance test scripts. If you have a large QA team it should be no problem to allocate a core of 3 or 4 test automation leads (QA's with some coding experience) to begin automating the manual test scripts in some way.

Gradually, they filter that knowledge down to all other QA engineers, who in time become responsible for the automation of the test scripts for their assigned areas. We've taken this approach in our team and it has worked quite well.


答:
They are not the same thing.

A bug is unintended behavior of a piece of software: the software doesn't do what it is supposed to do. Bugs can live at all levels of software development, ranging from plain old typos through logical errors up to inadequate functional specs.

An exception, by contrast, can refer to either an unusual condition of a program, deviating from normal operation, or, more specifically, to the language construct used to signal and handle such conditions.

The fact that an exception occurs can be a sign of a bug, but often it isn't. For example, an application that is supposed to download a document from a URL and process it locally might throw an exception when the remote server is down: the application is deviating from normal operation (it cannot download and process the document), but if it handles the exception properly and recovers, then there is no bug.

Conversely, the presence of a bug doesn't necessarily manifest itself as an exception. An application might silently discard data you enter instead of storing it in its database; no exception gets thrown, but it is still a bug.


问:
How to understand the beauty of UNIX?
Some of my friends say that UNIX is beautiful and simple. But I really don't know what they mean. Why are they saying so? For me, UNIX is just a boring command prompt with different shells. How can I experience the beauty of UNIX? Can you share any experience?</p>

答:
One of the fundamental differences between UNIX and Windows, is that Windows tends to have complex monolithic applications, whereas UNIX achieves complexity by combining small, self-contained applications each of which is good at performing one specific task. In Windows, a particular application, no matter how rich and complex it can be, is all you have. In UNIX you can combine applications in many different ways to fit your needs. It is a completely different world, different way of thinking and working.

If you want to experience this you just have to work with UNIX for a while on specific tasks, it is difficult to appreciate it in the abstract. But here is a small example. Suppose you want to look for all C++ source files containing the macro USE64BIT. Here is one way (my way) of solving this on a UNIX system (specifically, on Ubuntu GNU/Linux 10.04).

To check if a file contains a string, I use grep. So I would write:

```<code>$ grep USE64BIT mysource.cpp
</code>```

or

```<code>$ grep -H USE64BIT mysource.cpp
</code>```

if I want to print the name of the matching file before each matching line.

Now, I want to find all C++ files, so I need a tool to search for files. I use find:

```<code>$ find . -name "*.cpp" -print
</code>```

This will find all files with names matching the pattern *.cpp starting at the current directory (the first parameter '.') and print each file path (relative to .) on a separate line of output.

Fine, now I want to feed the output of find into grep to get all files containing my string. I have another tool: xargs. xargs can call another tool repeatedly, passing it as a parameter what it gets from standard input. So we need something like:

```<code>$ find ... -> xargs ... grep <input to xargs>
</code>```

The above is not a valid command, but the idea is to pipe the result of find into xargs and let xargs call grep on each line of input. Here is a first solution:

```<code>$ find . -name "*.cpp" -print | xargs -iFILE grep -H USE64BIT FILE
</code>```

Here, the output of find contains all the found files, one per line. xargs takes each line of input, sets the variable FILE to it, and calls grep repeatedly, each time passing it the current value of FILE as a parameter. The result of all these calls to grep is concatenated together to the final output stream.

This solution can still be improved: one should use -print0 in find and -0 in xargs so that the output from find uses a 0 character instead of newline as a separator (file names will never contain a 0 character, so 0 is a safer separator). So, the final solution is

```<code>$ find . -name "*.cpp" -print0 | xargs -0 -iFILE grep -H USE64BIT FILE
</code>```

This is what we were looking for: all lines in all C++ files containing the given macro.

If you are not interested to see the matching lines, but just the files that match, you can change the option in the grep command. On GNU/Linux you can use -l to only print the file name of the matching file:

```<code>$ find . -name "*.cpp" -print0 | xargs -0 -iFILE grep -l USE64BIT FILE
</code>```

Oh, but now you want to sort your list of matching file alphabetically. Fine:

```<code>$ find . -name "*.cpp" -print0 | xargs -0 -iFILE grep -l USE64BIT FILE | sort
</code>```

And, of course, you could continue and invent more and more examples.

As you can see, every command is relatively simple and very specialized, but you can perform very complex tasks by combining different commands. You can drive the OS to get exactly what you want. This is for me one of the reasons why I appreciate UNIX systems so much because I haven't found this flexibility e.g. on Windows. First thing I do when I have to work on a Windows system is to install cygwin (a UNIX-like environment for Windows).

Title: How to understand the beauty of UNIX?

Body:
One of the fundamental differences between UNIX and Windows, is that Windows tends to have complex monolithic applications, whereas UNIX achieves complexity by combining small, self-contained applications each of which is good at performing one specific task. In Windows, a particular application, no matter how rich and complex it can be, is all you have. In UNIX you can combine applications in many different ways to fit your needs. It is a completely different world, different way of thinking and working.

If you want to experience this you just have to work with UNIX for a while on specific tasks, it is difficult to appreciate it in the abstract. But here is a small example. Suppose you want to look for all C++ source files containing the macro USE64BIT. Here is one way (my way) of solving this on a UNIX system (specifically, on Ubuntu GNU/Linux 10.04).

To check if a file contains a string, I use grep. So I would write:

$ grep USE64BIT mysource.cpp

or

$ grep -H USE64BIT mysource.cpp

if I want to print the name of the matching file before each matching line.

Now, I want to find all C++ files, so I need a tool to search for files. I use find:

$ find . -name "*.cpp" -print

This will find all files with names matching the pattern *.cpp starting at the current directory (the first parameter '.') and print each file path (relative to .) on a separate line of output.

Fine, now I want to feed the output of find into grep to get all files containing my string. I have another tool: xargs. xargs can call another tool repeatedly, passing it as a parameter what it gets from standard input. So we need something like:

$ find ... -> xargs ... grep <input to xargs>

The above is not a valid command, but the idea is to pipe the result of find into xargs and let xargs call grep on each line of input. Here is a first solution:

$ find . -name "*.cpp" -print | xargs -iFILE grep -H USE64BIT FILE

Here, the output of find contains all the found files, one per line. xargs takes each line of input, sets the variable FILE to it, and calls grep repeatedly, each time passing it the current value of FILE as a parameter. The result of all these calls to grep is concatenated together to the final output stream.

This solution can still be improved: one should use -print0 in find and -0 in xargs so that the output from find uses a 0 character instead of newline as a separator (file names will never contain a 0 character, so 0 is a safer separator). So, the final solution is

$ find . -name "*.cpp" -print0 | xargs -0 -iFILE grep -H USE64BIT FILE

This is what we were looking for: all lines in all C++ files containing the given macro.

If you are not interested to see the matching lines, but just the files that match, you can change the option in the grep command. On GNU/Linux you can use -l to only print the file name of the matching file:

$ find . -name "*.cpp" -print0 | xargs -0 -iFILE grep -l USE64BIT FILE

Oh, but now you want to sort your list of matching file alphabetically. Fine:

$ find . -name "*.cpp" -print0 | xargs -0 -iFILE grep -l USE64BIT FILE | sort

And, of course, you could continue and invent more and more examples.

As you can see, every command is relatively simple and very specialized, but you can perform very complex tasks by combining different commands. You can drive the OS to get exactly what you want. This is for me one of the reasons why I appreciate UNIX systems so much because I haven't found this flexibility e.g. on Windows. First thing I do when I have to work on a Windows system is to install cygwin (a UNIX-like environment for Windows).


问:
Working with a remote developer
My company is going to hire an external developer to write some simple PHP modules and some minor bugfixing in our software.

We have never hired an external developer by the hour before. How can we measure external developer's productivity and coordinate with them?

I thought about using a combination of http://worksnaps.net/ and https://github.com/.

Any better ideas?

答:
You could check the progress of the projects directly via dropbox, at my work place, we tend to work on projects using Netbeans IDE, that we have linked to our dropbox accounts which means we can all see exactly what is being worked on at that point and see the actual files.

This may not be what you need but I think it would provide a good solution for you.

http://www.dropbox.com/

OwnerDisplayName: Mascarpone

Title: Working with a remote developer

OwnerDisplayName: Aaron Lee


答:
You should measure the developer's productivity by how well they solve your problems.

Ask the developer to give an estimate for how long a new feature or bug fix will take.

Ask yourself whether it's worth having them fix it based on their estimate.

If it's worth it, and they finish in more or less the time that they estimated, they were productive.

Unforeseen problems can (will) arise, in which case they should revise their estimate and you should go back to step 2.  If the estimates are regularly wrong to an extent that total cost is more than the fix is worth, stop working with them.

Title: Working with a remote developer

Body:
My company is going to hire an external developer to write some simple PHP modules and some minor bugfixing in our software.

We have never hired an external developer by the hour before. How can we measure external developer's productivity and coordinate with them?

I thought about using a combination of http://worksnaps.net/ and https://github.com/.

Any better ideas?

OwnerDisplayName: blahdiblah


答:
Measuring programmers is a stupid idea, but there're lot of checkpoints, which can be used as indicator. These indicators requires programming experience, e.g. if you wanna know that a solution is a long-term safe solution or just a quick hack, you should peek inside the code.

Fortunatelly, there's a sharp line between amateur and professional programmers, which can be judged by non-programmers (also, it requires some technical knowledge): the documentation. Amateurs don't make documentation, professionals do. The quality of the document may vary, but if there's no any, it's the sign of amateurism.

Title: Working with a remote developer


答:
Josh Bloch's Builder pattern, much like the GoF Builder Pattern, offers a way of creating an immutable object with lots of default data without long lists of chained constructors.

If you "have the one constructor with required parameters, normal getters/setters" then your object is no longer immutable. ie. You can change it long after instantiating it.

If that's not a problem for you then you never needed the Builder pattern in the first place. If it is a problem then your solution is flawed.

Title: Benefit of using static inner builder class

Body:
During the course of writing the code guidelines for a company I found myself recommending using the Builder pattern from Effective Java, instead of telescopic constructors.

However, after thinking about it a bit more, surely a more elegant solution is to just remove the builder class and the also remove the extra constructors with optional arguments.

So just have the one constructor with required parameters, normal getters/setters, and comment the code. When implementing just create a new instance of yr object then set values.

My original thinking was the benefit came from removing the confusion as to what paramters were optional and what were required; however the true benefit comes from using method chaining/fluent interface.

The builder pattern has benefits when you make lots of new instances as the ide can do the leg work and also if there are many (15+) optional parameters. However, is it worth the extra time coding the static inner class, would you recommend using the builder, or is it a waste of time ?


问:
Why don't we use dynamic (server-side generated) CSS?
As server-side generated HTML is trivial (and it was the only way to make dynamic webpages before AJAX), server-side generated CSS is not. Actually, I've never seen it. There are CSS compilers, but they generate CSS files which can be used as static.

Technically, it requires no special libraries, the HTML style tag should reference to the PHP(/ASP/whatever) templater script instead of the static CSS file, and the script should send out CSS content-type header - that's all.

Does it have cache problems? I don't think so. The script should send out no-cache etc. headers. Is it problem for designers? No, they should edit the CSS template (as they edit the HTML template).

Why we don't use dynamic CSS generators? Or if there's any, please let me know.

答:
Does it have cache problems? I don't think so. The script should send
  out no-cache etc

All very well, but that's a significant piece of generally-static information that you're asking the user to download every time they load a page. So you'd better have a good reason for it.

Now what could that reason possibly be?

If you want to change a style based on various parameters then you do that by having multiple stylesheets and generating the HTML to download the correct one.


答:
I believe your assumption is wrong: in my last project, the application was using server-generated CSS loaded by ajax (because, depending on the location of the map you were looking at, the page was branded with completely different styles).

However, usage cases where retrieving extra CSS by ajax would solve the problem are quite rare, this may be why you never encountered this: it's usually easier to maintain a set of stylesheets that are preprocessed at deployment time (LESS + minification) and cacheable (e.g. the next page will be able to re-use the stylesheet it cached before, so the initial time is shorter).

Title: Why don't we use dynamic (server-side generated) CSS?

Body:
As server-side generated HTML is trivial (and it was the only way to make dynamic webpages before AJAX), server-side generated CSS is not. Actually, I've never seen it. There are CSS compilers, but they generate CSS files which can be used as static.

Technically, it requires no special libraries, the HTML style tag should reference to the PHP(/ASP/whatever) templater script instead of the static CSS file, and the script should send out CSS content-type header - that's all.

Does it have cache problems? I don't think so. The script should send out no-cache etc. headers. Is it problem for designers? No, they should edit the CSS template (as they edit the HTML template).

Why we don't use dynamic CSS generators? Or if there's any, please let me know.


答:
Actually, there are use cases for dynamic CSS.  I've worked with three different kinds:

Less — Less CSS is basically a CSS language extension that adds "dynamic behavior such as variables, mixins, operations and functions."  It also allows "nested rules", which is very convenient. I have used Less mainly to make CSS writing less verbose by eliminating some of the repetition.

URL rewriting — Just as a proof to your statement that there are no cache problems, I've used PHP to serve scripts as CSS files with the correct cache headers for a long time.  I mainly do it to serve CSS files from libraries that are not inside the web root.

Dynamic reports — On one project I worked on, we had a report builder for all kinds of data in the system.  We output (inside style tags, as you mention) dynamic style rules mainly for colors that had been selected by the user in the report builder.

Note: When outputting CSS directly to a URL (like in 1 or 2) and not embedding it within a page that is already being generated by a script, you will add quite a significant load to the server over serving static content.  So, if you have sizable traffic, even though you can do it dynamically every time, you'd want to cache it as a static file if your use case allows.

But why is it not more common?  I think there is one main reason — CSS isn't really built to output content. So there simply isn't a great need.  Beyond outputting dynamic colors chosen by the user, as we did, or possibly background-images (though if the image is content, then it is probably a good argument to use the img tag), what else do you need to do dynamically?

Most dynamic style changes can be produced by referring to different static CSS documents.

So it is certainly possible, as you thought, but there just aren't too many reasons to do it.


答:
Dynamic CSS is fairly trivial, and even though its applications are more limited (seeing how dynamically-generated HTML with a static stylesheet solves most day-to-day needs, and CSS itself incorporates a few mechanisms to achieve semi-dynamic), I've seen it used on many occasions, and I use them myself whenever I need to.

Often, the 'dynamic' part does little more than combining several stylesheets into one (to reduce the number of HTTP requests) and minifying them (to reduce bandwidth usage), but simple things like variable substitution (e.g., using variables for colors used throughout the style sheet) can make your life much easier. However, since CSS has a fairly straightforward syntax with few caveats, a general-purpose text processing system or scripting language like PHP is usually enough for this, which is why you don't see many off-the-shelf CSS processing systems.

Maybe you have seen them in the wild, without recognizing them. Servers that send dynamic scripts usually use URL rewriting so that the URL becomes indistinguishable from statically-served content. This is necessary because some browsers (most notably IE) rely on extensions for correct MIME type detection under certain circumstances, ignoring (or discarding) any Content-Type headers you may have sent.

Regarding caching: Stylesheets are pulled in with GET requests, and making them cacheable is absolutely important for a decent user experience. You don't want to watch the page reflow as it re-downloads the stylesheet on every request. Instead, you should put all parameters that alter the output of your stylesheet processing into the query string; a different query string yields a different URL, which in turn causes a cache miss, so whenever the parameters are altered, the stylesheet will be re-downloaded, even if the client caches everything. If you really need CSS that is potentially different for each request and depends on side effects, consider putting the non-dynamic part into a statically-served stylesheet, and only serve those things dynamically that are absolutely required to be dynamic.


问:
Python Metadata Files and Project Organization
I have a project in Python where I have a server. The server can have a variety of different services, but I don't know what those are until I start it up. I want it to do a search of available plugin files to know what services are available.

Right now, I'm doing that by just having the metadata files as Python source code and loading it using imp.load_source.

My question is where do I store these metadata files? The metadata files need to contain information pointing to files on the filesystem. For example, one of the programs the service needs to launch is a java program. I have the jar file and I compile it myself, but when I'm working on the project the compiled file goes into the build directory. When I'm going to want to install this on a machine, I'll need to store the files somewhere else. I want to keep the source directory and build directory separate (as it makes the clean command easier).

What standard practice is done to handle the need for metadata files and where they are located?

EDIT: I'm trying to target both Windows and Linux systems (and hopefully Mac systems too, but that's less important). For Linux, most important are the major distributions (such as Fedora and Debian) and hopefully others (although this is dependent on others trying to use it on whatever distribution, as I cannot test all of them and will only test on Fedora and Debian myself).

答:
This sounds like you're reinventing software deployment. There are some great free tools for this! Using one will save you tons of headache and hassle, now and in the future, at the expense of learning one new simple tool.

I've had good experience with Buildout, which is quite widely used in Python projects and highly recommended.


答:
There are some scenarios were I'd love to use dynamic CSS, but more often than not I'm stuck with using designers who need a bit of help understanding CSS basics. Throwing a dynamic language in the mix might actually make a head explode.

Another way to look at this would be "some other guy is doing all the painful manual work, not really my problem, moving on . . ."


问:
When would someone be considered a bad programmer?
How would you consider that a programmer is bad at what he or she is doing?

If possible... How should he/she improve?

答:
A big warning sign in my experience is when they don't comment their hacks....

You know what I mean: when you're forced to do something very hacky because there is simply no better way to do it.

Good programmers will hate having to do it and put in inline comments saying how much they hate putting in that kind of hack, but there is no choice. Bad programmers will just put in the hack and not comment it.


答:
There's TWO separate aspects to loading CSS dynamically...

Generating the CSS file dynamically on the server

This is fairly straightforward, and a lot of websites do it.
This is useful if you change your CSS based on some condition. For example, if you choose your site's theme based on the Geo location of the user.

Loading a CSS file on demand via a JS script loader

This could come in handy if you create a big part of DOM dynamically and then load the required styles.
BUT  As author of LABjs says...

actually determining if a dynamically loaded CSS file has finished loading is actually quite complicated and challenging to do cross-browser. The "load" events don't fire as one would hope/expect. so adding such support would add a non-trivial size to LABjs


问:
Is it necessary to know and understand design patterns in order to be a professional programmer?

Possible Duplicate:

  Are design patterns really essential nowadays?

Is it necessary have a knowledge and understanding of design patterns for someone to be a professional programmer? Why?

答:
Algorithms, Design patterns, Application architecture types are building blocks for programmers.

They are the independent of most popular languages ( C#, Java etc ) and one of the positive sides of this fact is that they can be used to communicate your thoughts easier when it comes to explaining how something is coded.


问:
Am I programming too slow?
I've only been a year in the industry and I've had some problems making estimates for specific tasks. Before you close this, yes, I've already read this: How to respond when you are asked for an estimate? and that's about the same problem I'm having. But I'm looking for a more specific gauge of experiences, something quantifiable or probably other programmer's average performances which I should aim for and base my estimates.  The answers range from weeks, and I was looking more for an answer on the level of a task assigned for a day or so. (Note that this doesn't include submitting for QA or documentations, just the actual development time from writing tests if I used TDD, to making the page, before having it submitted to testing)

My current rate right now is as follows (on ASP.NET webforms):

Right now, I'm able to develop a simple data entry page with a grid listing (no complex logic, just Creating and Reading) on an already built architecture, given one full day's (8 hours) time.

Adding complex functionality, and Update and Delete pages add another full day to the task.

If I have to start the page from scratch (no solution, no existing website) it takes me another full day.

(Not always) but if I encounter something new or haven't done yet it takes me another full day.

Whenever I make an estimate that's longer than the expected I feel that others think that I'm lagging a lot behind everyone else. I'm just concerned as there have been expectations that when it's just one page it should take me no more than a full day. Yes, there definitely is more room for improvement.  There always is. I have a lot to learn. But I would like to know if my current rate is way too slow, just average, or average for someone no longer than a year in the industry.

答: You might be a little "slow" compared to someone who has been programming for 5 or 10 years, but it all comes with time. You are probably doing things now in 1/10th of the time as when you were first learning, and it will continue to become easier. That's just the way most things in life are... you are slow when you first learn it, and you gradually get better, faster, more efficient. If you practice long enough, you might become "masterful". </p>

Title: Am I programming too slow?


答:
Design patterns serve a couple of purposes:

They are tried-and-true solutions to many commonly encountered problems, and

Because many developers know them, they are a shorthand for communicating concepts.

You don't have to know them to be a professional developer, but not knowing them will handicap you to a certain degree, because you will be unable to "speak the language."  You will also be reinventing the wheel.

Title: Is it necessary to know and understand design patterns in order to be a professional programmer?

Body:
Possible Duplicate:

  Are design patterns really essential nowadays?

Is it necessary have a knowledge and understanding of design patterns for someone to be a professional programmer? Why?


问:
The dreaded C# programming interview test - any advice?
I have a possible C# dev job lined up but before I can interview, I need to pass a test with the employment agency.

Now even though I am a senior developer with over 10 years of programming experience and more than 3 of these years with c#, I am really not looking forward to this test and I think there is a good chance I will fail it.

In my experience these tests are unpredictable asking you stuff you seldom use in everyday work situations.

I need your best advice on what I should be revising on - a good book or website for example. I have less than 1 week to prepare and it is essential I pass this.

Thanks in advance.

EDIT: To further justify my concerns of writing such tests - Consider the following question:

12) An Event is :

```<code>   a) The result of a users action - correct answer
   b) The esult of a party
   c) code to force users action
</code>```

The correct answer according to the test is A, but since I've been doing SOA development (often when events can be based on system events (not user actions) I'm 100% sure an event doesn't have to be driven by a user action. This was also a C# question (not an ASP.net question). Based on my understanding, I couldn't really spot a correct answer but B seems the best of the lot (if the definition of party is : any entity that can trigger an event.
These kind of questions scare me.

答:
Just walk away, Renee

I've taken tests like this a couple of times. Now I just walk away. The tests measure the most trivial bits of programming knowledge. Do you want to work for someone who thinks these tests are a good way to evaluate programmers? I don't.


答:
The big reason why css is seldom generated dynamically (this is also true for javascript) is because they are good candidates for caching.  CSS is a very flexible way to style your pages, with the right combination of classes, you can get all of the different parts of all of your different pages styled according to all sorts of cues all  Without having to condition any of it in the CSS itself on what actually happens to be present on this pageview.

Simply because CSS doesn't need to be different per page leads to a very common practice of optimizing the cost of downloading it.  Most sites cram all of the css for their whole site into a single download, so that parts that would apply to different page-views are present in only one downloaded file.  With caching, your clients don't have to wait for it to download a second time.  Maybe more importantly, you, as a content provider, don't have to pay the cost of uploading the content more than once; and you can even put the static css on a server that is better suited serving static content, which frees resources for actual dynamic content on your application servers.

This practice is so common, that many browsers just assume that the css is static; and are very reluctant to download CSS they already have; even if the users reloads the page.  This special treatment applies only to CSS; other content types get reloaded as expected.


问:
How does Ruby, Python, PHP manage without Spring?
I write enterprise Java applications and web services at work (Spring, Hibernate, Maven, RESTEasy) and PHP (CakePHP) and Python (Django) for my side projects.

While I do see the value that Inversion of Control, Aspect Oriented Programming etc. that Spring brings in, I am not sure how massive web applications that are not on the Java stack manage without a framework like Spring.

So, do the developers just have to "put up with" tightly coupled components and other grievances that Spring eliminates or am I missing something?

For those unfamiliar with Spring, the features we use the most are:

Inversion of Control container: configuration of application components and lifecycle
management of Java objects,

Aspect-oriented programming: enables implementation of cross-cutting routines,

Transaction management: unifies several transaction management APIs and coordinates transactions for Java objects.

答:
For Python, BlueBream (aka Zope 3) provides what Spring does and more.

Complexity and power comes at a cost, there are times when you don't want to pay it.

Many programmers find BlueBream daunting and way too much for what they need to do, they prefer leaner, smaller toolkits. Most of the other solutions (Django, etc.) are based on the MVC paradigm.

You can see a similar forces in action in the Java space as well, with things like the beautiful Playframework.


问:
Solutions for implementing a full-duplex game server?
I am designing a game server which would be used for Android terminals. I've been searching for products or frameworks to use for two-way socket communication but haven't found anything worth mentioning.

Simply, I want to implement the architecture below:

In other words, one TCP connection from the client to the server, and another from the server to the client, in order to avoid always having to be connected.

Just to be clear, my main aim is for the server to be able to send data to the client, without the client having to explicitly request it.  I do not want the client to have to poll the server to see if there is any new data.

What combination of design strategies, network protocols, and/or products or frameworks (if any) would be appropriate for implementing this architecture?

答:
The problem is that the client will often be behind a NAT/firewall, which means that the server can't initiate a TCP connection to the client, because the client doesn't have a globally routable IP address and/or because the firewall will block the unexpected incoming TCP packets coming from the server.

So that means that any TCP connection will have to be initiated from the client side.  Once that is done, you have the option of leaving the TCP connection open indefinitely (which you don't want to do) or closing the TCP connection once any immediate business has been attended to (but that means that the client will need to connect again later to see if more updates have arrived in the meantime, which is polling, which you also don't want to do).

So you're kind of stuck.  The only possible solution I can think of is to set up a number of proxy servers that are not behind firewalls/NATs, and have your Android clients persistently connect to them.  The proxy servers can then forward requests on to your main server, and since you control the proxies, you can make sure the server is able to connect back to them as necessary.  If you're lucky, somebody else has already set up a system like this and you can simply piggyback on it... perhaps this will do what you want.


答:
No.  I only say that to be pedantic though.  The term "professional programmer" really just means you get paid to program.  I assure you that you can be paid to program without knowing any design patterns (I certainly did, for a few years).

However, knowing design patterns has some benefits:

It's a way that other programmers tell us about general ways that they've solved general classes of problems.

It's a name that you can apply to a specific pattern, and other programmers who know that pattern will understand what you mean.  You can even put it into the name of the methods and classes (XyzSingleton, for instance).

In many ways it's a good way to learn the shortcomings of programming languages and paradigms.  For instance the Visitor pattern exists because in object-oriented programming you typically have to make a choice between an architecture where it's easier to add new types that exhibit the same interface, or easy to add new behaviors to existing types, but doing both gets complicated.  Thinking about these problems informs your design decisions.


答:
While knowledge and understanding of design patterns is not a prerequisite to becoming a professional programmer, they are a useful tool to improve the reliability of your code, your ability to communicate with other programmers, and the ability for others to maintain the code you've written.

Just like learning additional programming languages and technologies, good understanding of design patterns improves your skill and value.

In other words, you don't need to know and understand design patterns, but the more you do understand, the better you will be professionally.


问:
Data Scraping - One application or multiple?
I have 30+ sources of data I scrape daily in various formats (xml, html, csv). Over the last three years Ive built 20 or so c# console applications that go out, download the data and re-format it into a database. But Im curious what other people are doing for this type of task. Are people building one tool that has a lot of variables and inputs or are people designing 20+ programs to scrape and parse this data. Everything is hard-coded into each console and run through Windows Task Manager.

Added a couple additional thoughts/details:

Of the 30 sources, they all have unique properties, all are uploaded into individual MySQL tables and all have varying frequencies. For example, one data source is hit once a minute, another on 5 minute intervals. Majority are once an hour and once a day.

At current I download the formats (xml, csv, html), parse them into a formatted csv and put them into staging folders. Within that folder, I run an application that reads a config file specific to the folder. When a new csv is added to the folder, the application then uploads the data into the specific MySQL tables designated in the config file.

Im wondering if it is worth re-building all this into a larger complex program that is more capable of dynamically adding content+scrapes and adjusting to format changes.

Looking for outside thoughts.

答:
It depends - if you need the scrapers to feed into a single application/database and have a uniform data format, it makes sense to have them all in a single program (possibly inheriting from a common base scraper).

If not and they are completely unrelated to each other, might as well keep them separate so changes in one have no effect on another.

Update, following edits to question:

Don't change things just for the sake of change. You have something that works, don't mess with it too much.

Since your data sources and data sinks are all separate from each other, combining them into one application will simply create a very complicated application that will be very difficult to change when needed.

Since the scrapers are separate, keep the separation as you have it now.


答:
cscope can do whatever ctags can do for C, plus, it can also list where all current function is called. Plus it is very fast. Scales easily to millions of LOC. Integrates neatly to emacs and vim.

C and C++ Code Counter - cccc can generate code metrics in html format. I have used wc also for getting LOC.

doxygen can generate syntax highlighted and cross referenced code in html. Useful in browsing large code base.

Title: How do you dive into large code bases?

Body:
What tools and techniques do you use for exploring and learning an unknown code base?

I am thinking of tools like grep, ctags, unit-tests, functional test, class-diagram generators, call graphs, code metrics like sloccount, and so on. I'd be interested in your experiences, the helpers you used or wrote yourself and the size of the code base with which you worked.

I realize that becoming acquainted with a code base is a process that happens over time, and familiarity can mean anything from "I'm able to summarize the code" to "I can refactor and shrink it to 30% of the size". But how to even begin?


问:
Starting a coherent architecture in a legacy application
I have responsibility for a large Asp.Net based website. It is currently a website (not web application), some windows services and a number of class libraries.

The data layer uses a mixture of LLBLGEN  and Linq To LLBGen, as well as a number of instances of legacy inline SQL which have not been refactored.

There are some manager type implementations, but in many cases the application exhibits the Smart UI anti-pattern (i.e. too much business logic in code behind classes)

The site is reasonably high traffic, and performance is fine, but we are growing our development capability to a team of around 10, and increasingly it is clear we need an overarching layered design on top of the existing middleware.

My question is where to start? We have 10 years of code (some of it still really just migrated ASP Classic stuff), many different approaches, and styles.

Refactoring the entire code base is not realistic and, probably not desirable

I know this is not a novel situation, are there any useful ideas or concepts as to how to approach this problem?

答:
I also have been working in similar situations and I can give you the following advice.

You need to reduce technical debt. Now. Why? Because technical debt is like financial debt. You will pay interest on it.

Since refactoring the whole code base is not feasible, ask yourself: what is preventing it? Is it simply too much work? Why?

Create a plan to reduce technical debt in time. For example, by setting up rules as "every bit of code that is touched by the team must be fixed/refactored to the new standard". Typically: unit tests must be written, code must be moved in the correct layers, etc. This allows you to fix a lot of code without resorting to ridiculously expensive and low value "refactoring" projects.

Wrap the crap. Decoupling is key to refactoring and good architecture. If you can partition the code base somehow, you can maybe refactor smaller bits.

Do not increase tech debt further. Do not increase tech debt further. Do not increase tech debt further. Do not...


问:
Can you change code distributed under the MIT license, and re-distribute it under the GPL license?
Is it possible to alter the code of the Chili plugin, which had its latest release on July 2008, and it is licensed under the MIT license, to then license it under GPL?

As far I can see, there is no restriction about the new code being licensed under the same license. Is it really so, or is there a minimum number of changes?

In my case, I would change the jQuery plugin in normal Javascript code that is executed in a CMS.
This essentially means that, among other things:

The code will not use the "ChiliBook" namespace.

The function will not be invoked as $($element).chili(), but as GlobalObject.ChiliHighlighter.process($jquery_element), where "GlobalObject" is a JavaScript object used from the CMS.

The code will allow other modules to alter the GlobalObject.ChiliHighlighter object to add functions that are optionally called from GlobalObject.ChiliHighlighter.process() when they are defined.

As alternative, as the repository I am using allows me to include code not licensed under GPL 2 or higher license when the code is not maintained anymore, could the plugin be considered not maintained anymore, as its last version was released three years ago?

答:
Yes. But the effect may not be what you think it is.

The MIT license includes all the rights the GPL gives and more. And while people who receive your distribution only receive a GPL license to elements you added, they still receive an MIT license (from the original authors, not from you) to any elements contained in the work that the authors offered under that license.

They may not know this, and so far as I know, no law obligates you to tell them. But if they "violate" the GPL license with respect to protectable expression contained in the work that you did not author (or that wasn't contributed by others to the GPL-only release), they have not violated your license or your copyright. (Actually, that should be rather obvious -- you only hold copyright to expression you authored.)

So you haven't converted any copyrightable elements from the MIT license to the GPL license. You've simply added new ones which are only offered under the GPL license and released the elements in a mixed/combined work.

ContentLicense: CC BY-SA 4.0


答: What you are working on is basically ETL.  So at a high level you need an export component (get stuff) a transform component (map to known format) and a load (take known format and put stuff somewhere).  If you are comfortable being tied to a RDBMS you could use something like SQL Server SSIS packages.  What I would do is create a host application that managed common aspects of the overall process (errors, and pipeline processing).  Then make the specifics of the E, T, and L pluggable.  A low ceremony way to get this would be to host the powershell runtime and create each seesion with common context objects that the scripts will use to communicate.  You get a built in pipe and filter model for scripts and easy, safe extensibility.  This design has worked extremely for my team with a similar situation. </p>

Title: Data Scraping - One application or multiple?

Body:
I have 30+ sources of data I scrape daily in various formats (xml, html, csv). Over the last three years Ive built 20 or so c# console applications that go out, download the data and re-format it into a database. But Im curious what other people are doing for this type of task. Are people building one tool that has a lot of variables and inputs or are people designing 20+ programs to scrape and parse this data. Everything is hard-coded into each console and run through Windows Task Manager.

Added a couple additional thoughts/details:

Of the 30 sources, they all have unique properties, all are uploaded into individual MySQL tables and all have varying frequencies. For example, one data source is hit once a minute, another on 5 minute intervals. Majority are once an hour and once a day.

At current I download the formats (xml, csv, html), parse them into a formatted csv and put them into staging folders. Within that folder, I run an application that reads a config file specific to the folder. When a new csv is added to the folder, the application then uploads the data into the specific MySQL tables designated in the config file.

Im wondering if it is worth re-building all this into a larger complex program that is more capable of dynamically adding content+scrapes and adjusting to format changes.

Looking for outside thoughts.


答:
We do this. All the time. Especially for things like customer-specific branding in a SaaS application, where colors etc. come from the database.

It's a lot faster (from the user's viewpoint) to pre-generate the CSS before or during deployment, or during application boot if the application has a boot phase. We generally prefer to pre-generate static CSS files whenever possible.

For maximum speed (from the user's viewpoint), it's best to deliver static CSS files to a CDN and to have the browser get them from the CDN, rather than from your application servers. This is generally possible only when the CSS files can be pre-generated before or during deployment, and where part of the deployment is delivering the pre-generated static CSS files to the CDN. CDNs are now very cheap and easy to use - check out Amazon's CloudFront and Rackspace's Cloud Files.


答:
You may want to use some good scheduling library, like Quartz.NET.

In a few words, here's what you can expect:

Your tasks are represented by classes and not processes

You can set and forget tasks and scale across multiple servers

You have an out-of-the-box system to actually take care of what is needed to be run when, what failed and needs to be re-run, etc. etc.

See also: https://stackoverflow.com/questions/507247/recommend-a-c-sharp-task-scheduling-library


问:
Patterns and practices for Web Scraping in .Net (C#)
I will be putting together an application to automate an external web site/application. In some instances I will need to navigate the site as a user would (some links I need to follow cannot be predicted and must be parsed from a response)

I am already using Html Agility Pack, and am aware of Tidy if that is needed.

Are there any other technologies I should be aware of?

Are there any recommended patterns for being able to quickly adjust in the event that the external web app changes? I’m envisioning encapsulating the validation of responses as some type of strategy or similar pattern that can be easily separated/plugged in as necessary, but any specific suggestions would be great.

答:
The pattern really should stem from the problem but here are some choices:

If you are mainly concerned with ongoing development cost/annoyance:
Strategy Pattern (already mentioned) - use this to implement the component level interfaces, and use a dynamic binding methodology to resolve specific strategies (implementations).  An IOC container (I like Autofac these days) would work well.

If you are need to support the above plus have a need to scale:
Map Reduce (anyone know of a good m+r fx for .net?).


答: Patterns are not necessary to write code and get paid for it.  The process of learning what types of pattens, algorithms, and architectural styles exist is a process of learning how to design and engineer software with higher internal quality and that meets more strict non functional requirements.  Oh and it may be necessary if you don't want the other dev kids to laugh and point. ;)</p>


问:
Is "Computer Science != Software Engineering" an excuse to teach programming poorly?
We've all heard it; whenever there's a discussion about CS grads having poor development skills someone eventually says,

Computer science isn't software engineering.

The problem that I see is that programming and software development are taught in CS courses. They're just commonly taught poorly. If it's being taught, then why not teach it right the first time? *

So I would like to see what the opinions are on 2 questions:

Is the CS != SE argument a copout or excuse for not properly teaching programming skills.

Regardless of your answer to question 1; if you were in the almighty position of making such a decision: would you force an emphasis on proper teaching of programming in CS courses?

*. I have a suspicion, based on anecdotal evidence I obtained throughout my education, that most academics in the field haven't had to write code to be maintained and haven't maintained code, and as a result don't have the knowledge/skills to teach it effectively.

答:
I have a CS degree, and for a whole year of my program there was no programming, only theory. We were told that we are not getting a degree in programming but in Computer Science. If you want to be a programmer go to community college.

We learned about algorithmns, design patterns, and alot of the theory about solving problems without a spacific language. Programming languages come and go, but the underlining theory stays the same.

So, to your first question, no I don't feel that CS != SE is a copout. It's a fact.

To your second question, no, I don't think I would. How do you properlty teach programming? Beyond loops, ifs, methods, classes and OOP, what would be 'proper programming' and how would you make it relevent to any programming language out there? You need experience writing code, something that a 4 year degree can't prepair you for.

One thing I would do though is provide a class on Development in the Real World. Source control, ticket/bug tracking, code tracing, and all that jazz would be a good start to prepare all the soon to be grads for what they will face in their new jobs.

I think it's on us when we hire a new grad to understand that they probably aren't going to be writing award winning code. They need guidance and direction.


答:
You're right that refactoring the entire codebase is not desirable. Refactoring is something you do in advance of new development to make that development go smoother. If you're not planning to modify all the code in your codebase, refactoring is going to prove an inefficient use of time.

Some advice in addition to what Sklivvz says:

Separate the code into frequently and infrequently modified sections. Only the frequently modified sections need to be brought fully into the new architecture. Integrate the infrequently modified code with the new architecture using as few changes as possible (or no changes if you can get away with it). Resist the temptation of the full rewrite, it'll cost more than you gain from it. Appreciate that the existing code works, even if it is ugly.

Find out what your refactoring goal is. Do you want to make it easier to get content into the site? Do you have a lot of bugs and want to improve user-perceived quality? Do you instead want to reduce feature development time? Or do you mainly want a better UX? Your architecture should make it easy to refactor code to meet the goals you set. Never forget that the primary beneficiary of your refactoring should be your user/customer/business. Cleaner code is not a goal in and of itself, it's a method to an end, and the end involves a user.

Try to find as many reference architectures as possible and don't be afraid to copy them. Don't reinvent the wheel. If someone else has an architecture that works well for sites like yours, learn from them.

Think about the people management side of things. In my own migration projects the hardest part was making people learn the new ways and stick to them. You'll need reference implementations, and a way of teaching the architecture to everyone on the team (both old and new). To reduce resistance to change, ask for input from everyone on the team before making decisions. Make sure that the new design actually improves things from the developers' personal perspective, and isn't such a big leap that they feel out of their depth.

Title: Starting a coherent architecture in a legacy application

Body:
I have responsibility for a large Asp.Net based website. It is currently a website (not web application), some windows services and a number of class libraries.

The data layer uses a mixture of LLBLGEN  and Linq To LLBGen, as well as a number of instances of legacy inline SQL which have not been refactored.

There are some manager type implementations, but in many cases the application exhibits the Smart UI anti-pattern (i.e. too much business logic in code behind classes)

The site is reasonably high traffic, and performance is fine, but we are growing our development capability to a team of around 10, and increasingly it is clear we need an overarching layered design on top of the existing middleware.

My question is where to start? We have 10 years of code (some of it still really just migrated ASP Classic stuff), many different approaches, and styles.

Refactoring the entire code base is not realistic and, probably not desirable

I know this is not a novel situation, are there any useful ideas or concepts as to how to approach this problem?


问:
What is a good way to familiarize myself with PHP, coming from an ASP.NET background?
Currently, I'm very comfortable with building tools/web apps in an ASP.NET environment. I'm not really looking to leave tbh, as I really like C#, ASP.NET, MVC 3, Visual Studio, etc.

However, right now I know almost nothing about PHP and that seems like a deficiency that I'd like to rectify.

Are there any books (or other learning methods) that would be a good resource to learn PHP? Obviously there are plenty of beginning PHP books, but I am already comfortable with much of what is involved with building a web page, and interested in focusing on PHP itself which might not be compatible with the scope of some beginning PHP books.

I went through the PHP Manual quite a bit, and it doesn't seem to flow as smoothly as might be ideal. Is there a beginning PHP book that would be appropriate? I miss the cohesiveness that most books contain when looking through those samples. There is lots of info more, but it feels more like a reference while coding than a primary learning vehicle.

答:
The best resource out there to learn PHP is the PHP manual. It's extremely well written and well structured, and it's one of the biggest assets of the PHP community. If you are confident with ASP.net, the manual is enough to get you started.

Before you start reading though, you should setup a PHP stack. You can install Apache, PHP and your favorite database (SQLServer is fine) by yourself (it's extremely easy) or you could setup a ready made stack like XAMPP. XAMPP will install:

Apache,

MySQL,

PHP,

The PHP Extension and Application Repository (PEAR)

PERL

OpenSS (via mod_ssl)

SQLite

phpMyAdmin

all in one go (plus some other stuff). One important library it's missing is phpUnit, that obviously will help you with unit testing.

Then you should install an IDE, your obvious choices are Eclipse Classic with the PHP Development Tools (PDT) or Netbeans for PHP. There are a lot of others, but these two I recommend. I use them both, if you can't choose between them Netbeans is a little easier to get the hang of, but you should really evaluate both and decide for yourself which one is better for you - I haven't worked with Visual Studio in a long time and I really don't know which IDE may feel more familiar to you.

When you get over the basics from the manual, you should start thinking of an MVC framework. Again, I will recommend two:

Zend Framework, and

CodeIgniter

Zend Framework is the beast and CodeIgniter is the beauty, if you allow me a silly metaphor. Zend Framework has a steep learning curve, is backed by Zend (the company behind PHP), and you can do almost everything with it. CodeIgniter is a lot easier to get the hang of, has nice documentation for beginners and it's fairly popular. But most of it's codebase is outdated crap, as they used to support PHP4 not so long ago.

For a beginner the obvious choice is CodeIgniter, but don't get stuck with it. Use it as a learning tool and move to Zend Framework as soon as possible. Again there are a lot more MVC frameworks in the PHP world, but these two are the ones I recommend.

As for books, a great non beginner book is PHP Objects, Patterns and Practice. Sitepoint's PHP books are always a delight to read. If you fall in love with PHP you should really consider a subscription to PHP Architect.

Lastly, check out this great discussion on purely technical reasons for PHP as a first choice.

Update: A few more online resources, that mostly target non beginners:

IBM's PHP project resources

Oracle's PHP Developer Center

Zend Developer Zone

and if for some weird reason you want to play around with PHP on IIS instead of Apache, a good starting place is Microsoft's PHP on Windows. PHP on IIS works and is a valid choice especially for a .Net developer, but you should really go with Apache (and MySQL or PostgreSQL instead of SQLServer) to get the full PHP experience and also ensure that your skills are portable to any other popular OS. You don't want to miss out on the joy that is mod_rewrite.

Personal note: There's a lot of hate floating around for PHP, some of it is justified. If you do decide to go for it, you must be extremely critical of the various PHP resources, scripts, libraries you will meet along the way, there's too much crap out there and it's impossible for a beginner to know the difference. PHP's vast popularity can be translated to a very big and helpful community, large marketability of your skills, millions upon millions of blogs, but it can also be translated to a few thousand terabytes of crappy code.


问:
Why is $ in identifier names for so many languages?
A lot of scripting languages like Perl, Awk, Bash, PHP, etc. use a $ sign before identifier names. I've tried to look up why but never had a satisfactory answer.</p>

答:
This appears to originate in BASIC, where the $ suffix indicates a string variable, and was also pronounced as "string". For example, INKEY$ is pronounced "in key string".

But why the dollar sign? Well, $ looks a bit like S for string. And according to Wikipedia:

As the dollar sign is one of the few symbols that is, on one hand, almost universally present in computer character sets, but, on the other hand, rarely needed in their literal meaning within computer software, the $ character has been used on computers for many purposes unrelated to money.

(Appropriately, For a Few Dollars More is on the telly as I type this.)