答:
I use javascript mainly for everything because I like it and my daily job is heavily influenced by it. Now what do I mean by saying everything:

Custom tools(with node-webkit you are able to bring desktop experience)

Custom scripts to run on my machine via node.js

Mobile apps. I don't even need PhoneGap as I am pretty comfortable with visiting URL.

Backend for my web apps with node.js . I can access filesystem and databases so what am I lacking? Well.. A mature enough framework and I hope this will be fixed in the feature.

Well of course fancy jQuery stuff for websites.

Misc:

I solve all the coding katas with javascript(project euler, codewars)

I implement algorithms I am interested in Javascript

3D experiments with three.js and webgl.

Someone will beat me because of performance but I want to satisfy performance of writing code and understanding a topic instead of making it run blazingly fast.

And as for desktop experience, for me working with HTML and CSS for user interface is the most pleasant way.

Title: Can JavaScript be used as a general scripting language?

Body:
I've used JavaScript and some frameworks (jQuery, Prototype, some node.js) for client-side web programming, but never on the desktop, where I do most of my scripting work in either Python or Bash.

But IMHO, JavaScript would make a great scripting language if used outside of the browser. Has anyone tried this? Can JavaScript be an adequate replacement for Python/Perl/Bash for quick and dirty scripting tasks?


问:
What's that rule where you aren't supposed to give visibility into an object called?
I forget the name of it but there's a rule that you aren't supposed to allow visibility into an objects inner makeup.  It has to do with not allowing more than one dot in the implementation like this for example:</p>

```<code>return world = foo.bar.hello.world();
</code>```

答:
It's part of the Law of Demeter. http://en.wikipedia.org/wiki/Law_of_Demeter

The Law of Demeter (LoD) or principle of least knowledge is a design guideline for developing software, particularly object-oriented programs. In its general form, the LoD is a specific case of loose coupling. The guideline was proposed at Northeastern University towards the end of 1987, and can be succinctly summarized in one of the following ways:[1]

Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.

Each unit should only talk to its friends; don't talk to strangers.

Only talk to your immediate friends.

The fundamental notion is that a given object should assume as little as possible about the structure or properties of anything else (including its subcomponents), in accordance with the principle of "information hiding"...

ContentLicense: CC BY-SA 3.0


问:
Using Type Parameter (or not)
Effective Java provides 2 ways to implement swap:

```<code>// Two possible declarations for the swap method
public static <E> void swap(List<E> list, int i, int j);
public static void swap(List<?> list, int i, int j);
</code>```

Then, Mr. Bloch says:

Which of these two declarations is preferable, and why? In a public
  API, the second is better because it's simpler. You pass in a list—any
  list—and the method swaps the indexed elements. There is no type
  parameter to worry about. As a rule, if a type parameter appears only
  once in a method declaration, replace it with a wildcard.

It appears that swapNoWildCard could be used rather than the swap and swapHelper method. Mr. Bloch explains the reasoning for using the 2nd signature above.

```<code>public static <E> void swapNoWildcard(List<E> list, int i, int j) {
    E e = list.set(j, list.get(i));
    list.set(i, e);
}

public static void swap(List<?> list, int i, int j) {
    swapHelper(list, i, j);
}

private static <E> void swapHelper(List<E> list, int i, int j) {
    E e = list.set(j, list.get(i));
    list.set(i, e);
}
</code>```

However, is this debatable given the fact that swapNoWildCard is almost half the # of lines of code compared to implementing the other 2 methods?

Why is it so useful to leave out the type parameter?

答:
In good software design what you want, or better yet in an idealized world you must, have an interface which communicates intent. Taking away the type parameter of the List expressed that intent clearly. You're telling the caller "I'm only interested in acting on a List and nothing more." This is why the second is better than the first.

As an aside, the reason that the second method requires two function calls is that Java does not have type inference so you are forced to declare an E to capture one of the swapped values.

Title: Using Type Parameter (or not)


问:
Programming conundrum - most efficient path
I have a non-language-specific problem which I'm having trouble finding a workable answer for.

I have a 10x10 grid containing integer values from 1-10.
Each value represents the cost of travelling across that square, moving north, east, south or west (cost is incurred while stepping off a square rather than onto it).

I need to find a method to navigate the cheapest path from a starting square to an end point.

I was using a recursive javascript function whereby each square could ask an adjacent square what the cost was if the journey went that way; the square asked would then ask its neighbours etc. until the cheapest route was found.
However, as might be expected this takes far too long, even if each square was marked as busy so it couldn't be asked again (in order to prevent circular routes which might never end).

I'm sure this must have been done before. Does anyone have a method they feel would work?

Thanks for your help :)

答:
Solved problem. I suggest the following references.

http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm

http://en.wikipedia.org/wiki/A*_search_algorithm

https://github.com/bgrins/javascript-astar


问:
An alternative to an array of functions?
I'm programming an app (php) which requires a very long list of similar yet different functions, which are being called by a set of keys:

```<code>$functions = [
    "do this" => function() {
        // does this
    },
    "do that" => function() {
        // does that
    }
]
etc.
</code>```

I've chosen to place the similar functions in an array because they are not similar enough - getting the same result with one big function which is full of conditional statements isn't gonna work. And I do need to be able to call them only by key, for example:

```<code>$program = ["do this", "do that", "do this"];
foreach ($program as $k => $v) {
    $functions[$v]();
}
</code>```

Thing is this functions-array structure is causing many problems, for example I'm having a hard time calling one array function from within another array function, e.g. this doesn't work:

```<code>"do that" => function() {
    $functions["do this"]();
}
</code>```

nor this:

```<code>"do that" => function() {
    global $functions;
    $functions["do this"]();
}
</code>```

or this:

```<code>"do that" => function($functions) {
    $functions["do this"]();
}

$functions["do that"]($functions);
</code>```

I guess I could have one giant function with a long switch statement:

```<code>function similar_functions($key) {
    switch ($key) {
        case "do this":
            // does this
        break;
        case "do that":
            // does that
        break;
    }
}
</code>```

But that doens't really seem like good practice. Or maybe it is?

So, what are my alternatives? Should I go with the switch structure? Or is there another, better solution?

答:
First of all, according to the DRY principle, you should try and make your functions even more similar, so they can share as much code as possible. This will make managing your codebase quite easy, which cannot be said about number of "similar yet different" functions.

The possible solution to your problem is to enclose all your functions in a class and make them publicly callable given only a name. The cleanest way to do it in your situation is to define method call, which will then call appropriate function, found using __get magic method. It's pretty and it's safe (well, depending on the implementation).


问:
Backend development philosophy
I feel kind of lost in this backend development process I am attempting right now. Most of the usual development practices I use while developing client-side applications don't apply here... Let me provide some context.

The debugging process

While developing a client side application (iOS, Java desktop app, or whatever), it is easy to quickly setup the project on your favorite IDE, get it running on your machine or a testing device, and debug the hell out of it as much as you like.

On the other hand, it's not as trivial to hook a debugger to your backend code, and especially if it is python code running on Google App Engine (GAE). That's what I am using, and ... yeah. Linters and all help A LOT, but still, semantic issues cannot be resolved that way, obviously.

I am currently going over my recently written backend code and just burying it with logging.debug('msg') statements, asserts and whatnot. This is the only thing I can think of. Is this normal for backend developers? Does logging and digging through logs usually how backend devs iterate on their applications?

Parallelism and request driven

This might be a bit more specific to GAE and other non-blocking backends, honestly. Single threaded servers don't suffer from this problem... Anyways, so when you are dealing with parallelism and everything is driven by socket events, how do backend developers usually test if their backend works?

I did the most naive thing of all time, which is to open python console and using the requests library just send requests and test bit by bit. Then, I went ahead and wrote a kivy app to help me send the requests from a GUI interface and see what is going on, but it's taking more time to maintain the kivy app than develop the backend!! I tried to check for test frameworks for GAE, but they didn't seem easy to get, so I was wondering if they are worth it? Would I be able to simulate 100s of clients using my backend using test frameworks? What do people use these days (For GAE specifically)?

Visualizing the "flow"

Because of my inexperience with backend development, it is surprisingly hard hard for me to keep a clear image of the request/response cycle in my head. I know the basics, I have written a few backend apps, but as soon as it get just a little complex, I have to keep reminding myself where the request goes through by looking at the entry point, and all the steps till the response is made. I am sure if I were able to somehow visualize it, I don't have to keep going back over and over. Instead, I would easily know where a bug would originate, for example, or where is the best place to add a certain feature.

In any case, I was wondering if there is some sort of standard "thing" to design the request flow. I don't know, maybe a UML diagram or something?
I tried to sketch it out, but I ended up with a mess. Like, I would sketch the backend design based on the features and requirements, but then the actual logic and model would be left out. Then, I try to include those in the diagram, and it becomes overly complex and cluttered with many weird arrows and boxes. I need something to backend development, like ER diagrams is for relational database design.

Yeah, Sorry. I talk a lot, and I am lost in this world. Help?

答:
Debugging / TESTING!

Unit test the heck out of your backend code. It's usually easier than unit testing frontend code, because the code isn't waiting for arbitrary clicks or keypresses. It's all "this data comes in, this data goes out". Aggressive unit testing will speed you up phenomenally because you don't have to go all the way back to the start to validate each little bit of code. And then you'll have those tests around as regression testing.

There is a TDD (Test-driven development) that says you should write your tests first, and then fill in the code that makes them work. But I can only do that halfway, and claim that I'm using "London style". But if that appeals to you, it is a good practice.

As a high water mark: in Python, I aim for 100% test coverage & it's pretty easy hitting that.

I'm one of those guys who almost never uses a debugger. Rather, I use unit tests to make gurantees about behavior and sensible logging. But that's just my preference.

Parallelism

More important to get the thing working at all IMHO

Visualizing

I find these diagrams essential for my work: sequence diagram, and (less so) ER diagram and state diagram

Check out http://websequencediagrams.com . It will save your life on a complicated project, and even on simple ones really help visualize the client-server interactions.

If you draw a sequence diagram, not only will it show the client-server interactions, but every arrow pointing at your service is an API method you must implement. Pretty handy & very direct.

Yes, I use ER diagrams for both database design and class design when the data reaches a certain complexity.

Sometimes a state diagram can be very useful.

My opinion is that backend development is easier than frontend devleopment because I see my job as "moving bytes from here to there". But that may be just because I'm really bad at frontend development.

Title: Backend development philosophy


问:
How to avoid unauthorized use of an API?
I have to design a "widget", a script that partners will embed in their websites to display some UI and make calls to our API.

Basically it will display our data on these sites based on some IDs they provide in our API calls. What we would like to avoid is someone abusing the API and using it to scrape the entirety of our catalog.

Each partner that embeds our script will be given a public key that must be provided when calling the API. An idea would be to ask them to append this key when loading the script, e.g.:

```<code><script src="//initrode.com/widget/loader.js?key=xxxx"></script>
</code>```

That way the request for the script can be used to register the key/source IP pair, and answer subsequent API calls only if the key/IP pair matches a registered one (with a limited lifetime, and a limit on requests per day).

I'm not sure it's a good idea since it's obviously security through obfuscation (someone reloading the script will completely bypass it) ; but I don't see any other way to restrict access. I cannot provide a unique key to every user, only to partners. I can't use a private-key system since all the code will be available to anyone. It's basically restricting access to a public API, i.e. contradictory in its definition.

What do you think of this solution, and what would you do with these constraints?

答:
Sounds like you're doing here making your javascript files into protected resources. And bundling it with a sort of token generation at the same time. That's interesting.

The security guys I work with usually dismiss IP address out of hand because IP is spoofable. But if you're using an IP restriction combined with SSL, that usually does the trick.

But you have to "whitelist" the IP addresses, otherwise any hacker can just come in the front door.

I was skeptical, but I'm actually thinking your scheme works pretty well. If 1) the .js file and subsequent API calls are made with TLS (i.e. SSL or https), and 2) the IPs are whitelisted. Then I'll make a bold statement and say I think you'd pass a security review, even for PCI (credit card) interactions.

IMHO... But if you're just trying to protect company-proprietary information instead of credit card (PCI) or personal / private information (PII), then this is probably good even even without SSL, depending on how much you're willing to risk exposing your catalogue.

Or put it this way: With SSL, a dedicated hacker could not get your catalog. (Unless they break SSL, but then they could break Amazon, too). Without SSL, a dedicated hacker could sniff your calls, spoof IP and pull down your catalog. So it's kind of a judgement call on the risk.

I'm trying to think of a way to dispense with the IP whitelist because that's usually a pain to manage ;) without going to full-blown OAuth. I'll noodle on that.


答:
You need several types of protection.

Firstly, you need to prevent Site A's key from being used on Site B.

In theory, if the key is bound to a domain, you can't depend on the referer header, but because you're client is embedding a script directly, you can reasonably rely on the document.location on the client-side. Sending that location (or portions of it) to the server directly is unreliable; but you can use it to generate a session key:

Client embeds client_key in request for API library.

Server determines host that has access to the API, if any.

Server picks "salt" for a session key and sends it to the client with the library [or as part of another pre-auth exchange].

Client calculates a session_key using hash(document.location.host + session_salt).

Client uses session_key + client_key for an API call.

Server validates the call by looking up the client_key's host and "salt" in the session, computing the hash, and comparing to the provided client_key.

Secondly, you need to impede Hacker Hank from opening the debug console or using a modified client on Site A to do whatever he wants with your API.

Note though, that it's very difficult, if not impossible, to completely prevent Hacker Hank from abusing the API. But, you can make it more difficult. And the most reasonably way to impede Hank, that I'm aware of, is rate limiting.

Limit the number of requests/second/session and requests/hour/session. (Spikes in activity are probably reasonable, but not sustained above-average traffic from a single client.)

Limit the number of sessions/IP/hour.

Limit the number of requests/IP/hour. Allow spikes, but not sustained heavy traffic from a single IP.

Thirdly, as you're likely already doing: encrypt the traffic. Sure, the NSA will see it; but Hacker Hank is less likely to.

Title: How to avoid unauthorized use of an API?

Body:
I have to design a "widget", a script that partners will embed in their websites to display some UI and make calls to our API.

Basically it will display our data on these sites based on some IDs they provide in our API calls. What we would like to avoid is someone abusing the API and using it to scrape the entirety of our catalog.

Each partner that embeds our script will be given a public key that must be provided when calling the API. An idea would be to ask them to append this key when loading the script, e.g.:

```<code><script src="//initrode.com/widget/loader.js?key=xxxx"></script>
</code>```

That way the request for the script can be used to register the key/source IP pair, and answer subsequent API calls only if the key/IP pair matches a registered one (with a limited lifetime, and a limit on requests per day).

I'm not sure it's a good idea since it's obviously security through obfuscation (someone reloading the script will completely bypass it) ; but I don't see any other way to restrict access. I cannot provide a unique key to every user, only to partners. I can't use a private-key system since all the code will be available to anyone. It's basically restricting access to a public API, i.e. contradictory in its definition.

What do you think of this solution, and what would you do with these constraints?


问:
How do I manage the technical debate over WCF vs. Web API?
I'm managing a team of like 15 developers now, and we are stuck at a point on choosing the technology, where the team is broken into two completely opposite teams, debating over usage of WCF vs. Web API.

Team A which supports usage of Web API, brings forward these reasons:

Web API is just the modern way of writing services (Wikipedia)

WCF is an overhead for HTTP. It's a solution for TCP, and Net Pipes, and other protocols

WCF models are not POCO, because of [DataContract] & [DataMember] and those attributes

SOAP is not as readable and handy as JSON

SOAP is an overhead for network compared to JSON (transport over HTTP)

No method overloading

Team B which supports the usage of WCF, says:

WCF supports multiple protocols (via configuration)

WCF supports distributed transactions

Many good examples and success stories exist for WCF (while Web API is still young)

Duplex is excellent for two-way communication

This debate is continuing, and I don't know what to do now. Personally, I think that we should use a tool only for its right place of usage. In other words, we'd better use Web API, if we want to expose a service over HTTP, but use WCF when it comes to TCP and Duplex.

By searching the Internet, we can't get to a solid result. Many posts exist for supporting WCF, but on the contrary we also find people complaint about it. I know that the nature of this question might sound arguable, but we need some good hints to decide. We're stuck at a point where choosing a technology by chance might make us regret it later. We want to choose with open eyes.

Our usage would be mostly for web, and we would expose our services over HTTP. In some cases (say 5 to 10 percent) we might need distributed transactions though.

What should I do now? How do I manage this debate in a constructive way?

答:
If I were in your position I would start by examining your teams abilities.  If everyone on your team already knows WCF and only a small percentage know Web API then your decision is already made for you.

By all means if you have the time then invest it in learning and improving your knowledge base, but not at the expense of the business need and company productivity.


问:
Using Git in Enterprise environment
Git is an excellent version control system. If we exclude the fact that, it doesn't have an excellent GUI support, it's really good and fast. But the source controls like Clearcase has large support for enterprise customers. Companies are investing huge amount for source control servers and licesense.

Of late most of the large companies like Google are adopting Git over other version control system. But this company has a strong open source group which consistently provide development and support for the tool (They might even have a custom version of Git of their own). At the same time, large companies are not really bothering about adopting open source projects and making them relevant to them.

Is Git really a reliable tool for enterprise environment, especially
on Windows Platform?

The support is in question for Git as it's an
open source product.

Are there any company that provides
solutions and support? How are the server costs compared to other
version controls like Clear-case?

答:
Git and Mercurial can be used in enterprise environments. To some degree. Some organizations have extra requirements currently not fulfilled by git, things like stricter access control so that i.e. only specific users have (read) access to specific files in the repository or like auditing interfaces that access can be tracked. Some commercial enterprise systems also have deeper integration with IT systems management, like corporate backup solutions.

Git also is not good for ensuring the history is kept - by default it allows forced pushes overwriting the fully history of the project.

Large organizations sometimes hit scaling issues. Here is a case Facebook had: http://comments.gmane.org/gmane.comp.version-control.git/189776, while some of those issues are fixable (i.e. Facebook fixed some issues they had in mercurial: https://code.facebook.com/posts/218678814984400/scaling-mercurial-at-facebook/ ) commercial version control systems have different scaling behavior which might (or in other environments might not) work better.

... and then there is this responsibility thing. Larger organizations might prefer calling an external vendor when there are issues instead of using their time to debug the issues and rely on community support. Especially if corrupted repositories with confidential information are involved.

These by no means are issues making it unusable in "enterprise environments", but like always different software has different pros and cons which has to be evaluated case by case.

Title: Using Git in Enterprise environment


问:
How can Scrum be adapted to a Volunteer setting?
I have recently joined a young hackerspace still in the process of setting itself up.  We're fortunate because the space has a few internal projects that need working on and no shortage of volunteers to work on them.

There have been some discussions on how to organize these projects.  My most recent professional experience has been with Scrum so I'm considering pitching a Scrum approach for our software projects, but I'm not sure it will be a good fit.

Although I've seen Scrum work well for small full-time teams, the nature of this organisation is different:

The members are volunteers.  Some are full time students.  Others work jobs full time.  We can't expect a constant level of contribution from anyone as their real lives take priority.

While pretty much everyone has years of experience writing software, not many members have done so professionally or in teams.

There is no Product Owner.  The requirements for these projects are determined by a committee.  The members of this committee will also be working on the implementation.  This means we will have no single, dedicated, Product Owner.

We have no deadlines (soft or hard).  The projects will get done when they get done.

These are pretty significant differences, but I'm not convinced they will be blockers to applying Scrum.  I think some minor tweaking could get us over this hurdle:

If we change Sprints to have a fixed story-point size, but fluid duration (time), we can still benefit from iterative releases without putting unrealistic delivery pressure on volunteer devs.

We can ditch burndown charts and velocity calculation.  If I understand correctly, these are tools and metrics that work as a bridge between the dev team and the Management.  They serve to report progress in a form that is meaningful to both the developers and the stakeholders.  Considering we have no one to report to (no Project Manager, no Product Owner, and no outside stakeholders) I believe we can drop this altogether.

Things I think we could benefit from which won't require tweaking:

The Requirements Gathering meeting(s).  Where everyone sits around a table and discusses User Stories, sketches up UI mocks, and builds up a Product Backlog.

Sprint Retrospectives.  This will be an interesting way for us to converge on a development process that works for us as a team of volunteers.

Things I'm not sure about:

How should daily Stand-ups be treated?  I wonder if they would have much value at all in our setting.  My understanding of the stand-up ritual is that it helps communication by naturally disseminating information throughout the team.  Considering the fact that our Sprints will likely be delivering much less complexity than an average Sprint there might be less need to be abreast of all the other team members' progress/developments.

Should I push for XP things like Continuous Integration, Code Reviews, and TDD?  I'm concerned this will be asking for a lot.  I'd be more tempted to bring these concepts in on future projects once people are more familiar with Scrum and working as a team.

My Questions:

Can Scrum be adapted to a volunteer-based environment?

And, is my planned approach so far going in the right direction?

答:
Look into Kanban. It's more appropriate than SCRUM for your constraints.

Edit: SCRUM is (very roughly) an ordered backlog with sprints and ceremonies to ensure that the volume of work 'in progress' stays under control and have something solid at the end of every sprint. If you ditch the ceremonies and the sprints cadence you end up with Kanban: an ordered backlog and a strong emphasis on limiting work 'in progress' directly and by making sure everything marked 'done' is done rather than by imposing stability at the end of each sprint.

You still get the agile benefits: release anytime, flexibility, some measure of predictability - although SCRUM can get you slightly further on that aspect - and without the ceremonies or aspects of SCRUM that don't fit well a loose, distributed team with no commitment. The catch? Ditching the ceremonies require more discipline, so you REALLY need to pay attention to tests, code quality, the current work in progress, and ensure the top of the backlog (stuff ready to be picked up by people) is sufficiently elaborated.

You could have a vote based backlog, although in a volunteer setting some people just work on whatever they want to.

(And yes, all the TDD, CI, reviews and peer programming ideas are good ideas).


问:
What does &callback= do
I am trying to create a timer that ever x minutes it will call to a server, get a JSON file and do something with it. The merits of that system are not in question right now, the question involves getting the JSON file. Currently I am using kimonify from KimonoLabs to create a JSON file from some other site. They suggest I use

```<code>function kimonoCallback(data) {
    // do something with the data
    // please make sure the scope of this function is global
  }

  $.ajax({
    "url":"http://www.kimonolabs.com/api/9ey3ljcs?apikey=d753b0c5546495826e7aaa5422f59e30&callback=kimonoCallback",
    "crossDomain":true,
    "dataType":"jsonp"
});
</code>```

At the same time I was pursuing other methods and was getting a parse error, and I found this solution. So far both used &callback=

what is so special about &callback= that makes it more preferable to something like .done() or success: I am guessing it has something to deal with Access-Control-Allow-Origin.

答:
The server you are making the call to will call your function when it's done. That way you don't have to parse the immediate response (which may not contain the JSON).

Say the server takes 10 seconds to do a long operation. Instead of leaving your connection open for 10 seconds it will respond immediately that it got your request. It will then start the operation and let you know when it's done by calling your function.

It's part of Asynchronous Programming

Title: What does &callback= do


问:
sqlite trigger or application event?
I've have two event queues(table mapped queues) based on two different states of same data stored in two different tables. The events are generated on create/update/delete on both the tables.

Constrain is that both the tables have to be in sync. The create/update/delete in one table has to be reflected into other table.

So the question is that should i use trigger to queue events in table or application/object to queue events in table? and Why?

Note:

Update on either is capable of generating 3 different types of events. So on application layer extra diff logic would be required to generate correct event.

The Negative thing in trigger is that it will introduce duplicate events from both sides. i.e. if some event is processed on one table it will create an event for processing on other table.

答:
I wrote this stuff a long time ago for a C++ application and made a post on my blog. Here's a quick summary (since the original article is quite long and contains file attachments):

In SQLite you write callbacks in raw C++:

Header file (file.h)

```<code>#include <iostream>
#include <sqlite3.h>
#include <cstdlib>
#include <assert.h>

void memberfunction(const unsigned char* text1,
                    const unsigned char* text2,
                    const unsigned char* text3);
void mcallback(sqlite3_context* context, int argc, sqlite3_value** argv);
</code>```

It defines the two additional functions we'll need for the next step (actually our C++ side function and a SQLite stored procedure).

Implementation file (file.cpp)

This function will be called from our trigger from the DB.

```<code>void memeberfunction(const unsigned char* text1,
                     const unsigned char* text2,
                     const unsigned char* text3)
{
    cout << "inserted: " << text1 << "  " << text2 << "  " << text3 << "n";
}
</code>```

And now a SQLite stored procedure to call our function; a SQLite trigger will invoke this.

```<code>void mcallback(sqlite3_context* context, int argc, sqlite3_value** argv)
{
    assert(argc == 3);
    //SQLite types must be converted to C++ types
    const unsigned char* text1 = sqlite3_value_text(argv[0]);
    const unsigned char* text2 = sqlite3_value_text(argv[1]);
    const unsigned char* text3 = sqlite3_value_text(argv[2]);
    memeberfunction( text1, text2, text3);
}
</code>```

We don't have to limit the function to just a simple print; this function could have (for example) moved data to another table.

Register the stored procedure to the DB

```<code>error = sqlite3_create_function(conn, "mcallback", 3, SQLITE_UTF8, NULL,
                                      &mcallback, NULL, NULL);
</code>```

Create the SQLite trigger

We need the stored procedure since triggers are built on top of them.

```<code>error = sqlite3_exec(conn, "create temp trigger callbacktrigger "
                           "after insert on hello for each row "
                           "begin "
                             "select mcallback(new.first_column, "
                             "new.second_column, new.exclamation_pt); "
                           "end;", 0, 0, 0);
</code>```

The trigger is only temporary. This way it won't stick around in the database after execution terminates (of our whole program). Our callback won't be around after then anyway and the trigger could (and will, given it's nature) cause major problems if we use the database outside this application.

Title: sqlite trigger or application event?

Body:
I wrote this stuff a long time ago for a C++ application and made a post on my blog. Here's a quick summary (since the original article is quite long and contains file attachments):

In SQLite you write callbacks in raw C++:

Header file (file.h)

#include <iostream>
#include <sqlite3.h>
#include <cstdlib>
#include <assert.h>

void memberfunction(const unsigned char* text1,
                    const unsigned char* text2,
                    const unsigned char* text3);
void mcallback(sqlite3_context* context, int argc, sqlite3_value** argv);

It defines the two additional functions we'll need for the next step (actually our C++ side function and a SQLite stored procedure).

Implementation file (file.cpp)

This function will be called from our trigger from the DB.

void memeberfunction(const unsigned char* text1,
                     const unsigned char* text2,
                     const unsigned char* text3)
{
    cout << "inserted: " << text1 << "  " << text2 << "  " << text3 << "n";
}

And now a SQLite stored procedure to call our function; a SQLite trigger will invoke this.

void mcallback(sqlite3_context* context, int argc, sqlite3_value** argv)
{
    assert(argc == 3);
    //SQLite types must be converted to C++ types
    const unsigned char* text1 = sqlite3_value_text(argv[0]);
    const unsigned char* text2 = sqlite3_value_text(argv[1]);
    const unsigned char* text3 = sqlite3_value_text(argv[2]);
    memeberfunction( text1, text2, text3);
}

We don't have to limit the function to just a simple print; this function could have (for example) moved data to another table.

Register the stored procedure to the DB

error = sqlite3_create_function(conn, "mcallback", 3, SQLITE_UTF8, NULL,
                                      &mcallback, NULL, NULL);

Create the SQLite trigger

We need the stored procedure since triggers are built on top of them.

error = sqlite3_exec(conn, "create temp trigger callbacktrigger "
                           "after insert on hello for each row "
                           "begin "
                             "select mcallback(new.first_column, "
                             "new.second_column, new.exclamation_pt); "
                           "end;", 0, 0, 0);

The trigger is only temporary. This way it won't stick around in the database after execution terminates (of our whole program). Our callback won't be around after then anyway and the trigger could (and will, given it's nature) cause major problems if we use the database outside this application.

ContentLicense: CC BY-SA 4.0


问:
What is the point of a Gantt Chart, and will it help me?
My (non-technical) colleague has threatened me with a Gantt chart for a new project that we are currently planning.  What is this likely to provide for us, and will it be a helpful tool?</p>

答:
I have successfully used Gantt charts in the past for software project management. I have also seen people abandon them in frustration.

Any project management tool is useful only if it's answering questions that somebody is actually asking. In my case, I was continually asked two questions, and my Gantt chart could answer it:

My Manager: When will the software be
in a shippable state?

A Developer:
I've finished the task you had
assigned me. What task are you
assigning me now?

So what factors are required for a Gantt chart to be useful?

Multiple team members

That should be obvious. If there's only one team member, then all you need is a list of tasks in one column. You're only going to do them one after another.

Knowledge of what the tasks are

This seems like another obvious statement, but you'd be surprised how many software projects are not well defined enough to be able to divided into tasks. You'll actually need an upfront specification, and some degree of upfront design. In some of the agile/extreme methodologies you couldn't use a Gantt chart, because you don't know what tasks will be in the subsequent 3-week iteration.

Time and Motivation to Maintain the Chart

Somebody HAS to put the time in to maintain the thing. Too often, somebody spends days making up a detailed Gantt chart, then neglects it. Maybe he'll get it out a month later, laugh nervously, and throw it away, never to talk about it again.

Once you have the tasks and best estimates, you put them on the chart. And when the first task has been completed, you have to mark that on the chart and then jiggle all of the other tasks around to compensate for the fact your estimate was wrong. And two days later you do it again. And then again, another two days later. And of course, when it turns out you forgot something or a defect appears, you have to put the new tasks on the chart.

That might sound like a significant ongoing time commitment, and you're right. Where does the motivation to do this come from?

Somebody actually cares about the results

The times that I have used a Gantt chart successfully was where there were weekly project management meetings. The manager would go around the room asking each team leader to state when their project would be delivered. If a project was running behind then resources would be reallocated. For the first two meetings I would stammer that I didn't really know when it would be delivered, and would come up with a vague "in three months". The embarrassment of this made me change my strategy, and make damn well sure I had a Gantt chart that was up-to-date and accurate before each meeting.

As a side effect, this made my project better organised and more efficient, and my team members more motivated.

ContentLicense: CC BY-SA 2.5


问:
Language that embraces mutable state?
There seems to be a trend towards immutable objects, and pure functional programming. While I recognize the benefits, I find it hard to apply these principles to GUI programming, for example. But I also find classical imperative languages with mutable objects lacking. I was wondering whether there is a language or system that embraces mutable state, and makes it especially easy to work with.

Below are some features I would consider to be "designed around mutability":

The ability to hook up events and get a change notification for any variable. It would make it very easy to write GUIs and MVC applications. And you could just make a List<MyObject>, and stuff it into a list widget, and with a bit of configuration it would manage your list for you, no manual listview.insert() etc..

A type system that considers state. For example, If I pass a Car into a function that requires a working one, the compiler should try to proove that car.broken == False. If it can't proove it, it won't compile, and I have to ensure it (by putting the code in an if block, or setting it manually to False).

A take on concurrency that makes sense for mutable objects. For example an atomic statement, that guarantees that certain statements are run together, using transactions or locks. The goal is not performance, but ease of use and GUI responsiveness. I should be able to manipulate data and the GUI from any thread, using atomic {step1; step2} to ensure invariants.

I'm not looking for a system with these exact features, but one written in a similar spirit. The closest I've seen to this is C#/.NET with its data binding features.

Gtk+ has custom ListModels that keep a GtkTreeView in like with your data without manual inserts/updates. Android has ListAdapters which are similar. I haven't found a thread-safe GUI, but you can get pretty close with a liberal use of Invoke() in C#/WinForms, or gobject_idle_add in Gtk+. Are there any systems like what I describe? Or research material, references, etc.?

答:
No language have all the properties you describe for very good reasons.

Change Notifications The main problem with is the overhead added to the system. Some versions of Smalltalk, for example, supported this. Other versions claimed lack of support of this as a significant performance feature. As you mention C# has INotifyPropertyChange but that must be manually implemented. Other systems have similar notification manual patterns for this. JavaScript ECMA 6's Observe specification is the latest attempt to do this for all mutable objects in a language.

This will not be mainstream until the underlying performance problems can be addressed in a way that is predictable and understandable.

Dependency Types Enforcing predicates such as "car.broken == False" is generally referred to as a dependency type system; a type system that depends on runtime properties of the candidate elements of the type. In general, this has been demonstrated to have polynomial-time complexity. There are some subsets of the general case that can be implemented in linear time but no mainstream language has such a thing. The SAL annotations by Microsoft are the closest I have seen though there might be others I am not aware of.

This will not be mainstream until the underlying principles and limitations of such a type system can be understood without a doctorate in type systems.

Concurrency Primitives Concurrency primitives of which atomic is a part is a hotly debated topic in languages. Each language has been adapted, in some respects, to allow for concurrency (except JavaScript which is a mutable state language which has explicitly taken a position against shared memory concurrency). There are several languages that have atomic in one form or another but differ in how they implement it. Unfortunately, there is no wide consensus on what the "right" solution to this problem is. The mainstream thought is tending to non-mutable shared state as the current savior, hence the ascendancy of functional languages, but which is outside the scope of this question.

This will not be mainstream until the ramifications and limitations of the primitives are understood and either accepted or demonstrated they can do better than atomic writes/shared locks that predominates today shared state concurrency models. This might never be mainstream as other models (such as functional) might prove more fruitful.

Title: Language that embraces mutable state?


问:
Where we should put validation for domain model
I still looking best practice for domain model validation. Is that good to put the validation in constructor of domain model ?  my domain model validation example as follows:

```<code>public class Order
 {
    private readonly List<OrderLine> _lineItems;

    public virtual Customer Customer { get; private set; }
    public virtual DateTime OrderDate { get; private set; }
    public virtual decimal OrderTotal { get; private set; }

    public Order (Customer customer)
    {
        if (customer == null)
            throw new  ArgumentException("Customer name must be defined");

        Customer = customer;
        OrderDate = DateTime.Now;
        _lineItems = new List<LineItem>();
    }

    public void AddOderLine //....
    public IEnumerable<OrderLine> AddOderLine { get {return _lineItems;} }
}

public class OrderLine
{
    public virtual Order Order { get; set; }
    public virtual Product Product { get; set; }
    public virtual int Quantity { get; set; }
    public virtual decimal UnitPrice { get; set; }

    public OrderLine(Order order, int quantity, Product product)
    {
        if (order == null)
            throw new  ArgumentException("Order name must be defined");
        if (quantity <= 0)
            throw new  ArgumentException("Quantity must be greater than zero");
        if (product == null)
            throw new  ArgumentException("Product name must be defined");

        Order = order;
        Quantity = quantity;
        Product = product;
    }
}
</code>```

Thanks for all of your suggestion.

答:
Despite the fact this question is a little stale, I'd like to add something worthwhile:

I'd like to agree with @MichaelBorgwardt and extend by bringing up testability. In "Working Effectively with Legacy Code", Michael Feathers talks a lot about obstacles to testing and one of those obstacles is "difficult to construct" objects. Constructing an invalid object should be possible, and as Fowler suggests, context dependent validity checks should be able to identify those conditions. If you can't figure out how to construct an object in a test harness you're going to have trouble testing your class.

Regarding validity I like to think of control systems. Control systems work by constantly analyzing the state of an output and applying corrective action as the output deviates from the set point, this is called closed loop control. Closed loop control intrinsically expects deviations and acts to correct them and that's how the real world works, which is why all real control systems typically use closed loop controllers.

I think using context dependent validation and easy to construct objects will make your system easier to work with down the road.


问:
OO design for a Windows application that communicates with an external machine via RS232
I'm after a bit of OO design advice... I'm about to start developing a Windows application that communicates with an external machine via RS232. The machine has an onboard "system controller" consisting of registers (addresses). You can write a value to a register (e.g. to turn a pump on), or read a value from a register (e.g. to see if the pump is running). The app will have a config file detailing each register's settings, e.g. its address, whether it's 16- or 32-bit, a friendly "alias" (so other code can deal with "Pump XYZ" rather than address "50B3D124"), and a few other things.

My first thought was to have a Register class reflecting these properties, plus Read() and Write() methods. But this raises the first question - should the Read() method have a return value, or should it populate a Value property on the class?

Similarly, should the Write() method include a "valueToWrite" parameter, or should it write whatever value is currently held in the Value property?

I could take this one step further (possibly even answering the above question) - instead of Read/Write methods, put the functionality into the Value property's getter and setter? Using a property for this purpose doesn't feel right though.

I then started wondering if a Register class was even necessary, as its read/write functionality would be doing little more than calling Read/Write methods on a SystemController class, e.g.

```<code>long ReadRegister(string registerAlias);
void WriteRegister(string registerAlias, long value);
</code>```

Why not just let the rest of the application read/write registers via the  SystemController class? (I suspect I would still need some concept of a Register class, even if it's just to represent a register's config settings).

答:
But this raises the first question - should the Read() method have a return value, or should it populate a Value property on the class? Similarly, should the Write() method include a "valueToWrite" parameter, or should it write whatever value is currently held in the Value property?

If you use a Value property instead of returning a value from Read(), you can "write" values to the Register via Write() but still see an old value until you call Read(). you've introduced unnecessary mutation into your implementation, and more importantly that's not how the hardware registers work.

Your Register class should be immutable, only store the minimal amount of information required to access the real hardware register (probably just the address), and should hide that information from the outside world. The only thing you should be able to do with a Register variable is read, write, and check if it's the same hardware register as another Register. For example, in Java:

```<code>public final class Register<T extends Number> {
    public static final Register<Short> PUMP_XYZ = new Register<Short>(0xA3F990);
    public static final Register<Integer> PUMP_ABC = new Register<Integer>(0xA3F9A0);
    // and so on

    private final int address;

    private Register(int address) {
        this.address = address;
    }

    public T read() throws CommunicationException {
        return /* read hardware */
    }

    public void write(T value) throws CommunicationException {
        /* write to hardware */
    }

    @Override
    public boolean equals(Object other) {
        if (other instanceof Register) {
            return this.address == ((Register) other).address;
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return address;
    }

    @Override
    public String toString() {
        return String.format("Register(0x%h)", address);
    }

    public static final class CommunicationException extends RuntimeException {}
}
</code>```

This is the simplest implementation that captures all the essential details of a real register. It's also immutable and disallows inheritance, both of which you should prefer when possible.

It's tempting to attach a printable name to Register, but that's not really a part of what you're trying to model. A hardware register has no notion of a name. It'd be better to keep that separate and create a Map<Register, String> or a simple struct which holds a String and Register field.

Why not just let the rest of the application read/write registers via the SystemController class?

One day you might change the communication protocol to be USB or use a different API to make the RS-232 calls. The application doesn't care how the registers are accessed and shouldn't have to know; it's an implementation detail.

Body:
But this raises the first question - should the Read() method have a return value, or should it populate a Value property on the class? Similarly, should the Write() method include a "valueToWrite" parameter, or should it write whatever value is currently held in the Value property?

If you use a Value property instead of returning a value from Read(), you can "write" values to the Register via Write() but still see an old value until you call Read(). you've introduced unnecessary mutation into your implementation, and more importantly that's not how the hardware registers work.

Your Register class should be immutable, only store the minimal amount of information required to access the real hardware register (probably just the address), and should hide that information from the outside world. The only thing you should be able to do with a Register variable is read, write, and check if it's the same hardware register as another Register. For example, in Java:

public final class Register<T extends Number> {
    public static final Register<Short> PUMP_XYZ = new Register<Short>(0xA3F990);
    public static final Register<Integer> PUMP_ABC = new Register<Integer>(0xA3F9A0);
    // and so on

    private final int address;

    private Register(int address) {
        this.address = address;
    }

    public T read() throws CommunicationException {
        return /* read hardware */
    }

    public void write(T value) throws CommunicationException {
        /* write to hardware */
    }

    @Override
    public boolean equals(Object other) {
        if (other instanceof Register) {
            return this.address == ((Register) other).address;
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return address;
    }

    @Override
    public String toString() {
        return String.format("Register(0x%h)", address);
    }

    public static final class CommunicationException extends RuntimeException {}
}

This is the simplest implementation that captures all the essential details of a real register. It's also immutable and disallows inheritance, both of which you should prefer when possible.

It's tempting to attach a printable name to Register, but that's not really a part of what you're trying to model. A hardware register has no notion of a name. It'd be better to keep that separate and create a Map<Register, String> or a simple struct which holds a String and Register field.

Why not just let the rest of the application read/write registers via the SystemController class?

One day you might change the communication protocol to be USB or use a different API to make the RS-232 calls. The application doesn't care how the registers are accessed and shouldn't have to know; it's an implementation detail.


问:
OOP and relational databases
I see a lot of talk in the OOP world about principles and laws such as Open/Close and Loose Coupling, I can understand how they are so high valued, However I seem to have ran into a problem with applying these principles and laws once I start to include relational databases.

For example purposes, if I have a application which we are able to separate well into multiple components(Open/Close design) and allow them to work with each other when if needed, I start to run into problems when trying to enforce referential integrity.
If I enforce a relational setup, and enforce integrity through foreign keys and so on, the tables become dependent on each other, gradually my OOP application logic starts to fall apart and become one big system.

I can of course remove all references to tables, but then I risk making data redundant and start to repeat code/data, which then goes against the Don't Repeat Yourself principle.

Have you came across such problems before? If so how did you handle it? Perhaps there is a way to achieve both referential integrity and OOP open/close components.

Thanks

答:
I think that OOP and RDBMS are not good friends. OOP seems to me more apt to deal with "rows" in each table. RDBMS deals with "sets of rows".

Nevertheless, there are lots of frameworks that try to overcome these problems, but they lose the "purity" of OOP.

Title: OOP and relational databases


问:
Can removing unnecessary file from a repo be considered part of refactoring?
We're using Git as our DVCS and we're about to start to do a clean up (never done before in this team) of files that are not necessary (not part of the sources) from our products.

This is done in two ways:

removing the product files from the repo and adding them to the ignore list.

deleting dead code

According to Wikipedia:

Code refactoring is the process of restructuring existing computer code without changing its external behavior. Refactoring improves nonfunctional attributes of the software. Advantages include improved code readability and reduced complexity to improve source code maintainability, and create a more expressive internal architecture or object model to improve extensibility.

and from Martin Fowler's entry:

Refactoring is a very specific technique, founded on using small behavior-preserving transformations (themselves called refactorings).

I haven't read anywhere that removing dead code or removing files from your repo are considered refactoring techniques but I see them both as techniques that "improve source code maintainability" by removing irrelevant code that may distract us later on.

Do you think it's reasonable to call those two activities "Refactoring"?

答:
I think removing dead code would technically be classified as refactoring, because it's a code transformation that does not change the overall code's functional behavior.

Adding files to an ignore list seems more like a code metadata transformation than an actual code transformation, so I'm not sure whether it would technically be considered refactoring.


问:
Are there any standards for separating different kinds of comments (explanatory, debug, to-do, etc.)?
For a while now I've been in the habit of differentiating different kinds of comments in my code.

```<code>//this is an explanatory comment

//!this line was commented out for debug purposes, DO NOT SHIP WITH THIS COMMENT IN PLACE

//?this code was tested, and executed properly in 2.3 uS
</code>```

This has saved me a lot of trouble, as I can quickly differentiate between debug comments and explanatory comments. It's especially nice to be sure that all my debug comments are gone, and none were accidentally left in place before publishing my code.

Is this a common practice? If so, is there a standard way of differentiating comments? Or are there perhaps better ways of achieving what I'm trying to achieve?

答:
There basically isn't a need for a standard for such comments, because the standard is usually to remove them before you check in.

That being said, @amon's snarky comment is pretty much right.  There's a lot of benefit to be gained by taking advantage of your source control to remove debug changes.  Basically, you make sure to only make debug changes since your last commit, then you can undo them all with a single command.  Or run a diff first if you're paranoid about what will be undone.

Git is especially easy to use with this model because local commits don't have to be shared and you can easily make an entire branch just for temporary debug changes, or use stashing, or the index.  However, I do it at work with perforce by shelving my work in progress before making debug changes, then unshelving when I want the debug changes to go away.  I think most modern version control systems have a concept of shelving.

The other benefit to using source control for debug changes is you aren't limited to finding commented out changes.  Added lines, partially changed lines, and rearranged lines are all undone with one command.  You just make the changes you need, without worrying about how you're going to find them later to undo them.


问:
In MV* pattern where does non-business model goes?
I am passing Menu items to View from ViewModel. My menu definition is a model with properties title, image, hasChildren and isEnabled. But this model is meant for UI unlike business domain models like Person, ContactDetail, Transaction, etc.

So, when i see this menu model sitting along with business domain models i felt like polluted. Is there a right place to put these kind of UI specific models?

Thanks.

答:
You are working on the View within your Model/View/Controller.

The model is the business of your application. The View displays visual elements (In this case a menu) and the Controller handles dynamic user interaction (Which keystrokes do what, which pointer selections ask the view to be active etc.) The View and Controller are nearly always very closely tied. Of course in the HTML world we hardly think about the controller aspect of the UI but in writing native applications it use to be much more hands on than it is now.

Most classes within M, V and C have instance variables. There is no need to be embarrassed that your menu (ie view) has state, it is still perfectly valid to think of it as part of the View.

I also get the idea that you could subclass (Or not) many different designs of menu within your view but you don't need to think of the attributes as being the model. They are the state needed to render the view and the detail belongs within the view.


答:
Nope, I wouldn't consider it refactoring - you're not actually changing anything by removing unused code files from a project, its more a cleanup task. As you say these are not part of the sources.

However, removing unused code from a file where some code remains can be considered a refactoring because you are changing the codebase, or removing code files from an active project where they used to be compiled in is a refactor - your codebase has changed, even if very slightly. You never know what crazy side-effects this change might have, whether its due to the executable size, include chains, or even simple reflection into the application that used to work and no longer does after you remove the code. As a result, you should be keeping track of the change as if it was a real code change, just so you can return to it later and pinpoint what changes were made to your old, working application.

So if you have truly useless files in your repo that are truly not used (and I think of things like .obj files or other non-code files) then get rid of them before you migrate.
If, however, they are code files, add them in and then delete them from the project and your repo so they remain in history only.

Title: Can removing unnecessary file from a repo be considered part of refactoring?

Body:
We're using Git as our DVCS and we're about to start to do a clean up (never done before in this team) of files that are not necessary (not part of the sources) from our products.

This is done in two ways:

removing the product files from the repo and adding them to the ignore list.

deleting dead code

According to Wikipedia:

Code refactoring is the process of restructuring existing computer code without changing its external behavior. Refactoring improves nonfunctional attributes of the software. Advantages include improved code readability and reduced complexity to improve source code maintainability, and create a more expressive internal architecture or object model to improve extensibility.

and from Martin Fowler's entry:

Refactoring is a very specific technique, founded on using small behavior-preserving transformations (themselves called refactorings).

I haven't read anywhere that removing dead code or removing files from your repo are considered refactoring techniques but I see them both as techniques that "improve source code maintainability" by removing irrelevant code that may distract us later on.

Do you think it's reasonable to call those two activities "Refactoring"?


答:
In .net mvc there is a concept called a view model, which is a class that is meant to take 1-n domain models and implement them for a specific view.  It had become a best practice for more complex applications to include a view model for every view.  You also find a similar practice in django with modelforms.

The mv* pattern doesn't mean you can't write classes to integrate your domain models. But those classes should not be in your domain model structure. The pattern is means of implementing SOC and having mixing domain and ui models breaks breaks that separation.

I would implement an additional ui class layer meant to translate domain models into different interfaces and have views talk with this layer.

Title: In MV* pattern where does non-business model goes?

Body:
I am passing Menu items to View from ViewModel. My menu definition is a model with properties title, image, hasChildren and isEnabled. But this model is meant for UI unlike business domain models like Person, ContactDetail, Transaction, etc.

So, when i see this menu model sitting along with business domain models i felt like polluted. Is there a right place to put these kind of UI specific models?

Thanks.


问:
If a variable containing a function gave the function's return instead of a reference to the function, what would an array of functions return?
I'm creating a prototype scripting language similar to something like Javascript. In my language, every single reference to a variable is actually a function call (a getter function), whether it has parentheses or not. So for example, if do this:

```<code>var foo = 3;
var bar = foo;
</code>```

What really happens is foo.set() is called on the first line, which creates a new getter function. In the second line, the newly created getter function for foo is called, which looks like this:

```<code>foo.get()
{
    return 3;
}
</code>```

I can also assign a function to a variable, in which case that function BECOMES the getter function.

```<code>var foo =
{
    return 4+5;
}
var bar = foo; // bar is now equal to the number 9, NOT the function that foo contains
</code>```

So what I'm working on now is what an array of functions should return. For example:

```<code>function func1
{
    return 1;
}
function func2
{
    return 2;
}

var foo = new array();
foo.push(func1);
foo.push(func2);

var bar = foo; //what does bar contain? [func1, func2] or [1, 2]?
</code>```

A reference to a single function runs that function and gives the return of the function. So I'm trying to decide if a reference to an array of functions should also run those functions, or if it would be more advantageous to just return the array of functions.

In other words, would the getter function for foo look like this:

```<code>foo.get()
{
    return [func1.reference, func2.reference]; //would return [func1, func2]
}
</code>```

Or like this:

```<code>foo.get()
{
    return [func1(), func2()]; //would return [1, 2]
}
</code>```

Specifically, I'm asking if anyone knows if there are problems or solutions that one method or the other would create?  Are there any established rules of good programming language design that apply here?

答:
Use the first approach. Unless your language is pure functional, the second approach can have weird results. For example:

```<code>var x = 0;
function func
{
    return x;
}
var arr = new array();
arr.push(func);
var arr2 = arr;
x = 1;
print(arr[0]()); // prints "1"
print(arr2[0]()); // prints "0"
</code>```

Or:

```<code>function func
{
    print("hello");
}
var arr = new array();
arr.push(func);
var arr2 = arr; // prints "hello"
</code>```

PS: Are you sure you want to construct a new array every time you read an array variable?

Body:
Use the first approach. Unless your language is pure functional, the second approach can have weird results. For example:

var x = 0;
function func
{
    return x;
}
var arr = new array();
arr.push(func);
var arr2 = arr;
x = 1;
print(arr[0]()); // prints "1"
print(arr2[0]()); // prints "0"

Or:

function func
{
    print("hello");
}
var arr = new array();
arr.push(func);
var arr2 = arr; // prints "hello"

PS: Are you sure you want to construct a new array every time you read an array variable?


问:
Are HSQLDB unit tests an anti pattern?
HSQLDB is great. It (also) has an embedded mode (no dedicated server needed), which allows for quick prototyping of stuff like Proof of Concepts, and it can also be great in production-ready applications, as a quick and simple storage of various data.

However, at least 90% of the projects I've worked on in the past years, if they deal in any way with an SQL database, they will unavoidably have unit tests that use an embedded HSQLDB.

Sure-enough, these projects (which use the standard Maven structure most of the times), have a ton of "unit tests" (or, at least, some kind of tests, but which are located in the "unit-test" area of the project (like "src/test/java")) which use one or more embedded instances of HSQLDB in order to do some CRUD operations and check the results.

My question is: is this an anti-pattern? Does the fact that HSQLDB is easy to integrate and the embedded server is very lightweight make it so that it can be overlooked as "mock-up" of an actual database, when it shouldn't be the case? Shouldn't such tests be treated more like integration-tests (since each of them is composed of "something" AND that "something"'s integration with a database server)? Or am I missing something in the "unit test" definition, and we can infact say that using HSQLDB like this simply adheres to the "mock the dependencies, and test only the unit" part of the "unit test" definition?

答:
I've found & fixed some really bad problems and greatly speeded up my development by testing against HSQL database. Often the lowest level of adaptor classes (i.e. your DAOs) can go untested in unit testing because it can be hard to decouple them from an actual round-trip to a live database. I have mocked Connection and JDBC artifacts in the past, but it was actually much harder than testing against an in-memory database.

On one project, I developed & tested against HSQL, ran locally against MySql, and deployed to production against SQL-Server. Amazingly, it worked just fine. The biggest integration issue I encountered was due to my own misunderstanding of the spec (seconds vs. milliseconds, lol).

While the persistence framework can mask the underlying database (like Hibernate does), the persistence framework itself can add enough complicated semantics that exercising it in isolation can shake out a lot of quirks before you get to full-blown integration testing.

Consider the case where you're using Hibernate or JPA to build a complicated result set with a lot of joins. If it's nasty and takes a lot of tries, you could develop and test that against a live database. But you could also develop and test it against an in-memory database with less overhead. You also don't have to worry about setup/teardown scripts for your database fixtures, or coordinating tests and builds with others. And if you test against the in-memory database, you enjoy the benefits of having those tests around for regression, just like other unit tests.

I've heard the term "Component Testing" for tests that are more than unit test, but still done in isolation.

Unit tests, Component Tests (if that's really their name), and Integration Tests all provide value. Teams can dispense with one or another (yes, lots of teams do no unit testing & rely solely on Integration testing), but if you do that, you're losing the benefits that the other testing tiers bring.

In the case of tests that are isolated by virtue of integrating in memory, the benefit is rapid validation of code, and then fast regression -- the benefits of isolated testing and no need for additional installations, licenses or hardware. It allows you to validate more levels of code in isolation than if you just punted on testing your DAOs until the database was provisioned.

So there's practical value. It's not required, but I've been more happy rather than less when I've done it.

Title: Are HSQLDB unit tests an anti pattern?


问:
Adding object properties using functional programming
I am currently learning functional programming using Underscore.js. What I want to do is add two co-ordinates together. Let P1 = (0, 0) and P2 = (1, 1). Therefore, P1 + P2 = (1, 1)

I have a solution, but it seems so convoluted that I'm sure I'm doing something wrong:

```<code>// Base 2D Cartesian Point
var Point = function(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.add = function(delta) {
  return _.object(_.keys(this),
    _.map(
      _.zip(
        _.values(this),
        _.values(delta)),
        function(point) {
          return _.reduce(point,
            function(memo, num) { return memo + num; }, 0);
        }
    )
  );
}
</code>```

Is this the proper implementation of the add function for points using Underscore.js or is there a better solution?

答:
If you're going to do functional programming on points, it would make more sense for your points to be lists of coordinates instead of objects.  That simplifies the code quite a bit:

```<code>function add(p1, p2) {
    _.map(_.zip(p1, p2), function(coords) {
        return _.reduce(coords, function(coord, sum) { return sum + coord; }, 0);
    });
}
</code>```

This may make sense if you're dealing with ten dimensional space, but it seems like overkill for two dimensions.

Body:
If you're going to do functional programming on points, it would make more sense for your points to be lists of coordinates instead of objects.  That simplifies the code quite a bit:

function add(p1, p2) {
    _.map(_.zip(p1, p2), function(coords) {
        return _.reduce(coords, function(coord, sum) { return sum + coord; }, 0);
    });
}

This may make sense if you're dealing with ten dimensional space, but it seems like overkill for two dimensions.


答:
My suggestion:

You have to enforce referential integrity with FK. Let the RDBMS do that work and  let the classes throw exceptions.

Tables being related has nothing to do with coupling of classes or SOLID principles. That's classes's stuff.

Tables are orthogonal to classes.

Don't overengineer things.

Title: OOP and relational databases

Body:
I see a lot of talk in the OOP world about principles and laws such as Open/Close and Loose Coupling, I can understand how they are so high valued, However I seem to have ran into a problem with applying these principles and laws once I start to include relational databases.

For example purposes, if I have a application which we are able to separate well into multiple components(Open/Close design) and allow them to work with each other when if needed, I start to run into problems when trying to enforce referential integrity.
If I enforce a relational setup, and enforce integrity through foreign keys and so on, the tables become dependent on each other, gradually my OOP application logic starts to fall apart and become one big system.

I can of course remove all references to tables, but then I risk making data redundant and start to repeat code/data, which then goes against the Don't Repeat Yourself principle.

Have you came across such problems before? If so how did you handle it? Perhaps there is a way to achieve both referential integrity and OOP open/close components.

Thanks


答:
There are several methods you can use to perform this calculation. I am going to use your base 2d point object and extend it a couple of ways

```<code>// Base 2D Cartesian Point
var Point = function(x, y) {
  this.x = x;
  this.y = y;
};
</code>```

Since Robert Harvey's suggestion is so straight forward, let's start with it:

```<code>var startpoint = new Point(0, 0);
var offsetpoint = new Point(startpoint.x + 5, startpoint.y + 5);
</code>```

Next, you can add a function to the Point instance already created:

```<code>Point.add = function(x, y) {
  this.x += x;
  this.y += y;
};
</code>```

As you have shown above, you can also modify the class prototype by changing Point.add to Point.prototype.add. The revised declaration adds the add method to all Point instances.

Suppose you want to pass a Point instead of x and y? We can do that too. We just can't use a polymorphic method declaration. We can, however, morph the function into a new function with different parameters. The down side to this is that, from that point on, you will not ever be able to get back to the first implementation with x and y without replacing the function again. That's probably too much for right now. Let's add the next version:

```<code>Point.prototype.addPoint = function(anotherPoint) {
    // Is the object being passed in of our class?
    if(anotherPoint instanceof Point) {
      this.add(anotherPoint.x, anotherPoint.y);
    }
};
</code>```

Here is a jsfiddle with this code working.

Title: Adding object properties using functional programming

Body:
I am currently learning functional programming using Underscore.js. What I want to do is add two co-ordinates together. Let P1 = (0, 0) and P2 = (1, 1). Therefore, P1 + P2 = (1, 1)

I have a solution, but it seems so convoluted that I'm sure I'm doing something wrong:

```<code>// Base 2D Cartesian Point
var Point = function(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.add = function(delta) {
  return _.object(_.keys(this),
    _.map(
      _.zip(
        _.values(this),
        _.values(delta)),
        function(point) {
          return _.reduce(point,
            function(memo, num) { return memo + num; }, 0);
        }
    )
  );
}
</code>```

Is this the proper implementation of the add function for points using Underscore.js or is there a better solution?

Body:
There are several methods you can use to perform this calculation. I am going to use your base 2d point object and extend it a couple of ways

// Base 2D Cartesian Point
var Point = function(x, y) {
  this.x = x;
  this.y = y;
};

Since Robert Harvey's suggestion is so straight forward, let's start with it:

var startpoint = new Point(0, 0);
var offsetpoint = new Point(startpoint.x + 5, startpoint.y + 5);

Next, you can add a function to the Point instance already created:

Point.add = function(x, y) {
  this.x += x;
  this.y += y;
};

As you have shown above, you can also modify the class prototype by changing Point.add to Point.prototype.add. The revised declaration adds the add method to all Point instances.

Suppose you want to pass a Point instead of x and y? We can do that too. We just can't use a polymorphic method declaration. We can, however, morph the function into a new function with different parameters. The down side to this is that, from that point on, you will not ever be able to get back to the first implementation with x and y without replacing the function again. That's probably too much for right now. Let's add the next version:

Point.prototype.addPoint = function(anotherPoint) {
    // Is the object being passed in of our class?
    if(anotherPoint instanceof Point) {
      this.add(anotherPoint.x, anotherPoint.y);
    }
};

Here is a jsfiddle with this code working.


答:
First of all: You are right, this is a real problem. As so often design issues surface when you try to test stuff. While testing is most of the time fairly easy if you have some design skills and OOP based code, things get tricky when the database gets involved.

One symptom is that if you want to have an entity A (i.e. an object persisted in a database) you need the full tree of dependencies and don't have an easy way to mock those.

The reason for this kind of problem is that there is no separation between runtime and compile time in databases, thus a dependency you want to have/use in runtime is there all the time.

A theoretical solution is to create a database system that actually has something like interfaces. But that is probably out of scope for most of us.

The more realistic solution is to separate the database very strictly from the rest of the code, thus isolating the big convoluted blob that is commonly referred to as database schema from the nicely structured application.

The first step is to have Repositories that return your entities and leak no information what so ever where and how these entities get persisted. A good way to ensure this is to have two implementations of those: one actually using your database and one using for example simple HashMaps for storage. The later are also very useful for testing. Be wary of any frameworks bleeding into your domain code. Hibernate for example has the habit of doing that by means of lazy loading and similar mechanisms.

The second step is to identify aggregates in the sense of Domain Driven Design. I.e. bags of  entities that get controlled by one entity and its repository, the entity root. For example LineItems of Orders should probably only loaded and updated via an Order, never on its own. But entities that belong to a different aggregate (for example customers) should get loaded via their own repository and not via some kind of magic lazy loading on navigation. This way   you can store different entities in different datastores, your application doesn't care about that. If they happen to be in the same database (as they probably do) they can have foreign keys, no problem.

There might be one technical challange with this approach caused by constraints: Normaly constraints get enforced on every single DML statement. If that causes you issues you might consider deferred constraints which only get enforced on commit. This might actually benefit performance, but also might make debugging more difficult, because now you might get foreign key violations on commit, long after your DML statements happened.

Title: OOP and relational databases


问:
Where should user permission checks take place in and MVC and by who?
Should user permission checks take place in the model or the controller? And who should handle the permission checks, the User object or some UserManagement helper?

Where should it happen?

Checking in the Controller:

```<code>class MyController {
  void performSomeAction() {
    if (user.hasRightPermissions()) {
      model.someAction();
    }
  }
  ...
</code>```

Having the checks in the Controller helps making the Models simple actions, so we can keep all logic to the Controllers.

Checking in the Model:

```<code>class MyModel {
  void someAction() {
    if (user.hasRightPermissions()) {
      ...
    }
  }
  ...
</code>```

By putting the checks in the Model, we complicate the Model, but also make sure we don't accidentally allow users to do stuff they aren't supposed to in the Controller.

And by who?

Once we've settled on the place, who should do the checks? The user?

```<code>Class User {
  bool hasPermissions(int permissionMask) {
    ...
  }
  ...
</code>```

But it's not really the user's responsibility to know what he or she can acccess, so perhaps some helper class?

```<code>Class UserManagement {
  bool hasPermissions(User user, int permissionMask) {
    ...
  }
  ...
</code>```

I know it's common to ask just a single question in, well, a question, but I think these can be answered nicely together.

答:
I use following scheme.
It worth to say that most user permissions checks can be divided into two general cases:

user access to controller action based on user role without checking
parameters action is called with,

user access to model based on any logic or relations between
particular user and particular model.

Access to controller action without checking of attributes are usually implemented in MVC frameworks. This is simple at all: you define rules, your users have role. You simply check that user has permission to action lookup up its role in rules.

User access to particular model should be defined in model. (Actor is base user class. Suppose it can be either customer, seller or guest.)

```<code>interface ICheckAccess
{
    public function checkAccess(Actor $actor, $role);
}

class SomeModel implements ICheckAccess
{
    public function checkAccess(Actor $actor, $role)
    {
        // Your permissions logic can be as sophisticated as you want.
    }
}
</code>```

Placing that logic in model brings some profit. Access check method can be inherited, you don't need to create any extra classes, you can use general OOP advantages.

Next, to simplify access checking, we take some assumptions that are almost always implemented already for simplicity and good style:

usually controllers are related to some model class;

actions which are checked for access take single model id as parameter;

this parameter can always be accessed uniformly from method of base controller class;

action is placed in controller corresponding to model which id action takes.

With these assumptions, actions that use model id can be associated with particular model instance. In fact, most actions can easily be transformed and moved to fit assumptions stated above.

Then, some base abstract controller class should be defined and inherited.

```<code>abstract class ModelController
{
    // Retrieve model from database using id from action parameter.
    public abstract function loadModel($id);

    // Returns rules for user role to pass to SomeModel::checkAccess()
    // Something like array('view' => 'viewer', 'delete' => 'owner', 'update' => 'owner')
    public abstract function modelRules();

    public abstract fucntion getIdParameter();

    public function filterModelAccess()
    {
        $id = $this->getIdParameter();
        if(!$this->checkModelAccess($id))
            throw new HttpException(403);
    }

    public function checkModelAccess($id)
    {
        $model = $this->loadModel($id);
        $actor = My::app()->getActor();
        $rules = $this->modelRules();
        $role = $rules[My::app()->getActionName()];
        return $model->chechAccess($actor, $role);
    }
}
</code>```

You can call SomeController::checkModelAccess($id) method when you construct your menus and decide whether to show some link.

Body:
I use following scheme.
It worth to say that most user permissions checks can be divided into two general cases:

user access to controller action based on user role without checking
parameters action is called with,

user access to model based on any logic or relations between
particular user and particular model.

Access to controller action without checking of attributes are usually implemented in MVC frameworks. This is simple at all: you define rules, your users have role. You simply check that user has permission to action lookup up its role in rules.

User access to particular model should be defined in model. (Actor is base user class. Suppose it can be either customer, seller or guest.)

interface ICheckAccess
{
    public function checkAccess(Actor $actor, $role);
}

class SomeModel implements ICheckAccess
{
    public function checkAccess(Actor $actor, $role)
    {
        // Your permissions logic can be as sophisticated as you want.
    }
}

Placing that logic in model brings some profit. Access check method can be inherited, you don't need to create any extra classes, you can use general OOP advantages.

Next, to simplify access checking, we take some assumptions that are almost always implemented already for simplicity and good style:

usually controllers are related to some model class;

actions which are checked for access take single model id as parameter;

this parameter can always be accessed uniformly from method of base controller class;

action is placed in controller corresponding to model which id action takes.

With these assumptions, actions that use model id can be associated with particular model instance. In fact, most actions can easily be transformed and moved to fit assumptions stated above.

Then, some base abstract controller class should be defined and inherited.

abstract class ModelController
{
    // Retrieve model from database using id from action parameter.
    public abstract function loadModel($id);

    // Returns rules for user role to pass to SomeModel::checkAccess()
    // Something like array('view' => 'viewer', 'delete' => 'owner', 'update' => 'owner')
    public abstract function modelRules();

    public abstract fucntion getIdParameter();

    public function filterModelAccess()
    {
        $id = $this->getIdParameter();
        if(!$this->checkModelAccess($id))
            throw new HttpException(403);
    }

    public function checkModelAccess($id)
    {
        $model = $this->loadModel($id);
        $actor = My::app()->getActor();
        $rules = $this->modelRules();
        $role = $rules[My::app()->getActionName()];
        return $model->chechAccess($actor, $role);
    }
}

You can call SomeController::checkModelAccess($id) method when you construct your menus and decide whether to show some link.


答:
Learning functional programming doesn't mean to forget what you already know.  For fixed two-dimensional coordinates, I would just use the following:

```<code>sum = [p1[0] + p2[0], p1[1] + p2[1]]
</code>```

If you don't know the dimension of your coordinates, or if it's large, the next best in this case is to use a list comprehension, which for some reason a lot of people forget about, or don't think it's "functional enough," because it resembles a for loop.  However, it is more powerful than a for loop as it is an expression that can be assigned, can be evaluated lazily, and is parallelizable if you don't introduce side effects.

```<code>sum = (p1[i] + p2[i] for i in [0..(p1.length - 1)])
</code>```

If you had a bunch of these to do, like addition, subtraction, multiplication, etc. you typically would create a function to do the iteration, which takes another function as an argument for what you want to do to each pair.  It would look like this:

```<code>corresponding = (p1, p2, f) -> f(p1[i], p2[i]) for i in [0..(p1.length - 1)]
</code>```

And you would use it like this:

```<code>sum  = corresponding(p1, p2, (i, j) -> i + j)
diff = corresponding(p1, p2, (i, j) -> i - j)
prod = corresponding(p1, p2, (i, j) -> i * j)
</code>```

Granted, that's not much shorter than the list comprehension, but a real world corresponding function would probably be significantly longer due to error handling.

Note that these examples are in CoffeeScript, as I'm not familiar with underscore.js, but the solutions are fairly typical of functional programming.

Body:
Learning functional programming doesn't mean to forget what you already know.  For fixed two-dimensional coordinates, I would just use the following:

sum = [p1[0] + p2[0], p1[1] + p2[1]]

If you don't know the dimension of your coordinates, or if it's large, the next best in this case is to use a list comprehension, which for some reason a lot of people forget about, or don't think it's "functional enough," because it resembles a for loop.  However, it is more powerful than a for loop as it is an expression that can be assigned, can be evaluated lazily, and is parallelizable if you don't introduce side effects.

sum = (p1[i] + p2[i] for i in [0..(p1.length - 1)])

If you had a bunch of these to do, like addition, subtraction, multiplication, etc. you typically would create a function to do the iteration, which takes another function as an argument for what you want to do to each pair.  It would look like this:

corresponding = (p1, p2, f) -> f(p1[i], p2[i]) for i in [0..(p1.length - 1)]

And you would use it like this:

sum  = corresponding(p1, p2, (i, j) -> i + j)
diff = corresponding(p1, p2, (i, j) -> i - j)
prod = corresponding(p1, p2, (i, j) -> i * j)

Granted, that's not much shorter than the list comprehension, but a real world corresponding function would probably be significantly longer due to error handling.

Note that these examples are in CoffeeScript, as I'm not familiar with underscore.js, but the solutions are fairly typical of functional programming.


答:
To address the differences you note first:

That your members are volunteers does not mean you can't ask them for a commitment. Especially with the relatively short duration of a sprint in Scrum, it must be possible for each of the members to know how much time they can commit to the project for the next few weeks. Having the team members available for a different amount of time each sprint will make the planning a bit harder, because it is harder to determine how many storypoints are realistic, but it does not make Scrum infeasible.

The product owner is responsible for consolidating and communicating the vision (and requirements) that the stakeholders have for the product to the development team. The consolidating part is probably already covered by the 'steering' committee. For the communication part, they can just delegate one of their members as their primary spokesperson. That one will then for all practical purposes be the product owner.

Not having an external deadline is not really a problem for Scrum. It just comes down more on the pride of the team in the product to get it finished. Scrum itself has a natural deadline for each sprint.

Regarding your proposed adaptations, especially when working with volunteers, I would strongly recommend to keep to the fixed sprint length. That way, the volunteers know definitely for which period they are giving off their commitment.

I also wouldn't ditch burndown charts immediately. They can also be useful for the team itself to see how they are doing on their commitment. I would leave it up to the team to decide to keep or ditch them. The same goes for the velocity calculations. especially with the large variation in available manhours each sprint, they can prove very useful (especially if you calculate the number of points completed per manhour) in estimating future sprints.

Regarding daily standups, they will still be useful in your setting, if only to let it be known what everyone is up to or has problems with (and that is independent of complexity). But it might be harder to realize a daily standup, so you might need to compromise there.

The XP practices you mention can be introduced or not independently of the use of Scrum and could also be proposed during a retrospective.

Title: How can Scrum be adapted to a Volunteer setting?

Body:
I have recently joined a young hackerspace still in the process of setting itself up.  We're fortunate because the space has a few internal projects that need working on and no shortage of volunteers to work on them.

There have been some discussions on how to organize these projects.  My most recent professional experience has been with Scrum so I'm considering pitching a Scrum approach for our software projects, but I'm not sure it will be a good fit.

Although I've seen Scrum work well for small full-time teams, the nature of this organisation is different:

The members are volunteers.  Some are full time students.  Others work jobs full time.  We can't expect a constant level of contribution from anyone as their real lives take priority.

While pretty much everyone has years of experience writing software, not many members have done so professionally or in teams.

There is no Product Owner.  The requirements for these projects are determined by a committee.  The members of this committee will also be working on the implementation.  This means we will have no single, dedicated, Product Owner.

We have no deadlines (soft or hard).  The projects will get done when they get done.

These are pretty significant differences, but I'm not convinced they will be blockers to applying Scrum.  I think some minor tweaking could get us over this hurdle:

If we change Sprints to have a fixed story-point size, but fluid duration (time), we can still benefit from iterative releases without putting unrealistic delivery pressure on volunteer devs.

We can ditch burndown charts and velocity calculation.  If I understand correctly, these are tools and metrics that work as a bridge between the dev team and the Management.  They serve to report progress in a form that is meaningful to both the developers and the stakeholders.  Considering we have no one to report to (no Project Manager, no Product Owner, and no outside stakeholders) I believe we can drop this altogether.

Things I think we could benefit from which won't require tweaking:

The Requirements Gathering meeting(s).  Where everyone sits around a table and discusses User Stories, sketches up UI mocks, and builds up a Product Backlog.

Sprint Retrospectives.  This will be an interesting way for us to converge on a development process that works for us as a team of volunteers.

Things I'm not sure about:

How should daily Stand-ups be treated?  I wonder if they would have much value at all in our setting.  My understanding of the stand-up ritual is that it helps communication by naturally disseminating information throughout the team.  Considering the fact that our Sprints will likely be delivering much less complexity than an average Sprint there might be less need to be abreast of all the other team members' progress/developments.

Should I push for XP things like Continuous Integration, Code Reviews, and TDD?  I'm concerned this will be asking for a lot.  I'd be more tempted to bring these concepts in on future projects once people are more familiar with Scrum and working as a team.

My Questions:

Can Scrum be adapted to a volunteer-based environment?

And, is my planned approach so far going in the right direction?


答:
As others have said a gantt chart (commonly informally referred to as a project plan) is a way of mapping tasks and the interdependencies between those tasks, the aim being to establish the minimum total elapsed time for a project.

From a management perspective the key output is the identification of the critical path, that is the list of tasks which if they are delayed then the project is delayed.

A very simple example - say two programmers are working on a project with three tasks (code module A taking one programmer 10 days, code module B taking one programmer 5 days, then integrate a and b taking both programmers 2 days).  The first two tasks (coding modules A and B) will be worked on in parallel and the aim is to complete all three tasks and thus the project it all in 12 days.

In this case the critical path is coding module A then integration testing.  The coding of module B can actually start 5 days late (or over run by five days) with no impact as even if it did finish on time, coding module A is going to take that much longer.  On the other hand if coding module A or the integration testing slips by any time at all, the whole project will slip.

Knowing this sort of thing helps you understand how to deploy resources and whether a delay to a particular task is likely to impact the whole project.

Are they useful?  Obviously yes, but with one significant caveat: only so long as the information that goes into them is good - that is:

the task list is complete

the estimates are accurate

the dependencies between tasks are comprehensive and

the resources representative of the team and correctly mapped to the task.

And from there the team has to work to the chart and carry out the tasks in the right order (no doing something that's more interesting that the assigned task as that will potentially delay something / someone else down the line).

If you do all that then yes, then it can really help you but the work does have to be put in up front to ensure it's accurate and realistic.

Title: What is the point of a Gantt Chart, and will it help me?

Body: My (non-technical) colleague has threatened me with a Gantt chart for a new project that we are currently planning.  What is this likely to provide for us, and will it be a helpful tool?</p>