答:
First, most JVMs include a compiler, so "interpreted bytecode" is actually pretty rare (at least in benchmark code -- it's not quite as rare in real life, where your code is usually more than a few trivial loops that get repeated extremely often).

Second, a fair number of the benchmarks involved appear to be quite biased (whether by intent or incompetence, I can't really say). Just for example, years ago I looked at some of the source code linked from one of the links you posted. It had code like this:

```<code>  init0 = (int*)calloc(max_x,sizeof(int));
  init1 = (int*)calloc(max_x,sizeof(int));
  init2 = (int*)calloc(max_x,sizeof(int));
  for (x=0; x<max_x; x++) {
    init2[x] = 0;
    init1[x] = 0;
    init0[x] = 0;
  }
</code>```

Since calloc provides memory that's already zeroed, using the for loop to zero it again is obviously useless. This was followed (if memory serves) by filling the memory with other data anyway (and no dependence on it being zeroed), so all the zeroing was completely unnecessary anyway. Replacing the code above with a simple malloc (like any sane person would have used to start with) improved the speed of the C++ version enough to beat the Java version (by a fairly wide margin, if memory serves).

Consider (for another example) the methcall benchmark used in the blog entry in your last link. Despite the name (and how things might even look), the C++ version of this is not really measuring much about method call overhead at all. The part of the code that turns out to be critical is in the Toggle class:

```<code>class Toggle {
public:
    Toggle(bool start_state) : state(start_state) { }
    virtual ~Toggle() {  }
    bool value() {
        return(state);
    }
    virtual Toggle& activate() {
        state = !state;
        return(*this);
    }
    bool state;
};
</code>```

The critical part turns out to be the state = !state;. Consider what happens when we change the code to encode the state as an int instead of a bool:

```<code>class Toggle {
    enum names{ bfalse = -1, btrue = 1};
    const static names values[2];
    int state;

public:
    Toggle(bool start_state) : state(values[start_state])
    { }
    virtual ~Toggle() {  }
    bool value() {  return state==btrue;    }

    virtual Toggle& activate() {
        state = -state;
        return(*this);
    }
};
</code>```

This minor change improves the overall speed by about a 5:1 margin. Even though the benchmark was intended to measure method call time, in reality most of what it was measuring was the time to convert between int and bool. I'd certainly agree that the inefficiency shown by the original is unfortunate -- but given how rarely it seems to arise in real code, and the ease with which it can be fixed when/if it does arise, I have a difficult time thinking of it as meaning much.

In case anybody decides to re-run the benchmarks involved, I should also add that there's an almost equally trivial modification to the Java version that produces (or at least at one time produced -- I haven't re-run the tests with a recent JVM to confirm they still do) a fairly substantial improvement in the Java version as well. The Java version has an NthToggle::activate() that looks like this:

```<code>public Toggle activate() {
this.counter += 1;
if (this.counter >= this.count_max) {
    this.state = !this.state;
    this.counter = 0;
}
return(this);
}
</code>```

Changing this to call the base function instead of manipulating this.state directly gives quite a substantial speed improvement (though not enough to keep up with the modified C++ version).

So, what we end up with is a false assumption about interpreted byte codes vs. some of the worst benchmarks (I've) ever seen. Neither is giving a meaningful result.

My own experience is that with equally experienced programmers paying equal attention to optimizing, C++ will beat Java more often than not -- but (at least between these two), the language will rarely make as much difference as the programmers and design. The benchmarks being cited tell us more about the (in)competence/(dis)honesty of their authors than they do about the languages they purport to benchmark.

[Edit: As implied in one place above but never stated as directly as I probably should have, the results I'm quoting are those I got when I tested this ~5 years ago, using C++ and Java implementations that were current at that time. I haven't rerun the tests with current implementations. A glance, however, indicates that the code hasn't been fixed, so all that would have changed would be the compiler's ability to cover up the problems in the code.]

If we ignore the Java examples, however, it is actually possible for interpreted code to run faster than compiled code (though difficult and somewhat unusual).

The usual way this happens is that the code being interpreted is much more compact than the machine code, or it's running on a CPU that has a larger data cache than code cache.

In such a case, a small interpreter (e.g., the inner interpreter of a Forth implementation) may be able to fit entirely in the code cache, and the program it's interpreting fits entirely in the data cache. The cache is typically faster than main memory by a factor of at least 10, and often much more (a factor of 100 isn't particularly rare any more).

So, if the cache is faster than main memory by a factor of N, and it takes fewer than N machine code instructions to implement each byte code, the byte code should win (I'm simplifying, but I think the general idea should still be apparent).

Body:
First, most JVMs include a compiler, so "interpreted bytecode" is actually pretty rare (at least in benchmark code -- it's not quite as rare in real life, where your code is usually more than a few trivial loops that get repeated extremely often).

Second, a fair number of the benchmarks involved appear to be quite biased (whether by intent or incompetence, I can't really say). Just for example, years ago I looked at some of the source code linked from one of the links you posted. It had code like this:

  init0 = (int*)calloc(max_x,sizeof(int));
  init1 = (int*)calloc(max_x,sizeof(int));
  init2 = (int*)calloc(max_x,sizeof(int));
  for (x=0; x<max_x; x++) {
    init2[x] = 0;
    init1[x] = 0;
    init0[x] = 0;
  }

Since calloc provides memory that's already zeroed, using the for loop to zero it again is obviously useless. This was followed (if memory serves) by filling the memory with other data anyway (and no dependence on it being zeroed), so all the zeroing was completely unnecessary anyway. Replacing the code above with a simple malloc (like any sane person would have used to start with) improved the speed of the C++ version enough to beat the Java version (by a fairly wide margin, if memory serves).

Consider (for another example) the methcall benchmark used in the blog entry in your last link. Despite the name (and how things might even look), the C++ version of this is not really measuring much about method call overhead at all. The part of the code that turns out to be critical is in the Toggle class:

class Toggle {
public:
    Toggle(bool start_state) : state(start_state) { }
    virtual ~Toggle() {  }
    bool value() {
        return(state);
    }
    virtual Toggle& activate() {
        state = !state;
        return(*this);
    }
    bool state;
};

The critical part turns out to be the state = !state;. Consider what happens when we change the code to encode the state as an int instead of a bool:

class Toggle {
    enum names{ bfalse = -1, btrue = 1};
    const static names values[2];
    int state;

public:
    Toggle(bool start_state) : state(values[start_state])
    { }
    virtual ~Toggle() {  }
    bool value() {  return state==btrue;    }

    virtual Toggle& activate() {
        state = -state;
        return(*this);
    }
};

This minor change improves the overall speed by about a 5:1 margin. Even though the benchmark was intended to measure method call time, in reality most of what it was measuring was the time to convert between int and bool. I'd certainly agree that the inefficiency shown by the original is unfortunate -- but given how rarely it seems to arise in real code, and the ease with which it can be fixed when/if it does arise, I have a difficult time thinking of it as meaning much.

In case anybody decides to re-run the benchmarks involved, I should also add that there's an almost equally trivial modification to the Java version that produces (or at least at one time produced -- I haven't re-run the tests with a recent JVM to confirm they still do) a fairly substantial improvement in the Java version as well. The Java version has an NthToggle::activate() that looks like this:

public Toggle activate() {
this.counter += 1;
if (this.counter >= this.count_max) {
    this.state = !this.state;
    this.counter = 0;
}
return(this);
}

Changing this to call the base function instead of manipulating this.state directly gives quite a substantial speed improvement (though not enough to keep up with the modified C++ version).

So, what we end up with is a false assumption about interpreted byte codes vs. some of the worst benchmarks (I've) ever seen. Neither is giving a meaningful result.

My own experience is that with equally experienced programmers paying equal attention to optimizing, C++ will beat Java more often than not -- but (at least between these two), the language will rarely make as much difference as the programmers and design. The benchmarks being cited tell us more about the (in)competence/(dis)honesty of their authors than they do about the languages they purport to benchmark.

[Edit: As implied in one place above but never stated as directly as I probably should have, the results I'm quoting are those I got when I tested this ~5 years ago, using C++ and Java implementations that were current at that time. I haven't rerun the tests with current implementations. A glance, however, indicates that the code hasn't been fixed, so all that would have changed would be the compiler's ability to cover up the problems in the code.]

If we ignore the Java examples, however, it is actually possible for interpreted code to run faster than compiled code (though difficult and somewhat unusual).

The usual way this happens is that the code being interpreted is much more compact than the machine code, or it's running on a CPU that has a larger data cache than code cache.

In such a case, a small interpreter (e.g., the inner interpreter of a Forth implementation) may be able to fit entirely in the code cache, and the program it's interpreting fits entirely in the data cache. The cache is typically faster than main memory by a factor of at least 10, and often much more (a factor of 100 isn't particularly rare any more).

So, if the cache is faster than main memory by a factor of N, and it takes fewer than N machine code instructions to implement each byte code, the byte code should win (I'm simplifying, but I think the general idea should still be apparent).


问:
Why would it ever be possible for Java to be faster than C++?
Sometimes Java outperforms C++ in benchmarks.  Of course, sometimes C++ outperforms.

See the following links:

http://keithlea.com/javabench/

http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy/

http://blog.cfelde.com/2010/06/c-vs-java-performance/

But how is this even possible?  It boggles my mind that interpreted bytecode could ever be faster than a compiled language.

Can someone please explain?  Thanks!

答:
That is because the final step generating machine code happens transparently inside the JVM when running your Java program, instead of explicit when building
your C++ proram.

You should consider the fact that modern JVM's spend quite a lot of time compiling the byte code on the fly to native machine code to make it as fast as possible.   This allow the JVM to do all kinds of compiler tricks that can be even better by knowing the profiling data of the program being run.

Just such a thing as automatically inlining a getter, so that a JUMP-RETURN is not needed to just get a value, speeds up things.

However, the thing that really has allowed fast programs is better cleaning up afterwards.  The garbage collection mechanism in Java is faster than the manual malloc-free in C.  Many modern malloc-free implementations use a garbage collector underneath.

ContentLicense: CC BY-SA 3.0


问:
Why is the Repository pattern needed in NHibernate?
I am reading the official Your first NHibernate based application.

While the tutorial is good and easy to follow, I am wondering why the Repository pattern is used.

In the various Add, Update, Remove methods in the ProductRepository implementation, the code is nearly identical - they are all using transactions, and the difference is in the "meat" i.e. call session.Save int the Add method, session.Delete in the remove method.
(The page lacks HTML anchors, but you can search the page for the relevant code like public void Remove, public void Add)

That code just "feels wrong".

Why is the author using the Repository pattern - is it just for demonstration of using NHibernate or is that required or some other reason?

Ps. My background is from Ruby on Rails using ActiveRecord so I'm trying to make sense of how NHibernate works/is used.

答: The repository pattern is not required. As for all the other pattern is an "Architectural" decision that you have to make against your business needs. In general the repository Pattern is used to implement the "Entity Persistance Ingorance" that means that your entities don’t know anything on how to persist themselves on your storing device (Database,XML,TextFile,etc). If for example you have an entity Address it won’t contains the persistence logic (you won’t find anywhere something like address.Save or address.Update) but you will pass your entity to a repository method which is in charge to persist the changes</p>

OwnerDisplayName: Zabba

OwnerDisplayName: Massimiliano Peluso


答: Advantage of using repository pattern is to mock your data access layer, so that you can test your business layer code without calling DAL code. There are other big advantages but this seems to be very vital to me.</p>

Title: Why is the Repository pattern needed in NHibernate?

Body:
I am reading the official Your first NHibernate based application.

While the tutorial is good and easy to follow, I am wondering why the Repository pattern is used.

In the various Add, Update, Remove methods in the ProductRepository implementation, the code is nearly identical - they are all using transactions, and the difference is in the "meat" i.e. call session.Save int the Add method, session.Delete in the remove method.
(The page lacks HTML anchors, but you can search the page for the relevant code like public void Remove, public void Add)

That code just "feels wrong".

Why is the author using the Repository pattern - is it just for demonstration of using NHibernate or is that required or some other reason?

Ps. My background is from Ruby on Rails using ActiveRecord so I'm trying to make sense of how NHibernate works/is used.

OwnerDisplayName: Shailesh


答:
But allocation is only half of memory management -- deallocation is
  the other half. It turns out that for most objects, the direct garbage
  collection cost is -- zero. This is because a copying collector does
  not need to visit or copy dead objects, only live ones. So objects
  that become garbage shortly after allocation contribute no workload to
  the collection cycle.

...

JVMs are surprisingly good at figuring out things that we used to
  assume only the developer could know. By letting the JVM choose
  between stack allocation and heap allocation on a case-by-case basis,
  we can get the performance benefits of stack allocation without making
  the programmer agonize over whether to allocate on the stack or on the
  heap.

http://www.ibm.com/developerworks/java/library/j-jtp09275/index.html

Title: Why would it ever be possible for Java to be faster than C++?

Body:
Sometimes Java outperforms C++ in benchmarks.  Of course, sometimes C++ outperforms.

See the following links:

http://keithlea.com/javabench/

http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy/

http://blog.cfelde.com/2010/06/c-vs-java-performance/

But how is this even possible?  It boggles my mind that interpreted bytecode could ever be faster than a compiled language.

Can someone please explain?  Thanks!


答:
Hand rolled C/C++ done by an expert with unlimited time is going to be at least as fast or faster than Java. Ultimately, Java itself is written in C/C++ so you can of course do everything Java does if you are willing to put in enough engineering effort.

In practice however, Java often executes very fast for the following reasons:

JIT compilation - although Java classes are stored as bytecode, this is (usually) compiled to native code by the JIT compiler as the program starts up. Once compiled, it is pure native code - so theoretically it can be expected to perform just as well as compiled C/C++ once the program has been running for long enough (i.e. after all the JIT compilation has been done)

Garbage collection in Java is extremely fast and efficient - the Hotspot GC is probably the best all-round GC implementation in the world. It's the result of many man-years of expert effort by Sun and other companies. Pretty much any complex memory management system that you roll yourself in C/C++ will be worse. Of course you can write pretty fast/lightweight basic memory management schemes in C/C++, but they won't be nearly as versatile as a full GC system. Since most modern systems need complex memory management, Java therefore has a big advantage for real-world situations.

Better platform targetting - by delaying compilation to application start-up (JIT compilation etc.) the Java compiler can take advantage of the fact that it knows the exact processor it is executing on. This can enable some very beneficial optimisations that you wouldn't be able to do in pre-compiled C/C++ code that needs to target a "lowest common denominator" processor instruction set.

Runtime statistics - because JIT compilation is done at runtime, it can gather statistics while the program is executing which enable better optimisations (e.g. knowing the probability that a particular branch is taken). This can enable Java JIT compilers to produce better code than C/C++ compilers (which have to "guess" the most likely branch in advance, an assumption which may often be wrong).

Very good libraries - the Java runtime contains a host of very well written libraries with good performance (especially for server-side applications). Often these are better than you could write yourself or obtain easily for C/C++.

At the same time C/C++ also have some advantages:

More time to do advanced optimisations - C/C++ compilation is done once, and can therefore spend considerable time doing advanced optimisations if you configure it to do so. There's no theoretical reason why Java couldn't do the same, but in practice you want Java to JIT-compile code relatively quickly, so the JIT compiler tends to focus on "simpler" optimisations.

Instructions that aren't expressible in bytecode - while Java bytecode is fully general purpose, there are still some things you can do at a low level that you can't do in bytecode (unchecked pointer arithmetic is a good example!). By (ab)using these kind of tricks you can get some performance advantages

Less "safety" contstraints - Java does some extra work to ensure that programs are safe and reliable. Examples are bounds checks on arrays, certain concurrency guarantees, null pointer checks, type safety on casts etc. By avoiding these in C/C++ you can get some performance gains (although arguably this can be a bad idea!)

Overall:

Java and C/C++ can achieve similar speeds

C/C++ probably has the slight edge in extreme circumstances (it's not surprising that AAA game developers still prefer it, for example)

In practice it will depend on how the different factors listed above balance out for your particular application.


问:
My customer wants me to record a video of how I develop his software product
Working as a freelancer, I often see strange requests from my customers, some of which can negatively affect my daily work¹, and others trying to set some sort of control. I usually encounter those things during preliminary negotiations, so it's easy enough at this stage to explain to the customer that I do care about my work and productivity and expect my customers to trust my work.

Things were much harder² on a project I just accepted, since it's only after the end of the negotiations (the contract has already been signed and did not mention anything about video tracking) and after I started to work on the project that my customer requested that I record a video of all I do on my machine when working on his project, that is, a video which will show that I move the cursor, type a character, open a file, move a window, etc.

I work in my own company, using my own PCs.

I answered to this customer that such request cannot be accepted, since:

Hundreds of hours of work on a dual-screen PC will require a large amount of disk space for the recorded videos. If I don't care about space, I do care about this customer wasting my bandwidth downloading those videos.

Recording a video can affect the overall performance and decrease my productivity (which is not actually true, since the machine is powerful enough to record this video without performance loss, but, well, it still looks like a valid argument).

I can't always remember to turn the video recording on before starting the work, and off at the end.

It may be a privacy concern. What if I switch to my mails when recording the video? What if, to open the directory with the files about this customers project, I first open the parent directory containing the list of all of my customers?

Such video cannot be a reliable source to track the cost of a project (I'm paid by the hour), since some work is done with just a pencil and a paper (which is actually true, since I do lots of draft work without using the PC).

Despite those points, the customer considers that if I don't want to record the video, it's because I have something to hide and want to lie about the real time spent on his project³.

How to explain to him that it is not usual practice for freelancers to record videos of their daily work, and that such extravagant requests must be reserved for exceptional circumstances⁴?

¹ The most frequent example is to be requested to work through Remote Desktop on a more-than-slow server which uses a more-than-slow Internet connection, or to be forced to use outdated software such as Windows Me without serious justification such as legacy support.

² In fact, I already did a lot of management and system design related work, which is essential, but usually misunderstood by customers and perceived as a waste of time and money. Observing the concerned customer, I'm pretty sure that he will refuse to pay a large amount of money for what was already done, since there is actually zero lines of code. Even if legally I can easily prove that there was a lot of work undertaken on the design level, I don't want to end my relation with this customer in a court.

³ Which is not as risky as it could be, since I gave this customer the expected and the maximum cost of the project, so the customer is sure to never be asked to pay more than the maximum amount, specified in the contract, even if the real work costs more.

⁴ One case when I effectively record on my own initiative the video of actions is when I have to do some manipulations directly on a production server of a customer, especially when it comes to security issues. Recording those steps may be a good idea to know precisely what was done, and also ensure that there were no errors in my work, or see what those errors were.

First update

Since the question attracted much more attention and had many more answers than I expected, I imagine that it can be relevant to other people, so here is an update. First, to summarize the answers and the comments, it was suggested to (ordered randomly):

Suggest other ways of tracking, as shown in Twitter Code Swarm video, or deliver a "short milestone with a simple, clear deliverable, followed by more complex milestones", etc.

Explain that video is not a reliable source and can be faked, and that it would be difficult to implement, especially for support.

Explain that video is not a reliable source since it shows only a small part of the work: a large amount of work is done without using a computer, not counting the extra hours spent thinking about a solution to a problem.

Stick with the contract; if the customer wants to change it, he must expect new negotiations and a higher price.

Do the video, "but require that the customer put [the] entire fee into an escrow account", require a lawyer to video tape all billable time, etc., in other words, "operate in an environment void of trust", requiring the customer to support the additional cost.

Search for the laws which forbid this. Several people asked in what country I live. I'm in France. Such laws exist to protect the employees of a company (there is a strict regulation about security cameras etc., but I'm pretty sure nothing forbids a freelancer to sign consciously a contract which forces him to record the screen while he works on a project.

Just do it and send the videos: the customer will "watch a few ten second snippets of activity he won't understand", then throw those videos away.

Say no. After all, it's my business, and I'm the only one to decide how to conduct it. Also, the contract is already signed, and has nothing about video tracking.

Say no. The processes and practices I employ in my company can be considered as trade secrets and are or can be classified.

Quit. If the relation starts like this, chances are it will end badly sooner or later. Also, "if he's treating you like a thief - and that is what he's suggesting - then it's just going to get worse later when XYZ feature doesn't work exactly the way he envisioned".

While all those suggestions are equally valuable, I've personally chosen to say to my customer that I accept to do the videos, but in this case, we must renegotiate the contract, keeping in mind that there will be a considerable cost, including the additional fee for copyright release. The new overall cost would be on average three times the actual cost of the project. Knowing this customer, I'm completely sure that he would never accept to pay so much, so the problem is solved.

Second update

The customer effectively declined the proposal to renegotiate the original contract, taking into account the considerable additional cost. He agreed to continue the project without video recording.

The project continued without video recording. Eventually, the customer seemed satisfied by the final result and cost, so the video recording was not mentioned again.

答:
Using a program like AutoScreenShot, you can easily make a (sped-up) video of the development process.

It doesn't take up that much space (one small ~80kb jpeg every 30 seconds), and you don't have to worry about turning it off because keeping it on helps with all sorts of things (proving the time it took to develop, if need be; going through your day to see all the things you wasted time on; etc).

I keep it on all the time.  A month's worth of PC use takes up about 3GB (after which it automatically gets deleted).

ContentLicense: CC BY-SA 4.0


问:
Why don't we use browser detection and platform-specific CSS?
Nowadays, the common phenomena is to develop a website for a browser and then corresponding apps for Android phones, iPhone, tablets and so on. </p>

<p>Since all the platforms come with a browser, why aren't companies using CSS to accommodate them? Surely we can detect from the request which browser was used and from which platform the request came. Reading those values, why don't we just implement the corresponding CSS for different platforms. Like we do for IE, Chrome and Safari. This way we can use the platforms' browser capabilities and don't need to develop subsequent apps for a platform.  </p>

答:
Generally what you have is one website for platforms that may accommodate large screens (PC, Mac, tablets, etc.) and another website for smaller platforms. There is a reason to that.

Most companies I worked with tend to have short-term vision and as such, do not specify at all or/and do not prepare anything for a "lite" version of their website. Only when the full-sized website is ready and alive on the Internet do they start to think about the mobile versions... Now, this mindset is changing slowly but will progressively be in people's (ont only developers, but managers too) minds to think of all platforms at once before starting the development of a website. The fact is that it is generally much harder to design afterwards if it was not foreseen.

Also there is another "technical" reason for developing separate websites. The thing is that since you don't have that much screen space you not only need to effectively use CSS to display information in a user-friendly way, but you may also need to display "less" information, and only the most important one (by the way the "mobile" version of StackExchange is a perfect example of how information should be presented, it looks great!). You can hide secondary information with CSS, but some time will be wasted retrieving this information from your data-access layer, using this information in your dynamic pages... and then hiding it with CSS because it is not displayed on smaller screens. Time is money. We all know what happens when a website takes too long to load, we just don't use it anymore.

Now, we can all agree that it is achievable only with CSS (and some client and server side browser detection) but you need to develop your website keeping that goal in your mind from the start. Often you will realize for example that your navigation system with big menus and such cannot properly work on mobile phones, that your pictures take too much space/size, that your HTML code is ugly, etc. This is often the case of websites that exist for some time already, but not necessarily. This may be also because sometimes is "cleaner" to have separate websites/views.

That is why you so often have to make a decision between hacking mobile-specific CSS into your full fledged website, OR quickly developing a "lite" version for smaller screens.

Edit: I forgot to explicitly answer the question. My answer is that browser detection (client-size with JS AND server-side) and CSS are in fact used to display different views of your website depending on the size of screen readers.

Finally: check out this article, it has examples of the different approaches one can take to create a mobile version of a website.


答:
The reality is they are both just high level assemblers that do exactly what the programmer tells them to, exaclty how the programmer tells them to in the exact order the programmer tells them. The performance differences are so small as to be inconsequential to all practical purposes.

The language is not "slow", the programmer wrote a slow program. Very rarely will a program written the best way in one language outperfrom (to any practical purpose) a program doing the same thing using the best way of the alternate language, unless the author of the study is out to grind his particular axe.

Obviously if you are going to a rare edge case like hard realtime embedded systems, the language choice may make a difference, but how often is this the case? and of those cases, how often is the correct choice not blindly obvious.


问:
How do I know if the compiler broke my code and what do I do if it was the compiler?
Once in a while C++ code will not work when compiled with some level of optimization. It may be compiler doing optimization that breaks the code or it may be code containing undefined behavior which allows the compiler to do whatever it feels.

Suppose I have some piece of code that breaks when compiled with higher optimizations level only. How do i know if it's the code or the compiler and what do I do if it's the compiler?

答:
I would say it is a safe bet that, in  the vast majority of the cases, it is your code, not the compiler, that is broken. And even in the extraordinary case when it is the compiler, you are probably using some obscure language feature in an unusual way, for which the specific compiler is not prepared; in other words, you could most likely change your code to be more idiomatic and avoid the weak spot of the compiler.

At any rate, if you can prove that you found a compiler bug (based on the language spec), report it the compiler developers, so that they may get it fixed some time.


答: Just as usual, as with any other bugs: perform a controlled experiment. Narrow down the suspicious area, turn off the optimisations for everything else and start varying the optimisations applied to that chunk of code. Once you get a 100% reproducibility, start varying your code, introducing things that might break certain optimisations (e.g., introduce possible pointer aliasing, insert external calls with potential side effects, etc.). Looking at the assembly code in a debugger might help as well.</p>

Title: How do I know if the compiler broke my code and what do I do if it was the compiler?

Body:
Once in a while C++ code will not work when compiled with some level of optimization. It may be compiler doing optimization that breaks the code or it may be code containing undefined behavior which allows the compiler to do whatever it feels.

Suppose I have some piece of code that breaks when compiled with higher optimizations level only. How do i know if it's the code or the compiler and what do I do if it's the compiler?


答:
I started writing a comment and then decided its too long and too much to the point.

I would argue that it is your code that is broken. In the unlikely event that you've discovered a bug in the compiler - you should report it to the compiler developers, but that's where the difference ends.

The solution is to identify the offending construct, and refactor it so that it would do the same logic differently. That would most likely solve the issue, whether the bug is on your side or in the compiler.


答:
Isolate the problematic spot and compare the observed behavior to what should happen according to the language spec. Definitely not easy, but that's what you have to do to know (and not just assume).

I probably wouldn't be that meticulous. Rather, I would ask the compiler maker's support forum / mailing list. If it's really a bug in the compiler, then they might fix it. Probably it would be my code anyway. For example, language specs regarding memory visibility in threading can be quite counterintuitive, and they could become apparent only when using some specific optimization flags, on some specific hardware (!). Some behaviour could be undefined by the spec, so it could work with some compiler / some flags, and not work with some other, etc.


答:
If you want to know whether it is your code or the compiler, you have to perfectly know the specification of C++.

If doubt persists, you have to perfectly know x86 assembly.

If you are not in the mood of learning both to the perfection, then it is almost certainly an undefined behaviour that your compiler resolves differently depending on optimization level.


答:
Making CSS specific for each platform is possible, but a lot of work. It also means maintaining multiple CSS files. Also, it is better to do feature-detection, instead of browser detection. I'm no expert on the matter, but you can just Google it, and you'll get enough results.

But, you say, isn't it also a lot of work to build and maintain multiple apps for multiple platforms? It is, but I think another reason comes into play here. And that is that native apps is what a lot of people expect these days. Native apps also have better/different capabilities than browsers, probably also better performance. Plus, native apps can be run when offline. And finally, native apps can be sold in an app store, creating revenue.

A mobile website probably also means using the lowest common denominator. So if a feature is supported by mobile browser X, but not by mobile browser Y, you can't use it or need a workaround. Then it's probably better to have native apps and use the full potential of the platform, without having to worry about the other platform.

So in short, the reasons can be

customers expect it

better performance and/or possibilities

the ability to sell your app in an app store

Title: Why don't we use browser detection and platform-specific CSS?

Body:
Nowadays, the common phenomena is to develop a website for a browser and then corresponding apps for Android phones, iPhone, tablets and so on. </p>

<p>Since all the platforms come with a browser, why aren't companies using CSS to accommodate them? Surely we can detect from the request which browser was used and from which platform the request came. Reading those values, why don't we just implement the corresponding CSS for different platforms. Like we do for IE, Chrome and Safari. This way we can use the platforms' browser capabilities and don't need to develop subsequent apps for a platform.  </p>


答:
Re-read your code thorougly.  Make sure you aren't doing things with side-effects in ASSERTs, or other debug (or more general, configuration) specific statements.  Also remember that in a debug build memory gets initialized differently - telltale pointer values you can check here: Debugging -  Memory Allocation Representations.  When running from within Visual Studio you are nearly always using the Debug Heap (even in release mode) unless you explicitly specify with an environment variable that this is not what you want.

Check your build.  It's common to get problems with complex builds in other places than the actual compiler - dependencies often being the culprit.  I know that "have you tried completely rebuilding" is almost as infuriating an answer as "have you tried reinstalling windows", but it often does help.  Try: a) Rebooting.  b) Deleting all your intermediate and output files MANUALLY and rebuilding.

Look through your code to check for any potential locations where you might be invoking undefined behavior.  If you've been working in C++ for a while, you'll know there are some spots where you think "I'm not ENTIRELY sure I'm allowed to assume that..." - google it or ask here about that particular type of code to see whether it is undefined behavior or not.

If that still doesn't seem to be the case, generate preprocessed output for the file that is causing the problems.  An unexpected macro expansion can cause all kinds of fun (I am reminded of the time a colleague decided a macro by the name of H would be a good idea...).  Examine the preprocessed output for unexpected changes between your project configurations.

Last resort - now you really are in compiler bug land - look at the assembly output.  This might take some digging and fighting just to get a handle on what the assembly is actually doing, but it's actually quite informative.  You can use the skills you pick up here to evaluate micro-optimizations as well, so all is not lost.


问:
Overcoming general lack of UI design skill in developers
I have been told, and have found for myself, that lots of developers are not good at UI design  (I don't know how true is this) but it is true about me at least.

In web development good code development skills are not enough without great skills in UI design to go with them.

So for me, and many developers like me, that only have half of the thing (good development skills) how should we complete our other half other than paying for a designer?

Is using Open Source web templates with little modifications the best solution for this, or are there other options?

答:
still in web development good development skills is not enough without great skills in designing

I don't know if this statement is true, I think it depends on where you work.

For example a smaller company will probably require you to be more flexible with your skillset, whereas a large company might not have the same expectation and you could actually spend all your time developing while a design team works on the designing.

Microsoft have actually updated their toolset to highlight the clear separation between developers and designers. They have introduced Expression Blend with WPF which now means that the developer can work on the functionality of a piece of software and someone else can do the design for it. They both use different tools, they can both work on the project at the same time but one does functionality and one does the design.

The developer specifies the data points and the designer displays them.


答: In over 30 years of programming, the number of genuine compiler (code generation) bugs I've found is still only ~ 10. The number of my own (and other people's) bugs I've found and fixed in the same period is probably > 10,000. My "rule of thumb" then is that the probability of any given bug being due to the compiler is < 0.001.</p>


答:
I am a developer who is also not so great at design.  I try to my hardest, when working on a project where I must do designing, to keep things as simple as possible.  I take a very logical approach and design only for user experience.  I cant make it look truly beautiful, but I can make it user friendly and relatively pleasing to the eye.

I have read several of these books: http://www.uxbydesign.org/2009/06/24/20-user-experience-books-you-should-own/ and they have really helped me out.

edit my favourite on that list is Don’t Make Me Think: A Common Sense Approach to Web Usability, 2nd Edition by Steve Krug

Title: Overcoming general lack of UI design skill in developers

Body:
I have been told, and have found for myself, that lots of developers are not good at UI design  (I don't know how true is this) but it is true about me at least.

In web development good code development skills are not enough without great skills in UI design to go with them.

So for me, and many developers like me, that only have half of the thing (good development skills) how should we complete our other half other than paying for a designer?

Is using Open Source web templates with little modifications the best solution for this, or are there other options?


问:
What are the options when Sql generated by ORM needs tuning?
I am starting working on a web project using django. While researching whether to use Sqlalchemy or raw sql when django orm is not sufficient which is also a question I asked here
Raw Sql vs SqlAlchemy when Django ORM is not enough

One question bugged me.

As the load on the website increases and we find out that sql queries ran by ORM needs tuning. But we have no control on how does an ORM executes queries. In that case we have to use raw sql queries because they give us the best control.

But if we start using raw sql queries, all the benefits of using an ORM in first place are gone. We are stuck with both sql and orm code which will surely mess up the reading and maintainability of the code.

It feels to me that we are opting for easy code in lieu of many problems later. No doubt our initial code will be fast and easy maintainable but this can cause later problems.

I would like to know thoughts of others on it. I am not starting a question comparing orms and sql but I would like to know what are the options when we have created web app using ORM and comes the situation when its clear that ORM is not supporting our cause?

答:
This is pretty straightforward. Two solutions :

Tune the ORM. This is the application of separation of concerns and the cleaner solution in the long run. Anyway this has drawbacks.

The ORM codebase could be hard to tweak.

This could be hard to achieve in a given deadline.

The tweak has to be ported to other versions of the ORM, or continuous obolescance will arise pretty quickly. Working with people behind the ORM is the way to go, but some company policies can prevent it.

The ORM can be impossible to modify that way. It can be a proprietary software or the company organisation could prevent you from doing this.

Use manually done queries mapped by the ORM.

This is easy and fast to do. get the job done.

Has to be unique, or you codebase will be quickly doomed with such hacks everywhere.

Has to be packed in an abstraction. Make it look like standard use of the ORM. This limits the dirtyness to a small portion of code.

The ORM may not provide this function (and if it the case, you probably choosed a crappy one).

Depending on the conext and deadlines, solution 2 is a real world solution, even if it not clean. Technical debt can be made in a project with precaution to limit it to a small portion of code and justified by some extra technical constraints.


答:
You can also look for succesful examples of "similar" sites to get ideas for layouts, graphics and designs.  With a bit of tweaking in your favorite paint program you can borrow a lot of ideas and make them your own.  Don't copy outright - it's not only bad manners, it's probably also illegal in most cases.

Once you've borrowed a few times you'll start to get a better feel for the designs of succesful sites, and you'll get to know the tools to make those designs as well (with your small tweaks).


答:
While a completely optimized Java program will seldom beat a completely optimized C++ program, differences in things like memory management can make a lot of algorithms idiomatically implemented in Java faster than the same algorithms idiomatically implemented in C++.

As @Jerry Coffin pointed out, there are a lot of cases where simple changes can make the code much faster -- but often it can take too much unclean tweaking in one language or the other for the performance improvement to be worthwhile. That's probably what you'd see in a good benchmark that shows Java doing better than C++.

Also, though usually not all that significant, there are some performance optimization that a JIT language like Java can do that C++ can't. The Java runtime can include improvements after the code has been compiled, which means that the JIT can potentially produce optimized code to take advantage of new (or at least different) CPU features. For this reason, a 10 year old Java binary might potentially outperform a 10 year old C++ binary.

Lastly, complete type safety in the bigger picture can, in very rare cases, offer extreme performance improvements. Singularity, an experimental OS written almost entirely in a C#-based language, has much faster interprocess communication and multitasking due to the fact that there's no need for hardware process boundaries or expensive context switches.


答:
Design (of anything) is a negotiation between the needs of the various stakeholders (customer, developer, users). None of the stakeholders are usually in a good position to create the best design because they tend to understand their own needs best and put them above the needs of the other stakeholders. A good designer can identify the needs of the various stakeholders -- often needs that the stakeholder himself doesn't realize he has -- and come up with a solution that  works for everybody.

You've probably seen this yourself many times. Users think about how they have to interact with a system, usually in terms of some other system that they're already familiar with. Developers think mostly in terms of how the system works. Customers usually want something that will solve all their problems, or else they want to solve some very specific problem for the least cost.

To become a good designer, you have to learn to stop thinking ahead to how you'll implement something. Instead, you must focus on what the other stakeholders are telling you about what they need and want, and you have to be able to read between the lines. Like developers, customers and users often have some preconceived solution in mind, and they tend to describe that solution instead of the underlying requirements. (That said, it's important to realize that sometimes a customer means what they say when they tell you exactly what they want; if you're not sure, ask.)

More superficially, the aesthetic design of a UI is also something that some developers have trouble with. I think that's partly because software developers often don't have much training in aesthetics -- CS students may not have much time for art classes. It's also partly again because we're more interested in how something works than we are in what it looks like; we just don't care if a button's corners have a 9-pixel radius or a 10-pixel radius. These two factors are surely related. Sometimes you can overcome this by relying on canned solutions in the form of UI frameworks, and using pre-designed components has the advantage of unifying your own work visually with other applications on the same system. You can improve your aesthetic skills by reading, looking at other people's work, and paying close attention to the visual details that you might have ignored in the past. You should also try to understand the logic behind visual differences: Do square-cornered buttons mean something different from rounded buttons? How is color used? etc.


答:
To be honest, UI designing is all together a different thing. A developer always thinks of a subtle design and isn't too creative when it comes to designing. The definite approach i feel is to keep a different developer for UI design. Though it adds to the cost but will definitely help you reach better results.

For someone who does both things himself, never really gives the best result. So, IMHO these two different aspects should be assigned to two different developers. A little knowledge of HTML and CSS for skinning and theme development is recommended in case of different CMS, but when you need to develop an entirely new design, consult a UI designer.


答:
I can definitely recommend Joel Spolsky's book User Interface Design for Programmers. In this book he pretty much takes the approach that you are looking for: Explaining why UI design matters to programmers. For some online-related material:

Designing for People Who Have Better Things To Do With Their Lives


问:
Was getting a computing science degree easier 10 years ago
I am currently a 3rd year computing science student at a Canadian University. I find it quite challenging, and extremely interesting. One thing  that i have noticed is that each person i speak to that took a class 3 or so years ago learned much less than i did in the same class, and people who are taking 1st year classes are doing more than i remember doing in my 1st year classes. Is this just me remembering stuff bad, or do you believe that getting a computing science degree was easier 10 (or even 5) years ago? </p>

答:
Computer science degrees are driven by the IT industry. Universities will churn out the type of students that companies demand (for the most part).

Things like parallel programming and mobile development are starting to come to the fore.

And don't forget as time goes on universitys get better at teaching their courses. The first class to take a particular module are basically the guinea pigs and as the years go on the university learns what's good, what's bad, what's useful and what's not. They can adapt their course.

ContentLicense: CC BY-SA 2.5


答:
I really like and agree with deadalnix's answer so I won't bother repeating his points, but one more possible option that I have done in the past was to use a tuned views.

I normally don't like the use of views but if a performance or database intensive read operation should be done in a specific way and the ORM can't be tweaked for this it can be easier to write raw tuned SQL for a view and map a read-only ORM entity to that.

With that being said I view it as a quick solution and a more robust solution would likely be something like SQLAlchemy that was mentioned above.

Title: What are the options when Sql generated by ORM needs tuning?

Body:
I am starting working on a web project using django. While researching whether to use Sqlalchemy or raw sql when django orm is not sufficient which is also a question I asked here
Raw Sql vs SqlAlchemy when Django ORM is not enough

One question bugged me.

As the load on the website increases and we find out that sql queries ran by ORM needs tuning. But we have no control on how does an ORM executes queries. In that case we have to use raw sql queries because they give us the best control.

But if we start using raw sql queries, all the benefits of using an ORM in first place are gone. We are stuck with both sql and orm code which will surely mess up the reading and maintainability of the code.

It feels to me that we are opting for easy code in lieu of many problems later. No doubt our initial code will be fast and easy maintainable but this can cause later problems.

I would like to know thoughts of others on it. I am not starting a question comparing orms and sql but I would like to know what are the options when we have created web app using ORM and comes the situation when its clear that ORM is not supporting our cause?


问:
Is it true that having the Nexus S is much better as an Android developer?
Soon, I'll be starting Android development, as I know a bit of Java. I'll also be getting an Android phone. My two options are the Nexus S and the Atrix 4G. I've heard the Nexus series is ideal for developers - can someone tell me why? Why is getting the Atrix bad as a developer?</p>

答:
I'd go for a slower handset - pref the current most popular rather than the best to develop on.  The majority of your users aren't going to be using the latest and greatest so if you are developing anything which pushes your dev handset to the limit, and you have a great handset, chances are that a lot of your users won't be able to use your application.

I've encountered handset specific issues with Android programs I've written in the past, so it's probably a good idea to make sure this doesn't happen to the handset most likely to be used by the people who want to download your app.

To be honest, I'd get multiple handsets (2nd hand off ebay - don't bother buying new) - work out what range of handsets (in terms of performance and screen size) you want to support and try and get a handset near the bottom of that range, one near the middle and one near the top - if you do this and get different screen sizes that should cover your bases.  I prefer this method to relying too much on the emulator as it'll let you play with the app on the different handset speeds and screen sizes and it'll give you much better hands on experience than the emulator can.


答: Remember that design can be tested too, not only code. Start simple, try out your design on a small group of people, record their feedback and go from there. This can help you identify problems with your design and give you ideas about what could/should be done different. Then revise the design and iterate.</p>


问:
How often do you use Formal UML?
I used ad-hoc MUML (made-up modeling language) to design and explain system fairly frequently.  It looks similar to UML and tends to be pretty well understood.

However, I've had a professor or two that harped on the use of strict, formal UML, as close to the spec as possible.  I always suspected that strict UML wasn't really as common as they claimed.  So, how 'bout it- how often do you actually draw out complete diagrams that use all the proper line endings, multiplicity, member type symbols, etc?

答: I use just enough UML (in terms of both the types of diagrams and the content of the information in the diagram) to get my point across to allow myself or someone else to implement the system or subsystem. And the only reason I use UML is because its a widely known set of symbols that each mean something very specific, so there's no ambiguity - any software engineer should be able to look at the diagram and understand what I'm trying to say about the system.</p>

Title: How often do you use Formal UML?


问:
What's a neat project to help me get used to the modern environment?
I haven't been programming for almost a decade. I used to be able to program in QBasic, Turbo Pascal, C, C++, Visual Basic and Assembly. I have no knowledge in any other programming language (other than HTML).

I want a project (in some programming language) to help me acquaint myself with the new environment (unix, python, perl, java, flash?) in a way that would give me the feeling that I've gained a mini-super-power. By that I mean something that give me the feeling of hacking (not actually learn about hacking, but just like learning C for the first time feels like hacking). Something that would put my programming skills to use in a way that the programming languages I do (did) know don't.

答: In my mind there are two mainstream lanaguages (and their associated class hierarchies) in which to learn - C# and Java. Depending on the enviornment you are targeting, I'd start with one of those. I'm not saying all these newer dynamic languages are not good to learn, but the classic C#/Java would be an easier transition for you coming from C/C++/QuickBasic</p>

OwnerDisplayName: Shannon

LastEditorDisplayName: Shannon


答:
If your ORM does not allow you to change the SQL, may be you can tweak the SQL by using stored procedures.
Also, make sure the problem is in the SQL, the performance can suffer because your table design or your indexing strategy. Those are outside the ORM scope, and your DBA should be able to figure out what to do.</p>


答: Steve Brookes has a very interesting blog about a new course in functional programming that he taught last spring to freshmen at Carnegie Mellon.  This is a very different approach than when I attended CMU ten years ago.  I believe Object Oriented programming is now an optional course.  They're putting much more emphasis on verification and parallel algorithms in the new CS curriculum.  I'm not sure whether this new curriculum is easier or harder, but it's definitely different.</p>

Title: Was getting a computing science degree easier 10 years ago

Body: I am currently a 3rd year computing science student at a Canadian University. I find it quite challenging, and extremely interesting. One thing  that i have noticed is that each person i speak to that took a class 3 or so years ago learned much less than i did in the same class, and people who are taking 1st year classes are doing more than i remember doing in my 1st year classes. Is this just me remembering stuff bad, or do you believe that getting a computing science degree was easier 10 (or even 5) years ago? </p>


答:
With the introduction of HTML, creating a simple non-ugly looking site became a challenge. While you may have the concept, it takes several tricks, tools, ready made graphics and CSS knowledge to get it right. Also, usability techniques and other human factors influencing the design process are required to produce the sharp looking pages.

Developers spend most of thier time batteling learning complex languages, OOP, ORM, SQL, T-SQL, etc. Also they rarely invest in tools for creating web sites (most are expensive).

As a result, many developers suffer from their inability to produce stunning web pages. I believe that if you learn the tools required, you will be able to create good pages too.

It is also important to know what your roll is in the application development process. You may find that web design is a nice to have skill rather being a mandatory skill. In large projects, it should not be a programmer task for the above mentioned reasons at least.

I found that this tool is a great tool, it may help you:

Artisteer

Take a look at it and try the demo, it is really good.


答:
You're just going to have to fake it and copy other designs. Avoid anything fancy except for one or two features that will be a major benefit to users. Follow some basic practices of limiting fonts, colors and clutter.

Don't be afraid to post questions on UI.stackexchange.com


答:
The first place I would start is by better tuning the database to handle the queries -- add indexes before changing code, it is shocking what they can do for you. </p>

<p>If you do need to go the custom SQL route, use the orms custom SQL facility if it has one. I don't think using custom SQL here and there removes all advantages of the orm, especially if it stays within the data layer. </p>

Body:
The first place I would start is by better tuning the database to handle the queries -- add indexes before changing code, it is shocking what they can do for you.

If you do need to go the custom SQL route, use the orms custom SQL facility if it has one. I don't think using custom SQL here and there removes all advantages of the orm, especially if it stays within the data layer.


答:
The problem is, you've chosen with your customer that you will be payed by hours, not by effects. This is very attractive to programmer usually, because he need not to analyze, how much the development will take and he takes no risk of under-estimating the costs.

Otherwise, however, the problem is you will actually earn less if you do your job faster. It gives no motivation to make things quick done. From the customers point of view everything is OK as long as he sees the progress and the total cost will not exchange the amount of what he 'thought it would cost'.

Propably this amount was exceeded and now the customer thinks you're billing him for more hours you actually works on the project. He pay you for hours, and when he questions the hours specified, you have to prove him that you've worked f.g. 100 hours, and not 50. In fact, pay-for-hours is not as attractive settlement method for developer as it would see on begin.

Title: My customer wants me to record a video of how I develop his software product

Body:
Working as a freelancer, I often see strange requests from my customers, some of which can negatively affect my daily work¹, and others trying to set some sort of control. I usually encounter those things during preliminary negotiations, so it's easy enough at this stage to explain to the customer that I do care about my work and productivity and expect my customers to trust my work.

Things were much harder² on a project I just accepted, since it's only after the end of the negotiations (the contract has already been signed and did not mention anything about video tracking) and after I started to work on the project that my customer requested that I record a video of all I do on my machine when working on his project, that is, a video which will show that I move the cursor, type a character, open a file, move a window, etc.

I work in my own company, using my own PCs.

I answered to this customer that such request cannot be accepted, since:

Hundreds of hours of work on a dual-screen PC will require a large amount of disk space for the recorded videos. If I don't care about space, I do care about this customer wasting my bandwidth downloading those videos.

Recording a video can affect the overall performance and decrease my productivity (which is not actually true, since the machine is powerful enough to record this video without performance loss, but, well, it still looks like a valid argument).

I can't always remember to turn the video recording on before starting the work, and off at the end.

It may be a privacy concern. What if I switch to my mails when recording the video? What if, to open the directory with the files about this customers project, I first open the parent directory containing the list of all of my customers?

Such video cannot be a reliable source to track the cost of a project (I'm paid by the hour), since some work is done with just a pencil and a paper (which is actually true, since I do lots of draft work without using the PC).

Despite those points, the customer considers that if I don't want to record the video, it's because I have something to hide and want to lie about the real time spent on his project³.

How to explain to him that it is not usual practice for freelancers to record videos of their daily work, and that such extravagant requests must be reserved for exceptional circumstances⁴?

¹ The most frequent example is to be requested to work through Remote Desktop on a more-than-slow server which uses a more-than-slow Internet connection, or to be forced to use outdated software such as Windows Me without serious justification such as legacy support.

² In fact, I already did a lot of management and system design related work, which is essential, but usually misunderstood by customers and perceived as a waste of time and money. Observing the concerned customer, I'm pretty sure that he will refuse to pay a large amount of money for what was already done, since there is actually zero lines of code. Even if legally I can easily prove that there was a lot of work undertaken on the design level, I don't want to end my relation with this customer in a court.

³ Which is not as risky as it could be, since I gave this customer the expected and the maximum cost of the project, so the customer is sure to never be asked to pay more than the maximum amount, specified in the contract, even if the real work costs more.

⁴ One case when I effectively record on my own initiative the video of actions is when I have to do some manipulations directly on a production server of a customer, especially when it comes to security issues. Recording those steps may be a good idea to know precisely what was done, and also ensure that there were no errors in my work, or see what those errors were.

First update

Since the question attracted much more attention and had many more answers than I expected, I imagine that it can be relevant to other people, so here is an update. First, to summarize the answers and the comments, it was suggested to (ordered randomly):

Suggest other ways of tracking, as shown in Twitter Code Swarm video, or deliver a "short milestone with a simple, clear deliverable, followed by more complex milestones", etc.

Explain that video is not a reliable source and can be faked, and that it would be difficult to implement, especially for support.

Explain that video is not a reliable source since it shows only a small part of the work: a large amount of work is done without using a computer, not counting the extra hours spent thinking about a solution to a problem.

Stick with the contract; if the customer wants to change it, he must expect new negotiations and a higher price.

Do the video, "but require that the customer put [the] entire fee into an escrow account", require a lawyer to video tape all billable time, etc., in other words, "operate in an environment void of trust", requiring the customer to support the additional cost.

Search for the laws which forbid this. Several people asked in what country I live. I'm in France. Such laws exist to protect the employees of a company (there is a strict regulation about security cameras etc., but I'm pretty sure nothing forbids a freelancer to sign consciously a contract which forces him to record the screen while he works on a project.

Just do it and send the videos: the customer will "watch a few ten second snippets of activity he won't understand", then throw those videos away.

Say no. After all, it's my business, and I'm the only one to decide how to conduct it. Also, the contract is already signed, and has nothing about video tracking.

Say no. The processes and practices I employ in my company can be considered as trade secrets and are or can be classified.

Quit. If the relation starts like this, chances are it will end badly sooner or later. Also, "if he's treating you like a thief - and that is what he's suggesting - then it's just going to get worse later when XYZ feature doesn't work exactly the way he envisioned".

While all those suggestions are equally valuable, I've personally chosen to say to my customer that I accept to do the videos, but in this case, we must renegotiate the contract, keeping in mind that there will be a considerable cost, including the additional fee for copyright release. The new overall cost would be on average three times the actual cost of the project. Knowing this customer, I'm completely sure that he would never accept to pay so much, so the problem is solved.

Second update

The customer effectively declined the proposal to renegotiate the original contract, taking into account the considerable additional cost. He agreed to continue the project without video recording.

The project continued without video recording. Eventually, the customer seemed satisfied by the final result and cost, so the video recording was not mentioned again.


问:
Big-O for nested loop
I am reading this post on Big-O

It says that the following code is O(n^2):

```<code>bool ContainsDuplicates(String[] strings)
{
    for(int i = 0; i < strings.Length; i++)
    {
        for(int j = 0; j < strings.Length; j++)
        {
            if(i == j) // Don't compare with self
            {
                continue;
            }

            if(strings[i] == strings[j])
            {
                return true;
            }
        }
    }
    return false;
}
</code>```

But I can not understand why.

The inner loop does something constant.

So it is summation of 1....N of a constant. i.e. constant number O(1).

The outer loop is summation over the O(1).

So I would imagine it is n*O(1).

I think I am misunderstanding something here.

I do not think that all nested loops mean O(n^2), right?

答:
You are misinterpreting what a constant operation means.

A constant operation is an operation which always executes in fixed amount of time independent of input it receives.

i == j is a constant operation because it executes this statement in fixed amount of time. Lets say it takes 1 unit of time.

But this constant operation is performed (no of values of i)*(no of values of j) times.
Lets say i and j are run 10 times each.
Then by calculation it takes 100 unit of time for completion of i==j when in a nested loop.
So it will vary as the values of i and j vary.

We can be sure that i==j will be done in 1 unit time but we cannot know how many times i==j will be performed.

If it is performed n times then it will take n units of time. Outer loop executes inner loop n times. So in essence i==j operations is done n^2 times.

All nested loops mean O(n^(no of nested loops)). Here O means the upper limit which means code will execute in less than or equal to the value of O(). This is the guarantee that it will not take longer than that but it can take less time not larger.

Title: Big-O for nested loop


答: Personally, I think it's a terrible idea. It's highly unlikely that your customer will watch the video, and if this is the level of micro-management you're getting now, then the amount of micro-management you'll get later is bound to increase. Unless you need this work, I would run away now.</p>


问:
Difference between Idiom and Design Pattern?
What is the difference between idiom and design-pattern? It seems that these terminologies overlap somewhere; where exactly, I don't know.  Are they interchangeable? When should I use what?

Here is a list of C++ Idioms. Can I call them design patterns?

Wikipedia defines,

Programming Idiom as a low-level Design Pattern

What does it mean? What does "low-level" mean here?

This question is inspired from another question : https://stackoverflow.com/questions/7343531/are-the-some-design-patterns-language-dependent

答:
Idioms are language specific. E.g. while (*dest++=*src++); is a C/C++ idiom. It is completely impossible to write something remotely similar in Pascal or Java. Use the word "idiom" as you use it in english. "How do you do?" as a greeting is an idiom. Some languages like german and frensh have the same idiom. But lots of other languages would not "ask" something like this as a greeting.
A (object oriented) pattern on the other hand usually can be adapted into any language that supports inheritance and delegation. A idiom might be as simple as one line of code. A design pattern always involves several classes.

OwnerDisplayName: Nawaz


答:
Short answer - it is not. Forget it, the topic is as old as fire or wheel. Java or .NET is not and will not be faster than C/C++. It's fast enough for most tasks where you don't need to think about optimization at all. Like forms and SQL processing, but that's where it ends.

For benchmarks, or small apps written by incompetent developers yes, the end result will be that Java/.NET is probably going to be close and maybe even faster.

In reality, simple things like allocating memory on stack, or simply using memzones will simply kill the Java/.NET on the spot.

Garbage collected world is using sort of memzone with all the accounting. Add memzone to C and C will be faster right there on the spot. Especially for those Java vs. C "high-performance code" benchmarks, that go like this:

```<code>for(...)
{
alloc_memory//Allocating heap in a loop is verrry good, in't it?
zero_memory//Extra zeroing, we really need it in our performance code
do_stuff//something like memory[i]++
realloc//This is lovely speedup
strlen//loop through all memory, because storing string length is soo getting old
free//Java will do that outside out timing loop, but oh well, we're comparing apples to oranges here
}//loop 100000 times
</code>```

Try to use stack based variables in C/C++ (or placement new), they translate into sub esp, 0xff, it's a single x86 instruction, beat that with Java - you can't...

Most of the time I see those benches where Java against C++ are compared it causes me to go like, wth? Wrong memory allocation strategies, self-growing containers without reserves, multiple new's. This is not even close to performance oriented C/C++ code.

Also a good read: https://days2011.scala-lang.org/sites/days2011/files/ws3-1-Hundt.pdf

Body:
Short answer - it is not. Forget it, the topic is as old as fire or wheel. Java or .NET is not and will not be faster than C/C++. It's fast enough for most tasks where you don't need to think about optimization at all. Like forms and SQL processing, but that's where it ends.

For benchmarks, or small apps written by incompetent developers yes, the end result will be that Java/.NET is probably going to be close and maybe even faster.

In reality, simple things like allocating memory on stack, or simply using memzones will simply kill the Java/.NET on the spot.

Garbage collected world is using sort of memzone with all the accounting. Add memzone to C and C will be faster right there on the spot. Especially for those Java vs. C "high-performance code" benchmarks, that go like this:

for(...)
{
alloc_memory//Allocating heap in a loop is verrry good, in't it?
zero_memory//Extra zeroing, we really need it in our performance code
do_stuff//something like memory[i]++
realloc//This is lovely speedup
strlen//loop through all memory, because storing string length is soo getting old
free//Java will do that outside out timing loop, but oh well, we're comparing apples to oranges here
}//loop 100000 times

Try to use stack based variables in C/C++ (or placement new), they translate into sub esp, 0xff, it's a single x86 instruction, beat that with Java - you can't...

Most of the time I see those benches where Java against C++ are compared it causes me to go like, wth? Wrong memory allocation strategies, self-growing containers without reserves, multiple new's. This is not even close to performance oriented C/C++ code.

Also a good read: https://days2011.scala-lang.org/sites/days2011/files/ws3-1-Hundt.pdf


问:
With agile, what do when a user story doesn't get completed in an iteration?
Do you just move the story to a new iteration, or delay the next iteration?

It gets a bit tricky when you use something like Jira when you have to copy or move around stories between iterations as it effects calculations of velocity/points etc.

Is there a best-practice?

答:
At the sprint review, the Product Owner, in consultation with the
sprint team and stakeholders makes the decision on done-ness. In
this case, the PO declares that the story will not meet the
customer's needs as intended.

The PO may elect to create a new story and place it into the
Product backlog.  The new story, like any story is based on the
information that the PO has about the current state of the product
and the current needs of the customer.  This obviously includes the
discussion that took place about the undone story above.

At the next planning meeting, the new story is assessed like any
other.  The PO prioritizes and the team estimates effort.

Notes:

The degree of done-ness is a factor in the decision process.
For example, if the team agrees that they are "one hour" from
completion, the PO may agree to delay the done decision.  But the
team still needs to demonstrate that the story is done!

On my team, a story is never moved out of the sprint after that sprints review (it's closed as-is).  We use the "done-done" rate to use as a talking point during the retrospective.  If we moved the story, then it would appear as if our done-done rate was 100% every sprint.

OwnerDisplayName: codecompleting


答:
Even though it's not your area of expertise, I think it's always interesting to study how to create UIs. Nowadays most webpages are very dynamic and knowing some UI skills would certainly help when creating components and set their interactions with your page's elements.
I've come from a backend-only development background and I was surprised at how much is involved when creating interfaces.

There's a particularly good book I've read about web design and that is aimed towards developers:

Web Design for Developers: http://pragprog.com/book/bhgwad/web-design-for-developers

It's an easy to read book that touches all the phases when creating interfaces: from plain sketching and prototyping UIs to creating designs with HTML + CSS.

To further improve your UI skills, I also recommend PeepCode's latest screencast with Ryan Singer:
http://peepcode.com/products/ryan-singer-ux


答:
I would suggest Python.

Looking at your languages list you are sorely lacking a scripting language I think, and scripting is essential for development.

I myself delved in Python a year and a half after having begun to work and I really felt like Superman: suddenly there were plenty of repetitive/mind-numbing tasks that I could just automate.

Stupid example:

You have the following directory:

```<code>xxx/
  Bar.h
  foo.h
  fooBar.h
  Zulu.h
</code>```

but your company policy requires that all include files begin with a lower case letter: how do you set about it ?

With any scripting language, it's a pretty trivial task, with a compiled language, it's usually a bit longer (need to create a file, compile it, etc...), and if you set to it manually, just pray there aren't too many to rename.

Furthermore, Python is also used to build applications (Mercurial) or web sites (using Django), so it's not restricted to throw away scripts either.

Title: What's a neat project to help me get used to the modern environment?

Body:
I haven't been programming for almost a decade. I used to be able to program in QBasic, Turbo Pascal, C, C++, Visual Basic and Assembly. I have no knowledge in any other programming language (other than HTML).

I want a project (in some programming language) to help me acquaint myself with the new environment (unix, python, perl, java, flash?) in a way that would give me the feeling that I've gained a mini-super-power. By that I mean something that give me the feeling of hacking (not actually learn about hacking, but just like learning C for the first time feels like hacking). Something that would put my programming skills to use in a way that the programming languages I do (did) know don't.

Body:
I would suggest Python.

Looking at your languages list you are sorely lacking a scripting language I think, and scripting is essential for development.

I myself delved in Python a year and a half after having begun to work and I really felt like Superman: suddenly there were plenty of repetitive/mind-numbing tasks that I could just automate.

Stupid example:

You have the following directory:

xxx/
  Bar.h
  foo.h
  fooBar.h
  Zulu.h

but your company policy requires that all include files begin with a lower case letter: how do you set about it ?

With any scripting language, it's a pretty trivial task, with a compiled language, it's usually a bit longer (need to create a file, compile it, etc...), and if you set to it manually, just pray there aren't too many to rename.

Furthermore, Python is also used to build applications (Mercurial) or web sites (using Django), so it's not restricted to throw away scripts either.


答:
The new/in-vogue thing to do with regards to browser detection is to use 'modernizers' in javascript to degrade gracefully in the face of browsers which are less feature-rich than others. In that vein, I personally would prefer websites to use a layout that looks good on both regular browsers and mobile devices, by arranging blocks in such a way that they flow well on screens of any resolution.

One can dream, I suppose...


答:
I think that picking up some basics of UX/UI/graphics/typography is certainly a valuable endeavor. You can't always have a "well-rounded" team of specialists, of course. Many times folks have to wear multiple hats. A good developer will see value in spending time learning about things outside his/her domain and should be able to at least recognize good work in design.

However, there is something to be said for what designers do. A developer can only do so much in the area of design (admittedly some more than others). In particular, large public-facing projects which reach out beyond a narrow niche benefit greatly by employing actual design professionals. And I don't simply mean folks who can swing around css and html color codes. I mean people that have spent YEARS studying things like typography, who have read and understood Josef Alber's book on color, who can make beautiful sketches with crumbling charcoal on newsprint. These are valuable skills and the projects that recognize that and that can put these skills to focused use have a decided edge over the competition.

That said, there are some areas where designers and developers can overlap their skills. Especially UX and its subdomain, UI. I recommend ...

Designing for Interaction

Designing Interfaces

Designing Interactions


问:
What qualifies "too many database requests" in code?
This is a discussion myself and some of my colleagues are having and thought I'd come out here and see what if there's a general consensus on it.

It basically comes down to the following 2 opinions on database calls:
1.  Make one large call to get everything that may be needed to reduce database the number of DB calls
2.  Make smaller separate calls based on what is requested to reduce the size of DB calls

Where this is especially coming into play is in common code.  We'll use the example of an Employee class as that's fairly straight forward.

Let's say that your Employee class has 10 value attributes (first name, last name, hiredate, etc.) and then 2 class attributes ... 1 pointing to a Department class and then 1 supervisor that points back to another Employee object.

In mindset #1, you'd make one call that returns the Employee data as well as the fields needed to populate the Department and Supervisor attributes ... or at least the fields that most often used from those sub objects.

In mindset #2, you'd only populate the Employee object at first and then only populate the Department and Supervisor objects if and when they are actually requested.

2's stance is pretty straight-forward ... minimize the size of the requests and how many database objects need to be hit each time one of those requests is made.  #1's stance is that even if it could be implemented properly, the sheer fact that the code would have to make multiple connections is going to cause more strain on the connection between the webserver and the database as opposed to reducing it.

The driving force behind researching this is that the amount of traffic between our webserver and database server is getting out of control.

答:
Always go for readability and clarity the first time you write something. You can then refactor if and when you need to. Do load testing to find the bottlenecks, in a lot of cases its not the number of calls causing the problem but badly written ones.

As for what classifies as too many, that depends on the application. For most web applications anything under 30 seconds is just about acceptable. I would speak to your users as to their expectations.


答:
If the driving force behind this question is too much traffic, have you looked into caching frequently used objects? For example: AFter you get the Employee and Department and Supervisor objects, maybe it would a good idea to add them a cache so that if they are requested again in the near future, they are already in cache and don't need to be retrieved again. Of course, the cache will need to let rarely used objects expire out, and also needs to be able to remove objects that have been modified by the application and saved back to the database.

Depending on what language and frameworks you're using, there might already be a caching framework that can do some (or most) of what you need. If you use Java, you could look into the Apache Commons-Cache (I haven't used it for a while, and while it looks dormant, it is still available to use and it was pretty decent the last time I used it).

Title: What qualifies "too many database requests" in code?

Body:
This is a discussion myself and some of my colleagues are having and thought I'd come out here and see what if there's a general consensus on it.

It basically comes down to the following 2 opinions on database calls:
1.  Make one large call to get everything that may be needed to reduce database the number of DB calls
2.  Make smaller separate calls based on what is requested to reduce the size of DB calls

Where this is especially coming into play is in common code.  We'll use the example of an Employee class as that's fairly straight forward.

Let's say that your Employee class has 10 value attributes (first name, last name, hiredate, etc.) and then 2 class attributes ... 1 pointing to a Department class and then 1 supervisor that points back to another Employee object.

In mindset #1, you'd make one call that returns the Employee data as well as the fields needed to populate the Department and Supervisor attributes ... or at least the fields that most often used from those sub objects.

In mindset #2, you'd only populate the Employee object at first and then only populate the Department and Supervisor objects if and when they are actually requested.

2's stance is pretty straight-forward ... minimize the size of the requests and how many database objects need to be hit each time one of those requests is made.  #1's stance is that even if it could be implemented properly, the sheer fact that the code would have to make multiple connections is going to cause more strain on the connection between the webserver and the database as opposed to reducing it.

The driving force behind researching this is that the amount of traffic between our webserver and database server is getting out of control.


答:
To me, Too many DB requests is making more requests than you need to load the data you require at any given time.

So I you don't need the data, don't waste memory getting it to avoid a second trip later. But if you need the amount of data, you should minimize the calls to the db.

So have both options, and use each one where the situation calls for it.

EDIT: Keep in mind that this ofcourse depends on your situation as well. If its a WebApp for example you should have different considerations than if its a desktop app accessing the DB within your network, as opposed to across the web for the WepApp.


问:
Benefits to starting JavaScript "for" loops at 0, or just traditional?

Possible Duplicate:

  Defend zero-based arrays

I'm running code that loops through an array of HTML IDs.

With the HTML IDs named content1, content2, …, content12, my loop looks like:

```<code>for (var i = 1; i<13; i++) {
    var contentFind = $('#content'+i)[0];
</code>```

I know that the usual way to run loops is to start at i = 0. Is there any benefit to this, or is it just the traditional, standard or normal way to write loops?

答:
Start your for loops where ever you have to start them.

The reason a lot of for loops start at 0 is because they're looping over arrays, and in most languages (including JavaScript) arrays start at index 0.


答:
It is a traditional method of doing it that is relative to the iteration across an array as you're describing. In a lot of cases, iteration of this nature of this nature is used on a zero-index array, so it makes sense to initialize your indexing variable to match the index of the array.

Other than that, you should always initialize your array looping variable to be what you need  rather than what convention shows.

Title: Benefits to starting JavaScript "for" loops at 0, or just traditional?

Body:
Possible Duplicate:

  Defend zero-based arrays

I'm running code that loops through an array of HTML IDs.

With the HTML IDs named content1, content2, …, content12, my loop looks like:

```<code>for (var i = 1; i<13; i++) {
    var contentFind = $('#content'+i)[0];
</code>```

I know that the usual way to run loops is to start at i = 0. Is there any benefit to this, or is it just the traditional, standard or normal way to write loops?


答:
Connect to DB, send out request and have it parsed usually takes significant time compared to retrieving results, so the overall trend is to concatenate as many queries as possible in one request.

Still, doing this all in one shot will make the code unmaintainable. Instead, it is usually attained by an additional abstraction layer: the code schedules several requests as they are needed, then the engine parses this as one big request (possibly using cache on the way) and then replies are dispatched as needed.

Of course not always all can be retrieved in one query - you'll often have a query that provides data necessary for building the next query, so you will have to repeat it. Still staggering bundles of queries and performing as many as possible at once is better than hundreds small shots to the database.

So, plan what you need, request and retrieve it, if more is needed, request and retrieve it again, and then utilize the data in generating content. Definitely avoid using database requests like local variable initialization scattered all over the code.


答:
We don't know enought about your application to know which choice are you guilty of optimizing too soon. How often is the Supervisor data utilized? Seems like it could be a waste, but we don't know. If you keep them separate, you may be able to monitor your system to see how often they end up being used together. Than you can make a decision to just combine them in one call. Otherwise, if you start creating a bottle neck with this one big call, where do you begin to trouble-shoot? Difficult to identify what makes sense to omit. More data fields may get added to this process.

It would be interesting to know how much of this is coming from db memory vs disk. There's nothing to make me feel that department is more or less likely to changed compared to address.


答:
Both of the strategies here are perfectly valid. There are advantages and disadvantages to each:

One call for all 3 objects:

will perform faster

will get you exactly what you need in the case where you need it

will probably only be useable in one case (it may be a very common case though)

will be more difficult to maintain

will have to be maintained more often (as it will change if any of the 3 objects' schemas or needed data change)

One call per object (3 calls total)

Gives you a general-purpose call to populate a single instance of each object type; they can then be used independently

Will be more maintainable as the query structure will be simpler.

Will be slower (not necessarily 3 times as slow, but overhead is increased for the same data)

Can cause issues with retrieving unneeded data (pulling the entire record when you need one field is wasteful)

May cause N+1 issues when a many-to-one relationship exists, if the single-record query is sent out N times, one per record in the collection.


答:
UI design is not something that comes natural to many people. However, I have recently become much better at it by following a few easy principles.

Don't freak out, it isn't as hard as you think.

Model the data structure and your engine first. Create clear and real-world-corresponding models. Obviously this assumes that you have taken the time to understand what the customer needs.

Now, with a sheet of paper and a pencil, sit down and start drawing the logical layout of screens. This normally simply presents your data model to the user in an organized fashion. Your goal should be simply:

a. Mimic the environment of where the app will be deployed. For example, if it is a windows app, it needs to behave like a windows app, if it is a web app, it needs to behave like similar web applications that are more popular than yours.

b. Your goal is to guide the user through your data model in a way that THEY would predict. A user interface is well designed when a user does something in your application and it does exactly what they expected it to do.

c. This takes time and it is a learning curve, but anyone can do it.

Don't worry about the graphics, i.e. the buttons, the backgrounds, etc... your only goal at this point is the logical layout of the page.

You do need to master the gui lib that you're using whether it is html, gtk, cocoa, android, Windows.Forms and so on to the extent that you understand the event handling mechanisms, the layout engine, and retrieving input and displaying data. Any developer should be able to do at least this.

There is no shame in getting a graphic designer to take over from here. But you should at least be able to get past step 5. This is 95% of the workload for the entire app.

Here is a helpful article that turned me from a poor gui designer to a much better gui designer.

http://www.joelonsoftware.com/uibook/fog0000000249.html


问:
With ASP.NET MVC actions, should I use web services?
In ASP.NET Web Forms if you want to use jQuery and call a method directly, you should either implement a web service, or use Page Methods. Also you can use Generic Handlers (.ashx files).

However, in ASP.NET MVC, a controller action (a method in nature) can be called directly from jQuery.

What web services has to offer in ASP.NET MVC world? In other words, seems that I can fulfill of my requirements via MVC's clean URLs, controllers and actions. Should I bother using Web Services?

答:
I think you got it all wrong regarding Web Services... Your page methods analogy is correct, but web services is a whole other ball game.

Here is a small, yet to the point, explanation on why use web services:

http://www.w3schools.com/webservices/ws_why.asp

Wikipedia's definition for Web Services also gives you an insight into why they are used.

There are many reasons, but the main one, I would say, is interoperability.

But, yeah, if all you used web services for was to use jQuery to call a method directly, then you probably shouldn't use web services...


问:
Great Programmer Productivity - Accounting for 10,000 fold difference?

A great lathe operator commands several times the wage of an average lathe operator, but a great writer of software code is worth 10,000 times the price of an average software writer. - Bill Gates

Say there's a "great" software engineer and an "average" software engineer on the same team. How can you account for one engineer being 10,000 times more productive? I can't quite fathom this, given they're both taking on their share of features, bugs and investigations, and consistently deliver with quality. Would my description possibly justify them to be above "average"? "great"?

答:
There are some solutions that only the best programmers are going to be able to solve. Throwing thousands of mediocre ones won't work. It's also more difficult to coordinate their efforts even if they could collectively combine the pieces of their knowledge.

Answering questions on SO is no different. There are many problems where out of a group of average developers, one is able to come up with the answer. These websites probably do a much better job of coordinating efforts than most development teams which is sad.

OwnerDisplayName: TheImpact


答:
Reasons why native apps are developed rather than HTML/CSS:

Richer API. You typically have more access to the hardware than a browser does. This could mean anything from better scrolling performance, to better multitasking/memory management, or access to the camera on the device.

The user is more likely to put the web-based application on the homescreen and use it. Yes, on the iPhone you can save an HTML website to the homescreen, but the end user may not be aware of or comfortable with the process.

Performance. This typically isn't an issue, but may be for gaming or graphics.

Ability to sell the app in the device's marketplace.

Network isn't necessarily required. Depending on what the website does, local caching of data means that basic functionality won't be affected if the device drops the signal and no longer has internet connectivity. (This disadvantage of HTML is being ameliorated with application cache support in newer browsers.)

Lastly, discovery and expectations. For example, I'm more likely to look for a native app for my iPhone rather than surf to my bank's website. Unfortunately, I expect the website won't be optimized, and I'll be faced with tiny text entry fields and buttons. It may be some time before users expect websites to be optimized for small devices and check the browser first for rich applications.

Also note that with HTML5 and CSS, you generally don't want to use browser detection through User-Agent, you want to detect browser support through the DOM. Modernizr is a javascript library which can detect browser capabilities and screen width.