问:
Which approach to follow for developing applications targeting multiple platforms?
For applications targeting multiple platforms, I see mainly two development approaches-

Go for some JAVA-like development platform. Have one code solution and let the intermediate runtime handle different platforms. If something goes wrong in any platform, tweak the code a bit. But keep it same for all.

Make modular code separating core logic and UI. Develop separate UIs for respective platforms which will be calling same core libraries. Build the application separately for each of the target platforms.

So, which one to follow? I know, the answer will start with "It depends". But I want to hear your opinions on these approaches and the factors to be considered to choose any of them.

答:
I built a system, starting with a desktop app, 15 years ago when Java was still in its infancy and not ready for use in building these kinds of apps. I knew I needed to have a core in C++ and designed it from the start to be cross platform, including using sized types (eg int32 instead of int or long), so it could run on Mac, Windows, and UNIX (pre-Linux days).

At the time I tried to look for a good cross-platform UI environment, there were a few then including XVT. I went through the training for XVT and when I started to build a real app, I realized that I wasn't going to be able to create a clean, native look and feel on the platform (starting with the Mac). So I gave up that idea and built a native Mac (PowerPlant) UI on top of the portable core.

A couple of years later, we moved onto Windows (UI in MFC). It was faster building a UI the second time around, we maintained a Mac and Windows UI in parallel for a short time and then went all over to Windows. The core later moved onto various flavors of UNIX and Linux, to allow us to run server-based computations. The core did port well, with some adjustments when we made it 64-bit ready.

Now I am back to using a Mac and I wish we could come back to the Mac, but the size and complexity of the app makes this a hard choice. It still makes sense for much of this app to be a desktop app - it is like a CAD environment. But rather than building the UI again in a platform-specific C/C++ language (and continue to maintain an MFC-based UI), I am more inclined to rewrite the entire stack in Java so it can run on multiple platforms.

There may still be reasons to run a non-Java core, say C++ as we did. But I would be wanting to run early performance tests to see if that was really required. And I would be looking carefully at my UI to see if I could be building it as a web app, connected to the core via web services, so I could have a range of clients - desktop apps, mobile apps, web apps, etc. If I needed a piece in C or C++, could it be written under a layer of Java? Or as a web service?

Another consideration - how long will your app be around? How complex will it grow to be? If you have any ideas about this, consider the possible longevity of any UI libraries you are using and your ability over time to have people help maintain them. This may be hard to consider now but worth a thought.

-- Alex


问:
Do any LOP languages exist?
I have read a few of the articles related to the Language Oriented Programming paradigm. Therefore, I concluded that LOP paradigm can let programmers be more productive because of it's extensibility.

Are there any programming languages that are already implemented LOP or in development status?

答: I assume you're referring to Meta Programming System, which is for creating domain-specific languages. Of course, you can create your own DSL with any other programming language. Indeed, many functional programming languages (including Haskell and Lisp) have tutorials for building simple interpreters. And you can always build your own parser with Lex and Yacc.

ContentLicense: CC BY-SA 3.0

Title: Do any LOP languages exist?


问:
Why is a Boolean value stored as a byte inside of a computer when it only requires one bit
I recently started learning to write code, and in my book I came across this question. "Why is a Boolean value stored as a byte inside of a computer when it only requires one bit?" can someone shed more light on this question?</p>

答:
As @barrem23 explains, the data must be addressable, and the smallest boundary on conventional architectures is a byte.

But since this question is tagged as c++, it may be worth pointing out that std::vector<bool> is specialized to allow individual elements to be stored as bits. This will save space by sacrificing some functionality (for example, std::search may not work).


问:
What is an Activation object in JavaScript?

In a given execution context, the Variable object is the Activation object of that execution context.

From my research online, I am able to find the previous sentence rephrased in different ways but no one is able to tell what it is.

What is an Activation object?

答:
Let me start from the roots...

Execution context is an object which consists of:

variable object, which is activation object in case of functions

scope chain, which you can think of as a linked list of outer scopes

this value

Variable object is an abstract thing, which can be either one of those:

global object (in global context) - the place where global vars (like window, document or console in a browser) reside

activation object (for functions, which define scopes in ECMAScript)

Activation object is an object which holds:

formal args of the function

arguments object for this function

any vars and (named) functions inside this function

So, activation object is just a special case of variable object.

It is basically a container for all the local stuff you can access by name inside a function, except for this. I may be imprecise here, but that's what I think it is.

More explainations with some nice pictures:

http://dmitrysoshnikov.com/ecmascript/javascript-the-core/

http://dmitrysoshnikov.com/ecmascript/chapter-2-variable-object/


问:
Storing in-text metadata in a discrete data structure
I am developing an application which will need to store inline, intext metadata. What I mean by that is the following: let's say we have a long text, and we want to store some metadata connected with a specific word, or sentence of the text.

What would be the best way to store this information?

My first thought was to include in the text some kind of Markdown syntax that would then be parsed on retrieving. Something looking like this:

```<code>Lorem ipsum dolor sit amet, consectetuer adipiscing elit,
sed diam __nonummy nibh__[@note this sounds really funny latin]
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
</code>```

This would introduce two problems I can think of:

A relatively small one, is that if said syntax happen to be fortuitously on the said text, it can mess with the parsing.

The most important one is that this doesn't maintain this metadata separate from the text itself.

I would like to have a discrete data structure to hold this data, such a different DB Table in which these metadatas are stored, so that I could use them in discrete ways: querying, statistics, sorting, and so on.

EDIT: Since the answerer deleted his answer, I think it might be good to add his suggestion here, since it was a workable suggestion that expanded on this first concept. The poster suggested to use a similar syntax, but to link the metadata to the PRIMARY KEY of the metadata database table.

Something that would look like this:

```<code>Lorem ipsum dolor sit amet, consectetuer adipiscing elit,
sed diam __nonummy nibh__[15432]
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
</code>```

Where 15432 would be the ID of a table row containing the necessary, queriable information, as per example below.

My second thought was to store information of this kind in a DB Table looking like this:

```<code>TABLE: metadata

ID    TEXT_ID    TYPE    OFFSET_START    OFFSET_END    CONTENT
1     lipsum     note    68              79            this sounds really funny latin
</code>```

In this way the metadata would have a unique id, a text_id as a foreign key connected to table storing the texts and it would connect the data with the text itself by using a simple character offset range.

This would do the trick of keeping the data separated from the metadata, but a problem that I can immediately see with this approach is that the text would be fundamentally not editable. Or, if I wanted to implement the editing of the text after the assignation of metadata, I would basically have to calculate characters additions, or removal compared to the previous version, and check whether each of this modifications adds or remove characters before or after each of the associated metadata.

Which, to me, sounds like a really unelegant approach.

Do you have any pointers or suggestions for how I could approach the problem?

Edit 2: some XML problems

Adding another case which would make quite necessary for this separation of data and metadata to happen.

Let's say I want to make it possible for different users to have different metadata sets of the same text, with or without the possibility of each user actually displaying the other user metadata.

Any solution of the markdown kind (or HTML, or XML) would be difficult to implement at this point. The only solution in this case that I could think about would be to have yet another DB Table which would contain the single user version of the original text, connecting to the original text table by the use of a FOREIGN KEY.

Not sure if this is very elegant either.

XML has a hierarchical data model: any element which happens to be within the borders of another element is considered as its child, which is most often not the case in the data model I'm looking for; in XML any children element must be closed before the parent tag can be closed, allowing for no overlapping of elements.

Example:

<note content="the beginning of the famous placeholder"> Lorem ipsum
  dolor sit <comment content="I like the sound of amet/elit"> amet </note>,
  consectetuer adipiscing elit </comment> , <note content="adversative?"> sed
  diam <note content="funny latin"> nonummy </note> nibh </note> euismod
  tincidunt ut laoreet dolore magna aliquam erat volutpat.

Here we have two different problems:

Different elements overlapping: The first comment starts within the first note, but ends after the end of the first note, i.e. it's not its child.

Same elements overlapping: The last note and the boldfaced note overlap; however, since they are the same kind of element, the parser would close the lastly opened element at the first closure, and the first opened element at the last closure, which, in this circumstance, is not what is intended.

答:
Lets say I have a text:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

I add the note like this:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam [@123,#456,2w]nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

[@123,#456,2w] means: user_id=123, note_id=456, and the text marked by this note spans for the next 2 words (could be chars (c), sentences (s), paragraps (p) or whatever). Exact syntax may be different, of course.

In plain text editors notes' text can be easily stored at the end of the document, just like with Markdown footnotes.

In rich text editors this kind of note can be displayed in the text as an icon, and marked text can be highlighted in some way. User can then delete such notes just as normal characters with Del or Backspace, and edit them with some kind of special editing mode. I imagine resizing noted areas with a mouse and editing note text with popup window.

Pros:

Goes nicely with "intersections" since you mark an offset (implicitly by note's position in the text) and a length for each note.

Supports multiuser environment. (In fact, this needs some deeper research and you'd probably have to deal with something like Google Wave operational transformations, which my brain cannot handle.)

Can be edited with both rich and plain text editors.

You can easily handle revisions, since all markers are in-place - when you edit the text before a marker, marker just shifts along with other text.

Easy to parse.

No need for external DB, but you can still use one if you want.

Can be mixed with Markdown or XML if you choose some unobtrusive syntax.

Cons for plain text editing:

You can't see areas in text marked with notes (unless you highlight plaintext, which is an option too), but just the places where notes start. This is compensated by the ability to choose arbitrary length units: chars, words, sentences, paragraphs.

You can edit the text under a note without noticing, especially if a note spans quite long (e.g. 2+ paragraphs). Can be compensated by revison control mechanism which compares a text under each note with it's previous version and notifying a user if it was changed.

General cons:

Troubles with multiple users editing the same text, but I think it is inavoidable anyway. I'm not an expert in this field.


问:
better way to define an exception thrown by a method in Java?
I know how to define exceptions and all, but I'm not sure if the way I'm doing it is the most intuitive and readable by another users.

I have a very simple method I've written that I want to throw an exception, because it's easier then manually checking return values; the method is private and there is no way need to define a public Exception type.  None of the existing Java exceptions fit the error exactly, so I'm trying to figure out what type of exception I want to throw here?

I don't want to just throw a RuntimeException, I only want to catch my specific exception I throw, all other Exceptions should propagate up. I figured I would define a little inner class for my exception.  However, i don't really need to overwrite anything in the RuntimeException class, I just want to catch and and print it's message.  So now I have a line that says something like

```<code>private class MissingPropertyException extends RuntimeException{};
</code>```

This does nothing but allow me to catch only the exception I'm intentionally throwing while ignoring the rest.  Is this good syntax?  it feels odd to define a inner class without implementing anything within it.  Is there a way to do this elegantly without creating an empty inner class?

答:
Side stepping all the "should" and "shouldn't" arguments (which are relevant, btw)..  if you do finally end up with an "inner class", at least make it "static":</p>

```<code>private static class MissingPropertyException extends RuntimeException{};
</code>```

Body:
Side stepping all the "should" and "shouldn't" arguments (which are relevant, btw)..  if you do finally end up with an "inner class", at least make it "static":

private static class MissingPropertyException extends RuntimeException{};


问:
Visiting points on a number line while minimizing a cost not related to distance
I need some help on this ACM ICPC problem. My current idea is to model this as a shortest path problem, which is described under the problem statement.

Problem

There are N = 1000 nuclear waste containers located along a 1-D number line at distinct positions from -500,000 to 500,000, except x=0. A person is tasked with collecting all the waste bins. Each second that a waste container isn't collected, it emits 1 unit of radiation. The person starts at x = 0 and can move 1 unit every second, and collecting the waste takes a negligible amount of time. We want to find the minimum amount of radiation released while collecting all of the containers.

Sample Input:

4 Containers located at [-12, -2, 3, 7].

The best order to collect these containers is [-2, 3, 7, -12], for a minimum emitting of 50 units. Explanation: the person goes to -2 in 2 seconds and during that time 2 units of radiation are emitted. He then goes to 3 (distance: 5) so that barrel has released 2 + 5 = 7 units of radiation. He takes 4 more seconds to get to x = 7 where that barrel has emitted 2 + 5 + 4 = 11 units. He takes 19 seconds to get to x = -12 where that barrel has emitted 2 + 5 + 4 + 19 = 30 units. 2 + 7 + 11 + 30 = 50, which is the answer.

Notes

There is an obvious O(N!) solution. However, I've explored greedy methods such as moving to the closest one, or moving to the closest cluster but those haven't worked.

I've thought about this problem for quite a while, and have kind of modeled it as a graph search problem:

We insert 0 in as a baseline position (This will be the initial state)

Then, we sort the positions from least to greatest.

We then do a BFS/PFS, where the state consists of

Two integers l and r that represent a contiguous range in the sorted position array that we have visited already

An integer loc that tells us whether we're on the left or right endpoint of the range

An integer time that tells us the elapsed time

An integer 'cost' that tells us the total cost so far (based on nodes we've visited)

From each state we can move to [l - 1, r] and [l, r + 1], tweaking the other 3 integers accordingly

Final state is [0, N], checking both ending positions.

However, it seems that [L, R, loc] does not uniquely define a state, and we have to store L, R, loc, and time, while minimizing cost at each of these. This leads to an exponential algorithm, which is still way too slow for any good.

Can anyone help me expand on my idea or push my into the right direction?

Edit: Maybe this can be modeled as a dynamic programming optimization problem? Thinking about it, it has the same issues as the graph search solution - just because the current cost is low doesn't mean it is the optimal answer for that sub problem, since the time also affects the answer greatly.

Greedy doesn't work: I have a greedy selection algorithm that estimates the cost of moving to a certain place (e.g. if we move right, we double the distances to the left barrels and such).

Could you do a Priority-first search, with a heuristic? The heuristic could combine the cost of the current trip with the amount of time elapsed.

答:
I think it makes most sense to think of every stage simply as a binary choice between going right to the nearest barrel and going left to the nearest barrel. Simply have a cost function that details the number of radiation units that would be incurred in total by making any motion and choose the one with the lowest cost.

Do NOT simply consider the closest barrel, but instead assume that by moving away from a barrel you are effectively adding twice the radiation because by moving away you have also incurred the cost of having to move back that direction later.

In your example of [-12,-2,3,7], moving left would incur a total of 14(2+2+10) on the left, and 18(2+2+5+9) on the right, for a total of 22. Moving right would incur 10(3+3+4) on the right, and 26(3+3+5+15) on the right. Clearly left is the right solution at first. A similar calculation can be done for every successive movement.

After that the problem basically reduces to a search, so the complexity should be O(nlog(n)), which is MUCH better than O(n!). I believe that this is necessarily the lowest complexity that can exist for this problem since it's basically a comparison based search algorithm for which it is not possible to do better than O(nlog(n))

Apparently I wasn't clear enough with this description, so I've decided to make it a bit more programmatic:
1. Calculate the cost incurred by going by left, and the cost incurred by going right based on current position
2. Move in the least expensive direction
3. Remove the reached barrel from consideration in calculating the cost of moving in a direction

Calculating cost:
1. Identify the closest barrel in the given direction. Let's say that $dist is the distance from current position to the nearest barrel in the given direction.
2. Cost is initialized as N*$dist where N only considers still active barrels.
3. To this, add the distance that the new position indicated by $dist would be from every barrel remaining.

OwnerDisplayName: Slater Tyranus


问:
How Immutable Sets are Manipulated
When working with an immutable set or map, like the ones found in many functional programming languages, operations that would otherwise modify the container generate a new container instead.

I know that most list operations in functional languages do not result in a copy of the list and just rearrange pointers. This is why working with lists is extremely efficient.

I am curious whether immutable maps are similar or if an entirely new map is created after each operation. I am asking because a library I wrote manipulates a lot of maps and I am curious whether I will see a performance boost if I switch over to immutable maps. Currently, I am just looping over my map adding or throwing away key/value pairs as I go.

答:
As far as I can tell, functional sets are generally implemented as trees, so sharing nodes between concurrent versions makes sense. Some functional languages, notably F# and Clojure, open source their code on github, you can look there for concrete details. F# uses trees.

Some time ago, I have been comparing performance of F# immutable Set (Microsoft.FSharp.Collections) vs mutable .NET HashSet (System.Collections.Generic). I do not have results available to share now, but as far as I remember lookup / union / intersection times were similar for both and when adding large numbers of entries the immutable set performed slower by some low constant factor (something around 3 or 4).

Apart from the book, there's also Okasaki's thesis available, which was the foundation for the book - glimpsed through it and it looks rather hard (well, like a proper thesis should), though you might find it useful.

Title: How Immutable Sets are Manipulated


问:
Maintain a web application once the only developer is gone
I have a terminal disease and there is a very high chance that I will no longer be in this world by the end of the year.

I have developed a web application that it is extensively used in my family’s business (a small hairdressing shop). No member of my family has neither programming nor system administration skills. I have neither close friends with those skills.

The business makes at most 10k in net profits per year. In fact, the business profits can only afford to pay the salaries of its 3 employees (father, mother and sister) and those are quite low and decreasing each year due to the financial crisis. In fact, I am not an employee of my family’s business, I work for a normal software development company. I developed the application during my free time in order to help them.

So far I do not care if another business also uses my application or even if the application itself loses my ownership. I just want that my family’s business can continue using it, which means system administration support if something goes wrong and development for new features/bugs.

I would like to ask you if you could give me the measures you think I could take in order to guarantee as much as possible the continuity of the application.

The technologies of the application are:

Platform: Tomcat (Java), MySQL and Linux

Frameworks: mainly JPA and ZK

答:
First of all I am sorry to hear of your situation. I hope for the best for you.

I'm not going to tell you how to spend your time, but I have a suggestion that could keep your application living on and your family business supported.

Open source the application

In doing this, you will benefit the wider community, making the assumption of course that this applies to other hair dressing salons.

Even if the application is fairly proprietary to your family, contributors could make it more generic (and customizable) so it could become widely used. And you never know, perhaps this could become a really widely used project.

I am predominately a .NET guy but I would be interested in maybe spending some time on this if you are willing to open source it. Put it on GitHub or BitBucket. Write some (brief) documentation for newbies on how to compile, run and deploy the application, and let the community carry your flame. If you do decide to do this, please post a comment on your question or my answer with the details.

Best wishes, Sam.


问:
Obsessed with finding most elegant solution
I find that at times I get obsessed with finding the most elegant solution to a problem or task.

I'll spend hours trawling the internet/texts for ideas and discussion on the right way to solve a problem or on the best pattern to use.

I constantly go back and refactor my code and make minor and major changes when what I have written already does the job. I'm always trying to anticipate what future requirements might be and how I can make my code as flexible as possible to avoid more work in the future when I'm really making more work for myself in the present.

Given infinite time this is not a problem but with deadlines looming the pressure gets more intense and while I search for the best solution I could be getting more done. I'm a solo developer and the company I work for is never going to look "under the hood" so why do I bother with this obsession? Anyone else get this? And what do you do to motivate yourself to just get it done.

答:
Yes, I find myself faced with this when designing much more so than when developing. If I can't think of an elegant solution I tend to move on wherever possible and let my subconscious do the hard work for me - this avoids procrastinating.

At the end of the day you need to remember that you want to finish the system (presumably) and as such you just need to tell yourself to move past to reach your end goal.


答:
It's your job to have well-written, refactored source code. You're succeeding at it, and that's great.

It's also your job to deliver on time. If you want a motivation to stop obsessing about code quality, how about the fact that if you spend precious time doing changes on code which is already correct, fulfills the requirements and works as expected, you wan't be able to met the deadlines for other requested features, thus not doing the job you're paid for?

Title: Obsessed with finding most elegant solution

Body:
I find that at times I get obsessed with finding the most elegant solution to a problem or task.

I'll spend hours trawling the internet/texts for ideas and discussion on the right way to solve a problem or on the best pattern to use.

I constantly go back and refactor my code and make minor and major changes when what I have written already does the job. I'm always trying to anticipate what future requirements might be and how I can make my code as flexible as possible to avoid more work in the future when I'm really making more work for myself in the present.

Given infinite time this is not a problem but with deadlines looming the pressure gets more intense and while I search for the best solution I could be getting more done. I'm a solo developer and the company I work for is never going to look "under the hood" so why do I bother with this obsession? Anyone else get this? And what do you do to motivate yourself to just get it done.


答:
There is some merit to working on what we call technical debt on an ongoing basis.  Keeping your code clean keeps the system agile and maintainable.  But you have to strike a balance; on the one hand, you don't want the system design to drift so much that the software becomes unmaintainable, but on the other hand, you don't want to be "gold-plating" for marginal benefit, and missing your deadlines.

Seth Godin says it this way: your job is to ship.  The way you do that on time and on budget is, when you run out of money or you run out of time, you ship.  You should plan your work so that you don't run out of either.

Seth discusses this in more detail in his Ted Talk, here:

http://vimeo.com/5895898


答:
If I understand your usage, I would consider using an "IllegalStateException" for this with a good message.  It's already built into Java.

Your reasons for choosing an unchecked exception are not clear to me, but I think it would make sense on the build() method of a Builder pattern if your builder requires that one of several possible parameters be used.  Please check your reasoning for using an unchecked exception against my blog post on checked vs. unchecked exceptions.

Title: better way to define an exception thrown by a method in Java?

Body:
I know how to define exceptions and all, but I'm not sure if the way I'm doing it is the most intuitive and readable by another users.

I have a very simple method I've written that I want to throw an exception, because it's easier then manually checking return values; the method is private and there is no way need to define a public Exception type.  None of the existing Java exceptions fit the error exactly, so I'm trying to figure out what type of exception I want to throw here?

I don't want to just throw a RuntimeException, I only want to catch my specific exception I throw, all other Exceptions should propagate up. I figured I would define a little inner class for my exception.  However, i don't really need to overwrite anything in the RuntimeException class, I just want to catch and and print it's message.  So now I have a line that says something like

```<code>private class MissingPropertyException extends RuntimeException{};
</code>```

This does nothing but allow me to catch only the exception I'm intentionally throwing while ignoring the rest.  Is this good syntax?  it feels odd to define a inner class without implementing anything within it.  Is there a way to do this elegantly without creating an empty inner class?


问:
How to know if an Open Source project is mature enough to use in a product?
There are some open source projects that I'd like to incorporate into a product at work.  We don't have the bandwidth nor the subject matter expertise to do it ourselves.  I found these by searching in Google.  I'm unaware of any "major players" that utilize the projects, but I'm pretty encouraged by what I see.

Now, I'm a bit concerned about the amount of risk I'm exposed to by using joe-blow's open source project.  If it takes me 95% of the way there, perhaps the remaining 5% is easy to add or fix.  Perhaps it's non-trivial.

How do people go about determining whether an open source project is mature enough to use in a product?

This is not a hobby project, so stability, maintainability, etc. are paramount.

答:
The criteria I use, providing that the project fits my requirements:

Is there an active community, with people able to provide assistance?

Is the license appropriate to my development?

Is the product still under active development?

Is it a commonly used framework?

Can I find any reviews / blog posts / etc of the product and how people have integrated with it?

4 & 5 don't really help for niche projects which it sounds like yours is.

The single most important thing is does it meet your requirements? If you feel that it does, the next thing to do is to make a harness to test the project and see if you can do what you want it to do. This will give you a feel for its API (if it's a library) and how it works.

At the end of the day, if there is something open source that does 90% of what you do, fork it, add the extra functionality and return it to the community. I've done this before on commercial projects.


答:
@bmused, I know your pain all too well. Much of it for me stems from stunning WTF code I've had to deal with in various places. It's professionally embarrassing to foist crap on others. There are even 2 times I recall begging the team lead to refuse to allow some code into the system. Oh well; ultimately delivery trumps quality even when code is acknowledged as bad. The code we all have to deal with proves it.

Motivations

A good Scout always leaves his camp site better than he found it. Amen.

It's still better than the existing horror.

Fun. Good design makes coding easier and more fun.

Avoiding pain, both self and boss inflicted. I simply learned to let good enough be. That was hard, and I must always be on my guard on this.

A "continuous improvement attitude" allowed me to not worry so much up front.

Good, thoughtful, complete, design up front is extremely important. Don't try to be too smart for your (and our) own good. I'm not saying "elegant", "brilliant", "slick implementation of obscure language features", etc. I'm saying complete, straight forward, Object Oriented. Fight for the time to make a decent design prior to coding.

A good design naturally lends itself to "good enough" coding that lets you sleep at night. You Code Complete (a play on a must have book title) so you simply don't worry so much about inventing places for future extension. And being "complete" there's less urge to keep fussing with it.

I had 2 very different experiences w/ the same code base. The well designed one more than anything completely defined business domain classes to cover the requirements; it was criticized by PEBCAK OO-ignorant co-workers for "too much", "too busy" - but it coded easier and faster (you may be surprised how much time you seem to have for improvements during coding!), and sailed through testing in days. Compared to the other time where design was incompetent at best and we were stuck in a 3 month test-fail-hack cycle of hell. Imagine how you might feel about getting it absolutely perfect next time given these two experiences.

Continuous improvement is a happier place. Get your new code good enough and as opportunities present themselves make improvements.

One's code base is either getting worse or getting better; continuous improvement or bust.

Making improvements later, in the face of known changing requirements, or just time to have thought about it is much preferable to second guessing every potential future change up front.

Consciously prevents over engineering in anticipation of changes that never come - my pet peeve is the interface implemented by only one class. An innocent thing you'd think but I see it way too many times and IMHO in a large code base every pointless, unhelpful bit is painful.

Good refactoring practices along with unit tests is the way to implement continuous improvement. I very highly recommend Refactoring by Martin Fowler.


问:
How to write tasks in Jira when using Scrum?
I am going to start a new project using Scrum and Jira and I have some questions regarding how to write proper tasks in Jira.

From what I understand user stories are small non-technical descriptions written by the stakeholders (ideally) that can have the form: As a user I want to order monkies so I can earn money.

However these tasks must be elaborated with requirements, technical requirements etc. My question is: How do you write such tasks in Jira properly, and do I have the right understanding of user stories.

Should I create user stories as super tasks and then create subtasks with the actual tasks/requirements?

Should I estimate super tasks/user stories, or only the sub tasks?

答:
Should I create user stories as super tasks and then create subtasks with the actual
  tasks/requirements?

Yes, same reason as @superM gave. Our team actually puts all the acceptance criteria and requirements in the user story (super task) and then create subtasks to outline what exactly the developers need to do to accomplish that story (eg, create table, add service to do X, tweak server params, etc).

We also use the GreenHopper plugin for JIRA (http://www.atlassian.com/software/greenhopper/overview) to track our Epics and Stories in the backlog. Once the Stories are estimated with Story Points and committed to a Sprint then the team creates sub-tasks under each Story for what they will actually have to do to get the software to implement the feature. The GreenHopper plugin does a great job visualizing the sub-task to User Story relationship.  However, even without the plugin, vanilla JIRA will let you specify a main task (call that your story) and then sub-tasks (what the team knocks out during the sprint).

Should I estimate super tasks/user stories, or only the sub tasks?

We estimate story points at the Story level only (the GreenHopper plugin adds a custom field for that value, but if you don't use the plugin you could create a custom field if you wanted). But on our team, as the developers complete their sub-tasks under each story, they log their work (eg, how many hours it took them) so we can report on it later. We never log work (hours) to the story (super task) and we never estimate the hours to complete the sub-tasks or stories going into them, it's always post-mortem in our case.


答:
Consider the amount of time used to solve the problem to be one of the costs you're trying to minimize.  You won't be able to optimize this perfectly, so just use your best judgement.

Perfectly elegant solutions that take way too long and horribly ugly kludges are both failure modes.  Try to maximize elegance per unit time, not straight elegance.

Also, there's a good principle called YAGNI: You Ain't Gonna Need It.  I think it's slightly overhyped, to the point where some people think it's an excuse to never plan for the future, but more often than not, it applies.  If you put something in your software that never gets used, that's not elegant, even if it would have been a good solution to a problem that never shows up.

I think you will find worse is better to be good reading.  It's an attempt to explain the failure of LISP machines to LISP hackers and the details are ancient history by now, but the details aren't the important part.


答:
For framework, I generally only go with large and mature framework with lots of prewritten modules and large community. Generally, choosing one framework over the other would not really reduce the amount of work you need to spend on your own code by much, some framework may encourage a more beautiful code, others may make certain operations easy, but they generally sum up to very little difference to total development effort. However  popular frameworks would have more prewritten modules you can leverage off and that's how you can usually save much more time and effort.

For small non framework library, generally you'd be able to make modifications yourself if needed without much problem, so usually I'd consider having community as an added bonus. Most small libraries are only managed by a single person, but they still are better than building yourself. For large libraries though, having a mature, active community, and documentation is essential because you're unlikely to be able to make changes yourself as easily.

License is essential. For one-man libraries, it's likely that you'll need to make modifications to the library, therefore it's essential that their license allows you to do so under terms you'd agree with.

For small libraries, you should always assume that you'll need to fork and that the project is already abandoned. This is usually not a problem, especially if the project is hosted on Github or BitBucket, because they make forking other people's project stupidly easy. For small libraries, you can always take over the maintenance of the project yourself, if the original maintainer is gone or if they're planning to take the project direction to places you don't want to go to.

I'm less concerned with project activity, mature library that have achieved their sense of "perfectness" generally would only need to do bug fixes, so their activity slowed down. Project activity is only important if the library involves a target that is actively evolving, for example, a wrapper for external service would need to be constantly updated as the external service evolves, so active development is essential, but a math library would not need much new development once it has all the feature it needed.

For larger libraries, things become more difficult. Taking over is much more involved, fortunately larger libraries generally do not move as fast, as they're generally more mature.

As @Sam said in his answer, I agree that the most important thing in evaluating open source library is how much it fits your requirement. Once any license issue is sorted out, using an open source library is rarely a mistake because you can always fork if things go south.

Title: How to know if an Open Source project is mature enough to use in a product?

Body:
There are some open source projects that I'd like to incorporate into a product at work.  We don't have the bandwidth nor the subject matter expertise to do it ourselves.  I found these by searching in Google.  I'm unaware of any "major players" that utilize the projects, but I'm pretty encouraged by what I see.

Now, I'm a bit concerned about the amount of risk I'm exposed to by using joe-blow's open source project.  If it takes me 95% of the way there, perhaps the remaining 5% is easy to add or fix.  Perhaps it's non-trivial.

How do people go about determining whether an open source project is mature enough to use in a product?

This is not a hobby project, so stability, maintainability, etc. are paramount.


问:
Hourly or per project billing?
How do you bill your programming projects? Do you do it per hour? Per job?

Please include what kind of project you are doing in the answer. (Mobile, Web, Desktop, etc... You can be more specific if you want.)

BONUS:

If you'd like to give specific amounts in your answer, you may. ;-)

答:
There's always going to be a struggle between you and the client over costs: you want to charge as much as you can from a client, and a client is going to want to get as much work for as little cost as possible.

So, when you charge hourly, it leaves open to negotiation how many hours a project should take to complete. You may think it'll take 10 hours, but your client thinks you should do it in 5.

By charging by project, there's very little open to negotiation: it costs $X, and the client can take it or leave it.

ContentLicense: CC BY-SA 2.5

Title: Hourly or per project billing?


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答: Pointers, obviously. :)</p>

Body: Pointers, obviously. :)


问:
Do good project managers need a programming background?
Sometimes I can't stand it when project managers ask me to estimate time to complete for various tasks.  An estimate is a guess, and guesses can be wrong.  Generally, bad requirements and documentation will lead to bad guesses.

So I often wonder if the project managers were ever in my shoes trying to guess at how long task X and Y will take, and how difficult it is to assign a number to it based on what little is known and collected from the client.

My question then is: Do good project managers need to have a programming background?

Or maybe the question should be, do good project managers need to have been a good programmer before?  Is there any correlation?

答: I believe they do need some programming background. If not then they will always be pressuring the programmers t d their tasks quick and expect it to be done within a few hours when actually the task requires lots of thinking and dedication. These qualities are known and well versed with programmers so if the project manager has programming background then he/she will understand how long a specific task will take and there will no arguments within the department and thus in the end a good project will evolve.</p>


问:
SQL Triggers and when or when not to use them.
When I was originally learning about SQL I was always told, only use triggers if you really need to and opt to use stored procedures instead if possible.

Now unfortunately at the time (a good few years ago) I wasn't as curious and caring about fundamentals as I am now so never did ask to the reason why.

What's the communities opinion in this? Is it just someone's personal preference, or should triggers be avoided (just like cursors) unless there is a good reason for them.

答:
Use of database triggers

To drive column values automatically.

To enforce complex integrity constraints.

To enforce complex business rules.

To customize complex security authorizations.

To maintain replicate tables.

To audit data modification.


问:
Finding the possible combinations of x switches out of y being true
I am working on an algorithm to find possible fills for gaps in text. My function will receive as input:
(example)

```<code>[false,"o",false,"b",false,"r"]
</code>```

representing the string "foobar" with some values cut out. My function should find opportunies for the possible ways to fill the gaps given a set maximum characters (and a minimum of one blank filled). so, given a maximum of 2 it should return:

```<code>[
[true,"o",false,"b",false,"r"],
[false,"o",true,"b",false,"r"],
[false,"o",false,"b",true,"r"],
[true,"o",true,"b",false,"r"],
[true,"o",false,"b",true,"r"],
[false,"o",true,"b",true,"r"]
]
</code>```

Can anyone give me a shove in the right direction?

Oh, and I planned to run the results through another function to sort these out, but if I can NOT get results where there is a false between the blanks (ie, from the above, [true,"o",false,"b",true,"r"]) it would be a huge bonus.

This is in a javascript/jQuery environment

答:
Found my own answer, it was particularly curious to my own solution, I don't really have a code example of a more general solution (like what MichaelT linked in comments) but in pseudocode it was essentially:

```<code>/*
Find the free(false) cells in the array and create an array of their indices
check the array is not empty
if it is return false (if there's no free space you cannot fill anything)
(now check the combinations...)
for n=1..the maximum number of fills (for each possible number of fills)
    for each of the free cells (for each possible first fill)
        check the number of free cells after this one
        if it is less than n-1 break (no room for this many fills)
        for 1..n-1 (for each fill left after the first)
            fill this spot
        add the result to the list of results
*/
</code>```

as I said, fairly specified to my solution of only replacing in line, I think some serious nested for's would be required to do it the other way round.

Anywho, I'll mark mine correct as it's how I solved mine, but it's probably not relevant to many people...

Body:
Found my own answer, it was particularly curious to my own solution, I don't really have a code example of a more general solution (like what MichaelT linked in comments) but in pseudocode it was essentially:

/*
Find the free(false) cells in the array and create an array of their indices
check the array is not empty
if it is return false (if there's no free space you cannot fill anything)
(now check the combinations...)
for n=1..the maximum number of fills (for each possible number of fills)
    for each of the free cells (for each possible first fill)
        check the number of free cells after this one
        if it is less than n-1 break (no room for this many fills)
        for 1..n-1 (for each fill left after the first)
            fill this spot
        add the result to the list of results
*/

as I said, fairly specified to my solution of only replacing in line, I think some serious nested for's would be required to do it the other way round.

Anywho, I'll mark mine correct as it's how I solved mine, but it's probably not relevant to many people...


答:
On high pressure projects people keep things in perspective by reminding themselves 'it's only software, nobody died'. Sadly you won't be able to develop a cure for yourself. Your family won't be able to learn support the application.

Perhaps they need you to help them develop an application using technologies they know - pen and paper, ledgers and cardex, diaries and address books. Maybe you can introduce them to cloud based apps such as Zoho - it's free for up to 3 users. If, after you have gone, they find they need something better they won't feel bad about it. It's only software.

Title: Maintain a web application once the only developer is gone

Body:
I have a terminal disease and there is a very high chance that I will no longer be in this world by the end of the year.

I have developed a web application that it is extensively used in my family’s business (a small hairdressing shop). No member of my family has neither programming nor system administration skills. I have neither close friends with those skills.

The business makes at most 10k in net profits per year. In fact, the business profits can only afford to pay the salaries of its 3 employees (father, mother and sister) and those are quite low and decreasing each year due to the financial crisis. In fact, I am not an employee of my family’s business, I work for a normal software development company. I developed the application during my free time in order to help them.

So far I do not care if another business also uses my application or even if the application itself loses my ownership. I just want that my family’s business can continue using it, which means system administration support if something goes wrong and development for new features/bugs.

I would like to ask you if you could give me the measures you think I could take in order to guarantee as much as possible the continuity of the application.

The technologies of the application are:

Platform: Tomcat (Java), MySQL and Linux

Frameworks: mainly JPA and ZK


问:
LOOP-computable functions
I was just reading a chapter about LOOP-computable functions and I have the following question: Is it possible to numerate every LOOP program with an algorithm?

Formally: Is it possible to have a LOOP program M, s.t M(n,m)=P_n(m)  (input is n,m. output is P_n(m), where P_n is the numeration of the loop programs).

答: No. Assume M is a loop-program. Define program D(x) = M(x, x). Then D is trivially a loop-program. Let i be the index of D in the enumeration, i.e. P_i = D; then M(i, i) doesn't halt because it's an infinite loop (D(i) calls M(i,i) calls D(i) ...). Therefore M can't be a loop-program.</p>

Title: LOOP-computable functions


问:
How to make creating viewmodels at runtime less painful
I apologize for the long question, it reads a bit as a rant, but I promise it's not! I've summarized my question(s) below

In the MVC world, things are straightforward. The Model has state, the View shows the Model, and the Controller does stuff to/with the Model (basically), a controller has no state. To do stuff the Controller has some dependencies on web services, repository, the lot. When you instantiate a controller you care about supplying those dependencies, nothing else. When you execute an action (method on Controller), you use those dependencies to retrieve or update the Model or calling some other domain service. If there's any context, say like some user wants to see the details of a particular item, you pass the Id of that item as parameter to the Action. Nowhere in the Controller is there any reference to any state. So far so good.

Enter MVVM. I love WPF, I love data binding. I love frameworks that make data binding to ViewModels even easier (using Caliburn Micro a.t.m.). I feel things are less straightforward in this world though. Let's do the exercise again: the Model has state, the View shows the ViewModel, and the ViewModel does stuff to/with the Model (basically), a ViewModel does have state! (to clarify; maybe it delegates all the properties to one or more Models, but that means it must have a reference to the model one way or another, which is state in itself) To do stuff the ViewModel has some dependencies on web services, repository, the lot. When you instantiate a ViewModel you care about supplying those dependencies, but also the state. And this, ladies and gentlemen, annoys me to no end.

Whenever you need to instantiate a ProductDetailsViewModel from the ProductSearchViewModel (from which you called the ProductSearchWebService which in turn returned IEnumerable<ProductDTO>, everybody still with me?), you can do one of these things:

call new ProductDetailsViewModel(productDTO, _shoppingCartWebService /* dependcy */);, this is bad, imagine 3 more dependencies, this means the ProductSearchViewModel needs to take on those dependencies as well. Also changing the constructor is painful.

call _myInjectedProductDetailsViewModelFactory.Create().Initialize(productDTO);, the factory is just a Func, they are easily generated by most IoC frameworks. I think this is bad because Init methods are a leaky abstraction. You also can't use the readonly keyword for fields that are set in the Init method. I'm sure there are a few more reasons.

call _myInjectedProductDetailsViewModelAbstractFactory.Create(productDTO); So... this is the pattern (abstract factory) that is usually recommended for this type of problem. I though it was genius since it satisfies my craving for static typing, until I actually started using it. The amount of boilerplate code is I think too much (you know, apart from the ridiculous variable names I get use). For each ViewModel that needs runtime parameters you'll get two extra files (factory interface and implementation), and you need to type the non-runtime dependencies like 4 extra times. And each time the dependencies change, you get to change it in the factory as well. It feels like I don't even use a DI container anymore. (I think Castle Windsor has some kind of solution for this [with it's own drawbacks, correct me if I'm wrong]).

do something with anonymous types or dictionary. I like my static typing.

So, yeah. Mixing state and behavior in this way creates a problem which don't exist at all in MVC. And I feel like there currently isn't a really adequate solution for this problem. Now I'd like to observe some things:

People actually use MVVM. So they either don't care about all of the above, or they have some brilliant other solution.

I haven't found an in-depth example of MVVM with WPF. For example, the NDDD-sample project immensely helped me understand some DDD concepts. I'd really like it if someone could point me in the direction of something similar for MVVM/WPF.

Maybe I'm doing MVVM all wrong and I should turn my design upside down. Maybe I shouldn't have this problem at all. Well I know other people have asked the same question so I think I'm not the only one.

To summarize

Am I correct to conclude that having the ViewModel being an integration point for both state and behavior is the reason for some difficulties with the MVVM pattern as a whole?

Is using the abstract factory pattern the only/best way to instantiate a ViewModel in a statically typed way?

Is there something like an in depth reference implementation available?

Is having a lot of ViewModels with both state/behavior a design smell?

答:
Sometimes it's good to go to the simplest definition rather than a full-blown example:
http://en.wikipedia.org/wiki/Model_View_ViewModel
maybe reading the ZK Java example is more illuminating than the C# one.

Other times listen to your gut instinct...

Is having a lot of ViewModels with both state/behavior a design smell?

Are your models are object per table mappings? Perhaps an ORM would help mapping to domain objects while handling the business or updating multiple tables.


问:
Continuous Integration Feedback Cycle
How long should the Continuous Integration process take (i.e. compiling classes and running unit tests + integration test)?

On my current project it takes about 30 minutes, is that OK?
What's the ideal length of build time?

Integration tests take most of that time, if the 30 min is too long what can be done here?

What's the impact of having the build complete in 30 min?

答:
The ultimate goal is to provide feedback while the details of the task are still in short term memory. According to some sources, the duration of short term memory can be as low as 15-30 seconds, so a target compile-and-test cycle of around 5-10 seconds would seem to be a well motivated and rational answer.

Unfortunately, practical considerations make this target exceedingly difficult to achieve without considerable engineering effort. It is my hope that future development automation tools will help with the difficult tasks of fine-grained dependency analysis, compilation unit and test case selection.

Title: Continuous Integration Feedback Cycle


问:
Do I need to learn python first to understand the part 2 of the book Test Driven development?
It seems like Python is used as a coding language for part 2 of Kent Beck's book Test Driven Development. I have read the first part of that book and started appreciating the value of TDD . First part was easy to understand as the examples were in Java and that is the only language that I have worked on. How should I prepare myself to go about reading the second part of the book? What value will it provide? I do not plan to write a testing framework myself. Can I skip this entirely and go to the third section?</p>

答:
Everybody should learn more than one language.

Python is a great language widely used to illustrate programming concepts such as 'Cognitive Intelligence', 'Semantic Web', 'Natural language processing' to name just 3 O'Reilly titles.

Learning a little Python will make you a better Java programmer .


问:
How to show data to the user using PHP?
I'm always trying to find new methods on development. So I looked into some websites and analyzed their ways of presentation.

Returning part of the page using AJAX

Normally I will use an array  to return values, for example:

```<code> //GET User details

 $user_id = $_POST['user_id'];

 $user_details = $this->get_user($user_id);

 if ($user_details['status'] == true) {
     exit(json_encode(array('status'=>true, 'data'=>$user_details['data'])));
 } else {
     exit(json_encode(array('status'=>false, 'reason'=>'SomeReasons....')));
 }
</code>```

But I see that some sites returning `HTML'. Is this preferable in any reason?

Also what is the best method to use: AJAX or an iframe?

答:
It's always better to return JSON rather than HTML in your AJAX result. By returning HTML you're letting your presentation layer leak into your data layer.

Generally speaking you should use AJAX rather than iFrames since its a neater solution and allows bookmarking (if you set it up). There are some use cases where iFrames are appropriate, for example when you need data from another site. For further reading have a look here and here.

Title: How to show data to the user using PHP?


问:
What is difference between publisher-subscriber and reactor patterns?
Publish-subscribe and Reactor patterns looking very similar to me. How they are different?

In both patterns a message is getting passed to subscribers indirectly (listeners in reactor pattern).

I feel observer pattern is very similar to two other patterns too.

What are key differences between those patterns?

答:
Reactor = single threaded event loop that receives and processes requests. Those requests could be loaded in batches from a file, via SMTP and/or HTTP. Processed concurrently responses are delivered when ready rather than sequentially.

Publishers emit.
Subscribers consume.

Publishers + Subscribers = Observer pattern (Heads First Design Patterns). Observers fire sequentially and usually block until they complete.


答:
I don't necessarily agree entirely with Tom's answer so I'm going to give my opinion.

Generally, you should avoid returning XHTML and instead return JSON, transforming the result into the DOM using JavaScript and your framework of choice.

There are some situations such as returning very large amounts of data where this isn't just not practical, but you end up duplicating your presentation in both JavaScript and in the initial renderer. An example of this recently for me would be a reporting part of an application I was working on. I had the service endpoint configured to return XML data, for the web site I created an adaptor to transform the data with and XML stylesheet and return the XHTML. You could of course return XML to the browser and run the XSL client side.

In summary, generally return JSON however there are appropriate times, in my opinion, to return XHTML, and this is the reason as you say you see it online in places.

Use of an iframe is an "old fashioned" way to update part of the page without a full refresh. This is not the same effect as AJAX as most browsers will now days restrict programmatic access to the DOM of the iframe, so from that you can infer Ajax is the correct way to do it.

Title: How to show data to the user using PHP?

Body:
I'm always trying to find new methods on development. So I looked into some websites and analyzed their ways of presentation.

Returning part of the page using AJAX

Normally I will use an array  to return values, for example:

```<code> //GET User details

 $user_id = $_POST['user_id'];

 $user_details = $this->get_user($user_id);

 if ($user_details['status'] == true) {
     exit(json_encode(array('status'=>true, 'data'=>$user_details['data'])));
 } else {
     exit(json_encode(array('status'=>false, 'reason'=>'SomeReasons....')));
 }
</code>```

But I see that some sites returning `HTML'. Is this preferable in any reason?

Also what is the best method to use: AJAX or an iframe?


问:
LOOP program only need inc and zero
I have 4 different commands in LOOP programming language:

```<code>    y=Zero()
    y=Val(x)=copy x and put it in register y
    y=Inc(x)=x+1
    y=Dec(x)=x-1
</code>```

Finally I also have

```<code>    loop n times {
    ...
    }
</code>```

How is it possible that there is an equivalent loop program to every other loop program which uses only Inc, Zero and the loop?

For me it is not clear how to express the Dec-command using only Inc, Zero and the loop.

答:
Here's one way to code y=Dec(x):</p>

```<code>y=Zero();
z=Zero();
loop x times {
  loop z times {
    y=Inc(y);
  }
  z=Zero();
  z=Inc(z);
}
</code>```

Title: LOOP program only need inc and zero

Body:
Here's one way to code y=Dec(x):

y=Zero();
z=Zero();
loop x times {
  loop z times {
    y=Inc(y);
  }
  z=Zero();
  z=Inc(z);
}


问:
Is a "build" assembly?
In an old book I have, they say that "build" is either a process of converting source code into executable or the actual result - assembly. Is that correct?

Is a build actually the assembly, I mean from terminological point of view.

答:
No, that statement isn't correct.

When you build a program the following steps happen:

The source files are compiled to object files
This takes your source code and turns it into object code. This step turns the source code into machine code.

The object files are linked to produce an executable
The linker will come along and link your various object files together, do any static linking it needs to and spit out the completed executable in machine code.

Assembly is a programming language which is not machine readable until it is "assembled" (aka compiled). When assembly is compiled it becomes machine code.

Edit based on Christopher's comment: If this book is specific to .NET then yes, the terminology could be considered correct as .NET executables are referred to as assemblies.

Title: Is a "build" assembly?


答:
If the book says so, then within that book, that is the meaning of the word. Obviously, in other contexts, the result of a build may not be anything usually called “assembly”, so the definition cannot apply there.

On a more general note, I don't find it odd to ask if we still have a backup of last Friday's build, so I'd say the usage of the word for the result of the build process is not entirely non-standard. English is full of words you can use as verbs or nouns, with more or less related meanings.

Title: Is a "build" assembly?

Body:
In an old book I have, they say that "build" is either a process of converting source code into executable or the actual result - assembly. Is that correct?

Is a build actually the assembly, I mean from terminological point of view.


问:
What is the best practice for method parameter validation in a library?
I develop a game library in javascript, containing many classes. I hesitate on the behavior that I should follow concerning method parameter validation:

Should I check the validity of parameters passed to each method ?

By example, when a method take only a number between 0 and 100 in parameter, should I check that the value is correct?

I have dozens of classes, each with dozens of methods. For a simple getter, I can have more than half lines code only used for checking parameters. Add checks makes my code less maintainable, more heavy.

Seeing that it's a library, destined to be used by many other programmers, checking parameters can avoid many mistakes and bugs, and would be a appreciated.

So, how do other javascript libraries, handle this and what is the best solution?

答:
Yes, you should always validate your inputs. Not validating is one of the primary sources of unexpected behaviour.

Without knowing the structure of your code, if you have a bunch of simple methods and one core method you could put your validation code in the main method rather than all of the individual ones.

As you say it is a library, developers will do their own validation based on their business logic. Their business logic may be different from yours.

A quick flick through the jQuery source sees them validating input parameters.


问:
Commercial software license with free upgrade clause
If I am selling software commercially and I offer users free upgrade for 12 months after purchase, can I make them agree to a new licence when they download an upgrade?

What should the original license say in order to stipulate this?

And if I can do this, then wouldn't it be possible to put in the new license that they are no longer entitled to free upgrades (being the devil's advocate here)?

答:
I'm not going to give you legal advice - see a lawyer - they will tell you what you can and cannot write, and they will also write it correctly.

In terms of having them agree to the license, yes, you can have them do that prior to installation and this is entirely normal on some platforms (i.e. Windows) when you install software.

You can modify licenses as need be; services such as iTunes are constantly changing their terms of use, and Office 2013 has a different license to 2010.

The wording of your licensing depends on what you can do. For example, if you say "free upgrades for life" then that forms a binding contract on you; however were you to say "free upgrades for life unless withdrawn earlier" then that is a different story.


问:
Should I / can I bundle node.js and mongod together with my application?
I'm working on a web application that runs on node.js and uses MongoDB. It's important to mention that I plan to release the application as commercial software. The way I wrote the installer, it asks the user to confirm the location of the node and mongod binaries (after autodetecting first). I figured I could skip this step altogether by bundling said binaries together with my application or making the installer download them, but there are a few issues I need to address:

First and foremost, the licensing issue. The friendly folks at 10gen
(the company that develops MongoDB) answered an email I sent them
and told me their license allows this, and from what I can figure
out, this is the case with node.js too. Are there any problems I
should keep an eye out for?

Is it worth (from the user's point of view) fetching ~20MB of extra data during installation just for the convenience of not having to manually install node.js and mongod (the MongoDB server binary)?

Should I expect any problems if I bundle the 32-bit binaries and the user installs the application on a 64-bit machine?

答:
Bandwidth is cheap. Time is not. I would suggest that if you are selling your software that you have the process as automated as possible, asking as few questions as possible, and have it "just work". Given this, 20mb isn't a lot and you're really looking at 20 seconds or less for most broadband connections. at least in my country.

Bundling the software also ensures that you distribute the version you've done your testing on so if node.js is 3 versions ahead in 5 years time, and there are breaking changes, you won't be having support issues.

Think about it from a users perspective. If you can get one package, that contains everything you need for something you bought, or you can get the software but then need to go find the dependencies online, you'd be frustrated.

If 10gen have said it's ok, and you have that in writing, you shouldn't have any problems. Node is MIT-licensed so I doubt there would be problems there. Also bare in mind most software that is designed to operate as a service, runtime or component does come with a redistribution policy and this is normal.

If you're always able to provide the files then you could go down this path, as I said above bandwidth is cheap. You might have more luck bundling the required files for a few reasons: offline installation, and in case your server goes down / you decide to stop selling software / etc.

You should install the correct architecture for the CPU, although there is unlikely to be problems.


问:
Architecting an application with a single page javascript driven UI
I have a single page application where everything in the UI is javascript driven so any operation requiring data or updating of data is done via Ajax requests. The way things are setup right now is that my Ajax called are made to one ajax.php file which takes care of routing them to the proper service method. This works well but there's one problem. Whenever I have operations that require a user ID, I don't want to pass them as part of an ajax request so as to prevent tampering. Since I have a session running server-side, I have a Security service from which I can retrieve the user ID of the user currently logged in. The security does so by using a Session object that abstracts the access to the session (in my case, $_SESSION in PHP) implementing an interface. My security service gets injected into other services as needed, so for example, if I have a PostService->findUserPosts() method, that method uses the getUserId() method of the injected SecurityService object to figure out the user ID instead of having it passed as an argument.

The problem is I suspect (and others seem to agree) that not passing in the user ID to the service is bad design. But how do I get around doing that without sending the user ID via ajax? I can think of a few options, none of which I really like or know of a good way to implement:

1) Add a controller layer on the server side, in which case I can call SecurityService->getUserId() in the controller and pass in a separate call to PostService->findUserPosts($userId); the problem with this approach is that it requires me to add a bunch of controllers that are for the most part pretty redundant. As it is, I already a PostService->findPosts() method that basically just calls PostGateway->findPosts(). I can live with that redundancy because there will be a lot of places where the service will need to do more. But adding a third layer with a controller with a findPosts() method, that seems too much of a pain.

2) Pass the user ID in the ajax request and come up with some kind of tampering mechanism to make sure the ajax request can't be altered. I could do that by hashing the URL string of my request and appending that as a parameter, and then on the server comparing the hash. This is more obfuscation than anything though, since the hash would need to be generated client side, which means somebody looking through the code could figure out how the hash is generated.

3) Keep things as they are, bearing in mind that my user ID is at least not hard coded and various implementations of the Session object could be used, that way the user ID can be retrieved in multiple ways, not tying me to the PHP $_SESSION object.

4) Use a hybrid method of #1 and the current setup where if I need to access session info I use a controller, otherwise I call the service directly. This could work, though it doesn't feel like a clean, unified approach.

I tried to figure this out with two separate questions dealing with separate smaller problems, but I think the lack of context made it difficult to answer, so figured I'd formulate a question with the entire problem. Suggestions are welcome. Suggestions are welcome. Or should I say, much needed!

UPDATE: maybe a valid compromise would be to have a PostService->findByUser($userId) method and then have a UserService->findPosts() method that gets the userId from SecurityService the same way PostService is doing now?

答:
I suggest what you do, rather than having user IDs visible at the client end, you implement a token.

It would work like this:

User logs on, you take note of this on the backend and generate a token which has an expiry

You return the token to the client (browser)

For each subsequent request, you pass the token to the server as a security assurance. For each successful call you increment the token expiry by +n minutes/hours or whatever is suitable for you. Before executing the service request you check to ensure the token is valid and has not expired.

When the user logs out, or the token expires, any subsequent service calls will fail.

My suggestion would be to require both a user ID and a token. The user ID is going to be useless without the token, and requiring the ID is going to give that little bit extra security against spoofing the tokens. Use PHPs uniqid function to generate a unique token as a starting point.


问:
Babysitting your Continuous Integration System
One of my roles in my team is the build person. I am responsible for maintaining/updating our build scripts and making sure we are building 'smoothly' on the continuous integration server. I usually do not mind this job, though often it feels like I am constantly babysitting the CI server.

This job can be annoying at times because if the build breaks I have to drop the story I am working on and investigate the build failure. Build failures happen daily on our team. Sometimes developers simply do not build locally before committing so tests fail on the CI server. In this situation I like to quickly get to the person who had the 'bad commit' so the build does not stay broken too long. Sometimes (a lot less frequently) a strange condition exists on the CI server that needs to be debugged.

I know that many mature teams use Continuous Integration but there is not a lot of material out there about good practices.

Do my problems point out that our continuous integration is not very mature or is this simply part of the job?

What are some good practices to follow? What are the characteristics of mature continuous integration?

Update

Instead of answering some comments I am going to make an update instead. We have a single, simple command that does exactly what the build server will do when building the app. It will compile, run all unit/integration and some quick UI based tests.

Reading everyone's answers, it feels we might have two major problems.

CI Server not complaining loud enough when a build fails.

Developers do not feel like its everyone's responsibility to make sure their commit goes through successfully.

What makes things harder in my team is that we have a large team (10+ developers) AND we have a couple of off-shore team members committing when we are not even at work. Because the team is large and we established that frequent, small commits are preferred, we sometimes have really a lot of activity in a day.

答: I am going to break with the chorus here, and say that actually, breaking the build occasionally is not such a bad thing, as it shows that actual work is being done. Yes, developers should build and test before they commit, but the main burden of testing should be borne by the development automation tools, including the continuous integration server. The tools are there to be used, and unless the build breaks now and again, then it is not clear that you are pushing as hard as you could. I do, however, think that the build should never ever remain broken for any significant length of time, and would even favour automatic rollbacks or a multi stage commit process if that helps support the twin objectives of quick feedback from centralised, automated test facilities, plus a "green" trunk.</p>


问:
implement cons function in Java - type safety question
I am working on a small functional library written in Java, which mimics the a functional style of programming. I am stuck with a undesirable type cast in one of my method definitions and would love some help.

Ok, so we do not have first class functions in Java, so I define them as objects, with one method 'apply()' like so:

```<code>public abstract class Function2<R,T1,T2> {
    public abstract R apply(final T1 paramOne, final T2 paramTwo);
}
</code>```

I then define my cons method as a Function2 object, which I can pass around like I would a function in another language that supports it:

```<code>public static <T> Function2<List<T>, T, List<T>> cons(){
    return new Function2<List<T>, T, List<T>>(){
        @Override
        public List<T> apply(T x, List<T> xs) {
            return new NonEmptyList<T>(x, xs);
        }
      };
    }
</code>```

I have omitted my list structure for brevity; assume it is a functional style list data structure with all the usual head/tail/etc. operations.

I then want to implement a function like 'reverse', which returns a list of items in reverse order. I use foldl1 (fold a non empty list from the left) to achieve this, and pass the cons function as a parameter to foldl1 like so:

```<code>public static <T> List<T> foldl( Function2<List<T>, T, List<T>> f,
                                 List<T> acc,
                                 List<T> xs ){
    if(xs.isEmpty()){ return acc; }
    return foldl(f, (f.apply(xs.head(), acc)), xs.tail());
}

public static <T> List<T> reverse(List<T> xs){
    // how do I avoid this cast??
    return foldl( (Function2) cons(), new EmptyList(), xs);
}
</code>```

But when I pass my 'cons()' object in 'reverse', I need to cast it as a Function2, and I have no idea how to avoid doing this. I have tried all manner of messing around with types...I feel this is simply a lack of experience on my part with the Java type system...anyone?

PS. I am aware of other functional libraries in Java, I just wanted to do my own small one as a learning experience.

EDIT - OK, so I am using a regular 'foldl' now to get back a List, but I still have to perform the cast? The return type of 'cons' align with 'foldl'...

答:
The reason that you can't pass cons as an argument to foldl1 without casting is that the type of cons simply does not match that of foldl1's function argument and your cast is in fact illegal - but, sadly, unchecked, so you don't get an exception right away (you will get one eventually though).

You've defined foldl1 to take a function that takes two arguments of the same type and cons doesn't do that. cons takes a T and a list of Ts. When foldl1 first calls cons, it will call it with the list's first and second elements as arguments. Since neither of those is a list, this will cause a ClassCastException to be thrown.

So cons is simply not a valid argument for foldl1. Not only is there no way to avoid the cast, there's also no way to make the cast actually work.

Another reason that you can't use foldl1 to reverse a list is its return type: foldl1 returns a T where T is the element type of the list you're calling it on. So if you use foldl1 on a list of Ts, the result will be a T. But clearly the result of reversing a list of Ts should be another list of Ts, not a plain T.

If you want to reverse a list using a fold and cons, you'll need to define it in terms of foldl, not foldl1. foldl allows for the result type to be different from the element type of the list and it allows you to use something other than the first element of the list as the starting value of the accumulator (which you need because, as I said, the accumulator needs to be a list).


问:
Is Agile the new micromanagement?
This question has been cooking in my head for a while so I wanted to ask those who are following agile/scrum practices in their development environments.

My company has finally ventured into incorporating agile practices and has started out with a team of four developers in an agile group on a trial basis. It has been four months with three iterations, and they continue to do it without going fully agile for the rest of us. This is due to the fact that middle management is entrusted to meet business requirements with quite a bit of ad hoc requests from upper management.

Recently, I talked to the developers who are part of this initiative; they tell me that it's not fun. They are not allowed to talk to other developers.  Their Scrum master enforces this restriction. And they are not allowed to take any non-business-related phone calls in the work area. For example, if I want to talk to my friend, who is in the agile team, just for kicks -- I am not allowed without the approval of the Scrum master; who is sitting right next to the agile team.

The idea of all this (or the agile, in general) is to provide a complete vacuum for agile developers from any interruptions, and to have them put in good 6+ productive hours. Well, guys, I am no agile guru but what I have read Yahoo agile rollout document and similar for other organizations, it gives me a feeling that agile is not cheap. It require resources and budget to instill agile into the teams and correct issue as they arrive to put them back on track.

For starters, it requires training for developers and coaching for managers and etc, etc... The current Scrum master was a manager who took a couple days agile training class paid by the management is now leading this agile team. I have also heard in the meeting that agile manifesto doesn't dictate that agile is not set in stone, and is customized differently for each company. Well, it all sounds good and reasonable.

In conclusion, I always thought the agile was supposed to bring harmony in the development teams which results in happy developers. However, I am getting the very opposite feeling when talking to the developers in the agile team. They are unhappy that they cannot talk about anything but work, sitting quietly all day just working, and they feel it's just another way for management to make them work more.

Tell me please, if this is one of the examples of good practices used for the purpose of selfish advantage for more dollars? Or maybe it's just us, the developers like me and this agile team, which feels that they don't like to work in an environment where they only breathe work while they're at work.

It's a company in the healthcare domain that has offices across the US. It definitely feels like a cowboy style agile, which makes me really not want to go for agile at all, especially at my current company.

All of it has to do with the management being completely cheap. Cutting out expensive coffee for a cheaper version, emphasis on savings and being productive while staying as lean as possible.

My feeling is that someone in the management behind closed doors threw out this idea: agile makes you produce more, so we can show our bosses we're producing more with the same headcount. Or, maybe, it will allow us to reduce headcount if that's the case.

They are having their 5 min daily meeting. But not allowed to chat or talk with someone outside of their team. All focus is on work.

答:
Original Author Smith Janes might have given experience.
But these are the typical problems I found in Agile project.

Most of the organizations, developers are supposed to work in multiple project, in Agile/scrum.. Sprints are never considered this fact. your Scrum Master assumes you should be done with your stories at the end of the sprint.. Your Scrum master might be dedicated to only one project, but not the developers..
THIS IS THE DISTRACTION-- need not be just taking a phone call or allowing a phone call.

I have seen Agile projects where Sprint is planned, Stories included in Sprint, without being huddled..at the half way or middle of the sprints.. developers finding dependencies not resolved, requirements or story is not completed narrated..... This is one of the Abuse in most agile projects.

Testing : TTD.. yes it is very good.. but I have seen most of the Agile projects totally relying on TTD... no scope or time allowed for Functional or Human testing.. Another Abuse... Lot of Scrum Masters also do not know or understand the importance of Functional testing.
Your piece of code might be working perfect, if does not serves the business need.. it is of no use.. This happens when business do not participate well ahead.. or participation is there... but not reflecting the business decision making..
At the end, developers are blamed, you did not deliver the functionality..or it will end up with last minute change... extra long hours because your Scrum master do not want to take blame for story not completed.

Abuse here... either low participation of business or participant not fully knowledgeable or business person dropping out in middle of sprint.

Not All projects are suitable for Agile ... Most of the managers or scrum masters do not know this.. Maintenance projects .. A defect might be initially assumed can be done in 8 hours, accepted in the sprint. After spending 4 hrs, found this is Java/another product... (I recently faced dealing defect related to Quartz Scheduler..inside our project) and this defect could lead to upgrading of product/package..deal with bureaucracy,approval,funding, new version or upgrade should be approved by Internal Engineering etc.,
5.Retrospection : only handful of Agile projects does this step.. If at all done..Management, Scrum Master never taken any responsibility of the failed stories..

Pairing .. Lot of developers treats pairing as venue to abuse co-workers.. criticize other design, coding practices.. rater treating as team work., learn from each other... Another way of Abusing Agile/Scrum.

Agile is definitely good methodology.. Unless your organization does not follow completely or not trained.... It is Abused.... side effects 60+ work hours/week, blame game, low moral.

OwnerDisplayName: Smith James

ContentLicense: CC BY-SA 4.0

Title: Is Agile the new micromanagement?


问:
What's a nice explanation for pointers?
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.

答:
http://cslibrary.stanford.edu/

This site has great tutorials for learning pointers and memory management .

I would suggest you to walk through pointers basics, pointers and memory given on the site.
You can also look at linked lists problems given on the link to further strengthen the pointer concepts.

Title: What's a nice explanation for pointers?


问:
Entropy in large scale software systems
I work on a fairly large software system and over the years it has accumulated a lot of entropy. There is plenty of scope for refactoring but there is always pressures to build the next features upon what's already there. This adds to more entropy, because design choices for implementing new features are typically made by first accepting what's there and 'working-around' some earlier weaker design that is otherwise ripe for refactoring.

What are some ways to manage this kind of complexity and build functionality without substantially weakening the structure of the system further. I know this is a very broad question and the approaches/solutions depend on the particular software system at hand, but I am still hoping there are some generic ways to manage the problem I am highlighting.

答:
I must say I don't really like the unit testing, and I still see it as a partial patch which doesn't fix good design, technical debt or any of the multi-threading issues. But, I think that the unit testing might be the only way to fix the issue.

After things get really bad, only the unit tests can help to get stuff under control.

Or a rewrite with skilled developers, but that will loose features, some of which might be bugs that customers perceive as features.

Title: Entropy in large scale software systems


答:
I went through this stuff earlier, and finally gave up on it, because even the types of simple functions like fold and map were so complicated that it makes programming with them in Java no fun.

But the real pain starts when you need higher kinded types, like that of fmap.

```<code>fmap :: Functor f => (a -> b) -> f a -> f b
</code>```

That is, if you not only want to abstract over the element type (of a list, say), but also about the container (Functor) type, symbolized by f above.

Btw, it is funny: as long as one does not do functional programming, such a need for higher kinded types does never arise, perhaps because one does not even have higher order functions. But when you have them, you realize quite soon that you now want to go a step further. In this regard, it will be interesting to see how Java 8 fares. With the lambda functions, they satisfy a long awaited need, but I am not sure they know they will open Pandoras's box. But higher kinded types would require a substantial rewrite of the Java type system ... or so I think.

Title: implement cons function in Java - type safety question

Body:
I am working on a small functional library written in Java, which mimics the a functional style of programming. I am stuck with a undesirable type cast in one of my method definitions and would love some help.

Ok, so we do not have first class functions in Java, so I define them as objects, with one method 'apply()' like so:

```<code>public abstract class Function2<R,T1,T2> {
    public abstract R apply(final T1 paramOne, final T2 paramTwo);
}
</code>```

I then define my cons method as a Function2 object, which I can pass around like I would a function in another language that supports it:

```<code>public static <T> Function2<List<T>, T, List<T>> cons(){
    return new Function2<List<T>, T, List<T>>(){
        @Override
        public List<T> apply(T x, List<T> xs) {
            return new NonEmptyList<T>(x, xs);
        }
      };
    }
</code>```

I have omitted my list structure for brevity; assume it is a functional style list data structure with all the usual head/tail/etc. operations.

I then want to implement a function like 'reverse', which returns a list of items in reverse order. I use foldl1 (fold a non empty list from the left) to achieve this, and pass the cons function as a parameter to foldl1 like so:

```<code>public static <T> List<T> foldl( Function2<List<T>, T, List<T>> f,
                                 List<T> acc,
                                 List<T> xs ){
    if(xs.isEmpty()){ return acc; }
    return foldl(f, (f.apply(xs.head(), acc)), xs.tail());
}

public static <T> List<T> reverse(List<T> xs){
    // how do I avoid this cast??
    return foldl( (Function2) cons(), new EmptyList(), xs);
}
</code>```

But when I pass my 'cons()' object in 'reverse', I need to cast it as a Function2, and I have no idea how to avoid doing this. I have tried all manner of messing around with types...I feel this is simply a lack of experience on my part with the Java type system...anyone?

PS. I am aware of other functional libraries in Java, I just wanted to do my own small one as a learning experience.

EDIT - OK, so I am using a regular 'foldl' now to get back a List, but I still have to perform the cast? The return type of 'cons' align with 'foldl'...

Body:
I went through this stuff earlier, and finally gave up on it, because even the types of simple functions like fold and map were so complicated that it makes programming with them in Java no fun.

But the real pain starts when you need higher kinded types, like that of fmap.

fmap :: Functor f => (a -> b) -> f a -> f b

That is, if you not only want to abstract over the element type (of a list, say), but also about the container (Functor) type, symbolized by f above.

Btw, it is funny: as long as one does not do functional programming, such a need for higher kinded types does never arise, perhaps because one does not even have higher order functions. But when you have them, you realize quite soon that you now want to go a step further. In this regard, it will be interesting to see how Java 8 fares. With the lambda functions, they satisfy a long awaited need, but I am not sure they know they will open Pandoras's box. But higher kinded types would require a substantial rewrite of the Java type system ... or so I think.


答:
You need apply Separation of Concerns principle in order to separate the system in modules which only communicate between each other other via very well defined interfaces. This greatly reduces complexity due to many reasons:

Some can work on a part of the project without understanding the other parts;

You can easily improve the system by adding another module;

Loose coupling - the modules are only connected by interfaces;

High cohesion - the data from a module is used in almost all the parts of that module.

Title: Entropy in large scale software systems

Body:
I work on a fairly large software system and over the years it has accumulated a lot of entropy. There is plenty of scope for refactoring but there is always pressures to build the next features upon what's already there. This adds to more entropy, because design choices for implementing new features are typically made by first accepting what's there and 'working-around' some earlier weaker design that is otherwise ripe for refactoring.

What are some ways to manage this kind of complexity and build functionality without substantially weakening the structure of the system further. I know this is a very broad question and the approaches/solutions depend on the particular software system at hand, but I am still hoping there are some generic ways to manage the problem I am highlighting.