答:
The classic approach in software reuse is to build components which depend on nothing else (that is what makes them low-level), and then build higher-level components which depend on lower-level components. "high level" and "low level" are specifially determined by the direction of the dependency, which is not inherent to the function of the component, but often just an architectural decision.

So, when single business applications are build with no dependency to workflow automation, but your work-flow controller has direct dependencies to the business application, then it should be clear that workflow automation is a "high level policy" and the business application is a "low level" component. Note that this structure is not obligatory - if your workflow automation component is a general framework, which is not coupled to your specfic business applications either, but can be configured to serve different applications, then you have already started to apply the DIP. In this situation, the "high level"/"low level" separation may not make sense between those two things any more.

So, the name "dependency inversion" is somewhat misleading - since dependencies are not "inversed", but completely removed (or to be more precise: changed from beeing compile time dependencies into run time dependencies).

Title: Dependency Inversion Principle: How to define "high-level policy" and "low-level detail" to other people?

Body: I am trying to explain the dependency inversion principle to my (mostly junior) colleagues. How can we define which one is the "high-level policy" and which one is the "low-level detail" in a software? For example, if our software automates workflow of several business applications, why do we say that the workflow automation is the high-level policy and the business applications are the details?</p>


问:
Which practice is the best for database connection? (PHP, etc)
Leave a open database connection throughout the execution of the aplication, or for each time a operation will be executed a new connection will be created?

Open throughout the execution:
Open aplication -> Open connection;
Operations -> use the opened connection -> commit;
Close aplication -> close connection;

For each time a operation will be executed:
Open aplication -> ...;
Operations -> create connection, execute operation, commit, close connection;
Close aplication -> ...;

答:
The best practice for database connections is the same regardless of the language used.

You have a pool of open connections at the start of your application. You take a connection from the pool as late as possible. Return it to the pool as soon as possible.

Never hold a connection out of the pool unless it is being used. Don't have Connections as member variables in a class. I've seen lots of horrible data layer wrappers that do nothing more than duplicate the API interface while introducing unnecessary state with the Connection.

The API you program against may hide the pooling implementation. But you will still be responsible for upholding the take late, return soon rule.

You should code in a style that guarantees the connection is returned to the pool in the event of an exception. This could be achieved with try/finally constructs in Java. "using" blocks in C#. RAII in C++.

ContentLicense: CC BY-SA 3.0


问:
unique_ptr and references - coding style question
I'm pretty sure this is a question purely about aesthetics but I wanted to get all your opinions on it before I start proliferating this type of code in my codebase. Consider the following code:

```<code>//Foo.h
class Bar;
class Foo
{
    public:
       Bar& GetBar(){return *bar.get();}
    private:
       std::unique_ptr<Bar> bar;
};

//Bar.h
class Bar
{
     public:
         DoSomething(){//did something...}
};
</code>```

This allows us to forward declare Bar in Foo.h and avoid having to #include Bar.h.
This leads to using Foo's Bar in the following way:

```<code>Foo foo;
foo.GetBar().DoSomething();
</code>```

Personally, I think this would look a lot nicer:

```<code>Foo foo;
foo.bar.DoSomething();
</code>```

To achieve that, I've written:

```<code>//Foo.h
class Bar;
class Foo
{
    public:
        Foo();
        Bar& bar;
    private:
        std::unique_ptr<Bar> bar_ptr;
};

//Foo.cpp
#include "Bar.h"
Foo::Foo() : bar_ptr(new Bar()), bar(*bar_ptr) {}
</code>```

This allows me to forward declare Bar and use the 'bar.' syntax.

Ugly? Not Ugly? The downside is that I have 2 member vars for only 1 object.

答:
```<code>foo.GetBar().DoSomething();
</code>```

This violates the Law Of Demeter.

Generally I would avoid exposing Bar entirely:

```<code>foo::doBarSomething() { this->bar.doSomething(); }
</code>```

Body:
foo.GetBar().DoSomething();

This violates the Law Of Demeter.

Generally I would avoid exposing Bar entirely:

foo::doBarSomething() { this->bar.doSomething(); }


问:
Dependency Inversion Principle: How to define "high-level policy" and "low-level detail" to other people?
I am trying to explain the dependency inversion principle to my (mostly junior) colleagues. How can we define which one is the "high-level policy" and which one is the "low-level detail" in a software? For example, if our software automates workflow of several business applications, why do we say that the workflow automation is the high-level policy and the business applications are the details?</p>

答:
I use a simple image to explain DIP. The classic view of software development is as a construction process with each layer sitting on top of the lower layers that support it. Using the Dependency inversion Principle is more like building a mobile.

Rather than the higher layers sitting on the lower layers, the higher layers in the mobile interface with the lower layers via the string that connects them. In a way, the lower layers depend on that interface for support (without the string they'd fall). That's DIP in a nutshell.


问:
VB.Net vs C# debate
I've been in workplaces where, at the start of a project, the "Should we use VB.Net or C#" question has been raised.

Granted, it's probably less common to have to make that decision now than it was in the early days of .Net, particularly given the trend towards language convergence, but it can still be a heated debate.

So, between VB.Net and C#, Which language do you prefer and why?

答:
I develop in Visual Basic .Net since 2001 and I love it and I hate it!!!

The order of presentation of these points is just based on the order in which he came to my mind...

In vb.net with visual studio, there is a visual line break between each method, property. For many people, it's not a good reason to prefer vb.net over c# but I don't understand why the c# team at Microsoft don't have implemented it. There is a add-in that draw this line in c# but thanx again Microsoft to have a c# team and visual basic team that don't talk to each other.

In vb.net, when you create a winform, you have two combobox in visual studio at the top of the editor and you can auto-generate event automatically when selecting an event on the right combobox. When you attach dozens of events each day, it can be very cumbersome to don't have this feature. With c#, you have a small button at the top of the property grid that can generate event but it's not fast as in vb.net. More, if you attach event of control in c# and delete the control on the form, the delegate created on the auto-generated code to handle event have to be deleted manually. Thank you again Microsoft.

In vb.net, when you try to modify a method that contain a linq query without modify the query itself, no problem but in c#, all the method code is locked. If you have a lots of linq queries or lambda expression, the edit and continue feature will rapidly be a good old thing. Ok, a little bit of exaggeration... but :)

In vb.net, when you create a method name and tap enter, the 'end sub' will be automatically created. In c#, do it yourself. Ok, if you have resharper or devexpress installed, it will be better but why all these little but greats features were not be implemented in c#.

In vb.net, when you have errors on your code, the errors are automatically displayed and when you correct it, these errors are removed of the stack in real time. In c#, you have to build your project to realize that you have successfully corrected or not the specified errors. Why c# team don't have put an option to verify in real time error like in vb.net. With big solution, no real time verification of error can be a very nice optimization of performance but I love to see a stack of error disapear while I correct it.

Like other person have mentionned, I think it's more easy to read vb.net condition if..end if, select case... end select but with devexpress painting bracket, forget what I said.

With vb.net, there are many many bugs in visual studio. Just to mention one in visual studio 2010, the intellisens don't filter correctly enumeration if you have the mode "common" activated instead of "all".

With vb.net, you are perceived as a dummy guy because statically, more bad programmers use vb.net instead of c# because c# is harder to learn and promote better programming practice.

Like other said, c# programmer have better chance to have a good job with more money.

In the head of customer, vb.net = guy who program in his basement with a bol of spaghetti of code. c# = wow, you are very intelligent. The fact is that it's not because you program in c#, that you make a good program but statically, yes.

With all these points, I chose to convert all my vb code in c#. I program with all the best practices of object oriented, design pattern, clean code with standards and strict syntaxe and I can program like that for 50 years but from the eyes of community, I'm not a good programmer. I will convert my code in c# with no other best practices and I will be another person; a great guy who you must respect..... :( what a joke...!!! but it's the reality.

ContentLicense: CC BY-SA 2.5

Title: VB.Net vs C# debate

OwnerDisplayName: Samuel


问:
Rush to client-side in web development
In the past few months, I recognized a big excitement about client-side scripting in web development. But while server-side technologies are mature, stable and well accepted by backend-developers, client-side technologies are immature (i.e. compared to big server-side framework) and disliked by many long-established developers. Nevertheless everyone is doing client-side development these days. I personally expect those big server-side frameworks to disappear in like 2-5 years, watching the current trend.

Why is that so? How could the new and "diffuse" client-side developing in HTML5/JS possibly be superior to big and well thought server-side solutions?

答: Absolutely agree with your sentiments. I also believe that beyond what you're saying we're going to see a dramatic drop in REST and massive upsurge in websockets for the main way we see sites communicate back to their servers. Vert.x, Node.js etc.. the entire server side, as well as client side, is moving to event driven programming. Java EE, PHP, Rails, etc.. they all need to adapt or they'll lose very quickly.</p>

Title: Rush to client-side in web development


问:
Detecting areas of isotropic vs anisotropic diffusion in a flood-fill (or similar) operation
Hello fellow programmers!

I have a 2D graph which is best described as a Cartesian grid with traversible and non-traversible cells.  I'd like to be able to detect subsets of this graph where the diffusion behaves anisotropically, i.e.: it is constrained by corridor-like passages.

I initially turned to diffusion tensor imaging in neuroscience, but I'm having a great deal of trouble digesting the material.  I'm wondering if any of this has already been distilled into a usable algorithm, or if there are other approaches that could be fruitful.

Specifically, I'd like to be able to determine the following:

Areas in which diffusion is anisotropic:  highly constrained to two directions (think of water flowing through a 2D slice of a straw).

Areas in which diffusion is isotropic: largely unconstrained (i.e., water is diffusing through a large, though irregularly-shaped space.

Since the graph only contains very narrow or open areas, it would be sufficient to determine either anisotropic or isotropic diffusion and deduce the other one with a simple contrast.

TL;DR:  How can I find the "average" direction of a diffusion in a flood-fill or similar operation?

EDIT: Here's an example of my graph as an image:

答:
I'm not aware of any known solutions, but at first thought a simple flood fill that fills based on connectivity might work.

Assumptions:

Every node's 'openness' will be a function of its connectivity to other nodes. That is, in a bi-directional graph that simulates a square grid, a completely open node will have 8 edges.

Untested, but the following pseudocode might be capable of finding open areas.

```<code>public class graph
{
    private static List<node> GetArea(node n)
    {
        if (isConnectedEnough(n))
        {
            yield n;
            yield! GetArea(n.neighbours)
        }
    }

    private static bool isConnectedEnough(node n)
    {
        return n.neighbours.Count >= 3;
            /* better: a connectivity threshold function */
    }
}
</code>```

I envisioned calling GetArea sequentially on the list of all nodes in the graph sorted by connectivity until an area of sufficient size was found. Depending on the characteristics of your graph(s) that might not be sufficient, but I was going on the assumption that the graph was structured such that there were numerous areas separated by passageways (ie. rooms connected by hallways).

The connectivity threshold is the key in this situation. Some experimentation would be required here based on the characteristics of your graph(s) because:

If the average connectivity of the neighbouring nodes is equal to the connectivity of n then the area is very possibly consistent in size (ie. not approaching a choke point, also not expanding in size).

If the average connectivity of the neighbouring nodes is larger than the connectivity of n then we may be expanding into an area. Depending on how you define an area, that may be fine, (potentially describes a "pinch" in an area). Careful consideration should be considered here because this also describes corners and "corridors" of width 2 nodes/1 edge (min threshold of 3 would permit corners in the area).

That's all I've got for now, but I'll check back in here. This is an interesting problem.

Body:
I'm not aware of any known solutions, but at first thought a simple flood fill that fills based on connectivity might work.

Assumptions:

Every node's 'openness' will be a function of its connectivity to other nodes. That is, in a bi-directional graph that simulates a square grid, a completely open node will have 8 edges.

Untested, but the following pseudocode might be capable of finding open areas.

public class graph
{
    private static List<node> GetArea(node n)
    {
        if (isConnectedEnough(n))
        {
            yield n;
            yield! GetArea(n.neighbours)
        }
    }

    private static bool isConnectedEnough(node n)
    {
        return n.neighbours.Count >= 3;
            /* better: a connectivity threshold function */
    }
}

I envisioned calling GetArea sequentially on the list of all nodes in the graph sorted by connectivity until an area of sufficient size was found. Depending on the characteristics of your graph(s) that might not be sufficient, but I was going on the assumption that the graph was structured such that there were numerous areas separated by passageways (ie. rooms connected by hallways).

The connectivity threshold is the key in this situation. Some experimentation would be required here based on the characteristics of your graph(s) because:

If the average connectivity of the neighbouring nodes is equal to the connectivity of n then the area is very possibly consistent in size (ie. not approaching a choke point, also not expanding in size).

If the average connectivity of the neighbouring nodes is larger than the connectivity of n then we may be expanding into an area. Depending on how you define an area, that may be fine, (potentially describes a "pinch" in an area). Careful consideration should be considered here because this also describes corners and "corridors" of width 2 nodes/1 edge (min threshold of 3 would permit corners in the area).

That's all I've got for now, but I'll check back in here. This is an interesting problem.


问:
Do tools, like Windows Workflow, inhibit development growth?
I’ve had this gut feeling about Windows Workflow (WW) for a while now. And, until now, I couldn’t think of the right words to say in order to explain it. Since I think I have a good way to verbalize it now, I thought I’d share.

I believe there is a problem in our industry where a great percentage of developers take a long time to understand simple, solid OOP principles and design patterns. Indeed, many developers never reach this level of understanding. My unsubstantiated concern is that tools like WW further shield developers from good design. The reason for this is that, absent WW, a developer could be shown how to write code using a state pattern, or chain of responsibility pattern, or a rules engine, or even simple OOP. Many developers simply don’t know how to implement polymorphism. My fear is that tools like WW provide an abstraction that hides, or inhibits, good design by simply providing a way for developers to click boxes on a canvas and write code in those boxes. What’s going on under the hood, or what should be going on under the hood, is lost to the developer.

Do tools, like Windows Workflow, inhibit development growth?

Disclaimer: I have not used WW. There may be great use cases for using it. My thoughts, above, are simply a gut feeling, and I'd be curious to know how others feel about the topic.

答:
Windows Workflow is an abstraction, just like WPF, EF, Windows, and every programming language  in existence.  Like all good abstractions, it provides a way to leverage foundational concepts, building on the ideas created by others and improving on them.

Without abstractions, there would be no growth at all, and no civilization (as we know it).

Excellent software developers know how to take apart these abstractions and understand the underlying principles.  The average ones just learn the abstractions and use them to build programs, and there is nothing wrong with that.


答:
These tools and frameworks don't inhibit growth, they foster growth in different directions.  There are many pieces required to build complex computational systems, some of those are core or common features like DB layers, UI frameworks, communication layers... Other pieces involve business or domain knowledge to implement the application functionality.

Some developers will work on those foundational pieces and their growth will be in those areas.  Other developers will take these components and build them into a system, and their growth will in those larger view areas.

Body:
I’ve had this gut feeling about Windows Workflow (WW) for a while now. And, until now, I couldn’t think of the right words to say in order to explain it. Since I think I have a good way to verbalize it now, I thought I’d share.

I believe there is a problem in our industry where a great percentage of developers take a long time to understand simple, solid OOP principles and design patterns. Indeed, many developers never reach this level of understanding. My unsubstantiated concern is that tools like WW further shield developers from good design. The reason for this is that, absent WW, a developer could be shown how to write code using a state pattern, or chain of responsibility pattern, or a rules engine, or even simple OOP. Many developers simply don’t know how to implement polymorphism. My fear is that tools like WW provide an abstraction that hides, or inhibits, good design by simply providing a way for developers to click boxes on a canvas and write code in those boxes. What’s going on under the hood, or what should be going on under the hood, is lost to the developer.

Do tools, like Windows Workflow, inhibit development growth?

Disclaimer: I have not used WW. There may be great use cases for using it. My thoughts, above, are simply a gut feeling, and I'd be curious to know how others feel about the topic.


答:
I don't think a tool is what inhibits growth of a developer anymore than a specific tool can inhibit the growth of a carpenter (unless it's a poorly made tool). What inhibits growth is complacency. When I've gone through hiring processes, I've come across developers with years of experience with .NET and a number of successful projects but don't really know much beyond the basics of syntax and using the designer (and it happens with other mature platforms as well, it's just that there are soooooo many .NET developers, you run across this phenomenon more frequently).

I call it the M. Night Shyamalan/Tyler Perry syndrome. Success breeds complacency. Shyamalan had success with the "epic twist" gimmick and felt the need to make that a part of every movie rather than...learning how to write a better story. Tyler Perry has had a lot of success writing Moral Plays, now he has about 20 movies out that for the most part are essentially the same. A developer who has success using the basic tools (which is quite possible) runs the risk of becoming complacent and not pushing himself to learn more. You can have quite a successful career doing it.

The tools aren't to blame, lack of passion is.

Title: Do tools, like Windows Workflow, inhibit development growth?


问:
What's the first language that had the 'Unless' conditional/loop built into itself?
What's the first (oldest) language that had the 'Unless' conditional/loop built into itself?

Where an example could be

```<code>unless (myVar) == if (!myVar)

until (myVar) == while (!myVar)
</code>```

答:
actually I've found a copy of the 1967 BCPL language manual with the UNLESS statement in it on section 6.7

http://www.fh-jena.de/~kleine/history/languages/Richards-BCPL-ReferenceManual.pdf

this was also the first language to demonstrate the "Hello World" program

BCPL became "B" at Bell Labs and then later "C"

the joke was that the real question was what would the next language be "P" from the BCPL or "D" from the Alphabetic order


问:
Is what someone publishes on the Internet fair game when considering them for employment as a programmer?
(Originally posted on Stack Overflow but closed there and more relevant for here)

So we first interviewed a guy for a technical role and he was pretty good. Before the second interview we googled him and found his MySpace page which could, to put it mildly, be regarded as inappropriate.  Just to be clear there was no doubt that it was his page (name, photos, matching biographical information and so on).

The content was entirely personal and in no way related to his professional abilities or attitude.

Is it fair to consider this when thinking about whether to offer them a job?

In most situations my response would be what goes on in someone's private life is their own doing. However for anyone technical who professes (implicitly or explicitly) to understand the Internet and the possibilities it offers, is posting things in a way which can so obviously be discovered a significant error of judgement?

EDIT: Clarification - essentially it was a fairly graphic commentary on porn (but of, shall we say, a non-academic nature).  I'm actually more interested in the general concept than the specific incident as it's something we're likely to see more in the future as people put more and more of themselves on-line.

My concerns are not primarily about him and how he feels about such things (he's white, straight, male and about the last possible victim of discrimination on the planet in that sense), more how it reflects on the company that a very simple search (basically his name) returns these things and that clients may also do it.  We work in a relatively conservative industry.

答:
It is hard to say without knowing the exact nature of his commentary. If he is giving a fairly graphic description of his weekend exploits then I doubt many people would have an issue with it. Most people say and think similar things but just don't post it publicly.

Having said that, when you hire you have to hire people with the character that will fit in with your company and that goes beyond just basic competence. Hiring someone who can't stop talking to work in a library is probably not a good idea, even if they can recite Shakespeare.


答:
There have been of course some examples in the past where newer technologies provided abstraction which made programming easier or for some cases even obsolete. I can think of

the invention of higher level programming languages (you did not need to learn assembler any more)

the invention of spreadsheets (allows users to solve a lot of problems without any programming)

SQL databases (a SQL query written in 20 minutes can replace a 1-developer-week program in pre-SQL technologies)

graphical UI designers

the wide adoption of programming languages with automatic memory management (instead of manual memory management)

And yes, each of that tools may have changed or reduced the need for certain development skills (for example, the need for assembler programmers). Thus, one could argue that they inhibit the growth of that skills. On the other hand, the also have increased the need for different, new skills - for example, SQL programming is a craft on its own.

For what I know about WW, however, there is absolutely no reason to believe this will have a similar influence like the examples above - the range of applications where this gives real benefits is IMHO just too small.


答:
I have worked a lot with tools of this general type ( not WW specifically but similar ) and my experience has been that they seem as though they will allow you to abstract away a bunch of functionality. That is their selling point.

There are many wheels in this world, there is no value for us as programmers inventing more of them. Why not abstract away some of those things not that we don't know how to do, but precisely that we have all done enough times that the prospect of doing it again is really unappealing. If we have a nice reliable tool that has been well tested by the vendor and ties into their operating system ( or is open source and well supported or whatever ) what reason could we have to justify not using it?

The practice has been, in my experience, that in many cases it would have been quicker to write it ourselves than to use the vendors tool and that for all the abstraction offered, you still end up needing to understand the internals of nine different libraries and the quirks of calling five different APIs and why they will work in this environment but won't work in that environment and actually maybe they aren't as well supported as they looked and it may just be the case that if we had written something ourselves for our specific situation it would probably have been quicker, performed better and saved us a whole bunch of headaches.

It doesn't always happen like that. But often, I'm sorry to say, it does.


问:
Creating a text input simplifaction tool
I have been working on a project for several months now to write a web-based tool that will help me at work. I work at a call center and the CRM software that is used is wretched, we basically have to input all of our information into notepad templates and then paste it in to a description box.

My initial goal was to create a web-interface for the templates so that I didn't have to use notepad anymore. I was just going to write it with HTML5/CSS/JS, both as a learning experience and, if I was fortunate enough, an opportunity for advancement.

As I worked on coding this tool I continuously found myself changing the foundation of the project, attempting to integrate more functionality in my tool. It has gotten to the point where I want the tool to be used alongside the CRM software for every call I receive. I want to be able to simply copy the customer's information off of CRM (simply with Ctrl + A/Ctrl + C), then be able to paste the block of jumbled text into a text box. The program will then pick out the customer's info by looking for keywords in specific positions to fill out a user selected template. The rest of the information is input manually and then the output is generated with the push of a button. The information will also be parsed into a backup text file. The text file will be created automatically based on the date. If the text file for the current date exists, it will simply concatenate the info.

As I wrote my code I found myself getting distracted looking at different coding languages and possibilities. I kept looking back at what I had completed and I was disappointed, I've started over from scratch two times now.

Now for the actual question: I am thinking of starting over, writing my program with AngularJS. I like the idea of a smooth, single page, app-like interface, but I'm scared of hitting more barriers and starting over using something else. Based on my description of how I want my program to run, can anyone suggest how to go about implementing this? Should I look into a different language, or is JS really the way to go these days? I just discovered Dart and am intrigued, but the idea of learning yet another language is discouraging instead of exciting. I feel like I'm missing a pretty big point.

I hope this question is appropriate for this forum. I feel a bit lost with StackExchange, and the last thing I want to do is receive negative attention for a bad post. I'm just feeling a bit lost when it comes to this project, and perhaps even programming in general. Regardless, any feedback will be appreciated. Even direction to a forum for emotionally distraught fledgeling programmers would be a welcome answer. >.<

Thank you.

答:
This sounds like the exact kind of job people used PERL for back in the day. Most of it was very simple to set up. We would create a HTML form or two. The information was submitted to a Perl (later Python) script that easily pull info out and merged it into templates. The regular expressions and string processing features will help with requirements like matching keywords. There is also many tutorials and code samples on the net for problems like this. Most modern scripting languages have enough functionality built in to easily do what you're describing if you don't like PERL. </p>

<p>One other suggestion I'd make is to build this thing gradually. Break this application into several manageable pieces. Build the first piece that helps you a little bit. Then the next and so on. Each successful improvement will give you confidence and mental energy to keep on the project. Breaking it into several deliverables will also help avoid scope creep or a feeling of being overwhelmed. </p>

Body:
This sounds like the exact kind of job people used PERL for back in the day. Most of it was very simple to set up. We would create a HTML form or two. The information was submitted to a Perl (later Python) script that easily pull info out and merged it into templates. The regular expressions and string processing features will help with requirements like matching keywords. There is also many tutorials and code samples on the net for problems like this. Most modern scripting languages have enough functionality built in to easily do what you're describing if you don't like PERL.

One other suggestion I'd make is to build this thing gradually. Break this application into several manageable pieces. Build the first piece that helps you a little bit. Then the next and so on. Each successful improvement will give you confidence and mental energy to keep on the project. Breaking it into several deliverables will also help avoid scope creep or a feeling of being overwhelmed.


问:
Performance considerations when using Go for my project
I'm looking at using Go (aka golang) for a project (a SQL database, but that mostly doesn't matter here) where performance is critical, but under low load the primary bottleneck will be I/O to disk. In this case, I think Go would be great!

Under high load or while hitting cache a lot, CPU and memory utilization will increasingly become bottlenecks, and I'm worried that Go could make the high-end of the performance spectrum significantly lower than what C/C++/D might provide.

Can anyone with experience working in Go give some insight into how quickly that bottleneck is reached (networking applications are subject to the same bottleneck, typically) and what you can do to relax it in Go other than rewriting the bottleneck in a faster language?

Note my question was sufficiently different that I asked it anyway after reading related question:

https://softwareengineering.stackexchange.com/questions/160651/what-kind-of-software-is-done-best-with-the-go-programming-language

I have a specific application I'm asking about, and I've limited my concerns to performance (not usability, library support, development tools, etc).

答:
What was said in another answer. I'll add that in garbage collected languages it pays to write the code in a way that's easy for the collector to work with.

Go also has a profiler you can use when experimenting with different code samples. You can also look at Doozer (written by a top Go coder) and sample projects (link below) for ideas on how to squeeze the most performance out of go.

https://code.google.com/p/go-wiki/wiki/Projects


问:
How to deal with management staff (company owner) that downplays the impact of specs changes?
I work in a small web development company (3 programmers) for a while. During the last year the company had hard times (less projects) and a few co-workers were fired, including our Production Manager. Having this person out of our team mean to us that we have to deal more and more with the company bosses (owners). It's them who meet the clients and discuss about upcoming projects (custom web app for example)

We had a meeting with the boss this week about a particular project for which he wants the specs to change (add a few features). I understand that in the real world specs always change during a project (I'm in this business for almost 10 years, I already figured that). What I am having hard time with is when the boss keeps trying to minimize the complexity, the impacts of the new specs because in his mind those changes are not that hard and should not take a lot more time (especially because he already signed a contract with our client for a fixed amount of money). With one programmer co-worker we joked about that, saying that it's not by adding two wings on a car that you will make plane, it has major impact on the whole design of the vehicle, time required is not the same, so is the same with software.

Any idea how we should handle that kind of attitude from a boss? Is it possible to make him change his minding in that kind of situation ?

答:
It's hard to work with boss who doesn’t understand our work. I had that kind of experience and It was the worst time in my live.

I think you should talk with your boss like a child(show him pros and cons of his decisions), you should explain him how it should works, maybe you can even buy him some book if he has sense of humor.

But to be honest many things depends on the agreement which your boss will sign with client. I know that sometimes complexity is minimized  because company wants to win contract and after that they talk with client again and complexity is increasing and then company earn more. The second case when complexity is minimized is when company knows that client will give us more task in the future - it's like throwing bait.
And the worst explanation of that behavior is inappropriate person.


问:
Is MVC the optimal pattern to build a RESTful web service?
Not being a Java practitioner, I recently came to learn about the JAX-RS specification and Apache CXF framework. While still wrapping my head around all these things, I also read the this question on SO.

Since MVC is a design pattern while JAX-RS is a specification, I was confused about the comparison. Granted my nascent understanding of JAX-RS, what makes it more suitable for implementing a RESTful API than say a framework that uses the MVC pattern?

N.B. I have a C and Python background.

答:
I don't think that one could say whether any specific pattern is "optimal" for something as broad as RESTful service development. Whether that pattern is optimal depends on your business needs, design, and whether it solves a problem for you.

That said, the MVC concept can be very useful in REST development. The mindset of separating your business logic (models, controllers) away from the HTTP protocol details (view) can keep your code more flexible/reusable. It would allow you to add other protocols on top of your service more easily. For example, you could support SOAP, REST, and a custom binary socket protocol as your "views" which all use the same core logic.

As far as comparing frameworks (JAX-RS, Apache CXF, other MVC frameworks), that's more of an issue of finding one that meets your needs. You'd have to consider factors like maturity, how familiar your developers are with it, community, etc. It's important to not conflate frameworks and patterns (even though many frameworks define themselves on an implementation of a pattern).


答:
Give him detailed time estimates with exactly the tasks you have to do to make the change. Do the time estimates in excrutiating detail. Make sure you include things like communication (emails and meetings), unit testing, QA, deployment, documentation, research and design not just development (and make sure you put in lots of steps inteh devlopement part). The only way to educate him is to show him the detailed impact. In our company all spec changes are changes to the estimate and all of them are sent to the client so they know the impact of the change on the deadline and the amount of money it will cost them. Now that they understand that changes aren't free, we have far fewer changes.

I would suggest you create a time estimate template to use for the future.

If this doesn't make him start to understand the impact, then he never will and it is time to move on before you are in a series of death marches that take up all your personal time to meet his unrealistic deadlines.

Title: How to deal with management staff (company owner) that downplays the impact of specs changes?

Body:
I work in a small web development company (3 programmers) for a while. During the last year the company had hard times (less projects) and a few co-workers were fired, including our Production Manager. Having this person out of our team mean to us that we have to deal more and more with the company bosses (owners). It's them who meet the clients and discuss about upcoming projects (custom web app for example)

We had a meeting with the boss this week about a particular project for which he wants the specs to change (add a few features). I understand that in the real world specs always change during a project (I'm in this business for almost 10 years, I already figured that). What I am having hard time with is when the boss keeps trying to minimize the complexity, the impacts of the new specs because in his mind those changes are not that hard and should not take a lot more time (especially because he already signed a contract with our client for a fixed amount of money). With one programmer co-worker we joked about that, saying that it's not by adding two wings on a car that you will make plane, it has major impact on the whole design of the vehicle, time required is not the same, so is the same with software.

Any idea how we should handle that kind of attitude from a boss? Is it possible to make him change his minding in that kind of situation ?


答:
There's likely nothing you can do now for this project. However, if you have the ability to track your time against both the original features and against the changes separately, do so. Once the project is over, do a retrospective.

Did you come in early and under budget? If so, your estimations are off and your boss is right. If you came in over budget / late, see if the amount of overages equates to the time spent on the new changes.

If you start doing this for all your projects, eventually you should see a trend. Likely, that the more features that are added after the original estimate, the later the projects are.

Don't do this to prove you're right and your boss is wrong. The goal isn't to prove that somebody is wrong, the goal is to learn how work together to make better estimates. If the projects are often late and changes are often made after the initial estimation, you'll have the information you need to make some changes in how you work.


答:
This happens where I work too -- the client will keep requesting little changes that end up causing us to go over schedule/budget. (I'm going to call this phenomenon "requirements creep" since it seems like it might be a cause of/related to feature creep in software).

Something we did on a recent project that I think might help combat requirements creep is that the higher-ups decided to go with a phased approach by offering a core set of functionality at the end of phase 1 then planning to meet extra requirements as part of a phase 2. Doing things this way would hopefully allow you to deliver a quality phase 1 product by the initial deadline at or under budget.

The second phase would of course have it's own deadline and payment, which your boss would probably like since it'd be more money. (Phase 3: profit!)

This might not be helpful if the phase 1 part takes longer than the initial deadline or if your boss doesn't realize there is a problem, but it's something you might suggest to him.


问:
Possible solutions for sharing working copy of project between multiple computers?
So there are 3 computers that I use to work on this project with, my home PC, work PC, and work Mac (for building to devices). The project has an SVN repository that two other programmers use so I can't commit broken code to it. The lead doesn't know how to use version control so the trunk contains art assets and everything else in addition to the project itself, making branching impractical (and I wouldn't want to use svn for branching anyway). I would use GIT if I could but it is not an option.

My question is, how can I go to work, update my working copy, work on it a bit, send it to my mac for building, then go home and work on it some more later- keeping in mind that I may go 1-2 days without being able to commit working code to the repository?

答:
Why don't you use git locally to share your code with your three development machines/environments, and then just use SVN to do the commits that go to the rest of your development team.

This way, you can use git without locally without making the rest of your team use it.


问:
Readable regular expressions without losing their power?
Many programmers know the joy of whipping up a quick regular expression, these days often with help of some web service, or more traditionally at interactive prompt, or perhaps writing a small script which has the regular expression under development, and a collection of test cases. In either case the process is iterative and fairly quick: keep hacking at the cryptic-looking string until it matches and captures what you want and will reject what you don't want.

For a simple case result might be something like this, as a Java regexp:

```<code>Pattern re = Pattern.compile(
  "^\\s*(?:(?:([\\d]+)\\s*:\\s*)?(?:([\\d]+)\\s*:\\s*))?([\\d]+)(?:\\s*[.,]\\s*([0-9]+))?\\s*$"
);
</code>```

Many programmers also know the pain of needing to edit a regular expression, or just code around a regular expression in a legacy code base. With a bit editing to split it up, above regexp is still very easy to comprehend for anyone reasonably familiar with regexps, and a regexp veteran should see right away what it does (answer at the end of the post, in case someone wants the exercise of figuring it out themselves).

However, things don't need to get much more complex for a regexp to become truly write-only thing, and even with diligent documentation (which everybody of course does for all complex regexps they write...), modifying the regexps becomes a daunting task. It can be a very dangerous task too, if regexp is not carefully unit tested (but everybody of course has comprehensive unit tests for all their complex regexps, both positive and negative...).

So, long story short, is there a write-read solution/alternative for regular expressions without losing their power? How would the above regexp look like with an alternative approach? Any language is fine, though a multi-language solution would be best, to the degree regexps are multi-language.

And then, what the earlier regexp does is this: parse a string of numbers in format 1:2:3.4, capturing each number, where spaces are allowed and only 3 is required.

答:
I thought it'd be worth mentioning logstash's grok expressions.
Grok builds upon the idea of composing long parsing expressions from shorter ones. It allows convenient testing of these building blocks and comes prepackaged with over 100 commonly used patterns. Other than these patterns, it allows use of all regular expressions syntax.

The above pattern expressed in grok is (I tested in the debugger app but could have blundered):

```<code>"(( *%{NUMBER:a} *:)? *%{NUMBER:b} *:)? *%{NUMBER:c} *(. *%{NUMBER:d} *)?"
</code>```

The optional parts and spaces make it seem a bit uglier than usual, but both here and in other cases, using grok can make one's life much nicer.

Body:
I thought it'd be worth mentioning logstash's grok expressions.
Grok builds upon the idea of composing long parsing expressions from shorter ones. It allows convenient testing of these building blocks and comes prepackaged with over 100 commonly used patterns. Other than these patterns, it allows use of all regular expressions syntax.

The above pattern expressed in grok is (I tested in the debugger app but could have blundered):

"(( *%{NUMBER:a} *:)? *%{NUMBER:b} *:)? *%{NUMBER:c} *(. *%{NUMBER:d} *)?"

The optional parts and spaces make it seem a bit uglier than usual, but both here and in other cases, using grok can make one's life much nicer.


答:
the trunk contains art assets and everything else in addition to the
  project itself, making branching impractical

Big Error one: server-side branches are cheap-copies, if you already have WC of trunk, create (server-side) branch and switch to it it costs nothing in traffic (and minimal traffic for updating non-synced files on changing back to trunk - without downloading the whole trunk conent)

(and I wouldn't want to use svn for branching anyway)

Big Error two - branches is your case, perfectly valid and easy way

Title: Possible solutions for sharing working copy of project between multiple computers?

Body:
So there are 3 computers that I use to work on this project with, my home PC, work PC, and work Mac (for building to devices). The project has an SVN repository that two other programmers use so I can't commit broken code to it. The lead doesn't know how to use version control so the trunk contains art assets and everything else in addition to the project itself, making branching impractical (and I wouldn't want to use svn for branching anyway). I would use GIT if I could but it is not an option.

My question is, how can I go to work, update my working copy, work on it a bit, send it to my mac for building, then go home and work on it some more later- keeping in mind that I may go 1-2 days without being able to commit working code to the repository?


答:
If you would like to use git but you are stuck with SVN you might want to take a look at git svn:

https://www.kernel.org/pub/software/scm/git/docs/git-svn.html

https://git.wiki.kernel.org/index.php/GitSvnCrashCourse

In your case it might be beneficial that Git repositories work disconnected from a central server which seems to fit the "at home" use case (depending on your connection and network settings, etc.).

Another thing to explore is, whether your lead has a strong opinion on the version control management or whether the lead is indifferent to it. The lead might have good arguments after all. For one thing putting binary into Version control systems is a valid use case for some applications (i.e. to keep a valid history of the project with code and binary data matching up, otherwise one might end up with disfunctional snapshots because binary data such as images etc are missing, this is very different from lets say checking in object files, or compilation products).


问:
Most MVC-strict php framework
I have been trying to wrap my head around MVC pattern for about 6 months.I've read tons of articles, Q&A, and blog posts about MVC and HMVC patterns, but I just simply don't get it 100%.

I tried learning MVC by exercising one of widely used PHP MVC framework, CodeIgniter. I've implemented few internal websites for my company with it. And STILL, I don't 100% get it. I believe one of the best ways to learn something is to follow strictly defined rules.

So my question is: What is the most strict PHP framework in terms of how MVC pattern is implemented? One that defines how I use models, controllers, and views so that I can completely get what MVC is?

答:
Short answer

There is no such thing.

Longer version:

Frameworks do not implement MVC or MVC-inspired design pattern. Your application does.

MVC is not some magic sauce, that you can add to your application by dumping it in a framework. Instead, you would actually have to learn and understand said pattern (and the accompanying principles and practices, like SOLID, LoD, SoC). Only then you can try to use it within your choice of a framework.

If a framework advertises that it "has MVC", then it is completely utter dren. In that situation, it is used to "sell" the framework to the noobs that care more about the latest hype then about application design and coding practices.

The goal of a framework would be to provide you collection of tools, that, when used as whole, provide you with an altered/improved development environment. They deal with such things as routing, autoloading, low level abstractions for storage (no, I am not talking about active record anti-pattern) and the rest of thing that let save you time in boh development and maintenance.

In conclusion.

There are no MVC frameworks in PHP. All of those who claim to me such are actually among the worst ones. Namely - codeigniter, cakephp and yii. Avoid them at all costs (except if you get paid really well for it).

If you need to use a framework, currently your best options would be latest version of Symfony 2.x, Zend Framework 2.x or Laravel 4.x. These ones will not implement MVC for you, but instead will do the least harm for you own application architecture.

Title: Most MVC-strict php framework


问:
Extreme Programming practices make an application more error prone?
I am conducting academic research on the topic of Extreme Programming and whether its practices lead to creating space for more errors and bugs in applications.

From the experiences I gathered from many, I have comments that fall on both sides.  Many support it and consider it a daily necessity, with dynamics that can facilitate changing project requirements.  Many others argue that it leads to many problems, such as:

Over-involvement with the customer in the process leads to the expression of customer wishes rather than needs

Many products have multiple customers which lead to conflicting needs
and opinions, creating unnecessary blockades

Many products don’t have any external customers, where the product
is made for internal use or to be sold in the future. In these cases,
the team itself is playing the user as well as the developer, hence
killing the effectiveness of the process.

Not many things exist in formal documentation, this informality
leads to vague vision and can create problems where the customer
might say that this is not what we asked etc. etc.

The questions is why such conflicting opinions exist regarding XP.  Is it a matter of different scenarios? Is there something else? To what extent is the claim (as written in the title) true?

I would like people who are working or have worked with XP here to contribute their learning and real world experiences.  It would be ideal if you have any facts or references to support you answer.

答:
Over-involvement with the customer in the process leads to the expression of customer wishes rather than needs.

This assumes that the customer is some sort of perfect oracle for the requirements of the system. One of the fundamental principles of XP is that the customer is not a perfect oracle and that constant feedback based on real shipping software is needed to determine the true needs of the market, the customers, and ultimately the stakeholders.

Many products have multiple customers which lead to conflicting needs and opinions, creating unnecessary blockades.

Yes, and regular involvement from those customers will help to make these conflicts explicit and help to resolve them over time. Hiding the problem won't make it go away.

Many products don’t have any external customers, where the product is made for internal use or to be sold in the future. In these cases, the team itself is playing the user as well as the developer, hence killing the effectiveness of the process.

Internal stakeholders are not fundamentally different from external stakeholders. You haven't explained how non-XP methodologies deal with this issue.

Not many things exist in formal documentation, this informality leads to vague vision and can create problems where the customer might say that this is not what we asked etc. etc.

XP involves frequent, incremental feedback between the stakeholders and the developers. If these failures of communication do exist then they can be discovered during early iterations and can be fixed before they significantly affect later iterations. The alternative is that these communication failures are not discovered until right before the product ships.

I think the fundamental misconception is that XP isn't creating these issues. It's just exposing them. Processes that expose and correct issues early and often are generally less error prone, not more.


问:
Storing a re-orderable list in a database
I'm working on a wishlist system, where users can add items to their various wishlists, and I plan to allow users to re-order the items later on. I am not really sure about the best way to go about storing this in a database while remaining fast and not turning in to a mess (this app will be used by a fairly large user base, so I don't want it to go down to clean up stuff).

I initially tried a position column, but it seems like that would be quite inefficient having to change every other item's position value when you move them around.

I have seen people using a self-reference to refer to the previous (or next) value, but again, it seems like you would have to update a whole lot of other items in the list.

Another solution I've seen is using decimal numbers and just sticking items in the gaps between them, which seems like the best solution so far, but I'm sure there has to be a better way.

I would say a typical list would contain up to about 20 or so items, and I will probably limit it to 50. The re-ordering would be using drag and drop and will probably be done in batches to prevent race conditions and such from the ajax requests. I'm using postgres (on heroku) if it matters.

Does anyone have any ideas?

Cheers for any help!

答:
This is really a question of scale, and use case..

How many items do you expect in a list?
If millions, i think gong the decimal route is the obvious one.

If 6 then integers renumbering is the obvious choice.
s
Also the questions is how the lists or rearranged. If you are using a up and down arrows (moving up or down one slot at a time), the i would use integers then swap with the prev (or next) on move.

Also how often do you commit, if the user can make 250 changes then commit at once, than i say integers with renumbering again...

tl;dr: Need more info.

Edit: "Wish lists" sounds like a lot of small lists (assumption, this may be false).. So I say Integer with renumbering.
(Each list contains its own Postion)


答:
First, understand that code that merely works is bad code. Good code also needs to accurately report any errors encountered.

For example, if you're writing a function to transfer cash from one user's account to another user's account; you wouldn't just return a "worked or failed" boolean because that doesn't give the caller any idea of what went wrong and doesn't allow the caller to inform the user properly. Instead, you might have a set of error codes (or a set of exceptions): couldn't find destination account, insufficient funds in source account, permission denied, can't connect to database, too much load (retry later), etc.

Now think about your "parse a string of numbers in format 1:2:3.4" example. All the regex does is report a "pass/fail" that doesn't allow adequate feedback to be presented to the user (whether this feedback is an error message in a log, or an interactive GUI where the errors are shown in red as the user types, or whatever else). What types of errors does it fail to describe properly? Bad character in first number, first number too large, missing colon after first number, etc.

To convert "bad code that merely works" into "good code that provides adequately descriptive errors" you have to break the regex up into many smaller regexes (typically, regexes that are so small that it's easier to do it without regexes in the first place).

Making the code readable/maintainable is just an accidental consequence of making the code good.

Title: Readable regular expressions without losing their power?

Body:
Many programmers know the joy of whipping up a quick regular expression, these days often with help of some web service, or more traditionally at interactive prompt, or perhaps writing a small script which has the regular expression under development, and a collection of test cases. In either case the process is iterative and fairly quick: keep hacking at the cryptic-looking string until it matches and captures what you want and will reject what you don't want.

For a simple case result might be something like this, as a Java regexp:

```<code>Pattern re = Pattern.compile(
  "^\\s*(?:(?:([\\d]+)\\s*:\\s*)?(?:([\\d]+)\\s*:\\s*))?([\\d]+)(?:\\s*[.,]\\s*([0-9]+))?\\s*$"
);
</code>```

Many programmers also know the pain of needing to edit a regular expression, or just code around a regular expression in a legacy code base. With a bit editing to split it up, above regexp is still very easy to comprehend for anyone reasonably familiar with regexps, and a regexp veteran should see right away what it does (answer at the end of the post, in case someone wants the exercise of figuring it out themselves).

However, things don't need to get much more complex for a regexp to become truly write-only thing, and even with diligent documentation (which everybody of course does for all complex regexps they write...), modifying the regexps becomes a daunting task. It can be a very dangerous task too, if regexp is not carefully unit tested (but everybody of course has comprehensive unit tests for all their complex regexps, both positive and negative...).

So, long story short, is there a write-read solution/alternative for regular expressions without losing their power? How would the above regexp look like with an alternative approach? Any language is fine, though a multi-language solution would be best, to the degree regexps are multi-language.

And then, what the earlier regexp does is this: parse a string of numbers in format 1:2:3.4, capturing each number, where spaces are allowed and only 3 is required.


问:
R vs Python for data analysis
I have been programming for about a year and I am really interested in data analysis and machine learning. I am taking part in a couple of online courses and am reading a couple of books.

Everything I am doing uses either R or Python and I am looking for suggestions on whether or not I should concentrate on one language (and if so which) or carry on with both; do they complement each other?

-- I should mention that I use C# in school but am familiar with Python through self-study.

答:
A key feature of R is that it is a library of packages, as much as it is a programming language.  Every package writer has access, in principle, to what is in every other package.  This dramatically reduces the need, to re-invent, to re-document, to re-learn. This applies both to package authors and to users.  Of course, this infrastructure comes at a cost.  Package authors must accommodate standards that become increasingly finicky with the passage of time.  Some of this may spill over into what users encounter.

Python does not, as I understand, have a package management system.  There is no equivalent of R's Comprehensive R Archive Network (http://cran.r-project.org), and no direct equivalent of the R task views (http://cran.csiro.au/web/views/).  Thus it is, to an extent that is not the case for R, a tool for programmers working pretty much on their own rather than as part of a communitarian effort to build on what is already available.

For data analysis and machine learning, the demand is surely, to a very large extent, to build on and take advantage of abilities that are already in place.  For more generic programming tasks, Python may well have advantages.  Will you do this type of work enough to justify the effort involved in learning Python?

Title: R vs Python for data analysis


问:
Moving past the ignoring or considering whitespace binary: how should I compare files for e.g. commit review?
I am dissatisfied with the file comparison tools I have worked with so far. While no tool would be able to always predict the line matchings that make best sense, at least current tools should be able to do a better job when changes mostly consist of added and removed indentation. But the tools have I used end up matching braces in isolation and separating actually related code, and do other seemingly obvious mistakes.

An example will speak volumes, let us take this:

```<code>// We also have to add any specified prefix and (pre-period) suffix.

if (prefix) [spriteName insertString:prefix atIndex:0];

if (suffix)
{
   NSRange pos = [spriteName rangeOfString:@"."];
   if (pos.location == NSNotFound)
   {
      // No point, it's a base sprite, so just append.
      [spriteName appendString:suffix];
   }
   else
   {
      // Append where the period was found, just before it.
      [spriteName insertString:suffix atIndex:pos.location];
   }
}
</code>```

and assume it gets changed to this:

```<code>// We also have to add any specified prefix and (pre-period) suffix.

if (prefix) [spriteName insertString:prefix atIndex:0];

while (we_need_to_do_stuff)
{
   if (suffix)
   {
      NSRange pos = [spriteName rangeOfString:@"."];
      if (pos.location == NSNotFound)
      {
         // No point, it's a base sprite, so just append.
         [spriteName appendString:suffix];
      }
      else
      {
         // Append where the period was found, just before it.
         [spriteName insertString:suffix atIndex:pos.location];
      }
   }
}
</code>```

I don't want to namedrop too much, but what does FileMerge (the graphical diff/merge utility that ships with Xcode) do? This:

…how thoughtful, FileMerge, you made sure to match the braces because they were at the same indentation level, and separated the related code. Couldn't have asked for more.

The usual solution in that case is to find the option to consider changes in the amount of whitespace as being not significant, and try again. But then I want to make sure I have not fumbled the indentation either, because it is something I am going to commit, so I go back to the options, disable the option, try again. Repeat for all the changes I want to review.

There has got to be a better way. Is it just me using my tools badly? Is it theoretically possible to improve this workflow? And this is a simple case, have trickier ones been solved in the abstract? How should I look for better tooling in this domain, given that this is hard to express as a search engine query?

答:
Here are some options you might want to consider.

Some diff tools have an option to input regular expressions as part of the comparison process and some, I believe, have active people in the forums tweaking the expressions for a given language.

Write your own diff tool that compares the syntax and tweak the code. I started this but you spend more time writing a tool than the time it saves.

Since you are committing the code, generate an abstract syntax tree and compare the abstract syntax tree. I don't know of any diff tools that can do this, are free, and open source, but it has been years since I last did a good search for one.

My suggestion would be to take option one as number two takes more time than it saves and number three if you really want to start a new company and make some money. Also if you do write one, realize the GUI takes more time than the diff part, unless you are willing to settle for a text only output.


答:
If we stick to the original question of

I am conducting academic research on the topic of Extreme Programming
  and whether its practices lead to creating space for more errors and
  bugs in applications.

I am not sure the concerns expressed are relevant to the question.

If there is a fear of customer over involvement leading to wishes rather than needs, I would look to the team to be sure they are properly breaking items down into small releases with simple designs.  After that prioritizing those items in such a way that the team can work at a sustainable pace.

If the effort has multiple customers that can not agree needs and opinions, what hope is there of ever being able to test that the software meets customer needs.  It is better to get those things cleared up early in the SDLC rather than later.

If the team has to be the user for XP, this does not kill the XP process.  In fact it is specifically stated that the customer is a member of the team.  At times this team member is an internal employee rather than a "true customer" it is important that the individual is empowered to represent the needs of the customer. I don't see how this is concern is any more relevant to XP as compared to any other approach, be it agile or traditional.

Not many things exist in formal documentation?  If done properly XP teams will spend more time planning than a traditional team.  Additionally, because specifications are written jointly between the business and technical minded team members at the beginning of each iteration, the specifications tend to be more accurate when compare to big design up front.

XP focuses on the development (engineering) aspects of a project.  Things that should be discussed when considering XP are:

Does the learning curve for test driven development interfere with the development of a quality product.

How difficult is it to create quality tests that will result in quality code.

How likely are developers to "cheat" the test driven development cycle and write the code first, then the test later.  Does it matter?

How effective are developers who work in pairs when compared to more traditional development (one person writing the code for a function).

Does iterative/emergent design lead to more stable, scalable systems than systems the are designed up front.

How effective is continuous integration at proactively preventing software defects.

To me those are the questions to consider with XP.  The concerns raised above seem to be more suitable for a discussion of Scrum (Which is very commonly paired with XP).

For references I would see:

http://xprogramming.com/index.php

or

http://www.objectmentor.com/resources/omi_reports_index.html

Cheers and Best of luck with your research.

Title: Extreme Programming practices make an application more error prone?

Body:
I am conducting academic research on the topic of Extreme Programming and whether its practices lead to creating space for more errors and bugs in applications.

From the experiences I gathered from many, I have comments that fall on both sides.  Many support it and consider it a daily necessity, with dynamics that can facilitate changing project requirements.  Many others argue that it leads to many problems, such as:

Over-involvement with the customer in the process leads to the expression of customer wishes rather than needs

Many products have multiple customers which lead to conflicting needs
and opinions, creating unnecessary blockades

Many products don’t have any external customers, where the product
is made for internal use or to be sold in the future. In these cases,
the team itself is playing the user as well as the developer, hence
killing the effectiveness of the process.

Not many things exist in formal documentation, this informality
leads to vague vision and can create problems where the customer
might say that this is not what we asked etc. etc.

The questions is why such conflicting opinions exist regarding XP.  Is it a matter of different scenarios? Is there something else? To what extent is the claim (as written in the title) true?

I would like people who are working or have worked with XP here to contribute their learning and real world experiences.  It would be ideal if you have any facts or references to support you answer.


答:
Use a floating point number for the position column.

You can then reorder the list changing only the position column in the "moved" row.

Basically if your user wants to position "red" after "blue" but before "yellow"

Then you just need to calculate

```<code>red.position = ((yellow.position - blue.position) / 2) + blue.position
</code>```

After a few million re-positions you may get floating point numbers so small that there is no "between" -- but this is about as likely as sighting a unicorn.

You could implement this using an integer field with an initial gap of say 1000. So your intial oredring would be 1000->blue,2000->Yellow,3000->Red.
After "moving" Red after blue you would have 1000->blue,1500->Red,2000->Yellow.

The problem is that with a seemingly large initial gap of 1000 as few as 10 moves will get you into a situation like 1000->blue,1001-puce,1004->biege ...... where you will no longer be able to insert anything after "blue" without re-number the whole list. Using floating point numbers there will always be a "halfway" point between the two positions.

Title: Storing a re-orderable list in a database

Body:
I'm working on a wishlist system, where users can add items to their various wishlists, and I plan to allow users to re-order the items later on. I am not really sure about the best way to go about storing this in a database while remaining fast and not turning in to a mess (this app will be used by a fairly large user base, so I don't want it to go down to clean up stuff).

I initially tried a position column, but it seems like that would be quite inefficient having to change every other item's position value when you move them around.

I have seen people using a self-reference to refer to the previous (or next) value, but again, it seems like you would have to update a whole lot of other items in the list.

Another solution I've seen is using decimal numbers and just sticking items in the gaps between them, which seems like the best solution so far, but I'm sure there has to be a better way.

I would say a typical list would contain up to about 20 or so items, and I will probably limit it to 50. The re-ordering would be using drag and drop and will probably be done in batches to prevent race conditions and such from the ajax requests. I'm using postgres (on heroku) if it matters.

Does anyone have any ideas?

Cheers for any help!

Body:
Use a floating point number for the position column.

You can then reorder the list changing only the position column in the "moved" row.

Basically if your user wants to position "red" after "blue" but before "yellow"

Then you just need to calculate

red.position = ((yellow.position - blue.position) / 2) + blue.position

After a few million re-positions you may get floating point numbers so small that there is no "between" -- but this is about as likely as sighting a unicorn.

You could implement this using an integer field with an initial gap of say 1000. So your intial oredring would be 1000->blue,2000->Yellow,3000->Red.
After "moving" Red after blue you would have 1000->blue,1500->Red,2000->Yellow.

The problem is that with a seemingly large initial gap of 1000 as few as 10 moves will get you into a situation like 1000->blue,1001-puce,1004->biege ...... where you will no longer be able to insert anything after "blue" without re-number the whole list. Using floating point numbers there will always be a "halfway" point between the two positions.


问:
How to read large XML files efficiently
I have a large XML file (about 75,000 lines) where I have to build a catalogue (houses) from. Building the lists works fine, but now I have a problem.

The catalogue should have a detailed presentation page of one house. One house (<item id="123">) has about 800-1200 lines of data, based on the house type.

Which is the best way, as referring to making the script faster and saving lines of code, to read these data and present them?

Some houses, for example, have a sauna, and when these data are in the XML file, the presentation page should contain a section sauna.

I tried before to read the whole XML content with a recursive function into arrays and with a lot of foreaches (maximum depth of children is three) with SimpleXML, but it was really ugly slow, and the recursion did not work at all, because my computer could not handle so much input.

Is there any other way to build this data except to query every variable with if?

答:
Maybe you're running into the limitation that SimpleXML tries to read the entire document in one step, and your document is large or complex. An alternative is to use a stream- or event-based parser which reads bits at a time, sets the state of the parser based on what was read, and lets you register handlers that will react to specific events. Here is a explanation of the idea with a simple example: http://sax.sourceforge.net/event.html

I'm not very familiar with PHP, but it looks like there is something like SAX for you to try: http://php.net/manual/en/book.xml.php. From the introduction:

This extension lets you create XML parsers and then define handlers
  for different XML events.

Searching for sax in php on Google also shows some promising leads.

Title: How to read large XML files efficiently


问:
Trying to code the points on a circle
I am trying to understand this:

I wrote a code for points on a circle of radius 1. Note that the first and last point intentionally coincide.

```<code>do i=1,imax
X(i,1) = COS(-2*4.0*ATAN(1.0)*(i-1)/(imax-1))
Y(i,1) = SIN(-2*4.0*ATAN(1.0)*(i-1)/(imax-1))
print *, X(i,1)**2 + Y(i,1)**2
end do
</code>```

The code is supposed to be a circle, but the following figure demonstrates the plot in Mathematica. It looks to me like an ellipse. Am I doing something wrong? Or is this just the way Mathematica plots it?

The command for the plot is

```<code>ListPlot[a, PlotLabel -> "MeshPoints", AxesLabel -> {"x", "y"}, PlotRange -> {{-2, 2}, {-2, 2}}]
</code>```

答: Without seeing your plot (see my comment on your question), I would assume that mathematica hasn't given you square axes, so it is distorting the circle.  Your parameters do describe a circle.

Title: Trying to code the points on a circle


答: It's simply a matter of your two axes not visually being the same size.  You can see that they go out to a radius of 1 in all 4 directions, which is 5 marks, but the distance between marks is different between the x axis and y axis.  Mathematically, your result is in fact a circle, it's how you're rendering it that is the problem.

Title: Trying to code the points on a circle

Body:
I am trying to understand this:

I wrote a code for points on a circle of radius 1. Note that the first and last point intentionally coincide.

```<code>do i=1,imax
X(i,1) = COS(-2*4.0*ATAN(1.0)*(i-1)/(imax-1))
Y(i,1) = SIN(-2*4.0*ATAN(1.0)*(i-1)/(imax-1))
print *, X(i,1)**2 + Y(i,1)**2
end do
</code>```

The code is supposed to be a circle, but the following figure demonstrates the plot in Mathematica. It looks to me like an ellipse. Am I doing something wrong? Or is this just the way Mathematica plots it?

The command for the plot is

```<code>ListPlot[a, PlotLabel -> "MeshPoints", AxesLabel -> {"x", "y"}, PlotRange -> {{-2, 2}, {-2, 2}}]
</code>```


问:
Is there an idiot's guide to software licensing somewhere?
Basically, my knowledge on the issue is zilch other than the fact that open-source and closed-source exists.

I'm a web developer (not a designer in the slightest), so I look online for things like icons. I've always been a big fan of these icons, which have a Creative Commons Attribution 2.5 License. As far as I can see, this license says 'do whatever you want with them as long as you have a link back to me somewhere'. Is that assumption correct?

Just today I found a new icon set, with a much more confusing license (found here), and to be quite honest I have no idea if I'm allowed to use them or not.

At the moment I want to just use them for toy stuff that might never see the light of day, but then my source code is stored on Github, is it legal to store the icons there where they're publicly accessible?

If I put them on my personal website that might have ads on it to make me five cents every now and then, is that legal?

If I use them on a site that offers a free service to users, is that legal?

If that site then starts making money (via things like paid subscriptions) or gets bought out by someone (highly unlikely but one day possible) is that legal?

Is there some noob guide out there that explains all this stuff, because I would hate to start using this sort of stuff now only to have to change it all later. Even if I buy the icons, there's still licensing issues that I don't understand! :(

And this sort of stuff keeps popping up more and more often...

答:
http://www.tldrlegal.com/ <== Summarizes licenses rather nicely.

update (fair comment about just dropping a link and calling it an answer): The site I linked explains different open-source licenses in concise layman's terms, pointing out what exactly you can, cannot and must do with software bound by a specific license - eg, use it in a commercial apps, not have to distribute your source code if you use their library etc.


问:
Converting Java applet to web application
I would like to convert this Java applet into an equivalent web app. This is my first time creating a web app, but I have some programming experience and time, and am willing to teach myself all of the necessary tools.

By "web app", I mean an application which would work in browsers without requiring Java or Flash, for example. Therefore, it could work on compatible mobile devices.

What tools should I look into for this development project?

答:
The critical part seems to be the drawing. This might be a use case for HTML5 Canvas, at least what I can tell from the screenshot (I cannot run Applet). WebGL might also be an option if 3D Graphics is of interest.

As with everything javascript related there are plenty frameworks available or you can follow HTML5 tutorials.

https://developer.mozilla.org/en-US/docs/HTML/Canvas

or you can resort to frameworks like http://kineticjs.com/

If you want to check out possibilities with HTML5 you can look at Mozilla's HTML5 demos:
https://developer.mozilla.org/de/demos/tag/tech:html5

For the User interface I would suggest using a UI Toolkit like Google Closure since you really don't want to start your own interface toolkit.


答:
"but it seems like that would be quite inefficient"

Did you measure that? Or is that just a guess? Don't make such assumptions without any proof.

"20 to 50 items per list"

Honestly, that is not "a whole lot of items", to me that sounds just very few.

I suggest you stick to the "position column" approach (if that's the most simple implementation for you). For such small list sizes, don't start unnecessary optimizing before you experience real performance problems


答:
When you do ListPlot[] in Mathematica, it uses an "Auto" aspect ratio, which is something like the Golden Mean. You can see that in your plot (the ticks are closer together on the Y axis than on the X axis).

To get what you are looking for, use the option AspectRatio->1, e.g.:

ListPlot[Points, AspectRatio -> 1]

I'd post a picture for you, but stack exchange won't let me.

In any case, if you use AspectRatio in your plot, you'll see that you have a circle.

As far as the expressions you list go, why are you using -2*4.0*ATAN(1.0) rather than 2 * Pi ?

-2*4.0*ATAN(1.0) = - 2 Pi

Title: Trying to code the points on a circle


答:
I can only speak to Cake, and I have nothing good to say about it in terms of MVC. They do not do MVC right. Codeigniter is very much in the same vein. It is not at all weird that you didn't "get" MVC even after having used it for a while.

MVC is simply about properly separating three distinct components of your application's logic: the core of the app, the presentation and the glue necessary to make both work in a real world context.

The core of your app, which contains all the business logic, database interaction, services, beeps and boops that make your app "your app" are the model. The model is not one specific thing in one specific shape, it is whatever is necessary to make your app work the way it does. You only have one "model", which is your app.

The View is used to output in some way what your model does. It's the user interface. It is whatever is necessary to show useful information to the user. This may be a website, it may be a command line interface, it may be a native desktop GUI. You may use all three in your app.

The Controller is simply whatever is left to make that work, mostly the thing that takes user input and directs it to the appropriate place. You may have several different kinds of controllers for different kinds of context, e.g. one that can handle incoming HTTP requests, one that handles command line input and one that is hooked up to GUI events.

What particular shape these individual parts take depends on your app entirely. All three can be sort of their own mini-applications. Any template-prefab framework "model" is made for one generalized case to help you get something up and running quickly; it often is not the optimal form your model should take. You'll have to come up with your own structure for your app, whatever is best suited to build it. Look into OOP principles, SOLID, dependency injection etc. and build your core model according to these guidelines. Then wrap views and controllers around it as necessary.

The point of this separation is simply to make the app maintainable and extendable. The model does not contain anything that is specific to any specific form of input or output. For example, it does not contain any format-specific text (like error messages in HTML format). It does not assume any particular form of input (like HTTP requests). The View conversely does not contain any business logic, its job is just to output. And the controller does not contain any business logic either, its job is only to "input". The reason is simply that both the controller and view are interchangeable, but your app is not.

If you want to use a framework for this, use one that is modular and lets you do whatever you need to do. Zend, Symfony, Laravel and similar component based pick-and-choose frameworks are best suited for this.

Title: Most MVC-strict php framework

Body:
I have been trying to wrap my head around MVC pattern for about 6 months.I've read tons of articles, Q&A, and blog posts about MVC and HMVC patterns, but I just simply don't get it 100%.

I tried learning MVC by exercising one of widely used PHP MVC framework, CodeIgniter. I've implemented few internal websites for my company with it. And STILL, I don't 100% get it. I believe one of the best ways to learn something is to follow strictly defined rules.

So my question is: What is the most strict PHP framework in terms of how MVC pattern is implemented? One that defines how I use models, controllers, and views so that I can completely get what MVC is?


答:
If the objective is to minimize number of database operations per reordering operation:

Assuming that

All shopping items can be enumerated with 32-bit integers.

There is a maximum size limit for a user's wish list. (I saw some popular website use 20 - 40 items as limit)

Store the user's sorted wish list as a packed sequence of integers (integer arrays) in one column. Every time the wish list is reordered, the entire array (single row; single column) is updated - which is to be performed with a single SQL update.

https://www.postgresql.org/docs/current/static/arrays.html

If the objective is different, stick with the "position column" approach.

Regarding the "speed", make sure to benchmark the stored procedure approach. While issuing 20+ separate updates for one wish list shuffle may be slow, there might be a fast way using stored procedure.


问:
Is there any difference between pointers and references?
References and pointers do the same thing as I know. Is there any difference between them?

If there is no difference, why we call them reference not pointer?

答:
Pointers and references look different enough (pointers use the * and -> operators, references use .), but they seem to do similar things. Both pointers and references let you refer to other objects indirectly. How, then, do you decide when to use one and not the other?
First, recognize that there is no such thing as a null reference. A reference must always refer to some object. As a result, if you have a variable whose purpose is to refer to another object, but it is possible that there might not be an object to refer to, you should make the variable a pointer, because then you can set it to null. On the other hand, if the variable must always refer to an object, i.e., if your design does not allow for the possibility that the variable is null, you should probably make the variable a reference.

for more refer
http://www.cplusplus.com/articles/ENywvCM9/


答:
You are juxtaposing the wrong things.  In C++, pointers and references have different meanings, but because you aren't asking about C++, I suspect that isn't what you are after.  If you are, check out Harssh's answer.

What you probably want to know is the difference between a reference to an object and the object itself.  In most newer languages you can pass an object around by value or by reference.

Passing an object by value means making a copy of it.  You can modify that copy without affecting the original.  Making that copy can cost a lot of memory access though.

Passing an object by reference means passing a handle to that object.  This is cheaper because you don't need to make a copy.  It also means that any changes you make will affect the original.

Functional programming languages will tend to pass everything by value because that avoids side effects.

Title: Is there any difference between pointers and references?

Body:
References and pointers do the same thing as I know. Is there any difference between them?

If there is no difference, why we call them reference not pointer?


答:
Pointers and references are placeholder to use objects.

Instead of using the object itself you can use a pointer or reference to access and/or manipulate the object.

```<code>Car myCar = new Car();
Car& myCarReference = myCar;
</code>```

Changing the content of myCarReference will change the content of myCar.

Pointers add powerful but potentially dangerous address operations to references. For example:

```<code>Car* myCarPointer;

    // 0x12345678=the memory adress where one car
    // object is supposed to be in memory.
myCarPointer = 0x12345678;
myCarPointer->setColor(red);

myCarPointer+=20;  // advance 20 cars in an array
</code>```

Potentially dangerous means "you can assign any address to a pointer. The pointer can point to a location where there is no car object.

Languages like java and c# introduced references to make programms more robust compared to c/c++ which have only pointers

Body:
Pointers and references are placeholder to use objects.

Instead of using the object itself you can use a pointer or reference to access and/or manipulate the object.

Car myCar = new Car();
Car& myCarReference = myCar;

Changing the content of myCarReference will change the content of myCar.

Pointers add powerful but potentially dangerous address operations to references. For example:

Car* myCarPointer;

    // 0x12345678=the memory adress where one car
    // object is supposed to be in memory.
myCarPointer = 0x12345678;
myCarPointer->setColor(red);

myCarPointer+=20;  // advance 20 cars in an array

Potentially dangerous means "you can assign any address to a pointer. The pointer can point to a location where there is no car object.

Languages like java and c# introduced references to make programms more robust compared to c/c++ which have only pointers


答:
There is no generally accepted difference between pointers and references if you look at a wide enough distribution of languages using the terms. Variant of the same concepts use both terms (and some other like access) nearly indifferently, yet some characteristics tend to be closely associated with one of the term:

if arithmetic is available, I've never seen the term reference used.  (But pointer doesn't imply that arithmetic is available)

if the referenced object can't be changed, I've never seen the term pointer used excepted when there is a constant property which can be applied to the pointer as well as to other things.  (But reference doesn't imply non rebindability).


答:
Such a framework can not possibly exist for a number of reasons.

First of all, the Model in the MVC pattern is the part that makes your application your application. If a framework were to define strictly what a model looks like, then that framework would only be usable for one or at most a handful of applications. This effectively stops it from being a framework.

The second problem is that there is no universal consensus on what a proper application of the MVC pattern looks like. For example, some will say that the Controller must provide the View with the data it needs from the Model, while others will say that the View should retrieve the information it needs by itself and the Controller should just make sure that the View knows where to find the Model.

Another example, more specific to web applications, is the amount of processing that the View can do. For some, the View should consist exclusively of HTML files where some place holders get replaces with the actual content (usually retrieved by the Controller from the Model), while others are perfectly comfortable with letting the View do UI-related processing, such as internationalisation of the presented content.

Title: Most MVC-strict php framework


答:
Broadly, you can make the following distinction:

A reference is a variable that refers to something else and can be used as an alias for that something else.

A pointer is a variable that stores a memory address, for the purpose of acting as an alias to what is stored at that address.

So, a pointer is a reference, but a reference is not necessarily a pointer.

Pointers are a particular implementation of the concept of a reference, and the term tends to be used only for languages that give you direct access to the memory address.

References can be implemented internally in a language using pointers, or using some other mechanism. For example, Perl has symbolic references, which refer to the variable by name rather than memory location.  Which is why weird code like this works:

```<code>my $bar = "foo";
$$bar = "Am I foo or bar?"; #This is actually a reference to $foo!
print $foo;
</code>```

This distinction between references and pointers is not a hard and fast rule (C++ being the main exception, because it has both references and pointers, with a distinct meaning for each) but it covers most of the usage.

Body:
Broadly, you can make the following distinction:

A reference is a variable that refers to something else and can be used as an alias for that something else.

A pointer is a variable that stores a memory address, for the purpose of acting as an alias to what is stored at that address.

So, a pointer is a reference, but a reference is not necessarily a pointer.

Pointers are a particular implementation of the concept of a reference, and the term tends to be used only for languages that give you direct access to the memory address.

References can be implemented internally in a language using pointers, or using some other mechanism. For example, Perl has symbolic references, which refer to the variable by name rather than memory location.  Which is why weird code like this works:

my $bar = "foo";
$$bar = "Am I foo or bar?"; #This is actually a reference to $foo!
print $foo;

This distinction between references and pointers is not a hard and fast rule (C++ being the main exception, because it has both references and pointers, with a distinct meaning for each) but it covers most of the usage.


问:
How to implement RGBA in 8-bit microcontroller?
I have successfully connected my microcontroller to my TV via through VGA adapter i made that convert digital to analog signals with the help of resistors.

Currently i am utilizing 8 pins that I am using as 2 Red 2 Green 2 Blue 1 Hsyn and 1 Vsyn. I was thinking if there is a way to add 'A' Alpha in it, it's used for transparency. My another question is that is Alpha software driven or is it in the hardware?

Apparently, i did not find any relevant resources on hardware side of RGBA. I did notice Gameduino has used it in their 16-bit microcontroller. Is it possible to use multiplexing/charlieplexing in this problem?

答:
Yes your going to need to support your Alpha channel in software. If you have 3 bytes for RGB you will need an extra Alpha byte to represent the transparency of the pixel in your source images.

The blending comes in to play when you composite all the layers on top of one another.

To blend you will need a screen size buffer in memory that you copy each object on to.

You didn't mention what language your using but if it is C you can convert your alpha to a percentage that you can use to blend with

```<code>float alpha = pixel.alpha / 255;
buffer[offset_dst].R += pixel[offset_src].R * alpha;
buffer[offset_dst].G += pixel[offset_src].G * alpha;
buffer[offset_dst].B += pixel[offset_src].B * alpha;
</code>```

Obviously that code is for illustration only, you will quickly saturate your buffers pixels with a few layers using this. Note you don't need an Alpha channel in the buffer.

Anyway once you have drawn all your elements to the buffer send the buffer to your TV.

Body:
Yes your going to need to support your Alpha channel in software. If you have 3 bytes for RGB you will need an extra Alpha byte to represent the transparency of the pixel in your source images.

The blending comes in to play when you composite all the layers on top of one another.

To blend you will need a screen size buffer in memory that you copy each object on to.

You didn't mention what language your using but if it is C you can convert your alpha to a percentage that you can use to blend with

float alpha = pixel.alpha / 255;
buffer[offset_dst].R += pixel[offset_src].R * alpha;
buffer[offset_dst].G += pixel[offset_src].G * alpha;
buffer[offset_dst].B += pixel[offset_src].B * alpha;

Obviously that code is for illustration only, you will quickly saturate your buffers pixels with a few layers using this. Note you don't need an Alpha channel in the buffer.

Anyway once you have drawn all your elements to the buffer send the buffer to your TV.


答:
While all of the feedback so far is good it is all recommending methods to change your bosses approach and trust me this is a futile effort that will ultimately result in you getting more and more frustrated.

Your boss, like mine and many others has a broader view of the company than us mere developers. They are concerned with customer satisfaction, repeat business and the word of mouth and reputation that comes from delivering what the customer wants even if it is out of scope.

Now I understand that for large development houses that take on government projects worth millions of dollars it is really important to get all the scope and details nailed down from the outset to ensure the overall success of the project. I do not think you work for such a company.

You mentioned that you recently lost your production manager, buddy... it's time for you to adapt and step up to the plate here. Your company is under some financial strain obviously and at least you still have a job here. I'm sure your boss is shitting his pants on a daily basis doing everything he can to keep you going ( including taking the last resort of firing people )

So to sum up, I think you should work differently and adapt to the new situation.. adopt a more Agile development style and put the customers needs first.

There is something fun about flying by the seat of your pants. You only need to be direct with your boss and tell him what you said here. Most of all understand he is human so be a little compassionate and explain that with the loss of your PM some of the processes that were once in place have come unstuck.. But at the same time explain you understand the pressures he is under and if he can accept that the developers are going to have to wing it for a while and make mistakes then that's all you need to say - he can never come back and say you didn't warn him at the very least.