问:
How to structure template system using plain PHP?
I was reading this question over on stackoverflow:

https://stackoverflow.com/questions/104516/calling-php-functions-within-heredoc-strings

and the accepted answer says to do plain PHP templates like this:

template.php:

```<html>
    <head>
        <title><?=$title?></title>
    </head>
    <body>
        <?=getContent()?>
    </body>
</html>```

index.php:

```<?php

$title = 'Demo Title';

function getContent() {
    return '<p>Hello World!</p>';
}

include('template.php');

?>```

To me the above isn't well structured in the sense that template.php depends on variables that are defined in other scripts. And you're using an include() to execute code when you do include('template.php')(as opposed to using include() to include a class or a function which isn't immediately executed).

I feel like a better approach is to wrap your template inside a function:

template.php:

```<?php

function template($title, $content) {
    ob_start(); ?>

<html>
    <head>
        <title><?=$title?></title>
    </head>
    <body>
        <?=$content?>
    </body>
</html>

    <?php return ob_get_clean();
}

?>```

index.php:

```<?php

require_once('template.php');

print template('Demo Title', '<p>Hello World!</p>');

?>```

Is the second approach better? Is there an even better way to do it?

答:
I wouldn't do the second approach as the parameters aren't named.

A well-written essay on describing how a template system should work is coming from Parr, it's often quoted by people writing template systems and/or web-mvc frameworks.

Personally, what I usually prefer is to implement an ArrayObject class with a properties array, and the template would refer to $this->propertyName, which in fact would be the template object's $this->property['name']. This could be also achieved simply by using __set and __get, so:

```<code>class Template {
  private $_scriptPath=TEMPLATE_PATH;//comes from config.php
  public $properties;
  public function setScriptPath($scriptPath){
    $this->_scriptPath=$scriptPath;
  }
  public function __construct(){
      $this->properties = array();
  }
  public function render($filename){

   ob_start();
   if(file_exists($this->_scriptPath.$filename)){
     include($this->_scriptPath.$filename);
    } else throw new TemplateNotFoundException();
    return ob_get_clean();
  }
  public function __set($k, $v){
      $this->properties[$k] = $v;
  }
  public function __get($k){
      return $this->properties[$k];
  }
}
</code>```

and a template would look like:

```<code><html>
      <head>
         <title><?=$this->title?></title>
      </head>
      <body>Hey <?=$this->name?></body>
</html>
</code>```

and invoking it would look like:

```<code>$view = new Template();
$view->title="Hello World app";
$view->properties['name'] = "Jude";
echo $view->render('hello.inc');
</code>```

As far as I remember, this is how the old Symfony 1.x and the Zend_View template engines look like, and for me it's fine.

Body:
I wouldn't do the second approach as the parameters aren't named.

A well-written essay on describing how a template system should work is coming from Parr, it's often quoted by people writing template systems and/or web-mvc frameworks.

Personally, what I usually prefer is to implement an ArrayObject class with a properties array, and the template would refer to $this->propertyName, which in fact would be the template object's $this->property['name']. This could be also achieved simply by using __set and __get, so:

class Template {
  private $_scriptPath=TEMPLATE_PATH;//comes from config.php
  public $properties;
  public function setScriptPath($scriptPath){
    $this->_scriptPath=$scriptPath;
  }
  public function __construct(){
      $this->properties = array();
  }
  public function render($filename){

   ob_start();
   if(file_exists($this->_scriptPath.$filename)){
     include($this->_scriptPath.$filename);
    } else throw new TemplateNotFoundException();
    return ob_get_clean();
  }
  public function __set($k, $v){
      $this->properties[$k] = $v;
  }
  public function __get($k){
      return $this->properties[$k];
  }
}

and a template would look like:

<html>
      <head>
         <title><?=$this->title?></title>
      </head>
      <body>Hey <?=$this->name?></body>
</html>

and invoking it would look like:

$view = new Template();
$view->title="Hello World app";
$view->properties['name'] = "Jude";
echo $view->render('hello.inc');

As far as I remember, this is how the old Symfony 1.x and the Zend_View template engines look like, and for me it's fine.


问:
How to handle security of temporary data on web server?
I'm primarily an ASP.NET developer but this question really applies regardless of language.  So obviously it is a good idea to prevent external attacks that arise from session hijacking and csrf attacks as well.  But what about internal attacks when the data involved is temporary, needed for the entire session but also sensitive and worth stealing?  There is the naturally just only hire trustworthy people route, but lets say that doesn't apply.

Say it is a given you already have code reviews and strict production data access permissions to prevent theft by developers.  The application encrypts sensitive data before storing to prevent theft by dbas.

How do you protect your temporary sensitive data against web server admins?  It seems that they could retrieve information by inspecting web server logs, traffic sniffing and inspection of process memory contents.  Naturally I would say production web server admins do not have access to the raw source code.

答:
Best thing you can do is limiting who has access to what. People with access to production boxes should not have access to the code. People with access to the code should not have access to production boxes (of course there will be temporary exceptions to those, like the need to investigate a bug occurring only on production boxes)
Like you said, a sysadmin could always sniff the network, or even put your app inside a emulator, and logging all the relevant accesses to memory. There's just nothing you can do about it.

All the recent data leaks we've seen came from people with authorized access to the data (most of wikileak sources), poorly implemented password storage (steam, Sony...) or from 0day exploits. Encrypting your memory won't help you in any of those cases, which your are more likely than not vulnerable to.

ContentLicense: CC BY-SA 3.0


问:
How to prevent intentional over-estimation in user stories?
I am asking this from a purely hypothetical standpoint.

According to the Sprint Planning Meeting section in the Scrum Guide:  "The number of items selected from the Product Backlog for the Sprint is solely up to the Development Team. Only the Development Team can assess what it can accomplish over the upcoming Sprint."

Questions:

What is there to stop the development team from over-estimating intentionally the time it takes to complete user stories?

If there is a long-term contact with the product owner and development team, should this be defined in the contract as some sort of violation or breach of contract?

Who would be responsible for discovering such a violation?

How could the product owner prove that such a violation was taking place?

Thank you for reading.

答:
What is there to stop the development team from over-estimating
  intentionally the time it takes to complete user stories?

I would say pride, and a sense of professionalism. Hire true professionals and you don't have to worry about it. If you have people that are intentionally trying to subvert your development efforts you've got bigger problems than just estimation issues.


答:
An essential principle of agile development is total openness. So in theory, at least, there's nothing to stop the scrum team from robbing you blind, other than the fact that it would be immediately obvious. That, and the fact that the team will have started by promising this openness, and that people are basically honest.

So (I'm asking this purely hypothetically): What's to stop you from stealing from the local sweet shop?

Somewhat less flippantly: the team's estimates will be checked against reality at the end of the sprint. They stand at the board every day to say what they expect work on, and the following day they answer for their progress against that commitment. What more could you want?

Title: How to prevent intentional over-estimation in user stories?

Body:
I am asking this from a purely hypothetical standpoint.

According to the Sprint Planning Meeting section in the Scrum Guide:  "The number of items selected from the Product Backlog for the Sprint is solely up to the Development Team. Only the Development Team can assess what it can accomplish over the upcoming Sprint."

Questions:

What is there to stop the development team from over-estimating intentionally the time it takes to complete user stories?

If there is a long-term contact with the product owner and development team, should this be defined in the contract as some sort of violation or breach of contract?

Who would be responsible for discovering such a violation?

How could the product owner prove that such a violation was taking place?

Thank you for reading.


问:
not checking in from the project root
Whenever I do a check-in, I always check in from the root of the project... i.e. check in all the files in my working copy, so after the check-in the source control repo contains exactly the same set of files that I just finished testing in my local copy.  I also make sure my source control is set to flag local files that are not under source control.  In general, there are none of these files... if there are, I either add them to source control or mark them as "ignored".  I also check in all my changes together in one check-in.

A lot of colleagues check in much differently.  They carefully select each file to check in, as if they are a master jeweler selecting only the very best gemstones to set into the royal crown, and they check in each one as a separate check-in.  They rely only on their memory to figure out which files need to be checked in, or especially added to source control.

The results are quite predictable... frequent broken builds because they forget to add their new files to source control or forget to check in a changed file (especially changed project files).

I have mentioned this to them and they never seem to change.  When I mentioned it to the team lead he said, "this is just a different way of working".  To which I may respond: What if I want to drive my car with my eyes closed?  Is that just "a different way of driving"?

Am I right in being bothered by this practice?

答:
Don't be bothered by the practice of checking in individual files - if someone can do that and make it work, that's fine.

Do be bothered by people checking in broken builds. The primary concern is the result. Addressing the root cause is absolutely a good idea, but the best first step is to find the appropriate motivation to stop checking in broken code.

ContentLicense: CC BY-SA 2.5

Title: not checking in from the project root


问:
Can't understand example using continuations
I'm reading the r6rs Scheme report and am confused by the explanation of continuations (I find it to be too dense and lacking of examples for a beginner).

What is this code doing and how does it evaluate to 4?  Why does call/cc want an argument that's a function of one argument?  How is call/cc's argument used?

```<code>(+ 1 (call-with-current-continuation
       (lambda (escape)
         (+ 2 (escape 3)))))
          =⇒ 4
</code>```

This example is from section 1.11 - Continuations.

答:
This introduction with a lots of examples helped me understand continuations.

Anyway. These are some examples on how to (ab)use continuations:

```<code>(define (pair-up x)
    (call/cc (lambda (continuation)
        ;; recursive helper functions
        (define (pair-up-aux x)
        (if (null? x)
            '()
            (if (null? (cdr x))
                (continuation #f) ; cancel everything and return #f
                (cons (cons (car x) (cadr x)) (pair-up-aux (cddr x)))))) ; build result
        (pair-up-aux x))))
</code>```

This code takes a list and makes a list of pairs such that (pair-up '(a b c d)) becomes ((a . b) (c . d)). It does so by recursing and chaining conses. When I'm at the end of the list and see that i lack one element to create the last pair I would want to cancel everything and return #f instead. If I did (pair-up '(a b c)) and just returned #f I would have got ((a . b) . #f). The call/cc at the moment gives me chance to change my mind and return something else alltogether even though I have started constructing my return. (continuation #f) returns #f as the result of this procedure since the call/cc is around the functions body. The next example implements a loop with continuations.

```<code>(let ((x 0))
    (let ((cont (call/cc (lambda (x) (x x)))))
        (set! x (+ x 1))
        (display x)
        (newline)
        (if (= x 10)
            (display "Finished!\n")
            (cont cont))))
</code>```

Now this one actually prints 1..10 and calling the continuation will make it do the body of the let several times. I had to use two separate let (or let*) or else x would have been initialized at each run to and x would never ever become 10.

Body:
This introduction with a lots of examples helped me understand continuations.

Anyway. These are some examples on how to (ab)use continuations:

(define (pair-up x)
    (call/cc (lambda (continuation)
        ;; recursive helper functions
        (define (pair-up-aux x)
        (if (null? x)
            '()
            (if (null? (cdr x))
                (continuation #f) ; cancel everything and return #f
                (cons (cons (car x) (cadr x)) (pair-up-aux (cddr x)))))) ; build result
        (pair-up-aux x))))

This code takes a list and makes a list of pairs such that (pair-up '(a b c d)) becomes ((a . b) (c . d)). It does so by recursing and chaining conses. When I'm at the end of the list and see that i lack one element to create the last pair I would want to cancel everything and return #f instead. If I did (pair-up '(a b c)) and just returned #f I would have got ((a . b) . #f). The call/cc at the moment gives me chance to change my mind and return something else alltogether even though I have started constructing my return. (continuation #f) returns #f as the result of this procedure since the call/cc is around the functions body. The next example implements a loop with continuations.

(let ((x 0))
    (let ((cont (call/cc (lambda (x) (x x)))))
        (set! x (+ x 1))
        (display x)
        (newline)
        (if (= x 10)
            (display "Finished!\n")
            (cont cont))))

Now this one actually prints 1..10 and calling the continuation will make it do the body of the let several times. I had to use two separate let (or let*) or else x would have been initialized at each run to and x would never ever become 10.


答:
The first template.php is easier to load as-is into dreamweaver/bluegriffon/whatever and edited by a server-side non-savvy web designer, the second... well it still kinda could, but it's much more likely to break during the editing process.

I'd go with the first to keep it looking like HTML with benefits, the way 3rd party designers usually prefer.

Title: How to structure template system using plain PHP?

Body:
I was reading this question over on stackoverflow:

https://stackoverflow.com/questions/104516/calling-php-functions-within-heredoc-strings

and the accepted answer says to do plain PHP templates like this:

template.php:

```<html>
    <head>
        <title><?=$title?></title>
    </head>
    <body>
        <?=getContent()?>
    </body>
</html>```

index.php:

```<?php

$title = 'Demo Title';

function getContent() {
    return '<p>Hello World!</p>';
}

include('template.php');

?>```

To me the above isn't well structured in the sense that template.php depends on variables that are defined in other scripts. And you're using an include() to execute code when you do include('template.php')(as opposed to using include() to include a class or a function which isn't immediately executed).

I feel like a better approach is to wrap your template inside a function:

template.php:

```<?php

function template($title, $content) {
    ob_start(); ?>

<html>
    <head>
        <title><?=$title?></title>
    </head>
    <body>
        <?=$content?>
    </body>
</html>

    <?php return ob_get_clean();
}

?>```

index.php:

```<?php

require_once('template.php');

print template('Demo Title', '<p>Hello World!</p>');

?>```

Is the second approach better? Is there an even better way to do it?


问:
Learning new programming languages and technologies
Some time ago I was to learn iOS development at my work. I didn't manage to learn it because I was moved to more important task with another technology already familiar to me. But the short time I  spent on iOS, I felt that I could do better if I spent a few hours at the workplace during which I could discuss some matters concerning iOS with my colleagues who know it, and the rest of the time working at home.

I think many developers would share my opinion and prefer to learn the new technology at home.

Is there any accepted practice? Has any developer had an experience when the company encouraged the developers to choose where they feel more comfortable to learn new technologies?

答:
Why do you feel that you could do better at home rather than at the office?

I'm guessing that it's due to interruptions and distractions. Since you mention being moved between tasks, I assume your work involves multiple simultaneous projects with developers moving between them. In this line of work, interruptions and distractions are always a problem. I know the feeling well, having spent many years as the most senior developer in an agency - there are always issues with require your involvement, you can never sit down to some guaranteed uninterrupted time to work on a thorny problem or learn a new technology.

I guess what I'm trying to get at is that perhaps your situation doesn't really have anything to do with learning a new technology, but is more an issue of general workplace organization? If it was possible to spread the knowledge around, avoid having a single person be the only one who could handle issues with a given project, and thus allow people to focus uninterrupted on a problem, do you think that would help with this situation and also improve your work environment overall?


问:
Web services and business rules engines
We have a web service that takes in input different types of messages. The function of the webservice is to merely write in a database the content of the messages. There is about one table (with foreign keys to others) for every kind of message.

We have been asked to transform the webservice in a configurable product by using a business rules engine. To have full configurability, a collegue suggested that the best way could be transform the webservice from one that accepts many types of messages to one that accepts one type of message, but in the content of the message there is a field that indicates the type of the content. This way, there would be just one table for the messages (plus other tables for static informations), and  it would be more configurable using business rules engines.

What is the best way to tackle such situation?

Update: for the business rules engines we are very likely going to use an implementation of the Rete Algorithm, like Drools

答:
Integrating a business rules engine does not come for free, you do not simply plug it in and then write any business rules you want. Instead, usually each type of business rule you want to implement needs to have code written in the underlying product to support. For example, a fact has to be loaded into the engine before a rule can use it.

This is why it is useless to integrate a BRE until you have an actual use case. And that use case must include fairly complicate business rules that change frequently. In any other case, I believe you are better served by writing the logic you want in the code, and wait for the configuration use-case (with well defined expecations) to come along.

Title: Web services and business rules engines


问:
Why doesn't DDD consider Documents?
... that is, the inputs and outputs of service functions ?

Are entities, or aggregates, allowed to leave service boundaries?

答:
Yes (depending on your definition of service boundary) but in practice it's going to depend on the consumers of the services.

If it's within your own application then it won't be a problem (for example if a service is calling a couple of other services and returning a result based on those results).

If it's outside your application then you will want those services to be returning either simple values or more usually DTOs composed of simple values. If you don't do this then your consumers will typically break any time your domain changes (and DDD is best applied when you have a regularly changing domain).

In all this I'm assuming you're talking about domain services.

Title: Why doesn't DDD consider Documents?


问:
Redistributing BSD-licensed software?
Is it acceptable to distribute unmodified BSD-licensed software (pyglet) with GPL-licensed software I created? The BSD allows for sale of modified software, I know, but does it allow re-licensing of unmodified? Seems to defeat the purpose of having a license at all.</p>

答: You don't need to relicense as the BSD license is compatible with the GPL: http://www.gnu.org/licenses/license-list.html#GPLCompatibleLicenses</p>

Title: Redistributing BSD-licensed software?


问:
What backs up the claim that C++ can be faster than a JVM or CLR with JIT?
A reoccurring theme on SE I've noticed in many questions is the ongoing argument that C++ is faster and/or more efficient than higher level languages like Java. The counter-argument is that modern JVM or CLR can be just as efficient thanks to JIT and so on for a growing number of tasks and that C++ is only ever more efficient if you know what you're doing and why doing things a certain way will merit performance increases. That's obvious and makes perfect sense.

I'd like to know a basic explanation (if there is such a thing...) as to why and how certain tasks are faster in C++ than the JVM or CLR? Is it simply because C++ is compiled into machine code whereas the JVM or CLR still have the processing overhead of JIT compilation at run time?

When I try to research the topic, all I find is the same arguments I've outlined above without any detailed information as to understanding exactly how C++ can be utilized for high-performance computing.

答:
I think that the real question here is not "which is faster?" but "which has the best potential for higher performance?".  Viewed on those terms, C++ clearly wins out - it's compiled to native code, there's no JITting, it's a lower level of abstraction, etc.

That's far from the full story.

Because C++ is compiled, any compiler optimizations must be done at compile time, and compiler optimizations that are appropriate for one machine may be completely wrong for another.  It's also the case that any global compiler optimizations can and will favour certain algorithms or code patterns over others.

On the other hand, a JITted program will optimize at JIT time, so it can pull some tricks that a precompiled program cannot and can make very specific optimizations for the machine it's actually running on and the code that it's actually running.  Once you get past the initial overhead of the JIT it has potential in some cases to be faster.

In both cases a sensible implementation of the algorithm and other instances of the programmer not being stupid will likely be far more significant factors, however - for example, it's perfectly possible to write completely brain-dead string code in C++ that will be walloped by even an interpreted scripting language.


答:
Bear in mind that the following is only comparing the difference between native and JIT compilation, and doesn't cover the specifics of any particular language or frameworks. There might be legitimate reasons to choose a particular platform beyond this.

When we claim that native code is quicker, we are talking about the typical use case of natively compiled code versus JIT compiled code, where the typical use of a JIT compiled application is to be run by the user, with immediate results (eg, no waiting on compiler first). In that case, I don't think anyone can claim with a straight face, that JIT compiled code can match or beat native code.

Let's assume we have a program written in some language X, and we can compile it with a native compiler, and again with a JIT compiler. Each work flow has the same stages involved, which can be generalized as (Code -> Intermediate Representation -> Machine Code -> Execution). The big difference between to two is which stages are seen by the user and which are seen by the programmer. With native compilation, the programmer sees all but the execution stage, but with the JIT solution, the compilation to machine code is seen by the user, in addition to execution.

The claim that A is faster than B is referring to the time taken for the program to run, as seen by the user. If we assume that both pieces of code perform identically in the Execution stage, we must assume that the JIT work flow is slower to the user, as he must also see the time T of the compilation to machine code, where T > 0. So, for any possibility of the JIT work flow to perform the same as the native work flow, to the user, we must decrease the time of Execution of the code, such that Execution + Compilation to machine code, are lower than only the Execution stage of the native work flow. This means we must optimize the code better in the JIT compilation than in the native compilation.

This however, is rather infeasible, since to perform the necessary optimizations to speed up Execution, we must spend more time in the compiling to machine code stage, and thus, any time we save as a result of the optimized code is actually lost, as we add it to the compilation. In other words, the "slowness" of a JIT based solution is not merely because of added time for the JIT compilation, but the code produced by that compilation performs slower than a native solution.

I'll use an example: Register allocation. Since memory access is some thousands of times slower than register access, we ideally want to use registers wherever possible and have as few memory accesses as we can, but we have a limited number of registers, and we must spill state into memory when we need a register. If we use a register allocation algorithm which takes 200ms to compute, and as a result we save 2ms of execution time - we're not making the best use of time for a JIT compiler. Solutions like Chaitin's algorithm, which can produce highly optimized code are unsuitable.

The role of the JIT compiler is to strike the best balance between compilation time and quality of produced code, however, with a large bias on fast compilation time, since you don't want to leave the user waiting. The performance of the code being executed is slower in the JIT case, as the native compiler is not bound (much) by time in optimising code, so is free to use the best algorithms. The possibility that overall compilation+execution for a JIT compiler can beat only execution time for natively compiled code is effectively 0.

But our VMs are not merely limited to JIT compilation. They employ Ahead-of-time compilation techniques, caching, hot swapping, and adaptive optimizations. So let's modify our claim that the performance is what the user sees, and limit it to the time taken for execution of the program (assume we've AOT compiled). We can effectively make the executing code equivalent to the native compiler (or perhaps better?). A big claim for VMs is that they may be able to produce better quality code then a native compiler, because it has access to more information - that of the running process, such as how often a certain function may be executed. The VM can then apply adaptive optimizations to the most essential code via hot swapping.

There's a problem with this argument though - it assumes that profile-guided optimization and the like is something unique to VMs, which is not true. We can apply it to native compilation too - by compiling our application with profiling enabled, recording the information, and then recompile the application with that profile. It's probably also worth pointing out that code hot swapping is not something that only a JIT compiler can do either, we can do it for native code - although the JIT based solutions for doing this are more readily available, and much easier on the developer. So the big question is: Can a VM offer us some information that native compilation cannot, which can boost the performance of our code?

I can't see it myself. We can apply most of the techniques of a typical VM to native code too - although the process is more involved. Similarly, we can apply any optimizations of a native compiler back to a VM which uses AOT compilation or adaptive optimizations. The reality is that the difference between natively run code, and that run in a VM is not as big as we've been made to believe. They ultimately lead to the same result, but they take a different approach to get there. The VM uses an iterative approach to produce optimized code, where the native compiler expects it from the start (and can be improved with an iterative approach).

A C++ programmer might argue that he needs the optimizations from the get-go, and shouldn't be waiting for a VM to figure out how to do them, if at all. This is probably a valid point with our current technology though, as the current level of optimizations in our VMs is inferior to what native compilers can offer - but that may not always be the case if the AOT solutions in our VMs improve, etc.

Title: What backs up the claim that C++ can be faster than a JVM or CLR with JIT?

Body:
A reoccurring theme on SE I've noticed in many questions is the ongoing argument that C++ is faster and/or more efficient than higher level languages like Java. The counter-argument is that modern JVM or CLR can be just as efficient thanks to JIT and so on for a growing number of tasks and that C++ is only ever more efficient if you know what you're doing and why doing things a certain way will merit performance increases. That's obvious and makes perfect sense.

I'd like to know a basic explanation (if there is such a thing...) as to why and how certain tasks are faster in C++ than the JVM or CLR? Is it simply because C++ is compiled into machine code whereas the JVM or CLR still have the processing overhead of JIT compilation at run time?

When I try to research the topic, all I find is the same arguments I've outlined above without any detailed information as to understanding exactly how C++ can be utilized for high-performance computing.


问:
How have languages influenced CPU design?
We are often told that the hardware doesn't care what language a program is written in as it only sees the compiled binary code, however this is not the whole truth. For example, consider the humble Z80; its extensions to the 8080 instruction set include instructions like CPIR which is useful for scanning C-style (NULL-terminated) strings, e.g. to perform strlen(). The designers must have identified that running C programs (as opposed to Pascal, where the length of a string is in the header) was something that their design was likely to be used for. Another classic example is the Lisp Machine.

What other examples are there? E.g. instructions, number and type of registers, addressing modes, that make a particular processor favour the conventions of a particular language? I am particularly interested in revisions of the same family.

答:
The Intel iAPX CPU was specifically designed for OO languages. Didn't quite work out, though.

The iAPX 432 (intel Advanced Processor architecture) was Intel's first 32-bit microprocessor design, introduced in 1981 as a set of three integrated circuits. It was intended to be Intel's major design for the 1980s, implementing many advanced multitasking and memory management features. The design was therefore referred to as a Micromainframe...

The iAPX 432 was "designed to be programmed entirely in high-level languages", with Ada being primary and it supported object-oriented programming and garbage collection directly in hardware and microcode. Direct support for various data structures was also intended to allow modern operating systems for the iAPX 432 to be implemented using far less program code than for ordinary processors. These properties and features resulted in a hardware and microcode design that was much more complex than most processors of the era, especially microprocessors.

Using the semiconductor technology of its day, Intel's engineers weren't able to translate the design into a very efficient first implementation. Along with the lack of optimization in a premature Ada compiler, this contributed to rather slow but expensive computer systems, performing typical benchmarks at roughly 1/4 the speed of the new 80286 chip at the same clock frequency (in early 1982).

This initial performance gap to the rather low profile and low priced 8086-line was probably the main reason why Intel's plan to replace the latter (later known as x86) with the iAPX 432 failed. Although engineers saw ways to improve a next generation design, the iAPX 432 Capability architecture had now started to be regarded more as an implementation overhead rather than as the simplifying support it was intended to be.

The iAPX 432 project was a commercial failure for Intel...


问:
How do you keep track of the meaning of your SQL fields?
The more SQL fields I add to my tables and the more primary/foreign keys I add the more I lose the overview for specific fields for certain scenarios like Get/Add/Delete/Update data.

I use SQL Management Studio (SQL Server) to design my database in the database diagram designer.

Maybe there is a better tool or good approach how to keep track of the meaning of all those fields?

答:
Since you're using MSSQL, if you're able to deploy a website then put together a little site that queries the system catalogs for the information you want to document.  Connect to your database and go to Views -> System Views to see them.

I'd ignore the views in INFORMATION_SCHEMA because while they provide a more user-friendly format if you just want to look at them directly, they're lacking some useful information.  The views in the "sys" schema contain everything.

The ones you'll most likely want to start looking at are:

```<code>sys.types
sys.objects
sys.tables
sys.columns
sys.indexes
sys.procedures
sys.views
sys.parameters
sys.schemas
sys.foreign_keys
sys.foreign_key_columns
sys.extended_properties
</code>```

If you have any problems figuring out the meanings of columns in those views, they're all documented in Books Online / MSDN.  Most of those should be self explanatory, except maybe sys.extended_properties.  That's where Management Studio saves descriptions.  If you add a description to a table and save it, then right-click the table in Object Explorer, and select Properties then Extended Properties you'll see the description.  You can add an arbitrary amount of extended properties to things, and this can come in real handy for documentation depending on what you want to document and how detailed you want to get.

If you want to allow descriptions to be edited in the site itself, you can use the sys.sp_addextendedproperty, sys.sp_updateextendedproperty, and sys.sp_dropextendedproperty stored procedures.

Finally, if you want to document where a table / view / etc. is referenced throughout the database, you can use the sys.sp_depends stored procedure to get that information.

The nice thing about this approach is that your documentation will be exactly as up to date as the database itself.  Looking at a table definition and add a new column to the table?  Refresh the page and it's there.  Although, if you want to have documentation that's just a snapshot, you can do that too.  And you get something you can navigate through and in a format that avoids the clunkiness of trying to read description fields in SSMS.

Body:
Since you're using MSSQL, if you're able to deploy a website then put together a little site that queries the system catalogs for the information you want to document.  Connect to your database and go to Views -> System Views to see them.

I'd ignore the views in INFORMATION_SCHEMA because while they provide a more user-friendly format if you just want to look at them directly, they're lacking some useful information.  The views in the "sys" schema contain everything.

The ones you'll most likely want to start looking at are:

sys.types
sys.objects
sys.tables
sys.columns
sys.indexes
sys.procedures
sys.views
sys.parameters
sys.schemas
sys.foreign_keys
sys.foreign_key_columns
sys.extended_properties

If you have any problems figuring out the meanings of columns in those views, they're all documented in Books Online / MSDN.  Most of those should be self explanatory, except maybe sys.extended_properties.  That's where Management Studio saves descriptions.  If you add a description to a table and save it, then right-click the table in Object Explorer, and select Properties then Extended Properties you'll see the description.  You can add an arbitrary amount of extended properties to things, and this can come in real handy for documentation depending on what you want to document and how detailed you want to get.

If you want to allow descriptions to be edited in the site itself, you can use the sys.sp_addextendedproperty, sys.sp_updateextendedproperty, and sys.sp_dropextendedproperty stored procedures.

Finally, if you want to document where a table / view / etc. is referenced throughout the database, you can use the sys.sp_depends stored procedure to get that information.

The nice thing about this approach is that your documentation will be exactly as up to date as the database itself.  Looking at a table definition and add a new column to the table?  Refresh the page and it's there.  Although, if you want to have documentation that's just a snapshot, you can do that too.  And you get something you can navigate through and in a format that avoids the clunkiness of trying to read description fields in SSMS.


问:
eXtreme Programming (XP) Methodology Testing
I am about to undertake a project for university, and given the project scope I have decided to use XP/agile methodology. I have began with developing a use case diagram; gathering user stories for the first couple features.

I am in the process of helping the customer develop the acceptance test and my question is: can the user stories for each feature be used as a user acceptance test?

答:
This depends on exactly what the scope of your user stories are - if they are broadly scoped, for example 'a user signs in to a site, confirms his email and receives his download', then 'no'; however is your user stories are narrowly scoped for example 'a user with a queue of 1)a and 2)b, sends a request to get the next movie, 'a' is not available, then send 'b', then 'yes'.

I would be happy to update this answer AFTER you provide one or two samples of your user stories.


问:
To be an interviewer - Java
The internet is full of references on how to get prepared for an interview. Many websites are loaded with questions and answers. But I can't find any useful information about what exactly an interviewer should do to evaluate a candidate.

What I mean is not just collecting good questions to be asked. I am asking about strategy for evaluating a candidate and find out if he is really good or just learnt the questions and answers well. I wonder if someone can share his experience in interviewing SWES, and what do you think about the following

What to expect from a junior java developer? what he should know?

What to expect from a senior java developer? what he should know?

答:
The two main points to consider, in my opinion, are these:

Is the candidate a good cultural fit?

Can your candidate program?

Nobody wants a great programmer with an ego twice the size of your company (at least not if you're going to have a team of developers) or someone who's too shy to share ideas with others. And even the most likeable person is rather useless to you if they can't program their way out of a paper bag.

Cultural questions are ones you'll have to decide for yourself; after all, it's your culture the candidate needs to fit into.

As for programming questions, I recently had a good interview with some guys who gave me a FizzBuzz test (or maybe try some alternatives) while asking me a bunch of other questions. Sometimes it's good to see how candidates perform when you take them out of their comfort zone; this can trip up even some "senior" programmers. The last time I interviewed candidates, I put some intentionally bad code in front of them and asked them to point out how it could be improved. The point of FizzBuzz questions and code-on-paper type questions is to weed out "pretenders" who are good at theoretical programming but can't perform when they have to write or analyse actual code. It can also stump veterans who are too used to writing code exclusively with their favourite IDE and forget the pen-and-paper basics. How much you read into their performance is up to you (in my case we hired a guy who drew a complete blank when looking at the code sample, because he did really well in all other questions and we could tell from other questions that he was technically quite capable).

Whether you're interviewing for a junior or senior developer role, I would also recommend not wasting too much time going into detailed questions about specific technologies. Once you know they're technically good programmers (with good core Java skills), and have made sure they didn't just put buzzwords in their resume without really knowing anything about them, you should be confident that they can pick up skills in the relevant frameworks relatively quickly. If you can program, you should be able to program irrespective of what technology stack is used.

Last but not least, go with your gut instinct and try to see past artificial facades interviewees tend to put up.

Title: To be an interviewer - Java


答:
Some ARM processors, mainly those in mobile devices, include(d) Jazelle extension, which is hardware JVM interpreter; it interprets Java bytecode directly. Jazelle-aware JVM can use the hardware to speed up the execution and eliminate much of JIT, but fallback to software VM is still ensured if bytecode cannot be interpreted on chip.

Processors with such unit include BXJ instruction, which puts processor in special "Jazelle mode", or if activating the unit had failed, it is just interpreted as normal branch instruction. The unit reuses ARM registers to hold JVM state.

The successor to Jazelle technology is ThumbEE

Title: How have languages influenced CPU design?

Body:
We are often told that the hardware doesn't care what language a program is written in as it only sees the compiled binary code, however this is not the whole truth. For example, consider the humble Z80; its extensions to the 8080 instruction set include instructions like CPIR which is useful for scanning C-style (NULL-terminated) strings, e.g. to perform strlen(). The designers must have identified that running C programs (as opposed to Pascal, where the length of a string is in the header) was something that their design was likely to be used for. Another classic example is the Lisp Machine.

What other examples are there? E.g. instructions, number and type of registers, addressing modes, that make a particular processor favour the conventions of a particular language? I am particularly interested in revisions of the same family.


问:
Dependency injection ; good practices to reduce boilerplate code
I have a simple question, and I'm not even sure it has an answer but let's try.
I'm coding in C++, and using dependancy injection to avoid global state. This works quite well, and I don't run in unexpected/undefined behaviours very often.

However I realise that, as my project grows I'm writing a lot of code which I consider boilerplate. Worse : the fact there is more boilerplate code, than actual code makes it sometimes hard to understand.

Nothing beats a good example so let's go :

I have a class called TimeFactory which creates Time objects.

For more details (not sure it's relevant) : Time objects are quite complex because the Time can have different formats, and conversion between them is neither linear, nor straightforward. Each "Time" contains a Synchronizer to handle conversions, and to make sure they have the same, properly initialized, synchronizer, I use a TimeFactory. The TimeFactory has only one instance and is application wide, so it would qualify for singleton but, because it's mutable, I don't want to make it a singleton

In my app, a lot of classes need to create Time objects. Sometimes those classes are deeply nested.

Let's say I have a class A which contains instances of class B, and so on up to class D.  Class D need to create Time objects.

In my naive implementation, I pass the TimeFactory to the constructor of class A, which passes it to the constructor of class B and so on until class D.

Now, imagine I have a couple of classes like TimeFactory and a couple of class hierarchies like the one above : I loose all the flexibility and readability I'm suppose to get using dependancy injection .

I'm starting to wonder if there isn't a major design flaw in my app ...
Or is this a necessary evil of using dependancy injection ?

What do you think ?

答:
I'm not sure why you don't want to make your time factory a singleton. If there's only one instance of it in your whole app, it is de facto a singleton.

That being said, it is very dangerous to share a mutable object, except if it's properly guarded by synchronize blocks, in which case, there's no reason for it not to be a singleton.

If you want to do dependency injection, you might want to look at spring or other dependency injection frameworks, which would allow you to auto assign parameters using an annotation


答:
A template will always depend on outside variables, and with PHP being a dynamic language, there is no way to enforce at compile time that they will be there. So the first approach is probably fine; there are still a few problems though:

The example does not take care of HTML-encoding the output, which means you have potential XSS vulnerabilities.

If one of those variables isn't set, the code will raise a warning; you won't see whether the warning makes sense or not (maybe the variable is optional).

A very straightforward approach is to write a function, preferably with a very short name, that takes care of both these; calling it _() seems to be a common convention. A simple version might look like this:

```<code>function _($raw) {
    if (isset($raw)) {
        return htmlspecialchars($raw);
    }
}
</code>```

And then in your template, you'd do:

```<code><title><?= _($title) ?></title>
</code>```

More things to do with the _() function:

Give it a second argument to allow overriding the htmlspecialchars call, for cases where you want to pass HTML into it rather than raw strings.

Add type checking so that arrays and objects won't yield Array and Object, but rather something meaningful (or empty string).

Add internationalization support (yet another argument).

When in debug mode, print the name of the variable with some special formatting if it isn't defined. This way, you can see at a glimpse if there's anything wrong with the template.

Body:
A template will always depend on outside variables, and with PHP being a dynamic language, there is no way to enforce at compile time that they will be there. So the first approach is probably fine; there are still a few problems though:

The example does not take care of HTML-encoding the output, which means you have potential XSS vulnerabilities.

If one of those variables isn't set, the code will raise a warning; you won't see whether the warning makes sense or not (maybe the variable is optional).

A very straightforward approach is to write a function, preferably with a very short name, that takes care of both these; calling it _() seems to be a common convention. A simple version might look like this:

function _($raw) {
    if (isset($raw)) {
        return htmlspecialchars($raw);
    }
}

And then in your template, you'd do:

<title><?= _($title) ?></title>

More things to do with the _() function:

Give it a second argument to allow overriding the htmlspecialchars call, for cases where you want to pass HTML into it rather than raw strings.

Add type checking so that arrays and objects won't yield Array and Object, but rather something meaningful (or empty string).

Add internationalization support (yet another argument).

When in debug mode, print the name of the variable with some special formatting if it isn't defined. This way, you can see at a glimpse if there's anything wrong with the template.


答:
What do you mean by "I loose all the flexibility and readability I'm suppose to get using dependency injection" - DI isn't about readability. It's about decoupling the dependency between objects.

It sounds like you have Class A creating Class B, Class B creating Class C and Class C creating Class D.

What you should have is Class B injected in to Class A. Class C injected in to Class B. Class D injected in to Class C.

Title: Dependency injection ; good practices to reduce boilerplate code

Body:
I have a simple question, and I'm not even sure it has an answer but let's try.
I'm coding in C++, and using dependancy injection to avoid global state. This works quite well, and I don't run in unexpected/undefined behaviours very often.

However I realise that, as my project grows I'm writing a lot of code which I consider boilerplate. Worse : the fact there is more boilerplate code, than actual code makes it sometimes hard to understand.

Nothing beats a good example so let's go :

I have a class called TimeFactory which creates Time objects.

For more details (not sure it's relevant) : Time objects are quite complex because the Time can have different formats, and conversion between them is neither linear, nor straightforward. Each "Time" contains a Synchronizer to handle conversions, and to make sure they have the same, properly initialized, synchronizer, I use a TimeFactory. The TimeFactory has only one instance and is application wide, so it would qualify for singleton but, because it's mutable, I don't want to make it a singleton

In my app, a lot of classes need to create Time objects. Sometimes those classes are deeply nested.

Let's say I have a class A which contains instances of class B, and so on up to class D.  Class D need to create Time objects.

In my naive implementation, I pass the TimeFactory to the constructor of class A, which passes it to the constructor of class B and so on until class D.

Now, imagine I have a couple of classes like TimeFactory and a couple of class hierarchies like the one above : I loose all the flexibility and readability I'm suppose to get using dependancy injection .

I'm starting to wonder if there isn't a major design flaw in my app ...
Or is this a necessary evil of using dependancy injection ?

What do you think ?


答:
In my app, a lot of classes need to create Time objects

Seems that your Time class is a very basic data type which should belong to the "general infrastructure" of your application. DI does not work well for such classes. Think about what it means if a class like string had to be injected into every part of the code which uses strings, and you would need to use a stringFactory as the only possibilty of creating new strings - the readability of your program would decrease by an order of magnitude.

So my suggestion: don't use DI for general datatypes like Time. Write unit tests for the Time class itself, and when its done, use it everywhere in your program, just like the string class, or a vector class or any other class of the standard lib. Use DI for components which should be really decoupled one from each other.


答:
Do your A, B and C classes also need to create Time instances, or only class D? If it's only class D, then A and B should know nothing about TimeFactory. Create an instance of TimeFactory inside C class, and pass it to class D. Note that by "create an instance" I don't necessarily mean that the C class has to be responsible for instantiating the TimeFactory. It can receive DClassFactory from class B, and DClassFactory knows how to create Time instance.

A technique that I also often use when I don't have any DI framework is providing two constructors, one which accepts a factory, and another one which creates a default factory. The second one has usually a protected/package access, and is used mainly for unit tests.


问:
Have you ever found yourself using a specific tool in favor of another just because it looks better?
I found that this was the case with Eclipse.
When I first started learning Java a lot of people told me to start with NetBeans because it's easier, comes with a lot of predefined functionality and most of the configuration is done by default. Indeed it seemed like an easy IDE but I just hated the way it looked. The UI to me was horrible.

Then I downloaded Eclipse. I was pretty impressed with it. Everything looked shiny, fonts looked awesome and the UI in general was amazing compared to NetBeans'. So I stayed with Eclipse.

Has something like this ever happen to you? Should the UI be of such a relevance to a programmer, is this bad ? The problem of the UI extends to everything for me, not only IDE's (e.g. even on linux I have to customize the WM the way I want before starting working with it).

答: Personally, I don't really care about UI. Terminal programs work well, so do GUIs, and terminal ones take less memory. The UI isn't really an element for me unless it enables more productivity, like say firefox over w3m (at least for me).


问:
As a professional developer, is it acceptable to not write unit tests?
Just wondering on the pros and cons on TDD/automated unit testing and looking for the community's view on whether it's acceptable for professional developers to write applications without supporting unit tests?</p>

答:
To test what?

If you're talking about 100% code coverage, it's extremely rare, not useful and often impossible. In the same way, testing CRUD-related code is a waste of time, and it would be highly unprofessional to spend hours writing code you don't need instead of doing something actually useful.

Now, as a developer, you have to know how to write unit tests, and where do you need them.


答:
You definitely do not want "no testing". If you write unit tests, you ave at least some assurance that your code matches your tests (although you'd need to ensure that your tests matches your specification).

You're not done if all you have is unit tests, though. You probably still need to do integration tests and end-to-end tests (and over time accumulate test cases to catch bug regressions).

Title: As a professional developer, is it acceptable to not write unit tests?

Body: Just wondering on the pros and cons on TDD/automated unit testing and looking for the community's view on whether it's acceptable for professional developers to write applications without supporting unit tests?</p>


答:
It really depends on how the application will be used.  Is this a mission critical application?  Or is it a simple verification application only used internally by developers?  When working on the core applications for your company there should be as much unit tests as necessary to ensure the business decisions are covered.  Depending on your company, those are the applications customers see and bugs could cost the money.  When done well, unit tests can be a big help to ensure your applications will work when deployed.  But it is not a cure all and human testing should still be done.  Simple internal (or ancillary) applications don't need unit tests, but should still be written well.

TDD is not just about writing tests first.  It is about making sure your code is easily testable.  And more often than not easily testable code is also easier to read/debug/maintain.  More often than not easily testable code also follows patterns and OO principles such as SOLID.  I would argue as a professional developer your code should always be written that way.


答: Sure, it is acceptable to not write unit tests for little internal helper utilities, or test tools, or scenarios where business really really needs things other than quality and you as the professional developer find that you can get the software done and working just as quickly without.


问:
What does it mean by expected running time and average running time of an algorithm?
Let's say we want to analyze running time of algorithms. Sometimes we say that we want to find the running time of an algorithm when the input size is n and for the worst possible case it is denote it by O(n). Sometimes though I see books/papers saying that we need to find the expected time of an algorithm. Also sometimes the average running time is used .

What is "expected time"? In which cases is it useful to find expected time instead of worst case time?

Edit: I think there is a subtle difference between expected running time and average running time but I am not sure . Through this post I want to know the exact difference if any .

答:
The expected running time of a randomized algorithm is a well-defined concept, just like the worst case running time. If an algorithm is randomized, its running time is also random, which means we can define the expected value of its running time.

A well-known example is Quicksort: if we pick the pivots at random, we can prove that its expected running time becomes O(n log n), even though its worst case running time remains O(n^2). An example where randomization is very powerful is the smallest enclosing circle problem: there is a simple algorithm whose worst case running time is O(n^3), but in expectation, its running time is only O(n).

Average running time is usually used when talking about the behavior of an algorithm 'for most inputs'. We define some way of randomly generating an input, for instance, we fill an array with random numbers, or we randomly permute the numbers 1 through n (so no duplicates), or we flip a coin and either get a descending or ascending set of numbers. The average running time of an algorithm for that random distribution of inputs is then the expected running time of the algorithm (in which case the algorithm may not be randomized, but the input is).

As an example: there are geometric problems for which algorithms exist that seem to work well at first sight, until you discover some very weird way of distributing, say, the input lines. If you assume the lines are randomly distributed, then it may be the case that these weird scenarios are extremely unlikely to occur, so your algorithm ends up being good.

Contrasting: expected running time is about how an algorithm performs 'unless you have bad luck' - retrying the same algorithm on the same input but with different random choices may lead to it being solved much faster. Average running time talks about how well an algorithm performs 'for most inputs' - trying the same algorithm again on the same input won't help you (except perhaps if the algorithm is also randomized).


答:
In my experience, 95% of the errors that can be caught by unit tests come from calls to the data layer, especially after database design changes. If you're using a database, just put a test over every method you use to access it. The tests don't even need to be elaborate, just sanity checks.

In answer to your question - if you access a database, and you are a professional developer, than you should use unit tests. Otherwise, it depends.


答:
The history of software estimation is a history of underestimation, not of overestimation. In my experience, even when developers think they are padding their estimates they usually are still being overly optimistic. Projects having estimates less than half of reality are not uncommon.

Underestimation is also significatly more risk than overestimation, because of what happens to the project down the road. Underestimated projects will likely take longer than the same project overestimated because of the exponential increase in "catch up activities" such as bug fixes because of cut corners, constant status meetings, replanning and rescoping. Slipping milestones also have downstream effects, affecting the timelines of other teams and customers. They absoultely destroy the confidence of partners in the team's ability to deliver.

In essence, anytime a team is worried about overestimation I would stress that the much larger risk is underestimation. For a great review of this and other estimatation related topics, I love the book Software Estimation: Demystifying the Black Art.


问:
I've inherited 200K lines of spaghetti code -- what now?
I hope this isn't too general of a question; I could really use some seasoned advice.

I am newly employed as the sole "SW Engineer" in a fairly small shop of scientists who have spent the last 10-20 years cobbling together a vast code base. (It was written in a virtually obsolete language: G2 -- think Pascal with graphics). The program itself is a physical model of a complex chemical processing plant; the team that wrote it have incredibly deep domain knowledge but little or no formal training in programming fundamentals. They've recently learned some hard lessons about the consequences of non-existant configuration management. Their maintenance efforts are also greatly hampered by the vast accumulation of undocumented "sludge" in the code itself. I will spare you the "politics" of the situation (there's always politics!), but suffice to say, there is not a consensus of opinion about what is needed for the path ahead.

They have asked me to begin presenting to the team some of the principles of modern software development. They want me to introduce some of the industry-standard practices and strategies regarding coding conventions, lifecycle management, high-level design patterns, and source control. Frankly, it's a fairly daunting task and I'm not sure where to begin.

Initially, I'm inclined to tutor them in some of the central concepts of The Pragmatic Programmer, or Fowler's Refactoring ("Code Smells", etc). I also hope to introduce a number of Agile methodologies. But ultimately, to be effective, I think I'm going to need to hone in on 5-7 core fundamentals; in other words, what are the most important principles or practices that they can realistically start implementing that will give them the most "bang for the buck".

So that's my question: What would you include in your list of the most effective strategies to help straighten out the spaghetti (and prevent it in the future)?

答:
"The program itself is a physical model of a complex chemical processing plant
  ..."

"Since G2 is like not-code, but rather automated code written by some gadawful GUI..." – Erik Reppen

Assuming your software's main goal is to simulate (perhaps optimize, run parameter estimations upon) a complex chemical plant, or parts of one... then I'd like to throw out a rather different suggestion:

You might do well to consider using high-level mathematical modelling language to extract the essence, the core mathematical models, out of hand-coded software.

What a modelling language does is to decouple the description of the problem from the algorithms used to solve the problem. These algorithms are generally applicable to most simulations/optimisations of a given class (e.g. chemical processes) in which case they really shouldn't be re-invented and maintained in-house.

Three commercial packages used widely in your industry are: gPROMS, Aspen Custom Modeller, and (if your models don't include phenomena distributed along spacial domains) there are Modelica-based software packages, such as Dymola.

All of these packages support "extensions" in one way or another, so that if you have parts of your models that require custom programming, they can be encapsulated into an object (e.g. a .DLL) that can be referenced by the equations in the model.  Meanwhile, the bulk of your model remains succinct, described in a form easily readable by the scientists directly. This is a much better way to capture your company's knowledge and IP.

Most of these programs should also allow you to 'start small' and port small parts (sub-models) of your monolithic code into their format, by being called externally. This may be a good way to maintain a working system and validate it one piece at a time.

Full disclaimer: I worked as a software engineer at the company behind gPROMS for 8 years. In that time I saw (and occasionally incorporated) examples of custom software (e.g. coming from academia) which had started small and tidy, implementing some clever solution or algorithm, but then exploded over the years with extensions and modifications - without the helpful guidance of a software engineer to keep it clean. (I'm a big fan of multi-disciplinary teams.)

So I can say with some experience that certain key choices made poorly early on in a software's development (like a language or key library) tend to stick around and cause pain for a long long time... They've already 'shaped' the software around them. It sounds to me like you could be facing many many years of pure code cleaning here. (I'm hesitant to use numbers but I'm thinking 10+ person years, maybe much more if you can't get the code ported from G2 to something that supports good automated refactoring tools like Eclipse/Java quick-smart.)

While my default status is to "refactor and keeping a working system", I also think once a problem gets "too big", then a more radical change/re-write becomes faster overall. (And possibly brings additional benefits, like jumping to a more modern technology.) I say that with some experience porting to a new software platform, but from what I gather it's even more dramatic with a port to a mathematical modelling package.

To give some perspective, you might be quite amazed at the size reduction. E.g. the 200,000 LoC could actually be represented in something like 5,000 lines of equations (OK I'm guessing here, but I could try and get you an actual testimonial from friends in the business); plus a few relatively small function modules written in something like C (for example, physical-property calculations - although again off the shelf packages may exist depending on your chemical process).  This is because you literally just throw away the algorithmic solution code and let a general-purpose 'stack' of mathematical solvers do the hard work. Once you have simulations running, you can do much more with them, like optimising the process - without changing a line of code.

Finally I would say: if the only reliable documentation of the various mathematical models (and algorithms) is the code itself, you will want the help of the scientists and original authors to help extract those models out, ASAP, not years down the track when some of them may have moved on. They should find that a mathematical modelling language a very natural way to capture those models - they may even (shock horror) enjoy (re)writing it.

Finally, since my answer might be off the mark, I'd just like to add one more book to the list of good books already referenced here: Clean Code by Robert Martin. Full of simple (and justified) tips that are easy to learn and apply, but which could make a world of difference to people developing new code at your company.


问:
Generating different combinations from a list of muscles
Suppose we have a model of a human muscular system containing the following muscles each within a specific muscle group:

Arms

Biceps

Triceps

Forearms

Torso Front

Abs

Chest

Shoulders

Torso Back

Trapezius

Lats

Rear Shoulders

Lower Back

Lower Body

Quads

Hams

Hip & Butt

Calves

Now, given a list of selected muscles, I need to find combinations following the given rules:

If all muscles are selected from a group:

```<code>Full body (All muscles)
Arms
Torso
Torso Front
Torso Back
Lower Body
</code>```

If there are full groups together:

```<code>Arms and torso
Arms and torso front
Arms and torso back
Arms and lower body
Torso and lower body
Torso front and lower body
Torso back and lower body
</code>```

When both the front and back of the torso is selected it can be considered just "torso".

If there are more than 2 muscles selected from a group but not all:

```<code>Parts of torso (This is the case where there are muscles selected from both front- and back-torso)
Parts of torso back
Parts of lower body
</code>```

"Parts of torso front" and "Parts of arms" never occur on their own as they only have a total of 3 muscles, thus those cases can be represented by their names: eg. "biceps and triceps", etc.

Combinations of these aforementioned "parts"

```<code>Parts of arms and torso
Parts of arms and lower body
Parts of torso and lower body
Parts of  arms, torso and lower body.
</code>```

Parts = groups are not full and there are more than 2 muscles selected. This "rule of 2" is the most important one.

Examples of output

biceps, triceps and chest: parts of arms and torso

biceps, triceps, calves, tai biceps, triceps, quads, hams, hip & butt: Parts of arms and lower body

biceps, abs, calves: Parts of arms, torso and lower body

biceps, triceps: Biceps and triceps

biceps, triceps, forearms: Arms

chest, shoulders, abs, trapezius, lats, rear shoulders, lower back: Torso

and so on, there are multiple possible variations.

Now my problem is that I have no idea how to write this as clean and modular as possible, so that rules can be added or removed if necessary.

I could just write a massive if-elseif-else pile that would consider all cases, but you know why I won't.

How would you tackle this kind of task?

答:
Answer 2 :

The real problem is to link body's elements together.

For this case we have only two types : muscles and bones [here, grouped in body part].
So if we begin to develop group (of bones) we certainly will be able to detail them to bones granularity.

It is obvious that add a new group of nerves will not be difficult if link model between bones and muscles is adequate.

I'm thinking in Java with OODB to give sample.

I use the OpenSource db4objects, it is also Java, possibility to use EmbeddedObjectContainer  loaded with the API, no server, no DBA's problem.

Think it like a disk with useful database tools to manage complex I/O like Transparent Activation/Transparent Persistence, and other powerful tools like a manager, and it is able to migrate to huge Versant professional OODB.

Your job : work with a unique class with three fields :

```<code>package ElemBody;

import java.util.HashSet;
import java.util.Set;

public final class ElementBody {

    // In true life fields are 'private' with getters and setters
    public int typ; // TYP_ELEM.BONES.ordinale() Indexed
    public String name; // indexed with UniqueKey
    // HashSet (and not SortedSet for optimization) Element linked
    public Set<ElementBody> linkedElem = new HashSet<ElementBody>();

    // Print utility
    @Override
    public final String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append(name);
        sb.append(" - ");
        for (final ElementBody el : linkedElem) {
            sb.append(el.name);
            sb.append(", ");
        }
        sb.append(linkedElem.size());
        sb.append(".");
        return sb.toString();
    }
}
</code>```

The main, (tedious) loading/linking data and quering :

```<code>package ElemBody;

import java.io.File;
import java.util.Iterator;

import com.db4o.Db4oEmbedded;
import com.db4o.EmbeddedObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.config.EmbeddedConfiguration;
import com.db4o.constraints.UniqueFieldValueConstraint;
import com.db4o.query.Query;

public class PrmBody {
    public enum TYP_ELEM {
        BONES, MUSCLES, NERVES // here, place for futur types
    }

    public static void main(final String[] args) {
        // one of possible db4o's configuration
        final EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
        // Managing index and unique key
        config.common().objectClass(ElementBody.class).objectField("type")
            .indexed(true);
        config.common().objectClass(ElementBody.class).objectField("name")
            .indexed(true);
        config.common().add(
            new UniqueFieldValueConstraint(ElementBody.class, "name"));
        // You have also an InMemory option, here the file one
        // Because of name's uniqueKey option, delete for test, in true live
        // read before create/update
        new File("Q:/tmp/ElementBody.db4o").delete();
        final EmbeddedObjectContainer eoc = Db4oEmbedded.openFile(config,
        // "ElementBody.db4o"); // in "user.home" directory
            "Q:/tmp/ElementBody.db4o");

        // Tedious option to load database.
        // Use .properties ou CSV files

        // Create BONES
        for (final String s : new String[]{"Arms", "Torso Front", "Torso Back",
            "LowerBody"}) {
            final ElementBody el = new ElementBody();
            el.typ = TYP_ELEM.BONES.ordinal();
            el.name = s;
            eoc.store(el); // save new instance
        }

        // Create MUSCLES
        final String[] muscles = {"Biceps", "Triceps", "Forearms",//
            "Abs", "Chest", "Shoulders", //
            "Trapezius", "Lats", "Rear Shoulders", "Lower Back", //
            "Quads", "Hams", "Hip & Butt", "Calves"};
        for (final String s : muscles) {
            final ElementBody el = new ElementBody();
            el.typ = TYP_ELEM.MUSCLES.ordinal();
            el.name = s;
            eoc.store(el);
        }

        // Simplified control of read type form db4o
        final Query queryA = eoc.query();
        queryA.constrain(ElementBody.class);
        queryA.descend("name").constrain("Arms").equal();
        final ElementBody arm = (ElementBody) queryA.execute().iterator()
            .next();
        for (final String s : new String[]{"Biceps", "Triceps", "Forearms",
            "Shoulders"}) {
            final Query query = eoc.query();
            query.constrain(ElementBody.class);
            query.descend("name").constrain(s).equal();
            final ObjectSet<ElementBody> musT = query.execute();
            musT.get(0).linkedElem.add(arm);
            arm.linkedElem.add(musT.get(0));
            eoc.store(musT.get(0));
        }
        eoc.store(arm);

        final Query queryB = eoc.query();
        queryB.constrain(ElementBody.class);
        queryB.descend("name").constrain("Torso Front").equal();
        final ElementBody tf = (ElementBody) queryB.execute().get(0);
        for (final String s : new String[]{"Abs", "Chest", "Shoulders"}) {
            final Query query = eoc.query();
            query.constrain(ElementBody.class);
            query.descend("name").constrain(s).equal();
            final ElementBody mus = (ElementBody) query.execute().get(0);
            mus.linkedElem.add(tf);
            tf.linkedElem.add(mus);
            eoc.store(mus);
        }
        eoc.store(tf);

        final Query queryC = eoc.query();
        queryC.constrain(ElementBody.class);
        queryC.descend("name").constrain("Torso Back").equal();
        final ElementBody tb = (ElementBody) queryC.execute().get(0);
        for (final String s : new String[]{"Trapezius", "Lats",
            "Rear Shoulders", "Lower Back", "Shoulders"}) {
            final Query query = eoc.query();
            query.constrain(ElementBody.class);
            query.descend("name").constrain(s).equal();
            final ElementBody mus = (ElementBody) query.execute().get(0);
            mus.linkedElem.add(tb);
            tb.linkedElem.add(mus);
            eoc.store(mus);
        }
        eoc.store(tb);
        eoc.commit(); // End load part // // //

        // Two samples of request
        final Query r1 = eoc.query();
        r1.constrain(ElementBody.class);
        r1.descend("typ").constrain(TYP_ELEM.BONES.ordinal()).equal();
        for (final Object obj : r1.execute()) {
            final ElementBody el = (ElementBody) obj;
            System.out.println("\n" + TYP_ELEM.BONES + "\t" + el.name);
            final Iterator<ElementBody> it = el.linkedElem.iterator();
            while (it.hasNext()) {
                System.out.println("\t" + it.next());
            }
        }

        final Query r2 = eoc.query();
        r2.constrain(ElementBody.class);
        r2.descend("typ").constrain(TYP_ELEM.MUSCLES.ordinal()).equal();
        r2.descend("name").constrain("Q").smaller();
        r2.descend("name").orderAscending();

        final ObjectSet<ElementBody> osEl = r2.execute();
        System.out.println("---------------\n" + osEl.size()
            + " muscles in db with A to P prime letter name.");
        final Iterator<ElementBody> itEl = osEl.iterator();
        int sumLink = 0;
        while (itEl.hasNext()) {
            final ElementBody elTmp = itEl.next();
            System.out.print(elTmp.name + ", ");
            sumLink += elTmp.linkedElem.size();
        }
        System.out.println("\nThose muscles have " + sumLink
            + " links to bones, LowerBody's ones excluded.");
        eoc.close();
    }
}
</code>```

I've add “Shoulders” in two 'Torso' to show how you can feed back your links.

With samples of (SODA) query, you will be able to pick all needed groups.

Console:

```<code>BONES   Arms
    Forearms - Arms, 1.
    Triceps - Arms, 1.
    Shoulders - Arms, Torso Back, Torso Front, 3.
    Biceps - Arms, 1.

BONES   Torso Front
    Abs - Torso Front, 1.
    Shoulders - Arms, Torso Back, Torso Front, 3.
    Chest - Torso Front, 1.

BONES   Torso Back
    Lower Back - Torso Back, 1.
    Trapezius - Torso Back, 1.
    Rear Shoulders - Torso Back, 1.
    Shoulders - Arms, Torso Back, Torso Front, 3.
    Lats - Torso Back, 1.

BONES   LowerBody
---------------
9 muscles in db with A to P prime letter name.
Abs, Biceps, Calves, Chest, Forearms, Hams, Hip & Butt, Lats, Lower Back,
Those muscles have 6 links to bones, LowerBody's ones excluded.
</code>```

In my sense, it is not a mathematical model, but an intuitive one :

what is the real question? → where are  real objects? (do not begin with abstraction, or technical solution, if no needed, and decrypt the real problem, behind the beautiful requirements paper)

who really works? → what is done? (take the place of the objects, then imagine how you are now represented : hum, not so good representation doesn't it?)

who and what is really needed (a lazy developer want to verify/test less possible objects and more simple objects than an 'all home made' one)

we manage data? → a database is needed,

can we be more simple? → this take time, a night is generally a good elapse time

is request the only problem for final user? → right! look him working, he is the only men able to understand what he want, here the problem : experience will show you how decrypt those 'not said but critical' things.

If all [or part] of this is already made → use it

Unless it is for highly stress usage (or OS only known by one genius) all is already written, and often well written and optimized, and secure.

Here I've used something like 'internal reverse index model' (Perhaps exists under another official name) :

Database have indexes on fields (columns for SGBDRs) as all database you know

In OODB we add list/set/BTree/.. to link an instance of an object type to another one of same type, or to another instance of a different type (but always the same instances type linked in one list).

If your project came bigger and more complex you will be able to use such methods without difficulties.

No complexity to load numerous CSV files, no real difficulties to add queries,

One class, three fields, and basic methods (your job, already made, only add query for an object before create or update if you do not want delete database each tim - and other pitfall to avoid, listen in reference doc)

One OODB (imported) (just configure it, add TA/TP, you can put it inMemory)

One class for CSV file  (import CsvReader)

One class to load Csv in DB (Little job, model in PrmBody)

Some simple classes for dedicated queries (not painfull if you understand SODA query)

I use JSON, but take your prefered  web tool for presentation (may be time eater for all public usage).

Feel free to tell us if it convenient for you.

Body:
Answer 2 :

The real problem is to link body's elements together.

For this case we have only two types : muscles and bones [here, grouped in body part].
So if we begin to develop group (of bones) we certainly will be able to detail them to bones granularity.

It is obvious that add a new group of nerves will not be difficult if link model between bones and muscles is adequate.

I'm thinking in Java with OODB to give sample.

I use the OpenSource db4objects, it is also Java, possibility to use EmbeddedObjectContainer  loaded with the API, no server, no DBA's problem.

Think it like a disk with useful database tools to manage complex I/O like Transparent Activation/Transparent Persistence, and other powerful tools like a manager, and it is able to migrate to huge Versant professional OODB.

Your job : work with a unique class with three fields :

package ElemBody;

import java.util.HashSet;
import java.util.Set;

public final class ElementBody {

    // In true life fields are 'private' with getters and setters
    public int typ; // TYP_ELEM.BONES.ordinale() Indexed
    public String name; // indexed with UniqueKey
    // HashSet (and not SortedSet for optimization) Element linked
    public Set<ElementBody> linkedElem = new HashSet<ElementBody>();

    // Print utility
    @Override
    public final String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append(name);
        sb.append(" - ");
        for (final ElementBody el : linkedElem) {
            sb.append(el.name);
            sb.append(", ");
        }
        sb.append(linkedElem.size());
        sb.append(".");
        return sb.toString();
    }
}

The main, (tedious) loading/linking data and quering :

package ElemBody;

import java.io.File;
import java.util.Iterator;

import com.db4o.Db4oEmbedded;
import com.db4o.EmbeddedObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.config.EmbeddedConfiguration;
import com.db4o.constraints.UniqueFieldValueConstraint;
import com.db4o.query.Query;

public class PrmBody {
    public enum TYP_ELEM {
        BONES, MUSCLES, NERVES // here, place for futur types
    }

    public static void main(final String[] args) {
        // one of possible db4o's configuration
        final EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
        // Managing index and unique key
        config.common().objectClass(ElementBody.class).objectField("type")
            .indexed(true);
        config.common().objectClass(ElementBody.class).objectField("name")
            .indexed(true);
        config.common().add(
            new UniqueFieldValueConstraint(ElementBody.class, "name"));
        // You have also an InMemory option, here the file one
        // Because of name's uniqueKey option, delete for test, in true live
        // read before create/update
        new File("Q:/tmp/ElementBody.db4o").delete();
        final EmbeddedObjectContainer eoc = Db4oEmbedded.openFile(config,
        // "ElementBody.db4o"); // in "user.home" directory
            "Q:/tmp/ElementBody.db4o");

        // Tedious option to load database.
        // Use .properties ou CSV files

        // Create BONES
        for (final String s : new String[]{"Arms", "Torso Front", "Torso Back",
            "LowerBody"}) {
            final ElementBody el = new ElementBody();
            el.typ = TYP_ELEM.BONES.ordinal();
            el.name = s;
            eoc.store(el); // save new instance
        }

        // Create MUSCLES
        final String[] muscles = {"Biceps", "Triceps", "Forearms",//
            "Abs", "Chest", "Shoulders", //
            "Trapezius", "Lats", "Rear Shoulders", "Lower Back", //
            "Quads", "Hams", "Hip & Butt", "Calves"};
        for (final String s : muscles) {
            final ElementBody el = new ElementBody();
            el.typ = TYP_ELEM.MUSCLES.ordinal();
            el.name = s;
            eoc.store(el);
        }

        // Simplified control of read type form db4o
        final Query queryA = eoc.query();
        queryA.constrain(ElementBody.class);
        queryA.descend("name").constrain("Arms").equal();
        final ElementBody arm = (ElementBody) queryA.execute().iterator()
            .next();
        for (final String s : new String[]{"Biceps", "Triceps", "Forearms",
            "Shoulders"}) {
            final Query query = eoc.query();
            query.constrain(ElementBody.class);
            query.descend("name").constrain(s).equal();
            final ObjectSet<ElementBody> musT = query.execute();
            musT.get(0).linkedElem.add(arm);
            arm.linkedElem.add(musT.get(0));
            eoc.store(musT.get(0));
        }
        eoc.store(arm);

        final Query queryB = eoc.query();
        queryB.constrain(ElementBody.class);
        queryB.descend("name").constrain("Torso Front").equal();
        final ElementBody tf = (ElementBody) queryB.execute().get(0);
        for (final String s : new String[]{"Abs", "Chest", "Shoulders"}) {
            final Query query = eoc.query();
            query.constrain(ElementBody.class);
            query.descend("name").constrain(s).equal();
            final ElementBody mus = (ElementBody) query.execute().get(0);
            mus.linkedElem.add(tf);
            tf.linkedElem.add(mus);
            eoc.store(mus);
        }
        eoc.store(tf);

        final Query queryC = eoc.query();
        queryC.constrain(ElementBody.class);
        queryC.descend("name").constrain("Torso Back").equal();
        final ElementBody tb = (ElementBody) queryC.execute().get(0);
        for (final String s : new String[]{"Trapezius", "Lats",
            "Rear Shoulders", "Lower Back", "Shoulders"}) {
            final Query query = eoc.query();
            query.constrain(ElementBody.class);
            query.descend("name").constrain(s).equal();
            final ElementBody mus = (ElementBody) query.execute().get(0);
            mus.linkedElem.add(tb);
            tb.linkedElem.add(mus);
            eoc.store(mus);
        }
        eoc.store(tb);
        eoc.commit(); // End load part // // //

        // Two samples of request
        final Query r1 = eoc.query();
        r1.constrain(ElementBody.class);
        r1.descend("typ").constrain(TYP_ELEM.BONES.ordinal()).equal();
        for (final Object obj : r1.execute()) {
            final ElementBody el = (ElementBody) obj;
            System.out.println("\n" + TYP_ELEM.BONES + "\t" + el.name);
            final Iterator<ElementBody> it = el.linkedElem.iterator();
            while (it.hasNext()) {
                System.out.println("\t" + it.next());
            }
        }

        final Query r2 = eoc.query();
        r2.constrain(ElementBody.class);
        r2.descend("typ").constrain(TYP_ELEM.MUSCLES.ordinal()).equal();
        r2.descend("name").constrain("Q").smaller();
        r2.descend("name").orderAscending();

        final ObjectSet<ElementBody> osEl = r2.execute();
        System.out.println("---------------\n" + osEl.size()
            + " muscles in db with A to P prime letter name.");
        final Iterator<ElementBody> itEl = osEl.iterator();
        int sumLink = 0;
        while (itEl.hasNext()) {
            final ElementBody elTmp = itEl.next();
            System.out.print(elTmp.name + ", ");
            sumLink += elTmp.linkedElem.size();
        }
        System.out.println("\nThose muscles have " + sumLink
            + " links to bones, LowerBody's ones excluded.");
        eoc.close();
    }
}

I've add “Shoulders” in two 'Torso' to show how you can feed back your links.

With samples of (SODA) query, you will be able to pick all needed groups.

Console:

BONES   Arms
    Forearms - Arms, 1.
    Triceps - Arms, 1.
    Shoulders - Arms, Torso Back, Torso Front, 3.
    Biceps - Arms, 1.

BONES   Torso Front
    Abs - Torso Front, 1.
    Shoulders - Arms, Torso Back, Torso Front, 3.
    Chest - Torso Front, 1.

BONES   Torso Back
    Lower Back - Torso Back, 1.
    Trapezius - Torso Back, 1.
    Rear Shoulders - Torso Back, 1.
    Shoulders - Arms, Torso Back, Torso Front, 3.
    Lats - Torso Back, 1.

BONES   LowerBody
---------------
9 muscles in db with A to P prime letter name.
Abs, Biceps, Calves, Chest, Forearms, Hams, Hip & Butt, Lats, Lower Back,
Those muscles have 6 links to bones, LowerBody's ones excluded.

In my sense, it is not a mathematical model, but an intuitive one :

what is the real question? → where are  real objects? (do not begin with abstraction, or technical solution, if no needed, and decrypt the real problem, behind the beautiful requirements paper)

who really works? → what is done? (take the place of the objects, then imagine how you are now represented : hum, not so good representation doesn't it?)

who and what is really needed (a lazy developer want to verify/test less possible objects and more simple objects than an 'all home made' one)

we manage data? → a database is needed,

can we be more simple? → this take time, a night is generally a good elapse time

is request the only problem for final user? → right! look him working, he is the only men able to understand what he want, here the problem : experience will show you how decrypt those 'not said but critical' things.

If all [or part] of this is already made → use it

Unless it is for highly stress usage (or OS only known by one genius) all is already written, and often well written and optimized, and secure.

Here I've used something like 'internal reverse index model' (Perhaps exists under another official name) :

Database have indexes on fields (columns for SGBDRs) as all database you know

In OODB we add list/set/BTree/.. to link an instance of an object type to another one of same type, or to another instance of a different type (but always the same instances type linked in one list).

If your project came bigger and more complex you will be able to use such methods without difficulties.

No complexity to load numerous CSV files, no real difficulties to add queries,

One class, three fields, and basic methods (your job, already made, only add query for an object before create or update if you do not want delete database each tim - and other pitfall to avoid, listen in reference doc)

One OODB (imported) (just configure it, add TA/TP, you can put it inMemory)

One class for CSV file  (import CsvReader)

One class to load Csv in DB (Little job, model in PrmBody)

Some simple classes for dedicated queries (not painfull if you understand SODA query)

I use JSON, but take your prefered  web tool for presentation (may be time eater for all public usage).

Feel free to tell us if it convenient for you.


问:
When do we need to apply a software development methodology?
There are many software development methodologies - SCRUM, agile, XP, etc. - and they all have there advantages and disadvantages I suppose.

But when do we really need to apply them? Surely they are not necessary for small 1-man projects, but for large 50+ teams you can most certainly not go about ad-hoc:ing the whole thing.

So what's the line for when to use and when to not use such a methodology, if there indeed is one?

答: The question really doesn't make sense. No matter what you do you are applying some form of SDLC approach. That approach might be cowboy coding or waterfall, but it is an approach. A better question is what projects and team sizes are better suited to what approaches.</p>


问:
Are there open source alternatives to Bitbucket, Github, Kiln, and similar DVCS browsing and management tools?
I am aware of several tools/services that provide DVCS browsing and management such as Bitbucket, Github, Kiln, SCM-Manager and Rhodecode.

However, the use case I am considering is one such that:

Any source code must reside on an employers internal servers.

The solution must be open source.

It should provide a Bitbucket or Github like experience, including a project wiki, repository browsing and management, and social coding aspects such as code review.

The solution should have mercurial support (if not support for other DVCSs).

Of these, only SCM-Manager and RhodeCode come close as they can be installed on your own servers and are open source. However they do not have the Bitbucket or Github experience. There is no issue tracker or wiki and the UI, while functional, is not up to par with Github or Bitbucket.

I can get close with Trac or Redmine with their repository browsers but unfortunately they do not have any repository management capabilities.

Are there other open source tools out there that would provide a similar experience to Bitbucket, Github or Kiln?

答:
Take a look at cydra: https://github.com/mensi/cydra it has support for

Subversion (HTTP)

Git (HTTP and SSH on separate port)

Mercurial (HTTP)

Trac

It works on a project based approach which allows you to create a project and assign multiple repositories to it (at most one SVN repository). The auth is based on individual plugins (we integrated it into our ldap).

We use it for our https://code.vis.ethz.ch coding platform. At the moment there isn't any support for code review but it could easily be added as a plugin.

I can't post screenshots since I don't have enough reputation.


答:
It is professional to Write Maintainable Unit Tests That Will Save You Time And Tears !

There is a misconception that Unit test finds bugs. Well that is simply NOT true for all cases. Unit testing is not about finding bugs or detect regressions. It is by definition, examine each unit of your code separately. But when your application runs for real, all those units have to work together, and the whole is more complex and subtle than the sum of its independently-tested parts.

Thus, the goal of Unit testing (within the TDD process) is about designing software components robustly.

Edit: There is one exception where unit tests do actually detect bugs. It’s when you’re refactoring, or restructuring a unit’s code but without meaning to change its behaviour. In this case, unit tests can often tell you if the unit’s behaviour has changed.


问:
Why was the percent sign (%) chosen as the format specifier for the printf family of functions?
Everyone knows that, at least in C, you use the printf family of functions to print a formatted string. And these functions use a percent sign (%) to indicate the beginning of a format specifier. For example, %d means to print an int, and %u means to print an unsigned int. If you're unfamiliar with how the printf function and format placeholders work, or simply need a refresher, the Wikipedia article is a good place to start.

My question is, is there a particularly compelling reason why this was originally or should be chosen in the future as the format specifier?

Obviously the decision was made a long time ago (very likely for a predecessor of even the C language), and it's been more or less "standard" ever since then (not only in C, but also in a vast array of other languages that have adopted its syntax to varying degrees), so it's far too late to ever change. But I'm still curious if anyone has any insight on why this choice might have been made in the first place, and whether it still makes sense as the choice if one is designing a new language with similar functionality.

For example, with C# (and the other family of .NET languages), Microsoft made a slightly different decision regarding the operation of the string formatting functions. Although some degree of type safety can be enforced there (unlike with the implementation of printf in C), and therefore it is unnecessary to include an indication of the type of the corresponding parameter, they decided to use zero-indexed pairs of curly braces ({}) as format specifiers, like so:

string output = String.Format("In {0}, the temperature is {1} degrees Celsius.",
                              "Texas", 37);
Console.WriteLine(output);

// Output:
//     In Texas, the temperature is 37 degrees Celsius.
```

The documentation for the String.Format method contains more information, as does this article on composite formatting in general, but the exact details are rather unimportant. The point is simply that they abandoned the long-standing practice of using % to indicate the beginning of a format specifier. The C language could just have easily used {d} and {u}, but it didn't. Anyone have any thoughts on why, whether this decision makes sense in retrospect, and whether new implementations should follow it?

Obviously there's no character that could be chosen that wouldn't have to be escapable so that it could be included in the string itself, but that problem is quite well solved already by just using two of them. What other considerations are relevant?

答:
The Wikipedia entry doesn't contain much historical information, not specific to printf, but to escape characters in general.

http://en.wikipedia.org/wiki/Escape_character

Early reference to the term "escape character" is found in Bob Bemer's
  IBM technical publications. Apparently, it is he who invented this
  mechanism, during his work on the ASCII character set.

My guess is: The backslash was already used for string literals and another character was needed for the format strings. Most likely they chose the character with the assumed least frequency of normal usage and occurrence.

BTW, another related article is linked there with a term I've nether heard before:

http://en.wikipedia.org/wiki/Leaning_toothpick_syndrome

The article for printf has some more info snippets, but not about the reasons.

http://en.wikipedia.org/wiki/Printf

C's variadic printf has its origins in BCPL's writef function.

OwnerDisplayName: Cody Gray

OwnerDisplayName: Secure