答:
I think the reason is that OLAP databases (which are what MDX seems to be intended for use with) are really NOT just relational databases. They are somewhat different (I've no experience with them, so the details escape me at present), and a different mental model is useful for interacting with them (even if it's really a relational DB underneath).

The problem you are running into is that you're seeing the OLAP database as a relational DB, and so you want to use the appropriate language (SQL) to query the relational database. But it's NOT a relational DB, it's something similar, but not quite the same. It's structured for a different mental model, and the MDX query language fits that model better than SQL.

Title: Why creating a new MDX language instead of extending SQL?

Body:
I have a long experience with SQL, but recently began working with datawarehouse and OLAP technologies: building fact and dimension tables, that then are queried using MDX (MultiDimensional eXpressions).

The problem is that MDX works with a completely different logic compared to SQL, and it's a whole new learning curve even for someone with a strong SQL background.

Yes, MDX allows you to do things that would be hard or almost impossible with plain SQL.
But sometimes it's frustrating to be hours around an MDX to do something you know you could achieve in minutes using SQL (ok, you can tell me to RTFM ...).

But why go on to the trouble of creating a new completely different language when you could build on SQL, extend it to add the features needed by OLAP applications?


问:
Data structure for pattern matching
Let's say you have an input file with many entries like these:

```<code>date, ticker, open, high, low, close, <and some other values>
</code>```

And you want to execute a pattern matching routine on the entries(rows) in that file, using a candlestick pattern, for example. (See, Doji) And that pattern can appear on any uniform time interval (let t = 1s, 5s, 10s, 1d, 7d, 2w, 2y, and so on...).

Say a pattern matching routine can take an arbitrary number of rows to perform an analysis and contain an arbitrary number of subpatterns. In other words, some patterns may require 4 entries to operate on others may require more or less.

Say also that the routine (may) later have to find and classify extrema (local and global maxima and minima as well as inflection points) for the ticker over a closed interval, for example, you could say that a cubic function (x^3) has the extrema on the interval [-1, 1]. (See link)

Given that I don't know the size of the input file upon reading? What would be the most natural choice in terms of a data structure?  What about an interface that conforms a Ticker object containing one row of data to a collection of Ticker so that an arbitrary pattern can be applied to the data. For example, let's say I have a pattern that requires n elements to form a match, I need to apply the pattern to those elements and then analyze each one of those chunks.

What's the first thing that comes to mind?

I chose a doubly-linked circular linked list that has the following methods:

```<code>push_front()
push_back()
pop_front()
pop_back()
[] //overloaded, can be used with negative parameters
</code>```

But that data structure seems very clumsy, since so much pushing and popping is going on, I have to make a deep copy of the data structure before running an analysis on it.

So, I don't know if I made my question very clear -- but the main points are:

What kind of data structures should be considered when analyzing sequential data points to conform to a pattern that does NOT require random access?

What kind of data structures should be considered when classifying extrema of a set of data points?

Updated

Here's the main analyzer loop for my program (in some pseudocode that's a polyglot of a few languages)

```<code>data = new circular_linkedList()
// in my case, data is a circular linked list of elements.
foreach(element in dataFeed) {
    data.push_front(element)
}

step_value = Pattern.numberRequiredElementsForMatch()
buffer = new circular_linkedList()
// at this point, you'll have a circular linked list
// where pop_back() will return the oldest entry and
// entry, and pop_front() will return the newest

// initialize the buffer
for(value in range(step_value()) {
    buffer.push_back(data.pop_back())
    // fill a buffer with the number of
    // values required for a match.
    // so now buffer will contain
    // [elementk, ... , elementk+n]
    // where buffer[0] < ... < buffer[n]
}
do {
    last = buffer[len(buffer)]
    ...
    first = buffer[0]

    Pattern.match(first, ... , last)
    buffer.pop_front() // remove the first element
    buffer.push_back(data.pop_back()) //add another element to the back

} while (!data.isEmpty())

...
</code>```

Anyway, that's a basic idea of what I have going on. The problem is that the way I'm doing it now, I have to reiterate through the loop to apply another pattern. (buffer sizes differ) It just seems inefficient to do that. Also, what happens when there's no more data in the buffer and it's not evenly divisible by the number of elements needed by a match?

答:
Since you said you're reading the data from a file, my first choice for the underlying data structure would be an array.  It's the most compact form of storage, which has advantages with cache, and arrays work very well when your data size is fixed and known ahead of time.  Don't get thrown off by not "needing" random access.  Random access data structures can easily be substituted for sequential-only data structures, even though the reverse isn't true.

I would also recommend some sort of View object into the array, which provides an interface that better matches your needs.  It can handle internally the details of the starting point of the pattern, the time interval, etc., so your pattern matching functions can have a very simple interface, something like:

```<code>bool pattern(View &data) {
     return data[1].high > data[0].high;
}
</code>```

Your pattern matching function doesn't care if data[0] and data[1] are one second or one year apart.  It doesn't care if data[0] is the first row in your file or the millionth.  The View object abstracts those details away.  You just instantiate different View objects as needed, but they all share the same underlying array.

If the extrema are used as part of the pattern matching, you can calculate them once and store it in the View object, and use them like this:

```<code>bool pattern(View &data) {
     return (data.max() - data.min()) > 1.0;
}
</code>```

In summary, the idea is to decouple your data structure as much as possible from the matching functions.  You want those functions to read as close as possible to how a domain expert would express them in English.  Note I can easily just change the View object, if I need to match patterns streaming in on a socket instead of from a file.  The "meat" of the pattern matching doesn't need to change.

ContentLicense: CC BY-SA 3.0

Title: Data structure for pattern matching

Body:
Since you said you're reading the data from a file, my first choice for the underlying data structure would be an array.  It's the most compact form of storage, which has advantages with cache, and arrays work very well when your data size is fixed and known ahead of time.  Don't get thrown off by not "needing" random access.  Random access data structures can easily be substituted for sequential-only data structures, even though the reverse isn't true.

I would also recommend some sort of View object into the array, which provides an interface that better matches your needs.  It can handle internally the details of the starting point of the pattern, the time interval, etc., so your pattern matching functions can have a very simple interface, something like:

bool pattern(View &data) {
     return data[1].high > data[0].high;
}

Your pattern matching function doesn't care if data[0] and data[1] are one second or one year apart.  It doesn't care if data[0] is the first row in your file or the millionth.  The View object abstracts those details away.  You just instantiate different View objects as needed, but they all share the same underlying array.

If the extrema are used as part of the pattern matching, you can calculate them once and store it in the View object, and use them like this:

bool pattern(View &data) {
     return (data.max() - data.min()) > 1.0;
}

In summary, the idea is to decouple your data structure as much as possible from the matching functions.  You want those functions to read as close as possible to how a domain expert would express them in English.  Note I can easily just change the View object, if I need to match patterns streaming in on a socket instead of from a file.  The "meat" of the pattern matching doesn't need to change.


问:
Overview of the agile process that I can apply to a startup
I need to provide a quote to an external client for some software. I'm looking to use agile just for initial requirements building (which I'm experienced in from a developer perspective) but I need to do everything this is just a one man job. The client are having a hard time working out what there requirements are and the value I can add will be to sit down with them and work out what they want using user stories etc, I basically need to be a BA for a little bit.

I am looking for good overview of the procedures to go through in the agile process for building requirements, and the continuing process a bit for further down the line. For example the initial inception through to elaboration of epics and building user stories (or not) just need to read a bit about it before the meeting so I know the best way to proceed if I spend a day with them.  Having additional resources to provide to the client so that we are all on the same page would be useful too.

答:
The Lean Startup by Eric Ries would be my top recommendation.

For user stories specifically, I also recommend User Stories Applied by Mike Cohn.


问:
Should I use C style in C++?
As I've been developing my position on how software should be developed at the company I work for, I've come to a certain conclusion that I'm not entirely sure of.

It seems to me that if you are programming in C++, you should not use C style anything if it can be helped and you don't absolutely need the performance improvement. This way people are kept from doing things like pointer arithmetic or creating resources with new without any RAII, etc. If this idea was enforced, seeing a char* would possibly be a thing of the past.

I'm wondering if this is a conclusion others have made? Or am I being too puritanical about this?

答:
The new c++ has some advantages, this is much clearer than two 'c' style loops in i,j:</p>

```<code>int array[5][10]; int i;
for_each(array, array+5,
  for_loop(var(i)=0, var(i)<10, ++var(i),
           _1[var(i)] += 1));
</code>```

Title: Should I use C style in C++?

Body:
The new c++ has some advantages, this is much clearer than two 'c' style loops in i,j:

int array[5][10]; int i;
for_each(array, array+5,
  for_loop(var(i)=0, var(i)<10, ++var(i),
           _1[var(i)] += 1));


问:
How do you track bugs in your personal projects?
I'm trying to decide if I need to reassess my defect-tracking process for my home-grown projects.  For the last several years, I really just track defects using TODO tags in the code, and keeping track of them in a specific view (I use Eclipse, which has a decent tagging system).

Unfortunately, I'm starting to wonder if this system is unsustainable.  The defects I find are typically associated with a snippet of code I'm working on; bugs which are not immediately understood tend to be forgotten, or ignored.  I wrote an application for my wife which has had a severe defect for almost 9 months, and I keep forgetting to fix it.

What mechanism do you use to track defects in your personal projects?  Do you have a specific system, or a process for prioritizing and managing them?

答:
I came looking for an answer for this a while ago and have since worked out a very neat and simple system, which meets these key goals for me:

Goals in order of importance:

Make it possible to enter a new task/bug as effortlessly as possible, so that I can jot it down as soon as I spot it or dream it up, and go back to coding before I lose my place.

Make it easy to see and manage the issues without a lot of searching, clicking, drilling down.

Make it easy to tie in with version control so I can later find out what changes were made to resolve an issue, or what task or bug drove a specific change in the code.

Make it relatively easy to set up: minimal installation and configuration and minimal price.

(3 and 4 are less important, and I would have been okay with a system that didn't provide them, but this one does).

Step 1: Get a project in Bitbucket

I use bitbucket for issue tracking and for git version control (for an iOS project in XCode for example).
I looked at FogBUGz (which I've read about for years on JoelOnSoftware) and GitHub and others, but bitbucket seems to have the best free features set for small teams.

Step 2: Use Bitbucket Issue Tracking in the project

Next I set up issue tracking in the same bitbucket project. So my project now has a git repository and issue tracking.

Step 3: Make issue tracking easy!

For this I'm using Bitbucket Cards which is a nice, simple kanban-like front end to the Bitbucket issues. You just have to log into your Bitbucket account and set up the columns you want.
I have four columns: Backlog, Next, Bugs, and Resolved. (I'm thinking of merging Bugs with Backlog, but never mind that for now)

(This image is from the Bitbucket Cards blog, not from my project, hence the columns are different than the ones I use)

Bitbucket Cards lets you set up a very simple filter for each list where you choose the status(es) and kind(s) of issues that go in a card column. So, open status issues of the kind bug go in the Bug column.

(This one is from my project: that's how I select what goes in the Bug column)

What's really cool is that when you drag and drop a card from one column into another, it will automatically change the status of the issue the card represents to match that in the definition of the destination column.

Another nice thing about Bitbucket Cards is that it doesn't time out easily. This is crucial since the aim of this whole set up is to make it easy - so this system works for me instead of me working for it. I open a bookmark my card page and it stays open on a Chrome tab all day.

This takes care of my 2nd goal.

Step 4: Tie it in with version control.

Bitbucket issues tie in neatly with version control (as to most of the competitors) so when I'm finished working on an issue I commit it git with a message like "Added the thingo to the whatsit. Fixes #245".
If I commit this, then push it, then reload my Bitbucket Cards page, I'll see that the issue has moved to the Resolved column. Cool.

There's my 3rd goal done.

Step 5: Make it easier to CREATE issues.

You probably think that this whole set up is already way to complicated to set up, and why would I want to add another web app to the process. Well, remember my primary goal above: I want to make it so easy to add a task that I don't lose my train of thought before I get to the text area to type it in, nor do I want to lose my place in the code by the time I get done.

Now, Bitbucket Cards does let me create tasks fairly easily, but it's just a bit to clicky/scrolly to fully meet goal #1. You have to click Create an Issue; then a modal editor pops up; after entering your issue title you have to scroll down to specify the kind (bug/task) and the priority; then click create.

Instead I chose to use a second Bitbucket app called taskrd.

You can set up taskrd, by giving it your Bitbucket login, and set it on a bookmark and tab, and keep it open all day, just like Bitbucket cards.
Taskrd has a much simpler workflow for adding a new task, just type it in, optionally set the kind and priority, and hit the Add button.

(this image is from the Taskrd blog)

Now it's arguable that it's not worth the effort of setting up Taskrd over using Bitbucket Cards or even Bitbuckets own issue-entry system. After all, with Taskrd I have to click a tab on my browser, and click Reload on my page with Bitbucket Cards for it to refresh and get the new issue I added in the Taskrd app. But in fact, I find that I'm generally in mode or the other: Either I'm using Bitbucket Cards to organize what I'm doing next, or to look through the bug list, or I'm busy coding and entering tasks/bugs as they occur to me - all in rapid fire mode. For this 2nd mode of work, the Taskrd is great: I just keep it open on a separate monitor, and quickly enter issues as I work.

So that covers goal #1.

My last goal was easy/cheap set up.
Well cheap it is: all of this is free. Bitbucket has free private repositories for up to five users and the other apps were free.
Setup seems non-trivial based on the above, but really the most complicated part was setting up git to push to the bitbucket repository which will be the same anywhere. I didn't have to install anything, and connecting both of the apps to my bitbucket repository was pretty easy.
Setting up the cards columns how I liked them took a bit of playing around but wasn't really hard.

Reading this back, I might come off as a bit of a shill for Bitbucket - but I really don't mean to. It's just that I've been using this process for weeks - after years of trying different configurations to track what I'm doing  - and I'm really digging it, so thought I'd take the time to lay it out for others.

ContentLicense: CC BY-SA 2.5


答:
C++ is a language that provides a lot of features that you may chose to use or not. Your decisions should be based on

a) Frameworks you use

b) The domain of your application

c) Your current code base

Frameworks

Some frameworks lend themselves to specific styles. For example, if you are using Qt/KDE/Wt you will usually use their memory model and will not have your own smart pointers. You're unlikely to use exceptions as much. Qt's MOC also has certain implications for templates that limits how much you can do with them.

At the same time, code that is heavily based on boost tends to be heavy in what others have described as 'Modern C++'.

Then you have Google-stylized C++ which is essentially C with classes. Google C++ Style Guide

Application Domain

If you are coding software where performance is critical (financial, embedded,etc), a lot of the 'niceties' of C++ might go out the window in favour of limiting memory footprints or CPU cycles. There are situations where C is the 'right' language to use for a small part of the program, but not for the whole thing; C++ allows you to do that so that you can have your pointer arithmetic when doing crazy matrix math but have high level abstractions when combining the modules that use it.

Current Code Base

In the real world, if you are in a shop with 10 C coders who don't want or like C++ you will have a much better time sticking to something like the Google style guide than something that is more 'Modern'. If all your libraries are written in C and you are only gluing them together in C++ then char * might make more sense than going to and from std::string all the time.

Conclusion

C++ is not a langauge that is ideal in any academic sense, but it is a pragmatic compromise that worked out very well. So when using it, you should also have a very pragmatic approach to the problem and not get too bogged down on 'The Right Way Of Doing Things'.

To answer your question: you may or may not be too puritanical, but that depends on the specifics.

Title: Should I use C style in C++?

Body:
As I've been developing my position on how software should be developed at the company I work for, I've come to a certain conclusion that I'm not entirely sure of.

It seems to me that if you are programming in C++, you should not use C style anything if it can be helped and you don't absolutely need the performance improvement. This way people are kept from doing things like pointer arithmetic or creating resources with new without any RAII, etc. If this idea was enforced, seeing a char* would possibly be a thing of the past.

I'm wondering if this is a conclusion others have made? Or am I being too puritanical about this?


问:
What does it mean to write "good code"?
In this question I asked whether being a bad writer hinders you from writing good code. Many of the answers started of with "it depends on what you mean by good code".

It appears that the term "good code" and "bad code" are very subjective. Since I have one view, it may be very different from others' view of them.

So what does it mean to write "good code"? What is "good code"?

答:
Good code is going to be different for each person and the language that they are working with also has an impact upon what might considered to be good code. Generally when I approach a project I look for the following things:

How is the project organized? Are source files organized in a clean manner and can I find code with out too much effort?

How is the code organized? Is is clearly documented what the code in the file does, such as through the use of a file header, or through the use of each class residing in its own file? Are there function in the file that are no longer being used in the application?

How are the functions organized? Is there a clear pattern to where variables are declared, or is it a fairly random pattern? Does the code have a logical flow to it and avoid unnecessary control structures? Is everything clearly documented with code being self documenting where need be and comments clearly expression the why and/or how of what the code is doing?

Beyond all of this, does the design of the application make sense as a whole? The code residing in the application can be the best in the world, but it might still be a pain to work with if the overall design of the application makes no sense.

Title: What does it mean to write "good code"?


问:
Dealing with curly brace soup
I've programmed in both C# and VB.NET for years, but primarily in VB. I'm making a career shift toward C# and, overall, I like C# better.

One issue I'm having, though, is curly brace soup. In VB, each structure keyword has a matching close keyword, for example:

Namespace ...
    Class ...
        Function ...
            For ...
                Using ...
                    If ...
                        ...
                    End If
                    If ...
                        ...
                    End If
                End Using
            Next
        End Function
    End Class
End Namespace
```

<p>The same code written in C# ends up very hard to read:</p>

<pre class="lang-csharp prettyprint-override"><code>namespace ... {
    class ... {
        function ... {
            for ... {
                using ... {
                    if ... {
                        ...
                    }
                    if ... {
                        ...
                    }
                }
            }
            // wait... what level is this?
        }
    }
}
</code>```

Being so used to VB, I'm wondering if there's a technique employed by c-style programmers to improve readability and to ensure that your code ends up in the correct "block". The above example is relatively easy to read, but sometimes at the end of a piece of code I'll have 8 or more levels of curly braces, requiring me to scroll up several pages to figure out which brace ends the block I'm interested in.

答:
If you write your Code in Visual Studio, there's also a Plugin that shows you vertical dots between the beginning and the end of every structure that you construct.

But overall I think it'll just take some time until you're used to the "Curly-Braces-Soup". (Btw, I really like that expression. Sounds a bit like a Episode-Name for The Big Bang Theory)

Title: Dealing with curly brace soup


问:
Are closures with side-effects considered "functional style"?
Many modern programming languages support some concept of closure, i.e. of a piece of code (a block or a function) that

Can be treated as a value, and therefore stored in a variable, passed around to different parts of the code, be defined in one part of a program and invoked in a totally different part of the same program.

Can capture variables from the context in which it is  defined, and access them when it is later invoked (possibly in a totally different context).

Here is an example of a closure written in Scala:

```<code>def filterList(xs: List[Int], lowerBound: Int): List[Int] =
  xs.filter(x => x >= lowerBound)
</code>```

The function literal x => x >= lowerBound contains the free variable lowerBound, which is closed (bound) by the argument of the function filterList that has the same name. The closure is passed to the library method filter, which can invoke it repeatedly as a normal function.

I have been reading a lot of questions and answers on this site and, as far as I understand, the term closure is often automatically associated with functional programming and functional programming style.

The definition of function programming on wikipedia reads:

In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state.

and further on

[...] in functional code, the output value of a function depends only on the arguments that are input to the function [...]. Eliminating side effects can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming.

On the other hand, many closure constructs provided by programming languages allow a closure to capture non-local variables and change them when the closure is invoked, thus producing a side effect on the environment in which they were defined.

In this case, closures implement the first idea of functional programming (functions are first-class entities that can be moved around like other values) but neglect the second idea (avoiding side-effects).

Is this use of closures with side effects considered functional style or are closures considered a more general construct that can be used both for a functional and a non-functional programming style? Is there any literature on this topic?

IMPORTANT NOTE

I am not questioning the usefulness of side-effects or of having closures with side effects. Also, I am not interested in a discussion about the advantages / disadvantages of closures with or without side effects.

I am only interested to know if using such closures is still considered functional style by the proponent of functional programming or if, on the contrary, their use is discouraged when using a functional style.

答:
No.  "Functional-style" implies side-effect-free programming.

To see why, have a look at Eric Lippert's blog entry about the ForEach<T> extension method, and why Microsoft didn't include a sequence method like it in Linq:

I am philosophically opposed to providing such a method, for two
reasons.

The first reason is that doing so violates the functional programming
principles that all the other sequence operators are based upon.
Clearly the sole purpose of a call to this method is to cause side
effects. The purpose of an expression is to compute a value, not to
cause a side effect. The purpose of a statement is to cause a side
effect. The call site of this thing would look an awful lot like an
expression (though, admittedly, since the method is void-returning,
the expression could only be used in a “statement expression”
context.) It does not sit well with me to make the one and only
sequence operator that is only useful for its side effects.

The second reason is that doing so adds zero new representational
power to the language.  Doing this lets you rewrite this perfectly clear code:

```<code>foreach(Foo foo in foos){ statement involving foo; }
</code>```

into this code:

```<code>foos.ForEach((Foo foo)=>{ statement involving foo; });
</code>```

which uses almost exactly the same characters in slightly different
order. And yet the second version is harder to understand, harder to
debug, and introduces closure semantics, thereby potentially changing
object lifetimes in subtle ways.

Body:
No.  "Functional-style" implies side-effect-free programming.

To see why, have a look at Eric Lippert's blog entry about the ForEach<T> extension method, and why Microsoft didn't include a sequence method like it in Linq:

I am philosophically opposed to providing such a method, for two
reasons.

The first reason is that doing so violates the functional programming
principles that all the other sequence operators are based upon.
Clearly the sole purpose of a call to this method is to cause side
effects. The purpose of an expression is to compute a value, not to
cause a side effect. The purpose of a statement is to cause a side
effect. The call site of this thing would look an awful lot like an
expression (though, admittedly, since the method is void-returning,
the expression could only be used in a “statement expression”
context.) It does not sit well with me to make the one and only
sequence operator that is only useful for its side effects.

The second reason is that doing so adds zero new representational
power to the language.  Doing this lets you rewrite this perfectly clear code:

foreach(Foo foo in foos){ statement involving foo; }

into this code:

foos.ForEach((Foo foo)=>{ statement involving foo; });

which uses almost exactly the same characters in slightly different
order. And yet the second version is harder to understand, harder to
debug, and introduces closure semantics, thereby potentially changing
object lifetimes in subtle ways.

ContentLicense: CC BY-SA 4.0


问:
Will SRS be sufficient enough for the programmers to do their work, without the additional overhead of FS?
We always make 2 documents the SRS (Software Requirement Specification) and the FS (Functional Specifications) documents for the coders aka programmers.

As I have examined the SRS is more like containing both functional and non-functional requirements as compared to the FS that deals only with the functional requirements.

To cut it short will the SRS be sufficient enough for the programmers to do their work? and not make any FS anymore?

答:
The duplication in your docs is a data problem. Data views are being treated as data sources. Relational DBs, normalization, and queries were designed to handle this. It may be over-kill, but you could make a requirements database. A filtered query would produce the "functional" requirements.

Maybe an excel sheet with a functional/non-functional flag column would suffice.


问:
Forbidding or controlling "Hidden IT..." Who should write and maintain ad-hoc software applications?
Bigger companies usually have the problem, that it is not possible to write all programs employees want (to save time and to optimize processes) due to a lack of staff and money.

Then hidden programs will be created by some people having (at least some) coding experience (or by cheap students/interns...). Under some circumstances these applications will raise in importance and spread from one user to a whole department.

Then there is the critical point: Who will maintain the application, add new features, ...? And this app is critical. It IS needed. But the intern has left the company. No one knows how it works. You only have a bunch of sources and some sort of documentation.

Does it make sense to try and control or forbid application development done ad-hoc outside of the IT department (with the exception of minor stuff like Excel macros)?

答:
One way that my company helps in these sort of situations is to not be language agnostic. If you want an app/program to even be considered it needs to be in a language of our choice (java). We may stretch the rules a bit for some JQuery or js but it would need to be a well composed application that served a critical need. Don't come and say "I've got this PHP app that I need you to host for me" because you'll probably just be handed a policy sheet.

It's important to nip the things before they get too big, cause once they are you better have someone you can dedicate to learning it, or rewriting it. Because once that big wig upstairs decides he likes it your probably never going to get rid of it in my experience.


答:
No; the definition of functional paradigm is about lack of state and implicitly lack of side-effects. It is not about high-order functions, closures, language supported list manipulation or others language features...

The name of functional programming comes from the mathematical notion of functions - repeated calls on the same input always gives the same output - nullipotent function. This can only be achieved if the data is immutable. In order to ease development, the functions became mutable (functions change, data is still immutable) and thus the notion of higher-order functions (functionals in mathematics, as derivatives for example) - a function that takes as input another function. For the possibility of functions to be carried around and passed as arguments, first-class functions were adopted; following these, to further enhance productivity, closures appeared.

This is, of course, a very simplified view.

Title: Are closures with side-effects considered "functional style"?

Body:
Many modern programming languages support some concept of closure, i.e. of a piece of code (a block or a function) that

Can be treated as a value, and therefore stored in a variable, passed around to different parts of the code, be defined in one part of a program and invoked in a totally different part of the same program.

Can capture variables from the context in which it is  defined, and access them when it is later invoked (possibly in a totally different context).

Here is an example of a closure written in Scala:

```<code>def filterList(xs: List[Int], lowerBound: Int): List[Int] =
  xs.filter(x => x >= lowerBound)
</code>```

The function literal x => x >= lowerBound contains the free variable lowerBound, which is closed (bound) by the argument of the function filterList that has the same name. The closure is passed to the library method filter, which can invoke it repeatedly as a normal function.

I have been reading a lot of questions and answers on this site and, as far as I understand, the term closure is often automatically associated with functional programming and functional programming style.

The definition of function programming on wikipedia reads:

In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state.

and further on

[...] in functional code, the output value of a function depends only on the arguments that are input to the function [...]. Eliminating side effects can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming.

On the other hand, many closure constructs provided by programming languages allow a closure to capture non-local variables and change them when the closure is invoked, thus producing a side effect on the environment in which they were defined.

In this case, closures implement the first idea of functional programming (functions are first-class entities that can be moved around like other values) but neglect the second idea (avoiding side-effects).

Is this use of closures with side effects considered functional style or are closures considered a more general construct that can be used both for a functional and a non-functional programming style? Is there any literature on this topic?

IMPORTANT NOTE

I am not questioning the usefulness of side-effects or of having closures with side effects. Also, I am not interested in a discussion about the advantages / disadvantages of closures with or without side effects.

I am only interested to know if using such closures is still considered functional style by the proponent of functional programming or if, on the contrary, their use is discouraged when using a functional style.


答: In general, when it gets hard to match braces in whatever style -  it probably means the method is too long and should be re-factored.</p>

Title: Dealing with curly brace soup

Body:
I've programmed in both C# and VB.NET for years, but primarily in VB. I'm making a career shift toward C# and, overall, I like C# better.

One issue I'm having, though, is curly brace soup. In VB, each structure keyword has a matching close keyword, for example:

Namespace ...
    Class ...
        Function ...
            For ...
                Using ...
                    If ...
                        ...
                    End If
                    If ...
                        ...
                    End If
                End Using
            Next
        End Function
    End Class
End Namespace
```

<p>The same code written in C# ends up very hard to read:</p>

<pre class="lang-csharp prettyprint-override"><code>namespace ... {
    class ... {
        function ... {
            for ... {
                using ... {
                    if ... {
                        ...
                    }
                    if ... {
                        ...
                    }
                }
            }
            // wait... what level is this?
        }
    }
}
</code>```

Being so used to VB, I'm wondering if there's a technique employed by c-style programmers to improve readability and to ensure that your code ends up in the correct "block". The above example is relatively easy to read, but sometimes at the end of a piece of code I'll have 8 or more levels of curly braces, requiring me to scroll up several pages to figure out which brace ends the block I'm interested in.


答:
Functional programming take first class functions to the next conceptual level for sure, but declaring anonymous functions or passing functions to other functions is not necessarily a functional programming thing.  In C, everything was an integer.  A number, a pointer to data, a pointer to a function... all just ints.  You could pass function pointers to other functions, make lists of function pointers...  Heck, if you work in assembly language, functions are really just addresses in memory where blocks of machine instructions are stored.  Giving a function a name is extra overhead for the people who need a compiler to write code.  So functions were "first-class" in that sense in a completely non-functional language.

If the only thing you do is calculate mathematical formulas in a REPL, then you can be functionally pure with your language.  But most business programming has side effects.  Losing money while waiting for a long-running program to complete is a side effect.  Taking any external action: writing to a file, updating a database, logging events in order, etc. requires a change of state.  We could debate about whether state is really changed if you encapsulate these actions in immutable wrappers that push side-effects off so that your code doesn't have to worry about them.  But it's like discussing whether a tree makes a noise if it falls in the forest with no-one there to hear it.  The fact is that the tree started upright and ended up on the ground.  State gets changed when stuff gets done, even if only to report that the stuff got done.  True purity in functional programming is only fully realized in isolated sections of code or on paper - not in real, useful programs as a whole.

So we are left with a scale of functional purity, not black and white, but shades of gray.  And on that scale, the fewer side effects, the less mutability, the better (more functional).

If you absolutely require side effect or mutable state in your otherwise functional code, you strive to encapsulate or it from the rest of your program as best you can.  Using a closure (or anything else) to inject side effects or mutable state into otherwise pure functions is the antithesis of functional programming.  The only exception might be if the closure were the most effective way to encapsulate the side effects from the code it is passed to.  It's still not "functional programming" but it might be the closet you can get in certain situations.


问:
Strategies for invoking subclass methods on generic objects

Possible Duplicate:

  Alternatives to type casting in your domain

I've run into this issue in a number of places and have solved it a bunch of different ways but looking for other solutions or opinions on how to address. The scenario is when you have a collection of objects all based off of the same superclass but you want to perform certain actions based only on instances of some of the subclasses.

One contrived example of this might be an HTML document made up of elements. You could have a superclass named HTMLELement and subclasses of Headings, Paragraphs, Images, Comments, etc. To invoke a common action across all of the objects you declare a virtual method in the superclass and specific implementations in all of the subclasses. So to render the document you could loop all of the different objects in the document and call a common Render() method on each instance.

It's the case where again using the same generic objects in the collection I want to perform different actions for instances of specific subclass (or set of subclasses). For example (an remember this is just an example) when iterating over the collection, elements with external links need to be downloaded (e.g. JS, CSS, images) and some might require additional parsing (JS, CSS). What's the best way to handle those special cases.

Some of the strategies I've used or seen used include:

Virtual methods in the base class.

So in the base class you have a virtual LoadExternalContent() method that does nothing and then override it in the specific subclasses that need to implement it. The benefit being that in the calling code there is no object testing you send the same message to each object and let most of them ignore it. Two downsides that I can think of. First it can make the base class very cluttered with methods that have nothing to do with most of the hierarchy. Second it assumes all of the work can be done in the called method and doesn't handle the case where there might be additional context specific actions in the calling code (i.e. you want to do something in the UI and not the model).

Have methods on the class to uniquely identify the objects.

This could include methods like ClassName() which return a string with the class name or other return values like enums or booleans (IsImage()). The benefit is that the calling code can use if or switch statements to filter objects to perform class specific actions. The downside is that for every new class you need to implement these methods and can look cluttered. Also performance could be less than some of the other options.

Use language features to identify objects.

This includes reflection and language operators to identify the objects. For example in C# there is the is operator that returns true if the instance matches the specified class. The benefit is no additional code to implement in your object hierarchy. The only downside seems to be the lack of using something like a switch statement and the fact that your calling code is a little more cluttered.

Are there other strategies I am missing? Thoughts on best approaches?

答:
One other possible approach is to use the visitor design pattern.

It gives you the possibility of implementing different behaviors in different classes each of which should implement one method that will operate on each type.

Its advantage over declaring virtual methods in the base class and override them is that you can extend your functionality by adding new classes rather than changing existing ones.


问:
What is the best approach for inline code comments?
We are doing some refactoring to a 20 years old legacy codebase, and I'm having a discussion with my colleague about the comments format in the code (plsql, java).

There is no a default format for comments, but in most cases people do something like this in the comment:

```<code>// date (year, year-month, yyyy-mm-dd, dd/mm/yyyy), (author id, author name, author nickname) and comment
</code>```

the proposed format for future and past comments that I want is:

```<code>// {yyyy-mm-dd}, unique_author_company_id, comment
</code>```

My colleague says that we only need the comment, and must reformat all past and future comments to this format:

```<code>// comment
</code>```

My arguments:

I say for maintenance reasons, it's important to know when and who
did a change (even this information is in the SCM).

The code is living, and for that reason has a history.

Because without the change dates it's impossible to know when a change was introduced without open the SCM tool and search in the long object history.

because the author is very important, a change of authors is more credible than a change of authory

Agility reasons, no need to open and navigate through the SCM tool

people would be more afraid to change something that someone did 15 years ago, than something that was recently created or changed.

etc.

My colleague's arguments:

The history is in the SCM

Developers must not be aware of the history of the code directly in the code

Packages gets 15k lines long and unstructured comments make these packages harder to understand

What do you think is the best approach? Or do you have a better approach to solve this problem?

答:
I strongly support your colleague. You won't get by without looking at the SCM anyway if you want to understand why something was changed unless you keep the old code in a comment.

If the code is too complex to be understood without writing tons of comments, I'd suggest investing you energy into refactoring to make the code readable/maintanable without tons of comments.

After all, you hire programmers, not story tellers ;-)


问:
Which web framework to use under Backbonejs?
For a previous project, I was using Backbonejs alongside Django, but I found out that I didn't use many features from Django. So, I am looking for a lighter framework to use underneath a Backbonejs web app.

I never used Django built in templates. When I did, it was to set up the initial index page, but that's all.

I did use the user management system that Django provided.

I used the models.py, but never views.py.

I used urls.py to set up which template the user would hit upon visiting the site.

I noticed that the two features that I used most from Django was South and Tastypie, and they aren't even included with Django.

Particularly, django-tastypie made it easy for me to link up my frontend models to my backend models. It made it easy to JSONify my front end models and send them to Tastypie.
Although, I found myself overriding a lot of tastypie's methods for GET, PUT, POST requests, so it became useless.

South made it easy to migrate new changes to the database. Although, I had so much trouble with South. Is there a framework with an easier way of handling database modifications than using South? When using South with multiple people, we had the worse time keeping our databases synced. When someone added a new table and pushed their migration to git, the other two people would spend days trying to use South's automatic migration, but it never worked. I liked how Rails had a manual way of migrating databases.

Even though I used Tastypie and South a lot, I found myself not actually liking them because I ended up overriding most Tastypie methods for each Resource, and I also had the worst trouble migrating new tables and columns with South. So, I would like a framework that makes that process easier. Part of my problem was that they are too "magical".

Which framework should I use? Nodejs or a lighter Python framework? Which works best with my above criteria?

答: Consider for looking at Monorails.js. It's an ultra lightweight MVC framework for Node.js with nice ORM capabilities and scaffolding. It also supports Redis models, which is amazingly fast in combination with Node.js. So, try it, hope this will be helpful.</p>


答:
Acording to Liskov substitition principle, LSP, a base class must be replaceable by any of its subclasses.

This principle makes possible that a calling code written for the superclass should work with a subclass designed later in time.

If the calling method needs to call methods that don't exist in the superclass, then such calling method wasn't designed  around that superclass.

The best aproach is to improve the class design not to violate LISP.

In your example:

For example (an remember this is just an example) when iterating over
  the collection, elements with external links need to be downloaded
  (e.g. JS, CSS, images) and some might require additional parsing (JS,
  CSS).

The aditional parsing needs not be called from outside, breaking LISP. It's an under-the-hood behavior on the subclass that doesn't need to affect the superclass contract.

LoadExternalContent() should be a private methods of the subclass called in either the constructor or the Render method or other.

Also, you will find some behavior that should be promoted to the superclass. That's OK.

And finally: if you wrote a code that iterates a list of disparate objects and needs to call especific subclass methods, then that code is not written for the superclass/interface and casting the especific types is intrinsic to such a method.

Title: Strategies for invoking subclass methods on generic objects

Body:
Possible Duplicate:

  Alternatives to type casting in your domain

I've run into this issue in a number of places and have solved it a bunch of different ways but looking for other solutions or opinions on how to address. The scenario is when you have a collection of objects all based off of the same superclass but you want to perform certain actions based only on instances of some of the subclasses.

One contrived example of this might be an HTML document made up of elements. You could have a superclass named HTMLELement and subclasses of Headings, Paragraphs, Images, Comments, etc. To invoke a common action across all of the objects you declare a virtual method in the superclass and specific implementations in all of the subclasses. So to render the document you could loop all of the different objects in the document and call a common Render() method on each instance.

It's the case where again using the same generic objects in the collection I want to perform different actions for instances of specific subclass (or set of subclasses). For example (an remember this is just an example) when iterating over the collection, elements with external links need to be downloaded (e.g. JS, CSS, images) and some might require additional parsing (JS, CSS). What's the best way to handle those special cases.

Some of the strategies I've used or seen used include:

Virtual methods in the base class.

So in the base class you have a virtual LoadExternalContent() method that does nothing and then override it in the specific subclasses that need to implement it. The benefit being that in the calling code there is no object testing you send the same message to each object and let most of them ignore it. Two downsides that I can think of. First it can make the base class very cluttered with methods that have nothing to do with most of the hierarchy. Second it assumes all of the work can be done in the called method and doesn't handle the case where there might be additional context specific actions in the calling code (i.e. you want to do something in the UI and not the model).

Have methods on the class to uniquely identify the objects.

This could include methods like ClassName() which return a string with the class name or other return values like enums or booleans (IsImage()). The benefit is that the calling code can use if or switch statements to filter objects to perform class specific actions. The downside is that for every new class you need to implement these methods and can look cluttered. Also performance could be less than some of the other options.

Use language features to identify objects.

This includes reflection and language operators to identify the objects. For example in C# there is the is operator that returns true if the instance matches the specified class. The benefit is no additional code to implement in your object hierarchy. The only downside seems to be the lack of using something like a switch statement and the fact that your calling code is a little more cluttered.

Are there other strategies I am missing? Thoughts on best approaches?


答:
General Comments

I am a great believer in comments are for why (not how). When you start adding comments about how you fall into the problem that nothing is enforcing that comments be maintained in relation to the code (the why will usually not change (the why explanation may be enhanced some over time)).

In the same way date/authorInfo does not gain you anything in terms of why the code was done this way; just like the how it can degenerate over time because there is no enforcement by any tools. Also the same information is already stored in the source control system (so you are duplicating effort (but in a less reliable way)).

Going through the arguments:

I say for maintenance reasons, it's important to know when and who did a change (even this information is in the SCM).

Why. Neither of these things strike me as important to maintaining the code. If you need to talk to the author it is relatively simple to find this information from source control.

The code has life for that reason had an history.

History is stored in source control.

Also do you trust that the comment was written by that person. How comments tend to degrade over time so this kind of history becomes unreliable. Source control systems on the other hand will maintain a very accurate history and you can accurately see when comments were added/removed.

Because without the change date it's impossible to know when a change was introduced without open the SCM tool and search in the long object history.

If you trust the data in a comment.

One of the problems with this kind of things is that the comments become incorrect in relation to the code. Back to the correct tool for the job. The source control system will do this correctly without need for intervention from the user. If your source control system is a pain then maybe you need to either learn how to use it more appropriately (as that functionality is usually easy) or if does not support it find a better source control system.

because the author is very important, a change of authorx is more credible than a change of authory

All authors (apart from yourself) are equally credible.

Agility reasons, no need to open an navigate the SCM tool

If your source control tool are that burdensome you are wither using it incorrectly or (it is more likely) you are using the wrong set of tools to access the source control system.

people would be afraid of change something that someone did 15 years ago, than someting that was receantly made ...

If code has lasted 15 years then it is more likely to be more solid then code that has only lasted 6 months without needing review. Stable code tends to stay stable, buggy code tends to get more complex over time (as the reason it is buggy is the problem is not as simple as first thought).

Even more reason to use source control to get information.

The history is in the SCM

Yes. Best reason yet.

Developers must not be aware of history of the code directly in the code

If I really need this information I will look it up in source control.

Otherwise it is not relevant.

Packages gets 15k lines long and unstructured comments this packages harder to understand

Comments should be a description of why you are doing something anyway.

Comments should NOT be describing how the code works (unless the algorithm is not obvious).

Title: What is the best approach for inline code comments?

Body:
We are doing some refactoring to a 20 years old legacy codebase, and I'm having a discussion with my colleague about the comments format in the code (plsql, java).

There is no a default format for comments, but in most cases people do something like this in the comment:

```<code>// date (year, year-month, yyyy-mm-dd, dd/mm/yyyy), (author id, author name, author nickname) and comment
</code>```

the proposed format for future and past comments that I want is:

```<code>// {yyyy-mm-dd}, unique_author_company_id, comment
</code>```

My colleague says that we only need the comment, and must reformat all past and future comments to this format:

```<code>// comment
</code>```

My arguments:

I say for maintenance reasons, it's important to know when and who
did a change (even this information is in the SCM).

The code is living, and for that reason has a history.

Because without the change dates it's impossible to know when a change was introduced without open the SCM tool and search in the long object history.

because the author is very important, a change of authors is more credible than a change of authory

Agility reasons, no need to open and navigate through the SCM tool

people would be more afraid to change something that someone did 15 years ago, than something that was recently created or changed.

etc.

My colleague's arguments:

The history is in the SCM

Developers must not be aware of the history of the code directly in the code

Packages gets 15k lines long and unstructured comments make these packages harder to understand

What do you think is the best approach? Or do you have a better approach to solve this problem?


问:
Difference between a pseudo code and algorithm?
Technically, Is there a difference between these two words or can we use them interchangeably? Both of them more or less describe the logical sequence of steps that follow in solving a problem. ain't it? SO why do we actually use two such words if they are meant to talk of the same?

Or, In case if they aren't synonymous words, What is it that differentiates them? In what contexts are we supposed to use the word pseudo code vs the word algorithm?

答:
Even though pseudo-code seems closer to code than an algorithm, in practice, pseudo code is less formal and it is a more high level description. For instance you can describe a chess playing computer as a pseudo code like this:

place initial pieces in their locations

show board

while game is not over

make move and display board

prompt user for move

make users move

Yes, this is pseudocode, it is helpful as a good starting point but glosses over lots of details. It does not account for implementation difficulties and variations, but the biggest benefit is that it allows you to conceptualize the whole situation without having to solve all the details.

You can revise it, adding one more level like so:

place initial pieces in their locations

show board

while board is not checkmate or draw

make a list of white's legal moves

choose the best according to some criteria

make that move and compute resulting board

see if checkmate or draw has occurred

display board

make a list of black's legal moves

prompt user for legal move for input

make that move and compute resulting board

see if checkmate or draw has occurred

display board

Now you can write pseudocode for each of the major steps like "make a list of black's legal moves", like so:

for each black piece

for piece type in a given location

make a list of next possible locations

Now you can see the power of pseudocode is really in its ability to show the whole situation in one go and then allowing you to address details piece by piece.
The weakness is that any step is not a definite simple step.

An algorithm typically picks up one of these steps and details out various data structures in a symbolic language so that you can efficiently meet the goal of the step.

For example, get_legal_moves(board, color) is worthy of an algorithm design:

```<code>get_legal_moves(board, color):
    for i,j in board_dimensions
        if piece_at i,j is of color
            if piece type is KNIGHT
                add the following to the next moves list:
                    location i+1 j+2, i-1 j+2... etc
            if piece type is rook
                add locations:....
</code>```

You can see that the algorithm has to be very precise to be useful.

It ensures several things: that the goals will be met without errors, first and foremost. The steps are very detailed and executable in a mechanized way and that
the steps are small enough that you can reorder them to increase the efficiency
(speed) with which you finish the task.

Body:
Even though pseudo-code seems closer to code than an algorithm, in practice, pseudo code is less formal and it is a more high level description. For instance you can describe a chess playing computer as a pseudo code like this:

place initial pieces in their locations

show board

while game is not over

make move and display board

prompt user for move

make users move

Yes, this is pseudocode, it is helpful as a good starting point but glosses over lots of details. It does not account for implementation difficulties and variations, but the biggest benefit is that it allows you to conceptualize the whole situation without having to solve all the details.

You can revise it, adding one more level like so:

place initial pieces in their locations

show board

while board is not checkmate or draw

make a list of white's legal moves

choose the best according to some criteria

make that move and compute resulting board

see if checkmate or draw has occurred

display board

make a list of black's legal moves

prompt user for legal move for input

make that move and compute resulting board

see if checkmate or draw has occurred

display board

Now you can write pseudocode for each of the major steps like "make a list of black's legal moves", like so:

for each black piece

for piece type in a given location

make a list of next possible locations

Now you can see the power of pseudocode is really in its ability to show the whole situation in one go and then allowing you to address details piece by piece.
The weakness is that any step is not a definite simple step.

An algorithm typically picks up one of these steps and details out various data structures in a symbolic language so that you can efficiently meet the goal of the step.

For example, get_legal_moves(board, color) is worthy of an algorithm design:

get_legal_moves(board, color):
    for i,j in board_dimensions
        if piece_at i,j is of color
            if piece type is KNIGHT
                add the following to the next moves list:
                    location i+1 j+2, i-1 j+2... etc
            if piece type is rook
                add locations:....

You can see that the algorithm has to be very precise to be useful.

It ensures several things: that the goals will be met without errors, first and foremost. The steps are very detailed and executable in a mechanized way and that
the steps are small enough that you can reorder them to increase the efficiency
(speed) with which you finish the task.


答:
An algorithm is the semantic while the pseudo-code is just a syntax of the communication about solving a problem. This means that the algorithm is an actual way a problem is solved while the pseudo-code is just a way of expressing that way.

An algorithm has the same meaning (semantic) if you express it in any way (syntax) be it C programming language, pseudo-code or English language.

Title: Difference between a pseudo code and algorithm?

Body:
Technically, Is there a difference between these two words or can we use them interchangeably? Both of them more or less describe the logical sequence of steps that follow in solving a problem. ain't it? SO why do we actually use two such words if they are meant to talk of the same?

Or, In case if they aren't synonymous words, What is it that differentiates them? In what contexts are we supposed to use the word pseudo code vs the word algorithm?


答:
A good coder is like a good pool player.

When you see a professional pool player, you at first might not be impressed: "Sure, they got all of the balls in, but they had only easy shots!" This is because, when a pool player is making her shot, she doesn't think about what ball will go into which pocket, she's also thinking about where the cue ball will end up. Setting up for the next shot takes tremendous skill and practice, but it also means that it looks easy.

Now, bringing this metaphor to code, a good coder writes code that looks like it was easy and straightforward to do. Many of the examples by Brian Kernighan in his books follow this pattern. Part of the "trick" is coming up with a proper conceptualization of the problem and its solution. When we don't understand a problem well enough, we're more likely to over-complicate our solutions, and we will fail to see unifying ideas.

With a proper conceptualization of the problem, you get everything else: readability, maintainability, efficiency, and correctness. Because the solution seems so straightforward, there will likely be fewer comments, because extra explanation is unnecessary. A good coder can also see the long term vision of the product, and form their conceptualizations accordingly.

Title: What does it mean to write "good code"?

Body:
In this question I asked whether being a bad writer hinders you from writing good code. Many of the answers started of with "it depends on what you mean by good code".

It appears that the term "good code" and "bad code" are very subjective. Since I have one view, it may be very different from others' view of them.

So what does it mean to write "good code"? What is "good code"?


问:
Are flag variables an absolute evil?
Are flag variables evil? Are the following kind of variables profoundly immoral and is it wicked to use them?

"boolean or integer variables that you assign a value in certain places then down below you check then in orther to do something or not, like, for example using newItem = true then some lines below if (newItem ) then"

I remember doing a couple of projects where I totally neglected using flags and ended up with better architecture/code; however, it is a common practice in other projects I work at, and when code grows and flags are added, IMHO code-spaghetti also grows.

Would you say there are any cases where using flags is a good practice or even necessary?, or would you agree that using flags in code are... red flags and should be avoided/refactored; me, I just get by with doing functions/methods that check for states in real time instead.

答:
I don't think anything is an absolute evil in programming, ever.

There is another situation where flags might be in order, which were not mentioned here yet...

Consider the use of closures in this Javascript snippet:

```<code>exports.isPostDraft = function ( post, draftTag ) {
  var isDraft = false;
  if (post.tags)
    post.tags.forEach(function(tag){
      if (tag === draftTag) isDraft = true;
    });
  return isDraft;
}
</code>```

The inner function, being passed to the "Array.forEach", cannot simply "return true".

Hence, you need to keep the state outside with a flag.

Title: Are flag variables an absolute evil?

Body:
I don't think anything is an absolute evil in programming, ever.

There is another situation where flags might be in order, which were not mentioned here yet...

Consider the use of closures in this Javascript snippet:

exports.isPostDraft = function ( post, draftTag ) {
  var isDraft = false;
  if (post.tags)
    post.tags.forEach(function(tag){
      if (tag === draftTag) isDraft = true;
    });
  return isDraft;
}

The inner function, being passed to the "Array.forEach", cannot simply "return true".

Hence, you need to keep the state outside with a flag.


答:
I remove 2 levels of nesting by collapsing the namespace and class scopes horizontally.  Notice the methods are flush with the left edge of the screen. I don't see the point in losing 2 levels of indentation in every file.

After that it's rare you'll ever have nesting more than 4 levels deep.

```<code>namespace FooNameSpace {
class Foo {

public void bar()
{
    while(true)
    {
        while(true)
        {
            break;
        }
    }
}

public void fooBar()
{
    foreach(var item in FooList)
    {
        foreach(var b in item.Bars)
        {
            if(b.IsReady)
            {
                bar();
            }
            bar();
        }
        bar();
    }
}

}}//end class, namespace
</code>```

Title: Dealing with curly brace soup

Body:
I remove 2 levels of nesting by collapsing the namespace and class scopes horizontally.  Notice the methods are flush with the left edge of the screen. I don't see the point in losing 2 levels of indentation in every file.

After that it's rare you'll ever have nesting more than 4 levels deep.

namespace FooNameSpace {
class Foo {

public void bar()
{
    while(true)
    {
        while(true)
        {
            break;
        }
    }
}

public void fooBar()
{
    foreach(var item in FooList)
    {
        foreach(var b in item.Bars)
        {
            if(b.IsReady)
            {
                bar();
            }
            bar();
        }
        bar();
    }
}

}}//end class, namespace


问:
Git workflow for small teams
I'm working on a git workflow to implement in a small team. The core ideas in the workflow:

There is a shared project master that all team members can write to

All development is done exclusively on feature branches

Feature branches are code reviewed by a team member other than the branch author

The feature branch is eventually merged into the shared master and the cycle starts again

The article explains the steps in this cycle in detail:

https://github.com/janosgyerik/git-workflows-book/blob/small-team-workflow/chapter05.md

Does this make sense or am I missing something?

答:
I think you are missing the topic Continuous Integration. It should be part of every development setup.

With feature branches you have the problem, that you don't integrate continously, but only after a feature is completed.

If the feature branched is short lived, this might be acceptable, but it is definetly something one should consider.

Another alternativ is to setup CI builds for each feature branch. This sure does help, but it isn't integration. This becomes obvious once you find your first bug that doesn't appear in Feature A nor Feature B, but in the moment where you integrate Feature A&B

A third alternative is to make merging in some integration branch part of the CI build. This is true integration, and actually works reasonably well with git if the work is somewhat seperated, but causes merge conflicts during the build resulting in failed builds.

OwnerDisplayName: janos

Title: Git workflow for small teams

OwnerDisplayName: Jens Schauder


答:
I like the git flow branching model. The master branch is left alone most of the time, it only contains releases. The develop branch should be stable at all times, and the feature branches can be broken.

You can also combine this with continuous integration by merging develop into your feature branch and your feature branch into develop. Of course you should only merge something into develop when you're confident that things are working and do not break.

Title: Git workflow for small teams

Body:
I'm working on a git workflow to implement in a small team. The core ideas in the workflow:

There is a shared project master that all team members can write to

All development is done exclusively on feature branches

Feature branches are code reviewed by a team member other than the branch author

The feature branch is eventually merged into the shared master and the cycle starts again

The article explains the steps in this cycle in detail:

https://github.com/janosgyerik/git-workflows-book/blob/small-team-workflow/chapter05.md

Does this make sense or am I missing something?

OwnerDisplayName: Arjan


问:
Set modified date = created date or null on record creation?
I've been following the convention of adding created and modified columns to most of my database tables. I also have been leaving the modified column as null on record creation and only setting a value on actual modification.

The other alternative is to set the modified date to be equal to created date on record creation.

I've been doing it the former way but I recent ran into one con which is seriously making me think of switching. I needed to set a database cache dependency to find out if any existing data has been changed or new data added. Instead of being able to do the following:

SELECT MAX(modified) FROM customer

I have to do this:

SELECT GREATEST(MAX(created), MAX(modified)) FROM customer

The negative being that it's a more complicated query and slower. Another thing is in file systems I believe they usually use the second convention of setting modified date = created date on creation.

What are the pros and cons of the different methods? That is, what are the issues to consider?

UPDATE

I believe given the apparent trade-offs I'm going to go with modified = created strategy.  In addition, I was curious how other web databases handled this and I noticed drupal seems to follow the convention of modified = created also.

答: Depending on what you use the dates for, another strategy to consider is to add version numbers. Then you can keep previous versions around for auditing and this can help to resolve conflicts when two clients read the data simultaneously and then both submit modifications (although you can get there with modification dates as well)</p>


问:
What GUI tools are available for which DVCS?
When I worked at Sun, we used a DVC system called Forte SCCS/Teamware, which used the old SCCS file format, but was a true distributed source code revision control system.

One nice feature is that it had strong GUI support:

You could bringover and putback changes by simply clicking and dragging.

It would draw trees/graphs showing how workspaces relate to each other.

You also could have a graph view to display a single file's complete history, which might have had several branches and merges. Allowing you to compare any two points.

It also had a strong visual merge tool, to let you accept changes from one of two conflicting files.

Naturally, many of the current DVCSs have command line support for these operations, but I'm looking for GUI support in order to use this in a lower-level undergraduate course I'll be teaching.

I'm not saying the Forte Teamware solution was perfect, but it did seem to be ahead of the curve. Unfortunately, it's not a viable option to use for my class.

Question: What support do the current DVCSs have with regards to GUIs? Do any of them work on Windows, and not just Linux? Are they "ready for prime-time" or still works in progress? Are these standalone or built as plug-ins, e.g., for Eclipse?

Note: To help keep this discussion focused I'm only interested in GUI tools. And not a meta-discussion if GUI tools should be used in teaching.

答: TortoiseHg for Mercurial and TortoiseGit for Git are quite ready for serious use, in my experience. Don't know about Eclipse, but NetBeans supports Mercurial straight out of the box, and NbGit plugin gives Git support.</p>


问:
Sharing Large Database Backup Among Team
I work on a team of three - five developers that work on an ASP.net web application remotely. We currently run a full local database from a recent backup on all of our machines during development. The current backup, compressed, is about 18 GB.

I'm looking to see if there's an easier way to keep all of our local copies relatively fresh without each of us individually downloading the 18 GB file over HTTP from our web server on a regular basis. I guess FTP is an option, but it won't speed the process up at all.

I'm familiar with torrents and the thought keeps hitting me that something like that would be effective, but I'm unsure of the security or the process.

答: rsync or some other copy-only-differences system. Deltas between two subsequent db dumps ought to be pretty similar.</p>


答:
Indentation tells you where you are, in both styles of syntax. If you write either a VB program or a C# program on a single line, you will soon not be able to tell where in the nested syntax you are. The machine parses the block ending phrases or curly braces, but humans need indentation.

Block ending phrases come from an era of punched cards and paper tape, when programming was much less interactive and visual. Or, really, not interactive at all. It was difficult to enter programs, and so programmers needed compilers to be very clever about syntax analysis and error recovery.

In that bygone era, the edit-compile-run cycle might have involved preparing punched cards with a card puncher, and then lining up to a job submission window where a clerk took the punched cards and submitted them to the machine. Later, the programmer would collect the output (printed on paper) from another window. If the program had errors, the output would consist of just the compiler diagnostics.  When the turnaround times are long, the added cost of typing end if instead of just ) is justified if it helps to improve the quality of diagnostics, because the programmer needs to correct as many errors as possible in a single iteration to reduce the number of time-wasting iterations through the job submission window.

When a closing curly brace is missing, it is hard to tell which open brace is the one which is not closed. (The compiler may have to parse indentation to make an educated guess.) If you delete a closing brace inside a function, then it looks like the entire rest of the file is part of that function, resulting in a flurry of unhelpful error messages.  Whereas if you have an end function syntax, the compiler can deduce where the erroneous function ends, recover, and parse the subsequent functions properly, giving you additional diagnostics, if any, which are meaningful.

When you're working in code-aware text editor which automatically indents and colorizes your code, on a high resolution screen where you can see sixty or more lines, the arguments for those kinds of clumsy languages no longer apply. You can incrementally edit and rebuild programs so fast that you can just deal with one error at a time. Moreover, by seeing large sections of the program simultaneously on the screen and maintaining proper indentation, you can reduce the occurrence of those kinds of nesting errors in the first place. And good programming text editor will even flag some kinds of syntax errors as you type. What is more, there are folding editors which will collapse the blocks of a program based on its syntax, giving an "outline-like" view of its structure.

Lisp used parentheses from the beginning and perhaps, not coincidentally, Lisp hackers pioneered programming as an interactive experience by building systems which accepted programs in small chunks (expressions).

In fact, you don't need ending symbols at all, as the Python language illustrates. The  identation can just be the structure. Humans already use indentation to grok the structure of code even in languages where the machine relies on ending symbols or phrases.

Title: Dealing with curly brace soup


问:
Should the number of developers be considered when estimating a task?
I am pretty inexperienced with working in agile projects but I have tried it a few times and I always run into this problem when estimating a task.

Do we bring into the estimate the number of developers that will work on the task?

Let me explain:
Task A is estimated to one time unit and developer 1 will work on it.
Task B is also estimated to one time unit and developer 2 and 3 will work on it together.

I.e. if developer 1 begins to work on task A at the same time developer 2 and 3 begins to work on task B they will all finish at the same time according to the estimate.

Should the estimate for task B be twice of that for task A or the same?

The problem as I see it is that when a task is received and estimated, it is not always possible to know how many people will work on it. And if you assumed that two developers would work on the task for one time unit but it turns out that only one developer will actually do it, this will not automatically mean that that developer will work on it for two time units.

Is there any standard practice for this?

答:
Short answer; no, I do not believe the number of developers is an input to an estimation activity. However, in constrast to the answer from @ChrisF, I also do not believe that developer skill, or any other facet of 'complexity' should be an input to an estimation activity.

See my (rather long) response to this question; Should you ever re-estimate user stories?, where I discuss my views on complexity and estimation.

Number of developers, developer skill, and other aspects of complexity (such as choice of language, existing code libraries available) are all factors which will contribute to how long a task takes, but they should not change the size of the task, which is what you should be aiming to measure in your estimations.

Another example (on top of the one in that other thread); you have a user story which reads something like; "I want a button, which when clicked will show an error message to unauthorised users". Now, your team estimates this task as "small" (at least, mine would!),  and it goes in your backlog. Your team of 3 developers take 1 sprint to achieve this task. Another team of 10 developers may take 2 sprints to achieve the task, because this is their first ever job, and 7 of them don't share a common language. On the other hand, your lead developer by himself takes 1/2 a sprint to achieve this task, because he's done it before and knows some tricks.

At the end of these 3 different periods (1, 2, 1/2 sprints) what do you have? [thinking, thinking...] Correct! A button, which when pressed shows an error message to unauthorised users. The size of this task - has not changed between these 3 teams, they've all produced exactly the same output. However, other factors in the development process have affected the outcome in relation to time (and probably quality, code-reuse, and other nice things).

Estimating this way feeds much more effectively into velocity measurements (team 1 has good velocity, team 2 poor, and team 3 fantastic). Now we can adjust other aspects of the development process to get better results - e.g; give team 1 a couple more developers, split team 2 into smaller teams and add some experience, give team 3 some mentoring jobs so the other teams can improve.

On the other hand, if you estimate on complexity, or team capability, you skew your velocity, and conceal where the problems lie. Imagine instead that team 1 estimated the task as "medium", team 2 as "large" and team 3 as "small". We assign those estimates a velocity score of 10, 20, 5 respectively (for example).

Now after 1 sprint, team 1 has achieved 10 points, team 2 has 0 points (as the task is incomplete - but they will get 20 points after 2 sprints), and team 3 has 5 points (and probably another 5 as he could fit another small task into his sprint). AS you can see from these contrived example, the velocity of all teams is going to come out much the same. We have no way to then improve velocities. If you estimate this way, all you have come out with is an abstracted estimation of time.

To complicate this approach further - what seems complex now may not be so later (after you write more framework code, developers upskill, etc), or it may become more so (framework code is hard to work with, experienced developers leave the team, etc). So you'll need to re-estimate tasks every sprint to maintain consistency, which will mean re-estimating ALL (or many) tasks in your backlog so you can effectively prioritise them, which is all just wasted time - at the end of the activity, all teams are still producing the same button with the same warning.

So in summary, complexity, developer skill, team size, etc, should all form part of a planning activity, not a sizing activity. That way, it is clear that if you want the team to achieve more, you can adjust team metrics. You can not adjust time.

UPDATE

My response to a comment below is a bit long, so here it is in update form.

In regards to the "button" story; I just came up with some arbitrary story which could represent a single piece of work to illustrate my points. Another team might view this as a bigger task.

Estimating size of stories to a large extent depends on the Product Owner and the context of the system being developed (back-end, embedded, GUI, web, etc). I would aim to estimate the size in terms of what is being delivered, not how, or when. In the case of my example, the deliverable is a button and a dialog - 'small' size estiamtes to me. You could equally consider a deliverable to be a security framework, if that in itself is a deliverable for which the PO gains some perceived value (e.g; "I want single sign on support for our website so I don't have to remember lots of passwords").


问:
How can I best manage making open source code releases from my company's confidential research code?
My company (let's call them Acme Technology) has a library of approximately one thousand source files that originally came from its Acme Labs research group, incubated in a development group for a couple years, and has more recently been provided to a handful of customers under non-disclosure.  Acme is getting ready to release perhaps 75% of the code to the open source community.  The other 25% would be released later, but for now, is either not ready for customer use or contains code related to future innovations they need to keep out of the hands of competitors.

The code is presently formatted with #ifdefs that permit the same code base to work with the pre-production platforms that will be available to university researchers and a much wider range of commercial customers once it goes to open source, while at the same time being available for experimentation and prototyping and forward compatibility testing with the future platform.  Keeping a single code base is considered essential for the economics (and sanity) of my group who would have a tough time maintaining two copies in parallel.

Files in our current base look something like this:

```<code>> // Copyright 2012 (C) Acme Technology, All Rights Reserved.
> // Very large, often varied and restrictive copyright license in English and French,
> // sometimes also embedded in make files and shell scripts with varied
> // comment styles.
>
>
>   ... Usual header stuff...
>
> void initTechnologyLibrary() {
>     nuiInterface(on);
> #ifdef  UNDER_RESEARCH
>     holographicVisualization(on);
> #endif
> }
</code>```

And we would like to convert them to something like:

```<code>> // GPL Copyright (C) Acme Technology Labs 2012, Some rights reserved.
> // Acme appreciates your interest in its technology, please contact xyz@acme.com
> // for technical support, and www.acme.com/emergingTech for updates and RSS feed.
>
>   ... Usual header stuff...
>
> void initTechnologyLibrary() {
>     nuiInterface(on);
> }
</code>```

Is there a tool, parse library, or popular script that can replace the copyright and strip out not just #ifdefs, but variations like #if defined(UNDER_RESEARCH), etc.?

The code is presently in Git and would likely be hosted somewhere that uses Git.  Would there be a way to safely link repositories together so we can efficiently reintegrate our improvements with the open source versions?  Advice about other pitfalls is welcome.

答:
Probably it would be good idea to

1.add comment tags like :

```<code>> // *COPYRIGHT-BEGIN-TAG*
> // Copyright 2012 (C) Acme Technology, All Rights Reserved.
> // Very large, often varied and restrictive copyright license in English and French,
> // sometimes also embedded in make files and shell scripts with varied
> // comment styles.
> // *COPYRIGHT-ENG-TAG*
>   ... Usual header stuff...
>
> void initTechnologyLibrary() {
>     nuiInterface(on);
> #ifdef  UNDER_RESEARCH
>     holographicVisualization(on);
> #endif
> }
</code>```

2. Write script for open source builder to go through all files
and replace text between COPYRIGHT-BEGIN-TAG  and COPYRIGHT-ENG-TAG tags

Body:
Probably it would be good idea to

1.add comment tags like :

> // *COPYRIGHT-BEGIN-TAG*
> // Copyright 2012 (C) Acme Technology, All Rights Reserved.
> // Very large, often varied and restrictive copyright license in English and French,
> // sometimes also embedded in make files and shell scripts with varied
> // comment styles.
> // *COPYRIGHT-ENG-TAG*
>   ... Usual header stuff...
>
> void initTechnologyLibrary() {
>     nuiInterface(on);
> #ifdef  UNDER_RESEARCH
>     holographicVisualization(on);
> #endif
> }

2. Write script for open source builder to go through all files
and replace text between COPYRIGHT-BEGIN-TAG  and COPYRIGHT-ENG-TAG tags


答:
It seems like it wouldn't be too difficult to write a script to parse the preprocessors, compare them to a list of defined constants (UNDER_RESEARCH, FUTURE_DEVELOPMENT, etc.) and, if the directive can be evaluated to false given what's defined, remove everything up to the next #endif.

In Python, I'd do something like,

```<code>import os

src_dir = 'src/'
switches = {'UNDER_RESEARCH': True, 'OPEN_SOURCE': False}
new_header = """// GPL Copyright (C) Acme Technology Labs 2012, Some rights reserved.
// Acme appreciates your interest in its technology, please contact xyz@acme.com
// for technical support, and www.acme.com/emergingTech for updates and RSS feed.
"""

filenames = os.listdir(src_dir)
for fn in filenames:
    contents = open(src_dir+fn, 'r').read().split('\n')
    outfile = open(src_dir+fn+'-open-source', 'w')
    in_header = True
    skipping = False
    for line in contents:
        # remove original header
        if in_header and (line.strip() == "" or line.strip().startswith('//')):
            continue
        elif in_header:
            in_header = False
            outfile.write(new_header)

        # skip between ifdef directives
        if skipping:
            if line.strip() == "#endif":
                skipping = False
            continue
        # check
        if line.strip().startswith("#ifdef"):
            # parse #ifdef (maybe should be more elegant)
            # this assumes a form of "#ifdef SWITCH" and nothing else
            if line.strip().split()[1] in switches.keys():
                skipping = True
                continue

        # checking for other forms of directives is left as an exercise

        # got this far, nothing special - echo the line
        outfile.write(line)
        outfile.write('\n')
</code>```

I'm sure there are more elegant ways to do it, but this is quick and dirty and seems to get the job done.

Title: How can I best manage making open source code releases from my company's confidential research code?

Body:
My company (let's call them Acme Technology) has a library of approximately one thousand source files that originally came from its Acme Labs research group, incubated in a development group for a couple years, and has more recently been provided to a handful of customers under non-disclosure.  Acme is getting ready to release perhaps 75% of the code to the open source community.  The other 25% would be released later, but for now, is either not ready for customer use or contains code related to future innovations they need to keep out of the hands of competitors.

The code is presently formatted with #ifdefs that permit the same code base to work with the pre-production platforms that will be available to university researchers and a much wider range of commercial customers once it goes to open source, while at the same time being available for experimentation and prototyping and forward compatibility testing with the future platform.  Keeping a single code base is considered essential for the economics (and sanity) of my group who would have a tough time maintaining two copies in parallel.

Files in our current base look something like this:

```<code>> // Copyright 2012 (C) Acme Technology, All Rights Reserved.
> // Very large, often varied and restrictive copyright license in English and French,
> // sometimes also embedded in make files and shell scripts with varied
> // comment styles.
>
>
>   ... Usual header stuff...
>
> void initTechnologyLibrary() {
>     nuiInterface(on);
> #ifdef  UNDER_RESEARCH
>     holographicVisualization(on);
> #endif
> }
</code>```

And we would like to convert them to something like:

```<code>> // GPL Copyright (C) Acme Technology Labs 2012, Some rights reserved.
> // Acme appreciates your interest in its technology, please contact xyz@acme.com
> // for technical support, and www.acme.com/emergingTech for updates and RSS feed.
>
>   ... Usual header stuff...
>
> void initTechnologyLibrary() {
>     nuiInterface(on);
> }
</code>```

Is there a tool, parse library, or popular script that can replace the copyright and strip out not just #ifdefs, but variations like #if defined(UNDER_RESEARCH), etc.?

The code is presently in Git and would likely be hosted somewhere that uses Git.  Would there be a way to safely link repositories together so we can efficiently reintegrate our improvements with the open source versions?  Advice about other pitfalls is welcome.

Body:
It seems like it wouldn't be too difficult to write a script to parse the preprocessors, compare them to a list of defined constants (UNDER_RESEARCH, FUTURE_DEVELOPMENT, etc.) and, if the directive can be evaluated to false given what's defined, remove everything up to the next #endif.

In Python, I'd do something like,

import os

src_dir = 'src/'
switches = {'UNDER_RESEARCH': True, 'OPEN_SOURCE': False}
new_header = """// GPL Copyright (C) Acme Technology Labs 2012, Some rights reserved.
// Acme appreciates your interest in its technology, please contact xyz@acme.com
// for technical support, and www.acme.com/emergingTech for updates and RSS feed.
"""

filenames = os.listdir(src_dir)
for fn in filenames:
    contents = open(src_dir+fn, 'r').read().split('\n')
    outfile = open(src_dir+fn+'-open-source', 'w')
    in_header = True
    skipping = False
    for line in contents:
        # remove original header
        if in_header and (line.strip() == "" or line.strip().startswith('//')):
            continue
        elif in_header:
            in_header = False
            outfile.write(new_header)

        # skip between ifdef directives
        if skipping:
            if line.strip() == "#endif":
                skipping = False
            continue
        # check
        if line.strip().startswith("#ifdef"):
            # parse #ifdef (maybe should be more elegant)
            # this assumes a form of "#ifdef SWITCH" and nothing else
            if line.strip().split()[1] in switches.keys():
                skipping = True
                continue

        # checking for other forms of directives is left as an exercise

        # got this far, nothing special - echo the line
        outfile.write(line)
        outfile.write('\n')

I'm sure there are more elegant ways to do it, but this is quick and dirty and seems to get the job done.


答: Use Resharper, which will help recommend ways to reduce nesting. Also, read Bob Martin's book Clean Code, which emphasizes that a function should only do one thing, and therefore each function should only be a half-dozen lines long, so you won't have that many levels of nesting to worry about.

Title: Dealing with curly brace soup


答:
I was thinking about passing your code through the preprocessor to only expand macros, thus outputting only the interesting part in the #ifdefs.

Something like this should work:

```<code>gcc -E yourfile.c
</code>```

But:

You'll lose all comments. You can use -CC to (kind of) preserve them, but then you'll still have to strip off the old copyright notice

#includes are expanded too, so you'll end up with a big file containing all the content of the included header files

You'll lose "standard" macros.

There might be a way to limit which macros are expanded; however my suggestion here is to split up things, instead of doing (potentially hazardous) processing on the files (by the way, how would you plan to maintain them after? e.g. reintroduce code from the opensource version into your closed source?).

That is, try putting the code you want to opensource in in external libraries as much as possible, then use them as you would with any other library, integrating with other "custom" closed-source libraries.

It might take a bit longer at first to figure out how to restructure things, but it's definitely the right way to accomplish this.

Body:
I was thinking about passing your code through the preprocessor to only expand macros, thus outputting only the interesting part in the #ifdefs.

Something like this should work:

gcc -E yourfile.c

But:

You'll lose all comments. You can use -CC to (kind of) preserve them, but then you'll still have to strip off the old copyright notice

#includes are expanded too, so you'll end up with a big file containing all the content of the included header files

You'll lose "standard" macros.

There might be a way to limit which macros are expanded; however my suggestion here is to split up things, instead of doing (potentially hazardous) processing on the files (by the way, how would you plan to maintain them after? e.g. reintroduce code from the opensource version into your closed source?).

That is, try putting the code you want to opensource in in external libraries as much as possible, then use them as you would with any other library, integrating with other "custom" closed-source libraries.

It might take a bit longer at first to figure out how to restructure things, but it's definitely the right way to accomplish this.