答:
Yes, always. As a programmer, it's your job to learn from mistakes.

Letting them know mistakes they make will help them become a better coder and reduce their chance of making mistakes in future. BUT do be polite and don't make a big deal of it, we all create bugs every so often. I find a polite email is a very non-confrontational way of letting people know.

Title: Should I tell someone that their commit caused a regression?

Body:
When you track down and fix a regression—i.e. a bug that caused previously working code to stop working—version control makes it entirely possible to look up who committed the change that broke it.

Is it worth doing this? Is it constructive to point this out to the person that made the commit? Does the nature of the mistake (on the scale of simple inattentiveness to fundamental misunderstanding of the code they changed) change whether or not it's a good idea?

If it is a good idea to tell them, what are good ways to do it without causing offense or causing them to get defensive?

Assume, for the sake of argument, that the bug is sufficiently subtle that the CI server's automated tests can't pick it up.


问:
Are RSpec and Cucumber really worth it?
I know most RoR programmers are testing addicts and I understand the advantages of a large testing suite but when I start testing, I never get such a large suite and I always wonder "Am I testing the right way? Are there really efficient?". I'm often dealing with integration tests testing only the way the application behave.

First, is testing really worth it? I mean, is the time spent on writing tests really worth it?

Then, I use RSpec, I've recently discovered Cucumber, used it for a while but I don't know if writing all these steps is really worth the trouble? I know I can reuse steps but I never know if these steps are too complete or not: For instance, I've been using a Given I am logged in as (.+) but I don't know if I must say in its definition Given there's a user called $1 because it can duplicate the user if ever created but that's not worthwhile always having a step before Given I am logged in as (.+). It's quite a lot of code that will maybe rarely be useful. I guess there are not new bugs on the parts tested every day...
So is Cucumber really worthwhile compared to RSpec?

答:
My take is that you are right on the Cucumber front. Writing all those steps is  a lot of trouble, and the benefits don't justify the pain. I've written extensively about the six disadvantages of using Cucumber here: Why Bother With Cucumber Testing?

Unit tests and regular integration tests, done either with Rspec or Test::Unit do make a lot of sense, but luckily these are far faster to write than Cucumber tests. For one you can use pure Ruby instead of having to fight Gherkin's wordy and awkward syntax.

ContentLicense: CC BY-SA 3.0

Title: Are RSpec and Cucumber really worth it?


问:
Should I tell someone that their commit caused a regression?
When you track down and fix a regression—i.e. a bug that caused previously working code to stop working—version control makes it entirely possible to look up who committed the change that broke it.

Is it worth doing this? Is it constructive to point this out to the person that made the commit? Does the nature of the mistake (on the scale of simple inattentiveness to fundamental misunderstanding of the code they changed) change whether or not it's a good idea?

If it is a good idea to tell them, what are good ways to do it without causing offense or causing them to get defensive?

Assume, for the sake of argument, that the bug is sufficiently subtle that the CI server's automated tests can't pick it up.

答:
Be assertive not aggressive.  Always favour saying something akin to "this piece of code is not working" vs "your code is not working".  Criticise the code, not the person who wrote the code.

Better yet, if you can think of a solution, fix it and push to them -- assuming you have a distributed version control system. Then ask them if your fix is valid for the bug they were fixing.  Overall, try to increase both your and their knowledge of programming.  But do it without your ego getting in the way.

Of course, you should be willing to listen to other developers coming to you with the same problem and act how you would have wished they did.


答:
The constructive way is to find the bug, fix it and take actions to avoid similar bugs to arise in the future.

If it involves explaining people how not to introduce bugs, go for it.

Once, I worked in a team where the project manager never told a particular developer that he made a mistake: he organised a meeting with the whole team where he explained that a mistake was made and that a new process has been defined in order to suppress that kind of mistakes. That way, nobody was stigmatized.


答:
In general, yes.

Nobody should get defensive if you're tactful about it. An easy way to handle it is to ask them to double-check your change before you commit it back to the trunk (or whatever is relevant for your version control system). People will appreciate it if you save them a few minutes by fixing obvious errors, but they won't appreciate it if you fix something that wasn't broken and end up breaking their code. Giving them a chance to review your change tells them that you don't want to step on their toes and gives them an opportunity to object to your changes.

If it's a big change rather than just a typo, it's a good idea to give the author a heads up before you dig into trying to fix it. "Joe, I was merging my own stuff yesterday and found something that I'm not sure I understand. It looks like a bug, but I wanted to run it by you before I go messing with your code. Would you take a look with me?"

Your relationship with the author is a big factor. If you wouldn't mind the author fixing your code without telling you, and if you're pretty sure the feeling is mutual, then it might not be worth mentioning. If it's someone with more experience/seniority/status, you'll want to let them know that you're going to change their code. If it's someone with less, then consider whether it's the sort of thing they need to hear to avoid repeating the mistake or it might embarrass them needlessly.

Always remember that if you can find out who checked in the "bug", they can as easily find out who "fixed" their code. If you think they'd be upset/annoyed/embarrassed at finding out about your change after the fact, by all means tell them beforehand.

Also, fixing the bug isn't your only option. You can always just report the bug in your issue tracker. Tact is again required here -- reporting the bug makes it more visible to the entire team, but it also gives the author a chance to fix his or her own mistake. Reporting is the best option if you're not certain about the best way to fix the problem or if you just don't have time to fix it.


问:
Are Bools/Bits Faster Than Integers
As the title suggests I'm wondering whether bools or bits are faster than using integers (1 and 0)?  Specifically I thinking about their speed in CASE statements, even more specifically in T-SQL (although it would be interesting to hear about experiences from other languages).

For some context, I have a pretty big SELECT statement over a large table which has to transform a lot of data based on integer being either 1 or 0, and was considering converting the integers to bits for a performance boost.

EDIT:

Thank you all for your responses.  It kind of seemed like you were all giving me pretty much the same advice worded slightly differently or with different levels of detail.

答:
If your current implementation fails to meet performance requirements, use a profiler to identify where time is wasted.

If you identify bits vs. integers to be such a performance issue, then fix it.

Title: Are Bools/Bits Faster Than Integers


问:
How to include conditions in UML sequence diagrams?
I like to draw a UML sequence diagram to display the sequence of actions and interactions of different parts of my system (I think they called actors).

However, I need to include if then else statements here. Do I do something wrong? Can I use conditional if statements in my UML sequence diagram? How?

答:
While sequence diagrams are perfect for your description, make sure to check Activity Diagrams.

When you want to show internal details (including detailed rules), Activity Diagrams is what you want to use. The plain activity diagrams focus on sequence of activities and rules and are poor in showing Actor responsibilities, nevertheless, you can use swim lanes to hi-light individual actor's responsibilities. Each lane would include activities an actor is responsible for.

These links discusses activity diagrams with swim lanes:

Activity Diagram - Wikipedia

Activity Diagram - based on RUP descriptions


答:
Don't worry about it.

If you're particularly interested in T-SQL, that implies you're using a database.  Most likely a database on disk.

Disk access is multiple orders of magnitude slower than any CPU operation or memory access.  Touching the disk just once, to read a single block of data, will likely take longer than the total time spent to make all the comparisons you're doing.

If you have performance problems, profile the code to find out where the actual problem is rather than immediately focusing on things which most likely take up under 1% of your total run time (and, therefore, can improve performance by less than 1% even if completely removed).  Most likely, you'll get the best return on your optimization investment by improving your algorithms rather than by changing data types.

Title: Are Bools/Bits Faster Than Integers

Body:
As the title suggests I'm wondering whether bools or bits are faster than using integers (1 and 0)?  Specifically I thinking about their speed in CASE statements, even more specifically in T-SQL (although it would be interesting to hear about experiences from other languages).

For some context, I have a pretty big SELECT statement over a large table which has to transform a lot of data based on integer being either 1 or 0, and was considering converting the integers to bits for a performance boost.

EDIT:

Thank you all for your responses.  It kind of seemed like you were all giving me pretty much the same advice worded slightly differently or with different levels of detail.


问:
Why isn't functional programming more popular in the industry? Does it catch on now?
During my four years at university we have been using much functional programming in several functional programming languages. But I have also used much object oriented programming to, and in fact I use object oriented languages more when doing my own small project to prepare for my first job. But I often wish that I was coding in a functional programming language when doing these projects.

However, when looking for a job, it is very rare to see a job where knowledge of a functional programming language is required.

Why isn't functional programming languages used more in the industry? There is quite much news about functional programming languages these days, so I wonder if functional programming is catching on in the industry now?

答: For the same reason that Lisp never really caught on (let the flamewars begin!). Functional programming is a very alien paradigm compared to imperative and object-oriented programming. If, like the vast majority of CS students, you started off with C and progressed to C++/Java, you tend not to want to learn to think in a way that is completely orthogonal to the way you normally think.</p>

ContentLicense: CC BY-SA 2.5


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

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

答:
From my first programming class (FORTRAN IV):

What is a computer?

  It it a box with a little man in it.

  This man is blazing fast. He can do millions of instructions per second.

  But he is myopic. He's so myopic that he can see only one instruction at a time.

  He's also not very smart, he'll attempt to do exactly what you tell him to do.

This has become the base of my philosophy of programming and debugging.

LastEditorDisplayName: Roger Pate


答:
One could go and make wild speculations here, or even educated guesses, but the truth is that it probably doesn't matter, and if it does, it's going to depend on a lot of other factors. The only way to find out is to profile, and when you do, first be sure to rule out other factors (system load, fragmentation, etc.).

My bet would be that the difference is going to be negligible, and that there's much more to win elsewhere - set up sensible indexes, profile joins vs. subqueries, use caching where possible, experiment with many small queries vs. few large queries, avoid unnecessary trips to the database, buffer accumulated results, etc.

The thing is, an integer vs. bool optimization will never give you more than a linear speed increase, and the increase won't be large - if you get 5%, consider yourself lucky. Those 5% will get smashed if your query does an outer join requiring full scans on both joined tables when one table is really large and you add one row to the other.

Title: Are Bools/Bits Faster Than Integers


答:
Just to give you more than the two and a half words I've written as a comment, let's get down to the processor level and try to find out what the difference is there regarding this question.

First, a processor always loads a full register size of data whenever anything needs to be processed. So the least data loaded, wheter you use it for a binary or integer comparison, would be 32 or 64 bits. Let's assume 32 for the moment.

Then, the difference between the two is this:

```<code>mov ax,[address]
cmp ax,1
jne label
</code>```

or

```<code>mov ax,[address]
and ax,10h
je label
</code>```

Forgive me if my assembler is not right on the spot, it has been about 13 years. But the answer still stands. The difference between these two should at the current processor generation be practically zero.

Then, there's the engine of the RDBMS. It might translate your CASE statement into something like the assembler above, but chances are that it transforms it based on it's own rules.

Then, there's the query optimizer. Whatever it does can be determined, usually by something like EXPLAIN (in MySQL), there's a similar function in MS-SQL-Server that explains the execution plan.

Then, for testing the speed, you need an environment that can ignore the interference from different processes, caching mechanisms and the likes.

So that all makes testing such things difficult, and the results speculative at best. Usually the time spent figuring out such little differences can be used to much greater use by optimizing indexes or data structures, server parameters or SELECT statements.

Cheers.

Title: Are Bools/Bits Faster Than Integers

Body:
Just to give you more than the two and a half words I've written as a comment, let's get down to the processor level and try to find out what the difference is there regarding this question.

First, a processor always loads a full register size of data whenever anything needs to be processed. So the least data loaded, wheter you use it for a binary or integer comparison, would be 32 or 64 bits. Let's assume 32 for the moment.

Then, the difference between the two is this:

mov ax,[address]
cmp ax,1
jne label

or

mov ax,[address]
and ax,10h
je label

Forgive me if my assembler is not right on the spot, it has been about 13 years. But the answer still stands. The difference between these two should at the current processor generation be practically zero.

Then, there's the engine of the RDBMS. It might translate your CASE statement into something like the assembler above, but chances are that it transforms it based on it's own rules.

Then, there's the query optimizer. Whatever it does can be determined, usually by something like EXPLAIN (in MySQL), there's a similar function in MS-SQL-Server that explains the execution plan.

Then, for testing the speed, you need an environment that can ignore the interference from different processes, caching mechanisms and the likes.

So that all makes testing such things difficult, and the results speculative at best. Usually the time spent figuring out such little differences can be used to much greater use by optimizing indexes or data structures, server parameters or SELECT statements.

Cheers.


问:
To Domain or not to Domain
The SQL92 and SQL99 standards define CREATE DOMAIN DDL constructs. Not all databases support this, or have a different name for it (SQL Server has User Defined Types, for example).

These allow one to define a constrained data-type to be used in their database, to simplify and enforce rules pertaining to the allowed values. Such a data-type could be used in column declarations, in inputs and outputs to stored procedures and functions etc...

I would like to know:

Do people actually use domains in their database designs?

If so to what extent?

How useful are they?

What pitfalls have you encountered?

I am trying to asses the viability of using these in future database development.

答:
On paper, UDTs are a great concept.  They allow you to truly normalise your DB (e.g. when you have two columns that depend on each other), and also to encapsulate any logic related to your new type.

In practice, the price you pay (today) is too high.  Obviously there is the development overhead, but aside from that you lose support from a variety of ORM and reporting tools, and increase the overall complexity of the solution quite a bit.  There aren't too many developers out there who are intimately familiar with UDTs, and I've never seen managed UDTs used outside of examples.

One of the best examples of a type that is best done as a UDT (if it didn't already exist) would have to be hierarchyid (MSDN link).  In order to remain efficient, it stores its value in a binary format (as opposed to the usual varchar custom implementations), which would be cumbersome to maintain without the type's functions.  The 10 or so methods that the type provides are also best provided as part of the type, as opposed to external functions.  I would consider using custom managed UDT in cases such as this - where there is a significant gain to be had by providing an efficient and neat implementation as a separate type.

Title: To Domain or not to Domain


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

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

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

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

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

My straight questions are:

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

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

答: There are softwares used by teachers to detect plagiarism in the works of their students. Maybe this can work with code too. However, be cautious to avoid divugate yourself the code by using an unreliable software ...</p>

Title: Detecting Internet code leaks


问:
Do You Have To Know CIL To Make A Compiler for .NET?
Assume one wants to create a simple .NET language, or slightly more difficult, a compiler for an existing .NET language. Do you absolutely need to be familiar with the CIL (Common Intermediate Language) to implement a compiler? And do you have to translate the syntax of your language to CIL by hand? Or is there another (more preferable) way? If not, what is the best way to learn CIL and especially to learn how to translate High-Level code to CIL?

答:
Of course you can generate C# or any other higher level language code instead of targeting CIL directly.

It is common to implement compilers as eDSLs on top of meta-languages. You can take, say, a decent Scheme implementation for .NET, or a more heavyweight language, like Nemerle, and build up your compiler as a set of macros on top of a host language, with a syntax front-end at the very top of this hierarchy.

As you've mentioned "translating the syntax to CIL", you're likely having a somewhat distorted view on how compilers should work. Normally there are many more steps in between parser and code generation, and it does not make any sense to do everything in a single pass.

And, of course, if your language semantics is significantly different from the host language, for an efficient implementation you'd still be much better off with generating CIL directly (or via a sequence of intermediate languages).

Learning CIL is not a big deal at all: everything you have to know is available on MSDN.

And here is a trivial example of building a compiler on top of a meta-language - you can easily do it with any Lisp.


答:
The other answers have touched on how the processor may handle an int vs. how it would handle a bit.  A few other things to consider:

If you have multiple such fields in the table, storing them as bit should give you an advantage in row size (from MSDN):

The SQL Server Database Engine optimizes storage of bit columns. If
  there are 8 or less bit columns in a table, the columns are stored as
  1 byte. If there are from 9 up to 16 bit columns, the columns are
  stored as 2 bytes, and so on.)

So, in the best case scenario, for the "price" of an int (4 bytes), you could store 32 bit fields.  I don't want to generalise too much, but disk access is often a bottleneck; reducing the amount of data you are physically storing will lead to faster queries.

People also tend to focus on the performance of bit fields in indexes.  I've encountered quite a few cases where people changed bit fields to char(1) in order to allow the field to be indexed (mostly because you couldn't index a bit field prior to SQL 2005).  The truth is, regardless of how it's stored, if your field only has two possible values, you're going to have trouble convincing SQL Server that it's worthwhile using as an index, unless it's used in combination with several other fields.

Title: Are Bools/Bits Faster Than Integers


答:
Using bits make sense instead of integers when you utilize bit map indexes (not available in SQL Server, but can be found in Oracle) and when you use bit map filters (available in SQL Server). From your question, this is not what you are looking for, but I think it may be of interest to you because it shows a practical application using binary over other data types in database design.

The following link gives some details:

Link

Title: Are Bools/Bits Faster Than Integers

ContentLicense: CC BY-SA 4.0


问:
When should I care about performance?
For the longest time in places like Java's IRC channel, SO, and other places I've been told something along the lines of "Worry about how the code looks and its readability/understandability now, and performance later if absolutely necessary". So for the longest time, I haven't really been OCD about performance for my small desktop or web apps, just removing the obviously inefficient.

Most responses are "What about scalability?". Thats a legitimate point, but if my app was only built to parse, say, files 10,000 lines long, should I make my code a mess for the small percentage of people that are going to shove in a 1,000,000 line file?

My main question is when should I trade the easy but somewhat inefficient ways of doing tasks for big giant complicated beasts that do things extremely quickly but destroy any possible ways of upgrading and make the code excessively difficult and prone to rewriting anyway by the next developer?

答:
My main question is when should I trade the easy but somewhat inefficient ways of doing tasks for big giant complicated beasts that do things extremely quickly but destroy any possible ways of upgrading and make the code excessively difficult and prone to rewriting anyway by the next developer?

"Worry about how the code looks and its readability/understandability now, and performance later if absolutely necessary" is the easy way out, and generally unhelpful. a good design will be easy to maintain, easy to read, and efficient.

performance is one common component of a good design. if your program is slow and wasteful, it's really not reusable. when you need to fix that mess, you force updates on your clients, unless it's just too time consuiming for them to update. that slow program becomes the big mess that is too costly to improve. then they choose an alternative becasue it does not suit their needs. diagnosing, updating, and dealing with side effects of improvements to a bad design often outweigh the initial development time of writing it to be efficient, work correctly, and has a genrally good design. that program is highly reusable and requires low maintentance (win).

so, the short answer to your question is "don't be wasteful. write for reuse. it's ok to be lazy when prototyping/developing proofs of concepts, but don't use that prototype for production code.".

do be aware of and avoid wasteful designs when writing production programs and programs that you intend to reuse. during implementation is the ideal time to write your program to not be wasteful - you have a clear idea of the details and its operation, and it's really painful and ineffective to fix after it's written. a lot of people believe a little profiling (maybe) at the end or if there is a problem is adequete, when it's usually too time consuming to redesign/change and the inefficiencies are so many and so widespread that you don't understand the program well based on the results of a profile. this approach takes little time during implementation and (assuming you have done this enough times) typically results in a design that is several times faster, and is reusable in many more contexts. not being wasteful, choosing good algorithms, giving thought to your implementations, and reusing the right implementations are all components of good design; all of which improves readability, maintainability, and reuse more often than hurts it.

Title: When should I care about performance?


问:
Is there any reason lazy initialization couldn't be built into Java?
Since I'm working on a server with absolutely no non-persisted state for users, every User-related object we have is rolled out on every request.

Consequently I often find myself doing lazy initialization of properties of objects that may go unused.

protected EventDispatcher dispatcher = new EventDispatcher();

Becomes...

```<code>protected EventDispatcher<EventMessage> dispatcher;

public EventDispatcher<EventMessage> getEventDispatcher() {
    if (dispatcher == null) {
        dispatcher = new EventDispatcher<EventMessage>();
    }
    return dispatcher;
}
</code>```

Is there any reason this couldn't be built into Java?

protected lazy EventDispatcher dispatcher = new EventDispatcher();

As mentioned below in the comments, I realize a language could theoretically evolve to include most anything you want.  I'm looking for a practical measurement of possibility. Would this conflict with other features? Is the implementation simple enough to work well with the JVM as it exists?  And even, is it a good idea?

答:
Of course it is eminently possible. In fact, scala already has exactly this feature! (Scala is a JVM language and compiles down to bytecode). Here is a piece of scala source:

```<code>class Foo {
  lazy val bar = "Hello World"
}
</code>```

And here is what an intermediate form of the compiled code looks like:

```<code>scalac -Xprint:icode Foo.scala

[[syntax trees at end of icode]]// Scala source: Foo.scala
package <empty> {
  class Foo extends java.lang.Object with ScalaObject {
    @volatile protected var bitmap$0: Int = 0;
    lazy private[this] var bar: java.lang.String = _;
    <stable> <accessor> lazy def bar(): java.lang.String = {
      if (Foo.this.bitmap$0.&(1).==(0))
        {
          Foo.this.synchronized({
            if (Foo.this.bitmap$0.&(1).==(0))
              {
                Foo.this.bar = "Hello World";
                Foo.this.bitmap$0 = Foo.this.bitmap$0.|(1);
                ()
              };
            scala.runtime.BoxedUnit.UNIT
          });
          ()
        };
      Foo.this.bar
    };
    def this(): Foo = {
      Foo.super.this();
      ()
    }
  }
</code>```

}

Body:
Of course it is eminently possible. In fact, scala already has exactly this feature! (Scala is a JVM language and compiles down to bytecode). Here is a piece of scala source:

class Foo {
  lazy val bar = "Hello World"
}

And here is what an intermediate form of the compiled code looks like:

scalac -Xprint:icode Foo.scala

[[syntax trees at end of icode]]// Scala source: Foo.scala
package <empty> {
  class Foo extends java.lang.Object with ScalaObject {
    @volatile protected var bitmap$0: Int = 0;
    lazy private[this] var bar: java.lang.String = _;
    <stable> <accessor> lazy def bar(): java.lang.String = {
      if (Foo.this.bitmap$0.&(1).==(0))
        {
          Foo.this.synchronized({
            if (Foo.this.bitmap$0.&(1).==(0))
              {
                Foo.this.bar = "Hello World";
                Foo.this.bitmap$0 = Foo.this.bitmap$0.|(1);
                ()
              };
            scala.runtime.BoxedUnit.UNIT
          });
          ()
        };
      Foo.this.bar
    };
    def this(): Foo = {
      Foo.super.this();
      ()
    }
  }

}


答:
Unless you're finding someone actually stealing code and developing their own product on your work it's pretty much a waste of time. The internet is like a big coding cook book already. Finding snippets and code pieces that fit into your own puzzle isn't that hard. Optimization to make it fit into your own project is the hard part.

Writing software is easy. Writing easy software that performs well is hard.

As long there is no actually leakage of private keys in any matter involved I'd rather not care.

Title: Detecting Internet code leaks

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

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

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

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

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

My straight questions are:

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

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


答:
My 'ah-ha!' moments about testing in Ruby and Rails came when I really sat down and read the definitive resources on the subject, the Rspec and Cucumber books. I shared your initial disdain of Cucumber, but then I realized that I was looking at the picture from quite the wrong angle.

Basically, Cucumber is about BDD (behaviour driven development) - you use Cucumber to plan your features, what you're going to work on next. Hmm, next you want users to be able to promote posts on a forum or something (to steal an example ;)) So you write something simple.

```<code>Given I am logged in
And I can see the post "BDD is awesome"
When I vote the post up
Then the post should have one more vote
And the page should show a message thanking me for my vote.
</code>```

Note that there's no references to anything code related in there pretty much. That comes in your steps. When you refactor your code, you might have to change your step definitions, but the behaviour (your feature) will never need to change.

Now every time you run your Cucumber feature, you'll pretty much be led through how to test the feature using TDD (test driven development). This is done at a lower level using RSpec.

First run - my first step definition is undefined. Copy the block to define it in say user_steps.rb or even session_steps.rb because it relates to users and their sessions. Now, how do you define that a user is logged in? You can take them through the login process.

```<code>Given /^I am logged in$/ do
  visit login_path
  fill_in :name, :with => 'Joe'
  fill_in :password, :with => 'Password'
  click_button 'submit'
end
</code>```

Should be all happy. Second step.

```<code>Given /^I can see the post "(.+)"$/ do |name|
  visit post_path(Post.find_by_name(name))
end
</code>```

Again pretty easy. Note that if we totally redo our login process, or how our posts are defined and shown, we don't have to change the behaviour. Third step.

```<code>When /^I vote the post up$/ do
  pending
end
</code>```

Here's where you're starting to talk about new functionality, but you don't quite know how it's going to work yet. How do you vote a post up? You might click an image of a +1 or something, which does an ajax post to a controller, which returns JSON, or some such. So now you can move into pure Rspec testing.

Test your view to make sure the +1 image is displayed,

Test your controller that it behaves correctly when it receives a given ajax request of the right format (both the happy and unhappy paths - what if an invalid post ID is received? What happens if the user has used up their 25 upvotes in a day? Does it increment the number of votes correctly?)

Test your javascript that it responds correctly when given a blob of JSON in the right format (does it update the +1 image to show it's been used? (thinking of Google+ here...) Does it show the thank you message? etc.)

All of this doesn't affect the behaviour - but when you're finished dealing with the lower level testing, it will be trivial to fill in the step definition for how to vote a post up. It might be as simple as click_link '+1'. And the rest of the steps are testing results, which again should be straightforward to do. And when you're done, then you know your feature is complete and finished. If the necessary behaviour changes, you can tweak your feature, else you can tweak your implementation code in perfect safety.

I hope this makes sense. It's all been off the top of my head, but I think it demonstrates the difference between BDD and TDD, and why Cucumber and RSpec serve different needs.

Title: Are RSpec and Cucumber really worth it?

Body:
I know most RoR programmers are testing addicts and I understand the advantages of a large testing suite but when I start testing, I never get such a large suite and I always wonder "Am I testing the right way? Are there really efficient?". I'm often dealing with integration tests testing only the way the application behave.

First, is testing really worth it? I mean, is the time spent on writing tests really worth it?

Then, I use RSpec, I've recently discovered Cucumber, used it for a while but I don't know if writing all these steps is really worth the trouble? I know I can reuse steps but I never know if these steps are too complete or not: For instance, I've been using a Given I am logged in as (.+) but I don't know if I must say in its definition Given there's a user called $1 because it can duplicate the user if ever created but that's not worthwhile always having a step before Given I am logged in as (.+). It's quite a lot of code that will maybe rarely be useful. I guess there are not new bugs on the parts tested every day...
So is Cucumber really worthwhile compared to RSpec?

Body:
My 'ah-ha!' moments about testing in Ruby and Rails came when I really sat down and read the definitive resources on the subject, the Rspec and Cucumber books. I shared your initial disdain of Cucumber, but then I realized that I was looking at the picture from quite the wrong angle.

Basically, Cucumber is about BDD (behaviour driven development) - you use Cucumber to plan your features, what you're going to work on next. Hmm, next you want users to be able to promote posts on a forum or something (to steal an example ;)) So you write something simple.

Given I am logged in
And I can see the post "BDD is awesome"
When I vote the post up
Then the post should have one more vote
And the page should show a message thanking me for my vote.

Note that there's no references to anything code related in there pretty much. That comes in your steps. When you refactor your code, you might have to change your step definitions, but the behaviour (your feature) will never need to change.

Now every time you run your Cucumber feature, you'll pretty much be led through how to test the feature using TDD (test driven development). This is done at a lower level using RSpec.

First run - my first step definition is undefined. Copy the block to define it in say user_steps.rb or even session_steps.rb because it relates to users and their sessions. Now, how do you define that a user is logged in? You can take them through the login process.

Given /^I am logged in$/ do
  visit login_path
  fill_in :name, :with => 'Joe'
  fill_in :password, :with => 'Password'
  click_button 'submit'
end

Should be all happy. Second step.

Given /^I can see the post "(.+)"$/ do |name|
  visit post_path(Post.find_by_name(name))
end

Again pretty easy. Note that if we totally redo our login process, or how our posts are defined and shown, we don't have to change the behaviour. Third step.

When /^I vote the post up$/ do
  pending
end

Here's where you're starting to talk about new functionality, but you don't quite know how it's going to work yet. How do you vote a post up? You might click an image of a +1 or something, which does an ajax post to a controller, which returns JSON, or some such. So now you can move into pure Rspec testing.

Test your view to make sure the +1 image is displayed,

Test your controller that it behaves correctly when it receives a given ajax request of the right format (both the happy and unhappy paths - what if an invalid post ID is received? What happens if the user has used up their 25 upvotes in a day? Does it increment the number of votes correctly?)

Test your javascript that it responds correctly when given a blob of JSON in the right format (does it update the +1 image to show it's been used? (thinking of Google+ here...) Does it show the thank you message? etc.)

All of this doesn't affect the behaviour - but when you're finished dealing with the lower level testing, it will be trivial to fill in the step definition for how to vote a post up. It might be as simple as click_link '+1'. And the rest of the steps are testing results, which again should be straightforward to do. And when you're done, then you know your feature is complete and finished. If the necessary behaviour changes, you can tweak your feature, else you can tweak your implementation code in perfect safety.

I hope this makes sense. It's all been off the top of my head, but I think it demonstrates the difference between BDD and TDD, and why Cucumber and RSpec serve different needs.


问:
what is "graceful degradation"?
I hear a lot about this term "Graceful degradation".

For example ,

```<code> "An application server should gracefully degrage when it is under heavy load "

  "Graceful degradation of user interfaces.... "
</code>```

The term looks like an abstract thing to me. Any concrete example of what it means?

答:
When creating web apps graceful degradation comes into play when your site relies on JavaScript or Flash or a similar techniques that the user doesn't have or disabled.

Then you should still provide some basic functionality with HTML only or at least a message why the site is not functioning as expected.

Title: what is "graceful degradation"?


答:
If someone gets offended when you said him he made a mistake, it means he thinks he is the wisest on the earth and makes no mistake, and when criticized, he gets the feeling, as we said in Poland, that 'crown is falling from his head'.

So you shouldn't hesitate to say that someone has made a mistake. It is normal. Everyone makes mistakes, even the best! Only those who make nothing make no mistakes ;)


问:
How should someone used to FP thinking read imperative code?
I graduated from university about five months ago, and have been working in a local startup for past four months. While at university, I studied Haskell, F# etc on my own. We were taught Java at the university, but I was exposed to functional programming very soon, and have spent far more time with it than I did with imperative programming. As a result, my brain is wired for a functional thinking. The company I have joined uses Python, and the code is heavily imperative. I am having a very hard time reading imperative code. I cannot keep a track of mutations. When an for-if-else-for-... nesting goes more than four levels deep, I completely lose the track of what's happening in the code. To add to it, Python is a dynamic language, so there are no types in the code. It's been weeks since I have been trying to understand a part of our codebase (which is supposedly 'moderately complex'), but I haven't made any appreciable progress so far in understanding it. Please offer me some practical techniques on how I should go about understanding that code. Thanks in advance!

Edit:

Maybe I should also mention that there aren't really many comments in the code, and the names are also not very intuitive.

答:
I am having a very hard time reading imperative code.
  When an for-if-else-for-... nesting goes more than four levels deep, I
  completely lose the track of what's happening in the code.

Wait...anyone completely looses track of the code with such deep nesting levels. Or as Linus Torvalds put it:

If you need more than 3 levels of indentation, you're screwed anyway, and should fix your program.

Maybe I should also mention that there aren't really many comments in
  the code, and the names are also not very intuitive.

This does not sound as if your company is adhering to common best practices.

If I were you, I'd just try to understand the code base by discipline and force. Just dig into it, again and again and again. It's probably like anything. Right now you feel like you're underwater and can't breathe but continue to examine the codebase and soon you'll swim to the surface.

I'm afraid your question lacks the technical details to offer you a good advice on how to understand the codebase, but it's never wrong to go through it with experienced colleagues in a few sessions. Let them explain you the overall architecture and how the different components interact with each other, alongside with implementation decisions they made.

It's hard to give general advice for the transition from functional languages to imperative/OO ones. Sure, I could mention a few flowery phrases like "You need to think about states and behaviours of objects", but these won't help you much, I think this is something you have to experience.


答:
If (big if from the bad practices you describe) there are unit tests, then you can look at those to see how the code is tested.  This can offer a good insight as to what the code does.

Otherwise, I would suggest reading more generic python code to get used to the way it is written.

Title: How should someone used to FP thinking read imperative code?

Body:
I graduated from university about five months ago, and have been working in a local startup for past four months. While at university, I studied Haskell, F# etc on my own. We were taught Java at the university, but I was exposed to functional programming very soon, and have spent far more time with it than I did with imperative programming. As a result, my brain is wired for a functional thinking. The company I have joined uses Python, and the code is heavily imperative. I am having a very hard time reading imperative code. I cannot keep a track of mutations. When an for-if-else-for-... nesting goes more than four levels deep, I completely lose the track of what's happening in the code. To add to it, Python is a dynamic language, so there are no types in the code. It's been weeks since I have been trying to understand a part of our codebase (which is supposedly 'moderately complex'), but I haven't made any appreciable progress so far in understanding it. Please offer me some practical techniques on how I should go about understanding that code. Thanks in advance!

Edit:

Maybe I should also mention that there aren't really many comments in the code, and the names are also not very intuitive.


问:
Why do so many developers believe performance, readability, and maintainability cannot coexist?
While responding to this question, I began to wonder why so many developers believe a good design should not account for performance because doing so would affect readability and/or maintainability.

I believe that a good design also takes performance into consideration at the time it is written, and that a good developer with a good design can write an efficient program without adversely affecting readability or maintainability.

While I acknowledge that there are extreme cases, Why do many developers insist an efficient program/design will result in poor readability and/or poor maintainability, and consequently that performance should not be a design consideration?

答:
Precisely because highly performing software components are generally orders of magnitude more complex than other software components (all other things being equal).

Even then it is not as clear cut, if performance metrics are a critically important requirement then it is imperative that the design have complexity to accomodate such requirements.  The danger is a developer who wastes a sprint on a relatively simple feature trying to squeeze a few extra milliseconds out of his component.

Regardless, complexity of design has a direct correlation with the ability of a developer to quickly learn and become familiar with such a design, and further modifications to functionality in a complex component can result in bugs that might not be caught by unit tests.  Complex designs have many more facets and possible test cases to consider making the goal of 100% unit test coverage even more of a pipe dream.

With that being said it should be noted that a poorly performing software component could perform poorly just because it was foolishly written and unnecessarily complex based on the ignorance of the original author, (making 8 database calls to build a single entity when just one would do, completely unnecessary code that results in a single code path regardless, etc...)  These cases are more a matter of improving code quality and performance increases happening as a consequence of the refactor and NOT the intended consequence necessarily.

Assuming a well designed component however, it will always be less complex than a similarly well designed component tuned for performance (all other things being equal).


答: In my opinion performance should be a consideration when it's an actual problem (or e.g. a requirement). Not doing so tends to lead to microoptimizations, which might lead to more obfuscated code just to save a few microseconds here and there, which in turn leads to less maintainable and less readable code. Instead one should focus on the real bottlenecks of the system, if needed, and put emphasis on performance there.

Title: Why do so many developers believe performance, readability, and maintainability cannot coexist?

Body:
While responding to this question, I began to wonder why so many developers believe a good design should not account for performance because doing so would affect readability and/or maintainability.

I believe that a good design also takes performance into consideration at the time it is written, and that a good developer with a good design can write an efficient program without adversely affecting readability or maintainability.

While I acknowledge that there are extreme cases, Why do many developers insist an efficient program/design will result in poor readability and/or poor maintainability, and consequently that performance should not be a design consideration?


答:
I think such views are usually reactions to attempts at premature (micro-)optimization, which is still prevalent, and usually does way more harm than good. When one tries to counter such views, it is easy to fall into - or at least look like - the other extreme.

It is nevertheless true that with the enormous development of hardware resources in recent decades, for most of the programs written today, performance ceased to be a major limiting factor. Of course, one should take into account expected and achievable performance during design phase, in order to identify the cases when performance may be(come) a major issue. And then it is indeed important to design for performance from the beginning. However, overall simplicity, readability and maintainability is still more important. As others noted, performance optimized code is more complex, harder to read and maintain, and more bug-prone than the simplest working solution. Thus any effort spent on optimization must be proven - not just believed - to bring real benefits, while degrading the long term maintainability of the program as little as possible. So a good design isolates the complex, performance intensive parts from the rest of the code, which is kept as simple and clean as possible.


问:
Code Analysis & Reporting: Maven vs. Jenkins
My team (~10 devs) has recently migrated to Maven (multi-module project, ca. 50 modules) and we now use Jenkins for continuous integration. As the overall setup is running, we are planning to include code analysis and reporting tools (e.g., Checkstyle and Corbertura).

As far as I can see, we basically have two options to generate such reports: either use Maven's reporting plug-ins to generate a site and/or use Jenkins  plug-ins to do the reporting.

Which approach is better, and for which reasons?

It seems both have their merits:

Maven-Reporting:

 everything is configured in a single place (the pom files)

 report generation on a local machine (i.e., without Jenkins) is straightforward and does not require any additional steps

Jenkins-Reporting:

adjusting the reporting configuration seems more intuitive than with Maven and does not interfere with the main task of maven in our setup (building and deploying)

a single web-interface to check the overall status of the project, so that the reported issues are easier to find and harder to ignore (i.e., no need to click through the maven site, some nice history plots, notifications, etc.)

Has anyone made a similar decision in the past, or is this a non-issue for some reason? (How well does it work? Any regrets?)

Is it advisable to go both ways, or is that setup too tedious to maintain?

Are there aspects of the problem that I am unaware of, or some advantages I have not noticed  (e.g., is Maven-based reporting integrated nicely with m2eclipse)?

Any pitfalls or typical problems that we are likely to encounter?

EDIT:

We tried out Sonar, as suggested below (including its Jenkins plug-in). So far, it works pretty well. Sonar is relatively simple to install and works on top of our Maven setup (one just invokes mvn sonar:sonar or re-configures a Jenkins job, that's all). This means we do not have to maintain a duplicate configuration, as all our Maven settings are used automatically (the only exception being exclude patterns). The web-interface is nice, and -- even better -- there is an Eclipse plug-in that retrieves all issues automatically, so that no one really has to browse to the Sonar website, as all issues can be automatically displayed in the IDE.

答:
Since you already have your projects ready for Maven and Jenkins is installed, you may go one step further and install Sonar. It is an incredible code quality related tool, it performs Cobertura, Checkstyle, FindBug, and many other analysis tools at the same time. That way, the code quality reporting is done by Sonar, not by Maven or Jenkins.

You can install Sonar on the same machine where Jenkins is installed or somewhere else. If you just want to test it, you can just perform the standard install (it uses its own HSQLDB if you don't configure the database yourself) and you are almost ready to go. The last thing you need is to configure the relationship between Jenkins and Sonar.

There is done via the Sonar plugin for Jenkins. Once you have installed the plugin:

Indicate where Sonar can be located on the Jenkins configuration

For each build job you want to be analysed, go into the job configuration and check the "Sonar" checkbox.

Be careful for one thing: the analysis may be quite long for big projects. But then again, you may configure special nightly Sonar builds in addition to standard builds.

Hope that helped.


答:
The point is not readability should always trump efficiency. If you know from the get go that your algorithm needs to be highly efficient, then it will be one of the factors you use to develop it.

The thing is most uses cases don't need blinding fast code. In many cases IO or user interaction causes much more delay then your algorithm execution causes. The point is that you should not go out of your way to make some thing more efficient if you don't know it is the bottle neck.

Optimizing code for performance often makes it more complicated because it generally involves doing things in a clever way, instead of the most intuitive. More complicated code is harder to maintain and harder for other developers to pick-up (both are costs that must be considered). At the same time, compilers are very good at optimizing common cases. It is possible that your attempt to improve a common case means that the compiler does not recognize the pattern anymore and thus can not help you make your code fast. It should be noted that this does not mean write whatever you want without concern to performance. You should not be doing anything that is clearly inefficient.

The point is to not worry about little things that might make things better. Use a profiler and see that 1) what you have now is an issue and 2) what you changed it to was an improvement.


答:
Coming at your question from the side of a developer who works on high-performance code, there are several things to consider in design.

Do not prematurely pessimize.  When you have the choice between two designs that are equal in complexity, choose the one that has the best performance characteristics.  One of the famous C++ examples is the prevalence of post-increment of counters (or iterators) in loops.  This is a totally unnecessary premature pessimization that MAY not cost you anything, but it MIGHT, so don't do it.

In many cases you have no business to go anywhere near micro-optimization yet.  Algorithmic optimizations are a lower-hanging fruit and are nearly always a lot easier to understand than really low-level optimizations.

If and ONLY if performance is absolutely critical, you get down and dirty.  Actually, you isolate the code as much as you can first, and THEN you get down and dirty.  And it gets really dirty in there, with caching schemes, lazy evaluation, memory layout optimization for caching, blocks of inline intrinsics or assembly, layer-upon-layer of templates, etc.   You test and document like crazy here, you know it's going to hurt if you have to do any maintenance in this code, but you have to because performance is absolutely critical.  Edit:  By the way, I'm not saying this code cannot be beautiful, and it should be made as beautiful as it can be, but it's still going to be very complex and often convoluted compared to less optimized code.

Get it right, get it beautiful, get it fast.  In that order.


答:
```
    |
    P
    E
    R
    F
    O  *
    R   *
    M    *
    A      *
    N        *
    C          *  *   *  *  *
    E
    |
    O -- R E A D A B I L I T Y --
```

As you can see...

Sacrificing readability can increase performance -- but only so much. After a certain point, you have to resort to "real" means like better algorithms and hardware.

Also, losing performance at the cost of readability can happen only to some extent. After that, you can make your program as much readable as you want without affecting performance. For example adding more helpful comments doesn't toll performance.

So, performance and readability are but modestly related -- and in most cases, there's no real big incentives preferring the former over latter. And I am talking here about high level languages.

Body:
    |
    P
    E
    R
    F
    O  *
    R   *
    M    *
    A      *
    N        *
    C          *  *   *  *  *
    E
    |
    O -- R E A D A B I L I T Y --

As you can see...

Sacrificing readability can increase performance -- but only so much. After a certain point, you have to resort to "real" means like better algorithms and hardware.

Also, losing performance at the cost of readability can happen only to some extent. After that, you can make your program as much readable as you want without affecting performance. For example adding more helpful comments doesn't toll performance.

So, performance and readability are but modestly related -- and in most cases, there's no real big incentives preferring the former over latter. And I am talking here about high level languages.


答:
If you just approach them to tell them about a mistake they made then unless you are the best diplomat in the world its going to be difficult for it not to just sound like "Ha! - look at this mistake you made!".  We are all human and criticism is difficult to take.

On the other hand unless the change is completely trivial and obviously wrong I normally find it benificial to talk to the person who committed the original change as part of my investigation just to make sure that I fully understand whats going on, hence the way I usually end up handling these situation is by going over to said person and having a conversation that goes a little like this:

Me: I'm working on this bug where ... summary of bug ... and I think I've tracked down the problem to a change you made.  Can you remember what this change was for? / have you got some time to explain this change?

Then either:

Them: Sure, thats to handle ... situation I wasn't aware of ...

Or something along the lines of:

Them: Nope sorry I don't remember, looks wrong to me.

By going and investigating the change / bug together the original committer gets to learn from their mistakes without just feeling like they are being criticised*, and there is also a pretty good chance that you will learn something too.

If the original committer isn't around or is busy then you can alwasy just slog through and figure it all out yourself, I just normally find that talking to the person who originally made the change is quicker.

* Of course this is only going to work if you are genuinely interested in the other persons help.  If you are just using this as a thinly disguised method of telling someone about a mistake they made then this is probably worse than just being open about it.


答:
If I can presume to "borrow" @greengit's nice diagram, and make a small addition:

```<code>|
P
E
R
F
O  *               X <- a program as first written
R   *
M    *
A      *
N        *
C          *  *   *  *  *
E
|
O -- R E A D A B I L I T Y --
</code>```

We've all been "taught" that there are tradeoff curves.
Also, we have all assumed we are such optimal programmers that any given program we write is so tight it is on the curve.
If a program is on the curve, any improvement in one dimension necessarily incurs a cost in the other dimension.

In my experience, programs only get near any curve by being tuned, tweaked, hammered, waxed, and in general turned into "code golf".
Most programs have plenty of room for improvement in all dimensions.
Here's what I mean.

Body:
If I can presume to "borrow" @greengit's nice diagram, and make a small addition:

|
P
E
R
F
O  *               X <- a program as first written
R   *
M    *
A      *
N        *
C          *  *   *  *  *
E
|
O -- R E A D A B I L I T Y --

We've all been "taught" that there are tradeoff curves.
Also, we have all assumed we are such optimal programmers that any given program we write is so tight it is on the curve.
If a program is on the curve, any improvement in one dimension necessarily incurs a cost in the other dimension.

In my experience, programs only get near any curve by being tuned, tweaked, hammered, waxed, and in general turned into "code golf".
Most programs have plenty of room for improvement in all dimensions.
Here's what I mean.


答: It is not so much that those things cannot coexist. The problem is that everyone's code is slow, unreadable, and unmaintainable on the first iteration. The rest of the time is spent working on improving whatever is most important. If that is performance, then go for it. Don't write spitefully awful code, but if it just has to be X fast, then make it X fast. I believe that performance and cleanliness are basically uncorrelated. Performant code does not cause ugly code. However, If you spend your time tuning every bit of code to be fast, guess what you did not spend your time doing? Making your code clean and maintainable. </p>


问:
How does a programmer used to static languages cope with lack of Javascript tooling
I have programmed pretty much exclusively in compiled languages, particularly Java, for most of my career.  One of my favourite things about Java is how productive you can be, and how little code you actually have to write, when using tools like Eclipse.

You can:

Easily and automatically refactor your methods and classes

View instantly all the places where a method is invoked, or a constant is used (Open Call Hierarchy/Show References)

Static typing means you can use code completion to show all the parameters/functions available on an object

Control-click on a function/member/class name to go straight to its definition

All these facilities make me feel like the IDE is my best friend.  Writing Java code and particularly understanding other peoples' programs becomes far easier.

However, I am being called on more and more to use Javascript, and my experience so far has been quite negative.

In particular:

No immediate way of finding a function's entry point
(other than a plain text search, which may then result in a subsequent searches for methods further up the call hierarchy, after two or three of which you've forgotten where you started)

Parameters are passed in to functions, with no way of knowing what properties and functions are available on that parameter
(other than actually running the program, navigating to the point at which the function is called, and using console.logs to output all the properties available)

Common usage of anonymous functions as callbacks, which frequently leads to a spaghetti of confusing code paths, that you can't navigate around quickly.

And sure, JSLint catches some errors before runtime, but even that's not as handy as having red wavy lines under your code directly in the browser.

The upshot is that you pretty much need to have the entire program in your head at all times.  This massively increases the cognitive load for writing complex programs.  And all this extra stuff to worry about leaves less room in my brain for actual creativity and problem solving.

Sure, it's faster to just throw an object together rather than write an entire formal class definition.  But while programs may be slightly easier and quicker to write, in my experience they are far harder to read and debug.

My question is, how do other programmers cope with these issues?  Javascript is clearly growing in popularity, and the blogs I read are about how productive people are being with it, rather than desperately trying to find solutions to these issues.

GWT allows you to write code for a Javascript environment in Java instead, but doesn't seem to be as widely used as I would expect; people actually seem to prefer Javascript for complex programs.

What am I missing?

答:
The IDE-based niceties are not available* in a dynamic language such as javascript. You have to learn to do without them. You'll have to replace tool support with better design.

Use a module pattern -- either by hand, or with a tool like requirejs. Keep the modules small, so that you can reason about them easily.

Don't define as many types -- use anonymous objects created close to the point of call. Then you can look at the caller and the callee and know what's going on.

Try to avoid coupling your code to the DOM -- Try hard to limit the amount of DOM manipulation you do in your code. If you can pass in selectors or jQuery collections, do that rather than having your code know about the page structure.

*If you're using a popular library, you can get fake autocomplete, but it's more like "show all jquery methods" than like "what properties does this object have". It saves typing, but offers no guarantee of correctness.


答:
What am I missing?

You are missing the two enormous advantages that Javascript has over Java:

Javascript code is about one-fourth the size of equivalent Java code.

You never have to wait for a compile and server restart.

I work differently in Javascript.  I add a little bit of code at a time, as little as I can possibly test, and refresh the browser and test it.  With jQuery, a couple lines of Javascript are all I need most of the time.

I have found Java programming to be relatively unproductive, and am now writing all my server-side code in Groovy, for the same two reasons.

Title: How does a programmer used to static languages cope with lack of Javascript tooling

Body:
I have programmed pretty much exclusively in compiled languages, particularly Java, for most of my career.  One of my favourite things about Java is how productive you can be, and how little code you actually have to write, when using tools like Eclipse.

You can:

Easily and automatically refactor your methods and classes

View instantly all the places where a method is invoked, or a constant is used (Open Call Hierarchy/Show References)

Static typing means you can use code completion to show all the parameters/functions available on an object

Control-click on a function/member/class name to go straight to its definition

All these facilities make me feel like the IDE is my best friend.  Writing Java code and particularly understanding other peoples' programs becomes far easier.

However, I am being called on more and more to use Javascript, and my experience so far has been quite negative.

In particular:

No immediate way of finding a function's entry point
(other than a plain text search, which may then result in a subsequent searches for methods further up the call hierarchy, after two or three of which you've forgotten where you started)

Parameters are passed in to functions, with no way of knowing what properties and functions are available on that parameter
(other than actually running the program, navigating to the point at which the function is called, and using console.logs to output all the properties available)

Common usage of anonymous functions as callbacks, which frequently leads to a spaghetti of confusing code paths, that you can't navigate around quickly.

And sure, JSLint catches some errors before runtime, but even that's not as handy as having red wavy lines under your code directly in the browser.

The upshot is that you pretty much need to have the entire program in your head at all times.  This massively increases the cognitive load for writing complex programs.  And all this extra stuff to worry about leaves less room in my brain for actual creativity and problem solving.

Sure, it's faster to just throw an object together rather than write an entire formal class definition.  But while programs may be slightly easier and quicker to write, in my experience they are far harder to read and debug.

My question is, how do other programmers cope with these issues?  Javascript is clearly growing in popularity, and the blogs I read are about how productive people are being with it, rather than desperately trying to find solutions to these issues.

GWT allows you to write code for a Javascript environment in Java instead, but doesn't seem to be as widely used as I would expect; people actually seem to prefer Javascript for complex programs.

What am I missing?


答:
I haven't used it yet myself but I've seen some demos and I'm very impressed with Cloud 9 as a JavaScript IDE.

You can go for both the online service model or download it off GitHub.

And as evidence of its quality as an IDE, Cloud9 was written using... Cloud9!


答: In general, it is hard to have tools you mentioned for a dynamic language (unless the IDE is a part of the runtime - i.e. Smalltalk). Having said that, once you learn a really good text editor, most IDEs look less attractive - that's at least my experience.</p>


答:
I think most programmers get that gut feeling simply because most of the time, performance code is code based on a lot more informations (about the context, hardware knowledge, global architecture) than any other code in applications. Most code will only express some solutions to specific problems that are encapsulated in some abstractions in a modular way (like functions) and that means limiting the knowledge of the context to only what enter that encapsulation (like function parameters).

When you write for high performance, after you fix any algorithmic optilizations, you get into  details that requires far more knowledge about the context. That might naturally overwhelm any programmer that don't feel focused enough for the task.


问:
Why is PHP so frequently used on web servers?
My web server uses PHP as do 77.7% of web servers according to W3Techs, as of 14/03/2022.

The reason I use PHP is an inertia born out of seeing everyone else using it on web servers. What is it about PHP that would make it so ubiquitous on web servers?

(Note that this question is similar to the following question but takes it in a different direction: Why isn't Java used for modern web application development?)

答:
Lets face it, PHP is cheap, easy to learn, has a large community, you can host it anywhere, and it's been around a lot. So, if you think as someone using the internet as a way to make money fast in a small/medium industry and having to create a development area to do so with a practically nonexistent infrastructure, PHP sounds pretty great (to start with).

So I think PHP is a great way to make some money fast with a bunch of programmers and a small computer as a server.


答:
If I make a commit that includes a bug, you had better tell me. If I find a commit of yours that includes a bug, I will surely tell you.

We only improve when we comprehend our errors. That's how we produce better code in the future.


答:
Understanding legacy code is hard.  It has almost nothing to do with functional vs. procedural.

Create a map of some kind.  A component diagram of the Python packages and modules.  For each module, you'll need to create class diagrams.

Use the Python interpreter.  You should be able to import modules, create objects and exercise them interactively.  That's why Python is popular.  You can print type(x) to see what type a variable (x) actually is.

When in doubt, be sure to read the unit test code.  If there is no unit test code, you have large, looming problems in addition to learning a new code base.

Write stuff down.  Start with side documents.  Then, when you think you know what's going on, add docstring comments to functions, methods and classes.  Add these early and often.

Use Sphinx with 'autodoc' to collect what you're learning.

The most important part is this.  It's hard to keep things in your head.  It's easier to keep things on documentation files.


问:
What did Linus Torvalds mean by his quotation about portability?
In a debate with Andrew Tanenbaum over microkernel vs. monolithic operating system architecture, Linus Torvalds said,

Portability is for people who cannot write new programs.

What did he mean by that?

答:
Back when Linux was first written, it used features available only on the i386 CPU, which was fairly new and expensive at the time.

That is exactly what linux does: it
  just uses a bigger subset of the 386
  features than other kernels seem to
  do.  Of course this makes the kernel
  proper unportable, but it also makes
  for a /much/ simpler design.  An
  acceptable trade-off, and one that
  made linux possible in the first
  place.

As we went into the 21st century, the features that made the i386 unique became totally mainstream, allowing Linux to become very portable.


问:
Trying to identify IClass, Class, ClassImpl pattern
I've been seeing a lot of code recently that looks like this:

```<code>public interface IFoo { int Bar(); }

public static class Foo
{
    public static IFoo Create() { return new FooImpl(); }
    private class FooImpl : IFoo
    {
        public int Bar () { ... }
    }
}
</code>```

Basically, there is a contract defined by an interface, the the main business object class is a static class that provides factory methods, and there is an embedded class that provides the actual implementation.

There are some advantages to this pattern especially, the clean separation between the contract and the implementation.  Still, it seems a little ugly to me: especially the naming of a static factory class with a business object name rubs me the wrong way.

My questions are...

Is this an established pattern or style of development?

Are there any other advantages besides a rigorous hiding of implementation?

Is there a better way to achieve the same goals?

答:
It looks like a crippled cross between Abstract Factory and Factory Method. It includes a full class, not just a method, but that class is a static utility class, not abstract, thus you have no way of switching to a different Foo implementation.

Hiding the implementation of Foo is fine, however this design is not unit testable. Clients most likely call Foo.Create directly, thus unit tests have a hard time replacing / mocking out FooImpl to any different implementation of IFoo.

I agree with you in that the naming is bad too. The factory should not be mixed with the product it creates.

An alternative could of course be a full Abstract Factory implementation, but this may be overkill for a single product. Very often this can be replaced by Dependency Injection, which is simpler and easy to unit test.


答:
Because the cost of global warming (from those extra CPU cycles scaled by hundreds of millions of PCs plus massive data center facilities) and mediocre battery life (on user's mobile devices), as required to run their poorly optimized code, rarely shows up on most programmer's performance or peer reviews.

It's an economic negative externality, similar to a form of ignored pollution.  So the cost/benefit ratio of thinking about performance at all is mentally skewed from reality.

Hardware designers have been working hard adding power save and clock scaling features to the latest CPUs. It's up to programmers to let the hardware take advantage of these capabilities more often, by not chewing up every CPU clock cycle available.

ADDED: Back in ancient times, the cost of the one computer was millions, so optimizing CPU time was very important.  Then the cost of developing and maintaining the code became greater than the cost of the computers, so optimization fell way out of favor compared with programmer productivity.  Now, however, another cost is becoming greater than the cost of computers, the cost of powering and cooling all those data centers is now becoming greater than the cost of all the processors inside.


问:
What traits do the best testers you've worked with have in common?
Tester and blogger Lanette Creamer recently posted this question on Twitter:

If you are a professional software developer who works with testers, think of the best testers you know. What traits do they have in common?

I thought it would make an excellent question for here.

My thoughts are:

They want to remove ambiguity from requirements even if it means asking awkward questions.

They create new features by seeing the way software "should" work, rather than just how it's documented.

They demonstrate honesty and integrity and encourage but not demand it from those around them. In other words, they model behavior.

What are the traits of the best testers you've worked with?

答:
Sadly, for what is actually a highly skilled and technical role, there are a lot of cowboys out there. Far too many testers have had a long career moving from position to position being interviewed and hired by people who have no idea what testing is about.

The best testers I've met have:

excellent communication skills, in order to liaise with business people and interpret/clarify requirements

the ability to see the application from the perspective of a user unfamiliar with the system

the patience to go through things systematically when required, and can analyse a system so that they really are going through it systematically, not just spending a lot of time

a creative side to them to pick out things developers might not think of

the ability to organise their own time so they spend an appropriate amount of time on exploratory testing, automation, etc rather than just focussing on a single type of testing

an interest in what they do so they keep up with developments and best practices in their field

and lastly, if the tester is working on an agile project

can do test automation in a structured maintainable way - I'm afraid that these days if a tester can't automate things that can be automated (and not everything can) then that tester will never end up being effective in an agile project


问:
What are the arguments for/against Code Generation?
I'm in a position where we've got some brittle code that constructs SQL-like queries via text concatenation with parameters for inputs. The data source that it queries is fast and scalable but lacking tool support. Over time, addition entities and properties have been added to the data source that need changing or have obsoleted others, so the queries need changing.

I can see that this will happen again in a few months and then again.

In order to reduce errors introduced into the text queries, I suggested writing the queries into a separate e.g. .SQL file and then running some kind of code generator tool that could get the schema from the data source and generate a code wrapper around the SQL-like query which was easy to re-generate at any time and would give compile errors for any out-of-date client code.

This idea was met with some skepticism and resistance, even when I offered to fund the development myself.

What are the reasons against doing this? and, for balance, the reasons to go ahead and do it?

(I already saw this post with a couple of answers, but its' not comprehensive)

答:
Because I created and maintain a code generation framework (ABSE) my answers are probably biased, but here go my arguments:

For:

You can "reuse" yourself. Create one generator, use it over and over.

You can repeatedly update the generator and generate code. Change in one place, update everywhere.

Custom code is usually seen as a deterrent, but if your generator supports the inclusion of custom code, this "mix" can suddenly become a good thing.

An expert creates a code generator, the rest of the team can then use it. Everyone becomes as good as the expert. The expert may not like it though :).

Against:

Not suitable to newbies. Raising abstraction requires good thinking and some experience.

Not suitable for one-off development. If you are creating, say, a PHP script just this once, a code generator is never a good idea. Still, you can still generate common language patterns if you use one continuously.


答:
In this case, it depends on your language. I've seen several programming languages that target .NET or Java, and the developers did a "MyLanguage To Java translator" or "MyLanguage To C#/VB.NET translator", and later turn it into "MyLanguage To Java Bytecode" or "MyLanguage To MSIL/CIL Bytecode".

Its your language its similar to C# or VB.NET, perhaps it will be easier, in this case, to make a translator first.

Title: Do You Have To Know CIL To Make A Compiler for .NET?

Body: Assume one wants to create a simple .NET language, or slightly more difficult, a compiler for an existing .NET language. Do you absolutely need to be familiar with the CIL (Common Intermediate Language) to implement a compiler? And do you have to translate the syntax of your language to CIL by hand? Or is there another (more preferable) way? If not, what is the best way to learn CIL and especially to learn how to translate High-Level code to CIL?


问:
Version Control Workflow (Subversion)
I've been learning how to use subversion and would just like someone to clarify whether or not my understanding is correct?

Create a master repository at a given location (be it on a webserver or local).

Add/import files into said repository

Checkout a copy of the repository to work on (or specific files) to a working directory.

Change/work/add certain files.

Commit changes back to the master repository (With a note explaining changes, though changed files are noted, right?)

Happy days...

Assuming this is correct, I have a few questions.

When working in a team, what happens when several people are working on one project and change the same files in different ways in one day?

Surely when these changes are commit, they will overwrite each other?

How should one go about testing their changes before commiting back to the master repo?

Using PHP for my example, should the 'working' directory be in my xampp folder so I can test before commiting. Or should there be two "master repo's" on a webserver - one for testing and one for production?

Apologies for the novice questions - there don't seem to be many tutorials or documentation that cover the basics - I understand the concept of source control for the sake of reverting, tracking changes and what not, but maybe need some clarification on how teams can use it effectively. If the idea is that one person should only ever be working on a single file at a time that just seems a bit... odd. If you're working with an MVC architecture, I can see the need for common views and controllers to be needed to work on by several people.

答:
When working in a team, what happens when several people are working on one project and change the same files in different ways in one day?

Surely when these changes are commit, they will overwrite each other?

No, the one attempting to check in later must merge conflicting changes prior to committing his changes.

How should one go about testing their changes before commiting back to the master repo?

You should unit test your changes before committing them. Any further (integration / system / acceptance) tests are usually done on the committed version.

Or should there be two "master repo's" on a webserver - one for testing and one for production?

You should have one and only one source code repo per project. However, within that single repo, you can have different branches of the same codebase. And you can also deploy the actual version (or different versions) of your project to different environments. You should absolutely have (at least) one test environment next to your production server.

Title: Version Control Workflow (Subversion)


答:
When working in a team, what happens when several people are working
  on one project and change the same files in different ways in one day?

You have a conflict and you have to merge.  Generally the second to commit has to do the merging.

Surely when these changes are commit, they will overwrite each other?

No, there will be an error messages and you will have to merge the different changes.

How should one go about testing their changes before commiting back to
  the master repo?

Continuous testing and a good set of unit tests.

Never commit known broken code.

Using PHP for my example, should the 'working' directory be in my
  xampp folder so I can test before commiting. Or should there be two
  "master repo's" on a webserver - one for testing and one for
  production?

This is called branching.

Title: Version Control Workflow (Subversion)

Body:
I've been learning how to use subversion and would just like someone to clarify whether or not my understanding is correct?

Create a master repository at a given location (be it on a webserver or local).

Add/import files into said repository

Checkout a copy of the repository to work on (or specific files) to a working directory.

Change/work/add certain files.

Commit changes back to the master repository (With a note explaining changes, though changed files are noted, right?)

Happy days...

Assuming this is correct, I have a few questions.

When working in a team, what happens when several people are working on one project and change the same files in different ways in one day?

Surely when these changes are commit, they will overwrite each other?

How should one go about testing their changes before commiting back to the master repo?

Using PHP for my example, should the 'working' directory be in my xampp folder so I can test before commiting. Or should there be two "master repo's" on a webserver - one for testing and one for production?

Apologies for the novice questions - there don't seem to be many tutorials or documentation that cover the basics - I understand the concept of source control for the sake of reverting, tracking changes and what not, but maybe need some clarification on how teams can use it effectively. If the idea is that one person should only ever be working on a single file at a time that just seems a bit... odd. If you're working with an MVC architecture, I can see the need for common views and controllers to be needed to work on by several people.


答:
A more practical question/answer. Does your company allows to use it ?

Its your company working with several D.B. S.Q.L. brands that handle different DDL (s) ?

Each database brand may offer good additional features, like User Defined Types, but, if your company uses several D.B., you may have trouble with the non standard features.

If the company its only you, or you can decide which Databases & features are you going to use, then you may use D.D.L.

I have work with several projects where a User Defined Type could be useful, but, I should stick to more standard features, since we had to deal with several DB. (s).

Title: To Domain or not to Domain

Body:
The SQL92 and SQL99 standards define CREATE DOMAIN DDL constructs. Not all databases support this, or have a different name for it (SQL Server has User Defined Types, for example).

These allow one to define a constrained data-type to be used in their database, to simplify and enforce rules pertaining to the allowed values. Such a data-type could be used in column declarations, in inputs and outputs to stored procedures and functions etc...

I would like to know:

Do people actually use domains in their database designs?

If so to what extent?

How useful are they?

What pitfalls have you encountered?

I am trying to asses the viability of using these in future database development.


问:
Using SVN along with WAMP
I would like to run SVN server on my local machine along with WAMP.
All SVN server binaries include Apache. Whereas I don't need Apache as I'm already running WAMP.

Please let me know if there are any installs available that includes only the SVN server.
If there are none available, shall I go ahead with what's available? And how would I do that without breaking anything.

PS: I tried CollabNet and VisualSVNServer. Both includes Apache.

答:
If you'll check command-line binaries of SVN, you'll find svnserve, which can handle repos over net with svn:// protocol.

Or you can integrate needed parts of VisualSVN Server's config into your Apache and get http-served repos (which in common work better)

Title: Using SVN along with WAMP


问:
What are the advantages of prototype-based OOP over class-based OOP?
When I first started programming Javascript after primarily dealing with OOP in context of class-based languages, I was left confused as to why prototype-based OOP would ever be preferred to class-based OOP.

What are the structural advantages to using prototype-based OOP, if any?  (e.g. Would we expect it to be faster or less memory intensive in certain applications?)

What are the advantages from a coder's perspective?  (e.g. Is it easier to code certain applications or extend other people's code using prototyping?)

Please don't look at this question as a question about Javascript in particular (which has had many faults over the years that are completely unrelated to prototyping).  Instead, please look at it in context of the theoretical advantages of prototyping vs classes.

Thank you.

答:
The main advantage of prototype-based OOP its that objects & "classes" can be extended at runtime.

In Class-based OOP, there are several good features, unfortunately, it depends on the programming language.

Object Pascal (Delphi), VB.Net & C# has a very direct way to use properties (not to be confused with fields) and properties' access methods, while Java & C++, properties are accessed by methods. And PHP has a mixture of both, called "magic methods".

There are some dynamic typing classes, although the main class O.O. languages have static typing. I think static typing with Class O.O. its very useful, because allows a feature called Object Introspection that allows to make those I.D.E. and develop web pages, visually, and quickly.


问:
Why is Java considered more portable than other languages like C++?
What differs between "writing a specific JRE for each platform" for Java developers and "writing a C++ compiler for each platform" for C++ ones?</p>

答:
It's not just the language -- it's the libraries.

Both Java and C++ provide cross-platform libraries. Java provides a richer set.

OwnerDisplayName: Andy Thomas-Cramer


答: The difference is that Java will run on any platform without recompiling.  Having a C++ compiler for each platform isn't the same at all.

Title: Why is Java considered more portable than other languages like C++?

Body: What differs between "writing a specific JRE for each platform" for Java developers and "writing a C++ compiler for each platform" for C++ ones?</p>

OwnerDisplayName: Highland Mark


答:
Java is compile once run anywhere.
C++ is write once compile anywhere.</p>


答: The amount of work for the supporting tools is indeed similar, the difference lies elsewhere. Once a C++ program has been compiled for a platform, you have to compile it again if you want to use it on a different platform. However, when a java program has been compiled, you can move it to any other platform with a runtime environment without having to recompile it.</p>

OwnerDisplayName: Steven


答: The difference is that Java (it's not an acronym) programs can be distributed in a form that can be run on any computer with a JVM installed, but C++ is normally distributed as either source code, which is very user unfriendly, or as a bunch of different binaries for different platforms.</p>


答:
"writing a specific JRE for each platform" is not something you do everytime. Porting the JRE to a new platform is something you need doing only once. This task is generally done by the core maintainer/developers of the program and/or the platform. A lot of factors may come into play when deciding who and how the JRE would be ported. Among other things, it depends on the licensed it's published under (I hear Java is Open Source, so I guess anyone could do it). Funny anecdote, Steve Jobs made a big deal about not wanting to take care of the porting of Java on Mac, around a year ago.

The point is not how or who ports the JRE, but the fact that once it is ported, every Java application should now theoretically run easily on the new machine. In that sense, the JRE forms an abstraction layer, completely hiding the machine, allowing easy porting.

However, reality is not always pretty like this. I won't go as far as calling portability a "myth", but it's true that it's not so perfect. For instance, Java has a package called JNI that allows sending native calls, bypassing the JRE, thus preventing the perfect seamless portability, what Java fans like to call "Write once run everywhere".

As mentioned in the comments, C++'s approach to portability is different. On the one hand, it's a compiled language, and those binaries are almost always platform specific. So c++ executables will never be portable (unlike Java). On the other hand, porting the compiler can sometimes be enough. The community has found that by porting the compiler as well as some core libraries of the language, source codes (and not binaries) could be portable.

However, C++ is widely used in critical systems like compilers, kernels, real-time systems,embedded systems, ... There's a "low level" aspect of C++ that cannot be overlooked, when talking about portability.


问:
Zoom to Fit Points on Surface
I'm attempting to develop a piece of functionality using a 3rd party map control in an application that automatically pans/zooms the map surface to the best possible view given points on map. The map should be centered and zoomed in as close as possible without cutting out any points on the map.

To determine the maps center point, I averaged all of the points on the map surface. This seems to be working fine, but there may be a better approach. The issue I'm running into is how to appropriately zoom in or out to accommodate all points on the map in the "best" possible view.

I'm not very familiar with 3D techniques, so any terminology relating to this problem will probably be new to me. I'm not necessarily looking for a specific algorithm (though I certainly wouldn't turn one down). Mostly, I would like to understand the theory behind approaching such a problem so that I can implement it.

答:
I'm not sure what this question has to do with 3D.  I'm assuming you're specifying points in 2 dimensions:  latitude and longitude.

Just find the max and min latitude and longitude among all the points.  The smallest box that contains them all is (min lat, min long), (min lat, max long), (max lat, max long), (max lat, min long).  That's assuming relatively local points not near the international date line or the poles.

Let's say your points are (1,5), (2,8), and (3,2).  Your minimum latitude is 1, max latitude is 3, min longitude is 2, max longitude is 8.  The smallest bounding box is (1, 2), (1, 8), (3, 8), (3, 2).  Give yourself a little margin so the points aren't right on the edge, and you're good.

Title: Zoom to Fit Points on Surface


问:
Does teaching programming make you a better programmer
I consider myself an intermediate Python programmer and have been offered an opportunity to be a trainer for a beginner Python programming class.

I was wondering if this would really widen my programming repertoire. Has somebody had an enlightening experience after they successfully trained a group of people?

Does it also depend on those people -- whether they're programmers or noob students? (In my case they are intermediate .NET and Java programmers)

What should I expect from them?

One of my fears is -- what if I choked when one of them asked a tangled question. Is this normal?

答:
In my experience, teaching programming did make me better. It forced me to get a much better understanding of concepts I had previously just accepted or taken for granted. When I had to articulate ideas that were old to me but new to students, in a number of different ways (because not everyone learns the same way from the same examples), it eventually led to a deeper understanding of the material for me.

And yes, sometimes students ask questions you don't know the answer to. That's OK, you can tell them you don't know, come up with a possible explanation, and promise to look into it before the next class.