答:
Is it possible to create [a Single Page Application] that doesn't rely on JavaScript, without being difficult, or full of "hacks"?

Yes, you can…

If the definition of SPA is that you have only one point of entry for your web application, then you can definitely create an SPA without Javascript.

Unfortunately you'll only have one page relying on complicated postbacks.

I'm under the impression, and I agree with it, that it's bad to create a web application requiring JavaScript to function properly.

Why are you under such impression, really?

You might want to have a look at your server stats and see how many users have Javascript disabled. There is a pixel service for this as well. I haven't seen any stats on places I've worked at where this is above 1% for several years.

If you're working with sites where disabled javascript/css is a requirement then SPA is probably not the best option for you. I can imagine users with cognitive disability (such as visually impaired users) or anyone with a screen reader will have a difficult time navigating an SPA site.


问:
Is it a problem to have different styles of HTML coding within team?
I with 2 other friends are new to web development. We are learning HTML, CSS, Javascript and are creating simple websites to get a feel of different things. And as HTML is only a markup and not a programming language we have very different styles evolving. I mean whenever we look at each other's code, we tend to put a good amount of time in understanding why the other one does that.

Now we want to build a larger website together and my question is- Is that a problem having very different styles in a team for web development(specifically)?

答:
There is only one place where server-side and all client-side concerns meet and that is the HTML. It should be the most pristine, cleanest, most consistent and coal-crushed-to-diamonds-in-mere-minutes anally retentive portion of every web app.

Imagine grabbing and restructuring a string from innerHTML. How much easier is it when you know it will always be double-quotes on every attribute and every singular-style element will have that closing '/' ? When it's a late-night and you're trying to walk through some code how helpful is it to be able to easily separate ids and classes that have an underscore or dash convention from traditionally camel-cased property and var names?

And really, how much easier is it to simply read HTML when everything follows the same conventions.

It's not hard to keep HTML clean and consistent and there are too many wins not to. Server-side devs that treat the HTML as a disposable means to an end aren't understanding the web app from a holistic perspective IMO. And their code is usually sloppy too.

ContentLicense: CC BY-SA 3.0


问:
Writing the minimum code to pass a unit test - without cheating!
When doing TDD and writing a unit test, how does one resist the urge to "cheat" when writing the first iteration of "implementation" code that you're testing?

For example:

Let's I need to calculate the Factorial of a number.  I start with a unit test (using MSTest) something like:

```<code>[TestClass]
public class CalculateFactorialTests
{
    [TestMethod]
    public void CalculateFactorial_5_input_returns_120()
    {
        // Arrange
        var myMath = new MyMath();
        // Act
        long output = myMath.CalculateFactorial(5);
        // Assert
        Assert.AreEqual(120, output);
    }
}
</code>```

I run this code, and it fails since the CalculateFactorial method doesn't even exist.  So, I now write the first iteration of the code to implement the method under test, writing the minimum code required to pass the test.

The thing is, I'm continually tempted to write the following:

```<code>public class MyMath
{
    public long CalculateFactorial(long input)
    {
        return 120;
    }
}
</code>```

This is, technically, correct in that it really is the minimum code required to make that specific test pass (go green), although it's clearly a "cheat" since it really doesn't even attempt to perform the function of calculating a factorial.  Of course, now the refactoring part becomes an exercise in "writing the correct functionality" rather than a true refactoring of the implementation.  Obviously, adding additional tests with different parameters will fail and force a refactoring, but you have to start with that one test.

So, my question is, how do you get that balance between "writing the minimum code to pass the test" whilst still keeping it functional and in the spirit of what you're actually trying to achieve?

答:
If you are able to "cheat" in such a way, it suggests that your unit tests are flawed.

Rather than testing the factorial method with a single value, test it was a range of values. Data-driven testing can help here.

View your unit tests as a manifestation of the requirements - they must collectively define the behaviour of the method which they test. (This is known as behaviour driven development - its the future ;-))

So ask yourself - if someone were to change the implementation to something incorrect, would your tests still pass or would they say "hang on a minute!"?

Bearing that in mind, if your only test was the one in your question, then technically, the corresponding implementation is correct. The problem is then viewed as poorly-defined requirements.

ContentLicense: CC BY-SA 2.5


问:
Why are SQL databases still used with ORM?
ORMs and persistence ignorance make perfect sense: if I am programming in a language, then I want to use the language's native implementation of objects and data structures to drive my program. I shouldn't need to worry about SQL or a database, and I always thought that inline SQL strings in a program was very cumbersome.

Why is SQL still used as a backend? Why doesn't the ORM just persist objects to XML or a binary file(s) and avoid all the overheads and difficulties of administering a database server?

答:
An ORM is an Object Relational Mapper, and as almost every relational database uses SQL there is not going to be much of a change as its really your only option.

If we were to take the point about persistence abstraction and go down that avenue rather than the high level ORM concept then yes it would be good to have a persistence abstraction which just lets you save your objects/models to a given data store, be it MySQL, MongoDB, FlatFile etc. The problem for this is that relational databases support relational data, so you can setup relationships between your objects, however most NoSQL based solutions are more concerned with persisting your object as a whole rather than normalizing it into smaller relational tables.

Anyway the main point im getting at is that ORMs were designed with SQL databases in mind, most NoSQL style databases do not use relationships (maybe graph dbs in a way) so an ORM without a relational database would be redundant.


答:
if I am programming in a language, then I want to use the language's
  native implementation of objects and data structures to drive my
  program

yes, exactly this. Only trouble is when dealing with data stored in a database, the language's native implementation is SQL. So technically if you're not using SQL when working with databases, you're doing it wrong.

I imagine the problem here is that you just don't get tool assistance like intellisense when embedding SQL into your code. My advice then is to use stored procedures, so your SQL is wrapped up in a nice API that the DB exposes to you (a bit like implementing a web service). Then you can use your ORM as a client access technology to call those sprocs with the added benefit of better decoupling, better security, and often better performance.

Title: Why are SQL databases still used with ORM?

Body:
ORMs and persistence ignorance make perfect sense: if I am programming in a language, then I want to use the language's native implementation of objects and data structures to drive my program. I shouldn't need to worry about SQL or a database, and I always thought that inline SQL strings in a program was very cumbersome.

Why is SQL still used as a backend? Why doesn't the ORM just persist objects to XML or a binary file(s) and avoid all the overheads and difficulties of administering a database server?


问:
Is there any way around the field-of-use restrictions in Java?
Current field-of-use restrictions defined in "Oracle Binary Code License Agreement for the Java SE Platform Products" prohibit its use in embedded systems.

"General Purpose Desktop Computers and Servers" means computers, including desktop and laptop computers, or servers, used for general computing functions under end user control (such as but not specifically limited to email, general purpose Internet browsing, and office suite productivity tools). The use of Software in systems and solutions that provide dedicated functionality (other than as mentioned above) or designed for use in embedded or function-specific software applications... are excluded from this definition and not licensed under this Agreement.

Do these restrictions also apply to OpenJDK and other possible implementations? Is the only way to use Java in such an environment to acquire a separate license from Oracle?

答:
OpenJDK is the official open source Reference Implementation (RI) for Java.  Oracle's Java (the one that most people use) is a thin wrapper around that open source code with a Java(tm) label thrown over the top of it (confusing huh!).

There's no way around the restriction if you are using Oracle's Java but there is nothing stopping you from using OpenJDK directly (assuming you can build or find the appropriate binary).


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

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

My question is:

How you interact with such thousands lines of code?

EDIT:

Any shortcut will be great!

答: Whatever you do write up as much as you can as you go along so no-one ever ends up in the same position as you have.</p>


问:
Empty interface to combine multiple interfaces
Suppose you have two interfaces:

```<code>interface Readable {
    public void read();
}

interface Writable {
    public void write();
}
</code>```

In some cases the implementing objects can only support one of these but in a lot of cases the implementations will support both interfaces. The people who use the interfaces will have to do something like:

```<code>// can't write to it without explicit casting
Readable myObject = new MyObject();

// can't read from it without explicit casting
Writable myObject = new MyObject();

// tight coupling to actual implementation
MyObject myObject = new MyObject();
</code>```

None of these options is terribly convenient, even more so when considering that you want this as a method parameter.

One solution would be to declare a wrapping interface:

```<code>interface TheWholeShabam extends Readable, Writable {}
</code>```

But this has one specific problem: all implementations that support both Readable and Writable have to implement TheWholeShabam if they want to be compatible with people using the interface. Even though it offers nothing apart from the guaranteed presence of both interfaces.

Is there a clean solution to this problem or should I go for the wrapper interface?

UPDATE

It is in fact often necessary to have an object that is both readable and writable so simply seperating the concerns in the arguments is not always a clean solution.

UPDATE2

(extracted as answer so it's easier to comment on)

UPDATE3

Please beware that the primary usecase for this is not streams (although they too must be supported). Streams make a very specific distinction between input and output and there is a clear separation of responsibilities. Rather, think of something like a bytebuffer where you need one object you can write to and read from, one object that has a very specific state attached to it. These objects exist because they are very useful for some things like asynchronous I/O, encodings,...

UPDATE4

One of the first things I tried was the same as the suggestion given below (check the accepted answer) but it proved to be too fragile.

Suppose you have a class that has to return the type:

```<code>public <RW extends Readable & Writable> RW getItAll();
</code>```

If you call this method, the generic RW is determined by the variable receiving the object, so you need a way to describe this var.

```<code>MyObject myObject = someInstance.getItAll();
</code>```

This would work but once again ties it to an implementation and may actually throw classcastexceptions at runtime (depending on what is returned).

Additionally if you want a class variable of the type RW, you need to define the generic at the class level.

答:
None of the answers currently address the situation when you don't need a readable or writable but both. You need guarantees that when writing to A, you can read that data back from A, not write to A and read from B and just hope they are actually the same object. Usecases are plentiful, for example everywhere you would use a ByteBuffer.

Anyway, I've nearly finished the module I'm working on and currently I have opted for the wrapper interface:

```<code>interface Container extends Readable, Writable {}
</code>```

Now you can at least do:

```<code>Container container = IOUtils.newContainer();
container.write("something".getBytes());
System.out.println(IOUtils.toString(container));
</code>```

My own implementations of container (currently 3) all implement Container as opposed to the separate interfaces but should someone forget this in an implementation, IOUtils provides a utility method:

```<code>Readable myReadable = ...;
// assuming myReadable is also Writable you can do this:
Container container = IOUtils.toByteContainer(myReadable);
</code>```

I know this isn't the optimal solution but it's still the best way out at the moment because Container still is a fairly large usecase.

Body:
None of the answers currently address the situation when you don't need a readable or writable but both. You need guarantees that when writing to A, you can read that data back from A, not write to A and read from B and just hope they are actually the same object. Usecases are plentiful, for example everywhere you would use a ByteBuffer.

Anyway, I've nearly finished the module I'm working on and currently I have opted for the wrapper interface:

interface Container extends Readable, Writable {}

Now you can at least do:

Container container = IOUtils.newContainer();
container.write("something".getBytes());
System.out.println(IOUtils.toString(container));

My own implementations of container (currently 3) all implement Container as opposed to the separate interfaces but should someone forget this in an implementation, IOUtils provides a utility method:

Readable myReadable = ...;
// assuming myReadable is also Writable you can do this:
Container container = IOUtils.toByteContainer(myReadable);

I know this isn't the optimal solution but it's still the best way out at the moment because Container still is a fairly large usecase.


答:
No, these restrictions do not apply to OpenJDK. They are only for the Oracle-branded binary installation packages of the JDK and JRE (which I think still include some code that is not in OpenJDK).

If you use OpenJDK, you are only bound by the OpenJDK's license, which is "GPL+linking exception".

Title: Is there any way around the field-of-use restrictions in Java?

Body:
Current field-of-use restrictions defined in "Oracle Binary Code License Agreement for the Java SE Platform Products" prohibit its use in embedded systems.

"General Purpose Desktop Computers and Servers" means computers, including desktop and laptop computers, or servers, used for general computing functions under end user control (such as but not specifically limited to email, general purpose Internet browsing, and office suite productivity tools). The use of Software in systems and solutions that provide dedicated functionality (other than as mentioned above) or designed for use in embedded or function-specific software applications... are excluded from this definition and not licensed under this Agreement.

Do these restrictions also apply to OpenJDK and other possible implementations? Is the only way to use Java in such an environment to acquire a separate license from Oracle?


问:
Rails: Law of Demeter Confusion
I am reading a book called Rails AntiPatterns and they talk about using delegation to to avoid breaking the Law of Demeter. Here is their prime example:

They believe that calling something like this in the controller is bad (and I agree)

```<code>@street = @invoice.customer.address.street
</code>```

Their proposed solution is to do the following:

```<code>class Customer

    has_one :address
    belongs_to :invoice

    def street
        address.street
    end
end

class Invoice

    has_one :customer

    def customer_street
        customer.street
    end
end

@street = @invoice.customer_street
</code>```

They are stating that since you only use one dot, you are not breaking the Law of Demeter here. I think this is incorrect, because you are still going through customer to go through address to get the invoice's street. I primarily got this idea from a blog post I read:

http://www.dan-manges.com/blog/37

In the blog post the prime example is

```<code>class Wallet
  attr_accessor :cash
end
class Customer
  has_one :wallet

  # attribute delegation
  def cash
    @wallet.cash
  end
end

class Paperboy
  def collect_money(customer, due_amount)
    if customer.cash < due_ammount
      raise InsufficientFundsError
    else
      customer.cash -= due_amount
      @collected_amount += due_amount
    end
  end
end
</code>```

The blog post states that although there is only one dot customer.cash instead of customer.wallet.cash, this code still violates the Law of Demeter.

Now in the Paperboy collect_money method, we don't have two dots, we
  just have one in "customer.cash". Has this delegation solved our
  problem? Not at all. If we look at the behavior, a paperboy is still
  reaching directly into a customer's wallet to get cash out.

EDIT

I completely understand and agree that this is still a violation and I need to create a method in Wallet called withdraw that handles the payment for me and that I should call that method inside the Customer class. What I don't get is that according to this process, my first example still violates the Law of Demeter because Invoice is still reaching directly into Customer to get the street.

Can somebody help me clear the confusion. I have been searching for the past 2 days trying to let this topic sink in, but it is still confusing.

答:
Your first example does not violate the law of Demeter. Yes, with the code as it stands, saying @invoice.customer_street does happen to get the same value that a hypothetical @invoice.customer.address.street would, but at each step of the traversal, the value returned is decided by the object being asked - it's not that "the paperboy reaches into the customer's wallet", it's that "the paperboy asks the customer for cash, and the customer happens to get the cash from their wallet".

When you say @invoice.customer.address.street, you're assuming knowledge of customer and address internals - this is the bad thing. When you say @invoice.customer_street, you are asking the invoice, "hey, I'd like the customer's street, you decide how you get it". The customer then says to its address, "hey I'd like your street, you decide how you get it".

The thrust of Demeter is not 'you cannot ever know values from objects far away in the graph from you"; it is instead 'you yourself are not to traverse far along the object graph in order to obtain values'.

I agree this may seem like a subtle distinction, but consider this: in Demeter-compliant code, how much code needs to change when the internal representation of an address changes? What about in non-Demeter-compliant code?

Title: Rails: Law of Demeter Confusion


问:
Should I close database connections after use in PHP?
I wonder if I should close any unnecessary database connection inside of my PHP scripts.

I am aware of the fact that database connections are closed implicitly when the block stops executing and 'manually' closing the connections could kinda bloat the codebase with unnecessary code.

But shouldn't I do so in order to make by code as readable and as easy understandable as possible, while also preventing several possible issues during run time?

Also, if I would do, would it be enough to unset() my database object?

答:
For the purpose of safe coding, you should always close database connections explicitly to make sure that the code was able to close itself gracefully and to prevent any other objects from reusing the same connection after you are done with it.

Using unset is the same as leaving the database connection open, as you're relying on the garbage collector to clean up after the variable as opposed to asking the connection to gracefully close the connection after you're done with it. Though as mentioned by CodeCaster below, doing so is acceptable since the garbage collector makes sure that the connections are closed.

A useful example, lets say you're eating lunch at a cafeteria somewhere. After eating, you have two choice, throw your left overs in the trash then return the plate/tray to its rightful place(thats cleaning up after yourself). And the other is just leaving your mess on the table and wait for someone else(the garbage collector) to clean it up for you.

If you clean it up yourself, you're sure that your mess is cleaned up. But if you rely on the garbage collector, right before the garbage collector cleans up your mess, what if some weird stalker decides to use your used utensils to aid them in their nightly fantasies about you, then return them back to the cafeteria just in time for the garbage collector to clean up your mess. Stuff like that can happen.

EDIT: Corrected my mistake about garbage collectors.


问:
How to refactor when all your development is on branches?
At my company, all of our development (bug fixes and new features) is done on separate branches. When it's complete, we send it off to QA who tests it on that branch, and when they give us the green light, we merge it into our main branch. This could take anywhere between a day and a year.

If we try to squeeze any refactoring in on a branch, we don't know how long it will be "out" for, so it can cause many conflicts when it's merged back in.

For example, let's say I want to rename a function because the feature I'm working on is making heavy use of this function, and I found that its name doesn't really fit its purpose (again, this is just an example). So I go around and find every usage of this function, and rename them all to its new name, and everything works perfectly, so I send it off to QA.

Meanwhile, new development is happening, and my renamed function doesn't exist on any of the branches that are being forked off main. When my issue gets merged back in, they're all going to break.

Is there any way of dealing with this?

It's not like management will ever approve a refactor-only issue so it has to be squeezed in with other work. It can't be developed directly on main because all changes have to go through QA and no one wants to be the jerk that broke main so that he could do a little bit of non-essential refactoring.

答:
Usually I am developing refactored version in "parallel" with current, i.e. in same codebase, but not referencing it from core application. And when new solution is done and tested, I am starting actual refactoring.

Example 1. Assume I have Thing, let it be either function, interface, module, or whatever. And I want to refactor it. I am creating Thing2 in same codebase, it is refactored version of Thing. When it is done and tested, I am refactoring everything that references Thing, to replace it with Thing2. Usually this step takes relatively small amount of time.

If actual refactoring takes too much time to keep in sync without screwing team, I am taking all relevant features, and refactoring them in parallel, too.

Example 2. I have new rendering backend, that is refactored version of old one. But it is not compatible with old rendering frontend. Thus, I need to refactor frontend. And again: in same codebase. When everything is done, I am just changing class of frontend instance, ideally it will take one short commit.

Yes, recursively one may come to conclusion that everything must be done in parallel. But this usually happens when there is too much coupling in codebase, or it is changing too fast.

Finally, when new code integrated and works well, old features may be removed from codebase, and new features may be renamed to get old names.

Generally, idea is to prepare new features in parallel and switch to using them by one small step.

John Carmack uses this (or at least similiar) approach, perhaps his blog post explains it better: (link)


问:
Is ZeroMQ a good choice to make a Python app and a C# managed assembly work together?
I have a task that involves talking to a .NET-based API (namely AutoCAD) to retrieve data, send commands, and react to events.

I want to separate the API operations and the proper program logic (largely already implemented in Python) by using natural tools for both: a C# DLL for the former and a Python app for the latter.

To connect these two pieces, I began exchanging JSON in ZeroMQ messages. I'm at early development stages but having recently discovered that ZeroMQ does not guarantee message delivery/order, I have reservations about whether this is a feasible way to go. Right now my app is a very basic REQ/REP pair and I plan to handle reacting to events and executing different commands by adding some sort of 'recipient-function' field to my message format.

The reason that I want to use ZMQ is that I might be able to scale the software into a larger, multi-user, distributed solution sometime.

I am a lay programmer so I would ask for your advice about this architecture. Should I just go ahead with it and plan to deal with message reliability/ordering when problems appear? Should I consider developing some kind of a REST wrapper around ZMQ?

答: ZeroMQ probably wouldn't be my first choice for this, but it should be doable.  The ZeroMQ manual has a section on reliability with REQ/REP sockets is there something you need beyond that?  As far as ordering goes would a simple 1 up counter work?  It would work more or less like TCP does if you receive a message before its time hold on to it and wait for the earlier message and perhaps send a response asking for a repeat of the missing message.</p>


问:
Is programming in layers real?
I am fairly new in product development and I am trying to work over a product. The problem that I have realized is that people draw diagrams and charts showing different modules and layers.

But as I am working alone (I am my own team) I got a bit confused about the interaction I am facing in the development within the programs and I am wondering whether developing a product in modules is real or not?

Maybe I am not a great programmer, but I see no boundaries when data start to travel from frontend to backend.

答:
The "layers" that we describe when we describe software systems are abstract concepts. To the computer, all it gets to see is a featureless stream of one opcode after another, no matter which layer, which class or which method it originally came from. In this sense, they are not "real" at all.

However, layers (and classes and methods) are useful for programmers to ease thinking about the system. By voluntarily restricting ourselves to think about the system only on one level of description at a time, and to think about an operation only in terms of its input and output rather than its internal workings, we increase our ability to understand the relevant parts when adding functionality or making a change.

This is initially quite counter-intuitive, and under-taught in formal education. But I assure you that judicious use of abstraction is the only thing that makes software development "in the large" possible at all for people who aren't autistic savants.

Title: Is programming in layers real?


问:
How much freedom should a programmer have in choosing a language and framework?
I started working at a company that is primarily C# oriented. We have a few people who like Java and JRuby, but a majority of programmers here like C#. I was hired because I have a lot of experience building web applications and because I lean towards newer technologies like JRuby on Rails or nodejs.

I have recently started on a project building a web application with a focus on getting a lot of stuff done in a short amount of time. The software lead has dictated that I use mvc4 instead of rails. That might be OK, except I don't know mvc4, I don't know C# and I am the only one responsible for creating the web application server and front-end UI.

Wouldn't it make sense to use a framework that I already know extremely well (Rails) instead of using mvc4? The reasoning behind the decision was that the tech lead doesn't know Jruby/rails and there would be no way to reuse the code.

Counter arguments:

He won't be contributing to the code and is, frankly, not needed on

this project. So, it doesn't really matter if he knows JRuby/rails or not.

We actually can reuse the code since we have a lot of java apps that
JRuby can pull code from and vice-versa. In fact, he has dedicated
some resources to convert a Java library to C#, instead of just
running the Java library on the JRuby on Rails app. All because he
doesn't like Java or JRuby

I have built many web applications, but using something unfamiliar is causing some spin-up and I am unable to build an awesome application in as short of a time as I'm used to. This would be fine; learning new technologies is important in this field. The problem is, for this project we need to get a lot done fast.

At what point should a developer be allowed to choose his tools? Is this dependent on the company? Does my company suck or is this considered normal? Do greener pastures exist? Am I looking at this the wrong way?

答:
Maybe they're not satisfied with the way everyone is using MVC in the .NET environment. There could be too much treating it like webforms. This is no different when someone with a procedural background starts out in OOP, put everything in one big class and goes on with business as usual.

This first project is not the ideal situation because they want this done so quickly. Get up to speed on .NET as much as possible and start cranking out features as fast as you can. You're not going to like the way you're doing things, just try to keep in mind you'll start to refactor this stuff and apply your skills in another language.

Hopefully, your way of using MVC4 (assuming everyone else there is not doing it quite right) in a more Ruby-Style will catch on and break everyone away from the Webforms mentality.


答:
In my honest opinion, one of the things that separates good developers from great is their ability to adapt to new technology. We are living in a fast-paced world where today's top technology will become obsolete tomorrow. Hence, a developer that is unwilling to adapt is of limited use to the company.
This would be fine, if not for a little fact that finding and hiring good people is really really difficult to do and when a company finds their gem, they are planning for the long run.

I have seen companies hiring out of their technology scope and they do it for exact same reason. They want to get hands on great developers, even if that means waiting for them to adapt to new technology.

Now to your situation. As a new guy in the group, I would be very careful as to what I say and don't say to my superiors. Sure, you will get away with a lot based on the assumption that you are still in a process of adapting to your new environment. However, undermining authority and stubborn perseverance at your preferred technology will only make your superiors think they did a mistake hiring you and that you are not willing to leave your comfort zone.

What you will pick is up to you, but I would suggest you trying to learn new technology. It won't hurt, I promise.

Title: How much freedom should a programmer have in choosing a language and framework?

Body:
I started working at a company that is primarily C# oriented. We have a few people who like Java and JRuby, but a majority of programmers here like C#. I was hired because I have a lot of experience building web applications and because I lean towards newer technologies like JRuby on Rails or nodejs.

I have recently started on a project building a web application with a focus on getting a lot of stuff done in a short amount of time. The software lead has dictated that I use mvc4 instead of rails. That might be OK, except I don't know mvc4, I don't know C# and I am the only one responsible for creating the web application server and front-end UI.

Wouldn't it make sense to use a framework that I already know extremely well (Rails) instead of using mvc4? The reasoning behind the decision was that the tech lead doesn't know Jruby/rails and there would be no way to reuse the code.

Counter arguments:

He won't be contributing to the code and is, frankly, not needed on

this project. So, it doesn't really matter if he knows JRuby/rails or not.

We actually can reuse the code since we have a lot of java apps that
JRuby can pull code from and vice-versa. In fact, he has dedicated
some resources to convert a Java library to C#, instead of just
running the Java library on the JRuby on Rails app. All because he
doesn't like Java or JRuby

I have built many web applications, but using something unfamiliar is causing some spin-up and I am unable to build an awesome application in as short of a time as I'm used to. This would be fine; learning new technologies is important in this field. The problem is, for this project we need to get a lot done fast.

At what point should a developer be allowed to choose his tools? Is this dependent on the company? Does my company suck or is this considered normal? Do greener pastures exist? Am I looking at this the wrong way?


问:
Why I'm not selected in an interview?
I'm working in development for 4 years, and 3.5 in PHP - why I don't seem to be able to be selected in an interview.

I want to know what special things the interviewer wants to see in candidates - for senior PHP developer roles.

Interviewer asks me 10 questions and I'm able to answer only 5. Does selection depend on these things? It doesn't mean that I can't solve the problem, I can google the question, I can ask on forums. Why don't they understand that a man can't remember all the answers for each and every question? Especially programming ones.

Please advise.

答:
I've said it before. I'll say it again.

A job interview is a competition, not a pass-fail test.

The reason you aren't getting the job is that another candidate impressed the employer more than you did. If you got 5 questions right, perhaps someone else got 6 or more.

The fact that you can Google answers or get them from SO is irrelevant as I discussed in more detail in my blog article Why "I'd just Google it" is not an acceptable interview answer.

Title: Why I'm not selected in an interview?


答:
Adding my two cents...

You’re your own team; you’re working alone on that product, one piece of advice: keep it simple, stupid!

In your case, I don’t think you need to abstract things creating layers or modules, you’ll only gain complexity.

Things would obviously not be the same if you were to work within a 10 guy’s team where some of them would be involved on business rules development and the other ones on the UI. In that situation, separating concerns might be a good idea.
Just start simple and write unit tests to protect you from regression.

Why would you have to get things more complicated than they need to? You might not gonna need it at all!

Title: Is programming in layers real?

Body:
I am fairly new in product development and I am trying to work over a product. The problem that I have realized is that people draw diagrams and charts showing different modules and layers.

But as I am working alone (I am my own team) I got a bit confused about the interaction I am facing in the development within the programs and I am wondering whether developing a product in modules is real or not?

Maybe I am not a great programmer, but I see no boundaries when data start to travel from frontend to backend.


答:
The Biggest Expense in Software is in the Maintenance of it

I read that the biggest expense (80%) is in the maintenance of software.  The initial development is only 20% of the total cost of development.

I read a case about a developer who developed code and comments in his native language (not English) and when the other team members went to enhance and maintain the code, it was next to impossible because the language (not any programming language) was foreign to them.

Similarly, if you develop code in a programming language of your own choice, it would be difficult for other team members to maintain.

Solution: Pair Programming

Consider asking your employers to pair you with somebody else that does know the required programming language and you can work together.  You can learn from each other, and if either of you leave the company, the other one would know the code.

Wikipedia Article on "Pair Programming":
http://en.wikipedia.org/wiki/Pair_programming


问:
Rails/Node.js interaction
I and my co-worker are developing a web application with rails and node.js and we can't reach a consensus regarding a particular architectural decision.

Our setup is basically a rails server working with node.js and redis, when a client makes a http request to our rails API in some cases our rails application posts the response to a redis database and then node.js transmits the response via websocket.

Our disagreement occurs in the following point: my co-worker thinks that using node.js to send data to clients is somewhat business logic and should be inside the model, so in the first code he wrote he used commands of broadcast in callbacks and other places of the model, he's convinced that the models are the best place for the interaction between rails and node.

I on the other hand think that using node.js belongs to the runtime realm, my take is that the broadcast commands and other node.js interactions should be in the controller and should only be used in a model if passed through a well defined interface, just like the situation when a model needs to access the current user of a session.

At this point we're tired of arguing over this same thing and our discussion consists in us repeating to ourselves our same opinions over and over. Could anyone, preferably with experience in the same setup, give us an unambiguous response saying which solution is more adequate and why it is?

答:
Seeing your clarification, and since you want developers' opinions, here's my $0.02.  I would call Announce from inside your controllers, for two reasons. First, I tend to see ActiveRecord callbacks as being a kind of "implicit"/"passive" calling of an action.  ActiveRecord makes sure to run those callbacks for you and -- unless they break -- you don't really pay much attention to them again. You don't have to call them manually; they tend to minor, routine sorts of matters.

This working assumption I've always had leads into the second reason for me: returning a response client-side is an "active", realtime process, and by rights should be something explicitly invoked and viewable in the more "active" side of your codebase (viz., the controllers).  Returning responses back to a browser (whether via Rails, Node, &c.) are more of a controller's responsibility, and the Rails framework is geared toward that kind of setup.

Title: Rails/Node.js interaction


问:
How to refactor an OO program into a functional one?
I'm having difficulty finding resources on how to write programs in a functional style. The most advanced topic I could find discussed online was using structural typing to cut down on class hierarchies; most just deal with how to use map/fold/reduce/etc to replace imperative loops.

What I would really like to find is an in-depth discussion of an OOP implementation of a non-trivial program, its limitations, and how to refactor it in a functional style. Not just an algorithm or a data structure, but something with several different roles and aspects - a video game perhaps. By the way I did read Real-World Functional Programming by Tomas Petricek, but I'm left wanting more.

答:
I think this series of articles is exactly what you want:

Purely Functional Retrogames

http://prog21.dadgum.com/23.html Part 1

http://prog21.dadgum.com/24.html Part 2

http://prog21.dadgum.com/25.html Part 3

http://prog21.dadgum.com/26.html Part 4

http://prog21.dadgum.com/37.html Follow-up

The summary is:

The author suggests a main loop with side effects (side effects must happen somewhere, right?) and most functions return small immutable records detailing how they changed the state of the game.

Of course when writing a real-world program you will mix and match several programming styles, using each one where it helps most. However it's a good learning experience to try writing a program in the most functional/immutable way and also writing it in the most spaghetti way, using only global variables :-) (do it as an experiment, not in production, please)


问:
Configurable tables in SQL database
I have the following tables in my database:

Configuration Table:

```<code>======================================
Start_Range | End Range | Config_id
   10       |    15     |    1
======================================
</code>```

Available_UserIDs

```<code>==========================
 ID | UserID | Used_YN   |
  1 |   10   |    t      |
  1 |   11   |    f      |
  1 |   12   |    f      |
  1 |   13   |    f      |
  1 |   14   |    f      |
  1 |   15   |    f      |
==========================

Users
    ==========================
     UserId | FName | LName  |
        10  |  John |  Doe   |
    ==========================
</code>```

This is used in a reservation system of sorts... which lets an administrator specify a range of numbers that will be assigned to users in the configuration table. Once the range has been defined, the system then populates the Available_userIDs table with all the numbers in between the range, and sets the Used_YN flag to false.

As users sign up, they grab the next user_id number that's not in use... and
reserve it. Then the system adds a record to the Users table.

Once the administrator has specified a range, it is possible that they can change it. For example, they can start with 10-15... and then when the range is used up, they should be able to specify another range like 16 - 99.

I've put a unique constraint on the Available_UserIDs table, as well as on the Users table - to ensure that UserIds can't be duplicated.

What's the best way to prevent the administrators from using a range that's already in use? I thought of the following options:

-- Check either the Users table to see if the start range or ending range numbers are being used. If they are, assume that all the numbers in between are in use too, and reject the range.

-- Let them specify whatever they want, try to populate the Available_UserIDs table. If there are duplicates, just ignore that specific error message from the database and continue on.

How do I find gaps in the number ranges? For example, if they specify 10-15, and then 20-25, it'd be nice to be able to somehow suggest on my web page that 16-19 is currently available.

I found the article How do I find a "gap" in running counter with SQL?, but it only seems to return the first available number... so in my example above, it would only return the number 16.

I'm sure there's a simpler way to do things that I'm overlooking!

答:
What's the best way to prevent the admins from using a range that's already in use?

Maybe you could put constraints on the config table? The first one would be to have a unique constraint on start_range and end_range. This would prevent one range from having the same start or end as another. It doesn't prevent you from having a range that is a super-range or sub-range of another range. That might be something better checked using an ON INSERT trigger, where you might have to call a procedure or run a query to ensure that the new range is not a super/sub -range of an existing range.

Title: Configurable tables in SQL database


答:
If new users always get the first available user ID, you don't really need the admin to specify the start of a new range. Just have the admin define the new range size, take the first user ID that hasn't yet been reserved as the start, and add the new range size to that to get the end.

```<code>int range_start = max_reserved + 1;
int range_size = user_defined;
int range_end = range_start + range_size - 1;
</code>```

This would remove the need to identify range gaps, but if it's still desired, use the solution you linked to find the first missing ID, then query for the minimum ID greater than the missing ID. The end of your missing range would the result - 1.

```<code>select min(UserId) - 1 as missing_range_end
from Users
where UserId > $known_missing_id;
</code>```

If you need your admins to be able to specify the range start, before accepting the new range I would run a validation query to make sure the new range does't intersect another:

```<code>select count(*)
from Available_UserIDs
where UserID between $new_range_start and $new_range_end;
</code>```

If you get any results, reject the new range.

Title: Configurable tables in SQL database

Body:
I have the following tables in my database:

Configuration Table:

```<code>======================================
Start_Range | End Range | Config_id
   10       |    15     |    1
======================================
</code>```

Available_UserIDs

```<code>==========================
 ID | UserID | Used_YN   |
  1 |   10   |    t      |
  1 |   11   |    f      |
  1 |   12   |    f      |
  1 |   13   |    f      |
  1 |   14   |    f      |
  1 |   15   |    f      |
==========================

Users
    ==========================
     UserId | FName | LName  |
        10  |  John |  Doe   |
    ==========================
</code>```

This is used in a reservation system of sorts... which lets an administrator specify a range of numbers that will be assigned to users in the configuration table. Once the range has been defined, the system then populates the Available_userIDs table with all the numbers in between the range, and sets the Used_YN flag to false.

As users sign up, they grab the next user_id number that's not in use... and
reserve it. Then the system adds a record to the Users table.

Once the administrator has specified a range, it is possible that they can change it. For example, they can start with 10-15... and then when the range is used up, they should be able to specify another range like 16 - 99.

I've put a unique constraint on the Available_UserIDs table, as well as on the Users table - to ensure that UserIds can't be duplicated.

What's the best way to prevent the administrators from using a range that's already in use? I thought of the following options:

-- Check either the Users table to see if the start range or ending range numbers are being used. If they are, assume that all the numbers in between are in use too, and reject the range.

-- Let them specify whatever they want, try to populate the Available_UserIDs table. If there are duplicates, just ignore that specific error message from the database and continue on.

How do I find gaps in the number ranges? For example, if they specify 10-15, and then 20-25, it'd be nice to be able to somehow suggest on my web page that 16-19 is currently available.

I found the article How do I find a "gap" in running counter with SQL?, but it only seems to return the first available number... so in my example above, it would only return the number 16.

I'm sure there's a simpler way to do things that I'm overlooking!

Body:
If new users always get the first available user ID, you don't really need the admin to specify the start of a new range. Just have the admin define the new range size, take the first user ID that hasn't yet been reserved as the start, and add the new range size to that to get the end.

int range_start = max_reserved + 1;
int range_size = user_defined;
int range_end = range_start + range_size - 1;

This would remove the need to identify range gaps, but if it's still desired, use the solution you linked to find the first missing ID, then query for the minimum ID greater than the missing ID. The end of your missing range would the result - 1.

select min(UserId) - 1 as missing_range_end
from Users
where UserId > $known_missing_id;

If you need your admins to be able to specify the range start, before accepting the new range I would run a validation query to make sure the new range does't intersect another:

select count(*)
from Available_UserIDs
where UserID between $new_range_start and $new_range_end;

If you get any results, reject the new range.


问:
Is MVVM in WPF outdated?
I'm currently trying to get my head round MVVM for WPF - I don't mean get my head round the concept, but around the actual nuts and bolts of doing anything that is further off the beaten track than dumb CRUD.

What I've noticed is that lots of the frameworks, and most/all blog posts are from 'ages' ago.

Is this because it is now old hat and the bloggers have moved onto the Next Big Thing, or just because they've said everything there is to say?

In other words, is there something I'm missing here?

答:
MVVM isn't outdated, but it was overplayed to begin with.  I never liked it and it kept me in WinForms for too long; failing to see the forest for the trees, I threw the baby out with the bathwater.  I get WPF now, and I get the idea of not wanting to mix code with markup, but I prefer the Android style of sticking the markup in one place and dereferencing it with casts in my code (which you can also do in WPF, even though it never got trendy to do so for whatever reason).

That way you gain more fine-grained control and don't have to worry about all the "onchanged" handling everywhere.  I feel this is actually more testable because tests won't always catch it if you miss an "onchanged" event.

You lose a bit of "declarative"-ness, which seems to be a trend these days (e.g. if two widgets are mapped to the same value, in MVVM you can just do that, whereas with imperative code you have to set both individually). But even with MVVM, that only works in the menial case.  If some widget has to display the log of another widget, then you've got to write another handler and another "onchanged" event and so you end up having to stretch the definition of "declarative" to say it is so.

2015 update

WPF MVVM was (r)evolutionary for its time.  As was WPF.  But they both had their warts.  Plain WPF had too much built into it (plus it was built on XML), and was kind of a pain to deal with.  (Really, if WPF had just taken a more "library" approach rather than a "framework" approach, it could have turned into some really cool stuff and the whole tech universe might be entirely different now).  The idea of MVVM was great, but trying to fit an MVVM into WPF was somewhat hacky since 1) C# couldn't really express it without a lot of boilerplate, and 2) WinForms relics like modal popups were still ideologically prevalent but couldn't be easily represented in MVVM.  Thus it all sucked.

That said, it's still the only realistic option on Windows when you need transparency or GPU for LOB apps.

React has of course made MVVM obsolete.  I was disappointed that VS2015 didn't have a native counter to that.  For now we're still stuck using raw WPF (which is OK, but feels old (really feels just as old as winforms now), and doesn't have a ton of built-in functionality (feels like some cool but abandoned project) or with-MVVM, which at this point feels like much overhead for nothing, since even good MVVM (angular 1) has been exposed for its shortcomings.

I'd avoid WPF MVVM.  It's an extra layer, and nobody is caring about it anymore.

Title: Is MVVM in WPF outdated?


问:
TotalPhase Aardvark driver's GPL license
I'm using an SPI host adapter for a project. The Aardvark from TotalPhase. And I did something crazy, I read that EULA license that everyone just clicks through.

The driver installation license includes these bits:

This driver installer package also includes a WIN32 driver that is
entirely based on the libusb-win32 project (release 0.1.10.1).

...

LICENSE:

The software in this package is distributed under the following
licenses:

Driver:   GNU General Public License (GPL)
 Library, Test
Files:    GNU Lesser General Public License (LGPL)

Now, my understanding of of the GPL is that it's sticky and viral. If you include software then the whole project has to be released under the GPL (if you distribute it, you can do whatever you want with in-house projects).

If the driver was like the library, and was licensed under the LGPL, it could be used by my closed source proprietary project, as long as it's source and license was passed along with it. But it's not, it's pure GPL.

If I include this driver in my project and distribute it, am I required to release my project under the GPL?

答:
You can distribute the driver, yes. But you are required to provide the source code, or point to where end-users can get it, including any changes you make to the driver. The driver's license does not affect the rest of your project.

The library can also be used in your project, provided that you also provide source code for it or point to where users can get it, including any changes you've made. You can also link the library to your project, provided that it's possible for an end-user to replace the library with one they've built. Most projects meet this requirement by dynamically linking the library as a DLL or shared object.

This does not affect the license under which you distribute your own software, provided you meet the other requirements.

As always, however, you should consult your attorney.


问:
Finding the lowest average Hamming distance when the order of the strings matter
I have a sequence of binary strings that I want to find a match for among a set of longer sequences of binary strings. A match means that the compared sequence gives the lowest average Hamming distance when all elements in the shorter sequence have been matched against a sequence in one of the longer sets.

Let me try to explain with an example. I have a set of video frames that have been hashed using a perceptual hashing algorithm so that the video frames that look the same has roughly the same hash. I want to match a short video clip against a set of longer videos, to see if the clip is contained in one of these. This means that I need to find out where the sequence of the hashed frames in the short video has the lowest average Hamming distance when compared with the long videos.

The short video is the sub strings Sub1, Sub2 and Sub3, and I want to match them against the hashes of the long videos in Src. The clue here is that the strings need to match in the specific order that they are given in, e.g. that Sub1 always has to match the element before Sub2, and Sub2 always has to match the element before Sub3. In this example it would map thusly: Sub1-Src3, Sub2-Src4 and Sub3-Src5.

So the question is this: is there an algorithm for finding the lowest average Hamming distance when the order of the elements compared matter? The naïve approach to compare the substring sequence to every source string won't cut it of course, so I need something that preferably can match a (much) shorter sub string to a set of million of elements. I have looked at MVP-trees, BK-trees and similar, but everything seems to only take into account one binary string and not a sequence of them.

```<code>Sub1: 100111011111011101
Sub2: 110111000010010100
Sub3: 111111010110101101

Src1: 001011010001010110
Src2: 010111101000111001
Src3: 101111001110011101
Src4: 010111100011010101
Src5: 001111010110111101
Src6: 101011111111010101
</code>```

I have added a calculation of the examples below. (The Hamming distances aren't correct, but it doesn't matter)

```<code>**Run 1.**
dist(Sub1, Src1) = 8
dist(Sub2, Src2) = 10
dist(Sub3, Src3) = 12
average = 10

**Run 2.**
dist(Sub1, Src2) = 10
dist(Sub2, Src3) = 12
dist(Sub3, Src4) = 10
average = 11

**Run 3.**
dist(Sub1, Src3) = 7
dist(Sub2, Src4) = 6
dist(Sub3, Src5) = 10
average = 8

**Run 4.**
dist(Sub1, Src3) = 10
dist(Sub2, Src4) = 4
dist(Sub3, Src5) = 2
average = 5
</code>```

So the winner here is sequence 4 with an average distance of 5.

答:
I don't know any algorithm specific for this problem, but this seems like an optimization problem.

I would suggest branch and bound as a starting point. Combined with a depth-first search to get upper bounds (your lowest hamming distance) for the bounding and you won't need to traverse all edges of the tree. If your accumulated hamming distance on a node is already bigger than the lowest already found from root to a leaf you can stop traversing subtrees of this node.

If you can find a good heuristic to chose what branch to visit next you may further reduce the number of paths to traverse. Something like expand subtrees with lowest accumulated hamming distance yet.

Another thing you could maybe incorporate in the heuristic is the distance to the end. The further you are away from the end of the video the bigger the chance to find a better match thus lower hamming distance. (If I understood your problem correctly)

If you use heuristics with some crossover of depth-first and breadth-first seach, but may be even faster (I didn't made the math yet). The idea would be to traverse strictly from root to leaf but after you are done you decide which subtree you want to expand next from root to tree, not only looking on all the nodes you discovered by the last traversal (in contrast to recursive depth-first search). Thus you may find lower bounds even sooner, but you will need more space for computation as you will most likely have more nodes in the list of unexplored ones and you can summarize the results for subtrees later.


答:
I note that you don't say you were hired as a JRuby or Java programmer.

Here is why you said you were hired: "[B]ecause I have a lot of experience building web applications and because I lean towards newer technologies like JRuby on Rails or nodejs."

In other words, they like your web experience and your willingness to learn new technologies.

Now they're asking you to use your web experience and to learn a new technology.

So the question is, are you going to do that, or not?


问:
Why don't research papers that mention custom software release the source code?
Is there a reason why the source code of software mentioned in research papers is not released? I understand that research papers are more about the general idea of accomplishing something than implementation details, but I don't get why they don't release the code.

For example, this paper ends with:

Results

The human line drawing system is implemented through the Qt framework in C++ using OpenGL, and runs on a 2.00 GHz Intel dual core processor workstation without any additional hardware assistance. We can interactively draw lines while the system synthesizes the new path and texture.

Do they keep the source code closed intentionally because of a monetization they intend to make with it, or because of copyright ?

答:
I'd like to add a few points on the type of code I deal with as a chemometrician (chemist doing data analysis):

People who write data analysis code (like I do) are comparatively few compared to the people who use that code. "Custom code written in house" does not mean that the authors wrote it - could be colleagues' code so the authors cannot publish it.

A separate publication of the code may be planned, and the code's author (or the supervisor) may be concerned that the novelty is lost if the code has been (partially) made public before.

Even if the journal where code publication is intended for doesn't object to the code having been available publicly before, the pure concern of the supervisor (or someone in the IP office) can be enough to stop the publication of the code.

Data analysis code is often tailored to the data. It doesn't make too much sense without the data. (You may argue that the data should be published anyways, but that is a different question and off topic here.)

In any way, at my institute, we archive raw data and data analysis code together with the paper. Default policy is not (yet?) to make them publicly available, but they would certainly be available on request.

(The traditional view on what is reproducibility in chemistry corresponds rather to a description (possibly pseudo-code) of the algorithm than to shipping the actual source code)

Many of my colleagues use interactive tools for their data analysis which do not log the steps of the data analysis. So there is no source code that could be published. The data analyis corresponds less to a programming than to a lab approach: you do things and write down what you do and observe in your lab book.


问:
Structuring an input file
I am in the process of structuring a small program to perform some hydraulic analysis of pipe flow. As I am envisioning this, the program will read an input file, store the input parameters in a suitable way, operate on them and finally output results. I am struggling with how to structure the input file in a sane way; that is, in a way that a human can write it easily and a machine can parse it easily. A sample input file made available to me for a similar program is just a stream of comma-separated numbers that don't make much sense on their own, so that's the scenario I am trying to avoid.

Though I am giving the details of my particular problem, I am more interested in general input-file structuring strategies. Is a stream of comma-separated values my best bet? Would I be better off using some sort of key:value structure? I don't know much about this, so any help will probably put me in a better track than I am now.

答:
I recommend JSON, but here are three good options,

XML - eXtended Markup Language - used on the web, SOAP, preferred by Java programmers everywhere, can be validated, transformed, etc.  data elements are tagged using ... open/close tags, and tags can have attributes.  but considered wordy/verbose by many.

http://www.w3schools.com/xml/xml_examples.asp

JSON - JavasScript Object Notation - basically 'almost' a javascript object.  data elements are (usually) tagged with names, the open/close tags are simple braces

http://json.org/example.html

YAML - yet another markup language, and shares commonality with JSON.  Often expressed as multiple line records

http://www.yaml.org/start.html

CSV or DSV - Comma (or Delimiter) separated value file - you already have, and find it inadequate.  But extremely popular.

Title: Structuring an input file


问:
Stereo images rectification and disparity: which algorithms?
I'm trying to figure out what are currently the two most efficent algorithms that permit, starting from a L/R pair of stereo images created using a traditional camera (so affected by some epipolar lines misalignment), to produce a pair of adjusted images plus their depth information by looking at their disparity.

Actually I've found lots of papers about these two methods, like:

"Computing Rectifying Homographies for Stereo Vision" (Zhang - seems one of the best for rectification only)

"Three-step image rectiﬁcation" (Monasse)

"Rectification and Disparity" (slideshow by Navab)

"A fast area-based stereo matching algorithm" (Di Stefano - seems a bit inaccurate)

"Computing Visual Correspondence with Occlusions via Graph Cuts" (Kolmogorov - this one produces a very good disparity map, with also occlusion informations, but is it efficient?)

"Dense Disparity Map Estimation Respecting Image Discontinuities" (Alvarez - toooo long for a first review)

Anyone could please give me some advices for orienting into this wide topic?

What kind of algorithm/method should I treat first, considering that I'll work on a very simple input: a pair of left and right images and nothing else, no more information (some papers are based on additional, pre-taken, calibration infos)?

Speaking about working implementations, the only interesting results I've seen so far belongs to this piece of software, but only for automatic rectification, not disparity: http://stereo.jpn.org/eng/stphmkr/index.html

I tried the "auto-adjustment" feature and seems really effective. Too bad there is no source code...

答:
Although I don't have any specific expertise in this field, I can make some recommendations with regard to your research.

A Google Scholar search can be a bit daunting at first, but you can begin to filter the results by noting the number of citations a document has. (Citation count often correlates to how authoritative a given article is. Of course, this is only one metric and isn't foolproof: older documents tend to have more citations than newer ones simply because they've had more time to collect them. But it is a good starting point.)
For example, Di Stefano's paper has been cited by over 200 authors, so that might put into question your suggestion that his approach as "inaccurate" (unless that is the consensus of the other citations). On the other hand, the following paper has been cited over 4000 times in the last 10 years and so would probably be a good place to start:

A taxonomy and evaluation of dense two-frame stereo correspondence algorithms (Scharstein, '02)

Look for papers that offer reviews or aggregated summaries of other approaches, such as

Review of stereo vision algorithms: from software to hardware (Lazaros, '08)

I would also recommend looking at some of the standard textbooks in the field, such as:

An Introduction to 3D Computer Vision Techniques and Algorithms (Cyganek, '09)

Multiple View Geometry in Computer Vision (Hartley, '04; may be more dated)


问:
Applying DDD principles in a RESTish web service
I am developing an RESTish web service. I think I got the idea of the difference between aggregation and composition. Aggregation does not enforce lifecycle/scope on the objects it references. Composition does enforce lifecycle/scope on the objects it contain/own.

If I delete a composite object then all the objects it contain/own are deleted as well, while the deleting an aggregate root does not delete referenced objects.

1)
If it is true that deleting aggregate roots does not necessary delete referenced objects, what sense does it make to not have a repository for the references objects? Or are aggregate roots as a term referring to what is known as composite object?

2)
When you create an web service you will have multiple endpoints, in my case I have one entity Book and another named Comment. It does not make sense to leave the comments in my application if the book is deleted. Therefore, book is a composite object. I guess I should not have a repository for comments since that would break the enforcement of lifecycle and rules that the book class may have. However I have URL such as (examples only):

```<code>GET /books/1/comments
POST /books/1/comments
</code>```

Now, if I do not have a repository for comments, does that mean I have to load the book object and then return the referenced comments? Am I allowed to return a list of Comment entities from the BookRepository, does that make sense? The repository for Book may eventually become rather big with all sorts of methods. Am I allowed to write JPQL (JPA queries) that targets comments and not books inside the repository? What about pagination and filtering of comments. When adding a new comment triggered by the POST endpoint, do you need to load the book, add the comment to the book, and then update the whole book object?

What I am currently doing is having a own CommentRepository, even though the comments are deleted with the book. I could need some direction on how to do it correct. Since you are exposing not only root objects in RESTish services I wonder how to handle this at the backend.

I am using Hibernate and Spring.

答:
You have no other choice than to query comments by book id when you are dealing with RDBMS. For document database it is a different story and this is why document databases are more suitable for DDD than RDBMSes.

Just remember, I am repeating this again, DDD is not about repositories and any other particular implementation that Eric Evans has mentioned in his book. If you ever talk to him, you will learn that he sometimes regrets that there were so many implementation details included in the book. People think too much about repositories and specifications than on actual domains... Unless your application has a huge multi-domain landscape, nothing stops you from issuing queries like session.Query.Where(c => c.BookId == myBookId) right in your REST service. Your service is already a service layer, one more abstraction will be an overkill. You already mentioned that repositories grow and I bet most of your repository methods are one line data access calls. No domain expert will say this is right.


问:
Why do large IT projects tend to fail or have big cost/schedule overruns?
I always read about large scale transformation or integration project that are total or almost total disaster. Even if they somehow manage to succeed  the cost and schedule blow out is enormous. What is the real reason behind large projects being more prone to failure. Can agile be used in these sort of projects or traditional approach is still the best.

One example from Australia is the Queensland Payroll project where they changed test success criteria to deliver the project.

See some more failed projects in this SO question (on Wayback Machine)

Have you got any personal experience to share?

答:
Larger Project = More Complexity

More Complexity = More Uncertainties

More Uncertainties = Harder to Estimate

Harder to Estimate = Bad Estimates

Bad Estimates = Cost Overruns


问:
Is excessive indirection and/or redundant encapsulation a recognized concept?
I'm curious if there's a series of tendencies or anti-patterns when programming whereby a developer will always locally re-wrap external dependencies when consuming them.

A slightly less vague example might be say when consuming an implementation of an interface or abstract, and mapping every touch-point locally before interacting with them.  Like an overcomplicated take on composition.
Given my example, would the interface not be reliable enough and any change to it never be surmountable any any level of indirection?

Is this a good or a bad practice?  Can it ever go too far?  Does it have a proper name?

答:
I've seen these things called "shearing layers" - which are specializations of "abstraction layers" for external dependencies.

Personally, I think it is a bad practice that often falls into YAGNI.

Yes, abstraction layers protect you from changing interfaces outside of your control, or if you change dependencies. But I've seen too often people go "but what if our database provider changes?!?" for an app that has a 6 month lifespan. I've also seen far too many bad abstraction layers. They leak through enough implementation details that you end up with a boat load of work to adapt it to your new implementation anyways.

If you know the extenal interface is going to change, abstraction may be prudent. If you know that you're going to need multiple implementations, abstraction is important. If you don't know, you're (probably) not going to need it.


问:
Should the syntax for disabling code differ from that of normal comments?
For several reasons during development I sometimes comment out code. As I am chaotic and sometimes in a hurry, some of these make it to source control.

I also use comments to clarify blocks of code.

For instance:

```<code>MyClass MyFunction()
{
    (...)
    // return null; // TODO: dummy for now
    return obj;
}
</code>```

Even though it "works" and alot of people do it this way, it annoys me that you cannot automatically distinguish commented-out code from "real" comments that clarify code:

it adds noise when trying to read code

you cannot search for commented-out code for for instance an on-commit hook in source control.

Some languages support multiple single-line comment styles - for instance in PHP you can either use // or # for a single-line comment - and developers can agree on using one of these for commented-out code:

```<code># return null; // TODO: dummy for now
return obj;
</code>```

Other languages - like C# which I am using today - have one style for single-line comments (right? I wish I was wrong). I have also seen examples of "commenting-out" code using compiler directives, which is great for large blocks of code, but a bit overkill for single lines as two new lines are required for the directive:

```<code>#if compile_commented_out
    return null; // TODO: dummy for now
#endif
return obj;
</code>```

So as commenting-out code happens in every(?) language, shouldn't "disabled code" get its own syntax in language specifications? Are the pro's (separation of comments / disabled code, editors / source control acting on them) good enough and the cons ("shouldn't do commenting-out anyway", not a functional part of a language, potential IDE lag (thanks Thomas)) worth sacrificing?

Edit

I realise the example I used is silly; the dummy code could easily be removed as it is replaced by the actual code.

答:
In opposition to the answers, I'll answer with a "YES, there should be different syntax!"

I would challenge any developer to say that they go through even one day of coding without commenting out code. To do so does not mean one doesn't know source control or is lazy. Even as Thomas Owens says in his dissenting answer, "Except when I'm in a code/test/code/test... mode, I don't comment unused code."

How much of of your time is spent in code/test/code/test mode? For me that's at least 90% of work! At the moment I'm converting a large OSX project to iOS, and the first step was to disable all the code that was breaking until I had a stub that worked. For the next weeks I'll be slowly uncommenting and fixing code as I get it to work.

There are many other cases as well. What about when you're using example code where you often find directions like "Uncomment the following for Windows" or "Uncomment the this line for iPhone-only Apps"?

Yes, I'll be using source control all along. But also YES, I would love there to be a way to distinguish disabled code from actual comments.

In summary: Any programmer who says they don't use comments to disable code is lying. There is more to coding than the polished files you commit to HEAD. There are many valid reasons for disabled code.

Yes it would be nice if there were a syntax (or at least a convention) to distinguish true comments from disabled code.


答:
I think most people just call it "wrapping an API."  There are certain circumstances where it can be beneficial:

When you are only wrapping a small subset of the API.  This enforces a smaller interface.

When your ABI isn't constant.  Nvidia does this for their Linux drivers.  The installation script compiles the wrapper and links it against their closed source binary.

When you're creating a useful abstraction, not just a function-for-function copy of the original API.

When you already have two implementations of the API you know you need to use.  For example, different databases or operating systems or language versions.  I have a project for both Android and desktop Java where I wrapped most of the UI functionality.

The mistake a lot of people make is wrapping an API on the off chance they might need to replace it someday, but if and when that day comes, their wrapper is too much like the original and needs rewriting anyway.  Abstractions are only useful if they add some value to the layer below.

Title: Is excessive indirection and/or redundant encapsulation a recognized concept?

Body:
I'm curious if there's a series of tendencies or anti-patterns when programming whereby a developer will always locally re-wrap external dependencies when consuming them.

A slightly less vague example might be say when consuming an implementation of an interface or abstract, and mapping every touch-point locally before interacting with them.  Like an overcomplicated take on composition.
Given my example, would the interface not be reliable enough and any change to it never be surmountable any any level of indirection?

Is this a good or a bad practice?  Can it ever go too far?  Does it have a proper name?


答: My main concern with developers choosing how to implement their goals, is that they normally assume only they will be editting the code. Look at it this way, 12 months later they may need changes; you aren't available (left the company or really busy on another task), and another developer has to churn your code. If its a C# shop, then using their toolset is good teamwork. New technologies should be investigated and implemented, but only when the lead thinks the time is right, as they have their eye on many goals not just one.</p>


答:
I am struggling with how to structure the input file in a sane way; that is, in a way that a human can write it easily and a machine can parse it easily.

It greatly depends on the complexity and the quantity of information you need to input.  By complexity, I mean the relations between pieces fragments of information: a time series reporting the results of a measure at different time points has virtually no complexity, even if it is megabytes big, while describing the allocation of rooms and times to lectures in a university has a larger complexity, because there is a lot of constraints (only one lecture at a time in a given room, a professor cannot lecture simultaneously at several places, and so on).

Think to all that you want to do with the input of your program:

Prepare the input. obviously the input has to be prepared.  It is easier if the input format follows an organisation similar to the output format of the methodology (not necessarily a computer program) used to prepare the data.  Then, it is easy to resume from an interruption when preparing the input.

Review the input. if your program delivers questionable results, you will want to review the input.  It is then important that the format used be clear and put relevant information to the front.  (Complex data will probably require an exploration program to be succesfully reviewed, anyway.)

Correct the input. Once you spot a flaw, you want to correct it.  If your data is complex, a fix will not be limited to a specific location of the file but will have repercussions in other places.  Also, the fix could need to be peer-reviewed or checked-in a version control system.

Canonise the input. If your data is complex, there may be several very different ways to input the data, and you may need to be able to change from one to the other or to answer the simple but hard question: do these two input files represent the same data?

If you have little data, up to two or three screens of text, a key-value format like JSON, YAML or Property lists can be well suited.  Besides having a free imlementation for your favourite language, some also have visual editors (for instance the Property List Editor in Mac OS X can edit property lists, similar programs exist for JSON and probably others). Now, if the data set is small enough, 1. 2. 3. and 4. will remain practicable event if the representation is clumsy.

Now consider the case of a complex data: depending on the value that 1., 2., 3. and 4. for you, you may want to design a small declarative language to represent it.  This can be a very complex task, for which you can use lex/yacc or their avatars in your favourite programming language.

If you cannot afford to devise a specialised language, you may rely on SGML/XML that can catch some structure of your data.  An interesting alternative can be to use a simple dictionary format and write an auxiliary program to prepare the input of your main program.

Title: Structuring an input file

Body:
I am in the process of structuring a small program to perform some hydraulic analysis of pipe flow. As I am envisioning this, the program will read an input file, store the input parameters in a suitable way, operate on them and finally output results. I am struggling with how to structure the input file in a sane way; that is, in a way that a human can write it easily and a machine can parse it easily. A sample input file made available to me for a similar program is just a stream of comma-separated numbers that don't make much sense on their own, so that's the scenario I am trying to avoid.

Though I am giving the details of my particular problem, I am more interested in general input-file structuring strategies. Is a stream of comma-separated values my best bet? Would I be better off using some sort of key:value structure? I don't know much about this, so any help will probably put me in a better track than I am now.


问:
Writing the minimum code to pass a unit test - without cheating!
When doing TDD and writing a unit test, how does one resist the urge to "cheat" when writing the first iteration of "implementation" code that you're testing?

For example:

Let's I need to calculate the Factorial of a number.  I start with a unit test (using MSTest) something like:

```<code>[TestClass]
public class CalculateFactorialTests
{
    [TestMethod]
    public void CalculateFactorial_5_input_returns_120()
    {
        // Arrange
        var myMath = new MyMath();
        // Act
        long output = myMath.CalculateFactorial(5);
        // Assert
        Assert.AreEqual(120, output);
    }
}
</code>```

I run this code, and it fails since the CalculateFactorial method doesn't even exist.  So, I now write the first iteration of the code to implement the method under test, writing the minimum code required to pass the test.

The thing is, I'm continually tempted to write the following:

```<code>public class MyMath
{
    public long CalculateFactorial(long input)
    {
        return 120;
    }
}
</code>```

This is, technically, correct in that it really is the minimum code required to make that specific test pass (go green), although it's clearly a "cheat" since it really doesn't even attempt to perform the function of calculating a factorial.  Of course, now the refactoring part becomes an exercise in "writing the correct functionality" rather than a true refactoring of the implementation.  Obviously, adding additional tests with different parameters will fail and force a refactoring, but you have to start with that one test.

So, my question is, how do you get that balance between "writing the minimum code to pass the test" whilst still keeping it functional and in the spirit of what you're actually trying to achieve?

答:
It's perfectly legit.  Red, Green, Refactor.

The first test passes.

Add the second test, with a new input.

Now quickly get to green, you could add an if-else, which works fine.  It passes, but you are not done yet.

The third part of Red, Green, Refactor is the most important.  Refactor to remove duplication.  You WILL have duplication in your code now.  Two statements returning integers.  And the only way to remove that duplication is to code the function correctly.

I'm not saying don't write it correctly the first time.  I'm just saying it's not cheating if you don't.


问:
Is learning C# as a first language a mistake?
I know there are similar questions on here, which I've read, but I recently read this post by Joel Spolsky:

How can I teach a bright person, with no programming experience, how to program?

And it got me thinking about my way of learning and whether it might actually be harmful in the long run.

I've dabbled with various languages but C# is my first serious one, I've read "Head First C#" and created a few projects. But after reading the post above I've found it a bit disheartening that I may be going about it all wrong, obviously I respect Joel's opinion which is what has thrown me a bit.

I've started reading "Code" as recommended in the reading list and I'm finding it pretty hard going, although enjoyable. I feel like it's taken the shine off of my "noobish hacking about" in Visual Studio.

So now I'm unsure as to what path I should take? Should I take a step back and follow Joel's advice and start reading?

I guess my main aim is just to become a good programmer, like everyone else, but I don't want to be going into bad practice by learning a .NET language when someone who's opinion I respect thinks that it is harmful.

Thoughts?

答: To be a programmer you need to have passion.   The programmers I know are the ones that go out of their way to learn and notice industry changes.    I started my programming with basic on a Commodore Vic 20 (Yes that old) and kept moving on to other new languages.   Part of my programming years even included COBOL.   I also started to notice that some languages worked best in certain processes vs others.    My advice to you is to learn any language and to understand basic programming concepts like loops, methods, comparisons.   Most languages support those three concepts.   You should never say "This is the best way" but rather "How can I improve this ".    The worst thing about that last sentence is that you could catch yourself over engineering.    Programming is fun, make it fun!   The internet opened up a whole new way to experience programming because the level of access we have to information today is staggering.   For me before the internet I had to go to the shelf and pull down the GREY IBM programming books and learn.   Today you can simple type a thing into google and whammo.</p>


问:
Rails: Law of Demeter Confusion
I am reading a book called Rails AntiPatterns and they talk about using delegation to to avoid breaking the Law of Demeter. Here is their prime example:

They believe that calling something like this in the controller is bad (and I agree)

```<code>@street = @invoice.customer.address.street
</code>```

Their proposed solution is to do the following:

```<code>class Customer

    has_one :address
    belongs_to :invoice

    def street
        address.street
    end
end

class Invoice

    has_one :customer

    def customer_street
        customer.street
    end
end

@street = @invoice.customer_street
</code>```

They are stating that since you only use one dot, you are not breaking the Law of Demeter here. I think this is incorrect, because you are still going through customer to go through address to get the invoice's street. I primarily got this idea from a blog post I read:

http://www.dan-manges.com/blog/37

In the blog post the prime example is

```<code>class Wallet
  attr_accessor :cash
end
class Customer
  has_one :wallet

  # attribute delegation
  def cash
    @wallet.cash
  end
end

class Paperboy
  def collect_money(customer, due_amount)
    if customer.cash < due_ammount
      raise InsufficientFundsError
    else
      customer.cash -= due_amount
      @collected_amount += due_amount
    end
  end
end
</code>```

The blog post states that although there is only one dot customer.cash instead of customer.wallet.cash, this code still violates the Law of Demeter.

Now in the Paperboy collect_money method, we don't have two dots, we
  just have one in "customer.cash". Has this delegation solved our
  problem? Not at all. If we look at the behavior, a paperboy is still
  reaching directly into a customer's wallet to get cash out.

EDIT

I completely understand and agree that this is still a violation and I need to create a method in Wallet called withdraw that handles the payment for me and that I should call that method inside the Customer class. What I don't get is that according to this process, my first example still violates the Law of Demeter because Invoice is still reaching directly into Customer to get the street.

Can somebody help me clear the confusion. I have been searching for the past 2 days trying to let this topic sink in, but it is still confusing.

答:
Read further in the second article and I think the idea will become clearer. The idea just have customer offer a capability to pay and completely hide where the case is kept. Is it a field, a member of a wallet, or something else? The caller doesn't know, doesn't need to know and does not change if that implementation detail changes.

```<code>class Wallet
  attr_accessor :cash
  def withdraw(amount)
     raise InsufficientFundsError if amount > cash
     cash -= amount
     amount
  end
end
class Customer
  has_one :wallet
  # behavior delegation
  def pay(amount)
    @wallet.withdraw(amount)
  end
end
class Paperboy
  def collect_money(customer, due_amount)
    @collected_amount += customer.pay(due_amount)
  end
end
</code>```

So I think your second reference is giving a more helpful recommendation.

The "one dot" only idea, is a partial success, in that it hides some deep detail, but still inbcreases coupling between separate components.

Title: Rails: Law of Demeter Confusion

Body:
Read further in the second article and I think the idea will become clearer. The idea just have customer offer a capability to pay and completely hide where the case is kept. Is it a field, a member of a wallet, or something else? The caller doesn't know, doesn't need to know and does not change if that implementation detail changes.

class Wallet
  attr_accessor :cash
  def withdraw(amount)
     raise InsufficientFundsError if amount > cash
     cash -= amount
     amount
  end
end
class Customer
  has_one :wallet
  # behavior delegation
  def pay(amount)
    @wallet.withdraw(amount)
  end
end
class Paperboy
  def collect_money(customer, due_amount)
    @collected_amount += customer.pay(due_amount)
  end
end

So I think your second reference is giving a more helpful recommendation.

The "one dot" only idea, is a partial success, in that it hides some deep detail, but still inbcreases coupling between separate components.

OwnerDisplayName: djna


答:
The first example and the second are actually not very same. While the first talking about general rules of "one dot", the second talks more about other things in OO design, especially "Tell, Don't ask"

Delegation is an effective technique to avoid Law of Demeter violations, but only for behavior, not for attributes. -- From the second example, Dan's blog

Again, "only for behavior, not for attributes"

If you ask for attributes, you are supposed to ask. "Hey, guy, how much money do you have in pocket? Show me, I'll evaluate if you can pay this." That's wrong, no shopping clerk will behave like this. Instead, they'll say, "Please pay"

```<code>customer.pay(due_amount)
</code>```

It'll be customer's own duty to evaluate if he should pay and if he can pay. And the clerk's task is finished after telling customer to pay.

So, does the second example prove the first is wrong?

In my opinion. No, as long as:

1. You do it with with self-constraint.

While you can access all of the customer's attributes in @invoice by delegation, you rarely need that in normal cases.

Think about a page showing an invoice in a Rails app. There will be a section on top to show the customer's details. So, in invoice template, will you code like this?

```<code>#customer-info
  = @invoice.customer_name
  = @invoice.customer_address
  ....
</code>```

That's wrong and inefficient. A better approach is

```<code>#customer-info
  = render partial: 'invoice_header_customer',
           locals: {customer: @invoice.customer}
</code>```

Then let the customer partial to process all attributes belongs to customer.

So generally you don't need that. But you may have a list page showing all recent invoices, there is a briefing field in each li displaying the customer's name. In this case, you do need the customer's attribute to show, and it's totally legit to code the template as

```<code>= @invoice.customer_name
</code>```

2. There is no further action depending on this method call.

In above case of list page, the invoice asked the customer's name attribute, but it's real purpose is "show me your name", so it's basically still a behavior but not attribute. There is no further evaluation and action based on this attribute like, if your name is "Mike" I will like you and give you 30 days more credit. No, invoice just say "show me your name", no more. So that's totally acceptable according to the "Tell Don't Ask" rule in example 2.

Title: Rails: Law of Demeter Confusion

Body:
I am reading a book called Rails AntiPatterns and they talk about using delegation to to avoid breaking the Law of Demeter. Here is their prime example:

They believe that calling something like this in the controller is bad (and I agree)

```<code>@street = @invoice.customer.address.street
</code>```

Their proposed solution is to do the following:

```<code>class Customer

    has_one :address
    belongs_to :invoice

    def street
        address.street
    end
end

class Invoice

    has_one :customer

    def customer_street
        customer.street
    end
end

@street = @invoice.customer_street
</code>```

They are stating that since you only use one dot, you are not breaking the Law of Demeter here. I think this is incorrect, because you are still going through customer to go through address to get the invoice's street. I primarily got this idea from a blog post I read:

http://www.dan-manges.com/blog/37

In the blog post the prime example is

```<code>class Wallet
  attr_accessor :cash
end
class Customer
  has_one :wallet

  # attribute delegation
  def cash
    @wallet.cash
  end
end

class Paperboy
  def collect_money(customer, due_amount)
    if customer.cash < due_ammount
      raise InsufficientFundsError
    else
      customer.cash -= due_amount
      @collected_amount += due_amount
    end
  end
end
</code>```

The blog post states that although there is only one dot customer.cash instead of customer.wallet.cash, this code still violates the Law of Demeter.

Now in the Paperboy collect_money method, we don't have two dots, we
  just have one in "customer.cash". Has this delegation solved our
  problem? Not at all. If we look at the behavior, a paperboy is still
  reaching directly into a customer's wallet to get cash out.

EDIT

I completely understand and agree that this is still a violation and I need to create a method in Wallet called withdraw that handles the payment for me and that I should call that method inside the Customer class. What I don't get is that according to this process, my first example still violates the Law of Demeter because Invoice is still reaching directly into Customer to get the street.

Can somebody help me clear the confusion. I have been searching for the past 2 days trying to let this topic sink in, but it is still confusing.

Body:
The first example and the second are actually not very same. While the first talking about general rules of "one dot", the second talks more about other things in OO design, especially "Tell, Don't ask"

Delegation is an effective technique to avoid Law of Demeter violations, but only for behavior, not for attributes. -- From the second example, Dan's blog

Again, "only for behavior, not for attributes"

If you ask for attributes, you are supposed to ask. "Hey, guy, how much money do you have in pocket? Show me, I'll evaluate if you can pay this." That's wrong, no shopping clerk will behave like this. Instead, they'll say, "Please pay"

customer.pay(due_amount)

It'll be customer's own duty to evaluate if he should pay and if he can pay. And the clerk's task is finished after telling customer to pay.

So, does the second example prove the first is wrong?

In my opinion. No, as long as:

1. You do it with with self-constraint.

While you can access all of the customer's attributes in @invoice by delegation, you rarely need that in normal cases.

Think about a page showing an invoice in a Rails app. There will be a section on top to show the customer's details. So, in invoice template, will you code like this?

#customer-info
  = @invoice.customer_name
  = @invoice.customer_address
  ....

That's wrong and inefficient. A better approach is

#customer-info
  = render partial: 'invoice_header_customer',
           locals: {customer: @invoice.customer}

Then let the customer partial to process all attributes belongs to customer.

So generally you don't need that. But you may have a list page showing all recent invoices, there is a briefing field in each li displaying the customer's name. In this case, you do need the customer's attribute to show, and it's totally legit to code the template as

= @invoice.customer_name

2. There is no further action depending on this method call.

In above case of list page, the invoice asked the customer's name attribute, but it's real purpose is "show me your name", so it's basically still a behavior but not attribute. There is no further evaluation and action based on this attribute like, if your name is "Mike" I will like you and give you 30 days more credit. No, invoice just say "show me your name", no more. So that's totally acceptable according to the "Tell Don't Ask" rule in example 2.

OwnerDisplayName: Billy Chan