问:
Finding an A* heuristic for a directed graph
In a previous question, I asked about finding a route (or path if you will) in a city. That is all dandy. The solution I chose was with the A* algorithm, which really seems to suit my needs. What I find puzzling is heuristic. How do I find one in an environment without constant distance between 2 nodes? Meaning, not every 2 nodes have the same distance between them.

What I have is nodes (junctures), streets with weight (which may also be one-way), a start/finish node (since the start and end is always in the same place) and a goal node. In an ordinary case, I would just use the same way I got to goal to go back, but since one of the streets could have been a one-way, that may not be possible.

The main question

How do I find a heuristic in a directed graph?

答:
The case of one-way streets doesn't necessarily change the heuristic. You should just not generate invalid routes in the A* algorithm itself. I.e., in terms of the Wikipedia pseudocode,

```<code>neighbor_nodes(current)
</code>```

should only generate nodes (junctions) that can actually be reached by one step from current and not try to traverse a one-way street in the wrong direction.

The A* heuristic function, however, should be an underestimate of the distance to the goal, and assuming that one-way streets can be traversed both ways will give you exactly that.

(You might be able to take one-way streets into account in a smarter heuristic, but you don't need to.)

Body:
The case of one-way streets doesn't necessarily change the heuristic. You should just not generate invalid routes in the A* algorithm itself. I.e., in terms of the Wikipedia pseudocode,

neighbor_nodes(current)

should only generate nodes (junctions) that can actually be reached by one step from current and not try to traverse a one-way street in the wrong direction.

The A* heuristic function, however, should be an underestimate of the distance to the goal, and assuming that one-way streets can be traversed both ways will give you exactly that.

(You might be able to take one-way streets into account in a smarter heuristic, but you don't need to.)


问:
Algorithm to minimize distance variance between 2D coordinates
I've been looking around for an algorithm that would optimize the distance between 2 list of coordinates and choose which coordinate should go together.

Say I have List 1:

```<code>205|200
220|210
200|220
200|180
</code>```

List 2:

```<code>210|200
207|190
230|200
234|190
</code>```

Calculated Distance between Coords:

```<code>205|200 to 210|200 == 5.00
205|200 to 207|190 == 10.20
205|200 to 230|200 == 25.00
205|200 to 234|190 == 30.68

220|210 to 210|200 == 14.14
220|210 to 207|190 == 23.85
220|210 to 230|200 == 14.14
220|210 to 234|190 == 24.41

200|220 to 210|200 == 22.36
200|220 to 207|190 == 30.81
200|220 to 230|200 == 36.06
200|220 to 234|190 == 45.34

200|180 to 210|200 == 22.36
200|180 to 207|190 == 12.21
200|180 to 230|200 == 36.06
200|180 to 234|190 == 35.44
</code>```

This Algorithm would pick:

```<code>205|200 to 230|200 == 25.00
220|210 to 207|190 == 23.85
200|220 to 210|200 == 22.36
200|180 to 234|190 == 35.44
</code>```

The Algorithm would pick these numbers as they would be the group that would have the littlest variance between the distance.
Conditions:

A Coordinate may only be used ones from each list

If List 1 or List2 is larger than it still only uses each coordinate once, but it tries to get the smallest distance variance and does nothing with the unused coordinates.

If you need more clarification please ask.

P.S. I've looked at the Hungarian algorithm and it seems like it will sort of do the job, but not exactly how I was expecting. The Hungarian algorithm will only try and make the least distance from all the coordinates, which can mean the smallest variance, but not every time as variance is more important here then least distance optimization.

Additional Information

I will have an array of List1, List2, and then the distances:

```<code>Distance[List1_item_0][List2_item_0] = 5;
Distance[List1_item_0][List2_item_1] = 10.20;
Distance[List1_item_0][List2_item_2] = 25.00;
Distance[List1_item_0][List2_item_3] = 30.68;

Distance[List1_item_1][List2_item_0] = 14.14;
Distance[List1_item_1][List2_item_1] = 23.85;
Distance[List1_item_1][List2_item_2] = 14.14;
Distance[List1_item_1][List2_item_3] = 24.41;

Distance[List1_item_2][List2_item_0] = 22.36;
Distance[List1_item_2][List2_item_1] = 30.81;
Distance[List1_item_2][List2_item_2] = 36.06;
Distance[List1_item_2][List2_item_3] = 45.34;

Distance[List1_item_3][List2_item_0] = 22.36;
Distance[List1_item_3][List2_item_1] = 12.21;
Distance[List1_item_3][List2_item_2] = 36.06;
Distance[List1_item_3][List2_item_3] = 35.44;
</code>```

From the Distance['List1_item_#] I would need to pick a distance. Once that distance is picked the [List2_item_#] CANNOT be picked by a different [List1_item_#]. The distances picked for each [List1_item_#] element would need to be picked in a way that the variance between them all is minimal. So distance for each [List1_item_#] should be as close as possible to each other without reusing a [List2_item_#] more than once.

答:
For small lists, you can try to run a full-search, applying some branch-and-bound algorithm.

If you have list sizes where this cannot be applied any more since the running time will exceed your available time, you need some discrete optimization algorithm like simulated annealing or tabu search to find a good (perhaps not the globally best) solution. Here is a free online-book dealing with a lot of global optimization algorithms, hope this helps:

http://www.it-weise.de/projects/book.pdf

ContentLicense: CC BY-SA 3.0


问:
Was classical BASIC ever used for commercial software development, and if so, how were limitations overcome?
Many of us, including me, started their programming life with programs written on home computers, something like

```<code>10 PRINT "ENTER RADIUS"
20 INPUT R
30 PRINT "CIRCUMFERENCE="; 2 * R * PI
40 PRINT "AGAIN?"
50 INPUT A$
60 IF A$="Y" THEN GOTO 10
70 END
</code>```

Of course, the line-number based BASIC was prone for creating spagetti code, also because most BASIC dialects missed structural statements like WHILE, doing everything but the FOR-loop with IF, GOTO and GOSUB. I'm talking about BASIC dialects before 1991, when QBASIC and Visual Basic appeared.

While BASIC dialects may have promoted bad style amongst aspiring programmers, were there larger commercial projects created in such a BASIC dialect? If so, how did they manage to live with and workaround the obvious shortcomings?

By "serious", I mean:

Not a game (I know some commercial games were written in BASIC, for example, Pimania)

Not freeware

Not trivial, that is, reasonably large (say: at least 1500 LOC)

Sold to several customers (not an in-house development)

"Mission critical" is a plus

答:
IBM's hugely popular 4680/4690 retail point of sale system was written in a
dialect called IBM 4680 BASIC. I worked on this system from 1998-2002 for a major UK retailer.

This system was very popular, according to the wiki article it still held 12% of market share in 2005. The system is still going strong today, odds are good that most people in the western world have indirectly used this BASIC powered system in the last week.


问:
How much documentation is enough?
How much technical (for future developers) documentation is enough? Is there a ratio between hours coding and hours documenting that's appropriate?

Papadimoulis argues that you should

produce the least amount of documentation needed to facilitate the most understanding,

Is that a good guideline, or are there specific things I should be creating?

答:
I've been thinking about this topic for a while.

My conclusion is - it's not a matter of quantity, but of quality and context.

For example, a proper project structure beats comments explaining where the files are located (implementation vs. intension)

Similarily, classification to clarify context beats naming (Id on a Patient -> Patient.Id).

I believe DDD has a say in good documentation - classification provides context, context creates boundaries and boundaries lead to intentional implementations (this is where this belongs, rather than it needs to exist).

Code in itself isn't good enough to be considered documentation. The problem in most cases doesn't reside in the fact that the codes' working is commented or not commented, but rather the driving force (domain logic) isn't.

We sometimes forget who's boss - if the code changes, the domain logic or reasoning shouldn't, but if the domain logic or reasoning changes the code definitely will.

Consistency is very important also - convention by itself is useless if it isn't consistent.

Design patterns aren't just 'good practice' - it's lingo us developers should understand. Telling a developer to add a new type to a Factory is better understood than to add a new type to a method (where context and consistency is weak or missing).

Half the struggle is familiarity.

On a side note, API's which seem to favor a lot of documentation are also very domain and context sensitive. Sometimes duplicating functionality isn't evil (same thing, different contexts) and should be treated as separate.

In terms of commenting, it's always good to point out the domain logic behind the reasoning.

For example, you are working in the medical industry.
In your method you write "IsPatientSecure = true;"

Now, any decent programmer can figure out that the patient is being marked as secure. But why? What are the implications?

In this case the patient is an inmate that was transferred securely to an off premises hospital. Knowing this, it is easier to imagine the events that lead up to this point (and perhaps what still needs to happen).

Maybe this post seems philosophical at best - but remember that it is 'reasoning' or 'logic' that you are writing about - not code.

ContentLicense: CC BY-SA 2.5

Title: How much documentation is enough?


问:
How to implement a system to hide spammed user content?
I'm trying to work out a good way to manage user submitted content and create a method to determine when spammed/poor content should be hidden.

The aim is to create comment voting similar to youtubes like/dislike comments and if the score is good show the comments, else they're invisible.

Approach

My thought is to do this via the comments table, you could create two columns rateup, ratedown.

For each rate up the comment gets the rateup colulmn is: rateup = rateup + 1

and the same for the ratedown: ratedown = ratedown + 1

You can then put a clause into your database query to only select comments if their rateup ratio is greater than a number, say -5:

```<code>WHERE (rateup - ratedown) > -5
</code>```

but this would need a lot of voting up and down if a user posts many spam/poor content posts over the site?

To strengthen the approach I could add the same two columns to the user table and also update these columns to give an overlal view of the users combined content submission ratio and then display comments like so:

```<code>WHERE ((comment.rateup - comment.ratedown) > -5 ) && ((user.rateup - user.ratedown) > -5 )
</code>```

Issues

Would this approach lead to instances of users creating mass fake accounts to attack good users and ruin their reputation?

What other methods could I use to help hide spammed/poor content without moderators having to manually go through everything?

答:
I think your problem needs to be split in 3 sub-problems:

1) rating the user-submitted content

2) avoid people "cheating the algorithm"

3) spam detection

Solutions:

1) Simply subtracting upvotes and downvotes won't help much. For example, if a few people downvote it as the content gets out, it will be quickly hidden - other people will have no chance to upvote it. You could prevent this setting a minimum amount of votes, but this brings to another problem:
Content with 1 upvote and 6 downvotes has a total of -5. Content with 1000 upvotes and 1005 downvotes also has a total of -5, but its ratio is more balanced, and although it's probably something controversial, you might not want to hide that. This is an article I have found on how to rank entities: http://evanmiller.org/how-not-to-sort-by-average-rating.html . Probably the article goes in a direction that you don't really want to take, but it might help your decision.

2) You would need some kind of system that detects "vote fraud". I would suggest you to look into Support Vector Machines, or Artificial Neural Networks. You will need to identify patterns in the voting that are not natural. (IP blocking can be done without SVM or ANN, but that might not be enough)

3) Although I really like the Neural Network answer, probably is not really feasible due to the huge amount of data you'd need to train it. The organisation behind Wordpress, (most likely) already trained some machine learning algorithm for you: http://akismet.com/ . It is a popular anti-spam service, and it works pretty well

Hope this helps


答:
As little as possible, but as much as is necessary

I can't remember where & when I first heard that, but it's a maxim with many applications.

The more complex the technology or the application, the more documentation would be needed (obviously), but clearly you don't want to waste time going overboard.

JohnFx's 'hallway test' is sound. But trust yourself; you developed the code, and so you of all people should have a feel for the elements that need extra attention, and the elements that will be obvious to all. Think of the struggles you had developing the code and you'll likely have an idea what another developer will see when they look at your code.

Forget any relationship between effort spent coding and effort spent documenting.

Title: How much documentation is enough?

Body:
How much technical (for future developers) documentation is enough? Is there a ratio between hours coding and hours documenting that's appropriate?

Papadimoulis argues that you should

produce the least amount of documentation needed to facilitate the most understanding,

Is that a good guideline, or are there specific things I should be creating?


问:
How to make sure the application source code has a proper documentation for new programmers?

Possible Duplicate:

  How much documentation is enough?

Do you know how the big IT company like IBM, Microsoft, or google make sure their application source code has proper documentation for future new programmers? What are their methods or tecniques? Do they tell the programmers to write documentation or hire a specialized technical writer to do that? Is the documenation in a separate file or in the source code itself (in form of annotation/comment)? Or is it another method that I don't know?

I ask that because in my experience, I see most of the IT companies (in my country) are very lazy to impose the application-documentation-writing culture. So the problem always happens when a new programmer comes in, he will always face a situation where he is told to read and learn big chunks of source code with no documentation. Of course, he can ask the senior programmers to explain him, but sometimes the senior programmers are too busy with their works so they reluctantly want to help you, and sometimes it could be worse that the only one programmers that understand the code has already resigned. So you are left alone with the source code :(.

Somehow I can understand the laziness of programmer to write comment or documentation, because the programmer's jobs are already arduous and tedious with their coding and testing sessions. Not mention the deadline-bell or angry boss that always haunting behind them. I can't imagine how painful and tiring for the programmer when after their long session of code-typing, they have to type again for the documentation.

For technical writers, I never had a experience with them. I doubt how technical writer can be useful, because the one who fully understand the source code is the programmer himself. In that case, the programmer must accompany the tecnical writer to explain the source code.

Note: I'm talking about source code or application development documentation, not the user documentation/guide which I think it's more properly written by system analyst or business analyst. The development documentation usually contains technical information about the development of the application such as: application features, class/function reference, class relationship diagram, database information, network information, etc. While user documentation is more about application's how-to information for the end-users.

答:
Unfortunately, there is no way to "properly" document source code. Here are the main reasons:

What do you know? If you're an apprentice, you'll need much more detailed documentation than, say, someone with 70K on stackoverflow and a gold java badge. How can you know in advance what someone starting at your company will know and what you need to explain in the documentation?

How do you keep documentation and code in sync? Code is verified in many ways: Unit tests, code reviews, running it in production. If the documentation is wrong, someone has to read it and notice. This means docs age much faster than code and people quickly start to distrust and ignore it which makes it age even faster.

When do you document? Early? That raises the chance that the documentation lies (see the previous point). Late? Raises the chance that it's not done - ever.

What do you document? The 10'000 feet bird eyes view? Most useful and has the biggest chance to stay useful over time but useless most of the time - say when you hunt a bug.

Why do you document? Just to make the management happy? What do they know? Or do you need to document because the code is so bad? How about writing readable code instead?

I had some hopes with intentional programming but that didn't work out yet.

My current approach, based on 25+ years of experience, is to write readable code in the first place and put documentation efforts into the unit tests:

The unit tests can't lie

They must be simple (4-10 lines of code)

They explain each feature of the code one after the other

They are quick to run (rule in our company is that all unit tests must run in less than 10s)

People starting at our company can run in the debugger with 2-3 mouse clicks and see how the code works.

The biggest advantage: You need to write unit tests anyway. Why not use them for documentation purposes, too?


问:
When to do code reviews when doing continuous integration?
We are trying to switch to a continuous integration environment but are not sure when to do code reviews. From what I've read of continuous integration, we should be attempting to check in code as often as multiple times a day.  I assume, this even means for features that are not yet complete.

So the question is, when do we do the code reviews?

We can't do it before we check in the code, because that would slow down the process where we will not be able to do daily checkins, let alone multiple checkins per day.

Also, if the code we are checking in merely compiles but is not feature complete, doing a code review then is pointless, as most code reviews are best done as the feature is finalized.  Does this mean we should do code reviews when a feature is completed, but that unreviewed code will get into the repository?

答:
Set up pair programming?

All of the code is reviewed as it is being typed without extending the process or introducing another step.

OwnerDisplayName: SpecialEd


答:
I really-really-really think you would need a DVCS (e.g. mercurial, git) to do this naturally. With a CVCS you would need a branch and hope to whatever god you have there is no merging hell.

If you use a DVCS you can tier the integration process so that code already makes it reviewed before it arrives to the CI server. If you don't have a DVCS, well, the code will arrive your CI server before reviewed unless code-reviewers review the code on each developers' machine before they submit their changes.

A first way to do it, specially if you don't have repository management software that can help publish personal repositories (e.g. bitbucket, github, rhodecode), is to have hierarchical integration roles. In the following diagrams, you can have lieutenants review developers' work, and have the dictator as the main integrator reviewing how lieutenants merged the work.

Another way to do it if you have repository management software, is to use a workflow like the following:

Repository management software typically helps emit notifications when there is activity in repositories (e.g. email, rss) as well as allowing pull-requests. Code-review can organically happen during pull requests, as pull requests typically make people engage in conversations to have the code integrated. Take this public pull-request as example. The integration manager can actually not allow code to arrive to the blessed repository (aka "central repository") if the code needs to be corrected.

Most importantly, with a DVCS you can still support a centralized workflow, you don't need to have another fancy-awesome workflow if you don't want to... but with a DVCS you can separate a central development repository from the CI server and give someone the authority to push the changes from the dev repo to the CI repo once a code-review session has been done.

P.S.: Credit for the images go to git-scm.com

Title: When to do code reviews when doing continuous integration?

Body:
We are trying to switch to a continuous integration environment but are not sure when to do code reviews. From what I've read of continuous integration, we should be attempting to check in code as often as multiple times a day.  I assume, this even means for features that are not yet complete.

So the question is, when do we do the code reviews?

We can't do it before we check in the code, because that would slow down the process where we will not be able to do daily checkins, let alone multiple checkins per day.

Also, if the code we are checking in merely compiles but is not feature complete, doing a code review then is pointless, as most code reviews are best done as the feature is finalized.  Does this mean we should do code reviews when a feature is completed, but that unreviewed code will get into the repository?


答:
I believe you cannot put this into exact rules.  The reason for documenting is to provide the knowledge not easily gathered from the raw code in a form so others can understand and perhaps even maintain said raw code.

Hence the only way you can tell if you have documented enough, is to ask the target audience if it is good enough.  I believe the "peer review" process is very good at doing this up front.  Notice how much explaining is needed to make your peer understand what you are talking about, and work to minimize that.

If you have never done this before, you cannot estimate how much work it will take, but after a few iterations you will get a much better idea of how much is needed.

Title: How much documentation is enough?


答:
There was a company called Softek in India in the 80s that created their own versions of Wordstar, dBase and Lotus 1-2-3. Another of their products was a BASIC compiler.

Using their own CBASIC, they created a very comprehensive double entry accounting package called SIMS-FA (Softek Financial Accounting).

Title: Was classical BASIC ever used for commercial software development, and if so, how were limitations overcome?

Body:
Many of us, including me, started their programming life with programs written on home computers, something like

```<code>10 PRINT "ENTER RADIUS"
20 INPUT R
30 PRINT "CIRCUMFERENCE="; 2 * R * PI
40 PRINT "AGAIN?"
50 INPUT A$
60 IF A$="Y" THEN GOTO 10
70 END
</code>```

Of course, the line-number based BASIC was prone for creating spagetti code, also because most BASIC dialects missed structural statements like WHILE, doing everything but the FOR-loop with IF, GOTO and GOSUB. I'm talking about BASIC dialects before 1991, when QBASIC and Visual Basic appeared.

While BASIC dialects may have promoted bad style amongst aspiring programmers, were there larger commercial projects created in such a BASIC dialect? If so, how did they manage to live with and workaround the obvious shortcomings?

By "serious", I mean:

Not a game (I know some commercial games were written in BASIC, for example, Pimania)

Not freeware

Not trivial, that is, reasonably large (say: at least 1500 LOC)

Sold to several customers (not an in-house development)

"Mission critical" is a plus


问:
How do you handle database security from a desktop application?
For about 10 years I've worked on various in-house desktop client applications with SQL Server data stores.  Rarely did I start these projects - most are takeover work.

One thing that seemed constant everywhere was that there was a single global SQL Server user account that this application used that granted it permission to the common database, and yes in some naive situations it used the sa user account, which I generally tried to fix when possible.

You can't really effectively hide this username and password that the application uses to access the database.  They're usually stored in an ini or config file, or possibly baked into the executable itself.  In all cases, they're visible to the user if they do a little digging.  In one case we actually used a config file but encrypted it, but of course the encryption key had to be stored in the executable (we weren't naive to the limitations of this, but it did effectively stop people from poking around who were savvy enough to look in config files).

All of these systems had a user-authentication system built into the application, but of course they were all managed through the application itself, meaning the user information was stored in the database.  The application restricted what things you could do based on your access level, but it's all kind of moot if you can just connect to the database and run ad-hoc queries.

I'm interested to know what other systems do to get around this problem.  Here are the options I know of:

Use SQL Server's security mechanism to maintain a user and roles list, and make the desktop application add and remove users through T-SQL queries.

Instead of connecting directly to the database, create some kind of web service that runs on the server and put the authentication logic in there.  Make every request do security validation.

The first options is a bit ugly because you're separating users from the database so users are no longer first class entities and you can't reference them with foreign key relationships, etc.

The second just seems like a major performance problem, and a lot of extra work, plus you can't as easily use ORM mappers like NHibernate (I think).

Does anyone have experience with this?  Best practices?

Edit

Thinking a bit more, can SQL Server Authentication actually solve this problem?  For instance, if your user must be able to insert and update timesheet records so you can edit your timesheet, there's no way SQL server can disallow access to other rows in the timesheet details table, meaning you can read and write other people's timesheets too.

答:
I'm afraid adding a Web Service layer is probably the correct solution to your problem.

Separating the client from the underlying database implementation will probably help you in the long run too.

Adding a web service layer doesn't necessarily have to hurt performance...

Indeed, with an appropriate API, a web service can actually improve performance, by batching together multiple database queries within the data center LAN, rather than requiring multiple round trips over the WAN.

And of course a web service layer can often be scaled horizontally, and add appropriate caching to your database queries, perhaps even a change notification mechanism.

A server layer adds security that you cannot possibly ensure with apps running on a remote client. Anything that runs on a client can be "hacked" and should not really be considered in any way trusted. You should only really put presentation logic in the client, and host anything important on hardware you have complete control of.

I don't know about your apps, but my web apps are naturally split into several layers, with the presentation code separated from the persistence layer by at least one level of business logic that keeps the two apart. I find this makes it much easier to reason about my app, and so much faster to add or modify functionality. If the layers are separated anyway, it is relatively easy to keep the presentation layer in the client, and the rest on a server under my control.

So while you can solve your problems without introducing a "web service" layer, by the time you have written all the stored procedures (or equivalent) necessary to fill in the holes in the standard database security implementation, you would probably be better off writing a server-side application that you can write proper unit tests for.


问:
How do you deal with the anxiety of not knowing enough?
I just finished college a couple of months ago and I'm taking time out to improve my knowledge. I love programming but I feel like I don't know enough to be confident if I went for an interview. Last night I was browsing through questions and came across a question that asks interviewees how to work out a linked list. I learned these at college but if I was asked on the spot how to do it I wouldn't know. So that's another thing added to the list of what to learn.

This is when the anxiety hit me because I have so much to learn in so little time (at least it feels that way). Upon introspection, I think this anxiety is related to my perfectionism even though being perfect isn't rational e.g. Shakespeare and Einstein failed 80% of the time.

So the questions are, have you felt this anxiety of not knowing enough? If so, how did you deal with it? I suppose there's a point in time when you begin to feel comfortable in your abilities?

答:
90 % of programmers don't know they don't know stuff. So you are already in the top 10%.

The jobs that you will be going for are junior positions. The people looking at you don't expect you to know everything that they ask, if you did you would be a senior programmer. They aren't looking for an already knowledgable programmer, but one who has a grasp of the basics and is willing to learn.

So a third of the questions they will expect you to know, a third of the questions they expect you to not know, but have an idea what they are talking about and have a good try at answering. And the last third will be questions that try to figure out your personality, your learning ability, and willingness to learn. If you get the first third right, and show that you are enthusiastic about programming then you'll do alright.

Disclaimer: statistics are completely made up. :D


问:
How are functions called when passing ++
I don't understand what is passed to the function f() when I call it like this.

```<code>main()
{
  void f(int,int);
  int i=10;
  f(i,i++);
}

void f(int i,int j)
{ printf("%d %d",i,j); }
</code>```

gives me 11 10 .Can somebody explain why its 11?

答: The order of evaluation of function arguments is unspecified and so 11 10 is a correct possible output.


答: Because undefined behaviour, that's why. You read the value twice and modify it once with no intervening sequence point, which is a giant pile of illegal. Even if it were not illegal, the compiler has no obligation to evaluate your function arguments in any particular order, or indeed, to even evaluate one fully before evaluating another.</p>

Title: How are functions called when passing ++

Body:
I don't understand what is passed to the function f() when I call it like this.

```<code>main()
{
  void f(int,int);
  int i=10;
  f(i,i++);
}

void f(int i,int j)
{ printf("%d %d",i,j); }
</code>```

gives me 11 10 .Can somebody explain why its 11?


问:
Want to use a lib for my project, confused with license (AGPL vs MIT License)
Im working on a Java Software and there is a need to use some extern libraries. I found two relevant libs. The one is on an AGPL and the other on the MIT License. Now Im asking my self, can I use these libs if:

I would make a non-opensource-nonfree-software

or

I would make a non-opensource-free-software

I dont really understand the whole license stuff, could somebody tell me which one of the libs for what kind of software would be better? Thank you

答:
I think you can't go wrong with the MIT license, which is very permissive and pretty much allows you to do anything with the lib, as long as you include a copy of the license text. Your software can be closed-source and nonfree if you want.

I'm not sure about the Affero GPL, since I don't understand its provisions either. However, if its implications are like the GNU GPL's, then you cannot redistribute as nonfree, which wouldn't suit you.


问:
How fast should a web response be?
I've heard a few times that every extra [number1] milliseconds it takes to process a web request and return a response will lose you [number2] percent of users.  Is this just "conventional wisdom," or have there been actual studies on the subject?  And has there been found to be a lower bound to this phenomenon, like "[number3] milliseconds is fast enough, improving further than that won't hold any more users"?</p>

答:
You should read Jakob Nielsen thoughts on this topic.

http://www.useit.com/papers/responsetime.html

0.1 second is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is
  necessary except to display the result.

1.0 second is about the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay. Normally,
  no special feedback is necessary during delays of more than 0.1 but
  less than 1.0 second, but the user does lose the feeling of operating
  directly on the data.

10 seconds is about the limit for keeping the
  user's attention focused on the dialogue. For longer delays, users
  will want to perform other tasks while waiting for the computer to
  finish, so they should be given feedback indicating when the computer
  expects to be done. Feedback during the delay is especially important
  if the response time is likely to be highly variable, since users will
  then not know what to expect.

Title: How fast should a web response be?


问:
Can functional programming be used to develop a full enterprise application?
I am just beginning to learn Functional programming (FP). I come from a OOP world, where everything are objects, and most of them are mutable. I have a hard time wrapping around the concept that  functions don't have side effects.

If something is not mutable, how are common things objects like Employee or Person represented in FP.

Can FP be used to create a full fledged enterprise application?

答:
I don't think that it is necessarily the best idea. But it depends on the nature of the specific application.

I believe a lot in the philosophy of Eric Evans as described in his book, Domain-Driven Design, that you should make a domain model that is representation of the problem at hand that can help you solve your problem. Evans suggests finding a programming language that sits will with the particular problem at hand, e.g. he mentions Fortran as a way of solving problems of a mathematical nature. Or even creating specialized Domain-Specific languages for the problem at hand.

When you have succeeded in creating a good domain model, the you will find that the presentation code ends up being an thin shell on top of the domain layer.

Now the thing with enterprise application is that this type of application (if you can generalize about enterprise applications) often involves modifying state of entities of which identity is of importance, and persisting the modified entities in a database. This very generalized type of problem is IMHO a lot better solved by using en object oriented model than a functional model.

This doesn't mean that there are areas of an enterprise application that couldn't be better solved by a functional paradigm. For example a risk analysis module of a banking application, or a route planning module in a shipping application. And perhaps some enterprise applications could be implemented wholly using a functional paradigm.

But in general, I think that the object oriented paradigm allows creating more useful domain models for the majority of enterprise applications.

Edit

Due to some upvotes, my attention was drawn to this answer - and since I wrote it, I have learned a lot more about FP - and I am not entirely sure that I agree with my own answer anymore. Some functional languages can very nicely describe use cases. But you need to learn a completely different mind set.


答: Function Programming(FP) like Object Oriented Programming (OOP) are paradigms.  They represent different patterns or approaches to programming problems.  These different approaches do not obviate the ability to produce scalable, maintainable and extensible software.  That isn't to say the approaches are equivalent for all problems types; they aren't. Certain problems align themselves better (or worse) to particular paradigms, for example FP wouldn't be my first choice for a program which has a dependent sequence of operations with side effects.  However such programs can and have been written, and written well.</p>

Title: Can functional programming be used to develop a full enterprise application?

Body:
I am just beginning to learn Functional programming (FP). I come from a OOP world, where everything are objects, and most of them are mutable. I have a hard time wrapping around the concept that  functions don't have side effects.

If something is not mutable, how are common things objects like Employee or Person represented in FP.

Can FP be used to create a full fledged enterprise application?


答:
If you choose the AGPL licensed library, apparently you have no other choice than to relase your software as Open Source under the AGPL as well.

See these questions here at Programmers.SE for more information:

Using an AGPL 3.0-licensed library for extra functionality in an iOS app

AGPL - what you can do and what you can't

AGPL Question about Linking and Derivative Works

Of course you can't get binding legal advice from here, but the answers in the links above all sound pretty clear.

Given the fact that you have another available library to pick which is under the MIT license, this is a no-brainer: pick the MIT licensed library.

The MIT license is one of the most permissive open source licenses. As Andres F. already said in his answer, it allows basically everything.

Quote from Wikipedia:

It is a permissive free software license, meaning that it permits reuse within proprietary software provided all copies of the licensed software include a copy of the MIT License terms.

So you are allowed to use a MIT-licensed library in your software, no matter if your software is free / open source or not.

EDIT:

Concerning your question about GPL, see the GPL FAQ.

Quote from the link:

Does the GPL require that source code of modified versions be posted
  to the public?

The GPL does not
  require you to release your modified version, or any part of it. You
  are free to make modifications and use them privately, without ever
  releasing them. This applies to organizations (including companies),
  too; an organization can make a modified version and use it internally
  without ever releasing it outside the organization.

But if you release the modified version to the public in some way, the
  GPL requires you to make the modified source code available to the
  program's users, under the GPL.

Thus, the GPL gives permission to release the modified program in
  certain ways, and not in other ways; but the decision of whether to
  release it is up to you.

Short version:

if you use GPL code privately, do what you want

if you ever release it in any form, it must be with source code and under the GPL

Title: Want to use a lib for my project, confused with license (AGPL vs MIT License)

Body:
Im working on a Java Software and there is a need to use some extern libraries. I found two relevant libs. The one is on an AGPL and the other on the MIT License. Now Im asking my self, can I use these libs if:

I would make a non-opensource-nonfree-software

or

I would make a non-opensource-free-software

I dont really understand the whole license stuff, could somebody tell me which one of the libs for what kind of software would be better? Thank you


答:
Using certificate based authentication is the "correct" way of implementing a shared sql account.  The goal is it eliminate the password use for this kind of thing.

Update:

I suppose misunderstood the question.  I thought it had to do with trying to find an alternative to putting a db username and password either in an application config, or backed into the application itself.

You can eliminate the problem of managing passwords in applications by using client side certificates instead.  The cert itself is not enough, you have to have a distribution and management system capable of operations like cert revocation.

Reference: http://en.wikipedia.org/wiki/Public-key_infrastructure

Title: How do you handle database security from a desktop application?

Body:
For about 10 years I've worked on various in-house desktop client applications with SQL Server data stores.  Rarely did I start these projects - most are takeover work.

One thing that seemed constant everywhere was that there was a single global SQL Server user account that this application used that granted it permission to the common database, and yes in some naive situations it used the sa user account, which I generally tried to fix when possible.

You can't really effectively hide this username and password that the application uses to access the database.  They're usually stored in an ini or config file, or possibly baked into the executable itself.  In all cases, they're visible to the user if they do a little digging.  In one case we actually used a config file but encrypted it, but of course the encryption key had to be stored in the executable (we weren't naive to the limitations of this, but it did effectively stop people from poking around who were savvy enough to look in config files).

All of these systems had a user-authentication system built into the application, but of course they were all managed through the application itself, meaning the user information was stored in the database.  The application restricted what things you could do based on your access level, but it's all kind of moot if you can just connect to the database and run ad-hoc queries.

I'm interested to know what other systems do to get around this problem.  Here are the options I know of:

Use SQL Server's security mechanism to maintain a user and roles list, and make the desktop application add and remove users through T-SQL queries.

Instead of connecting directly to the database, create some kind of web service that runs on the server and put the authentication logic in there.  Make every request do security validation.

The first options is a bit ugly because you're separating users from the database so users are no longer first class entities and you can't reference them with foreign key relationships, etc.

The second just seems like a major performance problem, and a lot of extra work, plus you can't as easily use ORM mappers like NHibernate (I think).

Does anyone have experience with this?  Best practices?

Edit

Thinking a bit more, can SQL Server Authentication actually solve this problem?  For instance, if your user must be able to insert and update timesheet records so you can edit your timesheet, there's no way SQL server can disallow access to other rows in the timesheet details table, meaning you can read and write other people's timesheets too.


问:
Versioning and client upgrade strategy for web applications
I'm writing a web app and am wondering about future upgrades and how upgrading the webapp will affect the user experience.

In particular, I was wondering how a company like Google approaches this problem. For example, I have seen several examples where a particular google app will ask the user if they want to upgrade to 'the new google docs', or similar. This is the experience I would like to provide, but I'm not sure how to go about it. If it matter, I'm writing an app that uses backbone.js and has a heavy JS client side component. I have seen several discussions talking about versioning the REST component or the WebServices component, but none that discuss the actual client-side code or backend components (of course, the backend may not matter much if it is all behind a versioned webservice)

I'm interested in how they achieve this, from an application standpoint and from a (presumably) backend DB standpoint.

So it seems like there are several issues.

Where in the web root do the versioned applications live?

How do you serve multiple versions to different users?

How do you version the backend datastore?

Since I'm using backbone, I am particularly interested in to design the router for this type of app. If the various versions live in a subdir, how do I create a proper router?

There are probably some other considerations as well. Any advice would be welcome.

答:
If you wish to be able to stagger the upgrading of users you need (in the abstract):

multiple webservers behind a load balancer so you can have two (or more) versions of the web site live at any one time.

a common database/login system so that you have one point of entry and a way of recording which version of the site each user normally accesses.

Thus when a user logs in the database will indicate which version of the site is required and then the load balancer will direct the user at the appropriate version. Clearly it's a lot more complicated than that, but that's the basic principle.

You'd normally only have two versions, but you could also include a third low bandwidth version as a fallback and/or mobile version of the site using the same technology.


答:
What you hint at as 'web service' is called n-tier architecture.  Its generally the way to go in cases where security or configuration issues are likely (for ex, distribution of an application across many offices).  It does not have to be 'web based', though.  Many work with other protocols.

You create an application server to act as an intermediary between the client and the database (and other resources).  The application server handles your application based authentication and performs actions on behalf of the client.  In fact, ideally you wouldnt be doing any SQL in your client - rather you call methods on the app server.  The application server would handle all data manipulation.

There's a number of benefits to the approach.  You dont need to configure database connections and drivers on clients.   You dont store database users, passwords, & servers.  Configuration of the clients isnt even necessary - just point them in code to the right url or address.  Also, with the 'logic' in the application server, you dont have to repeat yourself when developing other applications - the same app server can be reused by different types of clients.


答:
One approach is to use AD groups and stored procedures to limit what the user can do -- for instance your time sheet DB, could allow inset, update and deletes of the users hours, but not allow updating of anyone else's hours.  The user's ID would be provided by the DB engine, user would have no direct access to the DB tables, just to sp's that ran queries based upon their login id.

Of course this isn't always feasible, but it can be.  The best approach will depend upon your requirements and resources.


问:
How to license a whole package without writing it into every file?
Is there a way I can make the license I use for an open-source software package be valid for all contents of the package without having to write it into every single file?

I often saw a LICENSE file, but does this file (with the license in it) makes all contents of the package (i.e. the current directory and all sub-directories) use this license?

答:
Judging by what I've seen in many other projects, you don't need to include the entire text of your license in every file. You should, however, include your copyright notice and a reference to your license in every file. I've often seen statements along the lines of:</p>

```<code>©2012 Joe Cool. See the license terms in the file 'license.txt' which should
have been included with this distribution. A copy of the license is also
available at <http://joecoolswebsite.com/license.txt>.
</code>```

Body:
Judging by what I've seen in many other projects, you don't need to include the entire text of your license in every file. You should, however, include your copyright notice and a reference to your license in every file. I've often seen statements along the lines of:

©2012 Joe Cool. See the license terms in the file 'license.txt' which should
have been included with this distribution. A copy of the license is also
available at <http://joecoolswebsite.com/license.txt>.


问:
Stuck due to "knowing too much"
Note more discussion at http://news.ycombinator.com/item?id=4037794

I have a relatively simple development task, but every time I try to attack it, I end up spiraling in deep thoughts - how could it extending the future, what are the 2nd generation clients going to need, how does it affect "non functional" aspects (e.g. Performance, authorization...), how would it best to architect to allow change...

I remember myself a while ago, younger and, perhaps, more eager. The "me" I was then wouldn't have given a thought about all that - he would've gone ahead and wrote something, then rewrote it, then rewrote it again (and again...). The "me" today is more hesitant, more careful.

I find it much easier today to sit and plan and instruct other people on how to do things than to actually go ahead and do them myself - not because I don't like to code - the opposite, I love to! - but because every time I sit at the keyboard, I end up in that same annoying place.

Is this wrong? Is this a natural evolution, or did I drive myself into a rut?

Fair disclosure - in the past I was a developer, today my job title is a "system architect". Good luck figuring what it means - but that's the title.

Wow. I honestly didn't expect this question to generate that many responses. I'll try to sum it up.

Reasons:

Analysis paralysis / Over engineering / gold plating / (any other "too much thinking up-front can hurt you").

Too much experience for the given task.

Not focusing on what's important.

Not enough experience (and realizing that).

Solutions (not matched to reasons):

Testing first.

Start coding (+ for fun)

One to throw away (+ one API to throw away).

Set time constraints.

Strip away the fluff, stay with the stuff.

Make flexible code (kinda opposite to "one to throw away", no?).

Thanks to everyone - I think the major benefit here was to realize that I'm not alone in this experience. I have, actually, already started coding and some of the too-big things have fallen off, naturally.

Since this question is closed, I'll accept the answer with most votes as of today. When/if it changes - I'll try to follow.

答:
Thinking about these things is definitely good, but don't let it stop your progress.

One approach that works really well (especially with iterative development) is to implement a simple solution and then refactor as necessary later. This keeps the code as simple as possible, and avoids over-engineering. Most of the performance or architecture changes you are contemplating probably aren't going to be required anyway, so don't bother writing them until they have officially become necessary. For example, don't worry about performance until a profiler has told you that it's time to improve performance.

One thing you can do to help you adjust is to set a hard time limit on how long you think about something before writing code. Most of the time, the code will turn out better if you think for a little, write it, realize your mistakes, and then fix them by refactoring.

There is a balance to be struck here. You shouldn't just jump in head-first and not think about the consequences, but you also shouldn't try to over-engineer your code either.

Title: Stuck due to "knowing too much"


答: Write the tests. You're done when the tests all pass: not before, and certainly not long after during an epic phase of over engineering. Having a suite of tests for the code you're writing will give you an independent, unbiased observer telling you when you can stop.</p>

Title: Stuck due to "knowing too much"

Body:
Note more discussion at http://news.ycombinator.com/item?id=4037794

I have a relatively simple development task, but every time I try to attack it, I end up spiraling in deep thoughts - how could it extending the future, what are the 2nd generation clients going to need, how does it affect "non functional" aspects (e.g. Performance, authorization...), how would it best to architect to allow change...

I remember myself a while ago, younger and, perhaps, more eager. The "me" I was then wouldn't have given a thought about all that - he would've gone ahead and wrote something, then rewrote it, then rewrote it again (and again...). The "me" today is more hesitant, more careful.

I find it much easier today to sit and plan and instruct other people on how to do things than to actually go ahead and do them myself - not because I don't like to code - the opposite, I love to! - but because every time I sit at the keyboard, I end up in that same annoying place.

Is this wrong? Is this a natural evolution, or did I drive myself into a rut?

Fair disclosure - in the past I was a developer, today my job title is a "system architect". Good luck figuring what it means - but that's the title.

Wow. I honestly didn't expect this question to generate that many responses. I'll try to sum it up.

Reasons:

Analysis paralysis / Over engineering / gold plating / (any other "too much thinking up-front can hurt you").

Too much experience for the given task.

Not focusing on what's important.

Not enough experience (and realizing that).

Solutions (not matched to reasons):

Testing first.

Start coding (+ for fun)

One to throw away (+ one API to throw away).

Set time constraints.

Strip away the fluff, stay with the stuff.

Make flexible code (kinda opposite to "one to throw away", no?).

Thanks to everyone - I think the major benefit here was to realize that I'm not alone in this experience. I have, actually, already started coding and some of the too-big things have fallen off, naturally.

Since this question is closed, I'll accept the answer with most votes as of today. When/if it changes - I'll try to follow.


问:
how to compare two large sets of data using PL/SQL?
I have two different tables in two separate databases with around 1.5 million records each. (BTW: im working on oracle databases)

The objective is to check if every record present in table A is also present in table B. Since the tables exist in different databases, I think I cannot calculate the "difference" between the two of them, so what im currently doing is selecting the column I need from each database and storing all the rows on separate text files. Then, I load the content of one of the files on a dictionary (using python) and then iterate the other file checking if every line is present on the dictionary.

I would like to make this more simple, perhaps directly on a stored procedure in the database. My main concerns are:

I don't know if PL/SQL associative arrays are as efficient as the dictionary (im assuming python dictionaries have constant lookup time)

The fact that tables exist on different databases makes me think that it would be impossible to "reach" the contents of table B if the stored procedure is on the database of table A, or viceversa.

Thanks in advance for any suggestion!

答:
If there are no security restrictions that prevent that, probably the easiest way is to create a database link, so those two databases see each other; then use the minus clause to find what is in one table but not the other.

```<code>CREATE DATABASE LINK otherdb
  CONNECT TO otheruser IDENTIFIED BY otherpwd USING 'otherdb.wherever';

SELECT mycolumn FROM mytable MINUS SELECT mycolumn FROM mytable@otherdb;

SELECT mycolumn FROM mytable@otherdb MINUS SELECT mycolumn FROM mytable;
</code>```

Copying the table from one machine to the other (using 'CREATE TABLE xxx AS SELECT * FROM mytable@otherdb') and using that for the comparison might be faster, though.

Body:
If there are no security restrictions that prevent that, probably the easiest way is to create a database link, so those two databases see each other; then use the minus clause to find what is in one table but not the other.

CREATE DATABASE LINK otherdb
  CONNECT TO otheruser IDENTIFIED BY otherpwd USING 'otherdb.wherever';

SELECT mycolumn FROM mytable MINUS SELECT mycolumn FROM mytable@otherdb;

SELECT mycolumn FROM mytable@otherdb MINUS SELECT mycolumn FROM mytable;

Copying the table from one machine to the other (using 'CREATE TABLE xxx AS SELECT * FROM mytable@otherdb') and using that for the comparison might be faster, though.


答:
The legal assumption is that every file is copyrighted. You can just describe in your license what's covered. Anyone who doesn't read the license but just the sourcefile will have a subset of the rights that you granted (Open Source doesn't take away legal rights). Everyone who does read the license knows what's covered, and can exercise all the rights that you have granted.

However, good Open Source licenses (such as the GPL) provide you with guidance how to apply the license. In particular, the GPL suggests adding to every source file a small reference to the actual license.

Title: How to license a whole package without writing it into every file?

Body:
Is there a way I can make the license I use for an open-source software package be valid for all contents of the package without having to write it into every single file?

I often saw a LICENSE file, but does this file (with the license in it) makes all contents of the package (i.e. the current directory and all sub-directories) use this license?


答:
Wikipedia names it "Analysis paralysis" in software. The recipe is to stick to agile methodologies. Meaning that any activity or individual action has much more value than attempt to establish practices or policies. Every contributor in the team is valuable, no matter how well or bad the person's abilities fit to architectural ideals. In agile, individuals, egos are first, the policies are last.

My favorite answer is "Architecture is verb". Stop thinking, start acting, no matter how imperfectly and inefficient you and the team will feel. Maybe the first actions can be dismantling inappropriate policies.

Title: Stuck due to "knowing too much"


问:
New application development - Use existing database or create a new one?
A Client has a huge Windows Application running on a Database. This client wants you to develop an "Express" version of this application, including only, let's say, 20% of its features. This Express version must be a Web Application, opened on the WWW. You have 2 choices:

Use the same Database to develop the web application

Create a new database to the web application, including only the necessary tables and objects and use some synchronization mechanism to keep the databases up to date.

The client prefers the 2nd option, because:

Security: If they have a separated Database for the web app, they will not "expose" the huge Windows App Database on the internet.

Performance: The windows application has some huge process that they run at night and "lock" the database for a couple of minutes. So, creating a separated DB would ensure better performance to the web application.

I prefer the 1st option, because:

Integrity: If we have different databases, we won't be able to create Foreign Keys between them.

Avoid Sync: If we have different databases, we would have to create a synchronization mechanism, which is very prone to failures.

Maintenance: Maintenance will be easier if we have only one database. No change will need to be replicated.

Can you help me decide which way to follow, and why?

答:
I'm inclined to agree with you for the reasons you state. Also, if you use the same database, you also get a very practical business benefit - you can easily 'upgrade' a customer to the full version without a complicated data export/import.

One thing you might recommend is trying it first with the one database approach.  If that becomes a problem, its far easier to then separate the 'express' data into a new database than it would be if you started off with two databases but later decided to merge them.


问:
Algorithm to minimize distance variance between 2D coordinates
I've been looking around for an algorithm that would optimize the distance between 2 list of coordinates and choose which coordinate should go together.

Say I have List 1:

```<code>205|200
220|210
200|220
200|180
</code>```

List 2:

```<code>210|200
207|190
230|200
234|190
</code>```

Calculated Distance between Coords:

```<code>205|200 to 210|200 == 5.00
205|200 to 207|190 == 10.20
205|200 to 230|200 == 25.00
205|200 to 234|190 == 30.68

220|210 to 210|200 == 14.14
220|210 to 207|190 == 23.85
220|210 to 230|200 == 14.14
220|210 to 234|190 == 24.41

200|220 to 210|200 == 22.36
200|220 to 207|190 == 30.81
200|220 to 230|200 == 36.06
200|220 to 234|190 == 45.34

200|180 to 210|200 == 22.36
200|180 to 207|190 == 12.21
200|180 to 230|200 == 36.06
200|180 to 234|190 == 35.44
</code>```

This Algorithm would pick:

```<code>205|200 to 230|200 == 25.00
220|210 to 207|190 == 23.85
200|220 to 210|200 == 22.36
200|180 to 234|190 == 35.44
</code>```

The Algorithm would pick these numbers as they would be the group that would have the littlest variance between the distance.
Conditions:

A Coordinate may only be used ones from each list

If List 1 or List2 is larger than it still only uses each coordinate once, but it tries to get the smallest distance variance and does nothing with the unused coordinates.

If you need more clarification please ask.

P.S. I've looked at the Hungarian algorithm and it seems like it will sort of do the job, but not exactly how I was expecting. The Hungarian algorithm will only try and make the least distance from all the coordinates, which can mean the smallest variance, but not every time as variance is more important here then least distance optimization.

Additional Information

I will have an array of List1, List2, and then the distances:

```<code>Distance[List1_item_0][List2_item_0] = 5;
Distance[List1_item_0][List2_item_1] = 10.20;
Distance[List1_item_0][List2_item_2] = 25.00;
Distance[List1_item_0][List2_item_3] = 30.68;

Distance[List1_item_1][List2_item_0] = 14.14;
Distance[List1_item_1][List2_item_1] = 23.85;
Distance[List1_item_1][List2_item_2] = 14.14;
Distance[List1_item_1][List2_item_3] = 24.41;

Distance[List1_item_2][List2_item_0] = 22.36;
Distance[List1_item_2][List2_item_1] = 30.81;
Distance[List1_item_2][List2_item_2] = 36.06;
Distance[List1_item_2][List2_item_3] = 45.34;

Distance[List1_item_3][List2_item_0] = 22.36;
Distance[List1_item_3][List2_item_1] = 12.21;
Distance[List1_item_3][List2_item_2] = 36.06;
Distance[List1_item_3][List2_item_3] = 35.44;
</code>```

From the Distance['List1_item_#] I would need to pick a distance. Once that distance is picked the [List2_item_#] CANNOT be picked by a different [List1_item_#]. The distances picked for each [List1_item_#] element would need to be picked in a way that the variance between them all is minimal. So distance for each [List1_item_#] should be as close as possible to each other without reusing a [List2_item_#] more than once.

答:
Looks like a Dynamic Programming problem. It looks like there are N*M pairs possible. The problem is, given points A1 and A2, and B1 and B2, the question whether pairs (A1,B1)+(A2,B2) are better than (A1,B2)+(A2,B1) depends on the addition of points A3 and B3.

I suspect therefore that any analytical solution will be O(exp(N*M)), i.e. really bad.


问:
Objects in non-OOP languages
Can we use the word "object" for data / functions in e.g. C (or Pascal) which doesn't really have objects? In C, what is an object? A data structure? A named memory area? I spoke to my collegue about "objects" in C and he said that there weren't any but in the text I study about C the word object is used as a generalization of either a function or data.

For example, if you in C declare a union  you can say that you have declared place for an object that can be either a function or data.

The ADT defined as "Object" looks like this in C

```<code>typedef enum { Integral, Real } Kind;
typedef struct {
  Kind type;
  union {
    double rvalue;
    int ivalue;
  } data;
} Object;
</code>```

Thanks for any reply

答:
EDIT:

As I see that nobody understood my answer, let me clarify. I don't say you can't have objects in C, as I explained below, you can have objects in even Assembly.

I said "You can't call structs or unions as objects. For example structs and unions does not support Inheritance or Polymorphism." to answer the original question.

There is nothing wrong in this answer. Objects are generally associated with Object Oriented Programming, so an object needs to support OOP principles. That's as simple as that.

Saying that "I'm smart enough to create objects even in C" does not help as an answer.

Title: Objects in non-OOP languages


答:
I agree with the 1 db option as well, for additional reasons.

Reporting

You can record actions taken via web client vs. the app client and report on it. Usage metrics like this can be very handy.

Performance

Having the app and web DBs out of sync for however long the sync timespan is can be a pain for users, depending on the sync strategy.

Cost

It'll be plain-old cheaper to not write a second DB.

Time To Market

If they already have a service layer, then you're gold, use that. If not, then you can create one to wrap the libraries/functionality that already exist and you have proven, tested, production quality codebase backing the service(s) - and it doesn't need to change to hit a new DB or schema.

Title: New application development - Use existing database or create a new one?

Body:
A Client has a huge Windows Application running on a Database. This client wants you to develop an "Express" version of this application, including only, let's say, 20% of its features. This Express version must be a Web Application, opened on the WWW. You have 2 choices:

Use the same Database to develop the web application

Create a new database to the web application, including only the necessary tables and objects and use some synchronization mechanism to keep the databases up to date.

The client prefers the 2nd option, because:

Security: If they have a separated Database for the web app, they will not "expose" the huge Windows App Database on the internet.

Performance: The windows application has some huge process that they run at night and "lock" the database for a couple of minutes. So, creating a separated DB would ensure better performance to the web application.

I prefer the 1st option, because:

Integrity: If we have different databases, we won't be able to create Foreign Keys between them.

Avoid Sync: If we have different databases, we would have to create a synchronization mechanism, which is very prone to failures.

Maintenance: Maintenance will be easier if we have only one database. No change will need to be replicated.

Can you help me decide which way to follow, and why?


答: "The client prefers the 2nd option .. " Therefore it's not a technical problem anymore. The client has spoken, he has a right to tell you what to do (and he accepts responsibility for that choice). If you don't do what the client asks, you have to accept responsibly for the choice, and not doing what your client has asked is not good business practice.</p>


答:
An object consist of a mixture of code and data, which in C can be represented by using a struct and add a function pointer for each method in the object (which in turn also needs to have a reference to the object itself (this) passed in as one of the parameters).

The hard part is then setting up the struct as the language doesn't help much, so you need some kind of convention to do it manually.   That said, when set up properly you can emulate all the fancy stuff like inheritance and polymorphism as it eventually just end up with a set of function pointers in each struct anyway, and then you actually have objects.

To clearly communicate to others that this is a construction not present in the core language, I would suggest calling it "emulated objects".

Title: Objects in non-OOP languages

Body:
Can we use the word "object" for data / functions in e.g. C (or Pascal) which doesn't really have objects? In C, what is an object? A data structure? A named memory area? I spoke to my collegue about "objects" in C and he said that there weren't any but in the text I study about C the word object is used as a generalization of either a function or data.

For example, if you in C declare a union  you can say that you have declared place for an object that can be either a function or data.

The ADT defined as "Object" looks like this in C

```<code>typedef enum { Integral, Real } Kind;
typedef struct {
  Kind type;
  union {
    double rvalue;
    int ivalue;
  } data;
} Object;
</code>```

Thanks for any reply


答:
The C standard defines an "object" as a "region of data storage in the execution environment, the contents of which can represent values" (N1570 3.15).

The C++ standard similarly defines an "object" as "a region of storage" (N3337 1.8p1).

The Pascal standard doesn't appear to have a definition of "object", but it does use the word once, in a sense that appears to be similar to the C and C++ definitions.

Other languages may or may not have their own definitions.

None of the definitions I've cited is related to concepts of "object-oriented" programming; C++ has object-oriented features, but the C++ standard doesn't use the word "object" to describe them.  Of course it's very common to use the word "object" in an "object-oriented" sense -- and there's nothing wrong with that, as long as you're clear about which meaning you're using.

"Object" is a common English word; see, for example, http://dictionary.reference.com/browse/object. Certain technical fields have established more specific meanings for it, for convenience in discussing certain topics. These meanings are not necessarily consistent with each other.

Title: Objects in non-OOP languages


答:
Is this wrong? Is this a natural evolution, or did I drive myself into a rut?

It depends. This tends to be a common step along the road of a developer.

Start throwing crap together, get bitten in the ass by it

Start over-engineering the living hell out of everything, realize that YAGNI

Settle on some pragmatic middle ground where the easy stuff is slapped together and the hard/change-likely stuff is given enough engineering to make it easy enough to work with/change.

It's only a rut if you stay at number 2.

Title: Stuck due to "knowing too much"


答:
There are only two things you really need to keep in mind when writing and designing software: maintainability and correctness.

Correctness is most important short-term and can easily be proven by tests.

Maintainability will help later in the development but is harder to pin down.

My current strategy is to first get a monolithic proof of concept up and then separate the UI from the model (ensuring the model doesn't know anything about the UI) once I'm satisfied that it is viable. If I would wait too long for this step, I'd get something unmaintainable. If I start with the separated layers, I just cannot seem to get started as I get stuck on what the UI needs to know about the model.

Title: Stuck due to "knowing too much"


答:
40 years ago Fred Brooks wrote about this "Write one to throw away, you will anyhow."
Nothing has changed........ </p>

Title: Stuck due to "knowing too much"


答:
Here's my personal process of elimination for crazy-awesome designs that (in their first version) can end up being impractical and damage a project from the business perspective.

Identify the epicenter: Think of your project as a hot-dog stand, the epicenter would be the hot dogs. You can take every other spice/dressing/vegetable out from your stand and still be able to sell hot dogs. What is the main purpose of your software? Isolate every other addition and/or added value from it and focus first on the epicenter.

Keep repeating to yourself "doing it later means doing it better": see where it makes sense and put a little "for later" note on it. If you do it well and thinking about its real-world usage you will end up with the same design but prioritized in a roadmap.

Diminish-Decouple-Discard: Whatever module design you have make it as simple/essential/pure/universal as you can (sometimes this can be accomplished without even removing features). When you cannot simplify it further, start decoupling elements that could live by themselves and have a purpose. In the end if you still have some fat in there, you will be able to just cut it off.

Separate "library code" from "production code": There will always be code that cannot be reused, but it always adds noise to design. This code is the one that contains business rules. You will find that sometimes some business rules just are easier and quicker to change (extremely important) than with a robust design. You will find code which you can rely on, and code the customer needs to change or reimplement in the future. You will want those to be kept as separate as possible.

And BTW, step 0 is: "go crazy with the design". This helps me out getting it out of my system and often finding new implications, hidden requirements and even emergent features.

I took 1 & 2 from Rework.

Title: Stuck due to "knowing too much"


答:
One of the things I always like to keep in mind is the saying "the future isn't what it used to be."

With a certain amount of experience it becomes tempting to believe you can predict the future, but you cannot.  It is easy to envision features that future clients/users/whatever may want, but that doesn't mean they are going to want them right away. It also doesn't mean they're going to want them over some other conflicting feature.  So you really do need to limit how much time you spend today planning for the future. You especially need to limit how much time you spend building things today that are only going to be of use in the future.

The question that I ask that keeps me on the straight and narrow is "how much harder will it be to build this feature later than it is to build support for that feature now?" Usually, the answer is that the future effort is about the same or maybe twice what it would be to do it now. In that case, because I can't predict the future, I have no problem not building it now.  If the answer gets up to 10x or more, then I'll start asking around about how likely people think it is that we are going to need this in the next year or two.  Even then, unless there is widespread agreement, I would simply limit myself to making sure it is not necessary to undo things we are doing today in order to achieve that goal in the future.

For example, I worked on a few projects where we spent a lot of time abstracting out the fact that we were using Hibernate as a data access later.  (Never have I ever seen the project built on Hibernate stop using it, so that was a waste of time to begin with, but let's set that aside.) Even if it had been a reasonable possibility that we might want to change later, because we were also using a data access object pattern, it would have been no harder to build in the flexibility to change out Hibernate and change it out at the same time when we needed it than it was to build in the flexibility from the start.  Faced with a situation like that now, I would just put off having that flexibility until we really needed it.

Unless you're doing strategic planning for a large corporation, it's hardly even worth it to think about architectural issues more than two or three years away, because technology is changing so quickly.  The feature you may be thinking about building today may be freely available in open source in two or three years.  Almost certainly the cost-benefit analysis will have changed.

Limit yourself to building a system that does what you need today, that you're proud of, and that you will be happy to work on in a few months whatever the next round of changes bring. Really that's the best you can do.

Title: Stuck due to "knowing too much"


问:
Is writing software in the absence of requirements a skill to possess or a situation I should avoid?
I find that some software developers are very adept at this, and often times are praised for their ability to deliver a working concept with abstract requirements. Frankly, this drives me crazy, and I don't like "making it up" as I go. I used to think this was problematic, but I've started to sense a shift, and I'm wondering if I need to adjust my thought (and programming) process when given very little direction. Should I begin to acquire this ability as a skill, or stick to the idea that requirement's gathering and business rules are the first priority?</p>

答:
A bit of both. You need to satisfy your clients, which means that you need to know what they want. On the other hand, clients are notoriously bad at communicating what they really want.

So you want to avoid scenarios where you don't know what clients want, but you will inevitably run into a scenario where the requirements are 'squishy' at best, and deceptive at worst. A good real world programmer requires adaptability.


答:
The behavior is undefined, as follows:

From the C99 standard:

6.5 Expressions

...

2 Between the previous and next sequence point an object shall have its stored value
 modified at most once by the evaluation of an expression.72) Furthermore, the prior value
  shall be read only to determine the value to be stored.73)

72) A floating-point status flag is not an object and can be set more than once within an expression.

73) This paragraph renders undefined statement expressions such as
```<code>
    i = ++i + 1;
    a[i++] = i;</code>```
while allowing
```<code>
    i = i + 1;
    a[i] = i;
</code>```

We're violating the second sentence of that paragraph; we're not just reading the prior value to determine the new value to be stored.

Note that undefined doesn't necessarily mean illegal.  Undefined simply means that the compiler is free to handle the situation any way it sees fit; any result is considered "correct".  You could very well wind up with the result you expected.  Or not.  The program could crash.  Or not.  Or anything else could happen.

In this case, you will get different results based on platform, compiler, optimization settings, surrounding code, etc.  The reason for that is as follows:

6.5.2.2 Function calls

...

10 The order of evaluation of the function designator, the actual arguments, and
  subexpressions within the actual arguments is unspecified, but there is a sequence point
   before the actual call.

It is unspecified whether i or i++ is evaluated first; furthermore, it is unspecified whether the side effect of ++ is applied immediately after i++ is evaluated, as follows:

6.5.2.4 Postfix increment and decrement operators

...

2 The result of the postfix ++ operator is the value of the operand. After the result is
   obtained, the value of the operand is incremented. (That is, the value 1 of the appropriate
  type is added to it.) See the discussions of additive operators and compound assignment
 for information on constraints, types, and conversions and the effects of operations on
pointers. The side effect of updating the stored value of the operand shall occur between
the previous and the next sequence point.

Emphasis mine.

Edit

Changed the wording a bit to make it clear that the behavior is undefined.

Body:
The behavior is undefined, as follows:

From the C99 standard:

6.5 Expressions

...

2 Between the previous and next sequence point an object shall have its stored value
 modified at most once by the evaluation of an expression.72) Furthermore, the prior value
  shall be read only to determine the value to be stored.73)

72) A floating-point status flag is not an object and can be set more than once within an expression.

73) This paragraph renders undefined statement expressions such as

    i = ++i + 1;
    a[i++] = i;

while allowing

    i = i + 1;
    a[i] = i;

We're violating the second sentence of that paragraph; we're not just reading the prior value to determine the new value to be stored.

Note that undefined doesn't necessarily mean illegal.  Undefined simply means that the compiler is free to handle the situation any way it sees fit; any result is considered "correct".  You could very well wind up with the result you expected.  Or not.  The program could crash.  Or not.  Or anything else could happen.

In this case, you will get different results based on platform, compiler, optimization settings, surrounding code, etc.  The reason for that is as follows:

6.5.2.2 Function calls

...

10 The order of evaluation of the function designator, the actual arguments, and
  subexpressions within the actual arguments is unspecified, but there is a sequence point
   before the actual call.

It is unspecified whether i or i++ is evaluated first; furthermore, it is unspecified whether the side effect of ++ is applied immediately after i++ is evaluated, as follows:

6.5.2.4 Postfix increment and decrement operators

...

2 The result of the postfix ++ operator is the value of the operand. After the result is
   obtained, the value of the operand is incremented. (That is, the value 1 of the appropriate
  type is added to it.) See the discussions of additive operators and compound assignment
 for information on constraints, types, and conversions and the effects of operations on
pointers. The side effect of updating the stored value of the operand shall occur between
the previous and the next sequence point.

Emphasis mine.

Edit

Changed the wording a bit to make it clear that the behavior is undefined.


问:
I feel unprepared to start my first job out of college... how can I improve?
I just graduated from university with a degree in Computer Science/Engineering and was fortunate enough to land a job working in the pharmaceutical industry as a developer. My title is System Developer I, which will require the following skills:

0-3 years development experience with C# .NET and SQL Server
Experience writing T-SQL and stored procedures
XML
Javascript

I learned of the company at a job fair and was not aware that I would need those skills for the job until after they wanted to set up an interview with me. The interview consisted of talking about my background, an almost-too-simple logic test, and a couple SQL questions that anyone with any experience should be able to answer. I was honest with them and indicated that I had absolutely no experience with SQL Server, .NET, XML, or Javascript, but they offered me the position anyway. Of course, I accepted it, but I am now extremely worried that my skills will not be up to snuff.

I fully realize from reading lots of Coding Horror, Stack Overflow, and The Daily WTF that a degree in Comp Sci in no way prepares me to be a software developer; I further realize that I will be a monumental noob in the presence of people who have been doing this for years. I feel like the only thing that makes up for my lack of development experience and programming knowledge are my social skills, innate writing ability, and humility (at least compared with some of my co-graduates who fancied themselves to be the next Steve Jobs... barf) You will never find me being the prima donna constantly complaining about the system, the language, etc... I just want to do my job like I'm told, work 9 - 5, and go home with my paycheck feeling like I'm competent. If that requires home-study, I'm more than willing because I do love programming and computer science.

So far, I've familiarized myself a bit on using SQL Server Management Studio, gave myself a refresher on basic SQL, and started learning more about C# and .NET using Introducing Visual C# 2010 by Adam Freeman from Apress. Can anyone recommend anything else I can do in the meantime to:

A. Chill the ** out and enjoy my new job without worrying so much about getting canned for incompetence

B. Improve my understanding of design patterns and OOP

C. Get the low-down on writing T-SQL in the most efficient way possible

Thanks everyone.

答: Don't worry too much. The experienced programmers read the same blogs you did and know that a comp sci degree doesn't prepare you very well. Their expectations will be low, so as long as you're honest, ask a bunch of questions and work to improve you have nothing to worry about.</p>


答:
The skill isn't to write software without requirements. It is instead to elicit requirements from the project owner regardless of whether there is a formal requirements documentation or not.

Gathering requirements is definitely your first priority, but you don't necessarily need to get all of the customer's needs noted up front.  The risk is of course is that you might miss some vital piece of information that renders your system architecture useless if you haven't managed to have the right sort of conversations with your customer, however it is not unusual to define a product and even get much of the development out of the way, while deferring the major system architecture decisions until the last possible moment.  This is a lean development approach which is meant to ensure that you don't commit to a potentially incompatible architecture too early in your product development until you have more solid information.  In the situations the OP has described in his question, this lean approach would be quite important IMHO to avoid major rework and cost blow-out later on, which is when you've finally managed to learn what it was your customer really needed.

Yes, you do sometimes need to crystal-ball-gaze a little to get to the heart of what it is the customer really is asking for, which is where prototyping spikes and the slow - and yes sometimes painful - incremental drawing out of requirements requires that you really develop good customer relationship skills, and also the patience to realize that with any complex software idea, that in the beginning the customer doesn't often know much more than you about what the software actually needs to do. Most often, the customer calls you in early to depend on your expertise to define their requirements as the customer doesn't always have the necessary expertise or knowledge of the software development process.

Title: Is writing software in the absence of requirements a skill to possess or a situation I should avoid?

Body: I find that some software developers are very adept at this, and often times are praised for their ability to deliver a working concept with abstract requirements. Frankly, this drives me crazy, and I don't like "making it up" as I go. I used to think this was problematic, but I've started to sense a shift, and I'm wondering if I need to adjust my thought (and programming) process when given very little direction. Should I begin to acquire this ability as a skill, or stick to the idea that requirement's gathering and business rules are the first priority?</p>


答:
Don't worry yet.  Any company that hires a new grad has realistic expectations.  Enjoy the time now, because there isn't much you can learn between now and then.  Every hour learning on the job will be worth ten after you start.

There are a couple things you can do once you start though...

When they start giving you work, do everything in less time than is requested, no matter how late you have you stay.  Yes, it is unpaid overtime, but you won't have to do it forever.  You just want to establish a reputation for being reliable.  (If you establish the opposite reputation, you may never be able to shed it)

Whatever technology you are given (and it sounds like you know it) don't complain about it.  Just learn in much better than every other new hire.  Find the company experts and learn from them.  In a non-software firm, you'll be surprised how quickly you can differentiate yourself.  Don't worry about "It's not Python" or "I prefer an Open Source Stack" or any of that until later in your career.

After you get your technical chops, it's very important to learn the domain of the business.  In the end they're not in the business of producing software.  Figure out how you can help them make money.  Is it shortening their drug development time?  Better understanding their customers?  Understanding purchasing trends?  Cutting out paperwork?  All of these require an understanding of technology (How can IT help?) but also require knowing the business almost as well as the people that are doing the job.  Don't worry that it's difficult - a CS degree is very hard.  If you know CS, you can learn Finance, Marketing, Regulatory Affairs, etc.

Related to the above - learn the data of the business first before worrying about fancy GUI tricks.  The GUIs come and go, the data model underlying a company doesn't.

You'll never get a learning curve like this again - enjoy your first few years out of school!

Title: I feel unprepared to start my first job out of college... how can I improve?

Body:
I just graduated from university with a degree in Computer Science/Engineering and was fortunate enough to land a job working in the pharmaceutical industry as a developer. My title is System Developer I, which will require the following skills:

0-3 years development experience with C# .NET and SQL Server
Experience writing T-SQL and stored procedures
XML
Javascript

I learned of the company at a job fair and was not aware that I would need those skills for the job until after they wanted to set up an interview with me. The interview consisted of talking about my background, an almost-too-simple logic test, and a couple SQL questions that anyone with any experience should be able to answer. I was honest with them and indicated that I had absolutely no experience with SQL Server, .NET, XML, or Javascript, but they offered me the position anyway. Of course, I accepted it, but I am now extremely worried that my skills will not be up to snuff.

I fully realize from reading lots of Coding Horror, Stack Overflow, and The Daily WTF that a degree in Comp Sci in no way prepares me to be a software developer; I further realize that I will be a monumental noob in the presence of people who have been doing this for years. I feel like the only thing that makes up for my lack of development experience and programming knowledge are my social skills, innate writing ability, and humility (at least compared with some of my co-graduates who fancied themselves to be the next Steve Jobs... barf) You will never find me being the prima donna constantly complaining about the system, the language, etc... I just want to do my job like I'm told, work 9 - 5, and go home with my paycheck feeling like I'm competent. If that requires home-study, I'm more than willing because I do love programming and computer science.

So far, I've familiarized myself a bit on using SQL Server Management Studio, gave myself a refresher on basic SQL, and started learning more about C# and .NET using Introducing Visual C# 2010 by Adam Freeman from Apress. Can anyone recommend anything else I can do in the meantime to:

A. Chill the ** out and enjoy my new job without worrying so much about getting canned for incompetence

B. Improve my understanding of design patterns and OOP

C. Get the low-down on writing T-SQL in the most efficient way possible

Thanks everyone.


答:
This is very ambiguous …

Two things I can say:

There are a lot of very gifted technical people whose careers get halted because they wait for perfect requirements.  Or they play the, "Sorry, can't do it, wasn't in the requirements."  The reality is requirements writing is very difficulty.  The precision required for good requirements is unlike anything most business people have ever created.  There's a bridge between technology and the business, and people who make the others come 100% of the way to meet them usually lose.

There are software people who learn the domains as good or better than their customers.  These people are worth their weight in gold, even if they aren't 100% the best developers.  I have seen software people anticipate the quantitative marketing needs of the best brand managers in the country.  They weren't the best at coding all the solutions, but they were heroes because they could cross the bridge.

Life's not about black and whites though.  If you draw a narrow box around yourself, you'll limit yourself.  On the flip side, an organization that dismisses what's needed to create technology is also limited.  You'll have to see where in the gray you prefer to be.


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答: I had worked for a few months in Japan. Although the code was in English the file headers and small amount of comments they had was in Japanese. They actually had to find me a English keyboard to work with.</p>


答:
Priority #1: Find a mentor. Make it someone you respect, you like and he/she likes you.  It will help if they have a little grey hair -- they will be more likely to be in a position to want to help a newbie.

IMHO, the mentor/mentee relationship is the absolute best way to learn to be a developer, architect or whatever other technical job you want to have.  Find a guru, do what he/she does and you will become a guru someday.  Books and blogs will help you sharpen your sword, but it takes a mentor to give you your first sword.

I floundered a couple of years out of school before I found my first mentor.  It took a few years until we had the "But Master, my skills have become more powerful than yours!"  Some years after that, when I started my own company, he came and worked for me.