答:
Why not any other symbol?

A few languages have used other symbols -- old versions of BASIC used a colon instead, for one example.

Ignoring the few exceptions, however, I think there are two primary reasons. The first is that you're simply looking for something unambiguous. In a typical parser, if you run into a serious enough error that you can't continue parsing the current statement, you normally try to get the parser back in sync by just skipping ahead to the statement terminator and re-start the parser from the beginning of the next statement. For that, you want something that won't normally occur anywhere else in the code, and a semicolon happens to be a symbol with little other meaning attached, so it's pretty easy to dedicate it to this purpose.

The second reason is somewhat similar, but aimed more toward people reading/using the code. Again, it comes back to the fact that the actual symbol you use doesn't matter much. There's a substantial advantage in readability to gain from using the symbol your reader is accustomed to seeing for a particular purpose, when and if possible. That doesn't mean that C is the one perfect syntax and everything else should follow it slavishly, but it does mean that enough people are familiar with that style of syntax that a vaguely similar language gains a lot (and loses very little) by following roughly the same syntax where it can.

I'd note that this is much like designing almost any other program. If I write a program that uses windows of some sort, I'll try to just use the native features of the target platform(s). Many of the decisions that embodies will be largely arbitrary, and could be done differently without any major loss of functionality -- but equally, changing them without a substantial gain in functionality just confuses users without accomplishing anything useful. The same basic principles apply to "what should terminate (or separate) statements in a language?" as "what should a scroll bar look like", or "how should a tree control work?" In all these cases, the decision is mostly arbitrary, and uniformity provides a substantial benefit in and of itself.

I'd add that much the same happens throughout many languages, just in ways that most of us are so accustomed to before programming that few people think about it. Why does everybody use "+" to indicate addition, or "-" to indicate subtraction? Because the shape of the symbol doesn't matter much, but everybody agreeing to apply the same meaning to each symbol matters a lot.


问:
Becoming a Better Bug-Fixer
I love being a programmer. There, I said it. However, with that said, I've realized lately that I really can't stand bug-fixing. At all.

In fact, while I'm developing something, my productivity is extremely high. Even when writing unit-tests and doing self testing of my development, I'm generally really productive. I can focus well, and I can get tasks done.

However, when QA time comes around and I'm working on fixing bugs, my inspiration takes a massive nosedive. I have to force myself with pretty extreme measures (you know, high BPM music, excessive amounts of caffeine, etc.) to get anything done. My job is usually involved with stepping into an existing massive project and adding new features or fixing bugs, so I can't exactly tell my employer that I need a couple weeks to write unit tests for all of their code :) In addition, the server technology that we often use is very prohibitive to both unit and integration testing, as it has quite a few Java classloader issues. I'm not completely against bug-fixing, sometimes it can be fun, but it's not fun at all when you have to make minor changes and wait 30 seconds to 3 minutes to be able to see if they worked or not (due to the way the system works).

How can I improve my productivity and motivation when bugfixing? Is this something that most programmers deal with?

答:
Bug fixing is an extremely important skill that you should learn. I read somewhere that, normally one spends 80% of time fixing the 20% of issues in an application.

I believe in learning from mistakes, and bug fixing is an opportunity to learn from others mistakes. You can take it a learning and will help be a better programmer in future. This is the motivation I had when I started fixing a lot bugs and moving forward to re-factoring the code.

ContentLicense: CC BY-SA 3.0

Title: Becoming a Better Bug-Fixer


答:
Personally, I've found it helpful to stop thinking of bugs as 'small things' but rather as big showstoppers that are just as important as huge features even though they just involve changing a few lines of code after hours of debugging. That way, having spend an entire day to kill 3 bug tracker entries is way less depressing (the approach depends a bit on your personal ability to talk yourself into believing it :-).

Maybe it helps to make it a game, for example together with your co-workers (who fixes the most bugs a day? Or, even worse, who did the least number of rebuilds a day?)

Title: Becoming a Better Bug-Fixer

Body:
I love being a programmer. There, I said it. However, with that said, I've realized lately that I really can't stand bug-fixing. At all.

In fact, while I'm developing something, my productivity is extremely high. Even when writing unit-tests and doing self testing of my development, I'm generally really productive. I can focus well, and I can get tasks done.

However, when QA time comes around and I'm working on fixing bugs, my inspiration takes a massive nosedive. I have to force myself with pretty extreme measures (you know, high BPM music, excessive amounts of caffeine, etc.) to get anything done. My job is usually involved with stepping into an existing massive project and adding new features or fixing bugs, so I can't exactly tell my employer that I need a couple weeks to write unit tests for all of their code :) In addition, the server technology that we often use is very prohibitive to both unit and integration testing, as it has quite a few Java classloader issues. I'm not completely against bug-fixing, sometimes it can be fun, but it's not fun at all when you have to make minor changes and wait 30 seconds to 3 minutes to be able to see if they worked or not (due to the way the system works).

How can I improve my productivity and motivation when bugfixing? Is this something that most programmers deal with?


问:
Where is the application of Calculus (of continuous quantities) in Computer Science or programming
I am a Software Engineer professional. I have studied calculus as a core course in my graduation studies. I want to ask question, that what/where is the implementation of calculus in computer science?</p>

答: A developer needs calculus to the extent it is important to the problem domain.  The developers of Twitter don't need any calculus. Developers at Boeing or Airbus need a good understanding of calculus.  </p>


答:
Is your problem debugging or bug fixing?  If you can debug enough to isolate the component that's causing the issue, then look at it as a new development task.

Write some unit tests for just the piece of code that's breaking.
Make sure you have tests validating all of its desired
functionality, plus some that particularly isolate the buggy
behavior.

Write new code that passes all the tests you just wrote.

Replace the old code with the new.

Run some integration tests.  This is where you'll run into your three minute server reboots, but it should be minimized if you did steps 1-3 well.

Voila!

Title: Becoming a Better Bug-Fixer


问:
How to control work of programmers (outsourcers)
Some time ago I decided to outsource web development projects (php coding & design). I've opened small office abroad with manager and couple of programmers and designer. I just started but already have a problem controlling their work.

Some programmers are fast, others work much slower. I pay them fixed salary, so it matters for me if they do their job on time.

When they work from office, I at least have a person responsible for the project to tell if they really worked. But sometimes they work from home and in that case I have no way to know if they really spent that time working on some issue.

Some of my ideas were: controlling amount of code done with svn, strict deadlines, everyday reporting.. But nothing seems perfect to me. It creates even more work from my side.

Can anyone suggest a way of fair judgement on how much really time was spent on actual work? How to stimulate people to work? Maybe create some bonus system if work is done fast? Any idea/experience on this topic would be highly appreciated.

答:
Your only measure should be achievement.

Is the work done?

No? Get another developer.

It is so easy I still don't understand why people try to control other people (impossible to do) while what you should do is stop working with them.

Whether they are outsourced or offshore, the problem is the same. The only difference is the location and the fact that it's harder to try to control someone that is 4000km away.

ContentLicense: CC BY-SA 2.5


答:
It's part of the job, unfortunately. You will have crappy projects and crappy employers (I'm not saying either is the case here, just generalizing).

You can write unit tests against their code.  Sneak it in as you can.  Once you have something you can show to the bosses, you may be able to turn the tide.

Use debugging tools to fix the slowness, use unit tests to test new code and use them to fix existing code's issues as well as breakdown the existing code into smaller pieces.

You can make it a challenge and become a process improvement hero.  And, if it doesn't work, you will have good experience to take to the next employer.

Title: Becoming a Better Bug-Fixer


问:
Javascript naming conventions
I am from Java background and am new to JavaScript. I have noticed many JavaScript methods using single character parameter names, such as in the following example.

```<code>doSomething(a,b,c)
</code>```

I don't like it, but a fellow JavaScript developer convinced me that this is done to reduce the file size, noting that JavaScript files have to be transferred to the browser.

Then I found myself talking to another developer. He showed me the way that Firefox will truncate variable names to load the page faster.  Is this a standard practice for web browsers?

What are the best-practice naming conversions that should be followed when programming in JavaScript? Does identifier length matter, and if so, to what extent?

答:
I worked in JavaScript for a very long time.

We had a naming standard that you had to use Hungarian Notation for all variables.

It seemed to work OK.  I know that there are cases against using that, but it worked well for us.  Especially when you have massive JavaScript files where you need to find stuff.

I would caution against prematurely optimizing.  You are very likely to end up with messy code that doesn't really run much faster at all.

Title: Javascript naming conventions


问:
Software bundle containing LGPL libraries as Java Fat-Jar Archive
At work, we're deploying a software bundle of a Java application (written by us) which has lots of external dependencies, most of them being LGPL and BSD-licensed third-party-libraries distributes as JAR archives.

Currently, we're deploying a test-client of the software which is distributed as a single java fat jar archive, created by the Maven assembly plugin, which does roughly the following:

extract all dependencies

rebundle them as a single jar-archive

All class files are extracted, and then bundled back into a single JAR file with our own application. I realized that also some files get overwritten, mostly LICENSE.txt-files, due to having the same name.

I'm wondering whether this is correct and complies with the LGPL license. What would be a better way to distribute the software? How would this particular package be best organized?

We did not incorporate any source code directly into our source files, nor did we touch the binary files. The source code of the libraries accompanies the whole product. (It is software that is internally used, not deployed to customers or anything, but I guess that does not matter.)

PS: I asked the same question on Stack Overflow, and I was suggested to ask it here.

答: Since you're using Maven, I recommend switching to the shade plugin to build your JAR. It can be configured to automatically handle multiple "standard" license files (see the section on resource transformers), and will warn you if your dependencies have overlapping classes.</p>


答:
Most programmers have to deal with bug-fixing personal issues at some point in their career.

The right sense of person-to-work distance is essential for your motivation. Do not over- or underidentify with your work. If you are overly identifying yourself with your work, problems such as the ones you have described can surface: You might be very reluctant to fix the bugs since you are half of the time blaming yourself. Get some inner distance and find out how you can work on your problem rationally.

Regarding the particular issues on your platform, there are a few ways to mitigate long deploy and test times (and, on the side, yours aren't particularily long).

Firstly, the longer your test time is, the more averse you should be to cargo cult. If you make a change, think about it until you are confident it will fix the bug. Of course, just how confident is subject to the length of your test cycle. But if your test cycles get longer, and long tests can't be avoided, spend more time thinking, and you'll be rewarded and more happy in debugging because it is faster and has the rewarding effect of a good moment of "fiat lux".

Secondly, bias more towards unit tests and less towards integration tests. Remove every point-of-failure from the hard-to-debug platform you can.

Title: Becoming a Better Bug-Fixer


答:
it's not fun at all when you have to make minor changes and wait 30 seconds to 3 minutes to be able to see if they worked or not

That's the real problem here.  You feel unproductive when you have to wait so long for feedback, I know the feeling.  Perhaps it is possible to fake out more services and create better test tools so you can get immediate feedback.

Unit testing legacy code is expensive or can involve dangerous refactorings.  However, creating better test fixtures can let you hand test in seconds compared to minutes and you can get almost the same productivity as working with new unit testable code.

Waiting so long for feedback is boring and demotivating, not the act of fixing bugs itself.

Title: Becoming a Better Bug-Fixer


答:
You will find that the developers themselves are not using short variable names. Whilst developing, they are using meaningful and detailed variable names.

Then, in the build/release process, the code they've written is ran through a minifier/obfuscator with the intention of minimizing the size of the file, as a best practise to speed up a website. This is an optional step if you care that much about performance. Most small websites don't do this.

You, as a developer, should not care about the minification/ obfuscation process; write your code so that it is readable, meaningful, well documented and well structured. Then if you care so much about performance (optional, don't forget!), introduce a minifier/ obfuscator into your release process to minize the code (remove white space, new lines, comments etc) and to obfuscate it (e.g. shorten variable names). A good article which explains obfuscation vs minification can be found here.

Additionally, Desktop FireFox will not truncate variable names period. The truncation of variable names is there to speed up the page download. By the time FireFox gets the file, it has already been downloaded therefore there is no need to do so. Your friend may run a plugin which is doing this; in which case, tell him to uninstall it, because it's useless.

For completion, some (mobile) browsers have the option to use middle-man servers, which intercept the responses of resources you requested, and compress them for you (which could include the minification of JavaScript files). Note that the compression is done on the server (i.e. before you have downloaded the page), hence the potential benefit of downloading a smaller file, rather than in the browser once you have already downloaded the file (as suggested in the question). Such mobile browsers include Opera Mini, and newer versions of Google Chrome (on iOS at least; not sure about Android). For more info, see here.

Title: Javascript naming conventions

Body:
I am from Java background and am new to JavaScript. I have noticed many JavaScript methods using single character parameter names, such as in the following example.

```<code>doSomething(a,b,c)
</code>```

I don't like it, but a fellow JavaScript developer convinced me that this is done to reduce the file size, noting that JavaScript files have to be transferred to the browser.

Then I found myself talking to another developer. He showed me the way that Firefox will truncate variable names to load the page faster.  Is this a standard practice for web browsers?

What are the best-practice naming conversions that should be followed when programming in JavaScript? Does identifier length matter, and if so, to what extent?


答:
Bug fixing can be "awesome" or "tedious". I have some game credits that are entirely due to fixing one single bug - the crash bug that no-one else could fix. But the day-to-day grooming of bugzilla is mind-numbing. Minor bugs are tedious. Major bugs are worthy.

Here's the realization: The fact that you have a giant list of minor bugs is itself one major bug. Its just not a code bug. Its a process or management bug.

Find that bug, and fix it.

Title: Becoming a Better Bug-Fixer


问:
Is obscuring/obfuscating public-facing database ids really a "best practice"?
I've heard people lecture here and there on the internet that it's best practice to obscure public facing database ids in web applications. I suppose they mainly mean in forms and in urls, but I've never read anything more than a mouthful on the subject.

EDIT: Of course, now that I ask this, I find some resources on the subject:

https://stackoverflow.com/questions/2374538/obscuring-database-ids

https://stackoverflow.com/questions/1895685/should-i-obscure-primary-key-values

http://joshua.schachter.org/2007/01/autoincrement.html

These links satisfied some of my curiosity, but the SO posts don't have many votes and aren't necessarily centered around the topic in this context so I'm not sure what to make of it, and some of them claim that the third link is bogus. I'll leave the rest of my post intact:

I understand the differences between obscurity and security, as well as how the two can work together, but I can't imagine why this would be necessary.

Is there any truth to this, is it just paranoia, or is it just totally bogus altogether?

I can think of ways to do it, but of course it adds a lot of complexity to the application code. Under what circumstances would this be useful? If this is something people frequently do, how is it usually deployed? Hashing the identifiers? Something else? It seems like a lot of work for not much extra security. I'm not looking for real solutions, I just want to get an idea of how/why people would do this in the real world.

Is this really considered a "best practice" or is it merely a micro-optimization of little value?

NOTE: I think a few folks might have gotten the wrong idea: I'm not suggesting that difficult-to-guess ids would be the only security mechanism, obviously there would have be the usual access checks. Let's assume those are in place, and that simply knowing the id or hashed id of a record is not enough to grant access.

答:
I will go against the mainstream, and tell you that using a random, long identifier is in my opinion a pretty decent form of security.

It must be made clear to whoever has access to that data that it is as much sensitive as a password. And of course it has the disadvantage that if it goes into the wild it may be harder to change.

But it has a couple of advantages over the usual username and password pair. First, the user has no choice over it, so you can be sure it is essentially impossible to guess. There is no point in designing a perfectly secure site when the administrator choses its first name as password. Second, each item has a different identifier, so if one gets access to one item, this does not help with the other.

Of course, the more layers of security there are, the better. But this method alone can be more secure than a couple of credentials.


答:
This is my take on it:

While "security through obscurity" obviously isn't enough, obscurity can aid security, even if just a little. You have to decide if that little bit of psuedo-security is worth the extra effort it takes to deploy something like this in your application.

There is another reason outside of security I can think of to implement this:

Privacy

Let's say we're dealing with user ids in the url. If Joe's user id is 100 and Bob's user id is 101, it's probably obvious that Joe's account was created first. While this may not matter in most applications, it may matter to some. This is an example of privacy stricly through obscurity, so unless you have a very sophisticated system of obfuscating the user ids, it's might be easy enough to dissolve and figure out if the user with id 3Js9kW3hTs7sa120 has had an account longer than the user with id Q8Hs73kks0hEg.

From the link I referenced:

The first is that given the URL for some object, you can figure out
  the URLs for objects that were created around it. This exposes the
  number of objects in your database to possible competitors or other
  people you might not want having this information (as famously
  demonstrated by the Allies guessing German tank production levels by
  looking at the serial numbers.)

Using an auto-increment id publicly exposes the number of objects in the database, and can expose which ones were created first and which ones are newer. This information can give away the fact that a business is new, or not doing well even. For example: let's say you order a book and your order id is 1. It might be apparent that your order was the first one in the system, which can be unnerving. Let's say you go back and order another and your order id is 9. This gives away the information that only 7 orders were placed in the time frame between your two orders. This might be valuable information to competitors. In this case, the numerical auto-increment id is probably better off obfuscated.

Title: Is obscuring/obfuscating public-facing database ids really a "best practice"?

Body:
I've heard people lecture here and there on the internet that it's best practice to obscure public facing database ids in web applications. I suppose they mainly mean in forms and in urls, but I've never read anything more than a mouthful on the subject.

EDIT: Of course, now that I ask this, I find some resources on the subject:

https://stackoverflow.com/questions/2374538/obscuring-database-ids

https://stackoverflow.com/questions/1895685/should-i-obscure-primary-key-values

http://joshua.schachter.org/2007/01/autoincrement.html

These links satisfied some of my curiosity, but the SO posts don't have many votes and aren't necessarily centered around the topic in this context so I'm not sure what to make of it, and some of them claim that the third link is bogus. I'll leave the rest of my post intact:

I understand the differences between obscurity and security, as well as how the two can work together, but I can't imagine why this would be necessary.

Is there any truth to this, is it just paranoia, or is it just totally bogus altogether?

I can think of ways to do it, but of course it adds a lot of complexity to the application code. Under what circumstances would this be useful? If this is something people frequently do, how is it usually deployed? Hashing the identifiers? Something else? It seems like a lot of work for not much extra security. I'm not looking for real solutions, I just want to get an idea of how/why people would do this in the real world.

Is this really considered a "best practice" or is it merely a micro-optimization of little value?

NOTE: I think a few folks might have gotten the wrong idea: I'm not suggesting that difficult-to-guess ids would be the only security mechanism, obviously there would have be the usual access checks. Let's assume those are in place, and that simply knowing the id or hashed id of a record is not enough to grant access.


问:
Which style to use for unused return parameters in a Python function call
Is there any recommended/generally accepted coding style for handling situations where a function returns a tuple of values but only one of those values is used afterwards (note that this is mostly meant for library functions I can't change -- writing a wrapper around the call is probably a bit of overkill…)?
Instead of doing

```<code>a, b, c = foo()
</code>```

and then just not using b and c, which of the following variants should be preferred (or is there another one?):

Variant 1 (underscore)

```<code>a, _, _ = foo()
</code>```

(which is very clear and simple but might clash with _ = gettext.gettext used in many applications that use translation)

Variant 2 (dummy name)

```<code>a, unused, unused = foo()
</code>```

(not very appealing, I think, same goes for other names like dummy)

Variant 3 (index)

```<code>a = foo()[0]
</code>```

(to me the ()[0] looks un-pythonic…)

答:
Here's a general rule: If only 1 of the returned values is used, why not simply return that 1 value? In case the flag is being called from multiple places, keep a flag for the same and return values as per the flag.

EDIT:

In case I was in your situation, and I hadn't written the function, I'd perhaps go for Variant 2. I'd keep the dummy names there so that the parameters can be used in case need arises. Slicing a list will have a little overhead. Perhaps you can spare a few bytes to receive the unwanted data.

ContentLicense: CC BY-SA 4.0


问:
Is it "normal" for people to not work?
After graduating from college I was hired as a junior programmer a little over a year ago. I quickly noticed that I was degrees of magnitude faster than all the other programmers; this seems to be because I simply don't waste time "in general". The majority of other people however seem to enjoy staring at the ceiling, browsing YouTube, Facebook, and random websites, and in general doing in a day the work I usually do in an hour. I'm 100% sure they would be able to do that work in an hour too if they focused.

I've been quickly promoted to senior developer and more recently to team leader and now I replaced a lot of those people with new hires (still a couple to go). The situation is now more acceptable, but still I think it could be much better.

I can't help but notice though, that everyone seems to behave like this is "normal". All my bosses aren't concerned about this and they too seem to work little to nothing. I always have a very hard time finding them, they arrive much later than they are supposed to and leave early. Obviously there is nothing I can do in this case since they're above me, but is this is the "norm" in all companies, or did I simply end up in a very bad one (this is my first work experience)?

Also, will I "become like them" in a few years?

答:
If you watched me closely you might conclude I am lazy and shiftless.  I do stare at the ceiling a lot, yes.  I sometimes leave the worksite for an hour or so during the regular workday and go take care of personal business -- or just joyride.  But is it me, or is it the job?

As to not getting any "work" accomplished, I find I am incredibly frustrated at not being given much meaningful work to do.  I mostly maintain several existing web-based systems, and while there could be much to do, improving them, updating them, adding new functionality, and so on, because our QA testing shop is so understaffed and overworked (obviously on other projects, not mine), I can't do a blessed thing.  I've proposed a number of medium-impact, low-risk enhancements/fixes to a couple of my systems, but have been told over and over again that we don't have "resources" to QA test them, so I can't develop them.  Meanwhile I sit on my butt and cruise Wikipedia, StackOverflow, and play around with technologies that we are just not going to implement here (such as MVC, Silverlight etc), waiting for something to go wrong with my systems so I can fix them.  It has occurred to me more than once that I should quietly and deliberately break something so I can go in and fix it -- thus keeping management aware that I actually have a function.

I could be actually doing something creative and useful, and I've actually built some useful apps on the side, and got chewed out for my initiative.  I still do it, but I have to take pains to keep it a secret.  And I can't put it into production, obviously enough.

It's a pleasant place to work, all in all, and my job is fairly secure, but I am getting bored and frustrated.  I am six years from retirement and while a bit superannuated, I remain close to the cutting edge technologically and plan to code until I die.  And I've killed another twenty minutes of my life (and my employer's time!) adding this answer to the question above; and it doesn't matter.

Title: Is it "normal" for people to not work?


答:
I'm a non-Python programmer, but to me the third variant makes the most sense.

In variant 3 you are absolutely clear which values your are interested in dealing with.  In variant 1 and 2, you are assigning the values back to variables, and thus, they can be used. You may have named them obscurely, but poor naming isn't really a solution to any problem.

Aside from clarity, why would you want to assign unused values to a slot in memory (as in variants 1 and 2)? This would be a poor solution in terms of memory management.

Title: Which style to use for unused return parameters in a Python function call

Body:
Is there any recommended/generally accepted coding style for handling situations where a function returns a tuple of values but only one of those values is used afterwards (note that this is mostly meant for library functions I can't change -- writing a wrapper around the call is probably a bit of overkill…)?
Instead of doing

```<code>a, b, c = foo()
</code>```

and then just not using b and c, which of the following variants should be preferred (or is there another one?):

Variant 1 (underscore)

```<code>a, _, _ = foo()
</code>```

(which is very clear and simple but might clash with _ = gettext.gettext used in many applications that use translation)

Variant 2 (dummy name)

```<code>a, unused, unused = foo()
</code>```

(not very appealing, I think, same goes for other names like dummy)

Variant 3 (index)

```<code>a = foo()[0]
</code>```

(to me the ()[0] looks un-pythonic…)


答:
One thing I have found among colleagues and acquantances who are good "debuggers/bug fixers/problem solvers" is that they generally like to solve puzzles. That might mean crossword puzzles, number games (like Sudoku), and logic puzzles, etc...

So one way you might become a better bug fixer would be to spend some time working on your problem solving or puzzle solving skills.

Here is a Wikipedia link that might be a good starting point for things to help you to be a better problem solver.

Mind you, some people are just better at problem solving, or they just enjoy it more. Some people don't like it at all, which makes it hard to force yourself to do - but make no mistake - if you force yourself to learn to be a puzzle solver it will make it easier to be a good bug fixer in the future.

Title: Becoming a Better Bug-Fixer


问:
How do you manage feature requests and software changes?
I am a Software Engineer and over the past few years I have become the de-facto software project manager simply because there isn't one. So to keep our sanity in the R&D/Engineering department, customers have become accustomed to coming to me with their requests. I have no experience in this realm so it is my first time acting as a project manager for software projects. I have managed other things but not software.

So, how do you manage software projects and mark priorities? Requests come in at infrequent intervals so we very well could be working on something for someone else and then another person comes in with a "rush" job that needs working on. Is it easier to just say First Come, First Serve or is it the person with the most money?

答: The company I work for uses two main applications, a web based tool called JIRA to handle the project related aspects and our help desk system to handle the change request via it's rfc functionality</p>


答:
Maybe you should look at Brian Hayes' Debugging Myself, an article that appeared in American Scientist in 1995.  You could take steps (like habitual use of Yoda Conditions) to reduce or eliminate the most hated kinds of bugs you produce.

I am of the opinion that debugging is a skill different than programming, although related. In particular, debugging multi-threaded programs is almost entirely different than writing them.

Title: Becoming a Better Bug-Fixer


问:
Converting mysql and SQLServer tables quickly in an update utility
The requirements are to take an existing list of identical tables (AAA0001 - AAA9999) which generally don't meed our current requirements and need to be swapped out with three tables (XXX0001-XXX999, YYY0001-YYY999 and ZZZ0001-ZZZ999).

Currently, the guy who is programming this update which is supposed to take place on our clients machines who run both mysql and microsoft SQL Server is running select and insert queries which is bound to make the next update the slowest and most painful in the history of our product.

I'd think we could so something faster by dumping the tables to a database, doing some string manipulation and undumping the database.

However, we've never used any database connectors besides ODBC for our program and don't necessarily have the faculties to do both a mysql and a SQLServer dump (unless it's easy).

So, what's the speediest way to dump and undump rows over ODBC?  If there is no speedy way what's the safest and easiest to implement alternative?

We use Delphi XE2 Enterprise, if anyone has any 3rd party DB tools or knows any shortcuts.  We've never used datasnap, as we didn't have the "good version" of Delphi until we updated to XE2, so I'm clueless as to whether it's got this functionality.

答:
I would do this directly on the SQL server..

Restore the Source DB onto the Target DB Server
Then Create a bunch of Insert Statements

```<code>INSERT INTO TargetDb.dbo.XXX0001 ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM SourceDb.dbo.AAA0001
--
INSERT INTO TargetDb.dbo.XXX0001 ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM SourceDb.dbo.AAA0002
--
INSERT INTO TargetDb.XXX0001 ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM SourceDb.dbo.AAA0003
</code>```

OR
Use The SQL Server import Utility

Body:
I would do this directly on the SQL server..

Restore the Source DB onto the Target DB Server
Then Create a bunch of Insert Statements

INSERT INTO TargetDb.dbo.XXX0001 ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM SourceDb.dbo.AAA0001
--
INSERT INTO TargetDb.dbo.XXX0001 ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM SourceDb.dbo.AAA0002
--
INSERT INTO TargetDb.XXX0001 ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM SourceDb.dbo.AAA0003

OR
Use The SQL Server import Utility


答:
Using the underscore for unused variables is definitely acceptable. Be warned though, in some codebases it's not an option as that identifier is reserved as shorthand for gettext. This is the most frequent objection to this style (though it's not an issue for the majority as far as I can judge). I'd still recommend it, and always use it myself.

Names like dummy or unused tend to irritate me personally, and I don't see them terribly often (in Python, that is - I know a Delphi codebase which uses dummy liberally, and it has also leaked into scripts associated with the program in question). I'd advice you against it.

Just extracting one item from the returned tuple is okay too. It also saves some hassle with getting the number of unused values right. Note though that it's has two potential downsides:

It doesn't blow up if the number of values is different from what you expect. This may be useful to detect mixups and typos.

It only works when the return value is a sequence (that's mostly tuples and lists, but let's stay general). Offhand, I know one class in my code (a 2D vector) that is iterable and yields a constant number of values (and thus can be used in unpacking assignments), but is not indexable.


问:
Why are statements in many programming languages terminated by semicolons?
Is there a reason that a semi-colon was chosen as a line terminator instead of a different symbol?

I want to know the history behind this decision, and hope the answers will lead to insights that may influence future decisions.

答:
It was my understanding that it was chosen because there was a need for an explicit statement-terminator other than a carriage-return/new-line. Back in the days of 80-column screens, actually having a single line of code wrap across multiple lines was common enough that using \r or \n for the statement terminator would not work.

Semicolons were just convenient because they're not used in logic/math statements. As such, they don't conflict with the actual content of the statements to any significant extent.

Personally, I think the continuing use of the semicolon, together with style requirements to keep lines under 80 characters, is frankly stupid and anachronistic. Languages like python have extensively demonstrated that you can write easy to understand, concise code more easily without them. Also, if you have issues with lines that are longer then 80 chars, you need a bigger monitor.


答:
It has a slight learning curve but SQL Server Integration Services (SSIS) is built for doing exactly what you want and it does it quite quickly too. It supports straight data dumps and even data transformation using a "pipeline" approach to and from SQL Server and almost any other data source you can throw at it.

Rhino ETL is another tool that couples the speed and power of SSIS with a more code-friendly approach to ETL.

Title: Converting mysql and SQLServer tables quickly in an update utility

Body:
The requirements are to take an existing list of identical tables (AAA0001 - AAA9999) which generally don't meed our current requirements and need to be swapped out with three tables (XXX0001-XXX999, YYY0001-YYY999 and ZZZ0001-ZZZ999).

Currently, the guy who is programming this update which is supposed to take place on our clients machines who run both mysql and microsoft SQL Server is running select and insert queries which is bound to make the next update the slowest and most painful in the history of our product.

I'd think we could so something faster by dumping the tables to a database, doing some string manipulation and undumping the database.

However, we've never used any database connectors besides ODBC for our program and don't necessarily have the faculties to do both a mysql and a SQLServer dump (unless it's easy).

So, what's the speediest way to dump and undump rows over ODBC?  If there is no speedy way what's the safest and easiest to implement alternative?

We use Delphi XE2 Enterprise, if anyone has any 3rd party DB tools or knows any shortcuts.  We've never used datasnap, as we didn't have the "good version" of Delphi until we updated to XE2, so I'm clueless as to whether it's got this functionality.


答:
The fastest way would be to use set-based operations on the server using odbc as a simple SQL command pass-through. Would work something like:

1) Run SQL DDL to create the new table

2) Run sql command to SELECT from the old table INTO the new table with required data massaging.

Doing anything row-by-row on the client-side will be orders of maginitude slower than this sort of approach but it has some advantages. Especially if the data transformation step gets complex.


答: You should not be measuring the productivity of developers - the manager should be doing that instead of you, because he's there and you are not. </p>

Title: How to control work of programmers (outsourcers)

Body:
Some time ago I decided to outsource web development projects (php coding & design). I've opened small office abroad with manager and couple of programmers and designer. I just started but already have a problem controlling their work.

Some programmers are fast, others work much slower. I pay them fixed salary, so it matters for me if they do their job on time.

When they work from office, I at least have a person responsible for the project to tell if they really worked. But sometimes they work from home and in that case I have no way to know if they really spent that time working on some issue.

Some of my ideas were: controlling amount of code done with svn, strict deadlines, everyday reporting.. But nothing seems perfect to me. It creates even more work from my side.

Can anyone suggest a way of fair judgement on how much really time was spent on actual work? How to stimulate people to work? Maybe create some bonus system if work is done fast? Any idea/experience on this topic would be highly appreciated.


问:
How to minimize typos when you code?
I make a lot of typing mistakes when I program. I have a good keyboard writing speed but I try to write faster and in the process end up making typos.

I want to type faster, but make less errors. Can I do something to improve the situation?

答:
One trick I adopted a long time ago involves testing variables for equality in 'C' and other languages that use '==' to test for equality and '=' for assignment.

I always used to write something like:

```<code> if ( X == 10 ) { ....
</code>```

and so whenever I'd miss a '=' and accidently write:

```<code> if ( x = 10 ) { .....
</code>```

I'd be ferschnoggled for a while. The condition is true, the statement compiles & runs, the variable gets changed when I ddin't want it to be, etc. Then somebody told me to write the constant first! ex:

```<code> if ( 10 == x ) { ....
</code>```

That way, when you forget to type a '=', the compiler tells you you're being stupid!

Title: How to minimize typos when you code?

Body:
One trick I adopted a long time ago involves testing variables for equality in 'C' and other languages that use '==' to test for equality and '=' for assignment.

I always used to write something like:

 if ( X == 10 ) { ....

and so whenever I'd miss a '=' and accidently write:

 if ( x = 10 ) { .....

I'd be ferschnoggled for a while. The condition is true, the statement compiles & runs, the variable gets changed when I ddin't want it to be, etc. Then somebody told me to write the constant first! ex:

 if ( 10 == x ) { ....

That way, when you forget to type a '=', the compiler tells you you're being stupid!


问:
Giving variables default values vs. treating accessing an undefined variable as an error
Having messed around with several scripting languages and being a bit of a linguist, there seems to be a way to divide dynamically typed languages into two groups: languages that give variables a default value, and languages that treat accessing an up-to-now unused variable an error.

For instance, consider this code:

```<code>print(hi)
</code>```

In Lua, it prints nil

In PHP (with a semicolon and $), it prints nothing

In Perl (with a semicolon and $), it prints nothing (but using say yields an error)

However,

In Python it throws a NameError

In Ruby, it throws a NameError (looks like Ruby ripped off Python's name for it)

In Javascript, it throws a ReferenceError

In Lisp, some type of error occurs that takes me to a debugger (I'm just learning Lisp now so I don't know what to call it)

Additionally, these languages behave differently when indexing an hash map, a similar operation, and they again fall into two camps (and when I say 'nothing' I mean that language's representation of nothing):

Lua returns nothing

PHP returns nothing

Ruby returns nothing

Perl returns nothing

Lisp returns nothing

Javascript returns nothing

But

Python throws a KeyError

So I am wondering what the comparative advantages and disadvantages are for a language to make accessing an undefined variable an error or just return a default value, and also what decisions would lead a language designer to choose one path or the other.

答:
Well, one thing to keep in mind is that it's harder to debug a misspelled variable or similar error if you do not have an error. Especially if you have to declare variables somehow (like with a define or var), chances are that using an undeclared variable is an error, so signalling it as such is probably the right thing to do.

However, there are also times when having it be some undefined value also makes sense. For example, in JavaScript accessing an argument that wasn't passed in is not an error:

```<code>(function (foo) {
  alert(foo)
})()// alerts 'undefined'
</code>```

This also makes sense--while a global variable is something the programmer has to define, an argument can be anything somebody else passes into the function. Now, these cases are not 100% analogous, but it's something to keep in mind.

As for hashes it's a different story. Depending on the language, there will be many times you're dealing with a hash that wasn't yours. I think it's completely reasonable to expect a hash only containing some of the keys you need to be passed in as an argument to a fucntion, say, so letting you access keys not in the hash makes sense. Again borrowing from JavaScript, this would let us write code like:

```<code>function (options) {
  var color = options.color || "white",
      font  = options.font  || "palatino"
  ...
}
</code>```

Since there are places where it's completely reasonable to access a key that was not set, I think making it return some value is better than signalling an error. Since the programmer did not have to define the hash himself--unlike local variables--this is more akin to the arguments of a function than local variables.

Also note that some of those languages have mechanisms for handling missing keys in a hash some special way. You may want to also provide some mechanism to let the programmer specify how these are handled, so that if they don't like your default behavior they can change it.

So, in summary: I think using an undeclared variable should be an error while accessing an undeclared field in a hash should not.

Body:
Well, one thing to keep in mind is that it's harder to debug a misspelled variable or similar error if you do not have an error. Especially if you have to declare variables somehow (like with a define or var), chances are that using an undeclared variable is an error, so signalling it as such is probably the right thing to do.

However, there are also times when having it be some undefined value also makes sense. For example, in JavaScript accessing an argument that wasn't passed in is not an error:

(function (foo) {
  alert(foo)
})()// alerts 'undefined'

This also makes sense--while a global variable is something the programmer has to define, an argument can be anything somebody else passes into the function. Now, these cases are not 100% analogous, but it's something to keep in mind.

As for hashes it's a different story. Depending on the language, there will be many times you're dealing with a hash that wasn't yours. I think it's completely reasonable to expect a hash only containing some of the keys you need to be passed in as an argument to a fucntion, say, so letting you access keys not in the hash makes sense. Again borrowing from JavaScript, this would let us write code like:

function (options) {
  var color = options.color || "white",
      font  = options.font  || "palatino"
  ...
}

Since there are places where it's completely reasonable to access a key that was not set, I think making it return some value is better than signalling an error. Since the programmer did not have to define the hash himself--unlike local variables--this is more akin to the arguments of a function than local variables.

Also note that some of those languages have mechanisms for handling missing keys in a hash some special way. You may want to also provide some mechanism to let the programmer specify how these are handled, so that if they don't like your default behavior they can change it.

So, in summary: I think using an undeclared variable should be an error while accessing an undeclared field in a hash should not.


问:
Is there evidence that developers working remotely are less productive then when they work onsite?
So I was speaking to one of the folks I work with here a few days ago, and they were complaining that their company no longer allows workers to work remotely at all any more due to the decrease in productivity. As someone that has heard this excuse used for justifying onsite only staffing in my search for remote opportunities, I'm wondering if there's any empirical evidence that confirms this at all or if I and others that I know in the industry are being told a tale.</p>

答:
No.

For a very simple reason: you can't test it.

Let's say you can evaluate productivity, and give a number (by the way, how do you do it?). Now how do you create a situation where a developer will be in the exact same circumstances, remotely in a part of the test, on-site in another part?

Even if you succeed in doing such a test, what it will show? How would you ever apply it in practice?

There are too many factors to take in account. For example:

Is it stressful to commute? If you have to spend an hour in jams or in a noisy bus/underground, your productivity will decrease.

Is it stressful to be among other people? Personally, I find it much more comfortable to be alone, to know that nobody will enter in my room, etc. But it's different for some other developers.

Are you distracted a lot if you're alone? I'm not, but there are some people who can't work at home, just because they find themselves watching YouTube for two hours before starting to do what they have to do, and when they will finally start their daily work, they will remember that they must call their dentist to make an appointment, etc.

Is 9 AM. - 7 PM. the best shift for you? I know that if I have to do something creative, I have to sleep until evening, and work during the night. For a non-creative, technical work, my best shift is different. If I work at home, I have this flexibility which allows me to increase the overall productivity. On the other hand, some other developers may find this unproductive, because they will, for example, stay for 20 hours, trying to solve a bug in a product, and instead, introducing even more bugs, because they are tired.

etc.

Here are two examples from daily life. The first one is mine, the second one comes from my colleague.

Example 1:

I live alone, and I don't have pets at home. There is no noise around me (the street is too small so there are just neighbor cars). I have a fast computer with an SSD, two large screens, the newest software, a keyboard I love, etc. I don't answer my phone, so customers learnt that it's not a good idea to call me when they need something.

Recently, I was asked to work for a customer in his own company. It was a noisy, crowded place. I was in an open-space, with phones ringing around. I had an old laptop with a small screen, which I used to connect through Remote Desktop to another computer, from which I connected through another Remote Desktop into a third computer. The software was old. The internet connection was slow.

Guess in which case I was more productive.

Example 2:

My colleague has a family and a small child. He has a separate room where he can work, but often he must take care of a child, or answer a call of a customer, etc. His house has some noisy neighbors (with a dog barking all the time) and a large road nearby. He works on a new computer with pretty decent software, but cannot afford an SSD or a license of Visual Studio Ultimate. He has a very slow internet connection (and cannot have a faster one in his area).

Recently, he was asked to work on-site for a customer who has 10/12 on Joel Test. He had a separate room, very quiet. No distractions. Fast computer. Fiber optic internet.

Guess in which case he was more productive.


问:
What did Ruby do right (or was it Rails)?
Most programming languages have some design decisions that influence their usage and applicability.

For example:

Python focused on maintainability/readability of code and had indentation be a part of the language itself.

Java's intention was to be cross platform OOP 'easier' and 'friendlier' than C++

Objective-C was built as an OO wrapper around C not knowing the future of C++ at the time

Erlang is designed for highly fault tolerant and concurrent systems

PHP designed for handling dynamic creation of web pages

CoffeeScript designed to expose the good parts of Javascript and adding OOP syntactical sugar and hiding the nuances (globals etc.) of JS 'behind the scenes' etc.

Each programming language tried to exploit and capitalize on a particular niche IMHO. The above are my perspectives on what were the founding principles of the programming languages and that governed their evolution and widespread adoptability. Of course, there are many more, but the list is only intended as an example

However, I've struggled to understand the founding principles on which Ruby is based and its growing popularity. What were the founding principles of Ruby that makes it popular today? Or is it the genius of one man who designed the Rails framework? If the latter was it that Ruby made the designing of Rails better/easier/faster? In what sense?

The most commonly cited reason as per its creator is '...wanted a fun weakly typed programming language' - I don't see that as a reason for creating a new programming language altogether! Programming is sheer fun IMHO irrespective of the language (each language has some bad parts, but one either gets around it or lives with it).

So what niche did (or does) Ruby exploit that isn't exploited by the current languages? What is the 'strong point' (USP) of Ruby that has led to its widespread adoptability? What did Ruby do that wasn't done before (or was extremely difficult)?

I'm not a Ruby programmer, but just a Ruby noob and hence the confusion.

Disclaimer: This is NOT a flame war and I'm not looking for Ruby vs Programming language type of answers. I am looking for the design decisions on which Ruby is based that has led to widespread adoption. What niche does Ruby satisfy to have become popular or is that purely attributed to Rails?

答:
First, Ruby is a "current language".  Maybe you mean "Languages that were popular when Ruby was created in 1995."

I like Ruby for the same reasons I liked Perl:

It's powerful and expressive.  I can write about one line of Ruby code instead of five lines of Java or C++.  There is no repetition that can't be factored out with minimal fuss.

It's dynamic.  Methods and properties can be created at run-time, so I can wrap objects around externally defined things, like database tables, without duplicating the definition of those things, and without rebuilding the application.

There is an excellent book on the language (Programming Ruby) that is both readable and comprehensive.

There is a single repository for public-domain packages, and a convenient command-line interface to the repository.

But I like Ruby better than Perl because it's more readable.

There are numerous pages comparing Ruby with Python.  I like them both.  I prefer Ruby, but I have limited experience with Python.


答:
Unless someone can identify what you need to get done and when, where you do it and at what time, won't matter.

If there is evidence to support it, that can be a start, but it doesn't really matter. First there has to be a way to measure productivity; that's not easy and is a major topic of debate. A given worker can test both environments. Obviously if you know you're being tested, you may work harder in the desired situation.

I've usually started working in the office, and then was allowed some flexibility after proving myself (And moving away from the city but keeping my job.). I think I end up working more at home because I cut nearly 2 hours out of my commute.

Call in sick (stomach flu - need to stay close to toilet), but work from home and get a lot done. That's one way to make your arguement. Make sure your supervisor is enlightened about your increased productivity.

I have to go now, my dog needs to go out ;)

Title: Is there evidence that developers working remotely are less productive then when they work onsite?

Body: So I was speaking to one of the folks I work with here a few days ago, and they were complaining that their company no longer allows workers to work remotely at all any more due to the decrease in productivity. As someone that has heard this excuse used for justifying onsite only staffing in my search for remote opportunities, I'm wondering if there's any empirical evidence that confirms this at all or if I and others that I know in the industry are being told a tale.</p>


答: It is harder to tell if an employee is being productive while working remotely and some employees will take advantage of that to be less productive. Others may prefer to code in their underwear and be even more productive. There are so many different factors and so many different personal motivations that coming up with any universal truth in this matter is impossible since there is no commonality between most cases.</p>


答: What those companies are really saying is that they don't trust developers to work at home. Or that if they allow one to work from home they have to allow everybody and they don't trust everybody.


答:
All it takes is one person who goofs off when working remotely to kill it for everyone in many companies. Are there people who are more efficient working remotely, yes.

Are there people who get less done and perpetually miss deadlines that people in the office are easily able to meet, yes. There are people who are never on IM and don't respond to emails in a timely manner and don't answer their phone (OK is the boss going to think you are working when he can't get in contact with you for hours? No.) and who never commit anything after about noon. And who miss every deadline with some excuse but never tell you in advance that things are not progressing as they should be. And who take 4 weeks to deliver the same type of product that in house developers (and sometimes ones of a lower skill level) can deliver in a week or that they themselves delived in that time frame before starting to work from home. Indeed I have worked with these people and they are now no longer allowed to work remotely. Luckily for several other people (who live out of town) management didn't decide to punish everyone becasue a few abused it.

Remote workers are not visible to management, they have to be more aware of keeping management appraised of what they are doing and what issues they have than they have to be in the office. When they don't and simultaneously fail to deliver a quality product, then remote working gets a bad name. Managers don't often see the 20 people doing it right when they are trying to fix the one going bad. And it is often perceived as less risky for them to remove a benefit from everyone than only the ones abusing it.

What I am saying is they don't care if there is empirical evidence, if they have perceived a local situation where it wasn't working.


问:
Staying alert and awake while coding
What methods do you use to stay awake and alert while working?

Personally I drink coffee non stop throughout the day.  But I've also heard of this thing called exercise that should help too.  Does anyone else have tips and tricks to stay more awake and alert while working?  Redbull? Maybe a magic pill that won't require me to sleep?

答:
Having Fun - Nothing reinvigorates me mentally like having fun! Grab a couple coworkers/friends, and go toss a football around for 15 minutes, and play a video game, or whatever is fun for you. You'll feel completely recharged.

Move Around - I work from home, so when I'm feeling sluggish I put on my headphones, and do some house cleaning. It gets my blood flowing again, and gives my brain a chance to rest.

And yes, there are some magic pills that are prevalent in the IT industry (And among college students), but they're illegal without a prescription. So I'm not going to recommend them.

Title: Staying alert and awake while coding


问:
How to deal with frequent requirements changes?
I'm dealing with pretty stressful (in my opinion) situation in my current work place.

We've started developing new project, get some requirements, implemented it and then show to someone you can call a 'business advisor' (person who knows business requirements but will not use the program). That person is supposed to evaluate application from customers point of view, test it etc.

Here how the 'process' looks:

business advisor talks in the evening with my boss for hour or two on windows messenger

the next day I receive email with copy of that conversation. I am supposed to choose tasks from that, check reported bugs (which often aren't bugs, just poor testing and forgetting about past establishments)

I implement changes, implementation gets accepted and then in a week or two it turns out that isn't want they want (they talked with some potential client that have seen software for 5 minutes and he suggested changes) - I have to do new changes

Don't get me wrong, I understand that sometimes requirements change. What upsets me is how often the change occur in my workplace and how easy for 'management' is two give new requirements or sometimes fundamental changes to existing features.

At the same we working on tight deadlines and I have impression that instead of going forward with our software we're running circles.

I seek advise from you how to deal with this situation? Is this normal situation and I'm just hypersensitive about it?

答:
In the real world, requirements change routinely.  On the plus side, you find out about it before you finish building the software and ship it out - you have a tight feedback cycle from the direct user of the software, which is actually great.

It seems like the biggest problem here is the very ad-hoc way that change is managed.  You have what agile / Scrum consider a "product owner", who gives feedback, but the process is poorly documented, and poorly thought out.

You probably want to look at the models in Scrum, and their view of what an effective product owner is, to help inform your next steps.

So, instead of having this ad-hoc process, aim to move to a world where you have a closer and more useful relationship with the "business advisor", and where everyone is on the same page about the outcomes of the changes they are discussing.


问:
Looking for a better Factory pattern (Java)
After doing a rough sketch of a high level object model, I am doing iterative TDD, and letting the other objects emerge as a refactoring of the code (as it increases in complexity). (That whole approach may be a discussion/argument for another day.)

In any case, I am at the point where I am looking to refactor code blocks currently in an if-else blocks into separate objects. This is because there is another value combination which creates new set of logical sub-branches.

To be more specific, this is a trading system feature, where buy orders have different behavior than sell orders. Responses to the orders have a numeric indicator field which describes some event that occurred (e.g. fill, cancel). The combination of this numeric indicator field plus whether it is a buy or sell, require different processing buy the code.

Creating a family of objects to separate the code for the unique handling each of the combinations of the 2 fields seems like a good choice at this point.  The way I would normally do this, is to create some Factory object which when called with the 2 relevant parameters (indicator, buysell), would return the correct subclass of the object. Some times I do this pattern with a map, which allows to look up a live instance (or constructor to use via reflection), and sometimes I just hard code the cases in the Factory class.

So - for some reason this feels like not good design (e.g. one object which knows all the subclasses of an interface or parent object), and a bit clumsy.

Is there a better pattern for solving this kind of problem?  And if this factory method approach makes sense, can anyone suggest a nicer design?

答:
```<code>> feels like not good design ... one object which knows
> all the subclasses of an interface or parent object
</code>```

I agree with your feeling - this violates the open closed principle: every time you implement a new handler you have to change the factory.

One possible solution is to inverse the dependencies:

Each instance registeres at the factory with its specefic parameters. now ever class knows the factory.

Body:
> feels like not good design ... one object which knows
> all the subclasses of an interface or parent object

I agree with your feeling - this violates the open closed principle: every time you implement a new handler you have to change the factory.

One possible solution is to inverse the dependencies:

Each instance registeres at the factory with its specefic parameters. now ever class knows the factory.


答:
A central factory sounds like a good idea to me, as it avoids having the logic of which object to choose spread over the code.  The remaining issue I understand needs to solved is how to avoid this factory class knowing about all the derived classes.  The way I would usually solve this is by having the factory class be a registry of types, by which I mean it knows how to give out the right type based on querying a map of objects that are fed to it by other code.

You could add to your abstapract base class for a trade some functions allowing the factory to ask for which (indicator, buy sell) combination it handles.  Then when each type is registered with the factory, it calls these and adds the combination as the key to the map and the registered instance as a prototype object.  Then for each request it looks the parameters up in the map and clones the prototype object.

The registration could either be done in some setup code, which would then know about all the objects, or by several blocks of code each of which knew about a few of the sub types.

Title: Looking for a better Factory pattern (Java)

Body:
After doing a rough sketch of a high level object model, I am doing iterative TDD, and letting the other objects emerge as a refactoring of the code (as it increases in complexity). (That whole approach may be a discussion/argument for another day.)

In any case, I am at the point where I am looking to refactor code blocks currently in an if-else blocks into separate objects. This is because there is another value combination which creates new set of logical sub-branches.

To be more specific, this is a trading system feature, where buy orders have different behavior than sell orders. Responses to the orders have a numeric indicator field which describes some event that occurred (e.g. fill, cancel). The combination of this numeric indicator field plus whether it is a buy or sell, require different processing buy the code.

Creating a family of objects to separate the code for the unique handling each of the combinations of the 2 fields seems like a good choice at this point.  The way I would normally do this, is to create some Factory object which when called with the 2 relevant parameters (indicator, buysell), would return the correct subclass of the object. Some times I do this pattern with a map, which allows to look up a live instance (or constructor to use via reflection), and sometimes I just hard code the cases in the Factory class.

So - for some reason this feels like not good design (e.g. one object which knows all the subclasses of an interface or parent object), and a bit clumsy.

Is there a better pattern for solving this kind of problem?  And if this factory method approach makes sense, can anyone suggest a nicer design?


答:
If at all possible, take the conversation you're emailed and turn it into a requirements document. List the tasks that you can glean from it and order them by what you perceive to be the priority and assign an estimate to each. Then ask which features they want for the next release.

Basically, force some kind of feedback loop where the management is aware what is it that you're going to build. Write your own requirements documents until such time as they get the message.

Story Cards

I think your situation is well suited to introducing user stories. They're really helpful in providing an ongoing, interactive way for your manager to set priorities and he can even throw them away when he comes back to the idea a week later and realises it's not workable.

Title: How to deal with frequent requirements changes?

Body:
I'm dealing with pretty stressful (in my opinion) situation in my current work place.

We've started developing new project, get some requirements, implemented it and then show to someone you can call a 'business advisor' (person who knows business requirements but will not use the program). That person is supposed to evaluate application from customers point of view, test it etc.

Here how the 'process' looks:

business advisor talks in the evening with my boss for hour or two on windows messenger

the next day I receive email with copy of that conversation. I am supposed to choose tasks from that, check reported bugs (which often aren't bugs, just poor testing and forgetting about past establishments)

I implement changes, implementation gets accepted and then in a week or two it turns out that isn't want they want (they talked with some potential client that have seen software for 5 minutes and he suggested changes) - I have to do new changes

Don't get me wrong, I understand that sometimes requirements change. What upsets me is how often the change occur in my workplace and how easy for 'management' is two give new requirements or sometimes fundamental changes to existing features.

At the same we working on tight deadlines and I have impression that instead of going forward with our software we're running circles.

I seek advise from you how to deal with this situation? Is this normal situation and I'm just hypersensitive about it?


问:
How to read thousands lines of code without any documentation?
Previously I was searching for a good TimeLine control for a WPF project. I found an answer in Here which direct me to this CodePlex project.

Now I want to change code to feed my culture needs. But there are some mismatches!

My question is:

How you interact with such thousands lines of code?

EDIT:

Any shortcut will be great!

答:
Before you refactor anything write tests. Lots of tests. Very specific tests to small blocks of code that are at least callable, as it'll depend on how your inherited mess is written.

The advantage to writing tests to begin with is that you need to have some kind of understanding of the code before you can test it, so every test you write will hopefully be a little bit of knowledge gained. You can also heavily comment the tests with your assumptions alongside the assertions.

By doing it test first, you don't run the risk of altering something in the code that has knock-on effects you can't know about. You'll also have a safety net when you do come to refactor the code.


答:
Sounds fine to me.

BTW, those objects you are creating in your factories are called strategies. Determining the concrete implementation of your strategy sounds like a good use case for a factory to me. I never like that kind of if/else code so hiding it away in a factory makes it nicer for all the client code that wants to use the strategies.

Like you say, you're using TDD/iterative design so if a deficiency in the design is determined at any point, improve it then.


问:
Why is the Flyweight Pattern practical?
I was reading up on design patterns, to better my understandings of ones I know and reveal ones I didn't. One of the last ones I looks at was the Flyweight Pattern. It preaches about shared common function, and I understand this. Keeping with the game example (in the link), sharing functions for units in an RTS I'm sure would save on memory. But would this not sacrifice a great deal of [speed] performance?

Keeping with the RTS theme, suppose you have 300 units on the field, all sharing the same run function, would this not be an asynchronous nightmare? And if one was do perform this in-line (via maybe a step/render style engine), would this not bog the the CPU?

答:
Just because code is shared over threads doesn't mean that it is not thread safe. Only when threads share mutable state does it need to be synchronized; note that code is immutable.

also the code for each function is stored once in memory (barring optimizations) even if there are hundreds of objects and can be used by multiple threads at the same time as long as the data it acts upon is different.

Title: Why is the Flyweight Pattern practical?


答:
I guess Ruby took off for many reasons:

The Rails framework. Rails assembled together many useful patterns to ease the development of web applications and boosts developer's productivity. Compare this to Java's verbose and tedious web development and the "one man show" .NET platform. Creating weblog web applications in minutes was a jaw dropping.

You can see the "Rails effects" on many new JVM web frameworks like Grails, Play! and Spring Roo.

Success stories like Twitter and Github. Startups needs to hit the market as soon as possible and with Rails, this is possible. Success stories were an evidence.

Ruby programming language itself is beautiful, powerful and expressive. IMHO, Ruby is the secret sauce of Rails success.

Look at the beauty of Cucumber and Sinatra, the beauty of DSLs done right.

Eager and brave community that isn't afraid to experiment and innovate.

(Personal opinion and may not be vital reason) It is created in Japan. Nothing beats the image of "Made in Japan".

To me, learning programming languages created in different countries is the same as meeting new people. It is fun and educative.

Ruby/Japan, OCaml/France, Lua/Brazil, Lisp/Mars :)

Title: What did Ruby do right (or was it Rails)?

Body:
Most programming languages have some design decisions that influence their usage and applicability.

For example:

Python focused on maintainability/readability of code and had indentation be a part of the language itself.

Java's intention was to be cross platform OOP 'easier' and 'friendlier' than C++

Objective-C was built as an OO wrapper around C not knowing the future of C++ at the time

Erlang is designed for highly fault tolerant and concurrent systems

PHP designed for handling dynamic creation of web pages

CoffeeScript designed to expose the good parts of Javascript and adding OOP syntactical sugar and hiding the nuances (globals etc.) of JS 'behind the scenes' etc.

Each programming language tried to exploit and capitalize on a particular niche IMHO. The above are my perspectives on what were the founding principles of the programming languages and that governed their evolution and widespread adoptability. Of course, there are many more, but the list is only intended as an example

However, I've struggled to understand the founding principles on which Ruby is based and its growing popularity. What were the founding principles of Ruby that makes it popular today? Or is it the genius of one man who designed the Rails framework? If the latter was it that Ruby made the designing of Rails better/easier/faster? In what sense?

The most commonly cited reason as per its creator is '...wanted a fun weakly typed programming language' - I don't see that as a reason for creating a new programming language altogether! Programming is sheer fun IMHO irrespective of the language (each language has some bad parts, but one either gets around it or lives with it).

So what niche did (or does) Ruby exploit that isn't exploited by the current languages? What is the 'strong point' (USP) of Ruby that has led to its widespread adoptability? What did Ruby do that wasn't done before (or was extremely difficult)?

I'm not a Ruby programmer, but just a Ruby noob and hence the confusion.

Disclaimer: This is NOT a flame war and I'm not looking for Ruby vs Programming language type of answers. I am looking for the design decisions on which Ruby is based that has led to widespread adoption. What niche does Ruby satisfy to have become popular or is that purely attributed to Rails?


问:
Google Analytics with multiple environments
We are planning to use Google Analytics in our organization and I am in charge for setting it up. I was wondering how to deal with multiple environments. We sure do not want to collect data during development and QA (or maybe collect data to a different analytics account), but we want to when the site goes to production (obviously).

How do you deal with multiple environments and Google Analytics ?

Do you setup multiple accounts for Google Analytics and use either one depending on the environement ?

We're using ASP.NET 2.0, if that matters.

答:
The easiest answer is yes, setup multiple accounts for each environment. Then, replace the profile ID (the text that looks like 'UA-XXXXX-X', as seen here)  with the correct ID from the desired environment.

Since you are using ASP.NET, you can store the profile ID in the web.config. This will lead to having to embed .NET code within JavaScript (which may or may not be okay).
You could also configure the production configuration to be the only configuration to output the tracking code, but that would lead to code being released that wasn't tested.

Depending on how you host your site (dev.domain.tld, test.domain.tld, www.domain.tld) you can possibly use a single profile and then filter the results based on subdomain/folder/url. Google has a pretty good article on the various tracking scenarios.


答:
This doesn't directly answer the title question, but addresses some points raised (i.e. why Ruby was created)

Quotes from Yukihiro 'Matz' Matsumoto, creator of Ruby, which may help explain what inspired its creation:

"I wanted a scripting language that was more powerful than Perl, and more object-oriented than Python"

"I hope to see Ruby help every programmer in the world to be productive, and to enjoy programming, and to be happy. That is the primary purpose of Ruby language."

So basically, Matz wanted an extremely object-oriented language that was designed for programmer happiness.


答:
Can you make sure that during development and QA, the site is only accessed internally from machines in your company network?

If yes, you could just use the same analytics account that will be used for production, and filter out all traffic from within your organization.

Quote from the link:

If you want to exclude internal traffic from appearing in your reports, you can filter out a specific IP address or a range of IP addresses. You can also use cookies to filter out visits from particular users. We'll explain how below.

Title: Google Analytics with multiple environments

Body:
We are planning to use Google Analytics in our organization and I am in charge for setting it up. I was wondering how to deal with multiple environments. We sure do not want to collect data during development and QA (or maybe collect data to a different analytics account), but we want to when the site goes to production (obviously).

How do you deal with multiple environments and Google Analytics ?

Do you setup multiple accounts for Google Analytics and use either one depending on the environement ?

We're using ASP.NET 2.0, if that matters.


答:
The phrase "Requirements change" is sometimes abused by IT people. What you are describing is indeed change of requirements but this may be because one or more of the following (I don't know enough about your case, so the following may or may not apply):

Management's ambition to make the end user happy as quickly as possible and show quick progress.

Lack of detailed analysis. Remember that Analysts need to ask questions about why not only what. The analysts needs to "think" with the end user about a "solution" not only take orders.

Lack of a formal process for requirements verification and confirmation, followed by approval.

Asking the incorrect person to perform one or more roles they are not necessarily trained for such as Business Analyst or Systems Analyst roles.

Limited prototyping.

The assumption/fear that it has to be done quickly and if not its IT to blame.

Unless one addresses all of the above properly, the relationship between IT and the business/end user will be stressful. Please note that this does not imply that the above point are conclusive. There are other factors that leads to stressful situations similar to your situation but I think this list should get you going.


问:
TDD for batch processing: How to do it?
I like "red/green/refactor" for RoR, etc. just fine.

My day job involves batch processing very large files from third-parties in python and other custom tools.

Churn on the attributes of these files is high, so there are a lot of fixes/enhancements applied pretty frequently.

Regression testing via a known body of test data with expected results does not exist.  Closest thing is running against the last batch with new test cases hand coded in, make sure it does not blow up, then apply spot-checking and statistical tests to see if data still looks OK.

Q>> How to bring TDD principles into this kind of environment?

答:
Just an FYI: Unit testing is not equivalent to TDD. TDD is a process of which unit testing is an element.

With that said, if you were looking to implement unit testing then there's a number of things you could do:

All new code/enhancements are tested

This way you don't have to go through and unit test everything that already exists, so the initial hump of implementing unit testing is much smaller.

Test individual pieces of data

Testing something that can contain large amounts of data can lead to many edge cases and gaps in the test coverage. Instead, consider the 0, 1, many option. Test a 'batch' with 0 elements, 1 element and many elements. In the case of 1 element, test the various permutations that the data for that element can be in.

From there, test the edge cases (upper bounds to the size of individual elements, and quantity of elements in the batch). If you run the tests regularly, and you have long running tests (large batches?), most test runners allow categorization so that you can run those test cases separately (nightly?).

That should give you a strong base.

Using actual data

Feeding in 'actual' previously used data like you're doing now isn't a bad idea. Just complement it with well formed test data so that you immediately know specific points of failure. On a failure to handle actual data, you can inspect the results of the batch process, produce a unit test to replicate the error, and then you're back into red/green/refactor with useful regression cases.

Title: TDD for batch processing: How to do it?


答:
I think you should approach this from a few directions:

Have all the stake holders (including the entire development team) meet (offline/online) with the business advisor and try to understand the domain, the vision and then brainstorm requirements together.

Formalize requirements/user stories, grading each one's:

a. Priority (urgency/importance)

b. Maturity (how well defined it is - understood and agreed on by majority of stake holders *)

c. Complexity (rough estimate)

When choosing which requirement/user storie to work on next, taken all three factors into account. If the requirement has low maturity, add a research mission before it, in which you contact all stake holders, investigate the reasoning behind the requirement and better define the requirement (write use cases and/or create wire-frames and present them) before acting upon it.

Try to think a few steps ahead while designing before each implementation - design a flexible architecture that has room to accommodate changes.

Try to adapt an agile development process e.g. SCRUM or Kanban - this will provide you with a toolkit for developing a product with changing requirements.

You should also consider asking the moderators to move this question to PM.stackexchange.com (by flagging it) as even though this question fits here, it would fit there better.

(*) Stake holders for agreement: business, marketing, project management, development and QA.


答:
Your current process makes it too easy for these people to just brainstorm ideas with no reguard for the resources and money this will consume. If they want all these features, they need to get some "skin in the game."

Take that email of the conversation and put it into some sort of feature/bug tracking application even if it is just a spreadsheet. Send the new additions back to the business advisor and ask him/her to sign off on each item or provide corrections. Along with the sign-off, they should prioritize (Which ones do you want first?).

After they approve, send them back your schedule on when the items will be completed for testing and get them to commit to a time to do the testing/approval of completion.

I know creating this type of documentation is not why you became a programmer, but you can either risk throwing these lists away or keep throwing your hard-earned code away.

Push back. Those in charge need to see how much these requests are costing.


问:
How can I find a good open source project to join?
I just started working a year ago, and I want to join an open source project for the same reasons as anyone else: help create something useful and develop my skills further.

My problem is, I don't know how to find a project where I'll fit in.

How can I find a beginner-friendly project?  What attributes should I be searching for?  What are warning signs that a project might not be the right fit?  Are there any tools out there to help match people with open source projects?

There's a similar question here, but that question has to do with employment and is limited to PHP/Drupal.

答:
I am a project owner on google code, and I am looking for contributors.
(Yet I will not misuse this answer for advertising.)
Hence my opinion might be interesting for you.

You'll first have to find out what you're interested in. Then develop some expertise in some fields that are related to your interests.
Then find a project where your expertise is demanded and needed.

The smaller the project, the less contributors are already there, the greater the chances that contributors are sought and you can contact the authors/project owners directly. Tell them a) what your expertise is b) where you see it could be applied in the project c) what you think you can achieve.

Remember: just knowing one or two mainstream programming languages is not expertise.


答:
Its the same as any other environment.

Separate out the logic into its smallest level of granularity. This will give you a set of rules for the process, each rule will cover one item of logic that is required for your process.

Then write a test for each rule. These tests will fail. Write the code to fix the test.

The regression testing with known test data that you are talking about is not unit testing. That would be integration testing, this is different from TDD. With TDD you may have a single test to test that you could load a file, but generally no other test would actually go near a data file with test data. Instead you would simulate the data required to exercise a particular rule using a mocking object.

Title: TDD for batch processing: How to do it?

Body:
I like "red/green/refactor" for RoR, etc. just fine.

My day job involves batch processing very large files from third-parties in python and other custom tools.

Churn on the attributes of these files is high, so there are a lot of fixes/enhancements applied pretty frequently.

Regression testing via a known body of test data with expected results does not exist.  Closest thing is running against the last batch with new test cases hand coded in, make sure it does not blow up, then apply spot-checking and statistical tests to see if data still looks OK.

Q>> How to bring TDD principles into this kind of environment?


答:
One thing that I've repeatedly noticed when it comes to people looking to get started with open source development is that they get overwhelmed at the sheer complexity and magnitude of big projects. I faced the same problem a couple of years ago, and from my experience, its best not to look at the bigger projects right away.

After spending sometime looking at projects that I might like, I realized that they were still out of my reach and then started to work on very small projects on my own. I make it a point to just release the code on Github, irrespective of whether its really relevant or whether other people will start using it. Eventually, people might start taking interest in what you do. Even otherwise, you will gain confidence and technical ability to slowly move to bigger and more popular projects.

Title: How can I find a good open source project to join?

Body:
I just started working a year ago, and I want to join an open source project for the same reasons as anyone else: help create something useful and develop my skills further.

My problem is, I don't know how to find a project where I'll fit in.

How can I find a beginner-friendly project?  What attributes should I be searching for?  What are warning signs that a project might not be the right fit?  Are there any tools out there to help match people with open source projects?

There's a similar question here, but that question has to do with employment and is limited to PHP/Drupal.