答:
It is quite simple. You need a FIFO container (stack) and root node.

Always add new nodes as childs of front node in stack. When you see greater depth than previous, put latest added note onto stack, before adding next. When you see smaller depth, pop from stack delta times (again: before adding next node). Don't track current depth, it is already tracked by stack.

Pseudocode:

```<code>root = new Node
stack = new Stack
stack.push(root)

for record in records
    delta = record.depth - (stack.size - 1)

    if delta > 0
        assert delta == 1
        stack.push(stack.front().last_child())

    while delta < 0
        stack.pop()
        delta++

    stack.front().add_child(record.node)

return root
</code>```

You can understand it better, if you represent depth as N indents, where N = depth.

```<code>node #1, depth 0 // parent: none
    node #2, depth 1 // parent: #1
    node #3, depth 1 // parent: #1
        node #4, depth 2 // parent: #3
    node #5, depth 1 // parent: #1
        node #6, depth 2 // parent: #5
</code>```

Title: Reconstructing a tree from depth information

Body:
I have a data structure that describes a tree. Nodes are ordered, with "depth" information, and knowing the order and the depth the tree can be reconstructed. I'm not entirely sure how to describe it so I'm hoping this small example will illustrate it

```<code>node #1, depth 0 // parent: none
node #2, depth 1 // parent: #1
node #3, depth 1 // parent: #1
node #4, depth 2 // parent: #3
node #5, depth 1 // parent: #1
node #6, depth 2 // parent: #5
</code>```

(I added parent information in there for clarification. That's not part of the data structure.)

I'm trying to write an algorithm (in JS, if that's any help) that will iterate over each node and build a tree out of the data. I'm fairly recursion is the way to go but beyond that I'm not sure where to start. Any suggestions?

Edit: The way I see it, I have four cases:

Node has depth 0 (initial case)

Node has same depth as previous

Node has greater depth as previous (should only be previous.depth+1)

Node has less depth than previous

Here's my pseudo-JS-code so far:

```<code>process (nodes, 0);
process = function(nodes, i) {
  cur = nodes[i], prev = nodes[i-1]
  if cur.depth = 0 then cur.parent = null  // case #1
  else if cur.depth == prev.depth then cur.parent = prev.parent // case #2
  else if cur.depth > prev.depth then cur.parent = prev // case #3
  else // case #4... here's where I'm stuck.
  if i <= nodes.length then process (nodes, i+1)
}
</code>```

Body:
It is quite simple. You need a FIFO container (stack) and root node.

Always add new nodes as childs of front node in stack. When you see greater depth than previous, put latest added note onto stack, before adding next. When you see smaller depth, pop from stack delta times (again: before adding next node). Don't track current depth, it is already tracked by stack.

Pseudocode:

root = new Node
stack = new Stack
stack.push(root)

for record in records
    delta = record.depth - (stack.size - 1)

    if delta > 0
        assert delta == 1
        stack.push(stack.front().last_child())

    while delta < 0
        stack.pop()
        delta++

    stack.front().add_child(record.node)

return root

You can understand it better, if you represent depth as N indents, where N = depth.

node #1, depth 0 // parent: none
    node #2, depth 1 // parent: #1
    node #3, depth 1 // parent: #1
        node #4, depth 2 // parent: #3
    node #5, depth 1 // parent: #1
        node #6, depth 2 // parent: #5


问:
From an execution perspective is an interpreter the same as the JVM / or the .net Framework
I've recently started two introductory level courses - one using Python, the other Java.

I've read the answers to this Question but still have difficulty understanding how each ends up with machine code and what the main differences between the two models are:

Is an interpreter doing the same job as something like the JVM, just without the
byte-code?

For python is the interpreter taking the high-level code
and translating it into machine code?

The Java virtual machine needs to be installed on a machine for a java program to run on it - is it similar for python - if the interpreter is installed on the target machine then the python program will run?

Is the JVM (& .net framework) effectively byte-code interpreters?

答:
Various comments have pointed out several ambiguities in the question and nuances to the answer, but the simple answer is no.

The JVM and .NET Framework are Just-In-Time Compilers. They are still compilers, and do all of the work of a compiler. They take an intermediate language (bytecode), optimize it, and convert it into machine code. The only difference between jitters and traditional compilers is when they do the compilation.

Interpreters, at least in their traditional definition, never compile code. Rather, they use code that is already compiled in order to execute the instructions they are given. This makes them faster to start up (since they don't need to compile anything) but generally slower to run, since there is overhead associated with each instruction.

If you wrote some code that did the following with a bunch of "switch" or "if" statements:

Read every line of a file

For every line that says "A", write "hello" to the screen

For every line that says "B", write "world" to the screen

For every other line, write "error" to the screen

Then this would be a (very crude) interpreter. It would not be a compiler of any kind, because all of the parts that actually run on the machine are in your program. It's doing parsing, but skipping the compile and link steps and going directly to execution based on a look-up table.

Another way to think of it - and I caution that this is purely an analogy for beginners and not a perfectly accurate technical description - is that interpreters essentially work on a line-by-line basis, whereas jitters will compile large chunks of the bytecode or possibly even the entire bytecode at the same time.

It's also often possible to precompile bytecode without a jitter (like Microsoft's NGen), since bytecode is typically very similar (but not identical) to the machine code. Interpreted code usually remains in a high-level language all the way to execution.

ContentLicense: CC BY-SA 3.0


问:
Should there be a formal role (internal or external) assigned to dev environments to control wasteful complexity?
A few years ago, I worked for a small company that went so far into developing in-house frameworks that they dedicated their most senior developer, and their architect to developing a custom MVC framework and ORM from scratch. These two things were orthogonal to their core product. Unfortunately the support for this framework-driven approach came from the top, and it delayed delivery of revenue-generating software - and the frameworks produced were notably inferior to off-the-shelf alternatives, which compounded the delays. The company burned through cash quickly, and, eventually, everyone was laid off.

A later employer made a similar mistake - they got a highly technically skilled developer - a perfectionist, with a strong grounding in enterprise design patterns to grossly over-engineer a consulting solution for one of their clients, knowingly taking a loss, in the hope that the solution could be adapted and extended for other customers. The project overran significantly. But no other potential customers bit. A gold-plated strategic blunder that cost a small fortune.

In both cases there was a significant degree of overengineering. In both cases the company and project management were people with domain or analysis backgrounds, rather than a programming background. In both cases the software architects built overly-complex solutions to scratch their itches, and enhance their résumés, with some complicity from non-technical management. In both cases the architects had no stake in keeping costs down (apart from the risk of losing their jobs if the companies went bankrupt- which wasn't much of a risk, considering their high employability).

My experience suggests that it isn't an uncommon trap for dev shops to fall into.

Is there place in software projects for a formal internal or external technical adversarial role - a "Quantity Surveyor" - to use a building analogy- that can call out, or prevent wasteful over-engineering? Who is best suited to fill this role?

答:
"Controlling complexity" is the job of:

The architect, whose job it is to ensure that the system and enterprise architecture is suitable for the current projects/products;

The developer, whose job it is to create designs and code that are not only correct but also maintainable, and also to review the code of other developers to ensure that they can understand it; and

The business/systems analyst or product owner, whose job it is to work out what the business actually needs right now, what can be finished later, or what might never materialize at all.

"Complexity" is an abstract concept anyway, and it could well be argued that "reducing complexity" is the very purpose of software in the first place, so it doesn't make sense to suggest a role dedicated to it - that's what the whole team should already be doing!

Assuming that a cursory look at the ROI and TCO demonstrate that the solution(s) is/are really and truly over-engineered, then I'm sorry to say that the architects and developers and analysts who were working on it simply weren't very good at their jobs. And the people in charge of that aspect are the managers or executives who hired them; possibly they've cultivated a culture of over-engineering and are partially at fault, or possibly they've just been getting bad advice from the implementation team.

I won't venture a guess at which one since I (probably) haven't worked for your company, but I'm sure you can figure it out for yourself pretty easily by just having a one-on-one conversation with one or a few of said managers.

Incidentally, developing in-house frameworks isn't always a bad thing. It's just that those frameworks should generally be based on observation and refinement of the current process. Frameworks or libraries that come about by refactoring existing code tend to last a long time. On the other hand, if people just dive in and start developing a framework with no context at all, then it usually becomes a liability, and quickly.

People have to be able to recognize the difference between conventions (most projects at an organization will use the same technology stack, with a certain amount of boilerplate code, but that doesn't mean jamming it all together into a "framework" is a good idea) vs. duplication (people are literally solving the same business or technical problems over and over again and the inconsistencies lead to convoluted designs and serious defects). Software businesses can and should recognize the latter scenario and actively take steps to, well, reduce the complexity. Frameworks do reduce complexity as long as they're not succumbing to the inner-platform effect.


问:
How unique should a UUID identified object be?
I am working on a fairly large open source project (Drupal) and the next major version will begin to use UUIDs for a lot of things, including configuration objects. If we put UUIDs into the configuration we ship with and then various sites change their configuration then there will be many, many objects in the wild with the same UUID but different properties. Is this... OK? Or is it better practice to ship without UUIDs and generate them on install?</p>

答:
I guess it depends on whether or not all of these things you ship will ever have to talk to each other, or whether you plan to use the IDs for support or upgrades.

The first "U" in "UUID" stands for "Universal[ly]". If you allow the thing identified by a UUID to be changed, it might not universally identify the thing anymore. But then it depends what the thing really is that you're tryiing to identify:

If, in your world, the "thing" means the specific instance being shipped to a customer site, then you should definitely generate the UUIDs at the site, because even if customers don't change it, you're still using a UUID for something that isn't unique.

On the other hand, if (for example) you wanted to track changes in the wild to this configuration object, and be able to tie them all back together to what the original configuration was or should have been, then what you're really trying to identify is the type, and a pre-generated UUID makes perfect sense.

As usual, the answer is "it depends on your requirements/expectations". What is the domain or business concept - not just the technical object - that the UUID identifies? If you have the answer to that, it should become obvious where the ID needs to be generated.


问:
Comparing TCP/IP applications vs HTTP applications
I'm interested in developing a large-scale user-facing website that is written in Java.

As for design, I'm thinking of developing independent, modular services that can act as data providers to my main web application.

As for writing these modular services (data providers), I can leverage an existing framework like Spring and develop these services following the RESTful design pattern, and expose resources via HTTP with a message format like JSON...or I can leverage an existing network framework like Netty (http://netty.io/) and serialization format like Protobufs (https://developers.google.com/protocol-buffers/docs/overview) and develop a TCP server that sends back and forth the serialized protobuf payload.

When should you choose one over the other? Would there be any benefit of using a serialization format like Protobufs and sending stream of bytes over the wire? Would there be overhead in just using JSON? How much overhead is there between using TCP/IP and using HTTP? When should you use Spring over Netty, and vice versa to build such a service?

答:
This is actual a non question. According to the Internet protocol suite tcp is a protocol in the transport layer and http is a protocol in the application layer. You're comparing totally different things with each other. (See more here: http://en.wikipedia.org/wiki/Internet_protocol_suite)

In fact, most http is over tcp/ip. So to answer your question, yes you should use tcp/ip. Then you want to add a application layer protocol over that (like http) and then a data format (like json, xml, html). Netty let you use http and protobuff is equal to json, xml, html.

It all depends on what your requirements are and what type of data you'll need to transport. Do you need sessions in your protocoll, can a handshake improve your protocol configuration, how much data will you send at once, do you need encryption? These are questions you need to answer when choosing an application protocol.

For choosing a data representation format (json, xml, html, protobuff, etc.) it depends on your bandwidth, readability, language/tool support etc.

You can't compare http to tcp.

Remember that speed isn't everything. Speed is of no use if you can't express yourself in a sensible way.


答:
There are definitely pros/cons about using JSON over REST vs. straight up TCP/IP with binary protocol and I think you are already suspecting that binary protocol will be faster.  I can't tell you exactly how much faster (and this would depend on a lot of factors), but I would guess maybe 1-2 orders of magnitude difference.

At first glance if something is 10-100 times slower than something else, you might have a knee-jerk reaction and go for "fast thing".  However, this speed difference is only in the protocol itself.  If there's database/file access on the server side, that won't get impacted by your choice of the transfer layer.  In some cases, it might make your transfer layer speed much less significant.

HTTP REST and JSON are good for a number of reasons:

they are easily consumable by just about anyone. You can write your Web App, then turn around and publish your API for the rest of the world to use. Now anyone can hit the same end-points and get to your services

they are easily debuggable, you can open a packet sniffer or simply dump incoming requests to text files and see what's going on.  You can't do that with binary protocols

they are easily extendable. You can add more attributes and data at a later time and not break compatibility with old clients.

consumable by javascript clients (not sure they have protobuf JS parser yet, don't believe there's one)

Protobufs over TCP/IP:

they are faster

If it was my choice, I would hands down go with HTTP REST and JSON.  There's a reason that so many other companies and websites went that route.  Also keep in mind that in the future you could always support 2 end points.  If your design is correct, your end-point choice should be completely decoupled from your server-side business logic or the database.  So if you realize later on that you need more speed for all/some requests, you should be able to add protobufs with minimal fuss.  Right off the bat however, REST/JSON will get you off the ground faster and get you further.

As far as Netty vs Spring goes.  I haven't used Netty directly, but I believe it is just a light-weight web server where as Spring is a framework that provides a lot more for you than just that.  It has data access layers, background job scheduling and (I think) an MVC model, so it is much more heavyweight.  Which one to choose?  If you decided to go HTTP way, then next question is probably how standard is your app?  If you are about to write some crazy custom logic that doesn't fit the standard mold and all you need is just a HTTP server layer, go with Netty.

However, I'm suspecting you app isn't that special and it could probably benefit from a lot of things that Spring has to offer. But that means that you should structure your app around Spring's framework and do things the way they expect you to do, which would mean learning more about Spring before diving into your product.  Frameworks in general are great because again they get you off the ground faster, but the downside is that you have to fit into their mold instead of doing your own design and then expect the framework to just work.

(*) - in the past it was pointed out that my posts do not reflect opinions of the entire world, so I'll go on the record and just add that I have limited experience with either Netty (I've used Play framework before which is based on Netty) or Spring (I've only read about it).  So take what I say with a grain of salt.

Title: Comparing TCP/IP applications vs HTTP applications

Body:
I'm interested in developing a large-scale user-facing website that is written in Java.

As for design, I'm thinking of developing independent, modular services that can act as data providers to my main web application.

As for writing these modular services (data providers), I can leverage an existing framework like Spring and develop these services following the RESTful design pattern, and expose resources via HTTP with a message format like JSON...or I can leverage an existing network framework like Netty (http://netty.io/) and serialization format like Protobufs (https://developers.google.com/protocol-buffers/docs/overview) and develop a TCP server that sends back and forth the serialized protobuf payload.

When should you choose one over the other? Would there be any benefit of using a serialization format like Protobufs and sending stream of bytes over the wire? Would there be overhead in just using JSON? How much overhead is there between using TCP/IP and using HTTP? When should you use Spring over Netty, and vice versa to build such a service?


问:
How to explain to non-programmer to build my Visual Studio source code in "Release" mode?
I'm writing documentation for some software that I wrote.  Specifically, I'm writing a guide to installing the software.  I'm delivering the source-code to my client, so I expect that they will want to be able to build from source.

I explain to open the solution in Visual Studio 2010 and to right-click on the project and select "Publish".

There doesn't seem to be a clear and straight-forward way to explain that they must build it in "Release" mode or what the simplest way to explain how to do that is.

What's the best way to explain this?

Edit: In response to the comments asking me to be more specific, on my setup of Visual Studio 2010, there is a drop-down list next to the green icon that starts the debugger.  It doesn't have any label next to it.  That's how I'm familiar with changing the setting myself, but I don't want to write in my documentation, "Click on the drop-down list next to the green button and select "Release".  There's got to be a better way.  I am particularly concerned that if I get in wrong, it could result in someone changing the setting at the project level instead of the solution level.

答:
I would add a note "build in Release mode" to the doc and assume the reader (either the client or a developer hired by the contractor) is competent enough to find the right button to push.

There is a minimum skill level required to make even trivial code changes and I'd include this as one of them.  Put another way, if your reader needs instructions on how to build in Release mode, what are the chances that they're qualified to not break the code through ignorance?

It makes perfect sense for the client to request the source code - they paid for it.  If they don't have the skills to make changes themselves, they can hire it out to someone else.

FWIW, I count myself in this category.  In some environments I can certainly build code.  In others I know better than to do anything more than look over someone's shoulder.


问:
How do you formulate the Domain Model in Domain Driven Design properly (Bounded Contexts, Domains)?
Say you have a few applications which deal with a few different Core Domains.

The examples are made up and it's hard to put a real example with meaningful data together (concisely).

In Domain Driven Design (DDD) when you start looking at Bounded Contexts and Domains/Sub Domains, it says that a Bounded Context is a "phase" in a lifecycle.

An example of Context here would be within an ecommerce system. Although you could model this as a single system, it would also warrant splitting into separate Contexts. Each of these areas within the application have their own Ubiquitous Language, their own Model, and a way to talk to other Bounded Contexts to obtain the information they need.

The Core, Sub, and Generic Domains are the area of expertise and can be numerous in complex applications.

Say there is a long process dealing with an Entity for example a Book in a core domain. Now looking at the Bounded Contexts there can be a number of phases in the books life-cycle. Say outline, creation, correction, publish, sale phases.

Now imagine a second core domain, perhaps a store domain. The publisher has its own branch of stores to sell books. The store can have a number of Bounded Contexts (life-cycle phases) for example a "Stock" or "Inventory" context.

In the first domain there is probably a Book database table with basically just an ID to track the different book Entities in the different life-cycles.

Now suppose you have 10+ supporting domains e.g. Users, Catalogs, Inventory, .. (hard to think of relevant examples).

For example a DomainModel for the Book Outline phase, the Creation phase, Correction phase, Publish phase, Sale phase.
Then for the Store core domain it probably has a number of life-cycle phases.

```<code>public class BookId : Entity
{
    public long Id { get; set; }
}
</code>```

In the creation phase (Bounded Context) the book could be a simple class.

```<code>public class Book : BookId
{
    public string Title { get; set; }
    public List<string> Chapters { get; set; }
    //...
}
</code>```

Whereas in the publish phase (Bounded Context) it would have all the text, release date etc.

```<code>public class Book : BookId
{
    public DateTime ReleaseDate { get; set; }
    //...
}
</code>```

The immediate benefit I can see in separating by "life-cycle phase" is that it's a great way to separate business logic so there aren't mammoth all-encompassing Entities nor Domain Services. A problem I have is figuring out how to concretely define the rules to the physical layout of the Domain Model.

A. Does the Domain Model get "modeled" so there are as many bounded contexts (separate projects etc.) as there are life-cycle phases across the core domains in a complex application?

Edit: Answer to A.
Yes, according to the answer by Alexey Zimarev there should be an entire "Domain" for each bounded context.

B. Is the Domain Model typically arranged by Bounded Contexts (or Domains, or both)?

Edit: Answer to B. Each Bounded Context should have its own complete "Domain" (Service/Entities/VO's/Repositories)

C. Does it mean there can easily be 10's of "segregated" Domain Models and multiple projects can use it (the Entities/Value Objects)?

Edit: Answer to C. There is a complete "Domain" for each Bounded Context and the Domain Model (Entity/VO layer/project) isn't "used" by the other Bounded Contexts directly, only via chosen paths (i.e. via Domain Events).

The part that I am trying to figure out is how the Domain Model is actually implemented once you start to figure out your Bounded Contexts and Core/Sub Domains, particularly in complex applications. The goal is to establish the definitions which can help to separate Entities between the Bounded Contexts and Domains.

答:
To be honest, your question is not easy to understand.

When you start your DDD journey, you identify your domains and bounded contexts. Ideally you have one bounded context per domain but it depends. Each domain has its own domain model, you mention this yourself. But these domain models have nothing in common. They don't know about each other. Your idea to have one base class for two entities from different domains does not fit to DDD. Real domain models do not allow accessing anything within the domain model to anything outside of the bounded context. All communication between bounded contexts go via pre-defined interfaces like queries and commands if you do CQRS. This way you can make your components loosely coupled and allow different groups to work on different domains without depending on each other.

Bounded context always mean separate application. You can think of a separate solution though. It will include a domain project with entities, VOs, commands. It will also include services project with command handlers and query handlers. It will include transport projects like an application that uses service bus for commands and events.

Remember that using domainevents is crucial to enable inversion of control on the business logic level, when one domain informs everyone else about things that happen, allowing the, to react accordingly and do necessary activities. You can think of order payment event in sales domain that triggers a dispatching process in the inventory domain. Sales domain does not even need to know about the inventory domain.


问:
Story Point Estimation vs Ideal Days Estimation
In my project we assign 4 hours for 1 story point and estimate based on story point. So in this case one ideal day of work will be done in 2 elapsed days. From an agile standpoint are we doing story point estimation or ideal days estimation or none of these?</p>

答:
You're definitely doing a time based estimation, hence, no story points in the original sense. Story points are meant to be an abstract measure for relative estimation of story complexity. The mapping to an amount of time only happens implicitly, when you pull a certain number of story points into your fixed-time iteration. Here's an interesting discussion about how Story Points relate to hours.

But, on the other hand, your not really doing ideal-days estimation either, because at least you say that you estimate in hours. Ideal days means that you give estimates like "in 1.5 days we will be through with this". Of course you can map 8h = 2SP = 1 day. Actually, I would bet that many of you estimate in days and then derive hours from that and than story points. So implicitly you're probably doing ideal-days estimation ;)


问:
Module system for OOP language
I'm designing a simple OO programming language.

It's statically typed, compiled, and executed by a VM - similar to Java.

The difference is that I don't want to have such a strong emphasis on OOP. The code itself will mostly resemble C++ (classes, functions, and variables allowed in the file scope).

One of the things that I need to have is a module system. I have the following figured out:

Every file is a module (once compiled) - like Python

Programmers must import a module with the import keyword, which causes the compiler to search for modules in standard directories and the file directory (the VM has to do this at runtime as well)

And now I have no idea how should I introduce the concept of submodules and module hierarchy.

One option, for example, is to depend on the directory hierarchy, so that import engine.graphics.renderer would expect to find a directory called "engine" in the working directory, and inside a directory called "graphics", with a module called "renderer".

What are the drawbacks of such a design? Am I missing anything?

答:
First of all, let's assume that you map your namespaced model to another namespace, such as the filesystem, as you suggested. Second, I'm assuming that modules can import other modules. In other words, engine.graphics.renderer could very well contain a line like import circle.arc. That raises two issues:

Where would the VM look for circle.arc? According to to the filesystem mappimg mentioned, there should be a directory like /etc/mylang/modules/circle/arc (/etc/mylang/modules being the root of your module structure).

How would an application reference circle.arc: by importing circle.arc or engine.graphics.render.circle.arc?  The first would "spoil" (if not ruin) the hierarchy, because circle.arc is clearly a submodule of engine.graphics.renderer, and the second would imply that there should be a /etc/mylang/modules/engine/graphics/renderer/circle/arc in your filesystem, placing circle.arc in two locations simultaneously.

Having said that, and should you decide to go with the namespace approach, mapping it to the filesystem seems too restrictive to me. I think modules can reside in all different kinds of places (even zip files, as already mentioned, even urls). The VM would start by looking up an entry in some kind of index (maybe a config file) that would map the namespace to actual module locations.

Title: Module system for OOP language


答:
Since this is for a non-technical client, I would ask: Why are you even requiring them to build from source?

Instead, if the want the source code, do the following:

Build a release of your software for them and deliver the executable binaries

Also deliver the source code to them

This is really the best mechanism for them to receive your software. If they need to run it on multiple platforms, that's all the more reason for them not to have to compile your source. Instead, deliver prebuilt binaries for all their target platforms.

You can still deliver the source code while offering a much better initial user experience of delivering prebuilt binaries. That's much preferable to going through any documentation on building it themselves, no matter how well the documentation is written.

Title: How to explain to non-programmer to build my Visual Studio source code in "Release" mode?

Body:
I'm writing documentation for some software that I wrote.  Specifically, I'm writing a guide to installing the software.  I'm delivering the source-code to my client, so I expect that they will want to be able to build from source.

I explain to open the solution in Visual Studio 2010 and to right-click on the project and select "Publish".

There doesn't seem to be a clear and straight-forward way to explain that they must build it in "Release" mode or what the simplest way to explain how to do that is.

What's the best way to explain this?

Edit: In response to the comments asking me to be more specific, on my setup of Visual Studio 2010, there is a drop-down list next to the green icon that starts the debugger.  It doesn't have any label next to it.  That's how I'm familiar with changing the setting myself, but I don't want to write in my documentation, "Click on the drop-down list next to the green button and select "Release".  There's got to be a better way.  I am particularly concerned that if I get in wrong, it could result in someone changing the setting at the project level instead of the solution level.


问:
Why does assigning a variable to false return false?
Why does:

```<code>something = false
</code>```

always return false?

Since it is an assignment and not a comparison, it seems it would make more sense to return the result (success/failure) of the assignment (like pretty much every other assignment you do).

EDIT - this is wrong, as the answers below point out. My bad. Slight brain fart. See the original impetus for this question in the comments below.

What happens if some_boolean_var = false failed for whatever reason (unlikely, but theoretically possible, especially if you defined a custom method for this action)? That would also return false, so you have no indication as to whether the assignment actually worked.

It basically just means you can't combine assignment and comparison in one line like you can do with nearly everything else in Rails. For example, you can't do:

```<code>if something = false (note the single =)
  do stuff
end
</code>```

I mean you can do it but not if you wanted to check and make sure the assignment succeeded first.

Just really weird to me.

I'm sure there is a reason for this so please enlighten me :)

Thanks in advance!

答:
Assignment evaluates to the assigned value, which can be useful for some shortcuts, e.g:</p>

```<code>if x = get_some_value()
  puts "x is #{x}"
else
  puts "no x"
end
</code>```

Body:
Assignment evaluates to the assigned value, which can be useful for some shortcuts, e.g:

if x = get_some_value()
  puts "x is #{x}"
else
  puts "no x"
end


答:
In ruby (and may languages that trace some semblance of a lineage to C), the = operator traditionally returns the value that was assigned.

```<code>>> foo = false
=> false
>> foo = 4
=> 4
</code>```

This allows one to use what is known as chained assignment (see related question on P.SE) to do things such as:

```<code>>> foo = bar = 42
=> 42
>> foo
=> 42
>> bar
=> 42
</code>```

In this example, it is parsed as foo = (bar = 42).  From this, bar = 42 returns 42, which is then assigned to foo.

This type of structure is found in C, C++, Java, Perl and many other languages.

Think of it this way - every operator returns something - what else would = return than the value that was assigned?

While it doesn't allow your if something = false test, it does allow for structures that resumable:

```<code>while data = file.getc
    ...
end
</code>```

In Ruby getc returns the character read (and an nil (a falsey value) when the file has been completely read).  Thus, the read and the loop conditional test are done within the loop itself.

Title: Why does assigning a variable to false return false?

Body:
Why does:

```<code>something = false
</code>```

always return false?

Since it is an assignment and not a comparison, it seems it would make more sense to return the result (success/failure) of the assignment (like pretty much every other assignment you do).

EDIT - this is wrong, as the answers below point out. My bad. Slight brain fart. See the original impetus for this question in the comments below.

What happens if some_boolean_var = false failed for whatever reason (unlikely, but theoretically possible, especially if you defined a custom method for this action)? That would also return false, so you have no indication as to whether the assignment actually worked.

It basically just means you can't combine assignment and comparison in one line like you can do with nearly everything else in Rails. For example, you can't do:

```<code>if something = false (note the single =)
  do stuff
end
</code>```

I mean you can do it but not if you wanted to check and make sure the assignment succeeded first.

Just really weird to me.

I'm sure there is a reason for this so please enlighten me :)

Thanks in advance!

Body:
In ruby (and may languages that trace some semblance of a lineage to C), the = operator traditionally returns the value that was assigned.

>> foo = false
=> false
>> foo = 4
=> 4

This allows one to use what is known as chained assignment (see related question on P.SE) to do things such as:

>> foo = bar = 42
=> 42
>> foo
=> 42
>> bar
=> 42

In this example, it is parsed as foo = (bar = 42).  From this, bar = 42 returns 42, which is then assigned to foo.

This type of structure is found in C, C++, Java, Perl and many other languages.

Think of it this way - every operator returns something - what else would = return than the value that was assigned?

While it doesn't allow your if something = false test, it does allow for structures that resumable:

while data = file.getc
    ...
end

In Ruby getc returns the character read (and an nil (a falsey value) when the file has been completely read).  Thus, the read and the loop conditional test are done within the loop itself.


问:
OOP language design attribute symbol
I am designing a language, and wondering which character (or string) to use to represent that something is an attribute of something else.

In all languages I have used, this is done with a dot - my_class_instance.attribute.

However, in this language, I want to have what would usually be methods as syntactic sugar for normal functions, like so:

```<code>x.f(y, z).g(a, b).h(p, q)
</code>```

is the same thing as

```<code>x = f(x, y, z)
x = g(x, a, b)
x = h(x, p, q)
</code>```

However, if I also use . to show that an attribute belongs to a class I think that will get confusing, so I'm looking for another symbol for that purpose (or another solution).

Currently I am thinking that I should use either the apostrophe - instance'attribute - which shows ownership in a clear way, but means it can't be used for strings, the backtick - instance`attribute - kind of looks like an apostrophe, which is good in the sense it shows ownership, but bad in the sense it could be mistaken for one, and is less commonly typed, and therefore likely to be slower to be typed (and missing from some keyboards).

Alternatively, are there any symbols I could replace the dot used for the syntatic sugar inplace function calling thing with?

答:
First of all, the dot-method and dot-attribute syntax isn't mutually exclusive precisely then when you require parens on method calls. Consider this piece of Java:

class Foo {
  int bar = 1;

  int bar() { return 2; }
}

...
Foo foo = new Foo();
foo.bar;   // the attribute
foo.bar(); // the method
```

<p>Of course, using this language feature can't be recommended. So the real question is how you are going to disambiguate method calls from your “inplace functions”. The probably best way is to use some form of <em>interpolation</em>. Consider this Perl:</p>

<pre class="lang-perl prettyprint-override"><code>my $function = sub {
  my ($object, $arg) = @_;
  return $object + $arg;
};
my $x = 40;
say $x->$function(2); #=> 42
</code>```

where $x->$y(@z) is syntactic sugar for &$y($x, @z). This syntax is orthogonal to method calls which would look like $x->y or $x->y(). Perl can pull this off because variables have a $ prefix.

Using a similar syntax might be recommendable, so you might end up with

```<code>foo.bar;            // attribute
foo.bar();          // method
foo.$bar();         // inplace function
foo.{bar || baz}(); // alternative interpolation marker
</code>```

You are right, this is confusing. Consider carefully what expressiveness you gain by using inplace functions. In the case of Perl, the variable may contain the name of the method, thus allowing data to decide which method gets called, which in contrast to the above syntactic sugar is actually useful.

$foo->bar;
# the same as
my $meth = "bar";
$foo->$meth;
```

<p>Your “inplace methods” overload this with very diferent meaning. It would make more sense for <code>x.$y(z)</code> to mean <code>y(x, z)</code> (as the equivalent Perl). Your example with multiple chains would then become</p>

```x = x.$f(y, z).$g(a, b).$h(p, q)
// the same as
x = h(g(f(x, y, z), a, b), p, q)
```

<p>Note that here the <code>.$</code> apparently has characteristics of a <em>feed operator</em>. In Perl6, these two lines are equivalent:</p>

<pre class="lang-perl prettyprint-override"><code>@input ==> grep { $_ % 3 == 0 } ==> map { $_ * 2 } ==> my @processed;
# the same as
my @processed = map({ $_ * 2 }, grep({ $_ % 3 == 0 }, @input));
</code>```

Summary: come up with a very good reason why you want to invoke functions as if  they were methods, and choose sensible semantics (esp. the auto-assign looks like a bad idea if you've ever programmed functional).

Then, there are various syntactic possibilities to call arbitrary functions on your objects, ranging from “interpolation” x.$y() to operators that emphasize dataflow like ==>.

Title: OOP language design attribute symbol

Body:
First of all, the dot-method and dot-attribute syntax isn't mutually exclusive precisely then when you require parens on method calls. Consider this piece of Java:

class Foo {
  int bar = 1;

  int bar() { return 2; }
}

...
Foo foo = new Foo();
foo.bar;   // the attribute
foo.bar(); // the method

Of course, using this language feature can't be recommended. So the real question is how you are going to disambiguate method calls from your “inplace functions”. The probably best way is to use some form of interpolation. Consider this Perl:

my $function = sub {
  my ($object, $arg) = @_;
  return $object + $arg;
};
my $x = 40;
say $x->$function(2); #=> 42

where $x->$y(@z) is syntactic sugar for &$y($x, @z). This syntax is orthogonal to method calls which would look like $x->y or $x->y(). Perl can pull this off because variables have a $ prefix.

Using a similar syntax might be recommendable, so you might end up with

foo.bar;            // attribute
foo.bar();          // method
foo.$bar();         // inplace function
foo.{bar || baz}(); // alternative interpolation marker

You are right, this is confusing. Consider carefully what expressiveness you gain by using inplace functions. In the case of Perl, the variable may contain the name of the method, thus allowing data to decide which method gets called, which in contrast to the above syntactic sugar is actually useful.

$foo->bar;
# the same as
my $meth = "bar";
$foo->$meth;

Your “inplace methods” overload this with very diferent meaning. It would make more sense for x.$y(z) to mean y(x, z) (as the equivalent Perl). Your example with multiple chains would then become

x = x.$f(y, z).$g(a, b).$h(p, q)
// the same as
x = h(g(f(x, y, z), a, b), p, q)

Note that here the .$ apparently has characteristics of a feed operator. In Perl6, these two lines are equivalent:

@input ==> grep { $_ % 3 == 0 } ==> map { $_ * 2 } ==> my @processed;
# the same as
my @processed = map({ $_ * 2 }, grep({ $_ % 3 == 0 }, @input));

Summary: come up with a very good reason why you want to invoke functions as if  they were methods, and choose sensible semantics (esp. the auto-assign looks like a bad idea if you've ever programmed functional).

Then, there are various syntactic possibilities to call arbitrary functions on your objects, ranging from “interpolation” x.$y() to operators that emphasize dataflow like ==>.


问:
How can I handle clock hands using doubles that suffers at most O(log n) corrupt bits at nth frame of display?
I presently have a clock app that calculates from scratch at every iteration. This means O(1) corrupt bits in my doubles and heavy object creation and deletion as well.

I am wary of running indefinite calculations with doubles or any other floats because O(n) corrupt bits normally accompany every step.

I would like to know if there is an alternate way (in an iOS app) to transform and position clock hands with O(1), or maybe O(log n), corrupt bits after n steps.

In particular, I was wondering what the corruption would be for "At each step, rotate each hand back to the zero position, meaning an affine rotation transformation of -1 * the last rotation the hand received, and then rotate forward by the new angle the hand should have at this step." In Objective-C's floating point arithmetic, is it ever not the case (excluding exceptions like a value indicating a number is corrupt) that x - x != 0.0 exactly? The cases I've seen illustrating floating point corruption bits include Python saying that 1.1 + 1.1 + 1.1 - 3.3 != 0.0; I haven't seen textbook examples of the form x - x != 0.0.

This is not exactly the question of whether a raster image transformed by angle x and then by angle -x is its original self; it may be that the preceding suggestion would work fine for O(1) error on angles but usual corruption in the image drawn and transformed.

What is the minimum "corruption complexity", meaning fewest corrupt bits at end of n calculations, for rendering a clock? Are there O(1) or O(log n) approaches?

Thanks,

答:
For computations like this you really need not care. At least not much.

Just make sure that you don't accumulate the error over too many iterations. Here, too many means something like millions. It takes ages before the error gets close to 0.1%. In in doubt, use double rather than float.

I would like to know if there is an alternate way (in an iOS app) to transform and position clock hands with O(1), or maybe O(log n), corrupt bits after n steps.

Don't think about corruption and bits. There's some numerical error and there are some not exactly simple rules for bounding it. Concerning the absolute error you're safe unless you deal with very large numbers or divide by something close to zero. So you're safe.

is it ever not the case (excluding exceptions like a value indicating a number is corrupt) that x - x != 0.0 exactly?

I've never seen Objective-C, but I'm perfectly sure that x - x == 0.

Python saying that 1.1 + 1.1 + 1.1 - 3.3 != 0.0

Yes, that's fine. Rule 1: Never ever compare two floating point numbers for equality. There's always some error. Rule 2: The error is very small. In this example it's 4.44e-16 (it's using double rather than float). Now imagine what terrible impact this can have on your clock hands.

What is the minimum "corruption complexity", meaning fewest corrupt bits at end of n calculations, for rendering a clock? Are there O(1) or O(log n) approaches?

I guess there's no O(1) approach, unless you can convert it somehow into fixed point arithmetic as otherwise there's always the possibility of the error increasing due to rounding.

I guess, the normal and stupid way (assuming you're doing rotations via matrix multiplications) increases the error like O(n). So after 1e9 iterations you get an error like 4.44e-7. Nothing to worry about.


问:
Is it necessary to use "-" or "+" before every property or method declaration in Interface and why?
I'm new to objective C, I'm following "Objective C 5th Edition Stephen Kochan and I don't have anyone to ask my doubts to. I'm confused with this question:

Q. Is it necessary to use "-" or "+" before every property or method declaration in Interface? What will happen if I don't use "-" or "+" before every property or method declaration in Interface?

答:
A "+" before a method indicates a class method. These methods can only operate on class variables (variables common to all objects of a class), and can be called before an object of this class has been instantiated.

A "-" indicates an instance method. These methods can operate on class and instance variables. They are called on an instance of an object.


问:
Why does the instruction "do" require a "while"?
Since this statement is so common:

while (true) (Java)

or

while (1) (C)

or sometimes

for (;;)

Why is there not a single instruction for this? I could think that an instruction that could do it is just do but do requires a while at the end of the block but it would be more logical to write an infinite loop like this

```<code>do {

//loop forever

}
</code>```

Why not? AFAIK the instruction do always requires a while at the end but if we could use it like above then it would be a clear way to define something like while (true) which I think should not be written like that (or for (;;)).

答:
This is largely because creating a separate command would be unnecessary.  Adding extra, unneeded commands to a programming language is often considered poor design.  Why create a special instruction when one already exists that works?

Your idea of having only one of the "do/while" pair is how it works in other languages, like Python, for instance, since Python doesn't having closing brackets to worry about.

```<code>while True:
    ...
</code>```

It is simply a matter of how any given language is designed.  Remember that programming languages are man-made things - they can take whatever form we, as humans, design them to take.  You could make your own language that follows the principle you desire, if you felt it was important enough.

Body:
This is largely because creating a separate command would be unnecessary.  Adding extra, unneeded commands to a programming language is often considered poor design.  Why create a special instruction when one already exists that works?

Your idea of having only one of the "do/while" pair is how it works in other languages, like Python, for instance, since Python doesn't having closing brackets to worry about.

while True:
    ...

It is simply a matter of how any given language is designed.  Remember that programming languages are man-made things - they can take whatever form we, as humans, design them to take.  You could make your own language that follows the principle you desire, if you felt it was important enough.


问:
What is exactly bug in the requirements?
I've just looked for a formal definition and haven't found one.
The term - "bug in the requirements" was always confusing for me, what does mean exactly?</p>

答:
It means the requirements were wrong, somehow.

missing something critical

conflicting requirements

incorrectly stated requirements

In non-technical language, this is also known as a "mistake" ;)


答:
"A bug in requirements" could refer to one or more of the following (more may exists though...):

A requirement provided by the end-user that conflicts with another requirement or constraint. Example: The user wants to email all customers but does not want the system to collect customer emails.

A requirement provided by the user and not flagged by the business analyst as not feasible for a given project. Example, I want the system to automatically fix addresses of my million customers when the user pushes a button.

The user passes a wrong business fact to the business analyst. Example: A wrong formula to calculate profit.

The analyst captures wrong information or makes false assumptions and considers those as true requirements that need to be implemented.

An incomplete requirement provided to the business analyst that led to a bug in implementation. Example: The user says to the analyst "We only record a customer when a sale is made". A developer getting this requirement may end-up creating a DDL rule that makes the relationship of customer and invoice mandatory such that when an invoice is deleted  the corresponding customer information is also deleted. Unless the developer and business analyst confirm with the user that this required, this searing may be considered as a bug in requirements (and development).

A bug in requirement could occur also when the user and the business analyst miss an entire business function. Example, when the user does not specify security requirement and the business analyst does not ask about this requirement. When such a system is completed, it may not be usable because it is not secure enough.

Title: What is exactly bug in the requirements?

Body:
I've just looked for a formal definition and haven't found one.
The term - "bug in the requirements" was always confusing for me, what does mean exactly?</p>


问:
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?

答: Usually the complexity of project is underestimated.

ContentLicense: CC BY-SA 2.5


问:
Why aren't web frameworks simple, elegant and fun like programming languages?
When I think of pretty much any programming language - like C, C++, PHP, SQL, JavaScript, Python, ActionScript, Haskell, Lua, Lisp, Java, etc - I'm like awesome I would love to develop a computer application using any of those languages.

But when I think of web frameworks(I do mostly PHP) - like Cake, CI, Symfony, Laravel, Zend, Drupal, Joomla, Wordpress, Rails, Django, etc - I'm like god no.

Why aren't there web frameworks that provide me with simple, fun and powerful constructs like a programming language?

答: Ah, but you see that is exactly the problem. Frameworks are not supposed to be Turing complete. They are supposed to be composed of more restricted abstractions that can be composed together to perform a specific set of tasks in a succinct manner. So all those frameworks you mentioned are no fun exactly because they don't provide a restricted set of abstractions. They provide leaky abstractions than in and of themselves compose an abstract machine that is more than likely Turing complete. The concept of "weird machines" is the closest thing I'm thinking of. All those frameworks are "weird machines" for web applications and a "weird machine" is the opposite of what a framework should be.</p>


答:
I think a lot of it has to do with the limitations of the WWW. Specifically, there's no built in way to store state between the server and client. A client requests some data, the server provides it and the connection is closed. As such, all of these web platforms have to put together their own method of keeping state between server calls.

I had to make a small web app once and at the time I'd never done any server/client programming. It took me a few weeks to figure it all out and the hardest part was trying to get my head around keeping track of where the client and server were at.

Will this ever change? I doubt it. It would require a fundamental change in the architecture of the web.

Title: Why aren't web frameworks simple, elegant and fun like programming languages?

Body:
When I think of pretty much any programming language - like C, C++, PHP, SQL, JavaScript, Python, ActionScript, Haskell, Lua, Lisp, Java, etc - I'm like awesome I would love to develop a computer application using any of those languages.

But when I think of web frameworks(I do mostly PHP) - like Cake, CI, Symfony, Laravel, Zend, Drupal, Joomla, Wordpress, Rails, Django, etc - I'm like god no.

Why aren't there web frameworks that provide me with simple, fun and powerful constructs like a programming language?


答:
I had this question for years too, even though I am on Python side. I do not have a single explanation for this phenomenon, but here are my thoughts on the subject:

Web-frameworks must deal with XMLish markup language - HTML, part of the current web-triad HTML-CSS-JavaScript in a client-server way. It means three languages, which interact with each other, a browser DOM and execution model (and security model). In effect, each piece of functionality (a "module") should have its code in all three languages. To add to this, jQuery's selector language is becoming one more language to care of.

HTML+CSS lacks intuiitive and mathematically sound model for placing objects. Even Tcl/Tk is IMHO better at defining geometry managers. This prevents programmer from defining HTML rendering in strict terms and rely on the luck instead: "maybe this div will work most of the time in most of the browsers". There are some positive developments on this side though, for example, HTML5 and Twitter Bootstrap.

Web technology has grown organically and frameworks has grown with it, so their shape is not necessary elegant. It means programmer should remember the APIs, which are suboptimal, going to be deprecated, and so on

Web browsers do still have slight incompatibilities, and it adds unnecessary complexity to web-frameworks

The overall architecture is a mess. It's a split-thinking of back-end and frontend, which are tied together with request/response on backend side and data-driven rendering on front-end side. Order of execution is not very well-defined (synchronisation requires effort) and placing styles, scripts to proper slots is required (almost all js scripts need to be placed before the end of body tag, and so on). Caching is yet another aspect, which spans from backend to proxy(ies) to front-end. And I do not even mention form-handling!

Web-framework necessarily deals with most of these complexities by adding a lot of concepts and processing pipes.

In web industry labour is usually divided between graphics designer, web designer/web programmer and backend programmer as a minimum set of roles. The former two do not necessarily have programming skills, so they need a different abstractions and tools, and frameworks should facilitate them too

In summary, web frameworks try to abstract a lot of complexity (growing complex themselves), but it is very hard to achieve due to rapid development of standards and other moving parts. Programming languages are much more mature, because it is usually not a problem not to use new features.

I think, making convenient web-framework will be possible only after GUI standards will be in place (covering different modes of operation, such as mobile devices) and the underlying technologies will be stable enough.

Web-frameworks lack simple constructs because there are no such things in the web-technology domain. Lower-level abstractions necessarily leak to higher level.


答:
Generally speaking, the causes might be multiple:

The abstraction gap is larger in the framework case. A modern procedural/OOP language provides abstraction over a machine but keeps some machine constructs (such as assigning a variable some data / writing some data in a memory unit, or calling a procedure etc.); the gap is not that big, while a framework tries to provide abstraction for developing a web application which operates with much more concepts.

Frameworks can be more complex from the programmer's point of view; this is like a consequence of the first point. A programming language is rather simple, it has simple constructs (if, for, variables, procedures etc.). Also the standard library abstracts simple things like writing to IO, or using collections. The standard library it is also very modularized, with few or no connection between on module with another; you do not need to know IO to use collections or vice-versa. To be noted that if some parts of the standard library are rather complex, they are placed in a mini-framework (e.g. Java Collections Framework or Executors framework). In the framework case you kind of need to know the whole flow, all the parts in order to use the framework at it's full strength. Also, a a framework is an already built application; a programmer only needs to customize certain parts but s/he needs to know the application first, what it does.

Not so many resources are put in a framework as in a programming language. I believe this does not need any explaining.


答:
Well there might be two large cases:

The requirements do not represent what exactly the business owner wants; they do not model the business flow.

The requirements are not consistent; this can, or cannot be a consequence of 1.


问:
Is fewer lines of code always better?
Which of these programming styles is better?

```<code>var result = methodOne(methodTwo(a, methodThree(b)), c, d);
</code>```

or

```<code>var result3 = methodThree(b);
var result2 = methodTwo(a, result3);
var result = methodOne(result2, c, d);
</code>```

答:
Spelling things out can help not only with readability but also writability.

This might seem like a silly interview question but I was asked once in an interview to write a function to rotate an image 90 degrees. The source and destination are provided (you don't need to do any memory allocation) and the width and height of the source. Yes, it's an easy problem. I suggest you do it before continuing and see if you have any trouble.

.

Did you? Did you test it? Since I was asked the question in an interview I used the question in interviews as well and what I found was many programmers would get confused. They'd write code like this

```<code> void Rotate90(const Pixel* src, Pixel* dst, int width, int height)
 {
    for (int y = 0; y < height; ++y)
    {
      for (int x = 0; x < width; ++x)
      {
         dst[???] = src[???];
</code>```

And that's where they would get stuck. They would spend sometimes as much as 20 minutes on the whiteboard trying to figure out what goes in those ??? area. Lots of times they'd think they have the answer and write things like

```<code>         dst[x * width + (height - 1 - y)] = src[y * width + x];
</code>```

getting the fact that using width with dst is wrong. Or often they'd get the x and y mixed up in one side or the other.

The problem is that x, y, width, and height all swap meaning because when rotating 90 degrees the destination becomes width tall and height wide which makes referring to those variables confusing. I always wished a programmer would add some more variables to help make it clearer for themselves, like this

```<code> void Rotate90(const Pixel* src, Pixel* dst, int src_width, int src_height)
 {
   int dst_width = src_height;
   int dst_height = src_width;

   for (int src_y = 0; src_y < src_height; ++src_y)
   {
     for (int src_x = 0; src_y < src_width; ++src_x)
     {
       int dst_x = src_height - src_y - 1;
       int dst_y = src_x;
       dst[dst_y * dst_width + dst_x] = src[src_y * src_width + src_x];
     }
   }
 }
</code>```

It seemed to me breaking things out into their explicit meanings would make it far easier to write the code and far easier to avoid mistakes. I felt like if I saw a programmer do this I'd think of them as wise and rate them higher.

Yes there are a few optimizations you can make. That's not the point. Yes, the math inside the last statement could also be broken out into separate lines. That would be fine as well. The point is, adding more lines made it easier to understand for the person writing the code, not just a person reading it later. In this case because the meaning of x, y, width and height are different in relation to dst vs src making separate variables for each makes the code far clearer to read AND write.

Continuing...similarly it's often useful to be able to inspect values before a function is called, especially if it's a function in a library or the system that you can't step into. If you write code like this

```<code>ctx.lineTo(x + Math.cos(angle) * radius, y + Math.sin(angle) * radius);
</code>```

vs this

```<code>var circleX = x + Math.cos(angle) * radius;
var circleY = y + Math.sin(angle) * radius;
ctx.lineTo(circleX, circleY);
</code>```

In the second style you can now stop the debugger at the ctx.lineTo line and inspect circleX and circleY. You might find they are NaN which would probably get you to check that x, angle, and radius are actually the correct names, something you wouldn't be able to do in the debugger. ("strict" mode probably catches that). It also allows you to easy log the values

```<code>console.log("cx: " + circleX = ", cy: " + circleY);
</code>```

Yet another example,

```<code>class Person
{
public:
   ...
   const String& name() const { return m_name; }
   int age() const { return m_age; }

private:
   string m_name;
   int m_age;
};
</code>```

vs

```<code>class Person
{
public:
   ...
   const String& name() const
   {
     return m_name;
   }

   int age() const
   {
     return m_age;
   }

private:
   string m_name;
   int m_age;
};
</code>```

I know some of you will scream at this example because your personal style wants getters and setters to be 1 line but hear me out ... when debugging, depending on the debugger, in the first style if you put a breakpoint on age or name the debugger will not be able to inspect this nor m_age nor m_name so you'll have no way to checking before the function returns what it's going to return or what object it's referencing. In the second style you can put breakpoints on the return lines and you'll be able to inspect everything.

The point of this answer is that more lines is often not only good for readability. It's also often good for writability and for debugging.

Title: Is fewer lines of code always better?

Body:
Spelling things out can help not only with readability but also writability.

This might seem like a silly interview question but I was asked once in an interview to write a function to rotate an image 90 degrees. The source and destination are provided (you don't need to do any memory allocation) and the width and height of the source. Yes, it's an easy problem. I suggest you do it before continuing and see if you have any trouble.

.

Did you? Did you test it? Since I was asked the question in an interview I used the question in interviews as well and what I found was many programmers would get confused. They'd write code like this

 void Rotate90(const Pixel* src, Pixel* dst, int width, int height)
 {
    for (int y = 0; y < height; ++y)
    {
      for (int x = 0; x < width; ++x)
      {
         dst[???] = src[???];

And that's where they would get stuck. They would spend sometimes as much as 20 minutes on the whiteboard trying to figure out what goes in those ??? area. Lots of times they'd think they have the answer and write things like

         dst[x * width + (height - 1 - y)] = src[y * width + x];

getting the fact that using width with dst is wrong. Or often they'd get the x and y mixed up in one side or the other.

The problem is that x, y, width, and height all swap meaning because when rotating 90 degrees the destination becomes width tall and height wide which makes referring to those variables confusing. I always wished a programmer would add some more variables to help make it clearer for themselves, like this

 void Rotate90(const Pixel* src, Pixel* dst, int src_width, int src_height)
 {
   int dst_width = src_height;
   int dst_height = src_width;

   for (int src_y = 0; src_y < src_height; ++src_y)
   {
     for (int src_x = 0; src_y < src_width; ++src_x)
     {
       int dst_x = src_height - src_y - 1;
       int dst_y = src_x;
       dst[dst_y * dst_width + dst_x] = src[src_y * src_width + src_x];
     }
   }
 }

It seemed to me breaking things out into their explicit meanings would make it far easier to write the code and far easier to avoid mistakes. I felt like if I saw a programmer do this I'd think of them as wise and rate them higher.

Yes there are a few optimizations you can make. That's not the point. Yes, the math inside the last statement could also be broken out into separate lines. That would be fine as well. The point is, adding more lines made it easier to understand for the person writing the code, not just a person reading it later. In this case because the meaning of x, y, width and height are different in relation to dst vs src making separate variables for each makes the code far clearer to read AND write.

Continuing...similarly it's often useful to be able to inspect values before a function is called, especially if it's a function in a library or the system that you can't step into. If you write code like this

ctx.lineTo(x + Math.cos(angle) * radius, y + Math.sin(angle) * radius);

vs this

var circleX = x + Math.cos(angle) * radius;
var circleY = y + Math.sin(angle) * radius;
ctx.lineTo(circleX, circleY);

In the second style you can now stop the debugger at the ctx.lineTo line and inspect circleX and circleY. You might find they are NaN which would probably get you to check that x, angle, and radius are actually the correct names, something you wouldn't be able to do in the debugger. ("strict" mode probably catches that). It also allows you to easy log the values

console.log("cx: " + circleX = ", cy: " + circleY);

Yet another example,

class Person
{
public:
   ...
   const String& name() const { return m_name; }
   int age() const { return m_age; }

private:
   string m_name;
   int m_age;
};

vs

class Person
{
public:
   ...
   const String& name() const
   {
     return m_name;
   }

   int age() const
   {
     return m_age;
   }

private:
   string m_name;
   int m_age;
};

I know some of you will scream at this example because your personal style wants getters and setters to be 1 line but hear me out ... when debugging, depending on the debugger, in the first style if you put a breakpoint on age or name the debugger will not be able to inspect this nor m_age nor m_name so you'll have no way to checking before the function returns what it's going to return or what object it's referencing. In the second style you can put breakpoints on the return lines and you'll be able to inspect everything.

The point of this answer is that more lines is often not only good for readability. It's also often good for writability and for debugging.


答:
Programming languages are still languages, and when translating code from English to programming language X, you may have to change some idioms, reorder words, sentences, or sometimes include unpronounceable curly braces…

When you want an infinite loop, the while (true) or its equivalents can be used. Without good reasons, no language designer will add yet another keyword just for infinite loops.

Your idea that do { ... } always implies a trailing while ... doesn't hold up. In Ruby, do starts a code block, and in Perl it allows you to use a code block on expression level:

# read a whole file at once
my $file_contents = do {
  local $/;
  open my $fh, "<", $filename or die "Can't open $filename: $!";
  <$fh>;
};
```

<p>Because <code>do</code> is always an expression, various other statement modifers may be used as well (<code>if</code>, <code>unless</code>, and special-cased keywords to evaluate the block once before testing the condition: <code>while</code> and <code>until</code>).</p>

<p>Perl6 is interesting here because it renames the C-style <code>for</code> to the <code>loop</code> keyword. The various statements like initialization are optional, so one can write:</p>

```loop {
  say "hi";
}
```

… which is the same as say "hi" while True.

Just use while (true) – everyone will understand that. The for(;;) is also a widely-understood idiom. If you are using a language with a preprocessor, you could also do evil stuff like #define forever for(;;), but that reduces maintainability.

Title: Why does the instruction "do" require a "while"?

Body:
Since this statement is so common:

while (true) (Java)

or

while (1) (C)

or sometimes

for (;;)

Why is there not a single instruction for this? I could think that an instruction that could do it is just do but do requires a while at the end of the block but it would be more logical to write an infinite loop like this

```<code>do {

//loop forever

}
</code>```

Why not? AFAIK the instruction do always requires a while at the end but if we could use it like above then it would be a clear way to define something like while (true) which I think should not be written like that (or for (;;)).

Body:
Programming languages are still languages, and when translating code from English to programming language X, you may have to change some idioms, reorder words, sentences, or sometimes include unpronounceable curly braces…

When you want an infinite loop, the while (true) or its equivalents can be used. Without good reasons, no language designer will add yet another keyword just for infinite loops.

Your idea that do { ... } always implies a trailing while ... doesn't hold up. In Ruby, do starts a code block, and in Perl it allows you to use a code block on expression level:

# read a whole file at once
my $file_contents = do {
  local $/;
  open my $fh, "<", $filename or die "Can't open $filename: $!";
  <$fh>;
};

Because do is always an expression, various other statement modifers may be used as well (if, unless, and special-cased keywords to evaluate the block once before testing the condition: while and until).

Perl6 is interesting here because it renames the C-style for to the loop keyword. The various statements like initialization are optional, so one can write:

loop {
  say "hi";
}

… which is the same as say "hi" while True.

Just use while (true) – everyone will understand that. The for(;;) is also a widely-understood idiom. If you are using a language with a preprocessor, you could also do evil stuff like #define forever for(;;), but that reduces maintainability.


答:
I would say that do while is more explicit than just do. In programming it's often beneficial to be explicit. This translates into code that is easier to read. With the proposed do loop the while(true) portion or condition is still implied.

So to sum it all up I'd say it's because most languages are designed to be explicit and readable.


问:
Interview for job that uses skills you have no experience with?
I am currently employed as a software developer using C# and C++. However, I want to find a new job for personal reasons and applied for a job ad that listed PHP, CSS, and Javascript as the skills the company is looking for. I am interested in learning about PHP, CSS, Javascript. That company wants to interview me. However, I have very little experience with those so I don't know how to prepare. Is it likely that I won't even be asked questions about PHP, CSS, Javascript? What kinds of technical questions do you guys think I will be asked? To succeed, I just need to demonstrate that I am really eager to learn PHP, CSS, Javascript?</p>

答:
My answer looks at the broader aspects of your question - namely, how do you apply for a job where your current programming languages don't match what's required.

Be honest with the prospective employer and let them know what your skill level is in those languages which can range from nothing to hobbyist to professional experience.

You need to demonstrate how your skills in other languages would carry over to the new languages.

You need to start studying up on the new languages now and as far in advance of your potential interview.  Don't expect your future employer to train you at their expense.  There are many resources available to help with this.

As far as specific questions or if you have a chance at this interview, I don't know and the community here doesn't know.  A lot of that will come down to the particular job and how much preparation you put in.


答:
I would assume that language designers care somewhat about helping developers write accurate code. A language may prefer to not introduce a construct that leads to an infinite loop without the developer explicitly request it. A language like REXX take this concept further and introduces a forever loop as in:

```<code>do forever
...
end
</code>```

So, to answer your question the reasons may be:

To help developers write better code.

To be similar to other popular languages.

To use a single construct instead of several.

Body:
I would assume that language designers care somewhat about helping developers write accurate code. A language may prefer to not introduce a construct that leads to an infinite loop without the developer explicitly request it. A language like REXX take this concept further and introduces a forever loop as in:

do forever
...
end

So, to answer your question the reasons may be:

To help developers write better code.

To be similar to other popular languages.

To use a single construct instead of several.


问:
How do I limit the resources available to a program?
I'm delving into multi-threaded programming with Java, but I'm finding it hard to test my program for bugs. My computer simply has too many resources and cores, making it hard to see how my program acts under stress.

Is there any way to limit the resources available to my program? It seems ridiculous that my only option right now is to open another application and render HD video in order to starve out the application I'm debugging.

答: An easy way to limit resources is setting up a virtual machine with limited resources.</p>


问:
In Android, is there any reason to set up a content provider for a local database?
I have an android application with a custom content provider set up to load data asychonously. The database is a local file so I'm not sure if I needed to set up a content provider at all. Sometimes I just need to do something like get a name back from a short list by id. Is it ok to mix the content provider pattern with simple direct database calls, i.e open, query, close type of code blocks?</p>

答:
from http://developer.android.com/guide/topics/providers/content-providers.html

You don't need to develop your own provider if you don't intend to
  share your data with other applications. However, you do need your own
  provider to provide custom search suggestions in your own application.
  You also need your own provider if you want to copy and paste complex
  data or files from your application to other applications.


问:
How important it is to fix memory leaks?
I found by Valgring that some GTK+ programs leaks memory. How important it is to fix those leaks? I mean, often those programs works very well but on the other hand, one can never be sure if one wants to copy part of the leaking code to some other program. And I'm not sure if the idea of GTK+-programs is to work fast and therefore there are leaks.

So if I sometimes find a memory leak in an open source program, should I fix it or are there for example efficiency issues and therefore programmers original idea was to write some small leaking code?

答:
For short running programs memory leaks are not as important; the OS will reclaim everything on termination, but they may cause other resources to not be released.

However short running is relative, a leak can spiral out of control in a few hours or stack up for weeks unnoticed.

My advice is to file a bug in the tracker with a proposed fix, if the lead cares he will fix it.

The type of leak is also important. It's possible that the allocation that leaks is a one-off allocation where the dev deliberately relied on the OS for the cleanup. These will give a false positive on valgrind.


答:
You could invest in a Raspberry Pi.  The Model A costs $25 and the Model B $35.

Model A has 256MB RAM, one USB port and no Ethernet (network connection). Model B  has 512MB RAM, 2 USB ports and an Ethernet port.  They contain a ARM1176JZFS, with floating point, running at 700Mhz, and a Videocore 4 GPU.

Your resources most certainly will be limited with this, except for graphics power.

Title: How do I limit the resources available to a program?

Body:
I'm delving into multi-threaded programming with Java, but I'm finding it hard to test my program for bugs. My computer simply has too many resources and cores, making it hard to see how my program acts under stress.

Is there any way to limit the resources available to my program? It seems ridiculous that my only option right now is to open another application and render HD video in order to starve out the application I'm debugging.


答: Type java -X to get a whole bunch of command line options that affect available resources on the virtual machine itself.  On Linux, you can also use ulimit to limit the resources for any process, which is mostly used to protect other users on multi-user systems.  I don't know if there's something equivalent for windows.  Try playing around with the task manager.


问:
Using Functions for Never-Repeated Code
What are some best practices for using functions to break up large blocks of code into discrete chunks of logic when those functions are only ever going to be used once within the lifetime of a function?

The canonical example for web development is the initialization of a home page. When the page loads, you might do something like check some credentials and authentication, make an API call to get some data, and parse that data. Naturally, this could all be written in a procedural format within a large function called initialize(). None of the logic will foreseeably be re-used anywhere else within the program.

When I'm confronted with such scenarios, my initial instinct is to divide each piece of logic into a discrete function and simply call the functions from an initialize() function, with a few lines of code within initialize() performing some clean up and tear down duties. So I'd have something like an authenticate(), get_data(), and parse_data() function, as well as perhaps a few helper functions for the main functions.

In my opinion, that makes the code easier to understand from a high level, makes unit tests more meaningful, and helps organize your thinking as you're writing your code.

However, I recently clashed with a guy who essentially thinks the opposite. He feels too many functions lead to "annoying jumping around", functions should never be used if code is not going to be re-used, and that the over-use of functions/classes/modules/any kind of modularity amounts to over-engineering. I was put off by his argument and felt that it leads to the shitty procedural PHP that so often  makes web development a nightmare, but perhaps there is some validity in what he's saying?

答:
Executive Summary: He's an idiot.  There's no validity to what he's saying.

Code is ALWAYS modified eventually, it is ALWAYS "maintained" eventually, it is ALWAYS reused eventually.

It is always tested and retested.

You always want to design your code for testability and reusability, because, sooner or later, someone is going to need to test it and reuse it, even over your most vociferous objections.

Yes, you can make an over-engineering argument.  The problem is that no two engineers will ever agree on what constitutes over-engineering, and over-engineering something generally gives better results than under-engineering it.

Title: Using Functions for Never-Repeated Code


问:
Why doesn't Git daemon start in the background?
Just as in the title, why doesn't git daemon start the service in the background, since it's a "daemon", being a background process? I know that I can start it in the background using git daemon &, but I'm just wondering about the philosophical reason for this decision.

答:
The simplest answer is likely consistency.  All of the other git subcommands are intended to be invoked from the shell.  To have one subcommand work differently may surprise some people.  Beyond this, its just a guess that may be found somewhere in the depths of the the git@vger.kernel.org mailing list, the comments on the code, the commits for the revisions, or the mind if Linus (in likely order of accessibility).

There are options for the git daemon subcommand that make it work better than appending an & after the command.  From the kernel.org documentation (note the examples of the starting options at the end):

--inetd
  Have the server run as an inetd service. Implies --syslog. Incompatible with --detach, --port, --listen, --user and --group options.

--detach Detach from the shell. Implies --syslog.

One might also want to look at the git-daemon tags on serverfault and stackoverflow for related setup help.


答:
It is better to decompose into smaller functions.  If these functions are named clearly, it will make the code much more readable and it will make debugging much easier as well. Think about what the stack trace would look like using this more modular approach vs. the all in one function approach. The fact that these functions are only called in one place doesn't reduce any of these benefits.

Each function should do one thing and do that one thing well.  That one thing may include combining the results of some of the functions into a simple interface for the consumer of the functionality.  Ultimately, this approach will lead to more compact functions  which will make your code much easier to understand.  Much worse than having to jump around from one function definition to another (which your IDE should facilitate) is having to scroll through screen after screen of code within one method and trying to keep track of what exactly is going on in your head.

Bob Martin has a great post about this with a detailed example.

Title: Using Functions for Never-Repeated Code

Body:
What are some best practices for using functions to break up large blocks of code into discrete chunks of logic when those functions are only ever going to be used once within the lifetime of a function?

The canonical example for web development is the initialization of a home page. When the page loads, you might do something like check some credentials and authentication, make an API call to get some data, and parse that data. Naturally, this could all be written in a procedural format within a large function called initialize(). None of the logic will foreseeably be re-used anywhere else within the program.

When I'm confronted with such scenarios, my initial instinct is to divide each piece of logic into a discrete function and simply call the functions from an initialize() function, with a few lines of code within initialize() performing some clean up and tear down duties. So I'd have something like an authenticate(), get_data(), and parse_data() function, as well as perhaps a few helper functions for the main functions.

In my opinion, that makes the code easier to understand from a high level, makes unit tests more meaningful, and helps organize your thinking as you're writing your code.

However, I recently clashed with a guy who essentially thinks the opposite. He feels too many functions lead to "annoying jumping around", functions should never be used if code is not going to be re-used, and that the over-use of functions/classes/modules/any kind of modularity amounts to over-engineering. I was put off by his argument and felt that it leads to the shitty procedural PHP that so often  makes web development a nightmare, but perhaps there is some validity in what he's saying?


问:
Is it possible to do decent spam filtering without scanning the contents of emails?
I don't have much knowledge of the subject but as I know, when servers receive an email they have two sources of data to classify it as SPAM or not. The contents of the message (subject + body) and the metadata that goes with it (from who / to who / server that sent the message, etc).

I know you can do basic filtering by blacklisting emails list and other sorts of metadata. But is it possible to do decent spam filtering without checking the contents of a message? Defining 'check the contents' as using any function that relies on data found on the body/subject of the message to classify it as spam or not spam.

Edit: The reason I ask for this because of the "scroogled" campaign where Microsoft accuses Google of scanning the contents of emails for advertising purposes, and I think that they do the same for spam prevention purposes. So I asked them and they said:

We have tools and system set up to filter spam emails to and from
  Outlook.com email accounts. However, we are not allowed to disclose
  how these spam filters work for security purposes.

ME: So can you assure me that no content from my personal email is
  being analysed and cross referenced with other data in any way?

...In response to your question, its a yes, we can assure you that.

答:
I looked at the link you supplied - what you got was a couple of 'canned' answers, neither of which actually address your question.  It's one of the demons of outsourcing that agents get rewarded for giving something that looks plausible to a non-techy even if it's completely unrelated to the question that was asked.

Without a direct quote or link to an advert it's hard to know exactly which claim you're trying to verify with the support team.

Microsoft absolutely do algorithmically check incoming and outgoing message content on outlook/hotmail to check for spam and malware, but they don't use your email to build a profile of you for targeting advertisements (some of which now take the form of emails directly in your mailbox) which gmail does and always has (and has always been open about.)  The point of the campaign was to point it out to people who use gmail are not have been aware of that practice and that many people disapprove of it in the hope they'd switch to Outlook/Hotmail.

There are also rumours that google employees regularly read mail to help tune their algorithms (as they do with web pages) but google deny this.

http://www.scroogled.com/mail/OurPosition says..

Outlook.com only scans the contents of your email to help protect you and display, categorize, and sort your mail appropriately. Just like the postal service sorts and scans mail and packages for dangerous explosives and biohazards, Outlook.com scans your mail to help prevent spam, gray mail, phishing scams, viruses, malware, and other dangers and annoyances.


问:
Branching Strategy for Test Environment
We will be starting a new project this month. The project will be 1 year and production deployment will only occur towards the end of the project.

We will be doing iterative development (1 month per iteration), so this means we will drop features to Test environment at the end of each iteration for QA testing.

Our branching strategy is:

Trunk - All development will happen on trunk.

Feature Branch -  Branches off trunk will be created on a per need basis for development of large features which could potentially be breaking if done on trunk

QA Release Branches - At the end of each iteration, a branch of trunk will be created. This branch (which includes a version number) will be released to Test environment. All critical and blocking bugs found in this version will be fixed on this branch and fixes will have to be merged to trunk. Non-critical/trivial bugs will not be addressed on the QA release branch and will only be fixed in trunk since the QA release branch will be thrown away after the end of the next iteration where a new release branch will be created off trunk.

Production Branch - this will be the latest QA release branch at the end of the project. This will be tagged and all production bug fixes will be on this branch and merged to trunk.

Is this a correct branching strategy? Is there anything else that we've missed to consider?

We're using SVN.

答:
From what you state:

Your code resides in trunk

For each major feature / enhancement - you cut a branch off trunk - develop and then provide to QA to test

All major and important bugs get fixed in this 'QA branch'

Post QA you 'trunk' the code from this branch back to trunk

This sounds pretty ok strategy to me

we have been regularly branching , merging and trunking  into SVN using eclipse svn plugin or tortoise

Looks good to me

Title: Branching Strategy for Test Environment


问:
From an execution perspective is an interpreter the same as the JVM / or the .net Framework
I've recently started two introductory level courses - one using Python, the other Java.

I've read the answers to this Question but still have difficulty understanding how each ends up with machine code and what the main differences between the two models are:

Is an interpreter doing the same job as something like the JVM, just without the
byte-code?

For python is the interpreter taking the high-level code
and translating it into machine code?

The Java virtual machine needs to be installed on a machine for a java program to run on it - is it similar for python - if the interpreter is installed on the target machine then the python program will run?

Is the JVM (& .net framework) effectively byte-code interpreters?

答:
The distinction between interpreted code and compiled code used to be more clear when I was first learning.

The first programming language that I learned was an early version of Microsoft BASIC which was text and it was interpreted by an interpreter.

Then, when I went to college, I learned to program in Pascal and C which are both compiled languages that compile down to machine code and don't need anything like a virtual machine to run.

Also, in college, I learned Unix shell-scripting which is text and is interpreted.

The distintion used to be more clear.

I think of Java and Python as both being compiled and interpreted.  I see Python as being the right tool for the job when you want to be able to change something without having to recompile.

Java is good because you when you compile it, more of the bugs are found at compile-time.

I believe that both Python and Java are both compiled and interpreted.  I see Java as being "more compiled" because more bugs are found at compile-time.


问:
Is QA or testing a lot of overhead or not utilized properly?
From my experiences in software development (Eg. Waterfall ) I see it that most of the times it is the development team that sweats it out with the BA folk to get requirement clarity. The development folks then slog it out to meet deliverable deadlines.

Where is the QA - they might be free - but will only hitch onto the bandwagon after the code is delivered.

Then starts a slew of communication regarding what is a defect and what is a requirement change / clarity needed. From QA perspective - log a defect / bug / issue - and then its the development team responsibility to go figure it out.

Clearly this is problematic and affects my opinion of the role and value that QA brings to the table in the Waterfall model.

The question is if Agile is actually geared towards reducing this 'waste' by getting testing involved early in the development so that issues get eliminated at the start?  If so then what aspects of Agile help solve some of the above problems I have experienced?

答:
Testing is to QA what and Ambulance is to Healthcare. The idea is to focus on what can be done within the latter so the former is not needed. QA should be as busy at the start of the process as anyone, if not busier. The sooner they get involved in establishing how and how much quality will be achieved, the less testing will be needed, and the few issues will come from testing.

Agile is not a silver bullet to slay those problematic, pesky little testers with. Learn to show some respect, or anything you do is doomed to fail. Arguably the only reason testing is bothering you is that you did not do your job. By not doing you job, you have made a lot more work for them. If you think you have grounds to complain about testers finding defects, think long and hard what part you played in that little problem, and how much work you have created for them. (Rant Over)

So how to fix it - Agile, Waterfall whatever does not matter - just talk to each other. If you are unclear on requirements, make sure you ask the BA and the testers. Ask the testers how they expect to test each feature. Ask the testers for access to their test plans, and ensure your software passes the plans. Don't throw you product over a fence, hand it over in a well wrapped package. If anyone is unclear on any of this, go back to the BA till you know what is needed and how each team will achieve the outcome.