答:
I have a similar setup - our development lab cannot be connected to the internet (details not important, not a technical issue and nothing I can do about it so please please please take it as stated and  don't got there with comments). I have a desktop system with internet access.

Pros - I have 3 screens - 30" + 19" development and 24" wide screen for desktop. boss would never give me 3 off one box, and the insane amount of screen real estate really is useful.

Cons - Cut and paste between boxes does not exist. File transfer is difficult (I manage to burrow in with a couple of ssh tunnels, which may or may not be legit, so I eeor on teh side of asking forgiveness.....

Impact on productivity is neutral - learn to work within the environment you have. It will take less time than fighting the boss over it. I suggest you recite the poem about wisdom, serenity and courage.....


问:
Good practice or service for monitoring unhandled application errors for a small organization
I'm working with multiple software with varying ways of monitoring for errors. When I make software, I usually send email with the stack trace to admins(usually me). Some customer software is monitored by a team who check that a particular batch run was successfull. Other software might not have any monitoring at all(someone will call when things go wrong horribly).

Sending emails is good, except when things start going wrong, my mail gets filled fast. Also I don't want to solve the same problem in code for every software. Is there some relatively cheap and low maintenance software or practice to handle this. I want it to be cheap/low maintenance because usually I work alone or in teams of 5 or smaller. For example it would be great if errors would be aggregated so I don't get 10 000 emails when something unexpected happens...

For clarification: By unhandled errors I mean Exceptions that were unhandled by application code that were propagated to Tomcat or Jboss. I don't need help with how to catch those errors. I need help with what to do with them.

Is there any cloud application that I could send my errors to? Or some simple server to install? Or some library that can handle errors using configuration files. I use Java if that is any help.

答:
You have options...

Implement you own log4j/logback appender (WriteYourOwnAppender) that "does what you want"

Use an SMTPAppender that accumulates logging events in one or more fixed-size buffers and sends the contents of the appropriate buffer in an email after a user-specified event occurs

Use a DBAppender that inserts logging events into three database tables in a format independent of the Java programming language

Use a SocketAppender that is designed to log to a remote entity by transmitting serialized ILoggingEvent instances over the wire. You would have to take care of the receiving side of course.

Use a SyslogAppender a that sends a small message to a syslog receiver. The receiver is commonly called syslog daemon or syslog server. Logback can send messages to a remote syslog daemon. In short, it will send all your exceptions (errors, warnings, depending how you configure it in logback.properties/xml) to an OS syslog.

Or, there is Bug4J, that you can either use via Bug4jAppender or through the Bug4J agent. Both will write into a Bug4J server which has a web gui that looks a bit nicer than ChainSaw (which, btw, is another way..):

ContentLicense: CC BY-SA 3.0


问:
Triggering custom events in AJAX callbacks
I'm pretty new to JavaScript, but one of the things that's been frustrating is that our AJAX callbacks have been getting packed with different functionality, making it difficult to keep everything separated and organized.

I'm really new to programming, I have a feeling learning MVC a bit more would help me, but for now using custom events seems like it could help me keep my code a lot cleaner and prevent some problems. Here's what I'm talking about:

```<code>function myAjaxFunctionThatGetsTestData(){
    $.post('ajax/test.html', function(data) {
        $(document).trigger('testDataLoaded',data);
    });
}

function myOtherFunctionThatsDependentUponAjax(){
    getSomeTestData(); //start process of retrieving the data from ajax
    //then let me know when data has been retrieved
    $(document).one('testDataLoaded', function(data){
        alert (data);
    }
}

function getSomeTestData(){
    //maybe data was already retrieved by a different module, so check first
    if (data){
        $(document).trigger('testDataLoaded',data);
    }
    else{
        myAjaxFunctionThatGetsTestData();
    }
}
</code>```

I also don't know if it's ok that I'm triggering document or not...

Are there any patterns that look like this that I can read more about? What are the potential problems with this?

答:
Here's a simplified version of what you're trying to do.  And it's much easier to follow:

```<code>function myAjaxFunction(){
    $.post('ajax/test.html', function(data) {
        myOtherFunctionThatsDependentUponAjax(data);
    });
}

function myOtherFunctionThatsDependentUponAjax(){
    alert(data);
}
</code>```

This should also be possible, although I'm uncertain about JQuery idioms:

```<code>function myAjaxFunction(){
    $.post('ajax/test.html', myOtherFunctionThatsDependentUponAjax);
}

function myOtherFunctionThatsDependentUponAjax(){
    alert(data);
}
</code>```

Body:
Here's a simplified version of what you're trying to do.  And it's much easier to follow:

function myAjaxFunction(){
    $.post('ajax/test.html', function(data) {
        myOtherFunctionThatsDependentUponAjax(data);
    });
}

function myOtherFunctionThatsDependentUponAjax(){
    alert(data);
}

This should also be possible, although I'm uncertain about JQuery idioms:

function myAjaxFunction(){
    $.post('ajax/test.html', myOtherFunctionThatsDependentUponAjax);
}

function myOtherFunctionThatsDependentUponAjax(){
    alert(data);
}


答:
This is called an Event Bus, and it is a very useful way to decouple your code when you don't want each AJAX post (or any other action for that matter) to have to explicitly state what has to happen as a result.

```<code>// We've consolidated this functionality in an event manager, which gives us more power
// to log and recover from errors in event handlers.
EventManager.subscribe('ContentAdded', function(e) {
    // color every other row whenever content is added to the DOM.
    $('table.grid>tbody>tr:nth-child(even)', e.Content).addClass('even-row');
});
</code>```

Note how I can publish this event anywhere I want in code, and none of those places need to be aware of this code at all. I can also handle the event anywhere else I want, without being tightly coupled to the publishing code.

On the (ASP.NET MVC) project I work on, we have found this to be such an effective approach that we have almost eliminated any other kind of AJAX calls. We've got our event-driven framework to the point where most of our AJAX links use a single, global callback handler that simply publishes whatever events are returned from the server. Any modules that are interested in being notified when specific events occur can subscribe to these events globally.

I might create a link using code like this:

```<code>@Html.EventAction("Create Task", "CreateTask")
</code>```

... which my framework can render as HTML like this:

```<code><a href="/.../CreateTask" data-ajax="true" data-ajax-success="EventHandlers.Success">
    Create Task
</a>
</code>```

When the user clicks this link, it is hijacked to perform an AJAX request to an action like this:

```<code>public ActionResult CreateTask()
{
    if(!UserCanCreateTasks())
        return Events.ErrorResult("You don't have rights to create tasks.");

    Events.OpenModalDialog("Create Task", "TaskEditView", new TaskEditViewModel());
    return Events.Result();
}
</code>```

This would in turn generate a JSON object with a ModalDialogOpenedEvent, which includes the rendered contents of the dialog.

The EventHandlers.Success method will simply publish all the events that come back, indirectly causing a handler like this to be invoked:

```<code>EventManager.subscribe('ModalDialogOpenedEvent', function(e) {
    createDialog(e.Title, e.Contents);
});
</code>```

So our controlling logic can actually stay in our controller, and we have dramatically reduced the amount of custom javascript that we need to write for a given piece of functionality. We no longer need to write custom handler code for each type of button in our UI, and we don't have to worry about what happens when the server returns a response we didn't expect.

For example, if the user's session has timed out, the action code won't even get invoked: the server will immediately redirect the AJAX request to a login handler. We've written the login handler to be smart enough to detect if it's in an event-driven AJAX request and return an event that causes a login dialog to be opened. The request that the user was trying to make gets saved until the server returns an event to indicate that the login succeeded, and then it automatically gets retried. You can imagine how much extra code this would require if every AJAX request in our system had to be ready to handle this sort of corner case. But with an event-based system, it's a breeze.

Title: Triggering custom events in AJAX callbacks

Body:
I'm pretty new to JavaScript, but one of the things that's been frustrating is that our AJAX callbacks have been getting packed with different functionality, making it difficult to keep everything separated and organized.

I'm really new to programming, I have a feeling learning MVC a bit more would help me, but for now using custom events seems like it could help me keep my code a lot cleaner and prevent some problems. Here's what I'm talking about:

```<code>function myAjaxFunctionThatGetsTestData(){
    $.post('ajax/test.html', function(data) {
        $(document).trigger('testDataLoaded',data);
    });
}

function myOtherFunctionThatsDependentUponAjax(){
    getSomeTestData(); //start process of retrieving the data from ajax
    //then let me know when data has been retrieved
    $(document).one('testDataLoaded', function(data){
        alert (data);
    }
}

function getSomeTestData(){
    //maybe data was already retrieved by a different module, so check first
    if (data){
        $(document).trigger('testDataLoaded',data);
    }
    else{
        myAjaxFunctionThatGetsTestData();
    }
}
</code>```

I also don't know if it's ok that I'm triggering document or not...

Are there any patterns that look like this that I can read more about? What are the potential problems with this?

Body:
This is called an Event Bus, and it is a very useful way to decouple your code when you don't want each AJAX post (or any other action for that matter) to have to explicitly state what has to happen as a result.

// We've consolidated this functionality in an event manager, which gives us more power
// to log and recover from errors in event handlers.
EventManager.subscribe('ContentAdded', function(e) {
    // color every other row whenever content is added to the DOM.
    $('table.grid>tbody>tr:nth-child(even)', e.Content).addClass('even-row');
});

Note how I can publish this event anywhere I want in code, and none of those places need to be aware of this code at all. I can also handle the event anywhere else I want, without being tightly coupled to the publishing code.

On the (ASP.NET MVC) project I work on, we have found this to be such an effective approach that we have almost eliminated any other kind of AJAX calls. We've got our event-driven framework to the point where most of our AJAX links use a single, global callback handler that simply publishes whatever events are returned from the server. Any modules that are interested in being notified when specific events occur can subscribe to these events globally.

I might create a link using code like this:

@Html.EventAction("Create Task", "CreateTask")

... which my framework can render as HTML like this:

<a href="/.../CreateTask" data-ajax="true" data-ajax-success="EventHandlers.Success">
    Create Task
</a>

When the user clicks this link, it is hijacked to perform an AJAX request to an action like this:

public ActionResult CreateTask()
{
    if(!UserCanCreateTasks())
        return Events.ErrorResult("You don't have rights to create tasks.");

    Events.OpenModalDialog("Create Task", "TaskEditView", new TaskEditViewModel());
    return Events.Result();
}

This would in turn generate a JSON object with a ModalDialogOpenedEvent, which includes the rendered contents of the dialog.

The EventHandlers.Success method will simply publish all the events that come back, indirectly causing a handler like this to be invoked:

EventManager.subscribe('ModalDialogOpenedEvent', function(e) {
    createDialog(e.Title, e.Contents);
});

So our controlling logic can actually stay in our controller, and we have dramatically reduced the amount of custom javascript that we need to write for a given piece of functionality. We no longer need to write custom handler code for each type of button in our UI, and we don't have to worry about what happens when the server returns a response we didn't expect.

For example, if the user's session has timed out, the action code won't even get invoked: the server will immediately redirect the AJAX request to a login handler. We've written the login handler to be smart enough to detect if it's in an event-driven AJAX request and return an event that causes a login dialog to be opened. The request that the user was trying to make gets saved until the server returns an event to indicate that the login succeeded, and then it automatically gets retried. You can imagine how much extra code this would require if every AJAX request in our system had to be ready to handle this sort of corner case. But with an event-based system, it's a breeze.


问:
Organizing my products database
I’m developing a web-based store in MVC (very closely based on the SportsStore example in Pro ASP.Net MVC 3 Framework http://www.powells.com/biblio/61-9781430234043-0).

I’m using a SQL database and accessing it through System.Data.Entity.DbContext

I have a table that describes the products that I’m selling, with columns for name, description, price – this seems to work fine.

However, I also want to include images. I’ll probably have between 3 and 6 images per product that are about ~150KB each.

I think it would be convenient to store these images as binary data into another table in the database and include a column that identifies which product they’re related to. This should work but it seems inelegant – do you have a better suggestion?

I’d really like to keep the images in the database, that seems easier than storing paths to images in the database and separately uploading the images to a webserver.

答:
Storing binary image data in a database is not usually the best idea. See this Stack Overflow question. If you are going to have a lot of images it looks like using the filesystem will scale better, but that's something you could benchmark on your own to be sure. I'm also not sure that it is any easier to store the images in the database compared to just using the filesystem.

As for modeling the data, your inclination to have a separate images table with a foreign key to the product doesn't seem inelegant at all.

Title: Organizing my products database


问:
Learn programming backwards, or "so I failed the FizzBuzz test. Now what?"

A Little Background

I'm 28 today, and I've never had any formal training in software development, but I do have two higher education degrees equivalent to a B.A in Public Relations and an Executive MBA focused on Project Management. I've worked on those fields for about 6 years total an then, 2,5 years ago I quit/lost my job and decided to shift directions.

After a month thinking things through I decided to start freelancing developing small websites in WordPress. I self-learned my way into it and today I can say I run a humble but successful career developing themes and plugins from scratch for my clients - mostly agencies outsourcing some of their dev work for medium/large websites.

But sometimes I just feel that not having studied enough math, or not having a formal understanding of things really holds me behind when I have to compete or work with more experienced developers. I'm constantly looking for ways to learn more but I seem to lack the basics.

Unfortunately, spending 4 more years in Computer Science is not an option right now, so I'm trying to learn all I can from books and online resources. This method is never going to have NASA employ me but I really don't care right now. My goal is to first pass the bar and to be able to call myself a real programmer.

I'm currently spending my spare time studying Java For Programmers (to get a hold on a language everyone says is difficult/demanding), reading excerpts of Code Complete (to get hold of best practices) and also Code: The Hidden Language of Computer Hardware and Software (to grasp the inner workings of computers).

TL;DR

So, my current situation is this: I'm basically capable of writing any complete system in PHP (with the help of Google and a few books), integrating Ajax, SQL and whatnot, and maybe a little slower than an experienced dev would expect due to all the research involved.

But I was stranded yesterday trying to figure out (not Google) a solution for the FizzBuzz test because I didn't have the if($n1 % $n2 == 0) method modulus operator memorized.

What would you suggest as a good way to solve this dilemma? What subjects/books should I study that would get me solving problems faster and maybe more "in a programmers way"?

EDIT - Seems that there was some confusion about what did I not know to solve FizzBuzz.

Maybe I didn't express myself right: I knew the steps needed to solve the problem. What I didn't memorize was the modulus operator. The problem was in transposing basic math to the program, not in knowing basic math.

I took the test for fun, after reading about it on Coding Horror. I just decided it was a good base-comparison line between me and formally-trained devs.

I just used this as an example of how not having dealt with math in a computer environment before makes me lose time looking up basic things like modulus operators to be able to solve simple problems.

答:
You may think FizzBuzz is a toy problem; when will I ever need to use the modulus operator in a real program.  But really you use it all the time.  Three common examples:

You are displaying a table and you want alternating background colors for different rows.  You check if a row is even (row_number % 2 == 0) and display one color for even  rows and one for odd rows.

You have a collection of objects that you are looping through and you want to print out a table with N objects per row; then the criterion for when to add a line break is (item_number % N == 0).  I actually had a SO question on this exact behavior though in that templating language the condition if item_number % N == 0 was written as the equivalent (if item_number|divisbleby: N).

You are doing several operations that you want to group into a transaction that only gets committed when the group gets to a certain size for efficiency reasons.  Maybe you are using the google data API and you don't want the HTTP header/authentication overhead for creating a new transaction for each operation, so you are batching them together into groups of 50 operations.  Or you are saving records to your database and want to commit the transaction when its a reasonable size.  Something like if cur_item_number % 50 == 0 then commit_data.

Sure there are other ways of doing all these things.  But you can do fizz buzz without using the modulus operator or comparing float division to integer division.  For example, for FizzBuzz you could do something like the following pseudo-code.

```<code>div_by_3_rem = 0
div_by_5_rem = 0
for(i = 0; i< 50; i++) {
    if(div_by_3_rem == 0 && div_by_5_rem == 0) {
       print "FizzBuzz"
    } elif(div_by_3_rem == 0) {
       print "Fizz"
    } elif(div_by_5_rem == 0) {
       print "Buzz"
    } else {
       print i
    }
    div_by_3_rem += 1
    div_by_5_rem += 1
    if(div_by_3_rem == 3) {
       div_by_3_rem = 0
    }
    if(div_by_5_rem == 5) {
       div_by_5_rem = 0
    }
}
</code>```

To conclude, if you want to be a great programmer someday, don't jump into learn a language books.  Yes, a PHP/Java book will have you getting answers from google/stackoverflow and half-working programs much faster than anything else.  But to actually be able to know how to write quality optimal programs and think like a programmer you need some exposure to a real CS books.

Start with a CS book that introduces a programming language and the CS background, with the famous example of Structure and Interpretation of Computer Programs (which will teach Scheme -- a Lisp dialect) or possibly something else like Think Python How to Think Like a Computer Scientist (which I have not read).  Both of these are free online.

You need to eventually read a good algorithms book, the best being CLRS's Algorithms (not free), though this free online algorithms book could be a low-cost replacement (though if you can just buy CLRS).  The algorithms book will teach you how to think solve computer problems and introduce you to a variety of data structures (Arrays/Linked Lists/Heaps/Binary Trees/B-Trees/HashTables) and important algorithms that you need to know how to use optimally.  You don't need to memorize every proof or know how to perfectly write every algorithm (who ever uses a Fibonacci Heap); but you should intuitively know two nested for loop is O(N^2); comparison sorts are at best O(N lg N), binary search is O(lg N), can find median in O(N), why hard disk databases use B-Trees, etc.).  At a minimum, strong knowledge of the algorithms book will help you ace technical programming interviews of the google/facebook variety.  When reading programming books, don't just skim/read; you'll learn much better if you work/code through examples and problems, and actively think through the logic.

I'd also recommend a book on software engineering (either Code Complete or Pragmatic Programmer) after you get through the CS and algorithms book, which will teach best practices of how to write good code that is maintainable (clear names; comment just when necessary; keep code together; refactor when necessary; use version control; etc).

Body:
You may think FizzBuzz is a toy problem; when will I ever need to use the modulus operator in a real program.  But really you use it all the time.  Three common examples:

You are displaying a table and you want alternating background colors for different rows.  You check if a row is even (row_number % 2 == 0) and display one color for even  rows and one for odd rows.

You have a collection of objects that you are looping through and you want to print out a table with N objects per row; then the criterion for when to add a line break is (item_number % N == 0).  I actually had a SO question on this exact behavior though in that templating language the condition if item_number % N == 0 was written as the equivalent (if item_number|divisbleby: N).

You are doing several operations that you want to group into a transaction that only gets committed when the group gets to a certain size for efficiency reasons.  Maybe you are using the google data API and you don't want the HTTP header/authentication overhead for creating a new transaction for each operation, so you are batching them together into groups of 50 operations.  Or you are saving records to your database and want to commit the transaction when its a reasonable size.  Something like if cur_item_number % 50 == 0 then commit_data.

Sure there are other ways of doing all these things.  But you can do fizz buzz without using the modulus operator or comparing float division to integer division.  For example, for FizzBuzz you could do something like the following pseudo-code.

div_by_3_rem = 0
div_by_5_rem = 0
for(i = 0; i< 50; i++) {
    if(div_by_3_rem == 0 && div_by_5_rem == 0) {
       print "FizzBuzz"
    } elif(div_by_3_rem == 0) {
       print "Fizz"
    } elif(div_by_5_rem == 0) {
       print "Buzz"
    } else {
       print i
    }
    div_by_3_rem += 1
    div_by_5_rem += 1
    if(div_by_3_rem == 3) {
       div_by_3_rem = 0
    }
    if(div_by_5_rem == 5) {
       div_by_5_rem = 0
    }
}

To conclude, if you want to be a great programmer someday, don't jump into learn a language books.  Yes, a PHP/Java book will have you getting answers from google/stackoverflow and half-working programs much faster than anything else.  But to actually be able to know how to write quality optimal programs and think like a programmer you need some exposure to a real CS books.

Start with a CS book that introduces a programming language and the CS background, with the famous example of Structure and Interpretation of Computer Programs (which will teach Scheme -- a Lisp dialect) or possibly something else like Think Python How to Think Like a Computer Scientist (which I have not read).  Both of these are free online.

You need to eventually read a good algorithms book, the best being CLRS's Algorithms (not free), though this free online algorithms book could be a low-cost replacement (though if you can just buy CLRS).  The algorithms book will teach you how to think solve computer problems and introduce you to a variety of data structures (Arrays/Linked Lists/Heaps/Binary Trees/B-Trees/HashTables) and important algorithms that you need to know how to use optimally.  You don't need to memorize every proof or know how to perfectly write every algorithm (who ever uses a Fibonacci Heap); but you should intuitively know two nested for loop is O(N^2); comparison sorts are at best O(N lg N), binary search is O(lg N), can find median in O(N), why hard disk databases use B-Trees, etc.).  At a minimum, strong knowledge of the algorithms book will help you ace technical programming interviews of the google/facebook variety.  When reading programming books, don't just skim/read; you'll learn much better if you work/code through examples and problems, and actively think through the logic.

I'd also recommend a book on software engineering (either Code Complete or Pragmatic Programmer) after you get through the CS and algorithms book, which will teach best practices of how to write good code that is maintainable (clear names; comment just when necessary; keep code together; refactor when necessary; use version control; etc).


问:
When/why is it easier to beg forgiveness than ask permission?
The saying "It's easier to beg forgiveness than ask permission" seems pretty popular among programmers and IIRC was attributed to Grace Hopper.  In what situations is this typically true, and why do you believe that such a counterintuitive proposition would hold?</p>

答:
In a hierarchical organization the upper management typically has no clue about the subject matter you're working on; then their decisions are, inevitably, based on how you represent your suggestions to them. Representing technical ideas to non-technical people is notoriously hard: if you explain it as it is, they don't understand anything and might refuse just because of that. And if you explain it so that they understand, you're not stating the thing as it is. Is it ethical either, huh? Thus is it may be best to just do the right thing instead of trying to explain that in such a flowery  and falseful manner that the management agrees with it.

It's not irresponsible. Even if you asked for permission, the result would strongly depend on how you represented your issue. Since you're able to affect the decision this way, why bother? Just do it and screw bureaucracy. At least you're not lying then. The key point is that you know it's the right thing to do.

Of course, you have to be pretty damn sure you're right, since you're now the one taking the risk. What you're saving is your and management's time and effort; not a small feat.

ContentLicense: CC BY-SA 2.5


答:
If you're talking low to medium numbers of images (say, under a couple or ten thousand) and low to medium traffic, its just not going to matter much where you put them.  Either will work.

There are some significant benefits to storing them in the file system, though, especially for a web app.  Primarily that the image is servable without a database connection.  So you wont need a script to extract the image out of the database and serve it up.  For low levels of traffic, reading blobs wont have a noticable impact.  But under high load, you'll quickly see things slowing down as the database server is spending all its time and effort retrieving images.

Storing in the filesystem is not difficult.  Set up a path where you'll store them (/images).  Keep a table in the db that stores their metadata (name, product id, etc).  And then save the files there based on their unique row id in that table.  1.jpg, 2.jpg, etc.  This is very easy to do if you have a web-based image upload in your app.  If you end up with many images, you just create a new directory for each 'thousands', so '4000.jpg' is stored in '4/4000.jpg'.

Title: Organizing my products database

Body:
I’m developing a web-based store in MVC (very closely based on the SportsStore example in Pro ASP.Net MVC 3 Framework http://www.powells.com/biblio/61-9781430234043-0).

I’m using a SQL database and accessing it through System.Data.Entity.DbContext

I have a table that describes the products that I’m selling, with columns for name, description, price – this seems to work fine.

However, I also want to include images. I’ll probably have between 3 and 6 images per product that are about ~150KB each.

I think it would be convenient to store these images as binary data into another table in the database and include a column that identifies which product they’re related to. This should work but it seems inelegant – do you have a better suggestion?

I’d really like to keep the images in the database, that seems easier than storing paths to images in the database and separately uploading the images to a webserver.


问:
Is WCF a good fit for this problem?
I'm working to implement a data service solution that has 2 request functions but can respond with one of 3 transmission types:

x12 EDI

HTTP MIME multipart

SOAP/XML + WSDL

I would also need to include logging and username/password authentication to the services. I'm in the very early learning stages of WCF. Is WCF a good fit for this?

答: Yes, WCF is a good fit for this.  It supports everything in your list.</p>

Title: Is WCF a good fit for this problem?


答:
May I recommend learning JavaScript before Java, C++?  Reasons for you:

Used in front-end design (jQuery, some of your WordPress plugins, Twitter feeds, loading databases into your browser via JSON with little to no back-end work, form validation, etc)

Can be used server-side via Node.js

Can be used to build hybrid apps for iOS, Android, Win8, etc

Studying JS will help you understand webpage performance in different browsers & devices better

JS was designed to be more newbie friendly

You already know HTML & CSS (I hope ;), so that helps with JS

Free Newbie Resources

http://www.codecademy.com/tracks/code-year

https://stackoverflow.com/tags/javascript/info

I had about 10 more links, but SE won't let me post them until I hit 10 rep.

Learning C++, Java, etc are also helpful, but not IMHO does not have the over all impact on web programming as JS does, since you can use it on both front & back end.
Have fun!

Title: Learn programming backwards, or "so I failed the FizzBuzz test. Now what?"

Body:
A Little Background

I'm 28 today, and I've never had any formal training in software development, but I do have two higher education degrees equivalent to a B.A in Public Relations and an Executive MBA focused on Project Management. I've worked on those fields for about 6 years total an then, 2,5 years ago I quit/lost my job and decided to shift directions.

After a month thinking things through I decided to start freelancing developing small websites in WordPress. I self-learned my way into it and today I can say I run a humble but successful career developing themes and plugins from scratch for my clients - mostly agencies outsourcing some of their dev work for medium/large websites.

But sometimes I just feel that not having studied enough math, or not having a formal understanding of things really holds me behind when I have to compete or work with more experienced developers. I'm constantly looking for ways to learn more but I seem to lack the basics.

Unfortunately, spending 4 more years in Computer Science is not an option right now, so I'm trying to learn all I can from books and online resources. This method is never going to have NASA employ me but I really don't care right now. My goal is to first pass the bar and to be able to call myself a real programmer.

I'm currently spending my spare time studying Java For Programmers (to get a hold on a language everyone says is difficult/demanding), reading excerpts of Code Complete (to get hold of best practices) and also Code: The Hidden Language of Computer Hardware and Software (to grasp the inner workings of computers).

TL;DR

So, my current situation is this: I'm basically capable of writing any complete system in PHP (with the help of Google and a few books), integrating Ajax, SQL and whatnot, and maybe a little slower than an experienced dev would expect due to all the research involved.

But I was stranded yesterday trying to figure out (not Google) a solution for the FizzBuzz test because I didn't have the if($n1 % $n2 == 0) method modulus operator memorized.

What would you suggest as a good way to solve this dilemma? What subjects/books should I study that would get me solving problems faster and maybe more "in a programmers way"?

EDIT - Seems that there was some confusion about what did I not know to solve FizzBuzz.

Maybe I didn't express myself right: I knew the steps needed to solve the problem. What I didn't memorize was the modulus operator. The problem was in transposing basic math to the program, not in knowing basic math.

I took the test for fun, after reading about it on Coding Horror. I just decided it was a good base-comparison line between me and formally-trained devs.

I just used this as an example of how not having dealt with math in a computer environment before makes me lose time looking up basic things like modulus operators to be able to solve simple problems.


问:
What is the term for a really BIG source code commit?
Sometimes when we check the commit history of a software, we may see that there are a few commits that are really BIG - they may change 10 or 20 files with hundreds of changed source code lines (delta). I remember that there is a commonly used term for such BIG commit but I can't recall exactly what that term is. Can anyone help me? What is the term that programmers usually use to refer to such BIG and giant commit?

BTW, is committing a lot of changes all together a good practice?

UPDATE: thank you guys for the inspiring discussion! But I think "code bomb" is the term that I'm looking for.

答:
(1) Ben Collins-Sussman: "... "code bombs". That is, what do you do when somebody shows up to an open source project with a gigantic new feature that took months to write? Who has the time to review thousands of lines of code? ..."

(2) Dan Fabulich: "The Code Bomb, or: The Newbie with Big Ideas ... A code bomb is a patch that's so large that no one can review it."

(3) Google Summer of Code: Guidelines: "Commit early, commit often ... Please do not work the whole day and then push everything out in a single code bomb. Instead, every commit should be self-contained to one task only which should be summarized in the log message."

(4) Jeff Atwood: "code-bombs ... Rule #30: Don't go dark. ...


答:
I would seriously recomend you keep your images in a folder under the root directory of your web server ("htdocs" or equivalent) and store a reference to the file name in your database.

That way you can select the file reference from the database and copy it into an html "img" tag and let your webserver and browser do the heavy lifting.

There are several advantages to this:-

smaller more efficient database.

much faster sql response -- no large blobs to handle

much simpler program code

faster response times for your users as the web server will serve image files faster than you can stream them.

much faster response times if they re-visit your site because many of the images will be cached in their browser.

Title: Organizing my products database


问:
How do you manage projects left over by other employees?
It happens that some one just leaves the company all of sudden. Now his work needs to be completed and you are being assigned it. Having no idea what was he up to (was it 90% done or 9%), how do you manage the leftover?

Shall I start from scratch? What if it was 90% done?

Shall I try and understand whatever he has done? What if it was just nonsense?

答:
In order to figure out what to do, you need to know what you have, and how good shape it is in.

So, start with having a quick look of all the source and see what you have.  If it is vividly clear then it is easiest to just finish what is missing.  Do unit tests to find out what works and what doesn't.

If it isn't vividly clear then start figuring out what works with new unit tests.  If this is impossible then bring out with your team leader that you have an issue and that you may not be able to make it.  He can then decide if the left work should be salvaged anyway or if it is just too bad and you need to redo it.


答:
I think it's much more complicated that you think. Here are my two views on the problem:

Asking cost nothing

I'm always amazing when I hear discussion about salary increase. People complaint they are not increased. But if they don't ask (unless they are in an administration automatic and predefined salary increase), they will get nothing by just waiting.

It's the same with the car of the neighbor you want to borrow... You may think "he will think I'm ....." or "She won't accept because ....." or "He will probably need it anyway ....".

The truth is that you don't know until you ask. However, the way our brain work will fill our mind with unhelpful thought that you created yourself. In most case, they are false.

So asking may be the first thing to try.

Do it instead of asking will prevent you from a refusal. If you fail, you can apologize

This statement is also true because in enterprise where responsabilities are clearly defined and where people are rated on their individual achievement.

If you ask the responsible of another department for something that may (thought he creates) affect him negatively, but the outcome (if positive), will not affect him, he will surely refuse, to be safe.

Two answers are very similar: fear. In the first answer it's YOUR fear, in the second is the fear of THEM.

To overcome fear of others, don't ask. In many many case, you will succeed, and in case of failure, then yes... apologize will be enought.

Not in most case unfortunaly, but that's a risk YOU MUST take in order to advance in both life and your career.

Title: When/why is it easier to beg forgiveness than ask permission?

Body: The saying "It's easier to beg forgiveness than ask permission" seems pretty popular among programmers and IIRC was attributed to Grace Hopper.  In what situations is this typically true, and why do you believe that such a counterintuitive proposition would hold?</p>


答:
You definitely need to try and run the software to see what works and what doesn't.

You'll then need to consider what documentation has been left.  Are there written requirements?  Are there specific tasks - are tasks tracked in some way?  Has anyone been testing it - if so, they'll know what's done and what not.

I think a plan of action would be:

Mark off which requirements have been completed (by a quick run through of the system like a tester would)

Look at the code - can you make sense of it? Is it well written?

Clearly if it's 90% done and the code is well written, you'd just finish it off.

Title: How do you manage projects left over by other employees?

Body:
It happens that some one just leaves the company all of sudden. Now his work needs to be completed and you are being assigned it. Having no idea what was he up to (was it 90% done or 9%), how do you manage the leftover?

Shall I start from scratch? What if it was 90% done?

Shall I try and understand whatever he has done? What if it was just nonsense?


问:
Should I add an "Abstract" prefix to my abstract classes?
Suppose I have an abstract class named Task.

Is there a standard or convention that would suggest I should name it AbstractTask instead?

答:
My five cents, Probably you'll have implementations of that abstract class and they will be named 'SomeSpecificTask', 'TaskWithBubbles', 'StrangeTask' etc. So there won't be a name clash between your abstract 'Task' and them.

Additionally, 'abstract' word is about language syntax, not business domain entities, so I'd prefer not to use it as a part of the name.

On the other hand, in one answer here I saw excerpt from J.Bloch Effective Java which says that using 'abstract' as a part of a name is a well-established practice. It may be so. But anyway in official java code conventions there is nothing about that.


问:
Is it bad practice to use an interface for categorization only?
For example:

Say I have classes A, B, C. I have two interfaces, lets call them IAnimal and IDog. IDog inherits from IAnimal. A and B are IDogs, while C is not, but it is an IAnimal.

The important part is that IDog supplies no additional functionality. It is only used to allow A and B, but not C, to be passed as an argument to certain methods.

Is this bad practice?

答:
I only know C# well, so I can't say this for OO programming in general, but as a C# example, if you need to categorize classes the obvious options are interfaces, enum property or custom attributes. Usually I would choose the interface no matter what others think. </p>

```<code>if(animal is IDog)
{
}
if(animal.Type == AnimalType.Dog)
{
}
if(animal.GetType().GetCustomAttributes(typeof(DogAttribute), false).Any())
{
}

var dogs1 = animals.OfType<IDog>();
var dogs2 = animals.Where(a => a.Type == AnimalType.Dog);
var dogs3 = animals.Where(a => a.GetType().GetCustomAttributes(typeof(DogAttribute), false).Any());

var dogsFromDb1 = session.Query<IDog>();
var dogsFromDb2 = session.Query<Animal>().Where(a => a.Type == AnimalType.Dog);
var dogsFromDb3 = session.Query<Animal>().Where(a => a.GetType().GetCustomAttributes(typeof(DogAttribute),false).Any());

public void DoSomething(IDog dog)
{
}
public void DoSomething(Animal animal)
{
    if(animal.Type != AnimalType.Dog)
    {
        throw new ArgumentException("This method should be used for dogs only.");
    }
}
public void DoSomething(Animal animal)
{
    if(!animal.GetType().GetCustomAttributes(typeof(DogAttribute), false).Any())
    {
        throw new ArgumentException("This method should be used for dogs only.");
    }
}
</code>```

Body:
I only know C# well, so I can't say this for OO programming in general, but as a C# example, if you need to categorize classes the obvious options are interfaces, enum property or custom attributes. Usually I would choose the interface no matter what others think.

if(animal is IDog)
{
}
if(animal.Type == AnimalType.Dog)
{
}
if(animal.GetType().GetCustomAttributes(typeof(DogAttribute), false).Any())
{
}

var dogs1 = animals.OfType<IDog>();
var dogs2 = animals.Where(a => a.Type == AnimalType.Dog);
var dogs3 = animals.Where(a => a.GetType().GetCustomAttributes(typeof(DogAttribute), false).Any());

var dogsFromDb1 = session.Query<IDog>();
var dogsFromDb2 = session.Query<Animal>().Where(a => a.Type == AnimalType.Dog);
var dogsFromDb3 = session.Query<Animal>().Where(a => a.GetType().GetCustomAttributes(typeof(DogAttribute),false).Any());

public void DoSomething(IDog dog)
{
}
public void DoSomething(Animal animal)
{
    if(animal.Type != AnimalType.Dog)
    {
        throw new ArgumentException("This method should be used for dogs only.");
    }
}
public void DoSomething(Animal animal)
{
    if(!animal.GetType().GetCustomAttributes(typeof(DogAttribute), false).Any())
    {
        throw new ArgumentException("This method should be used for dogs only.");
    }
}


答:
In addition to what others wrote, I would suggest you talk to anyone who had direct contact to the guy. I understand from your description that he was working alone, still he must have been reporting to someone? And there may be QA personnel having tested what he had produced... These persons should (normally) have at least a rough idea of how far the guy got with his project before leaving. Unless of course the info/product supplied by him turned out to be completely unreliable, contributing to his layoff.

Discuss this with your manager and allocate a time frame for the initial exploration / testing of leftover code, and understanding the specification and requirements. This could be roughly a day for a project on the time scale of a few person months, at most a week for a project of one or more person year's work, etc.

After this initial exploration, you should have a rough estimation of

what the product is supposed to do,

what can it currently do and how well,

how much time and risk it would take to rewrite from scratch,

how much time and risk it would take to finish what's already done.

Then you can sit down with your manager again to make a decision.


答:
In my experience this isn't an uncommon situation. Unfortunately, you really have two problems here:

1) The left overs of this project
2) The reasons you got into this mess in the first place

For (1) you need to consider the size / complexity of the project. If it is a week's work, you probably need to start all over again. If it is a year's worth of work, you might need to see what you can salvage from the existing code.

Either way, you need to take these steps immediately:

a) Tell your managers that you have a big problem

b) Get the project spec and get a thorough understanding of what you need to achieve - or talk to the project sponsors if there is no spec.

c) Talk to managers / customers etc. and find out if anyone has / thinks they have any idea what the state of the project is.

Once you've done that, you'll be in a position to start examining the code / working out a strategy.

(I don't think unit tests will help you much - they might tell you if the functions that have been written actually work, but they don't tell you what functions should be there.)

What I'd no next is get an overview of the architecture of the code that exists, and how this maps onto the problem defined in the spec. Then work our what the sub-components are of each of these main components, and see how they fit in to the big picture. Doing this will tell you (roughly) what components are missing.

Once you know what exists, you need to start examining the existing code to see if it does what it is supposed to do.

Once you've done all this, you'll be in a position to estimate how much work is left to do.

As for part (2) your company may need to look at hiring policies / staff retention policies, find ways of keeping programmers accountable for progress.

Finally, you should also consider how you could prevent this happening to the company should you leave in a hurry.


答:
A key characteristic of a successful shopping site is speed.  Serving images from the database is slow.  So storing images on the web server's file system is something of a must.

Having said that, there are several workarounds.  What we like to do is to store (not serve) the images in the database.  We run a scheduled job on the web server that reads the images in the database and stores them locally.  That way, the images are part of the database backup, and updating them is really easy.  If you write the job efficiently, it can run once a minute, so the delay is not much of a problem.

Title: Organizing my products database


问:
I'm doing 90% maintenance and 10% development, is this normal?
I have just recently started my career as a web developer for a medium sized company. As soon as I started I got the task of expanding an existing application (badly coded, developed by multiple programmers over the years, handles the same tasks in different ways, zero structure).

So after I had successfully extended this application with the requested functionality, they gave me the task to fully maintain the application. This was of course not a problem, or so I thought. But then I got to hear I wasn't allowed to improve the existing code and to only focus on bug fixes when a bug gets reported.

From then on I have had three more projects just like the above, that I now also have to maintain. And I got four projects where I was allowed to create the application from scratch, and I have to maintain those as well.

At this moment I'm slightly beginning to get crazy from the daily mails of users (read managers) for each application I have to maintain. They expect me to handle these mails directly while also working on two other new projects (and there are already five more projects lined up after those). The sad thing is I have yet to receive a bug report on anything that I have coded myself. For that I have only received the occasional let's-do-things-180-degrees-different change requests.

Anyway, is this normal? In my opinion I'm doing the work equivalent of a whole team of developers.

Was I an idiot when I initially expected things to be different?

I guess this post has turned into a big rant, but please tell me that this is not the same for every developer.

P.S. My salary is almost equal if not lower than that of a cashier at a supermarket.

答:
Is your manager aware of all these change requests (maintenance requests)? Does s/he realise that your time is taken up sifting through such requests that you have no authority to sanction? Or do you just make changes everytime a manager asks you?

It seems to me like your first port of call is to put it all on your manager's desk. No one should be coming to you directly. Issues should come through whoever fields such - usually a support team. It is normal that you support your code for a short handover period - usually a week or so. Changes should be costed and charged (transfer charging) in any company that would class itself as "medium size", and this it seems is being bypassed (no wonder they are flooding you - you are like the slut at the prom).

There should be a proper request procedure for both raising issues and change requests. Support/maintenance is about fixing bugs and issues (that fit with the original specification, but fail because of a bug in the code or an outside event - such as a power down or corrupt upstream system, etc.).

If your company offers none of this and expects you to cope and be responsible for this myriad of random requests, then seriously you need to consider moving on. Pay is always poor at the bottom - in my first programming job (almost 25 years ago) I spent 8 years for the same company and my pay went up little (although it was always much higher than a cashier!). Within 2 years of leaving I had doubled it - and two years after that I was taking home over ten times what I started at (but was then an independant contractor). As always, earn you spurs, learn your trade, and jump ship to warmer surroundings.


问:
Why almost no webpages hash passwords in the client before submitting (and hashing them again on the server), as to "protect" against password reuse?
There are many sites on the Internet that require login information, and the only way to protect against password reusing is the "promise" that the passwords are hashed on the server, which is not always true.

So I wonder, how hard is to make a webpage that hashes passwords in the client computer (with Javascript), before sending them to the server, where they would be re-hashed? In theory this doesn't give any extra security, but in practice this can be used to protect against "rogue sites" that don't hash your password in the server.

答:
I like X4u's answer, but in my opinion something like it should be integrated into the browser/the html specification - as at the moment it's only half the answer.

Here's a problem I have as a user -  I have no idea whether my password is going to be hashed at the other end when stored in the database.  The lines between me and the server may well be encrypted but I have no idea what happens to my password once it reaches the destination - it maybe stored as plain text.  The database admin guy may end up selling the database and before you know it the whole world knows your password.

Most users reuse passwords.  Non technical people because they don't know any better.
Technical people because once you get to the 15th password or so most people don't stand a chance of remembering them unless they write them down (Which we all know is also a bad idea).

If Chrome or IE or what ever it was I am using could tell me that a password box is instantly going to be client side hashed using a server generated salt and effectively sandbox the password itself - then I would know that as a user I could reuse a password with less risk.  I'd still want the encrypted channels as well as I don't want any eaves dropping going on during transmission.

The user needs to know that their password is not even available to be sent to the server - only the hash.  At present even using X4U's solution they have no way of knowing this is the case because you don't know if that technology is in use.

ContentLicense: CC BY-SA 4.0


答:
Not mentioned yet. </p>

<p>Try to contact the guy that leaved. Its not possible in every case. But if he is healthy and at least liked a little bit his work, he will help and give you a honest answer of progress and missing parts. And he could explain the big picture to you. </p>

Body:
Not mentioned yet.

Try to contact the guy that leaved. Its not possible in every case. But if he is healthy and at least liked a little bit his work, he will help and give you a honest answer of progress and missing parts. And he could explain the big picture to you.


答: I have done this. I did add 'Abstract' as prefix to my abstract class named AbstractOperation. The reason I did this was there was another package that had a non abstract class named Operation, and It helped my team and the programmers who took over later in avoiding any confusion between the two.</p>

Title: Should I add an "Abstract" prefix to my abstract classes?

Body:
Suppose I have an abstract class named Task.

Is there a standard or convention that would suggest I should name it AbstractTask instead?


问:
How to host a site in another site - with little or no coding
SUMMARY: All of these happens on Site A

User visits site A

User enter username and password

User click on Login Button

User authenticated on Site B behind the scene

User is shown a page on Site A that contains his/her profile from Site B as layout/styled from Site B

User can click links in the Profile page that links to other area in Site B
Meaning: Session has to be maintained somehow

I have web application where I store users' password and username. If you logon to this site, you can login with the password and username to have access to your profile.

There is another option that requires you to login to my site from your site and have your profile displayed within your site. This is because you might already have a site that your clients know you with.

This link is close to what I want to do: http://aspmessageboard.com/showthread.php?t=235069

A user on Site A login to Site B and have the information on site B showing in site A. He should not know whether Site B exists. It should be as if everything is happening in Site A

This latter part is what I don't know to implement.

I have these ideas:

Have a fixed IFrame within your site to contain my site: but I am concerned about size/layout since different clients have different layout/size for their content section. I am thinking of how to maintain session too

A webservice: I don't know how feasible this is since the Password and ID are on my server. You may have to send them back and forth. It means client would have to code with my API. But I am not just returning data, I have to show them a page that contains the profile details

OpenID, Single-SignOn: Just guessing - but the authentication and data resides on my server. there is nothing to access on your side in this case

Examples: like login into facebook within my site and still be able to do post updates, receive notifications

Facebook implement some of these with IFrame e.g. the Like button

*NOTE: * I have tested the IFrame option. It worked but I still have to remove my site specific content like my page Banner, Side Navigation etc.

I was able to login normally as if I was actually on the site.

This show my GUI but - style sheet was missing - content not styled with CSS - Any relative url won't work. It would look for that resource relative to the current server. Unless I change links to absolute - Clicking on the LogIn button produces this error: The state information is invalid for this page and might be corrupted.

UPDATE:
I was reading about REST webservice few days ago and I got this idea:

What about the idea of returning an XML from a webservice [REST or SOAP] and providing an XSLT (that I can provide) to display it. Thus they won't have to do much coding?

答:
The simple approach:

IFrame

A better more modular approach:

Web service

simply create  a web service that exposes two functions:

Authenticate (this takes, user name, and password, and Site API Key) returns sessionToken

GetUserProfile (this takes a sessionToken, and Site API Key, data type) and returns profile data eg JSON/XML/HTML

You can then write a API document for your clients. The clients can then style up the profile in whatever way they like.

EDIT:

For security reasons, I would add, that the webservice should be hosted with SSL, and use HTTPS.


问:
Why are side-effects considered evil in functional programming?
I feel that side effects are a natural phenomenon. But it is something like taboo in functional languages. What are the reasons?

My question is specific to functional programming style. Not all programming languages/paradigms.

答:
In my experience good design in Object Orientated programing mandates the use of functions that have side effects.

For example, take a basic UI desktop application. I may have a running program that has on its heap an object graph representing the current state of domain model of my program. Messages arrive to the objects in that graph (for instance, via methods calls invoked from the UI layer controller). The object graph (domain model) on the heap is modified in response to the messages. Observers of the model are informed of any changes, the UI and maybe other resources are modified.

Far from being evil the correct arrangement of these heap-modifying and screen-modifying side effects are at the core of OO design (in this case the MVC pattern).

Of course, that does not mean that your methods should have arbitary side-effects. And side effect free functions do have a place in improving the readbility and sometimes performance, of your code.


问:
Should a server "be lenient" in what it accepts and "discard faulty input silently"?
I was under the impression that by now everyone agrees this maxim was a mistake. But I recently saw this answer which has a "be lenient" comment upvoted 137 times (as of today).

In my opinion, the leniency in what browsers accept was the direct cause of the utter mess that HTML and some other web standards were a few years ago, and have only recently begun to properly crystallize out of that mess. The way I see it, being lenient in what you accept will lead to this.

The second part of the maxim is "discard faulty input silently, without returning an error message unless this is required by the specification", and this feels borderline offensive. Any programmer who has banged their head on the wall when something fails silently will know what I mean.

So, am I completely wrong about this? Should my program be lenient in what it accepts and swallow errors silently? Or am I mis-interpreting what this is supposed to mean?

The original question said "program", and I take everyone's point about that. It can make sense for programs to be lenient. What I really meant, however, is APIs: interfaces exposed to other programs, rather than people. HTTP is an example. The protocol is an interface that only other programs use. People never directly provide the dates that go into headers like "If-Modified-Since".

So, the question is: should the server implementing a standard be lenient and allow dates in several other formats, in addition to the one that's actually required by the standard? I believe the "be lenient" is supposed to apply to this situation, rather than human interfaces.

If the server is lenient, it might seem like an overall improvement, but I think in practice it only leads to client implementations that end up relying on the leniency and thus failing to work with another server that's lenient in slightly different ways.

So, should a server exposing some API be lenient or is that a very bad idea?

Now onto lenient handling of user input. Consider YouTrack (a bug tracking software). It uses a language for text entry that is reminiscent of Markdown. Except that it's "lenient". For example, writing

```<code>- foo
- bar
- baz
</code>```

is not a documented way of creating a bulleted list, and yet it worked. Consequently, it ended up being used a lot throughout our internal bugtracker. Next version comes out, and this lenient feature starts working slightly differently, breaking a bunch of lists that (mis)used this (non)feature. The documented way to create bulleted lists still works, of course.

So, should my software be lenient in what user inputs it accepts?

答:
Programs that are deployed to server, most of the time, are supposed to take thousands of requests every minute, or sometimes every second. If a server program accepts and corrects faulty input from clients, I am afraid it will have 2 disadvantages:

Loss of precious server time. With 1000+ requests per second, checking for faults in each request can reflect in slow response for each client.

Unfair to the client/client-programs that provide correct input.
Other than that, when a server side programmer sits on the server code, he/she has to think about the various cases of what faulty inputs can be. Who will decide that ?

Server programs should not accept faulty input, but the servers should return an error message to the client, if there is a faulty input.

OwnerDisplayName: romkyns


问:
What's the career path for a developer who doesn't like management?
If you're developer (Senior or Lead Developer) and you'd rather stay with code/design than pursue a management career, what are the available career paths at your company, or any you've heard of? How far can you go?

Is it possible to continue being a geek until you bite the dust or is that too naive?

Are people like Uncle Bob for example still considered developers, as they claim?

答:
Probably something like this:

Jr Developer -> Developer -> Sr Developer / Team Leader / Lead Developer -> Software Architect


问:
Overload or Optional Parameters
When I have a function that might, or might not receive a certain parameter, is it better to overload the function, or to add optional args?

If each one has it's ups and downs - when would I use each?

答:
If the language supports them properly (e.g. type-safety, if applicable), I would prefer optional arguments for the following reasons:

They convey your intent better so noone suspects that your function overload will do something different (which it probably shouldn't anyway).

Less code to maintain, even if the function overload only delegates to the more comprehensive one. If you want to rename the function later, you have at least 3 places to do it (two definitions + one call).

The compiler (if any) might generate smaller binaries.

Optional arguments scale better, at least in some languages. What if you want to have 3 optional arguments with the ability to mix and match? For full flexibility, you'd need 6 overloads to do that.

If it's an object method, multiple overloads will greatly hinder the implementation of overrides in subclasses.

Title: Overload or Optional Parameters


答:
Assuming a constructor kind of situation: I often choose a fluent builder pattern to prevent situations with many options.

Eg.Ordering.natural().onResultOf(function).reverse().compound(Ordering.natural().onResultOf(function2)) is an example of calling a fluent builder interface implemented in Guava.

Of course you now need a separate object to hold the state of your builder, but you reduce overall complexity by separating behavior of constructing from behavior of the constructed.

Title: Overload or Optional Parameters

Body:
When I have a function that might, or might not receive a certain parameter, is it better to overload the function, or to add optional args?

If each one has it's ups and downs - when would I use each?


答: SQL Server 2008 FILESTREAM option for a VARBINARY(MAX) column is the best of both worlds. The images are still saved to a file to help with performance, but your code will just save to a table and the database handles putting files to disk. This can handle large images as well as high traffic.</p>

Title: Organizing my products database


问:
Best approach to learning web programming
I come from a scientific and embedded programming background, and I have had minimal experience with web programming.  What would be the best approach to take to get up to speed with web programming?  Tools and framework suggestions?

One approach would be to dive into learning a framework, such as Rails. I started doing this with rails tutorial, but I find that the framework abstracts so many important concepts that I should be learning.

To sum up, experienced programmer wants to learn web-app programming.

答:
Maybe you should start learning basics before using more sophisticated tools like a framework. Exactly like you start with easy and simple programs in C before using C++ and libraries, you can start with simple websites in Php or Python, with a frontend in javascript, just to get used to it.

Then, when you feel at ease, you can start making cleaner websites "the right way".


问:
Non-English Naming Conventions

Possible Duplicate:

  Do people in non-English-speaking countries code in English?

I know that there are non-English based languages out there, where keywords are in some other tongue, but popular languages are in English. However, if you're a non-native English speaker, developing for a non-English market, do you use your native language when naming functions, classes, variables, etc.?

If you do, what kind of morphology do you adopt? For example, functions are often named with verbs (e.g., buildData), would you use the imperative form -- if your language has one -- in the name (e.g., construisciDati in Italian)?

A related question: For users of non-Latin writing systems and languages that support Unicode naming, do you make use of it or stick with romanisation? e.g., 建造数据, for our buildData example in [Googled] Mandarin.

答:
I'm German but all my sourcecode files are strictly english-only; this also includes comments and commit messages.

The reasons for this are:

Other people might work with the code. They are not necessarily German, too.

English is usually shorter.

Keywords, stdlib functions etc. are also english so it's consistent.

When asking other people for help, e.g. on Stack Overflow it will be much easier if they actually understand the code you post.

Title: Non-English Naming Conventions


答:
I use english language, if programming language allows to use it. However, there are some specific languages, that does not support english - I'm avoiding their usage and market where they are used.

Common sense of using english - it's world language, that allows you easily communicate with developers from other countries.

Title: Non-English Naming Conventions

Body:
Possible Duplicate:

  Do people in non-English-speaking countries code in English?

I know that there are non-English based languages out there, where keywords are in some other tongue, but popular languages are in English. However, if you're a non-native English speaker, developing for a non-English market, do you use your native language when naming functions, classes, variables, etc.?

If you do, what kind of morphology do you adopt? For example, functions are often named with verbs (e.g., buildData), would you use the imperative form -- if your language has one -- in the name (e.g., construisciDati in Italian)?

A related question: For users of non-Latin writing systems and languages that support Unicode naming, do you make use of it or stick with romanisation? e.g., 建造数据, for our buildData example in [Googled] Mandarin.


答:
it depends. When I'm coding only for me oder the company I work for and I know that it will be only used and developt here in germany, I use a mix. Sometimes I find an english function name more meaningfull than a germany adapted version of it. But I also sometimes use german function, variables, etc. names to make it clearer or if it fits. Example: RechneAlleFelder() instead of CalculateAllFields() . Sometimes is just a decision out of my current mood/feeling.

But if I use non-English names I avoid using special chars like the german umlaute. I have enough problems with them when converting data or displaying them on websites or in the programm as output. (Oh man...I realy like OEM/ANSI codepages NOT).   ;)

If the programm will be used internationaly or if it's a side/personal project that I might put up in Github or other places, than I'm only using english and no special chars and UTF-8. Just to be as safe as possible to avoid problems.

Title: Non-English Naming Conventions


答:
I'm German, and I doubt anyone outside of Germany will ever look at the code I write. Still, I use English when writing code. We even use English in the internal ticket tracker, mostly to make it look nicer with internal class names and to facilitate the processing of outside bug reports, which may be in English. Also, I'm a stickler for consistency. Professional hazard, I guess.

However, if I were to use German in my code, I'd shy away from using umlauts and other "exotic" characters. Until ASCII goes the way of the floppy disk and UTF8 is the absolutely dominant encoding, non-ASCII characters are just asking for trouble if you open the file in another editor for any reason.

Title: Non-English Naming Conventions


问:
C# foreach improvements?
I run into this often during programming where I want to have a loop count index inside of a foreach and have to create an integer, use it, increment, etc. Wouldn't it be a good idea if there was a keyword introduced that was the loop count inside of a foreach? It could also be used in other loops as well.

Does this go against the use of keywords seeing as how the compiler would not allow this keyword used anywhere but in a loop construct?

答: If you need a loop count inside a foreach loop why don't you just use a regular for loop. The foreach loop was intended to make specific uses of for loops simpler. It sounds like you have a situation where the simplicity of the foreach is no longer beneficial.

Title: C# foreach improvements?


问:
For what problems is object oriented programming not a good choice?
Somewhat inspired by this question: For what common problems is functional programming not a good fit? - but nevertheless a question which I always wanted, but was too afraid to ask.

I've been in ... well, let's call it engineering software development practically all my life, and in all that time, although OO had always been there (well, most of that time) I've never had the need to use "its ways", nor to learn that paradigm. We've always used rather simple program structures, routines/functions/modules and although it is opposite to today's best practices managing those programs (programs up to roughly 300k LOC, nothing too big) never proved to be difficult, let alone impossible.

So I wanted to ask you, what would be the sorta problems for which object oriented paradigm would not be a good choice? In comparison to procedural programming ?

答:
Object Orientated programming can be used to model your domain. The classes can be used to represent the state and behaviour of entities, aggregates, collaborations, services within your domain model. Moreover, the method invocations and protocols between the objects can model the dynamic relationships between entities.

I have found it to be a useful way of producing a DRY model that can cleanly represent the rules and behaviour of your application in a way that is decoupled from technical issues (such as the use of a database, or a message queue, or the fact it is a web application). A good book on the topic is Domain Driven Design

An important thing to note here, is that the "entities" I mentioned above do not have to map onto real world objects! They can represent abstract parts of the domain of your application to.

So, if that is what Object Orientated programming is good at; what is not good at? Well, anything where the domain model cannot be expressed well as objects. For instance, some mathematical, (statistical, logic, etc) or technical (e.g. a compiler) programs are expressible better in different styles. I have found that for business workflow applications a combination of OO and custom DSL techniques have been very effective in allowing us to model the kinds of relationships and events that occur in business process. For program verification and automated proof checking a functional approach is often used, because its pure functions allow more direct mathematical reasoning.


问:
What is the most effective way to add functionality to unfamiliar, structurally unsound code?
This is probably something everyone has to face during the development sooner or later.

You have an existing code written by someone else, and you have to extend it to work under new requirements.

Sometimes it's simple, but sometimes the modules have medium to high coupling and medium to low cohesion, so the moment you start touching anything, everything breaks. And you don't feel that it's fixed correctly when you get the new and old scenarios working again.

One approach would be to write tests, but in reality, in all cases I've seen, that was pretty much impossible (reliance on GUI, missing specifications, threading, complex dependencies and hierarchies, deadlines, etc).

So everything sort of falls back to good ol' cowboy coding approach. But I refuse to believe there is no other systematic way that would make everything easier.

Does anyone know a better approach, or the name of the methodology that should be used in such cases?

答:
I have been working on a complex code base for more than a year now. See if my insights can help you:

Your insights are right, by the time you reach a different part of the code, you forget about the previous part. It can be a never ending cycle. The important lesson to take away here is that the product cannot work without all the parts working properly. Even, if one part fails, the product doesn't work. See it from another angle: if you improve one part dramatically, it still MIGHT NOT result in better working of the product, which is your main goal here.

So, at First: Don't be a developer. Be a tester.

Don't try to understand part by part. Understand the whole product and its working when all parts are together. From a production environment(i.e., a non development environment - no debug points), test the product. Then, just like every tester does, log the problems you face into a bug tracker. Assign the severity and priority to it. As this software existed for quite some time, see if there is already a bug tracker created. If there is one already, you are lucky. Add to those and take time and verify each of the existing ones. At the end of this cycle, you understand the product from a user point of view(you definitely shouldn't miss it) and also a QA point of view. Due course, you might even realize that a line of code will fix the bug, and those who coded it didn't do so as there was no real need back then.

Second Step: Wear you designer cape

Break the product into several parts(not literally or according to your convenience, but according to how they work together). May be your work uptil now or existing knowledge might come into play. Then, try to understand how they work with each other as well as with the 10 dependent libraries. Then, for each tracked bug, write your notes identifying entities of code(e.g.: This change involves modifying classes X,Y,Z, etc.). Probably, by the end of this step, you will have FEW hints of what are the problems with current architecture and what can be improved.

Then, you can decide if the current architecture/design is sufficient and you can go with improving the software OR if the product needs a better design or changes in the existing design.

House of Cards

Also, since complex products come with a lot of code, we might not be in a position to pick up a few things and tweak or improve them. This is because the whole system can be intertwined in such a way that making change to one of the classes is equivalent to changing the position of one card in a house of cards, you never know which end might break. In my experience, this has been true. I have picked a part, improved its code, unaware of the contracts it had with other parts of the code and ended up abandoning the code and realizing my mistake. So, instead of trying to understand parts, try and understand it is a whole.

Prioritize your concerns

You need to keep in mind what you are trying to improve:

Do you want the product to be faster?

Of course you do. But is it the primary of the concerns? Is it being slow? If yes, create performance criteria, identify bottlenecks and improve on those parts. Test again.

Do you want to improve the usability?

Then it's pretty much the API/UI side.

Do you want to improve the security?

Then it's the boundaries you should be exploring.

I have provided only 3 examples, but there are a lot more to look for.

Latest and Best Documentation

I have read here in one of the posts that the latest and best documentation is the code itself. Even if you create a good amount of documentation today, it is history after a while. So, code is your latest piece of documentation. So, whenever you browse through some code, write your understanding in the comments there. While passing the code base, caution them to depend NOT ONLY on comments!


答:
You can use anonymous types like this

```<code>foreach (var item in items.Select((v, i) => new { Value = v, Index = i }))
{
    Console.WriteLine("Item value is {0} and index is {1}.", item.Value, item.Index);
}
</code>```

This is similar to Python's enumerate function

```<code>for i, v in enumerate(items):
    print v, i
</code>```

Title: C# foreach improvements?

Body:
I run into this often during programming where I want to have a loop count index inside of a foreach and have to create an integer, use it, increment, etc. Wouldn't it be a good idea if there was a keyword introduced that was the loop count inside of a foreach? It could also be used in other loops as well.

Does this go against the use of keywords seeing as how the compiler would not allow this keyword used anywhere but in a loop construct?

Body:
You can use anonymous types like this

foreach (var item in items.Select((v, i) => new { Value = v, Index = i }))
{
    Console.WriteLine("Item value is {0} and index is {1}.", item.Value, item.Index);
}

This is similar to Python's enumerate function

for i, v in enumerate(items):
    print v, i


问:
What guidelines should be met for something to be called a webapp
In my mind a webapp is any website that has some complicated features and that's served from the web, but I know there are people who are a lot smarter than me here and they'll point out other features that I'm not noticing. For example:

If it doesn't have a login system, can I still call it a webapp? (because most webapps end up being user-based).

Should I think of a CMS as a webapp? and how about the sites that are built with it? probably they're not webapps, right?

Is Gmail a webapp? I think so.

Is twitter a webapp? Yes, though the functionality is rather simple.

So what conditions need to be met to call a website a webapp?

P.S. StackExchange's tag system defines web-applications as

applications that are accessed over the "web", which can mean the
  Internet, or an internal network (an intranet).

答:
There is only one requirement - a program running on some server that responds to HTTP requests. All the rest is just hype and vague marketing catch phrases.

In other words, an application (program) that runs over the web (HTTP).

If this doesn't answer your question, then it doesn't belong in programming Q&A, but in marketing.


问:
Taking Object Oriented development to the next level
Can you mention some advanced OO topics or concepts that one should be aware of?

I have been a developer for 2 years now and currently aiming for a certain company that requires a web developer with a minimum experience of 3 years.

I imagine the interview will have the basic object oriented topics like (Abstraction, Polymorphism, Inheritance, Design patterns, UML, Databases and ORMs, SOLID principles, DRY principle, ...etc)

I have these topics covered, but what I'm looking forward to is bringing up topics such as Efferent Coupling, Afferent Coupling, Instability, The law of Demeter, ...etc.

Till few days ago I never knew such concepts existed (maybe because I'm a communication engineer basically not a CS graduate.)

Can you please recommend some more advanced topics concerning object oriented programming?

答:
Brother oh brother, nobody who'll actually interview you (i.e. other programmers) is going to want to hear you talk about vague sophisticated terms. You'll sound exactly as what you trained for - a guy who read a bunch of Wikipedia pages.

Instead, focus on understanding the advantages of abstraction over implementation, prepare some examples beforehand, explain the fallacies of tight coupling, how to recognize them, and how to avoid them (actually Law of Demeter comes in handy here - but it's important to know when to use it and why).

That's really all you need to know to not screw them over with bad code. I mean, that's really what they're worried about, that they'll get a new guy who's going to come in and make a big mess. You need to focus more on letting them feel they can trust you, rather than impress them.

A very good presentation of these topics is in the book Agile PPP by Bob Martin.


答:
I may be wrong about this, but I always thought that the main point of the foreach loop was to simplify iteration from the STL days of C++ i.e.

```<code>for(std::stltype<typename>::iterator iter = stl_type_instance.begin(); iter != stl_type_instance.end(); iter++)
{
   //dereference iter to use each object.
}
</code>```

compare this to .NET's use of IEnumerable in the foreach

```<code>foreach(TypeName instance in DescendentOfIEnumerable)
{
   //use instance to use the object.
}
</code>```

the latter is much simpler and avoids many of the old pitfalls. In addition, they seem to follow almost identical rules. For instance you can't change the the IEnumerable contents while inside the loop (which makes much more sense if you think of it the STL way). However, the for loop often has a different logical purpose than iteration.

Title: C# foreach improvements?

Body:
I may be wrong about this, but I always thought that the main point of the foreach loop was to simplify iteration from the STL days of C++ i.e.

for(std::stltype<typename>::iterator iter = stl_type_instance.begin(); iter != stl_type_instance.end(); iter++)
{
   //dereference iter to use each object.
}

compare this to .NET's use of IEnumerable in the foreach

foreach(TypeName instance in DescendentOfIEnumerable)
{
   //use instance to use the object.
}

the latter is much simpler and avoids many of the old pitfalls. In addition, they seem to follow almost identical rules. For instance you can't change the the IEnumerable contents while inside the loop (which makes much more sense if you think of it the STL way). However, the for loop often has a different logical purpose than iteration.


答:
It's somewhat contextual. In general, it's any application that interfaces over the web.

However, if you are talking about a webapp in the context of Java, it is implied that it's an application that, at minimum, conforms to the Java Servlet Specification. In other contexts, it might have other implications.

Title: What guidelines should be met for something to be called a webapp

Body:
In my mind a webapp is any website that has some complicated features and that's served from the web, but I know there are people who are a lot smarter than me here and they'll point out other features that I'm not noticing. For example:

If it doesn't have a login system, can I still call it a webapp? (because most webapps end up being user-based).

Should I think of a CMS as a webapp? and how about the sites that are built with it? probably they're not webapps, right?

Is Gmail a webapp? I think so.

Is twitter a webapp? Yes, though the functionality is rather simple.

So what conditions need to be met to call a website a webapp?

P.S. StackExchange's tag system defines web-applications as

applications that are accessed over the "web", which can mean the
  Internet, or an internal network (an intranet).


答:
Do you know anything about HTML?  This is probably the most basic and easiest yet essential thing you need.  Make yourself a simple webpage, play around with fonts, images, positioning etc and everytime you come across a problem look up the answer.

From there move onto CSS, Server Side Programming etc

I think you find this is the way most of us learnt.

Title: Best approach to learning web programming

Body:
I come from a scientific and embedded programming background, and I have had minimal experience with web programming.  What would be the best approach to take to get up to speed with web programming?  Tools and framework suggestions?

One approach would be to dive into learning a framework, such as Rails. I started doing this with rails tutorial, but I find that the framework abstracts so many important concepts that I should be learning.

To sum up, experienced programmer wants to learn web-app programming.


问:
Warn about 3rd party methods that are forbidden
Note: This question refers to code written in Java or C#.

I am managing a couple of large projects where we have discovered issues (not necessarily bugs) with some 3rd party/SDK methods and have written our own extensions that should be used instead. We want developers to remember that using those methods is not recommended for this project.

If we had been using our own libraries we could easily remove that method or mark it obsolete/deprecated but we cannot do so for libraries that we didn't write.

As an example, we use a library that provides us with two overloads:

```<code>acme.calculate(int quantity_, double priceInUsDollars_);
acme.calculate(int quantity_, string currencyCode_, double priceInCurrency_);
</code>```

We want developers to always use the first one and get price in US Dollars from our own standard FX rate systems. And it'd be nice to have the IDE (Eclipse/Visual Studio) warn the developers when they use the first one. A compiler warning will suffice too.

Right now, as it stands, we have to rely on the code reviewers to spot such errors and as you can see that is not a reliable approach.

One possible way I am prepared to go is to write my own check style check (http://checkstyle.sourceforge.net/writingchecks.html). But I was wondering if there was something simple that I could use. Does anyone know of ways to achieve an IDE/compiler warning of the sort I have described?

Non IDE/compiler solutions are most welcome.

答:
The "white list approach": write a wrapper library to the library with essentially the same interface signatures as the lib itself, but leave out the forbidden functions. The wrapper should delegate each method call to the corresponding library call. Then let your devs only use/link to that wrapper instead of the original lib. The wrapper may also be a good place for your library extensions.

Of coure, that may become impractical if the lib has a very big API with several hundred functions. Then you want to implement a "black list approach" like the "check style" solution you suggested.


问:
How do you manage projects left over by other employees?
It happens that some one just leaves the company all of sudden. Now his work needs to be completed and you are being assigned it. Having no idea what was he up to (was it 90% done or 9%), how do you manage the leftover?

Shall I start from scratch? What if it was 90% done?

Shall I try and understand whatever he has done? What if it was just nonsense?

答:
Congratulations, this is your chance to shine and make a really positive impression on your bosses. What you have here is a priceless opportunity. So what do you need to do and how?

First, get the code. He may not have checked everything in (the guy who did this to us did not) and so have someone with admin rights pull it off his computer and check it in for you.

Next triage the problem. Take the requirements and note which parts seem to have code written and which do not. This is the rough list of what isn't finished. It will grow as you do the next step. Then go through the code and evaluate it and run it and see what is currently working and what appears not to work even though there is code written. Add the not working parts to the list. Look for unit tests (I'd be surprised if you found them, the people who bail out just before a deadline because they know they are failing tend not to write them). Now at least you have a good idea of how bad it is. Also look through the requirements and see what questions you need answered. A lot of time, project failures come about as a result of poor requirments and a developer who doesn't want (for a myriad of reasons) to ask further questions.

Now you make your project plan. Start with a list of the questions you have from the requirements (write it up formally in a document) and then list the things you need to do to complete the work. Make an estimate of how much time each will take. Determine if what currently exists is salvageable (and if not, be prepared to justify why not).

Now have a meeting with the project manager (and your boss if they are two different people) and tell him or her the bad news. (It's almost always bad news when someone leaves suddenly and you have to pick up where they left off, good developers don't leave people in the lurch - they at least leave with a list of what they have done and what is left to do. The exception may be if someone left due to health issues.) In your discussion, you may get some of the answers you need and you and the PM may rework the project plan a little.

Follow up the meeting by sending the PM and other critical stakeholders (the PM will identify who), a copy of your questions that need to be answered and the project plan you worked out.

Now you have what you need to get started on the actual coding, so get to work.

In the meantime, you have probably been pulled off something else to salvage this project. Make sure your work is in shape for someone else to pick up or for you to pick up after you finish the project. That means the same types of things, a document where you say what is done and waht isn't and a check in of all source code (not necessariliy to the trunk if is isn't done, but somewhere that someone else can access it.

If you haven't been pulled off your existing work, then you need to work out with your boss how much time in the workday you will spend on each. This is one of those times when overtime may be needed and will be appreciated. The closer it is to the actual deadline, the more desperate management is, you may be able to work out overtime pay or a large bonus if the deadline is close. If this work is going to significantly delay the other work, then you need to make sure the stakeholders in that project are aware of that.

Once you succeed in salvaging the project, make sure to brag about that in your next performance review.


答:
I'm just adding Dan Finch's answer here, as requested.

Don't give me points, give points to Dan Finch :-)

The solution is to write the following generic extension method:

```<code>public static void Each<T>( this IEnumerable<T> ie, Action<T, int> action )
{
    var i = 0;
    foreach ( var e in ie ) action( e, i++ );
}
</code>```

Which is used like so:

```<code>var strings = new List<string>();
strings.Each( ( str, n ) =>
{
    // hooray
} );
</code>```

Title: C# foreach improvements?

Body:
I'm just adding Dan Finch's answer here, as requested.

Don't give me points, give points to Dan Finch :-)

The solution is to write the following generic extension method:

public static void Each<T>( this IEnumerable<T> ie, Action<T, int> action )
{
    var i = 0;
    foreach ( var e in ie ) action( e, i++ );
}

Which is used like so:

var strings = new List<string>();
strings.Each( ( str, n ) =>
{
    // hooray
} );


答:
One of the power with Java's Reflection is that you can change method properties at runtime. One of the use is make a private method public, to be able to use it anyway. It could very well work the other way around, with you making unwanted methods private, at runtime. Although it's won't be seen at compilation, it will be seen as soon as the project is tested. </p>

<p>This article shows how to modifiy methods properties at runtime. Here's the interesting part: </p>

```<code>Class theClass = MyClass.class;
Class[] paramTypes = { Integer.TYPE, String.class };
Method method = theClass.getDeclaredMethod("myMethodName", paramTypes);
method.setAccessible(false); // this makes the metod private
System.out.println("Making method  myMethodName(int,String) private");
</code>```

Title: Warn about 3rd party methods that are forbidden

Body:
Note: This question refers to code written in Java or C#.

I am managing a couple of large projects where we have discovered issues (not necessarily bugs) with some 3rd party/SDK methods and have written our own extensions that should be used instead. We want developers to remember that using those methods is not recommended for this project.

If we had been using our own libraries we could easily remove that method or mark it obsolete/deprecated but we cannot do so for libraries that we didn't write.

As an example, we use a library that provides us with two overloads:

```<code>acme.calculate(int quantity_, double priceInUsDollars_);
acme.calculate(int quantity_, string currencyCode_, double priceInCurrency_);
</code>```

We want developers to always use the first one and get price in US Dollars from our own standard FX rate systems. And it'd be nice to have the IDE (Eclipse/Visual Studio) warn the developers when they use the first one. A compiler warning will suffice too.

Right now, as it stands, we have to rely on the code reviewers to spot such errors and as you can see that is not a reliable approach.

One possible way I am prepared to go is to write my own check style check (http://checkstyle.sourceforge.net/writingchecks.html). But I was wondering if there was something simple that I could use. Does anyone know of ways to achieve an IDE/compiler warning of the sort I have described?

Non IDE/compiler solutions are most welcome.

Body:
One of the power with Java's Reflection is that you can change method properties at runtime. One of the use is make a private method public, to be able to use it anyway. It could very well work the other way around, with you making unwanted methods private, at runtime. Although it's won't be seen at compilation, it will be seen as soon as the project is tested.

This article shows how to modifiy methods properties at runtime. Here's the interesting part:

Class theClass = MyClass.class;
Class[] paramTypes = { Integer.TYPE, String.class };
Method method = theClass.getDeclaredMethod("myMethodName", paramTypes);
method.setAccessible(false); // this makes the metod private
System.out.println("Making method  myMethodName(int,String) private");


问:
Does groovy call partial application 'currying'?
Groovy has a concept that it calls 'currying'.  Here's an example from their wiki:

def divide = { a, b -> a / b }

def halver = divide.rcurry(2)

assert halver(8) == 4

My understanding of what's going on here is that the right hand argument of divide is being bound to the value 2.  This seems like a form of partial application.

The term currying is usually used to mean transforming a function that takes a series of arguments into a function that only takes one argument and returns another function.  For example here is the type of the curry function in Haskell:

curry :: ((a, b) -> c) -> (a -> (b -> c))

For people who haven't used Haskell a, b and c are all generic parameters.  curry takes a function with two arguments, and returns a function that takes a and returns a function from b to c.  I've added an extra pair of brackets to the type to make this more clear.

Have I misunderstood what's going on in the groovy example or is it merely misnamed partial application?  Or does it in fact do both: that is to say convert divide into a curried function and then partially apply 2 to this new function.

答:
Given this defintion found at IBM:

The term curry is taken from Haskell Curry, the mathematician who developed the concept of partial functions. Currying refers to taking multiple arguments into a function that takes many arguments, resulting in a new function that takes the remaining arguments and returns a result.

halver is your new (curried) function (or closure), that now takes just one parameter. Calling halver(10) would result in 5.

Therefor it transforms a function with n arguments in a function with n-1 arguments. The same is said by your haskell example what curry does.