问:
Which of these old criticisms of common lisp still apply today?
In A Critique of Common Lisp written by Rodney A. Brooks and Richard P. Gabriel from Stanford in 1984, some design decisions retained by the normalizing committee of Common Lisp are discussed.  While most of the discussion remains valid, there are two statements that refer to the technology available at the time and may be false today.

These two statements are:

Too many costs of the language were dismissed with the admonition that ‘any good
  compiler’ can take care of them. No one has yet written—nor is likely to without
  tremendous effort—a compiler that does a fraction of the tricks expected of it.

As I am a Common Lisp novice, or even an apprentice, I am not able to be more specific than the authors are.  They seem to state that a great generality and flexibility has been built into several aspects of the language, which makes writing a good compiler quite difficult.

In COMMON LISP a little too much control was
  placed on floating-point arithmetic. And certainly, although the correct behavior of a
  floating-point-intensive program can be attained, the performance may vary wildly.

As far I understand, it seems that writing efficient numerical code in Common Lisp is possible but more challenging than it has to be.

This was thirty years ago. How should I regard these statement today if I am willing to write Common Lisp programs for one of the common free software implementations (CLISP, SBCL et al.)?

答:
When this paper was written in 1984, a computer having 1 megabyte of RAM and a 20 megabyte hard drive, capable of sitting on your desk, was a big deal.  Naturally, disputes will arise over the practicality of a language as high-level as Lisp is on hardware that spartan.  The advances in both hardware and compiler technology that have taken place since then have made Lisp programs much easier to write and execute, regardless of any numerical inefficiencies that might be present in the language.

Programmers often trade computational efficiency for programming efficiency.  Lisp can be a slow language (in some implementations, but so can other languages), but it also has a well-deserved reputation for rapid development, and many programs do not require a highly-optimized infrastructure to exhibit adequate performance.

The choice of Lisp implementation can greatly affect the performance profile of your programs.  For example, CLISP readily admits that "If your code is heavily numeric, you might prefer CMUCL."  Several modern Lisp (and Scheme) implementations allow you to specify numeric type hints, which will increase numerical performance.

In short, the situation is much better today than it was then.


问:
How to minimize merge conflicts when using non-lock VCS like git?
I have been using git for about four months now.  While I like most of its features, I find it rather inconvenient that multiple developers can make concurrent changes to the same file and then a need for merging ensues.  In fact, I would prefer waiting for a file to get unlocked over tedious and brain hurting merges.

I was wondering if there was a team etiquette or workflow to circumvent this terrible predicament.  In my ideal world of development, there would never be a need to merge.  E.g. is there a combination of hooks, commands, and workflows for git in order to have a remote repository notified when a local repository changes a file so that other developers get a git notification if they themselves try to modify the same file concurrently (e.g. when they run git status or something like that)?

答:
Git really is designed to improve the merge process not remove it.  If you find that merging is overly painful then I would suggest that you want to refine your process.

I would also take a look at this question ...

https://stackoverflow.com/questions/13662255/is-there-a-way-to-lock-individual-files-or-directories-on-fork-when-using-github

ContentLicense: CC BY-SA 3.0


答:
In an ideal world, merge conflicts never happen. There are certain scenarios where merge conflicts are more common... So my advice to you would be avoid these scenarios. And here they are.

Tightly coupled concerns

Let's say you have a front-end engineer and a back-end engineer. And you run into conflicts. This is usually because your code is not architected such that the two parts can evolve without interrupting each other, like mixing database access with templating. You get around this by introducing just enough abstraction to add distance between the two concerns.

API changes and concurrent feature development

Let's say I'm adding a small feature to my product, and it is orthogonal to the innards. It will be a point release. Meanwhile, the lead architect is refactoring the guts of the product to bring it from 1.0 to 2.0. I'm expecting 1.0 to 1.1 for the release of my feature.

Here, the architect will be touching a lot of surface area. And if you don't have another layer of abstraction between your feature and the raw API, you will run into a very messy conflict.

Sometimes in large organizations this cannot be helped.

Overly aggressive refactoring

This is actually the same as API changes. Even though there are no functional changes, there lots of textual changes, and from Git's perspective, that is the same.

Remedies

Keep changes physically small. Small diffs, small amount of lines changed

Release to master frequently

Integrate master frequently

Communicate about disruptive changes (like API changes/large refactors)

Separate business concerns across "physical" boundaries (modules/files/repos)

Title: How to minimize merge conflicts when using non-lock VCS like git?

Body:
I have been using git for about four months now.  While I like most of its features, I find it rather inconvenient that multiple developers can make concurrent changes to the same file and then a need for merging ensues.  In fact, I would prefer waiting for a file to get unlocked over tedious and brain hurting merges.

I was wondering if there was a team etiquette or workflow to circumvent this terrible predicament.  In my ideal world of development, there would never be a need to merge.  E.g. is there a combination of hooks, commands, and workflows for git in order to have a remote repository notified when a local repository changes a file so that other developers get a git notification if they themselves try to modify the same file concurrently (e.g. when they run git status or something like that)?


答:
If you need that kind of functionality, then git is not for you.  It is fundamentally designed to allow independent, disconnected working.  Choose another VCS that fits your needs.

As far as minimizing merge conflicts, this can be done by communication about what you're working on, as well as good code architecture.  If you follow good design principles, you can minimize how widespread any changes are, which minimizes the chance of a conflict, although you can't eliminate conflicts altogether.

Also, I don't know if you've ever worked on a large team that used a locking VCS.  There's a reason hardly anyone uses them anymore, except for binary file formats.  You say you'd be fine waiting for a file to be unlocked, but most people don't feel that way.  What ends up happening is people make changes locally anyway, while they're waiting, and merge them in manually outside of version control once the file gets unlocked.  That's a very error prone system, and it's very difficult to get people to not do it.

In other words, merges happen whether you let your VCS help you with them or not.  Best to accept it and use a VCS that makes it easy.


问:
Is application written from scratch in programming language has to be license?
There are so many programming language like PHP, Perl, Python, Java, C, C++ and many other. These programming language has some open source license.
If i develop application from scratch which is not related the source modification of these languages. Is my application has to be open source license??
There are billions of applications written in these language? All application has be open source? I don't understand that, is there language issue ever existed? I think there should not programming language  licensing issue just like spoken language..either i speak in english, french or any other. I can write a book in any language without my book to be open source, is that right???</p>

答:
Of course this depends on the laws in your country. Generally speaking though, you own your sourcecode. However a license on a programming language can make your sourcecode useless on its own. (at least if some part of the programming language is patented and you live in a part of the world with software patents).

However more realistic is that some standard library or the compiler is protected. For example if you write a C-program and link that to glibc and we assume that glibc is under GPL, your program has to be GPL compatible if your release it (note that glibc is under LGPL and not GPL so this doesn't apply).

Generally the licenses of standard libraries and compilers does not force your application to be open source.

What I know, none of the languages your mentioned has any license at all, their compilers do, and a few of them has plenty of compilers...


问:
Comparing strings against a pool of words
I am creating an app where the user enters 8 characters. After he enters the string I have to see if it is an eight letter word. If not, check if contains a seven letter word etc.

I am checking against a given pool of 150k+ words. I only care about the longest possible match. Is there a better way then this one:

WordPool.Contains(word.substring(0,8))

WordPool.Contains(word.substring(0,7)),
 WordPool.Contains(word.substirng(1,7))

WordPool.Contains(word.substring(0,6)),
 WordPool.Contains(word.substirng(1,6)),
 WordPool.Contains(word.substirng(2,6))

etc...

Edit

I forgot to add that I am checking against an english dictionary.

So far I am using this:

```<code>for(i = 8; i >= 3; i--)
  for(j = 0; j <= 8 - i; j++)
      if(words.contains(word.substring(j, i))
         //do something
</code>```

Edit 2
I have been using the approach defined above just with a minor change. I am using a few background agents which all search for a word of a certain length. They all then return a result and I just pick the one which gives the user the highest score.

答:
Preprocessing your word pool into a trie would make the longest search easy.  Just traverse the trie until you can't go any further.  You'd still have to try it for each starting position, though.  For example:

```<code>wordPool.longestMatch("deadbeef");
wordPool.longestMatch("eadbeef");
wordPool.longestMatch("adbeef");
wordPool.longestMatch("dbeef");
wordPool.longestMatch("beef");
wordPool.longestMatch("eef");
wordPool.longestMatch("ef");
wordPool.longestMatch("f");
</code>```

You could also short-circuit if you already found a match longer than the length of the remaining subsequences. The example would find "dead" on the first line, and "beef" on the fifth line, so you could automatically skip the last three subsequences.

Body:
Preprocessing your word pool into a trie would make the longest search easy.  Just traverse the trie until you can't go any further.  You'd still have to try it for each starting position, though.  For example:

wordPool.longestMatch("deadbeef");
wordPool.longestMatch("eadbeef");
wordPool.longestMatch("adbeef");
wordPool.longestMatch("dbeef");
wordPool.longestMatch("beef");
wordPool.longestMatch("eef");
wordPool.longestMatch("ef");
wordPool.longestMatch("f");

You could also short-circuit if you already found a match longer than the length of the remaining subsequences. The example would find "dead" on the first line, and "beef" on the fifth line, so you could automatically skip the last three subsequences.


问:
Is it possible to be good at both programming and graphic design?
The stereotypical view of a programmer can't do graphics very well, from what I've read and seen. However, I love programming (preferably OOP, PHP, C++, Objective-C) and can't deny the fact I have a unique taste in web design and others have said I am doing well at it (CSS). I thought to myself "Hey, wait, I'm a programmer - how can I design well?". Question is: is it possible to be good at programming and designing? Does anyone here feel the same?

For the record: actual images I have created have been called programmer art several times before by friends

答: An individual can excel at both, but typically you can get more production out of one programmer and one graphic designer than one person doing both (Assuming the two are talented enough). On the other hand, it may be easier to get one person to understand what the client really wants. </p>

ContentLicense: CC BY-SA 2.5


问:
Do you track progress during a agile sprint (iteration)
We have recently adopted (or are trying) to adopt managing our projects in an Agile manner.  During our first sprint I asked our Scrum master (who also happens to be our primary resident Agile go-to person) if it was possible to see the progress of our sprint so we could identify if we were on schedule or not (an possible risk).  They turned around and said you don't do that at a sprint level?

I'm really new to agile but I thought it would be very beneficial to know if a sprint is on target or not.  However perhaps this is too hard to do at this stage?  If so, are there any suggestions/methods on how you could identify if a sprint is at risk?

答: It's more of a Kanban thing, but I've seen Scrum shops that keep a board with story cards that are moved from "Backlog" to "This Sprint" to "In Progress" to "Done." Sometimes the cards display point values. You could look at the relative number of points in those latter three columns to get a sense of how much is getting done so far.</p>


答:
Yes, we track progress and most likely it will be monitored by the project managers.

Tracking can be done either at the story level or possibly at the task level, although I would recommend the story level first.  If a story is behind then possibly look at status of the tasks.  (Go and talk to the developer)

A typical story flow would be defined, in progress, completed, accepted, and potentially sign off.  Depends on your work flow.   Flows can be visualized by a Kanban board.

I didn't include the back log as those stories would be planned or defined for future sprints, so although we are keeping track of the back log, its not necessary for sprint tracking.

As at @catfood stated, a Kanban board is very useful here for tracking purposes so anyone can walk into your co-location and instantly see how the sprint is doing.  If stories are falling behind and their is risk of hangover, the board will show it.

The Kanban board is not a substitute for daily stand ups which should alert the team to potential issues and blockages that could potentially cause stories to be hung over.

Title: Do you track progress during a agile sprint (iteration)

Body:
We have recently adopted (or are trying) to adopt managing our projects in an Agile manner.  During our first sprint I asked our Scrum master (who also happens to be our primary resident Agile go-to person) if it was possible to see the progress of our sprint so we could identify if we were on schedule or not (an possible risk).  They turned around and said you don't do that at a sprint level?

I'm really new to agile but I thought it would be very beneficial to know if a sprint is on target or not.  However perhaps this is too hard to do at this stage?  If so, are there any suggestions/methods on how you could identify if a sprint is at risk?


答:
The team will be achieve some story points in one sprint. These story points approximately define how many backlog item team can succesfully done in one sprint. I think the best way is aggregate these story points from many sprint results. So, if the team has knew your maximum story points, there is not support take more story points(task) in one sprint.

For checking team in during sprint there are exist many SCRUM tool. We are using versionone, but I think simple taskboard is enough for start team.

There are exist many charts to show how it's formed your or team work. For example the Release Burndown Chart chart show the sprints and story points.


问:
How to calculate the worst-case runtime of this search-algorithm
I've written a special indexOf function for a list of unsorted unique values.

I can search for one or multiple (unsorted) values, passed as array/list, and the function will return me an array/list of indices (possibly empty).

Based on the following circumstances:

I know that the values i'm searching for are in the list

I don't care about the order in which the indices are returned

Uniqueness

I'm doing the following:

Walk through the list (of size n)

Compare the values with all values in the search-list

If there's a match break, add to results, break out of the loop and remove the found value from the search-list (so it's smaller on the next item)

If there are no more values left to search for, break out of the list-traversal.

I'd like to know how to analyse this algorithm, and specifically what the worst-case runtime is. (I guess if I'm searching for all values contained in the list.)

Source in JavaScript:

```<code>function multipleIndexOf(search, arr) {

    var searchArr = search.slice(0);
    var result = [];

    /* loop through array */
    for (var i = 0, l = arr.length; i < l; i++) {

        /* loop through search values */
        for (var i2 = 0, l2 = searchArr.length; i2 < l2; i2++) {

            /* if a search value matches... */
            if (arr[i] == searchArr[i2]) {
                /* add to result */
                result.push(i);

                /* remove from array */
                searchArr.splice(i2, 1);

                /* continue search with next */
                break;
            }
        }

        if (searchArr.length == 0) {
            break;
        }
    }

    return result;
}
</code>```

答: You're going through each item in one collection for each item in another, that's O(N * M) where n and m are the sizes of each collection.  The short circuiting doesn't affect the big O representation, as it is measuring the worst case, in which you never exit early.  And even in the average case, the short circuiting cuts the time in half.  O(N * M / 2) is equivalent to O(N * M).</p>


问:
Definition of a type
Conceptually, I used to think of types as sets. However, I think I've seen people wishing to distinguish types A, B even if they represent identical collections of values. So I figured a better definition of type is a pair (type_name, set), where two different types cannot have the same first element.

Then I ran into a different situation. I thought a function is just a set of pairs (x, y). But then a function A->B (where A, B represent the same collections of values) cannot be distinguished from a function B->B or A->A or B->A, and again I think I've seen people want to distinguish them. So how do I define a function? As a tuple (A, B, (x1, y1), (x2, y2), ...), where each element of A appears exactly once as the first element in the pairs, and where each second element is of type B?

And the type F that represents all functions that takes A->B is then (F, ((A, B, (a1, b11), (a2, b12), ...), (A, B, (a1, b21), (a2, b22), ...), (A, B, (a1, b31), (a2, b32), ...))), where a1, ... are all the values represented by A, and b?1, b?2, ..., for any ?, are some of the values represented by B.

This all seems rather cumbersome, am I missing something?

答:
I think your real struggle here is one with decidability, which is totally understandable in this context so let's talk about that for a moment.

Your first mention of a type system is quite simple, essentially you have a set and everything in that set represents it's type. Now what type each one of these elements in is unfortunately undecidable because they're just free standing values at this point. This kind of hampers the whole purpose of a type system and is really more indicative of an untyped system. This is similar to the untyped lambda calculus where there are sets but no identifier tied together with values to delineate their enclosing set.

So you realized this undecidability, and decided a solution that makes sense: tie the value to an alias that identifies it's enclosing set as it's "type" so you have every value as a tuple (type, value). This is very similar to the lambda-mu calculus which is effectively an extension to the aforementioned untyped lambda calculus above (or it might be closer to simply typed lambda calculus correct me if I got these mixed up). However ah; there's a catch there, again which type is tied to an input and output set for a function is undecidable in some situations.

So another refinement you decide, alright I'll dictate the input and output types and possible elements at in my function! Aha! Now we've made the determination of types quite decidable! Though it feels like a lot of cruft, and we now require recursive type definitions on all abstracting types to continue building pieces of pieces here, this feels a little messy and burdensome no? Well, yes, it is. Unfortunately this is just how that works, and now you have entered Dependant Typing.

The burdensomeness speaks to one of the reasons implementations of this type system are so rare. However there's another catch to this type system and it's a doozy: As yet it's unknown how to make a truly totality checked (this is the checking you get to do when you make your type system decidable which is what you seem to be after) type system which can be turing complete. The problem is that when you make it totality checked, all possible inputs and outputs are guaranteed by the compiler which means we now have decidability of the programs termination, thus no halting problem which is necessary for turing completeness.

Many non-turing complete languages are still very useful so this is not a necessity, and these types of languages are often used for proof assistants where the code dictates a bunch of input and output possibilities and the compilation itself basically says "Yes, this is a valid logical system." thus proving whatever the code declared.

Title: Definition of a type


问:
How to estimate cost with very little information?
I have a client who wants a web app that will let him do the following (as he told me word for word):

User registration

Recurring payments for users

Online conference room reservation

I am supposed to give him a cost estimate very fast and I don't have any time to do any deeper requirements analysis! How would you deal with that kind of situation? Should I just give a very broad estimate and work out the exact requirements once he has accepted the estimate? At which point do you usually gather requirements, after or before getting a contract?

答:
You're saying the client refuses to give you enough time for deeper requirements analysis. That by itself is a red flag. Maybe they've already gotten an estimate from someone else and don't like it, and think if they can just trick you into accepting this for a lowball price, they'll be able to force you to deliver.

There's three ways I've seen to deal with this:

Do a gut estimate anyway, without deeper analysis

Automatically estimating it as 150 man days, and pointing the client to solution 3 if that shocks them.

Selling the client on an analysis project

I cannot recommend solution 1. The risk that you end up committed to an impossible estimate is too big.

Solution 2 is still risky. 150 man days is big enough that if they bite usually afterwards you can define a scope that fits inside that estimate. But, depending on what your client means by conference room reservation, this could still not be enough.

Specifically on that topic, how well do you know the problem space? Have you thought about all of the aspects involved?

Will the system have to integrate with outlook?

Will it have to support catering and equipment (e.g. beamers)?

Will it have to support tracking participants, with reception desk integration?

Will it have to support automatic billing of booked rooms and related catering? What sort of pricing models will it have to allow for?

Will you have to track room keys, with check-out / check-in?

Will everyone be able to book anything, or do you need room-level security?

...

I've just spent a year redesigning the front-end of a mature conference room reservation system, and the design specs ended up filling several hundred pages. Do not underestimate the complexity of a competitive conference room reservation system.

Of course, you can keep it simple. But if your client wants a system that's competitive with what's already out there, simple won't cut it. Unless this client agrees ahead of time on exactly what it is that you will build, it's pretty much guaranteed you'll end up in rough negotiation once the time comes to deliver and get paid.


答: The most common means of tracking a sprint is to use a Burn-down Chart.  Basically you total up all your estimated tasks that you've committed to for the sprint.  As you complete each task, you subtract the estimated points and plot the new point.  The goal is to have zero points left at the end of the sprint.


问:
Algorithm to calculate estimated future usage of a defined value
I am looking for the name of a computer algorithm. I'm fairly sure that one should exist which will help me, but I can't for the life of me figure out what to search for.

If you have implementations of the algorithm, that'd be awesome - but I'm really just researching this because I'd like to figure out how to build it myself.

Basically, I'm looking for an algorithm that can calculate future usage of some set of data based on my previous usage. For example, my electricity supplier knows how much power I've used for the previous 20 days of a 30 day month, so they can extrapolate that out and predict how quickly I will run out of money on my power account. I'd like to know if there's an algorithm out there that can tell me in how long I'm likely to run out.

What I'm looking for is something that given the following inputs:

A range (e.g. 30 days)

A period of time through that range (e.g. 4, never smaller than zero, never greater than the max of the range)

Some values for previous time periods - either the previous days, or the same days from previous months)

A total value for this range (e.g. 300)

Can give me a date range in which I'm likely to run out of the total value (300). What I'd like at the other end would be something simple - e.g. "Based on previous usage, you're going to run out in 2 days."

I've done the usual Google searches, but haven't come up with anything particular that even looks close - yet as far as I can see it's a reasonably common algorithm used all over the place.

答:
This is a case of Linear regression. The most commonly used approach is the Simple linear regression using the least squares method.

An implementation in java can be found at LinearRegression.java. See also this Weighted Linear Regression in Java question.


问:
Why do many languages not support named parameters?
I was just thinking how much easier it would be to read code if, when calling a function, you could write:

```<code>doFunction(param1=something, param2=somethingElse);
</code>```

I can't think of any drawbacks and it would make code a lot more readable. I know you could pass an array as the only argument and have the array keys as the parameter names, however that would still not be as readable.

Is there a disadvantage of this that I'm missing? If not, why do many languages not allow this?

答:
For the same reason that Hungarian Notation is no longer widely used; Intellisense (or its moral equivalent in non-Microsoft IDE's).  Most modern IDE's will tell you everything you need to know about a parameter by merely hovering over the parameter reference.

That said, a number of languages do support named parameters, including C# and Delphi.  In C#, it is optional, so you don't have to use it if you don't want to, and there are other ways to specifically declare members, like object initialization.

Named Parameters are mostly useful when you only want to specify a subset of optional parameters, and not all of them.  In C#, this is very useful because you no longer need a bunch of overloaded methods to provide the programmer with this flexibility.


问:
What are the data structures behind a spreadsheet?
I would like to understand how a spreadsheet (a group of named or otherwise identified cells containing values or formulas referencing other cells) is solved. I have tried looking at existing projects, but there was so much going on with the GUI, serialization, events, etc. that I couldn't find the spreadsheet.

At its simplest how does it work?

答:
As mentioned already, a spreadsheet is easily implemented as a DAG (directed acyclic graph) stored in a simple hash or dictionary.  Some simple code to play with is probably the easiest way to understand it:

A very simple Python version:  http://code.activestate.com/recipes/355045-spreadsheet/

This was explained and elaborated in this blog post: http://ralsina.me/weblog/posts/BB585.html

There's also a simple JavaScript version with a GUI here: http://jsfiddle.net/ondras/hYfN3/


问:
How to manage potentially outdated data from WikiMedia API
I am writing a web application that pulls small parts of articles from Wikipedia and presents them to users.

I do not wish to delete entries of the articles because I do not want to be sending a ridiculous amount of requests to the WikiMedia API, putting unnecessary load on them.

My question is, since Wikipedia is by nature, collaborative and dynamic, what would be the best way to serve reasonably updated content to users (the content does not have to reflect the current article 100%, but it shouldn't be too far behind) without constantly querying their servers?

I'm leaning towards storing the snippets of the articles in my database along with a timestamp  and whenever an user requests an article with a timestamp over x days, I would re-query the API and update the entry in my database.

The other problem with that is I am grabbing the articles via client-side Javascript, then calling an API on my server to store it. Updating an article would look like:

User queries article -> my server returns article -> client-side checking decides the timestamp is too old -> client-side re-queries WikiMedia and displays the content to the user -> client-side fires request to my server to store the data.

This seems like it could be done better, but I do not want to be querying WikiMedia directly from my server...

How could I make this better?

Architecture: SlimPHP framework, RethinkDB + PHP driver, jQuery/JS, HTML, CSS

答:
First thing that comes to mind is using proxy cache. Proxy should respect cache directive from the API; no programming required.

The other way to do it is implement some kind of cache yourself with your own preferred algorithm. Even if you go this way if the server load is high, you should put a proxy too as either as reverse proxy or just proxy or both.

Best way is to put a proxy and have a profile so you know where to optimise.


问:
Which specific practices could be called "software craftsmanship" rather than "software engineering"?
Although not a new idea there seems to have been a big increase in the interest in software craftsmanship over the last couple of years (notably the often recommended book Clean Code's full title is Clean Code: A Handbook of Agile Software Craftsmanship).

Personally I see software craftsmanship as good software engineering with an added interest in ensuring that the end result is a joy to work with (both as an end user and as someone maintaining that software) - and also that its focus is more at the coding level of things than the higher level process things.

To draw an analogy - there were lots of buildings constructed in the 50s and 60s in a very modern style which took very little account of the people who would be living in them or how those buildings would age over time. Many of those buildings rapidly developed into slums or have been demolished long before their expected lifespans. I'm sure most developers with a few years under their belts will have experienced similar codebases.

What are the specific things that a software craftsman might do that a software engineer (possibly a bad one) might not?

答:
I'd say the only difference between a professional and a craftsman is caring with a little bit of passion mixed in. There is no specific, observable practice that would classify one as a craftsman, but rather a collection of qualities:

A craftsman cares about the actual quality of his work, and not just the perceived quality.

A craftsman has an interest in his craft that goes beyond getting the job done, and naturally gravitates towards his craft.

A craftsman cares about his profession, aspiring to improve his skills and not only advance his career.

A craftsman spends some amount of time outside of his paid working hours (even if it's a small amount of time) doing something with his craft, be it discussing, learning, or even thinking about it.

A craftsman knows how little he actually knows, and is humbled by it.

A craftsman is willing to teach those who are willing to learn, guide those who seek guidance, and seek those things himself when he needs them.

A little bit of passion covers all of these without breaking a sweat.


答: Programming languages, or rather the compilers and interpreters that process programs written in those languages, almost never force a license on the programs you write with them.  So you can use a Free Software C compiler like gcc and compiler proprietary, closed-source programs. What you cannot do is incorporate Free Software or Open Source code in your closed-source program, and that may be harder than you expect.  For example, the output of gcc is usually linked against one of a few implementations of the C Standard Library, all of which are Free Software or Open Source.  And without some of that code, except in some very specific environments, your program cannot run.

Title: Is application written from scratch in programming language has to be license?

Body:
There are so many programming language like PHP, Perl, Python, Java, C, C++ and many other. These programming language has some open source license.
If i develop application from scratch which is not related the source modification of these languages. Is my application has to be open source license??
There are billions of applications written in these language? All application has be open source? I don't understand that, is there language issue ever existed? I think there should not programming language  licensing issue just like spoken language..either i speak in english, french or any other. I can write a book in any language without my book to be open source, is that right???</p>


答:
Bash certainly supports this style of programming, and both Perl and Ruby support passing name/value parameter lists (as would any language with native hash/map support).  Nothing stops you from choosing to define a struct/record or hash/map which attaches names to parameters.

For languages which include hash/map/keyvalue stores natively, you can get the functionality you want, simply by adopting the idiom to pass key/value hashes to your functions/methods.  Once you have tried it on a project, you will have better insight into whether you have gained anything, either from increased productivity derived from ease of use, or improved quality through reduced defects.

Note that experienced programmers have become comfortable with passing parameters by order/slot.  You may also find that this idiom is only valuable when you have more than a few arguments (say >5/6).  And since a large number of arguments is often indicative of (overly) complex methods, you may find that this idiom is only beneficial for the most complex of methods.

Title: Why do many languages not support named parameters?

Body:
I was just thinking how much easier it would be to read code if, when calling a function, you could write:

```<code>doFunction(param1=something, param2=somethingElse);
</code>```

I can't think of any drawbacks and it would make code a lot more readable. I know you could pass an array as the only argument and have the array keys as the parameter names, however that would still not be as readable.

Is there a disadvantage of this that I'm missing? If not, why do many languages not allow this?


答:
Specifying parameter names does not always make code more readable: as an example, would you prefer to read min(first=0, second=1) or min(0, 1)?

If you accept the previous paragraph's argument, then it is pretty obvious that specifying parameter names should not be mandatory. Why don't all languages make specifying parameter names a valid option?

I can think of at least two reasons:

In general, introducing a second syntax for an already-covered need (here, passing parameters) is something whose benefits must be balanced against the inherent cost of the introduced language complexity (both in language implementation and in the programmer's mind model of the language);

It makes changing parameter names an API breaking change, which may not conform to a developer's expectation that changing a parameter name is a trivial, non-breaking change;

Note that I do not know of any language that implements named parameters without also implementing optional parameters (which require named parameters) - so you should be wary of overestimating their readability benefits, which can be more consistently obtained with the definition of Fluent Interfaces.


答:
I think it's the same reason why c# is more popular than VB.net. While VB.NET is more "readable" eg you type "end if" instead of a closing bracket, it just ends up being more stuff that pads out the code and eventually makes it harder to understand.

It turns out that what makes code easier to understand is conciseness. The less the better. Function parameter names are normally pretty obvious anyway, and don't really go that far into helping you understand code.


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

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

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

Have you got any personal experience to share?

答:
The complexity of large project can be wildly exacerbated by external political pressures. One department may have a very clear, focused idea of what they want in the new system, but then associated departments jump in with dozens of requests along the lines of "Well, as long as you're doing that , why don't you do this little side task for us too?" You might start by saying "No, that's out of scope.", but then the political in-fighting among the deaprtments begins, and the budget for the project is threatened unless everybody gets their piece of the pie.

For years, our local police couldn't search for partial plates through the motor vehicle system, a feature that seems absurdly simple. I asked a friend what on earth was so hard about adding this feature, and they said that every time they proposed switching to a modern database, every other department in the state that had any interaction with the motor vehicle system wanted to get their portion of the system fixed too. The result was complete gird-lock in IT modernization. Finally the state put together enough capital to do a system wide modernization effort, which then floundered because it was so hideously complex.


问:
Theoretical basis for (Linux) kernel development
KernelDevViewpoint (an apparently serious source) makes kernel development look like an accessible art. According to them:

Contrary to popular belief, kernel developers rarely need to know math
at the calculus level.  You need to be good at basic arithmetic and
you must know Boolean algebra to work on device drivers.

One skill that many kernel developers learn on the job is the ability
to build state machines in your head of what the code is doing. (...)

and

Technical skills for kernel developers include experience with the C
programming language, and knowledge of Git.

Is that the basis of kernel development? Basic arithmetic, Boolean algebra, C and Git?

Obviously, I don't expect to read "C in ten days" (or whatever similar book) and start contributing to the Linux kernel development, however, I wonder how difficult will be to obtain the skills to do that?

答:
Is that the basis of kernel development? Basic arithmetic, Boolean
  algebra, C and Git?

I have never contributed to a kernel project, but unless you are working on certain parts like threading locks, security, etc. you don't need advanced math. You defiantly need to know how to work with others, communicate effectively, and use a version control system with a public repository, e.g. Git. You will have to learn the ethos of the group and expect to receive constructive criticism. Unit testing is big on the projects I do and it is the unit test and documentation that take most of the time.

On many projects don't expect to have the ability to commit updates to the project without passing through one or more layers of reviews. You must earn trust by proving your skills. On large projects don't expect to master all of the code, you will most likely become good at one section that you work on and over time learn other parts. You will see lots of different styles and skill levels unless they have a good set of standards to follow.

As you can see there are lots of checks and balances in good projects and it is more than just coding. If you think you can make a contribution make a change and submit the update. Expect it to get rejected at first then heed the comments, make the changes and soon you may become part of the team. It will take a lot of your time.


答:
Even though the source is respectable. I'd say it's a gross generalisation to say you only need Basic arithmetic, Boolean algebra, C and Git. When you see the code, almost everything has been reduced to plain and simple C code. But the code implements something that's far more complex than, say basic arithmetic. Some examples:

floating point emulation. Linux started on i386 which didn't have fpu. Someone wrote an emulation for fpu which includes geometry.

Algorithm analysis. At some point, someone proposed an AVL tree memory allocator. Why would anyone do that? Because to balance the tree it takes O(1) on average and O(log n) on maximum. Takes more than basic math to figure it out.

Not on linux. See http://www.ertos.nicta.com.au/research/l4.verified/ to see how formal methods is used in developing a kernel.

Title: Theoretical basis for (Linux) kernel development

Body:
KernelDevViewpoint (an apparently serious source) makes kernel development look like an accessible art. According to them:

Contrary to popular belief, kernel developers rarely need to know math
at the calculus level.  You need to be good at basic arithmetic and
you must know Boolean algebra to work on device drivers.

One skill that many kernel developers learn on the job is the ability
to build state machines in your head of what the code is doing. (...)

and

Technical skills for kernel developers include experience with the C
programming language, and knowledge of Git.

Is that the basis of kernel development? Basic arithmetic, Boolean algebra, C and Git?

Obviously, I don't expect to read "C in ten days" (or whatever similar book) and start contributing to the Linux kernel development, however, I wonder how difficult will be to obtain the skills to do that?


问:
Refactoring from Python to Ruby with a BSD v3 license?
There is a project that is written in python which works great and is under the BSDv3 license. I wanted to use it as a base template for a ruby project instead of starting from scratch. I'd be refactoring (converting) the code from python to ruby, as if the author wrote a ruby gem along with his python library.

My question is what proper credit should be given to the python lib author?

Just mention that the gem is based off the python lib or more extensive?

答:
The rewriting of software is a grey area that isn't fully tested in the courts.  Not that this particular issue would go to court, but thats where the answers would come from.  Thus, everything that I say here is as a non-lawyer commenting on legal things and should be taken with enough salt to make your doctor say nasty things about your blood pressure.

From Licensing a rewrite from GPL to MIT which discusses changing a license from a more restrictive one to a less restrictive one, one answer said:

Actually, last year our company IP lawyer talked with us about matters like this.

She said that copyright for software is rather dumb, or straight-forward, or what you prefer to call it. It only protects the actual text in the source code, just like if it was a book. If no lines of code are equal (should be true for a Perl->Ruby rewrite?), it's not the same work from a copyright view.

Ideas expressed by the code, e.g. algorithms, may be protected by patents. But that is another story altogether.

I don't think the courts are that straight forward (I know in art that the painting of a photograph is a derivative work of the photograph).  Thus, my take on it would be that this remains a derivative work of the original.

But, it sounds like you're not trying to change the license on it.  And the BSD is a not restrictive license.  Well, there are some restrictions, but its fairly permissive.

The simplest and most straight forward and least problematic thing to do is including the copyright notice of the original code in there, and then add that the conversion from Python to Ruby is copyright you, using the same license.

My (non-lawyer take) on this is that the copyright on the ruby files is wholly owned my you.  You don't need to put the original copyright on it.  However, the project is a derivative work and thus put the original copyright in the project read me and any files that move as is from the python to the ruby (configuration files or the like that are copyrightable).

Of course, all of this does not constitute legal advice and if you're really picky, contact a lawyer about the licensing.  Alternatively, contact the original author find out how they should be credited in your project and follow that answer.  But I think you should be safe if you include the copyright of the project in your project.


答:
Excellent answer from Mark Canlas. This is how we plan our the same strategy in our environment:

Commit often, and push often

One of the strategy that we use in our office is to commit often, and push often. If I commit and push to server often, the guy who make large changes will have to perform the merge, not me. This effectively encourage members of the team to keep their changes simple to that merges are not too complicated.

Have CI server to verify changes

We also have CI server to verify commits, which also run unit tests in additional to building the solution, so whoever breaks the build will have to fix it. The worst time to break the build is before leaving office, as our policy is to not leave the build broken through the night. The risk of having a broken build Friday afternoon is enough for developers to try to keep their changes small.

Have CI server send out emails on broken build

Our CI server sends out notification email when a build breaks, or when a broken build has been fixed. This email is sent to owner of the commit, as well as administrator of the project. Our broken builds were fixed quickly thanks to this.


问:
Practical Meta Programming System (MPS)
This is in regards to Meta Programming System or MPS by JetBrains. Thus far, from my efforts to learn how to use MPS, I have only learned its basic purpose and that it is very complex.

Is MPS worth learning?

Is there anyone who already effectively uses MPS to create their own languages and editors for those languages and uses these created editors as their primary way of programming? If so, what types of programs have they made with this?

What are the advantages and disadvantages of working with MPS?

答:
While not on Java, I've been wanting to make my own meta-programming for a while on .NET (Irony(link 1) is a cool thing to look at), I think of using the M modelling language(link 2) once I learn it too.

I'd post this as a comment, but thanks to this rant I can't, so I'll try and throw a 2¢ while I'm at it).

If you think about it, a language is a tool to tell the computer what to do. Some languages are more specific than others, and let you express what you want in a much more concise way than others (for a particular subject). Others try to be broad and provide a consistent baseline from where to build upon.

But these restricted, specific, and simplistic "Domain Specific Languages(link 3)" are great for the occasional cases where what you want is specific. In those cases, they save you a lot of typing and possible mistakes.

For instance, think about how much time you'd waste if you had to use an Object-Oriented "SQL API" for Java (and how verbose that would be) instead of using SQL queries that are so short and convey the message so clearly.

I'd love if more domain-specific languages were in use. I don't like XAML much (altough it is better than how UIs are coded in Winforms), but I see it as a step in the good direction. I'd like to, in a middle-term future, design DSLs for certain common tasks I do frequently, such as a simplified HTML annotation language that outputs hacked-for-IE code without me having to do the same things over and over (or maybe I don't do this, but that's not the point).

tl;dr:

I never used MPS, but I think if you're a Java guy by all means check it out, Java gets brains rusted after a while IMHO. How to learn it? Find something you'd like a language for (something repetitive and boring), and make a language for it! If it's useless, at least you'll have a new tool on the belt.

LINKS

(here due to rep)

http://irony.codeplex.com/

http://en.wikipedia.org/wiki/Oslo_(Microsoft_project)#Characteristics_of_the_.22M.22_Modeling_Language

http://en.wikipedia.org/wiki/Domain-specific_language

Title: Practical Meta Programming System (MPS)


问:
How many strings are created in memory when concatenating strings in Java?
I was asked about immutable strings in Java. I was tasked with writing a function that concatenated a number of "a"s to a string.

What I wrote:

```<code>public String foo(int n) {
    String s = "";
    for (int i = 0; i < n; i++) {
        s = s + "a"
    }
    return s;
}
</code>```

I was then asked how many strings this program would generate, assuming garbage collection does not happen.
My thoughts for n=3 was

""

"a"

"a"

"aa"

"a"

"aaa"

"a"

Essentially 2 strings are created in each iteration of the loop. However, the answer was n2. What strings will be created in memory by this function and why is that way?

答:
On each iteration, a new String is created by the + operator and assigned to s. After return, all of them but the last are garbage-collected.

String constants like "" and "a" are not created every time, these are interned strings. Since strings are immutable, they can freely be shared; this happens to string constants.

To efficiently concatenate strings, use StringBuilder.


答:
Because someone has to, I'll approach this from a more mathematical perspective. Types do indeed resemble sets, but it's more pleasant to think of them "nominally" rather than "structurally".

This essentially means that a : Foo /= a : Bar.

Now with this in mind, we can think of types as sets, but this is rather difficult to talk about since sets are often viewed structurally. Things get interesting when we consider these as objects of a category. Then total functions between types (a function that is never undefined) form arrows in this category. I'll refer to this category as STLC.

The set of specialized identity functions (id :: Foo -> Foo...) forms the identity arrow and function composition f . g == f (g x) forms composition. Now that we have a category, it's pleasant to think of other category theoretic concepts, the two interesting ones are products and exponentials.

For products we consider 3 operations

```<code>cross  : A -> B -> A X B
first  : A X B  -> A
second : A X B  -> B
</code>```

So we notice that tuples form products in STLC.

Next consider exponentials. These form the interesting backbone of higher order functions. We want 2 functions for some arrow f : A X B -> C

```<code>curry(f) : A X B   -> C^B
eval(f)  : C^B X B -> C
</code>```

This formalizes the notion behind higher order functions, they are the exponentials of STLC. So a function

```<code>f : A -> (B -> C)
</code>```

Is really an arrow from A to the exponential C^B.

There is a unique arrow to every type from the falsy type. This is a type with no witnesses of any kind. In Haskell

```<code>data Falsy =
</code>```

Last but not least, consider a terminal object T. This is trivially formed by a type with exactly one witness. Traditionally this is called Unit, or True. In Haskell

```<code>data Unit = Unit
</code>```

With these, we can actually state what the representation of a value is, it is a "point" (an arrow from Unit -> A). In a sane type system, the category it forms is well-pointed. Or, there are exactly enough arrows from p : Unit -> A so that if for all p, f . p = g . p, then f = g.

The category I've outlined here describes the type systems of Haskell, ML, and most other mainstream languages.

So as a direct answer to your question. A type is an object of a closed cartesian category with the initial and terminal objects being curry-howard False and True respectively, function values forming expontentials as well as arrows and pairs forming products.

Title: Definition of a type

Body:
Conceptually, I used to think of types as sets. However, I think I've seen people wishing to distinguish types A, B even if they represent identical collections of values. So I figured a better definition of type is a pair (type_name, set), where two different types cannot have the same first element.

Then I ran into a different situation. I thought a function is just a set of pairs (x, y). But then a function A->B (where A, B represent the same collections of values) cannot be distinguished from a function B->B or A->A or B->A, and again I think I've seen people want to distinguish them. So how do I define a function? As a tuple (A, B, (x1, y1), (x2, y2), ...), where each element of A appears exactly once as the first element in the pairs, and where each second element is of type B?

And the type F that represents all functions that takes A->B is then (F, ((A, B, (a1, b11), (a2, b12), ...), (A, B, (a1, b21), (a2, b22), ...), (A, B, (a1, b31), (a2, b32), ...))), where a1, ... are all the values represented by A, and b?1, b?2, ..., for any ?, are some of the values represented by B.

This all seems rather cumbersome, am I missing something?

Body:
Because someone has to, I'll approach this from a more mathematical perspective. Types do indeed resemble sets, but it's more pleasant to think of them "nominally" rather than "structurally".

This essentially means that a : Foo /= a : Bar.

Now with this in mind, we can think of types as sets, but this is rather difficult to talk about since sets are often viewed structurally. Things get interesting when we consider these as objects of a category. Then total functions between types (a function that is never undefined) form arrows in this category. I'll refer to this category as STLC.

The set of specialized identity functions (id :: Foo -> Foo...) forms the identity arrow and function composition f . g == f (g x) forms composition. Now that we have a category, it's pleasant to think of other category theoretic concepts, the two interesting ones are products and exponentials.

For products we consider 3 operations

cross  : A -> B -> A X B
first  : A X B  -> A
second : A X B  -> B

So we notice that tuples form products in STLC.

Next consider exponentials. These form the interesting backbone of higher order functions. We want 2 functions for some arrow f : A X B -> C

curry(f) : A X B   -> C^B
eval(f)  : C^B X B -> C

This formalizes the notion behind higher order functions, they are the exponentials of STLC. So a function

f : A -> (B -> C)

Is really an arrow from A to the exponential C^B.

There is a unique arrow to every type from the falsy type. This is a type with no witnesses of any kind. In Haskell

data Falsy =

Last but not least, consider a terminal object T. This is trivially formed by a type with exactly one witness. Traditionally this is called Unit, or True. In Haskell

data Unit = Unit

With these, we can actually state what the representation of a value is, it is a "point" (an arrow from Unit -> A). In a sane type system, the category it forms is well-pointed. Or, there are exactly enough arrows from p : Unit -> A so that if for all p, f . p = g . p, then f = g.

The category I've outlined here describes the type systems of Haskell, ML, and most other mainstream languages.

So as a direct answer to your question. A type is an object of a closed cartesian category with the initial and terminal objects being curry-howard False and True respectively, function values forming expontentials as well as arrows and pairs forming products.


答:
I was then asked how many strings this program would generate, assuming garbage collection does not happen. My thoughts for n=3 was (7)

Strings 1 ("") and 2 ("a") are the constants in the program, these are not created as part of things but are 'interned' because they are constants the compiler knows about.  Read more about this at String interning on Wikipedia.

This also removes strings 5 and 7 from the count as they are the same "a" as String #2.  This leaves strings #3, #4, and #6.  The answer is "3 strings are created for n = 3" using your code.

The count of n2 is obviously wrong because at n=3, this would be 9 and even by your worst case answer, that was only 7.  If your non-interned strings was correct, the answer should have been 2n + 1.

So, the question of how should you do this?

Since the String is immutable, you want a mutable thing - something you can change without creating new objects.  That is the StringBuilder.

The first thing to look at is the constructors.  In this case we know how long the string will be, and there is a constructor StringBuilder(int capacity)
 which means we allocate exactly as much as we need.

Next, "a" doesn't need to be a String, but rather it can be a character 'a'.  This has some minor performance boosting when calling append(String) vs append(char) - with the append(String), the method needs to find out how long the String is and do some work on that.  On the other hand, char is always exactly one character long.

The code differences can be seen at StringBuilder.append(String) vs StringBuilder.append(char).  Its not something to be too concerned with, but if you're trying to impress the employer it is best to use the best possible practices.

So, how does this look when you put it together?

```<code>public String foo(int n) {
    StringBuilder sb = new StringBuilder(n);
    for (int i = 0; i < n; i++) {
        sb.append('a');
    }
    return sb.toString();
}
</code>```

One StringBuilder and one String have been created.  No extra strings needed to be interned.

Write some other simple programs in Eclipse.  Install pmd and run it on the code you write.  Note what it complains about and fix those things.  It would have found the modification of a String with + in a loop, and if you changed that to StringBuilder, it would have maybe found the initial capacity, but it would certainly catch the difference between .append("a") and .append('a')

Title: How many strings are created in memory when concatenating strings in Java?

Body:
I was asked about immutable strings in Java. I was tasked with writing a function that concatenated a number of "a"s to a string.

What I wrote:

```<code>public String foo(int n) {
    String s = "";
    for (int i = 0; i < n; i++) {
        s = s + "a"
    }
    return s;
}
</code>```

I was then asked how many strings this program would generate, assuming garbage collection does not happen.
My thoughts for n=3 was

""

"a"

"a"

"aa"

"a"

"aaa"

"a"

Essentially 2 strings are created in each iteration of the loop. However, the answer was n2. What strings will be created in memory by this function and why is that way?

Body:
I was then asked how many strings this program would generate, assuming garbage collection does not happen. My thoughts for n=3 was (7)

Strings 1 ("") and 2 ("a") are the constants in the program, these are not created as part of things but are 'interned' because they are constants the compiler knows about.  Read more about this at String interning on Wikipedia.

This also removes strings 5 and 7 from the count as they are the same "a" as String #2.  This leaves strings #3, #4, and #6.  The answer is "3 strings are created for n = 3" using your code.

The count of n2 is obviously wrong because at n=3, this would be 9 and even by your worst case answer, that was only 7.  If your non-interned strings was correct, the answer should have been 2n + 1.

So, the question of how should you do this?

Since the String is immutable, you want a mutable thing - something you can change without creating new objects.  That is the StringBuilder.

The first thing to look at is the constructors.  In this case we know how long the string will be, and there is a constructor StringBuilder(int capacity)
 which means we allocate exactly as much as we need.

Next, "a" doesn't need to be a String, but rather it can be a character 'a'.  This has some minor performance boosting when calling append(String) vs append(char) - with the append(String), the method needs to find out how long the String is and do some work on that.  On the other hand, char is always exactly one character long.

The code differences can be seen at StringBuilder.append(String) vs StringBuilder.append(char).  Its not something to be too concerned with, but if you're trying to impress the employer it is best to use the best possible practices.

So, how does this look when you put it together?

public String foo(int n) {
    StringBuilder sb = new StringBuilder(n);
    for (int i = 0; i < n; i++) {
        sb.append('a');
    }
    return sb.toString();
}

One StringBuilder and one String have been created.  No extra strings needed to be interned.

Write some other simple programs in Eclipse.  Install pmd and run it on the code you write.  Note what it complains about and fix those things.  It would have found the modification of a String with + in a loop, and if you changed that to StringBuilder, it would have maybe found the initial capacity, but it would certainly catch the difference between .append("a") and .append('a')


答:
Failure to ship to actual users

Big projects have a nasty tendency to get into "infrastructure" mode for years, and forget about building real end-user features and shipping them. By the time it ships, it's very expensive to change, and usually the biggest conceptual changes end up being asked after the first real beta testing occurs.

Failure to accurately estimate cost

If projects seem like they will outgrow their return on investment, they get canceled.

Failure to control quality

With enough defects it is possible for forward momentum to fall to zero, or below. Without any progress at all, it's hard to argue for the continued existence.

Title: Why do large IT projects tend to fail or have big cost/schedule overruns?

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

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

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

Have you got any personal experience to share?


问:
Why delete method/field/function refactoring doesn't exist in Eclipse?
An operation in an interface is obsolete so I decided to delete it.
It seems that there is no automatic support for such a "refactoring" in Eclipse.

For me is a refactoring operation since the behavior of the code will be preserved since nobody (tests, client apis) will notice that the operation was removed.

In Eclipse, in Java code, on an method in an interface I have the following options: rename, move, change method signature, inline, extract interface, extract superclass, use supertype when possible, pull up, push down, introduce parameter objet, introduce indirection, generate declared type.

Is there any reason for which a delete method/field/function refactoring doesn't exist?

答:
There are only two situations when removing a method from an interface: either the method is being used somewhere, or it's not. If the method is never used, then deleting it is trivial even without a refactoring tool.

If the method is used, then there would almost never be a way to automatically remove it in every place that it is used. Simply deleting it everywhere would surely break things. The best that an IDE could do would be to give you a list of everywhere the method is used and let you decide how to safely remove the method in each case. IDEs like Eclipse will do that for you.

In short, a refactoring tool for deleting methods would either be useless because it is trivial, or useless because it breaks things, depending on which method you use it on.


答:
The reason is, this feature is not yet implemented - see Bug 39715 Add Refactor/Remove interface method and all impls. [refactoring] in Eclipse issue tracker:

Here is something I am running into now. I am cleaning up a bunch of code that removes no longer needed methods from interfaces and all implementing classes. Right now, this is quite a tedious processes. It would be helpful to have a refactoring such that I could select an interface method and delete it along with all impl. methods in all classes...

Above request has been in turn marked a duplicate of Bug 24379 [refactoring] Change interface signature:

When adding or removing methods in interfaces it would nice to have the possibility to add or remove the method automatically in implementing classes. When adding methods it should also add a task with the note implement this method...

Bug 24379 seems to be laying dormant for more than 10 years now, "Reported: 2002-10-04" and "Target Milestone" field is not yet set.

Title: Why delete method/field/function refactoring doesn't exist in Eclipse?

Body:
An operation in an interface is obsolete so I decided to delete it.
It seems that there is no automatic support for such a "refactoring" in Eclipse.

For me is a refactoring operation since the behavior of the code will be preserved since nobody (tests, client apis) will notice that the operation was removed.

In Eclipse, in Java code, on an method in an interface I have the following options: rename, move, change method signature, inline, extract interface, extract superclass, use supertype when possible, pull up, push down, introduce parameter objet, introduce indirection, generate declared type.

Is there any reason for which a delete method/field/function refactoring doesn't exist?


问:
How can I deal with the cargo-cult programming attitude?
I have some computer science students in a compulsory introductory programming course who see a programming language as a set of magic spells, which must be cast in order to achieve some effect (instead of seeing it as a flexible medium for expressing their idea of solution).

They tend to copy-paste code from previous, similar-looking assignments without considering the essence of the problem.

Are there some exercises or analogies to make these students more confident that they can, and should, understand the structure and meaning of each piece of code they write?

答:
I wrote a blog piece about this, from the perspective of what we programmers who write tuts should be doing differently to help alleviate this issue among junior (I hope!) professional programmers, and in part blaming it on us. I think the way we create material for them is an essential part of this problem. Some suggestions I make:

Break your code into small, incomplete parts : This is really just a mechanical thing, and possibly a bit of a "controversial" suggestion. Don't post large bits of working code in your tutorial. Make them work to put it all together, hopefully while actually reading and understanding each part. This is not easy - there are already so many tutorials with broken code, I can see this being frustrating for a learner. But I really believe if they are at the level where they reading "How to make a login form" then they really need to work through every step on their own (and link to Stackoverflow with questions if they can't make it work)

Explain the problem before answering it: A common technique in tutorial writing is to post a block of code, then go over it line by line. I would argue that we should say what we need to add AND WHY, then add it, then repeat. So, "We will need to build a form, with a post method, an element to hold our username & password, and a button to submit", then write it out. Knowing what you are looking at BEFORE you see it is a far more effective teaching method.

Teach debugging, not coding: In a recent post on this site, I tried (hopefully with some success) a new technique - I posted a bunch of broken code, then taught how to figure out what was wrong with it. Far too many new programmers do not even understand setting var_dump(); this is the number one cause of most new programmer questions, IMHO.

Go deeper, not broader: Anthony Ferrara has started a brilliant series of programming videos at Programming with Anthony. The reason I like them so much is that they pick one specific subject and really explain it "deeply". Instead of trying to make a complete "Social Widget Scroller", he just explains arrays all the way down to the memory level. Instead of trying to cover vast subjects, pick something small and explain it thoroughly and patiently.

Teach how to report the bug: Not for our own convenience. We all know how often we've figured something out while writing out the issue on some forum. The reason is simple - when you have to explain something, you have to think about it. Don't teach them to "look it up on Google" - teach them to sit and think about it, or write out a letter to themselves about the problem.

Full text: http://codebyjeff.com/blog/2013/05/death-to-teaching-cargo-programming


问:
An algorithm for a synchronization
I want to make a synchronization. What's the algorithm for it in a nutshell?

1) A client reads a local data and sends them to a server afterwards. The server compares them with its actual data, decides what are newer and overwrites its data with received data in case received data is newer.

or

2) A client reads data from the server first, compares them with its local data and in case data from the server is newer, overrwrites them with the server data.

And does the order matter?

答:
You should look at how distributed change management works. Look at
  SVN, CVS and other repositories that manage deltas work.

You have several use cases.

Synchronize changes. Clients send their deltas to the server; server consolidates and distributes the deltas to the clients. This is
  the typical case. Databases call this "transaction replication".

Client has lost synchronization. In this case, the client needs to get the current state from the server without going through the
  deltas. This is a copy from master to detail, deltas and performance
  be damned.

Client is suspicious. In this case, you need to compare client against server to determine if the client is up-to-date and needs any
  deltas.

You should follow the database (and SVN) design pattern of
  sequentially numbering every change. That way a client can make a
  trivial request ("What revision should I have?") before attempting to
  synchronize. And even then, the query ("All deltas since 2149") is
  delightfully simple for the client and server to process.

Original Answer: https://stackoverflow.com/questions/413086/client-server-synchronization-pattern-algorithm/413136#413136

Title: An algorithm for a synchronization


问:
How to compare features of two curves?
I need to compare two curves f(x) and g(x). They are in the same x range (say -30 to 30). f(x) may have some sharp peaks or smooth peaks and valleys. g(x) may have the same peaks and valleys. If so I want a measure on how well these features coincide without visual inspection. I have tried to solve this problem in the following way.

Normalize both functions by dividing each data point by the total area of the function. Now the area of the normalized function is 1.0

At each x get the minimum value out of f(x) and g(x). This will give me a new function that is basically the overlapping area between f(x) and g(x).

When I integrate the resulting function of step 2 I get the total overlapping area out of 1.0

However this does not tell me whether the peaks and valleys coincide or not. I am not sure if this can be done but if someone knows a method I would appreciate your help.

==EDIT==
For clarification I have included an image.

The difference between the two curves (black and blue) may not be the same but
will have complementing shapes.

Background:
The functions are projected density of states (PDOS) of atomic orbitals of a compound. So I have states for s,p,d orbitals. I want to determine whether the material has s-p, p-d or d-d hybridizations (orbital mixing). The only data I have is the PDOS. If say the PDOS of s orbital (function f(x)) has the peaks and valleys as at the same energies (x values) of the PDOS of p orbital (function g(x)) then there is s-p mixing in that material.

答:
how well these features coincide without visual inspection.

Probably the most straightforward way is to calculate Pearson's correlation coefficient. That is, use your f(x) as X and g(x) as Y. Effectively "plot g(x) as function of f(x) and see how well it forms a straight line".

Correlation coefficient is popular because it's easy to calculate, and is often justified merely by waving hands. It may be a good initial approximation for some uses, but is definitely not a panacea.

To get better results in real-world applications, you need to understand what's going on in the data, i.e. the process that generates the data. Often there's some sort of background, and the interesting features ride on top of that background. If you throw the whole data into a black box, you may end up comparing mostly the backgrounds: the black box doesn't know which part of the data is the interesting part. So, to get better results, it's often a good idea to remove the backgrounds somehow, and then compare what you have left. Fitting lines or curves or averages and subtracting or dividing by them, low-, band- or highpass filtering, feeding the data through some nonlinear function... you name it.

There's definitely no single right answer. You'll get as many different results as you try methods. But, some of the results are better than some ofters. Theoretical reasoning may help getting started in the right direction, but how to set parameters and fine-tune your method, can ultimately be found only by trying them out and comparing the real-world results.

Title: How to compare features of two curves?


答: Pick a random amount, double it, then tell the customer that number, plus or minus 200%.  That should get the point across.</p>

Title: How to estimate cost with very little information?

Body:
I have a client who wants a web app that will let him do the following (as he told me word for word):

User registration

Recurring payments for users

Online conference room reservation

I am supposed to give him a cost estimate very fast and I don't have any time to do any deeper requirements analysis! How would you deal with that kind of situation? Should I just give a very broad estimate and work out the exact requirements once he has accepted the estimate? At which point do you usually gather requirements, after or before getting a contract?


答:
Named Parameters Make Code Easier To Read, Harder To Write

When I am reading a piece of code, named parameters can introduce context that makes the code easier to understand. Consider for example this constructor: Color(1, 102, 205, 170). What on earth does that mean? Indeed, Color(alpha: 1, red: 102, green: 205, blue: 170) would be far easier to read. But alas, the Compiler says “no” – it wants Color(a: 1, r: 102, g: 205, b: 170). When writing code using named parameters, you spend an unnecessary amount of time looking up the exact names – it is easier to forget the exact names of some parameters than it is to forget their order.

This once bit me when using a DateTime API that had two sibling classes for points and durations with almost identical interfaces. While DateTime->new(...) accepted an second => 30 argument, the DateTime::Duration->new(...) wanted seconds => 30, and similar for other units. Yes, it absolutely makes sense, but this showed me that named parameters ≠ ease of use.

Bad Names Don't Even Make It Easier To Read

Another example how named parameters can be bad is probably the R language. This piece of code creates a data plot:

```<code>plot(plotdata$n, plotdata$mu, type="p", pch=17,  lty=1, bty="n", ann=FALSE, axes=FALSE)
</code>```

You see two positional arguments for the x and y data rows, and then a list of named parameters. There are many more options with defaults, and only those are listed whose defaults I wanted to change or explicitly specify. Once we ignore that this code uses magic numbers, and could benefit from using enums (if R had any!), the issue is that many of these parameter names are rather indecipherable.

pch is actually the plot character, the glyph that will be drawn for every data point. 17 is an empty circle, or something like that.

lty is the line type. Here 1 is a solid line.

bty is the box type. Setting it to "n" avoids a box being drawn around the plot.

ann controls the appearance of axis annotations.

For someone who does not know what each abbreviation means, these options are rather confusing. This also reveals why R uses these labels: Not as self-documenting code, but (being a dynamically typed language) as keys to map the values to their correct variables.

Properties Of Parameters And Signatures

Function signatures may have the following properties:

Arguments can be ordered or unordered,

named or unnamed,

required or optional.

Signatures can also be overloaded by size or type,

and can have an unspecified size with varargs.

Different languages land at different coordinates of this system. In C, arguments are ordered, unnamed, always required, and can be varargs. In Java the situation is similar, except that signatures can be overloaded. In Objective C, signatures are ordered, named, required, and can't be overloaded because it's just syntactic sugar around C.

Dynamically typed languages with varargs (command line interfaces, Perl, …) can emulate optional named parameters. Languages with signature size overloading have something like positional optional parameters.

How Not To Implement Named Parameters

When thinking of named parameters, we usually assume named, optional, unordered parameters. Implementing these is difficult.

Optional parameters could have default values. These must be specified by the called function and should not be compiled into the calling code. Otherwise, the defaults can't be updated without recompiling all dependent code.

Now an important question is how the arguments are actually passed to the function. With ordered parameters, the args can be passed in a register, or in their inherent order on the stack. When we exclude the registers for a moment, the problem is how to put unordered optional arguments onto the stack.

For that, we need some order over the optional arguments. What if the declaration code is changed? As the order is irrelevant, a reordering in the function declaration should not change the position of the values on the stack. We should also consider if adding a new optional parameter is possible. From a users perspective this seems so, because code that didn't use that parameter previously should still work with the new parameter. So this excludes orderings like using the order in the declaration or using the alphabetic order.

Consider this also in the light of subtyping and the Liskov Substitution Principle – in the compiled output, the same instructions should be able to invoke the method on a subtype with possibly new named parameters, and on a supertype.

Possible Implementations

If we cannot have a definitive order, so we need some unordered data structure.

The simplest implementation is to simply pass the name of the parameters along with the values. This is how named params are emulated in Perl or with command line tools. This solves all extension problems mentioned above, but can be a huge waste of space – not an option in performance-critical code. Also, processing these named params is now much more complicated than simply popping values off a stack.

Actually, the space requirements can be reduced by using string pooling, which can reduce later string comparisons to pointer comparisons (except when it can't be guaranteed that static strings are actually pooled, in which case the two strings will have to be compared in detail).

Instead, we could also pass a clever data structure that works as a dictionary of named arguments. This is cheap on the caller side, because the set of keys is statically known at the call location. This would allow to create a perfect hash function or to precalculate a trie. The callee will still have to test for existence of all possible parameter names which is somewhat expensive. Something like this is used by Python.

So it's just too expensive in most cases

If a function with named parameters is to be properly extensible, a definitive ordering cannot be assumed. So there are only two solutions:

Make the order of the named params part of the signature, and disallow later changes. This is useful for self-documenting code, but does not help with optional arguments.

Pass a key-value data structure to the callee, which then has to extract useful information. This is very expensive in comparision, and usually only seen in scripting languages without an emphasis on performance.

Other Pitfalls

The variable names in a function declaration usually have some internal meaning and are not part of the interface – even if many documentation tools will still show them. In many cases you'd want different names for an internal variable and the corresponding named argument. Languages that don't allow choosing the externally visible names of a named parameter don't gain much of them if the variable name isn't used with the calling context in mind.

An issue with emulations of named arguments is the lack of static checking on the caller side. This is especially easy to forget when passing a dictionary of arguments (looking at you, Python). This is important because passing a dictionary is a common workaround, e.g. in JavaScript: foo({bar: "baz", qux: 42}). Here, neither the types of the values nor the existence or absence of certain names can be checked statically.

Emulating Named Parameters (In Statically Typed Languages)

Simply using strings as keys, and any object as a value is not very useful in the presence of a static type checker. However, named arguments can be emulated with structs, or object literals:

```<code>// Java

static abstract class Arguments {
  public String bar = "default";
  public int    qux = 0;
}

void foo(Arguments args) {
  ...
}

/* using an initializer block */
foo(new Arguments(){{ bar = "baz"; qux = 42; }});
</code>```

Body:
Named Parameters Make Code Easier To Read, Harder To Write

When I am reading a piece of code, named parameters can introduce context that makes the code easier to understand. Consider for example this constructor: Color(1, 102, 205, 170). What on earth does that mean? Indeed, Color(alpha: 1, red: 102, green: 205, blue: 170) would be far easier to read. But alas, the Compiler says “no” – it wants Color(a: 1, r: 102, g: 205, b: 170). When writing code using named parameters, you spend an unnecessary amount of time looking up the exact names – it is easier to forget the exact names of some parameters than it is to forget their order.

This once bit me when using a DateTime API that had two sibling classes for points and durations with almost identical interfaces. While DateTime->new(...) accepted an second => 30 argument, the DateTime::Duration->new(...) wanted seconds => 30, and similar for other units. Yes, it absolutely makes sense, but this showed me that named parameters ≠ ease of use.

Bad Names Don't Even Make It Easier To Read

Another example how named parameters can be bad is probably the R language. This piece of code creates a data plot:

plot(plotdata$n, plotdata$mu, type="p", pch=17,  lty=1, bty="n", ann=FALSE, axes=FALSE)

You see two positional arguments for the x and y data rows, and then a list of named parameters. There are many more options with defaults, and only those are listed whose defaults I wanted to change or explicitly specify. Once we ignore that this code uses magic numbers, and could benefit from using enums (if R had any!), the issue is that many of these parameter names are rather indecipherable.

pch is actually the plot character, the glyph that will be drawn for every data point. 17 is an empty circle, or something like that.

lty is the line type. Here 1 is a solid line.

bty is the box type. Setting it to "n" avoids a box being drawn around the plot.

ann controls the appearance of axis annotations.

For someone who does not know what each abbreviation means, these options are rather confusing. This also reveals why R uses these labels: Not as self-documenting code, but (being a dynamically typed language) as keys to map the values to their correct variables.

Properties Of Parameters And Signatures

Function signatures may have the following properties:

Arguments can be ordered or unordered,

named or unnamed,

required or optional.

Signatures can also be overloaded by size or type,

and can have an unspecified size with varargs.

Different languages land at different coordinates of this system. In C, arguments are ordered, unnamed, always required, and can be varargs. In Java the situation is similar, except that signatures can be overloaded. In Objective C, signatures are ordered, named, required, and can't be overloaded because it's just syntactic sugar around C.

Dynamically typed languages with varargs (command line interfaces, Perl, …) can emulate optional named parameters. Languages with signature size overloading have something like positional optional parameters.

How Not To Implement Named Parameters

When thinking of named parameters, we usually assume named, optional, unordered parameters. Implementing these is difficult.

Optional parameters could have default values. These must be specified by the called function and should not be compiled into the calling code. Otherwise, the defaults can't be updated without recompiling all dependent code.

Now an important question is how the arguments are actually passed to the function. With ordered parameters, the args can be passed in a register, or in their inherent order on the stack. When we exclude the registers for a moment, the problem is how to put unordered optional arguments onto the stack.

For that, we need some order over the optional arguments. What if the declaration code is changed? As the order is irrelevant, a reordering in the function declaration should not change the position of the values on the stack. We should also consider if adding a new optional parameter is possible. From a users perspective this seems so, because code that didn't use that parameter previously should still work with the new parameter. So this excludes orderings like using the order in the declaration or using the alphabetic order.

Consider this also in the light of subtyping and the Liskov Substitution Principle – in the compiled output, the same instructions should be able to invoke the method on a subtype with possibly new named parameters, and on a supertype.

Possible Implementations

If we cannot have a definitive order, so we need some unordered data structure.

The simplest implementation is to simply pass the name of the parameters along with the values. This is how named params are emulated in Perl or with command line tools. This solves all extension problems mentioned above, but can be a huge waste of space – not an option in performance-critical code. Also, processing these named params is now much more complicated than simply popping values off a stack.

Actually, the space requirements can be reduced by using string pooling, which can reduce later string comparisons to pointer comparisons (except when it can't be guaranteed that static strings are actually pooled, in which case the two strings will have to be compared in detail).

Instead, we could also pass a clever data structure that works as a dictionary of named arguments. This is cheap on the caller side, because the set of keys is statically known at the call location. This would allow to create a perfect hash function or to precalculate a trie. The callee will still have to test for existence of all possible parameter names which is somewhat expensive. Something like this is used by Python.

So it's just too expensive in most cases

If a function with named parameters is to be properly extensible, a definitive ordering cannot be assumed. So there are only two solutions:

Make the order of the named params part of the signature, and disallow later changes. This is useful for self-documenting code, but does not help with optional arguments.

Pass a key-value data structure to the callee, which then has to extract useful information. This is very expensive in comparision, and usually only seen in scripting languages without an emphasis on performance.

Other Pitfalls

The variable names in a function declaration usually have some internal meaning and are not part of the interface – even if many documentation tools will still show them. In many cases you'd want different names for an internal variable and the corresponding named argument. Languages that don't allow choosing the externally visible names of a named parameter don't gain much of them if the variable name isn't used with the calling context in mind.

An issue with emulations of named arguments is the lack of static checking on the caller side. This is especially easy to forget when passing a dictionary of arguments (looking at you, Python). This is important because passing a dictionary is a common workaround, e.g. in JavaScript: foo({bar: "baz", qux: 42}). Here, neither the types of the values nor the existence or absence of certain names can be checked statically.

Emulating Named Parameters (In Statically Typed Languages)

Simply using strings as keys, and any object as a value is not very useful in the presence of a static type checker. However, named arguments can be emulated with structs, or object literals:

// Java

static abstract class Arguments {
  public String bar = "default";
  public int    qux = 0;
}

void foo(Arguments args) {
  ...
}

/* using an initializer block */
foo(new Arguments(){{ bar = "baz"; qux = 42; }});


问:
Add behavior without changing existing class
I have a class Container, which represents wrapper around std::list.
This class contains following public methods:

void add(Shape *item)

void next()

void setBegin()

Shape* curr()

and protected variables

std::list <Shape*> _container

std::list <Shape*>::iterator _iter

Now I need add sorting of Container without changing existing class code.

Which pattern should I use? I think, that Decorator is most appropriate pattern in this case.
Should I redesign class Container?

答: Yes, Decorator is exactly what you are seeking. Actually, you Container class is already a decorator for std::list.</p>


答:
Basically, I'm looking for an algorithm that can calculate future usage of some set of data based on my previous usage.

First of all, there is no way to predict the future. The best thing you can do is to make a projection, i.e. to make a statement like

Given all the information at hand, for some specific question it is useful (or reasonable or fair) to assume that this unknown variable has value X.

That said, there is of course no generic answer to your question: you are basically asking for a general approach to model anything. There is no such a thing.

Basically you need to model your values, by guessing how they are distributed. Once you picked a distribution, look at the past to guess parameters of the distribution. Then guess if values are independant or not.  If they are independant, you can make a draw of the missing values, compute the day when you run out, and repeating the process, compute the expected value of the day when you run out.  If values are not independant, then you are stuck, because it is hard to simulate non independant values (except for a few distributions, including the normal distribution).

But note that the correct modelisation depends on the system. Your energy company will take into account that you need more energy in winter than in summer, and will also note is the winter is especially cold. If she analyses my withdrawals and deposits, my banker should take into account that some are weekly, daily, or monthly, and other random, and so on.

Title: Algorithm to calculate estimated future usage of a defined value

Body:
I am looking for the name of a computer algorithm. I'm fairly sure that one should exist which will help me, but I can't for the life of me figure out what to search for.

If you have implementations of the algorithm, that'd be awesome - but I'm really just researching this because I'd like to figure out how to build it myself.

Basically, I'm looking for an algorithm that can calculate future usage of some set of data based on my previous usage. For example, my electricity supplier knows how much power I've used for the previous 20 days of a 30 day month, so they can extrapolate that out and predict how quickly I will run out of money on my power account. I'd like to know if there's an algorithm out there that can tell me in how long I'm likely to run out.

What I'm looking for is something that given the following inputs:

A range (e.g. 30 days)

A period of time through that range (e.g. 4, never smaller than zero, never greater than the max of the range)

Some values for previous time periods - either the previous days, or the same days from previous months)

A total value for this range (e.g. 300)

Can give me a date range in which I'm likely to run out of the total value (300). What I'd like at the other end would be something simple - e.g. "Based on previous usage, you're going to run out in 2 days."

I've done the usual Google searches, but haven't come up with anything particular that even looks close - yet as far as I can see it's a reasonably common algorithm used all over the place.


问:
Handling one code base for multiple clients, with their own custom code
I am working on a CMS, in which we have multiple clients that use it, so the code is stored on their servers. Each client has the default code (user manager, pages manager etc), but every client also has it's own set of code (themes, scripts, custom modules).

I am trying to figure out a way to maintain an up-to-date code base for all the clients without having to make every single change to the core to every single client.

We are using GitHub for version control, so I was think of having all the clients as different branches, but how can I keep the core up to date with the master?

Am I think about this all wrong?

What are my options?

答:
Branches might be ok.  When the code changes, i.e. new features are written, bugs are fixed, etc, then they are added to master and then for the new areas to receive it they should fetch/pull the latest master and/or rebase their branch against it to get the new changes.  They can then push the updated branch to github to make sure that the latest version of it is also stored there.

Another option is for other areas to fork the project.  This is basically a similar process in terms of getting updates (fetch the latest master and rebase on it).

The difference with forks is that they don't automatically get accepted into then main remote, they have to be approved by the github repository owner (or others who have been given that privilege).