问:
Concurrency with listeners and upload: is this solution sound?
I'm working on an Android app.

We have listeners for position data and camera capture which is timed on a background thread (not a service).

The timer thread dictates when the image is captured and also when the data is cached in a local sqlite db.

So, my question is how to properly store the location data as it comes in based on the listeners and pull that data so that the database can be updated as the camera capture is executed.

I can't put the location data into the database as it arrives because it is processed more frequently than the camera images and the camera images are what dominates the architecture at the moment. (Location data is supplement). However I need the location data to get a rough location of the where the image is captured.

My first thought was to have singleton store the location data. And have a semaphore on the getInstance method so if the database update is happening (after an image is captured) we don't have an error. The location data can wait for the database update or it can be lost for that particular event it doesn't really matter.

What are you thoughts? Am I on the right track? (And is this the right sub-site or would this be better on stackoverflow?)

答:
I think you've got it right.  Ideally you'd want the background thread handling the camera to send data straight to the database and so avoid using the singleton.  This lets the database handle all the concurrency problems.  But you need to trade a bit of safety for performance.

You need your picture and related data in a place where it can get referenced by multiple threads.  The singleton will do fine for this (but give some thought to juggling more than one picture at once--you'll write better code).  Make sure all references to the data are synchronized.  Use wait and notifyAll to signal that a picture is ready.  And read everything you can find on the problems of multithreading--it's a tricky and dangerous business.

Alternatively (just thought of this), you might be able to avoid multithreading--or at least the problems of multitheading--by using java.util.concurrent.ConcurrentLinkedQueue.  An instance would not need to be synchronized.  Your camera thread could create a data object, add (offer) it to the queue, and null its reference to it.  It would need to signal your main thread to let it know it was ready.  Then your main thread could take it (using poll).  Once your main thread has the data object, it would no longer be visible anywhere else.  The queue could work like a DB in taking responsibility for multithreading.

(Several other concurrent collections might work as well, but be sure to do the read and the remove in one method or you might find, someday, that two threads do reads before either does a remove and both think they have exclusive access to the data.)


问:
What is a widely accepted term for a string variable that would probably contain a file path and file name?
For functions that need to index files in a directory and rename them FileName0001, FileName0002, etc... I often need to write a function that splits the file name from the file path and rename the file.  When I put the file name and file path back together, I don't have a very good name for the variable that contains both of them and I usually just wind up concatenating them every time I want to use them (usually using them as parameters for functions labeled either filename or filepath) so I never really know what I'm doing until I notice a lot of files being written in the same directory as my binaries.

Anyway, what do I call a file name and a file path?  I don't want to call it File, because that usually means the binary information behind the file.  I don't want to call it URI because that usually means I've got some sort of protocol, which I don't.  I just want a good way to denote "c:\somedir\somedir\somedir\somefile.txt" so as to deconfuse this mess I've just realized I'm in.

Please don't just list your personal preference.  I think an excellent answer should "'site its sources". (as in, provide a link to a repository with a good example of the code being used as I described)

答:
As many others suggested, use something that works for you. If you make up a scheme, stick to it, and explain it in the documentation (you're documenting your work, don't you?). Your scheme will last longer, if you are able to extend it to cover different files and different paths. What seems to work well would be to construct your filename-holding variables in one central configuration place, for example

MyProjectRoot ... Root of your projects files to prepend to your subdirs

MyConfigDir = MyProjectRoot + "/conf"

MyConfigFile = MyConfigDir + "/complicatedconfiguration.xml"

This way, you not only make it obvious what the individual filenames are standing for, but you also gain a place where you (or someone else working with your code later on) can apply changes that will reflect consistently throughout your project.

For your specific project, I'd be more worried about mixing up source and target, so I'd go with

SourcePath, TargetPath for the pathname component

FileName (or BaseName) for the filename component common to both, (or SourceBaseName / TargetBaseName if they're not common to both)

and possible SourceFile and TargetFile for Path+Filename

And I'd explain this in the preamble of the program/script.

If you want to be very explicit that your FileName component doesn't contain any path component, you could call it BaseName.

So your entire thing is basically constructed from

/AbsolutePath/BaseName.Extension

./RelativePath/BaseName.Extension

combined with qualifiers like Source, or Target

ContentLicense: CC BY-SA 3.0


问:
Is it a good pattern that no objects should know more than what it needs to know?
I am implementing a controller class to manage a view. I have a file uploader class, Grabber, which could communicate in one of 2 ways:

1) Offer some kind of notification event to the controller on upload start and finish

2) Provide a property on Grabber that indicates true or false if upload has completed

I am concerned that with option 2) I am introducing a dependency between the controller and the Grabber.

What is the better design here?

答:
yes it is a good pattern, in fact it is the basis of most patterns and is called loose coupling

this will make it easier in general should you need to modify the Grabbing class in the future: for example when you want to notify the viewcontroller of an error that occured during uploading, with the events you define a error event to pass on to the view controller, while otherwise you would need to have a second property that only holds a meaningful value when grabbing.isDone() returns true.

also in this case it prevents the busy loop pattern of repeatedly checking the property to see if it changes before moving on


答:
This appears to be a classic case of the Observer pattern

Therefore, I would suggest that you implement a GrabEvent that contains state to indicate if it is a start, finish or error event. The Grabber then issues these GrabberEvent instances to anyone who has registered as a GrabberListener (or GrabberObserver).

However, you must make sure that the listeners are decoupled from the event provider (Grabber) thread. If not, your Grabber event handler will end up calling into the GrabberListener instances and updaing their state in a separate thread which could introduce inconsistencies and poor performance if the implementations of those listeners are outside of your control.

In Java, a good way to decouple consumers from providers is to use a BlockingQueue so that each end of the queue runs in its own thread.

Title: Is it a good pattern that no objects should know more than what it needs to know?

Body:
I am implementing a controller class to manage a view. I have a file uploader class, Grabber, which could communicate in one of 2 ways:

1) Offer some kind of notification event to the controller on upload start and finish

2) Provide a property on Grabber that indicates true or false if upload has completed

I am concerned that with option 2) I am introducing a dependency between the controller and the Grabber.

What is the better design here?


答:
In the time of clouds and the Internet, I like to use uri. There's even a RFC. The only problem I see with this naming convention is, when you are using a programming language like C#, where Uri is an Object containing an Uri (of course). Then it would be pretty strange to name a String uri. This is why I always use the Uri object if it is available or create one.

That said, I think that uri is the best choice, since the path given could and should be universal.

Title: What is a widely accepted term for a string variable that would probably contain a file path and file name?

Body:
For functions that need to index files in a directory and rename them FileName0001, FileName0002, etc... I often need to write a function that splits the file name from the file path and rename the file.  When I put the file name and file path back together, I don't have a very good name for the variable that contains both of them and I usually just wind up concatenating them every time I want to use them (usually using them as parameters for functions labeled either filename or filepath) so I never really know what I'm doing until I notice a lot of files being written in the same directory as my binaries.

Anyway, what do I call a file name and a file path?  I don't want to call it File, because that usually means the binary information behind the file.  I don't want to call it URI because that usually means I've got some sort of protocol, which I don't.  I just want a good way to denote "c:\somedir\somedir\somedir\somefile.txt" so as to deconfuse this mess I've just realized I'm in.

Please don't just list your personal preference.  I think an excellent answer should "'site its sources". (as in, provide a link to a repository with a good example of the code being used as I described)


问:
User defined type for healthcare / Medical Records variable name prefixes?
I was reading Code Complete regarding variable naming in trying to find an answer to this question and stumbled on a table of commonly accepted prefixes for programming word processor software.  Well, I'm not a word processor software programmer, but if I was, I'd be happy to use those user defined types.

Since I'm a programmer for a smallish healthcare ISV, and have no contact with the larger community of healthcare software programmers (other than the neglected and forsaken HealthCareIT.SE where I never had the chance to ask this question).  I want to know if there is a coding convention for medical records.

Like Patient = pnt and Chart = chrt and Medication = med or mdctn or whatever.  I'm not talking full on hungarian notation, but just a standard that would fit in code complete in place of that wonderful chart of word processor UDT's which are of so little use to me.

答:
I've worked with insurance companies, banks and real estate firms, which have some specialized voc too. When in doubt, I always use the full name. Lately I also started to put them at the end (since I noticed that I don't really use many different instantiations any more (in times of Lists, Collections and whatnot). I would do it like this:

```<code>Chart firstChart = new Chart("First");
Chart anotherChart = new Chart("Second");

Chart[] lotsOfCharts;
</code>```

In the (not so) good old times when I was coding using VB (Script) and stuff like that, I did it like this:

```<code>Chart chartOne
Chart chartTwo
Chart chartThree
...
</code>```

But again, why not just put it into a collection:

```<code>Chart[] charts
charts[0] = new Chart("One")
charts[1] = new Chart("Two")
charts[2] = new Chart("Three")
</code>```

As you see there isn't really any need for a prefix any more.

When it's about data types I then borrow from mathematics.

```<code>int x = 0;
int y = x + 5;
string w = "test";

...
</code>```

Body:
I've worked with insurance companies, banks and real estate firms, which have some specialized voc too. When in doubt, I always use the full name. Lately I also started to put them at the end (since I noticed that I don't really use many different instantiations any more (in times of Lists, Collections and whatnot). I would do it like this:

Chart firstChart = new Chart("First");
Chart anotherChart = new Chart("Second");

Chart[] lotsOfCharts;

In the (not so) good old times when I was coding using VB (Script) and stuff like that, I did it like this:

Chart chartOne
Chart chartTwo
Chart chartThree
...

But again, why not just put it into a collection:

Chart[] charts
charts[0] = new Chart("One")
charts[1] = new Chart("Two")
charts[2] = new Chart("Three")

As you see there isn't really any need for a prefix any more.

When it's about data types I then borrow from mathematics.

int x = 0;
int y = x + 5;
string w = "test";

...


问:
What popular "best practices" are not always best, and why?
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.

答:
Using static and final keywords.

static, because its faster.

final, because you dont want anybody to extend that class(aka Design For Extension).

it makes class using those classes very hard to unit-test.

ContentLicense: CC BY-SA 2.5


问:
practical way to learn C?
I want to dig into C and normally when I want to learn a new language I think of a simple/attainable project goal that has some practical purpose (make use of an api, automate a task, etc...)

I'm having a harder time coming up with one for C mainly because everything I read points to the fact that C's primary use currently is in embedded systems and more complex software projects like operating systems.

Does this point me to the fact that I don't need to learn it or that I just need to be a bit more convoluted in my learning strategy?

References to practical learning resources? (tutorial/how to that produces an end result that has some purpose/benifit)

答: If you are ALREADY a programmer, and JUST need to learn C, and don't mind learning an older version of the language (the core is still pretty much the same), then Leendert Ammeraal's "C for Programmers" can't be beat.  Work through it, beginning to end.</p>

Title: practical way to learn C?


答:
We use </p>

```<code>fileName = mystuff.txt
dirName = c:\data\mydocs
pathName = c:\data\mydocs\mystuff.txt
</code>```

Body:
We use

fileName = mystuff.txt
dirName = c:\data\mydocs
pathName = c:\data\mydocs\mystuff.txt


答: I would try to talk to someone who documented everything in patient charts and get familiar with their abbreviations, most hospital had/have standard charting abbreviations that may be useful. This would also allow your app to be more closely related with your domain which can be useful.</p>

Title: User defined type for healthcare / Medical Records variable name prefixes?

Body:
I was reading Code Complete regarding variable naming in trying to find an answer to this question and stumbled on a table of commonly accepted prefixes for programming word processor software.  Well, I'm not a word processor software programmer, but if I was, I'd be happy to use those user defined types.

Since I'm a programmer for a smallish healthcare ISV, and have no contact with the larger community of healthcare software programmers (other than the neglected and forsaken HealthCareIT.SE where I never had the chance to ask this question).  I want to know if there is a coding convention for medical records.

Like Patient = pnt and Chart = chrt and Medication = med or mdctn or whatever.  I'm not talking full on hungarian notation, but just a standard that would fit in code complete in place of that wonderful chart of word processor UDT's which are of so little use to me.


答:
I have also worked in healthcare software and I've found very few "established" acronyms and abbreviations. The only one that I've seen used regularly is "MRN" for "medical record number". There's also some terms that are commonly used as abbreviations (EMPI, XDS, etc.), so those are OK to use in code as well.

Outside of this, it's much more clear to avoid using abbreviations and use full words. Certainly don't bother with abbreviations for things like "patient", "document", "medication".

Best practices for healthcare are the same as best practices for any other piece of software. Unless it's a universally established abbreviation, it's much safer and cleaner to use the full work.


问:
Javascript MVC in principle
Suppose I want to implement MVC in JavaScript. I am not asking about MVC frameworks. I am asking how to build it in principle.

Let's consider a search page of an e-commerce site, which works s follows:

User chooses a product and its attributes and press a "search" button.

Application sends the search request to the server, receives a list of products.

Application displays the list in the web page.

I think the Model holds a Query and list of Product objects and "publishes" such events as "query updated", "list of products updated", etc. The Model is not aware of DOM and server, or course.

View holds the entire DOM tree and "subscribes" to the Model events to update the DOM. Besides, it "publishes" such events as "user chose a product", "user pressed the search button" etc.

Controller does not hold any data. It "subscribes" to the View events, calls the server and updates the Model.

Does it make sense?

答:
Remember, the idea behind a pattern like MVC is to make your life easier. If you start ajaxing in static content to ram client side squares into MVC triangles you're not really doing that. We've already got the basics on the front end, like the DOM API that already manages the DOM tree, covered. Use MVC as a higher level layer of abstraction to make code more legible as well as easier to modify and implement. If it's already covered by the DOM API or even JQuery core, you're wanting to implement at too low of a level for it to be more help than hindrance, IMO.

I think on the front end it makes more sense to think in terms of how MVC can be used to apply to types of UI widgets rather than a way to deliver and handle all HTML content.

So imagine a combo box that lazy loads content when you click on it.

So you have a model with methods for communicating with the server to get the data and process it into something that's easy for the view to render. I would stop short of actually converting an array of items into LIs at the model and let the view handle that. The model triggers events when it is finished prepping/updating/processing data.

You have a view that handles rendering/re-rendering of list items inside your combo boxes and it also handles user interface stuff like auto-complete/match in the text box, and triggering app-level (not DOM - it translates those) events when new items are selected or an unloaded box is clicked on indicating a need for new data. The view also establishes context (which combo box is being acted on by a user).

The controller makes the app-wide/relevant decisions. So when a new combo is clicked on, the controller is what tells all the other combos to close. I think there is variation on this but it makes the most sense to me when model and views have to go through the controller rather than listen to or call each other directly.

So a view detects that a new combo has been clicked on and triggers an event the controller listens for. The controller determines that data is needed and triggers an event the model listens for. The model loads in and processes the needed data and when finished, triggers a completed event the controller listens for. Then the controller hands that data off to the view so the view can convert to LIs and drop them into the appropriate combo box.

Now,  I don't love this as a triad of objects. It makes more sense to me for there to be a parent combo box object that essentially acts as a controller with aggregate model (if needed) and view/UI objects on the interior. That parent combo box object also manages state and maintains inventory of all the various combo boxes it's responsible for, which was more of a view responsibility in the triad model. What I like about this is that it's easier to make sense out of interaction with other objects and the combo box object itself gets all events pinged off of it, making them accessible to outside interests like a debug logger or other UI widget that needs to react to a combo box selection.

OwnerDisplayName: Michael

Title: Javascript MVC in principle


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答: Completely unused variables, especially when the variable has a name similar to variable names that are used.


问:
Bug fixing approach
I have been working on a database project, and I recently received a bug report for the remote execution of some queries.

Usually, you try to find out the actual cause for the bug to occur and then fix it.

But sometimes what I do when I'm fed up of doing some research (and can't find suitable information on the internet) is just change the logic, which takes me much less time compared to the other option.

Is this approach correct, or should I try to fix the original bug involving more R&D?

答:
If you mean that instead of analyzing a pile of WTF, you discard it, rewrite, and test, then your approach makes sense to me. Broken code has no value.

I have often answered the question "What's wrong with this code?" with "Who cares? Here is a solution."

Title: Bug fixing approach


问:
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.

答:
Two things:

It's not enough to know a lot. You have to have opinions about what's worth implementing. I personally see TDD as a crutch that enables bad architecture. Given the sheer quantity of popular opinion that works against me on this, I'm probably wrong, but whether to implement TDD in JavaScript is not an issue I put any thought into, because debug has never been a massive headache for me and hey, it wouldn't be the first time popular opinion in the development community was later seen as flawed years later. So learn to be an arrogant prick. At least on the inside. You might be wrong but at least your committing to stuff that works for you rather than overthinking stuff that might not.

It sounds like you're starting with micro. Start with macro. First the tools you need to do the stuff your app needs to do. That part should come easily enough. Then start with architecture/interface concerns. How the plumbing connects and what it connects to should really just be the flimsy bits on top of everything that you can just swipe aside and replace on a whim. Likewise with the details of how things are done. Wrapped properly these can be replaced/edited with ease.

Title: Stuck due to "knowing too much"


问:
Materialized View vs POJO View based on Objects representing Oracle tables
I have about 12 Oracle tables that represent data that's being integrated from an external system into my web application.  This data is going to be used in an informational and comparative manner for the clients using my web application.

On one particular page of my web application, I need to combine data from 3 - 5 Oracle tables for display as an HTML table on the page.

We are NOT currently using a framework (Apache Struts for instance) and we're not in a position to move this Java web application into one at this moment (I'm trying to get us there...).

I am certainly not an architect, but I see one of two ways that I can effectively build this page (I know there are other ways, but these seem like they would be good ones...):
1.  Create an Oracle Materialized View that represents what the HTML table should look like and then create a POJO based on the View that I can then integrate into my JSP.
2.  Create POJOs that represent the Oracle tables themselves and then create another POJO that is the View used for the HTML table and then integrate that POJO into my JSP.

To me, it seems the Materialized View would possibly offer quicker results which is always what we strive for in web applications.  But, if I just create 12 POJOs that represent the Oracle tables and then build POJO Views off of those, I have the advantage of keeping all the code in one place for this and possibility for creating any number of different views and reusable components in my web application.

Any thoughts on which one might be the better route?  Or, maybe you know of an even better one?

答:
The most obvious drawback to a materialized view is its effect on inserts, updates, and deletes, or as a result of them.  If your database is non-volatile, this is a non-issue.

The second issue would be future maintenance--a change in requirements for the html table would require you to revise the JSP, your POJOs, your SQL, and your view.  If you were to move the logic of the view into your SQL, then that's one fewer thing to modify.

So, couldn't you simply have a pojo that is loaded by a query that runs against the 12 tables?  With the right indexes, it should still be somewhat performant. If it isn't, I'd say go with the Materialized View.


问:
Where could Distributed Version Control Systems currently be in Gartner's hype cycle?
Edit: Given the recent downvoting (+8/-6 at this point) it was made clear to me that Gartner's lifecycle is a biased metric from a programmer's perspective. This is something that is part of a paper I'm going to present to management, and management types are part of Gartner's audience.

Giving DVCS exposure & enthusiasm (that "could" be deemed as hype, or at least attacked as such), think about the following question when reading this one: "how could I use Gartner's hype cycle to convince management that DVCSs are ready (or ready-enough) for us, and that it is not just hype"

Just asking if DVCSs is hype wouldn't be constructive, Gartner's hype cycle is a more objective instrument than just asking that (even if this instrument is regarded as biased). If you know any other instrument please, by all means, mention it.

Edit #2: I agree that Gartner's Life Cycle is not for every technology, but I consider it may have generated enough buzz to be considered hype by some, so it maybe deserves to be at least evaluated/pondered as such by using this instrument in order to prove/disprove it to whatever degree. I'm an advocate of DVCS, BTW.

Edit #3: Thanks for your answers. Bounty goes to Caleb for answering my question with detail and practical advise. Accepted answer goes to philosodad for providing another useful instrument and answering beyond my question.

I'm doing research for a whitepaper I'm writing in favor of DVCS adoption at company and I stumbled upon the concept of social proof. I want to prove that the social proof of DVCS adoption is not necessarily cargo cult and doing further research I now stumbled upon Gartner's hype cycle which describes technology maturity in 5 phases.

My question is: what could be an indicator of the current location of Distributed Version Control Systems (I mean git, mercurial, bazaar, etc. in general) at a particular phase in the hype cycle?... in other (less convoluted) words, would you say that currently expectations of DVCSs are a) starting, b)inflated, c)decreasing (disillusionment), d)increasing (enlightenment) or e)stabilizing (mature) and (more importantly) why?

I know it is a hard question and there is subjectivity involved, but I'll grant the answer (and the traditional cookie) to the clearest argument/evidence for a particular phase.

答:
My Answer:

I think that the answer lies somewhere between "Internet TV" and "Cloud Computing" on the rising shoulder of the "Peak of Inflated Expectations" (Although I think that both of these have moved on somewhat rapidly in the past couple of years).

Nature of the Hype Cycle:

As I understand it, progression through the hype cycle is characterized by an evolving awareness about the pros and cons of a particular technology, rather than by any objective measure of "maturity" (whatever that means).

Before we have accumulated a sufficiently diverse set of experiences to build balanced (and independent) opinions, crowd dynamics (naturally) hold sway, with highly correlated opinions with little diversity, subtlety or depth of analysis.

This is as true in the "Trough of Disillusionment" as it is in the "Peak of Inflated Expectations"

If the community were to produce a wide and diverse range of different opinions, with in depth analysis about where and when it is appropriate to deploy DVCS and where and when it is not, then we can infer we are in the "Plateau of Productivity" (Or at least some way up the "Slope of Enlightenment").

If, on the other hand, the discourse is focussed on the superiority (or otherwise) of a technology without regard to the dips and folds of the competitive landscape upon which it stands, then we might infer that we are either on the "Peak of Inflated Expectations" or the "Trough of Disillusionment". We could even be in both phases at the same time, if the community is divided into camps by a flame war.

:-)

Evaluation of DVCS according to these criteria:

From the relatively shallow analysis that I have seen in the discourse so far, and the relative absence of negative commentary, I would estimate that we are currently climbing the "Peak of Inflated Expectations", with questions (such as this one) indicating that there are some who are preparing the slope down on the other side.

I think a strong indicator of the maturity of DVCS technology (from a corporate standpoint) will be when the debate shifts from asking simply "Why DVCS?" to "How can we best structure our workflow and processes around DVCS to maximise benefit to the organisation?".

From what I have seen, we are not all there yet. (Although some of our more sophisticated compatriots are leading the way)

The role of the Hype Cycle in decision making:

The "Hype Cycle" model is a model of behavioral bias, and it helps us understand our own mental state. If we can determine that a technology is hyped by others, then that may affect our own mental stance, and (at the risk of some double-think) we may need to compensate accordingly and force ourselves to behave rationally in choosing our selection criteria.

Selection Criteria:

Needless to say, selection criteria choices are extremely context dependent.

Personally I would do (as a sort of brainstorming exercise) a short (15 minute) SWOT analysis of each option that you are considering, together with (seriously) a PEST analysis of the situation to ensure that you bring broader (non-technological) factors in your analysis.

SWOT for Distributed VCS

Strengths:

Flexibility - more freedom to choose different workflows.

Better performance over low-bandwidth/high-latency network connections - better for distributed teams & off-site workers.

More sophisticated merge functionality, allowing you to branch more often. (I am not sure that this is a good thing).

Source code is "backed up" on each developers machine. (pretty bogus, this one, as it might interfere with proper disaster recovery planning)

Weaknesses:

Flexibility - Because we have more freedom to choose different workflows, we need to do additional work to define which workflow we are using, and to enforce it.

Complexity & Conceptual Difficulty (especially for non-software-developer team members).

Opportunities:

Perhaps the flexibility can be utilized to engineer a workflow that is better suited to business needs?

Threats:

Perhaps we will spend so long re-engineering our workflow we will loose focus on our core product?

It can be difficult to get some people to use even simple tools, especially if they do not believe that they are necessary or are otherwise not motivated.

SWOT for Centralized VCS

Strengths:

Provides an in-band implicit communications channel for business organisation & process.

Restricts possible workflows to a (in many cases reasonable) subset.

Makes it easier to set up CI & other development automation tools.

(SVN specific) Supports huge repositories.

(SVN specific) Very stable, used by lots of big, conservative organisations.

Politically more acceptable in a top-down command & control organization?

Weaknesses:

Inflexible.

Poor performance over low-bandwidth / high-latency connections, making it harder to use for distributed teams and off-site workers (especially if the repository gets big)

Opportunities:

Perhaps we can use the monolithic nature of the repository to help developers navigate the product and reuse each other's code more?

Threats:

If the project suddenly becomes hyper-important and we need to bring in additional developers working on other sites, can they effectively work with a SVN repository hosted (for them) off-site?

If the set of developers grows so large that coordinating them becomes difficult, will the single centralized repository become a bottleneck? (Can we get around this any other way?)

Conclusion:

Which VCS to use is dependent upon individual circumstance. For many of the situations in which I have worked, a DVCS with a centralized workflow would have done just fine, but I would have had to justify the time & effort to build out mechanism to support and enforce workflow, which would have been (still is) difficult.

Ultimately, I think that the discussion should center around the question: What workflow best suits our business? The best tool to use should follow naturally from the answer to that question.


答: Your stated requirements don't show the need for Materialized View. You could use regular views if you want. What will make the real difference is how you code the SQL and how you design the indexes in addition to how much data you fetch in each call to the database. You could even code the logic to combine the tables in stored procs and with single invocation get your results.</p>

Title: Materialized View vs POJO View based on Objects representing Oracle tables

Body:
I have about 12 Oracle tables that represent data that's being integrated from an external system into my web application.  This data is going to be used in an informational and comparative manner for the clients using my web application.

On one particular page of my web application, I need to combine data from 3 - 5 Oracle tables for display as an HTML table on the page.

We are NOT currently using a framework (Apache Struts for instance) and we're not in a position to move this Java web application into one at this moment (I'm trying to get us there...).

I am certainly not an architect, but I see one of two ways that I can effectively build this page (I know there are other ways, but these seem like they would be good ones...):
1.  Create an Oracle Materialized View that represents what the HTML table should look like and then create a POJO based on the View that I can then integrate into my JSP.
2.  Create POJOs that represent the Oracle tables themselves and then create another POJO that is the View used for the HTML table and then integrate that POJO into my JSP.

To me, it seems the Materialized View would possibly offer quicker results which is always what we strive for in web applications.  But, if I just create 12 POJOs that represent the Oracle tables and then build POJO Views off of those, I have the advantage of keeping all the code in one place for this and possibility for creating any number of different views and reusable components in my web application.

Any thoughts on which one might be the better route?  Or, maybe you know of an even better one?


问:
Using static in PHP
I have a few functions in PHP that read data from functions in a class

```<code>readUsername(int userId){
$reader = getReader();
return $reader->getname(userId);
}

readUserAddress(){
$reader = getReader();
return $reader->getaddress(userId);
}
</code>```

All these make a call to

```<code>getReader()
{
require_once("Reader.php");
static $reader = new Reader();
return $reader;
}
</code>```

An overview of Reader

```<code>class Reader{
getname(int id)
{
//if in-memory cache exists for this id return that
//else get from db and cache it
}

getaddress(int id)
{
 $this->getname(int id);
 //get address from name here
}

/*Other stuff*/

}
</code>```

Why is class Reader needed
The Reader class does some in-memory caching of user details. So, I need only one object of class Reader and it will cache the user details instead of making  multiple db calls.
I am using static so that it the object gets created only once. Is this the right approach or should I do something else?

答: Consider the Registry pattern, it provides a way of accessing global objects and avoids some drawbacks, that the Singleton has.</p>

Title: Using static in PHP


问:
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>

答: You can NOT develop operational software without knowing the Requirements; but, you can have a jolly good stab at developing what your experience tells you the Requirements are likely to be. Agile development uses a combination of 'intuitive' techniques, including the 80:20 Rule and the 'discovery' of Requirements by prototyping. In other words, an experienced development team makes a best guess at what's needed and produces a prototype of the software. The 80:20 Rule says they'll be 80% correct. The project stakeholders then review the tangible prototype. Their feedback begins to fill the 20% gap in our understanding of the Requirements. So, in effect, Agile isn't about writing software without any requirements, rather, it's about using your prior experience to say, "are you wanting something like this?" Which, in 80% of cases, will allow you to leap ahead and confirm what's really needed quicker than plodding through traditional Requirements processes.


问:
When to use abstract classes instead of interfaces with extension methods in C#?
"Abstract class" and "interface" are similar concepts, with interface being the more abstract of the two. One differentiating factor is that abstract classes provide method implementations for derived classes when needed. In C#, however, this differentiating factor has been reduced by the recent introduction of extension methods, which enable implementations to be provided for interface methods. Another differentiating factor is that a class can inherit only one abstract class (i.e., there is no multiple inheritance), but it can implement multiple interfaces. This makes interfaces less restrictive and more flexible. So, in C#, when should we use abstract classes instead of interfaces with extension methods?

A notable example of the interface + extension method model is LINQ, where query functionality is provided for any type that implements IEnumerable via a multitude of extension methods.

答: I'm in the process of implementing an Abstract class in my project simply because C# does not support operators (implicit conversions, in my case) on Interfaces.</p>


问:
Maybe monad vs exceptions
I wonder what are the advantages of Maybe monad over exceptions? It looks like Maybe is just explicit (and rather space-consuming) way of try..catch syntax.

update Please note that I'm intentionally not mentioning Haskell.

答:
Using Maybe (or its cousin Either which works basically the same way but lets you return an arbitrary value in place of Nothing) serves a slightly different purpose than exceptions. In Java terms, it's like having a checked exception rather than a runtime exception. It represents something expected which you have to deal with, rather than an error you did not expect.

So a function like indexOf would return a Maybe value because you expect the possibility that the item is not in the list. This is much like returning null from a function, except in a type-safe way which forces you to deal with the null case. Either works the same way except that you can return information associated with the error case, so it's actually more similar to an exception than Maybe.

So what are the advantages of the Maybe/Either approach? For one, it's a first-class citizen of the language. Let's compare a function using Either to one throwing an exception. For the exception case, your only real recourse is a try...catch statement. For the Either function, you could use existing combinators to make the flow control clearer. Here are a couple of examples:

First, let's say you want to try several functions that could error out in a row until you get one that doesn't. If you don't get any without errors, you want to return a special error message. This is actually a very useful pattern but would be a horrible pain using try...catch. Happily, since Either is just a normal value, you can use existing functions to make the code much clearer:

```<code>firstThing <|> secondThing <|> throwError (SomeError "error message")
</code>```

Another example is having an optional function. Let's say you have several functions to run, including one that tries to optimize a query. If this fails, you want everything else to run anyhow. You could write code something like:

```<code>do a <- getA
   b <- getB
   optional (optimize query)
   execute query a b
</code>```

Both of these cases are clearer and shorter than using try..catch, and, more importantly, more semantic. Using a function like <|> or optional makes your intentions much clearer than using try...catch to always handle exceptions.

Also note that you do not have to litter your code with lines like if a == Nothing then Nothing else ...! The whole point of treating Maybe and Either as a monad is to avoid this. You can encode the propagation semantics into the bind function so you get the null/error checks for free. The only time you have to check explicitly is if you want to return something other than Nothing given a Nothing, and even then it's easy: there are a bunch of standard library functions to make that code nicer.

Finally, another advantage is that a Maybe/Either type is just simpler. There is no need to extend the language with additional keywords or control structures--everything is just a library. Since they're just normal values, it makes the type system simpler--in Java, you have to differentiate between types (e.g. the return type) and effects (e.g. throws statements) where you wouldn't using Maybe. They also behave just like any other user-defined type--there is no need to have special error-handling code baked into the language.

Another win is that Maybe/Either are functors and monads, which means they can take advantage of the existing monad control flow functions (of which there is a fair number) and, in general, play nicely along with other monads.

That said, there are some caveats. For one, neither Maybe nor Either replace unchecked exceptions. You'll want some other way to handle things like dividing by 0 simply because it would be a pain to have every single division return a Maybe value.

Another problem is having multiple types of errors return (this only applies to Either). With exceptions, you can throw any different types of exceptions in the same function. with Either, you only get one type. This can be overcome with sub-typing or an ADT containing all the different types of errors as constructors (this second approach is what is usually used in Haskell).

Still, over all, I prefer the Maybe/Either approach because I find it simpler and more flexible.

Title: Maybe monad vs exceptions

Body:
Using Maybe (or its cousin Either which works basically the same way but lets you return an arbitrary value in place of Nothing) serves a slightly different purpose than exceptions. In Java terms, it's like having a checked exception rather than a runtime exception. It represents something expected which you have to deal with, rather than an error you did not expect.

So a function like indexOf would return a Maybe value because you expect the possibility that the item is not in the list. This is much like returning null from a function, except in a type-safe way which forces you to deal with the null case. Either works the same way except that you can return information associated with the error case, so it's actually more similar to an exception than Maybe.

So what are the advantages of the Maybe/Either approach? For one, it's a first-class citizen of the language. Let's compare a function using Either to one throwing an exception. For the exception case, your only real recourse is a try...catch statement. For the Either function, you could use existing combinators to make the flow control clearer. Here are a couple of examples:

First, let's say you want to try several functions that could error out in a row until you get one that doesn't. If you don't get any without errors, you want to return a special error message. This is actually a very useful pattern but would be a horrible pain using try...catch. Happily, since Either is just a normal value, you can use existing functions to make the code much clearer:

firstThing <|> secondThing <|> throwError (SomeError "error message")

Another example is having an optional function. Let's say you have several functions to run, including one that tries to optimize a query. If this fails, you want everything else to run anyhow. You could write code something like:

do a <- getA
   b <- getB
   optional (optimize query)
   execute query a b

Both of these cases are clearer and shorter than using try..catch, and, more importantly, more semantic. Using a function like <|> or optional makes your intentions much clearer than using try...catch to always handle exceptions.

Also note that you do not have to litter your code with lines like if a == Nothing then Nothing else ...! The whole point of treating Maybe and Either as a monad is to avoid this. You can encode the propagation semantics into the bind function so you get the null/error checks for free. The only time you have to check explicitly is if you want to return something other than Nothing given a Nothing, and even then it's easy: there are a bunch of standard library functions to make that code nicer.

Finally, another advantage is that a Maybe/Either type is just simpler. There is no need to extend the language with additional keywords or control structures--everything is just a library. Since they're just normal values, it makes the type system simpler--in Java, you have to differentiate between types (e.g. the return type) and effects (e.g. throws statements) where you wouldn't using Maybe. They also behave just like any other user-defined type--there is no need to have special error-handling code baked into the language.

Another win is that Maybe/Either are functors and monads, which means they can take advantage of the existing monad control flow functions (of which there is a fair number) and, in general, play nicely along with other monads.

That said, there are some caveats. For one, neither Maybe nor Either replace unchecked exceptions. You'll want some other way to handle things like dividing by 0 simply because it would be a pain to have every single division return a Maybe value.

Another problem is having multiple types of errors return (this only applies to Either). With exceptions, you can throw any different types of exceptions in the same function. with Either, you only get one type. This can be overcome with sub-typing or an ADT containing all the different types of errors as constructors (this second approach is what is usually used in Haskell).

Still, over all, I prefer the Maybe/Either approach because I find it simpler and more flexible.


答: Who said Agile was writing code in the absence of requirements? I know the Manifesto has been interpreted this way by some...but that doesn't make it right.</p>

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>


问:
How should I pitch moving to an agile/iterative development cycle with mandated 3-week deployments?
I'm part of a small team of four, and I'm the unofficial team lead (I'm lead in all but title, basically).  We've largely been a "cowboy" environment, with no architecture or structure and everyone doing their own thing.  Previously, our production deployments would be every few months without being on a set schedule, as things were added/removed to the task list of each developer.  Recently, our CIO (semi-technical but not really a programmer) decided we will do deployments every three weeks; because of this I instantly thought that adopting an iterative development process (not necessarily full-blown Agile/XP, which would be a huge thing to convince everyone else to do) would go a long way towards helping manage expectations properly so there isn't this far-fetched idea that any new feature will be done in three weeks.

IMO the biggest hurdle is that we don't have ANY kind of development approach in place right now (among other things like no CI or automated tests whatsoever).  We don't even use Waterfall, we use "Tell Developer X to do a task, expect him to do everything and get it done".

Are there any pointers that would help me start to ease us towards an iterative approach and A) Get the other developers on board with it and B) Get management to understand how iterative works?  So far my idea involves trying to set up a CI server and get our build process automated (it takes about 10-20 minutes right now to simply build the application to put it on our development server), since pushing tests and/or TDD will be met with a LOT of resistance at this point, and constantly force us to break larger projects into smaller chunks that could be done iteratively in a three-week cycle; my only concern is that, unless I'm misunderstanding, an agile/iterative process may or may not release the software (depending on the project scope you might have "working" software after three weeks, but there isn't enough of it that works to let users make use of it), while I think the expectation here from management is that there will always be something "ready to go" in three weeks, and that disconnect could cause problems.

On that note, is there any literature or references that explains the agile/iterative approach from a business standpoint?  Everything I've seen only focuses on the developers, how to do it, but nothing seems to describe it from the perspective of actually getting the buy-in from the businesspeople.

答:
Wayne, as specialist consultants in Agile adoption, I must say that the recommended approach is to employ a Mentor: someone who has been through the process before, and so knows what to expect and whether things are going right. Often, things are going right: but, if it's your first time, the lightweight nature of Agile will make you nervous.

Michael Durrant gives some very good advice. It is about 'people'. However, you're also correct to identify the need for a process. So, Wayne, choose one and adopt it! As simple as that. The point being that any process is better than no process. And, once you've adopted a process, you can then evaluate how well it is working. Only then can you decide what to tweak or change. Agile is about being daring; yet, because you'll be running in short iterations, it's easy to correct any errors. Being Agile applies as much to tweaking the process as it does to tweaking the software you're developing.

As for producing 'usable' software from a three week iteration cycle. Yes, that is possible. You need to focus on measurable Requirements. That way you'll deliver something meaningful. However, you will not produce a complete software suite with the piecemeal approach -- iterative development is about riquirements discovery (exploration) and risk management -- but, as your intuition is telling you, there's a bit more to it than simply piling iterations on top of each other. Also, as you're using XP, don't forget about the project's future documentation & training needs!

Most Agile adoption consultancies, like Gatethorn, will give some free advice to people who are getting going. Don't be afraid to give them a call. After all, we only know what help our customers need by answering questions on Forums or taking calls. So, Wayne, keep coming back to this Forum if you need help.

All the best, Richard (CEO Gatethorn Agile thinking)


答:
but every time I try to attack it, I end up spiraling in deep thoughts

There is nothing wrong. You have only noticed that it is time to improve your process: in this case, your thinking process.

Many people get lost in analysis or sidetracked in other ways and never even notice it. You have noticed so you can change your thinking process to stay on track.

There are many solutions to this, and the best one I have seen above is setting a time constraint. Before you start, decide how long (1 hour?) you will devote to analyzing and thinking about it. Set a timer.

Then, when the timer goes off, start the coding. If you find yourself thinking about things for too long again, just make an instant decision. Whatever you decide at that moment is the correct decision. You can always make changes and improvements later.

Besides, our environment is always changing. We often need to update our code to handle new requirements, new technology, new hardware, language and system updates, etc.

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.


问:
Why doesn't Visual Studio auto increment your version number?
This question asked how to auto update version number in VS 2010 :
https://stackoverflow.com/questions/4025704/publishing-in-net-produces-application-files-myapp-someversionnumber-how-to-ge

The answer was,
You have to update both Assembly Version AND File version manually

Shouldn't the version number increment each time I publish?  Why should I do it manually?  Is this is a conscious decision by MS to do it this way? What's the thinking behind having people manually update their own version number?

答: So two or more developers can publish their code under the same version.</p>


问:
Approach on working with many programmers on one module/feature
How can 2 or more developers code a certain feature/module of a software?  Let's assume that the module is big and feature rich.  How would they prevent each other from overlapping their code?  Say, we have the same method but is implemented in a different way.  Do you think it might be better to have one focused at a specific feature only?

Is a version control system like Git would help solve the problem?  Is it correct that it allows developers to have these "branches" and then merge it later on?

What's your take on this?

答:
In object oriented programming, there are a number of best practice revolves around high cohesion and the Single Responsibility Principle.  The basic idea is that each object should do one-and-only-one thing well.

If you follow this rule, then you run into a lot fewer conflicts.  Several implementations of a method?  Several Strategy objects containing the varying implementations.  Each developer can work on a different strategy--no conflicts.  (See the Strategy Pattern for more info on this).

Even if you are not doing OOP, the principle is still a good one.  Don't put all your code in one file, but only the code needed to do one thing.  Call that code from a master procedure, which one or two developers can own and maintain.

However you do it, you need to maintain good communication between team members.  Also, develop a good regression testing process (automated, preferably), so you know when a change is going to break something.


问:
Review quality of code
I have been asked to quality review two code bases. I've never done anything like that, and need advice on how to perform it and report it.

Background

There are two providers of code, one in VB and one in C (ISO 9899:1999 (C99)). These two programs do not work so well together, and of course, the two suppliers blames  each other. I will therefore as a independent person review both codes, on a comprehensive level review the quality of the codes to find out where it is most likely that the problem lies. I will not try to find problems, but simply review the quality and how simple it is to manage and understand the code.

Edit:
I have yet not received much information about what the problem consists of. I've just been told that I will examine the code in terms of quality. Not so much more. I do not know the background to why they took this decision.

答:
How much time have you been allocated - unless is rough order off magnitude is 20% - 50% of the development time for the apps you are reviewing, you are wasting your time and performing a political exercise to make someone feel good about it.

Most of the suggested things to look for are (although the best we know of) an inaccurate way to determine software quality, and very unlikely to standup up to rigorous scrutiny. Consider what you write in your report carefully - you may end up having to defend it in a witness box - how far is this dispute going to go, and how much money is at stake, are the parties wanting to find resolution or blame?

Assuming you are a programmer, not a forensic analyst with a programming specialization (In which case you would know not to have asked this question in a public forum), if I was you I would refuse the assignment in the strongest way I could. You are being set up to take a fall - playing software vendors off against each other with nothing but your opinion..... If one of those vendors finds this Q&A, how will that make you look....

Before you complete you report, you will need to be certain what it is going to be used for. Make sure it is phrased with statements such as "it appears" and "I believe" rather than absolutes such as "the code is crap". If you must make assertions - reference to published and widely accepted standards will be required. e.g. "The code does not meet the standards specified in the MISRA guidelines for C" is a fact, but stating that is should meet those guidelines would not be (unless your contract said so or they claimed it did).

OwnerDisplayName: magol

Title: Review quality of code


问:
Can a language support something like "Retry/Fix"?
I was just wondering if a language could support something like a Retry/Fix block?

The answer to this question is probably the reason it's a bad idea or equivalent to something else, but the idea keeps popping into my head.

```<code>void F()
{
  try
  {
    G();
  }
  fix(WrongNumber wn, out int x)
  {
    x = 1;
  }
}

void G()
{
  int x = 0;
  retry<int>
  {
    if(x != 1) throw new WrongNumber(x);
  }
}
</code>```

After the fix block ran, the retry block would run again...

答:
Yes, a language could do that.

There are examples in existing languages. Common Lisp provides a system which allows an exception (condition, in CL terminology) handler to return control to the point at which the exception was thrown, passing extra information about how the condition should be handled.

A good description of this is available in the book Practical Common Lisp, 19. Beyond Exception Handling: Conditions and Restarts

As other commenters have mentioned, Scheme's general continuation system could be used to implement this, and Eiffel provides similar functionality.

Thanks to @9000 and @delnan for bringing up Eiffel and call/cc in the comments on the question


问:
I can write code... but can't design well. Any suggestions?
I feel that I am good at writing code in bits and pieces, but my designs really suck. The question is, how do I improve my designs - and in turn become a better designer?

I think schools and colleges do a good job of teaching people how to become good at mathematical problem solving, but let's admit the fact that most applications created at school are generally around 1000 - 2000 lines long, which means that it is mostly an academic exercise which doesn't reflect the complexity of real world software - on the order of a few hundred thousand to millions of lines of code.

This is where I believe that even projects like topcoder / project euler also won't be of much help, they might sharpen your mathematical problem solving ability - but you might become an academic programmer; someone who is more interested in the nice, clean stuff, who is utterly un-interested in the day to day mundane and hairy stuff that most application programmers deal with.

So my question is how do I improve my design skills? That is, the ability to design small/medium scale applications that will go into a few thousand of lines of code? How can I learn design skills that will help me build a better html editor kit, or some graphics program like gimp?

答:
In my personal experience read others code is a good source of "inspiration". I mean try to understand other people designs and ask yourself why he/she do things in that way ?

you can find a lot of open-source projects for research.

anyway you need practice.


问:
Will HTML5/JS Eventually Replace All Client Side Languages?
I'm just wondering about the future of it all. IMHO, there are 4 forces that define where technology goes: Microsoft, Apple, Google, Adobe.

It looks like in Apple's iPhone/iPad iADs can now be programmed in HTML5. So does that mean HTML5 will eventually replace objective-c?

Also, Microsoft has now shifted it's focus from WPF/Silverlight to HTML5 and I assume Visual Studio 2011 will be all about tooling support for HTML5. Because that's what Microsoft do. (Tools). In a few months IE9 the last major browser will support HTML5.

Similarly Adobe is getting on the HTML5 bandwagon and allows to export flash content to HTML5 in their latest tools.

And we all know how much in bed Google is with html5. Heck, their latest Operating System (Chrome OS) is nothing but a big fat web browser.

Apps for Mobile (i.e., iPhone, Android, WM7) are very hard for a company to program especially for many different devices (each with their own language) so I'm assuming this won't last too long. I.e., HTML5 will be the unifying language. Which is somewhat sad for app developers because now users will be able to play the "cool" html5 apps for free on the web and it'll be hard to charge for them.

So are strongly-typed languages really doomed, and in the future, say 5-10 years, will client side programming only be in HTML5? Will all of us become javascript programmers? :) Because the signs are sure pointing that way...

答:
There is a will to replace application coding languages such as C++, Java... with HTML/Javascript. There are many reasons behind that, some of them:

Faster development

Cheaper workforce

Connectivity is built in

Easier to produce something that looks good

Text is accessible to indexing engines

Yet maybe other languages will appear, to be used as drop-in replacements for JavaScript. After all, it's hard to have a language that can do everything right, while staying a high level language! And JavaScript has been around for a while and accumulated some shortcomings.

JavaScript might very well end up being the major language for client side, yet I don't think it can nor should be the only language, because, JS being a standards-driven, designed-by-commitee language, this will simply kill innovation at that level (programming languages).

OwnerDisplayName: Shnitzel

LastEditorDisplayName: Shnitzel


问:
Headaches using distributed version control for traditional teams?
Though I use and like DVCS for my personal projects, and can totally see how it makes managing contributions to your project from others easier (e.g. your typical Github scenario), it seems like for a "traditional" team there could be some problems over the centralized approach employed by solutions like TFS, Perforce, etc. (By "traditional" I mean a team of developers in an office working on one project that no one person "owns", with potentially everyone touching the same code.)

A couple of these problems I've foreseen on my own, but please chime in with other considerations.

In a traditional system, when you try to check your change in to the server, if someone else has previously checked in a conflicting change then you are forced to merge before you can check yours in. In the DVCS model, each developer checks in their changes locally and at some point pushes to some other repo. That repo then has a branch of that file that 2 people changed. It seems that now someone must be put in charge of dealing with that situation. A designated person on the team might not have sufficient knowledge of the entire codebase to be able to handle merging all conflicts. So now an extra step has been added where someone has to approach one of those developers, tell him to pull and do the merge and then push again (or you have to build an infrastructure that automates that task).

Furthermore, since DVCS tends to make working locally so convenient, it is probable that developers could accumulate a few changes in their local repos before pushing, making such conflicts more common and more complicated.

Obviously if everyone on the team only works on different areas of the code, this isn't an issue. But I'm curious about the case where everyone is working on the same code. It seems like the centralized model forces conflicts to be dealt with quickly and frequently, minimizing the need to do large, painful merges or have anyone "police" the main repo.

So for those of you who do use a DVCS with your team in your office, how do you handle such cases? Do you find your daily (or more likely, weekly) workflow affected negatively? Are there any other considerations I should be aware of before recommending a DVCS at my workplace?

答:
A tool like SVN strongly encourages a tightly integrated way of working.

I.e. committing frequently to a shared branch (either trunk or a dev branch).

This is A-OK for most corporate development environments that I have experienced, and is facilitated and encouraged even further through the use of Continuous Integration supported by extensive integration tests, regression tests and unit tests (Helping individual developers gain confidence that they have not broken anything by their changes).

DVCS gives you the freedom to work more independently, which you do need in some situations, and the (much-vaunted) improved support for merges cannot do any harm whatsoever.

The worry that always lingers at the back of my mind is this: With great freedom comes the temptation to use that freedom.

Certainly, in my (limited) experience, I spend a lot more time working independently in my current team (using Mercurial) than I did in previous roles (Where we used SVN, CVS & P4).

This is only partially attributable to the tool, but I think that it is a reasonable observation to make that, absent a compelling reason to expend the effort on communication and coordination, people will tend to work apart and in isolation.

This is not necessarily a bad thing, but I believe that it is something that needs to be taken into consideration.


答:
If you want to work as a software developer at a startup, it's a skill to possess.

If you want to work at a consulting company then it's a situation to avoid at all costs.  This is because your firm gets paid according to how well you implement the spec/requirements and not how well you solved the customer's problem.

If you are coding for fun in your spare time, then it's your call.  If you don't feel qualified to make the call for your spare time projects then try a couple each way and see what works.  Also it's not necessary a one-size-fits-all thing, some projects call for one or the other type of a approach.  Usually if you pick the wrong one on one of these projects you'll figure it out pretty fast.


答:
From your comment on the question:

Once the reader object is created it uses some in-memory caching. So
  if I call reader twice for getName and getAddress I will be doing many
  things twice.

Looks like Reader should be implemented roughly this way:

```<code>class Reader {
   private $name;
   public function getName() {
      if (isset($this->name)) { return $this->name; }

      $this->name = // Pull it from the database or wherever
      return $this->name;
   }
}
</code>```

Usage is simple and straightforward, and getReader() probably isn't even necessary anymore:

```<code>require_once("Reader.php");
getReader()
{
   return new Reader();
}
</code>```

Title: Using static in PHP

Body:
I have a few functions in PHP that read data from functions in a class

```<code>readUsername(int userId){
$reader = getReader();
return $reader->getname(userId);
}

readUserAddress(){
$reader = getReader();
return $reader->getaddress(userId);
}
</code>```

All these make a call to

```<code>getReader()
{
require_once("Reader.php");
static $reader = new Reader();
return $reader;
}
</code>```

An overview of Reader

```<code>class Reader{
getname(int id)
{
//if in-memory cache exists for this id return that
//else get from db and cache it
}

getaddress(int id)
{
 $this->getname(int id);
 //get address from name here
}

/*Other stuff*/

}
</code>```

Why is class Reader needed
The Reader class does some in-memory caching of user details. So, I need only one object of class Reader and it will cache the user details instead of making  multiple db calls.
I am using static so that it the object gets created only once. Is this the right approach or should I do something else?

Body:
From your comment on the question:

Once the reader object is created it uses some in-memory caching. So
  if I call reader twice for getName and getAddress I will be doing many
  things twice.

Looks like Reader should be implemented roughly this way:

class Reader {
   private $name;
   public function getName() {
      if (isset($this->name)) { return $this->name; }

      $this->name = // Pull it from the database or wherever
      return $this->name;
   }
}

Usage is simple and straightforward, and getReader() probably isn't even necessary anymore:

require_once("Reader.php");
getReader()
{
   return new Reader();
}


问:
When calculating how many days between 2 dates, should you include both dates in the count, or neither, or 1?
I am trying to make an algorithm that counts the days between two dates, e.g. between 3/1/2012 and 3/2/2012.

What is the correct answer, or the most popular choice? Should be the one I use?

In this case, if I don't include both dates I am comparing, the days are 0; if I include one of them, the days are 1; if I include both, the days are 2.

答: I would answer 1 because they are one day apart.  There isn't a right answer to this though.  It depends on the requirements for what you want to accomplish.</p>


答: First what would make sense in your application if both dates were the same day? In my opinion the obvious answer is 0 and if that's your answer as well then the logical conclusion is to map dates that differ by one day to 1 and not 2. If you map dates that differ by a day to 2 then you have a gap and there is no way to map dates that don't coincide to 1. From a mathematical perspective things feel more consistent if there are no gaps.</p>

Title: When calculating how many days between 2 dates, should you include both dates in the count, or neither, or 1?

Body:
I am trying to make an algorithm that counts the days between two dates, e.g. between 3/1/2012 and 3/2/2012.

What is the correct answer, or the most popular choice? Should be the one I use?

In this case, if I don't include both dates I am comparing, the days are 0; if I include one of them, the days are 1; if I include both, the days are 2.


答: Do one thing and do it well, then document it and make sure your peers understand it well enough to use it. Having two people working on a very localized piece of code is just a waste of developer time and unless your entire module consists of two functions, in which case you are probably doing it wrong anyway, you can always split it up into pieces that can be worked on by individual programmers without interference. It's a simple formula that works and usually deviations from this simple workflow are a sign of a dysfunctional team. That last bit is just my opinion of things as I have observed them on the job.</p>

Title: Approach on working with many programmers on one module/feature

Body:
How can 2 or more developers code a certain feature/module of a software?  Let's assume that the module is big and feature rich.  How would they prevent each other from overlapping their code?  Say, we have the same method but is implemented in a different way.  Do you think it might be better to have one focused at a specific feature only?

Is a version control system like Git would help solve the problem?  Is it correct that it allows developers to have these "branches" and then merge it later on?

What's your take on this?


问:
Create many similar classes, or just one
The goal is to create an application that has objects that can represent some operations (add, subtract, etc).

All of those objects will have common functions and members, and thus will either implement an interface or inherit from an abstract class (Which would be better practice, this will be in C# if that matters?).

As far as I can see, there are two different ways of organizing all of these classes.

I could create an addition class, a subtraction class, etc. This has the upside of being highly modular but the difference between classes is so minimal.

I could create one class, and have a member that will say what type of operation is being represented. This means lots of switch statements, and losing some modularity, in addition to being harder to maintain.

Which is is better practice? Is there a better way of doing that is not listed above? If it matters, the list of functions that should be supported is long.

答:
.3. One base class, overriding implementations where needed in child classes.

Why? Main reason: Any changes required only happen in a single location and propagate to all dependents.


问:
How common are generic-case exponential time algorithms in production software?
I know that exponential time algorithms should generally be avoided but are sometimes necessary. A case being the Traveling Salesman. How common are such algorithms in production software? Are these cases typically necessary or a result of rush jobs? I understand that many can be solved with a good heuristic. What is typically done with those that cannot?</p>

答:
Let me take the example of travelling salesman problem.  I have worked on it a few times.

There are a few times when I have been in a team that wrote solution for travelling salesman problem but with some more parameters.  For example, it could be a store with a fleet of technicians and engineers each with a unique skill set.  The destinations come up every day in the form of service requests.  All the programs are in production though they have undergone modifications and maintenance since originally writing them.

This is how they worked.  Each engineer would receive a list of things to service on a hand held device everyday.  As they finish each service task, they should close the case.  The cases that are left out join the cases to be scheduled for the following day with slightly higher priority as by then the customer would have expressed some dissatisfaction.  There was a large set of reasons why an engineer would not attend a case.  Traffic problems were most common.

How common are they?  At least as common as number of after sale service requests coming from customers.  Without after sale service, for example, retaining customers is going to be hard and gaining new ones is going to be harder.

With many web based shops such as Amazon and other book stores and other such shops doing well in business, I would think travelling salesman is more common than it used to be.  Also, there could be many variations of the travelling salesman problem that are taught in text books.


答:
In an object-oriented world dominated by languages like Java and C#, option 1 is the way to go. There are different ways you can model your data, for example another way is with a tree that can be walked. But sticking with the spirit of your question, there are two approaches to consider. In both cases it is important to use interfaces. Writing programs on top of abstractions is far more flexible than writing them on top of concrete implementations.

The first approach is to extract common code into abstract super classes. This is really easy to do with languages like Java and C#, and at first glance seems like the obvious choice. The main problem with this approach is that it is too easy to conflate inheritance with the abstractions you are trying to create. I argue that these abstract classes created entirely to share common, but otherwise unimportant to inheritance, code are part of of the implementation, and thus shouldn't be relied upon in client code. This may or may not be a problem, but in either case there is nothing that can be done to prevent it from happening.

To remedy this, the second approach would be to to favor composition over abstract classes. While this is not as easy to implement as the first, it does address the problem left by abstract classes. Namely, there can be no reliance in the artifacts left by the implementation details of the abstract classes, as long as you properly encapsulate the composed objects. If, however, the abstract classes (if they even need to be abstract) are important to the inheritance hierarchy, and are thus more than just "common code buckets", then favoring composition will reduce the usefulness of the classes.

In the end I think it depends on whether the abstract classes are important to building a proper abstraction based on inheritance, or if the common code is just there to ease the burden of maintaining it. It may be flat-out annoying to implement if there are a lot of methods that just delegate to an encapsulated object, but that trade-off might be worth it for something more pure. However, some languages such as Ruby make it easy to support composition with its modules, which are basically mixins.

Title: Create many similar classes, or just one

Body:
The goal is to create an application that has objects that can represent some operations (add, subtract, etc).

All of those objects will have common functions and members, and thus will either implement an interface or inherit from an abstract class (Which would be better practice, this will be in C# if that matters?).

As far as I can see, there are two different ways of organizing all of these classes.

I could create an addition class, a subtraction class, etc. This has the upside of being highly modular but the difference between classes is so minimal.

I could create one class, and have a member that will say what type of operation is being represented. This means lots of switch statements, and losing some modularity, in addition to being harder to maintain.

Which is is better practice? Is there a better way of doing that is not listed above? If it matters, the list of functions that should be supported is long.


答:
I think it is a question of terminology and context.

If days between excludes the bounds, then the days between the two dates would be 0. Whereever this may be needed.

Date difference, i.e. how many days do I need to add to the start date to reach the end date: 1.

Or a date interval, including the bounds, e.g. how many leave days do I have from a start to an end date? Here the answer is 2.


答:
It depends on how much these classes have in common:

Nothing at all - make a bunch of standalone classes.

They have the same methods, but implement them all differently - make an interface and a bunch of classes that implement it.

They share some core functionality, but other functionality differs - make a base class and derive your classes from that.

Depending on the complexity of your classes, you may want to have more than one level in your class hierarchy if you go with the last option.

There's also a fourth option, which is especially viable if all your class needs to have is one operation: take a functional-programming approach and ditch the classes altogether. Instead, implement a function for each operation (in C#, this will have to be a static method somewhere, or you'll have to return lambdas from a factory method, as the language lacks free functions) and pass those around. Most likely, you want to declare a delegate type for this.


问:
Can a class be inside another class?
Here's an excerpt from "The C++ Programming Language"

```<code>template<classT> class List { // optimal
public:
class Link { /* ... */ };
List (); // initially empty
void put(T *); // put before current element
T* get(); // get current element
/ / ...
};
</code>```

Can we make a class inside another class ?
How about other languages? For PHP see this question

答:
Can we make a class inside another class ?

Yes, in C++ you can, it is called a nested class. However, this class is more like an extension of it's containing class, so don't forget that the sub class can access it's containing class members even if they are private.

See https://stackoverflow.com/questions/486099/can-inner-classes-access-private-variables … also http://codepad.org/UxxG4ixD

How about other languages?

You'll have to check fo each language but I know at least Python allow this, with different semantic. Don't assume features are providing exactly the same semantic between languages.

Title: Can a class be inside another class?


问:
A measure of development speed
I've seen a lot of tests measuring execution speed of programming languages, but I've never found tests measuring development speed.

I've heard development speed is increased when working with dynamic languages, but is there any proof of that ? I'm not trying to say dynamic languages aren't efficient, but I'd kind of like to see the results of a scientific study, if such a thing exists.

Even better would be informations on maintenance facility. Are some languages easier to debug than others ?

EDIT : I'm mostly interested in the differences between two languages that are close in syntax. For example, I guess programming in C will usually be slower than programming in Java; but is programming in Java faster than programming in C# ?

答:
For me this is kind of analogous to which type of paint brush lets you paint quicker.

If you consider what you paint a commodity, then the bigger the brush the quicker you will paint.

If you see good code as an art-form, then it is less abut the size of brush, and more what exactly you do with your brushes.

Sorry, this is a bit of a non-answer to the actual question.

Title: A measure of development speed


答:
It's called a nested class. Some languages (C++) allow it, others (PHP) don't.

It is not technically necessary for a language to support it, but sometimes, it helps prevent cluttering outer namespaces. In the case of STL, it makes for a neat way of organizing dependent types such as iterators (e.g. list<T>::iterator and vector<T>::iterator instead of list_iterator<T> and vector_iterator<T>, the former signalling functional dependency much more clearly).

Title: Can a class be inside another class?

Body:
Here's an excerpt from "The C++ Programming Language"

```<code>template<classT> class List { // optimal
public:
class Link { /* ... */ };
List (); // initially empty
void put(T *); // put before current element
T* get(); // get current element
/ / ...
};
</code>```

Can we make a class inside another class ?
How about other languages? For PHP see this question


答:
Ultimately, the correct answer to this is whatever your business requirements state.

However, when dealing with dates and time spans between dates, one generic way of looking at it to assume that any date that is expressed solely as a date (i.e. without a time portion) is to implicitly add 00:00 to the end of the date (midnight).

Now, calculate how many minutes of difference there is between the two date/times.  So using your example (and I'm assuming US Date format here), how many minutes to you have to add, one at a time, to 2/1/2012 00:00 before you reach 3/1/2012 00:00 ?

Once you've done that, convert your minutes to hours, then to day (divide by 60, then divide result by 24) and you'll have your number of days between the two dates.

Using this, it turns out there's 1 day between 2/1/2012 00:00 and 3/1/2012 00:00 which seems to be both logical and in accordance with the general thinking of most people here and those who design well used functions in this area (i.e. Java's java.util.Date or .NET's System.DateTime etc.)


答:
The principle of working with centralized repository is the same when working with non-locking centralized or distributed system:

In centralized system you:

Get the latest version from mainline ("trunk" in subversion, "master" in git, ...)

Modify the files

Merge the modifications with latest version from mainline using "update" command

Commit to mainline

In distributed system you:

Get the latest version from mainline

Modify the files

Commit locally

Merge the modifications with latest version from mainline and commit the result locally

Push to mainline.

No distributed version will allow you to push revision that does not fully merge the previous head revision (without special override; sometimes it's useful), so it won't go through without doing the merge step (so there won't be two versions somebody would have to consolidate as you concerned).

Now note that four of the steps are the same except for terminology, but distributed systems add an extra step "3. Commit locally". The big advantage of this step is that when the update/pull creates conflicts and you are not sure how to resolve them or make a mistake resolving them, you can go back, review what you did and redo the merge. Subversion won't remember any of those, so if you make a mistake resolving update, you are screwed.

As for accumulating changes, people tend to do that with centralized system too. Especially if you have to switch between features often (like interrupt some longer work to fix a bug or do some tweak that customer urgently needs), people will often need to keep changes locally simply because they are not finished. So it's better if the system at least supports making sense of it.

In either case these issues need to be addressed by proper guidelines and communication in the team and not the tools. With more flexible tools the guidelines are more important, but the more flexible tools allows better addressing various corner cases.

Title: Headaches using distributed version control for traditional teams?

Body:
Though I use and like DVCS for my personal projects, and can totally see how it makes managing contributions to your project from others easier (e.g. your typical Github scenario), it seems like for a "traditional" team there could be some problems over the centralized approach employed by solutions like TFS, Perforce, etc. (By "traditional" I mean a team of developers in an office working on one project that no one person "owns", with potentially everyone touching the same code.)

A couple of these problems I've foreseen on my own, but please chime in with other considerations.

In a traditional system, when you try to check your change in to the server, if someone else has previously checked in a conflicting change then you are forced to merge before you can check yours in. In the DVCS model, each developer checks in their changes locally and at some point pushes to some other repo. That repo then has a branch of that file that 2 people changed. It seems that now someone must be put in charge of dealing with that situation. A designated person on the team might not have sufficient knowledge of the entire codebase to be able to handle merging all conflicts. So now an extra step has been added where someone has to approach one of those developers, tell him to pull and do the merge and then push again (or you have to build an infrastructure that automates that task).

Furthermore, since DVCS tends to make working locally so convenient, it is probable that developers could accumulate a few changes in their local repos before pushing, making such conflicts more common and more complicated.

Obviously if everyone on the team only works on different areas of the code, this isn't an issue. But I'm curious about the case where everyone is working on the same code. It seems like the centralized model forces conflicts to be dealt with quickly and frequently, minimizing the need to do large, painful merges or have anyone "police" the main repo.

So for those of you who do use a DVCS with your team in your office, how do you handle such cases? Do you find your daily (or more likely, weekly) workflow affected negatively? Are there any other considerations I should be aware of before recommending a DVCS at my workplace?


答:
Sure thing! Although it doesn't do anything except change the scope and perhaps give structure to your code.

Also worth noting is Java's inner class feature. It's a nested class that can access instance variables of the enclosing class. E.g. if you have a class, Outer, which contains an inner class, Inner, you can access Outer's fields from within the inner class with the syntax Outer.this.banana (given that Outer has the field banana). In order to create an instance of an inner class one first has to have an instance of the outer class. This also means that an object of the inner class cannot outlive the its outer class. I find this a very handy feature of Java. To get the behavior of a normal nested class in Java, you declare it static.

Other languages that I'm aware of supporting nested classes (not necessarily inner classes) are C++, C# and python.

Title: Can a class be inside another class?