问:
Choosing a functional programming language
I have read a lot of threads about functional programming languages lately (almost in the past year, in fact). I would really like to pick one and learn it thoroughly.

Last [course] semester, I have been introduced to Scheme. I loved it. Loved the extreme simplicity of syntax, the homoiconicity principle, the macros (hygienic and non-hygienic), the n-arity of procedures, etc.

The problem with Scheme is it's an academic language. I don't think it is really used in production environments. I don't believe either that it is particularly good to have on our resume. So, I have been looking around for alternatives. There are many of them and they somehow all seem to have a similar level of popularity.

Some thoughts about some other functional languages I have considered yet:

Clojure: It sounds great because it can access the Java world, it is oriented towards scalability and concurrency, but isn't the Java world on an edge right now? I already know Java pretty well, but would it be wise to add even more energy on depending on the JVM?

Haskell: Looks like a very appreciated language, but from what I have read, it's also more of an academic language.

Lisp: It's been around since forever. It seems to have most of what I like from Scheme. It has a big community. For what I [think I] know, it is probably the most widely used functional programming language in industry(?).

F#: Didn't really consider it. I'm not a big fan of MS stuff. I don't have the money to pay for their softwares (I could have them free from university alliances, but I'm more inclined to go with community-driven solutions). Though... I guess it would be the best career-oriented choice.

Tonight, I'm leaning towards Lisp. One week ago, it was Haskell. Before that it was Clojure. In the past year, I was doing some Scheme for fun, not pushing it for the reason you know. Now I would like to get serious (about learning one, about doing real projects with it, about maybe eventually professionally working with it). My problem is I would need to learn them all in depth before being able to choose one.

答:
Actually, if you were able to implement a reasonably complex system in Scheme, you'd be fairly desirable at companies where you'd probably want to work. Earlier in my career I ran into some students who had done a fair amount of work in Scheme, and the only time it was a disadvantage was when they were unable to explain their work or didn't actually understand it well enough to implement basic data structures and algorithms within a reasonable amount of time. I always let candidates answer such questions in their preferred language; I did run into some people who thought that they were best at Scheme who managed to struggle quite a bit with things that should be easy, like adding an element to a linked list, which mystified me.

But if you were able to "get" Scheme well enough to write even an average web app, that would be a pretty good selling point at most serious software companies.

If you were interviewing at a "blub" shop and the developers just thought you were weird because of your proficiency at Scheme or Haskell or F#, you probably wouldn't want to work there. In most cases, competent developers get their choice of gigs, so don't sweat "practicality" unless the only options you can imagine in your future are corporate. Work on being competent, flexible, and breaking down problems.

College isn't about practicality. It's about creating a safe environment to explore and learn. That is, in fact, useful, even if you end up writing ordinary software for the rest of your career.

That being said, I don't see why you'd want to limit to just one of those choices so soon. You could easily get a sense of all four of the languages in about 4 weeks, then pick one to concentrate on that meshes best with your current whims. Then go back to another one of your options and try to implement something similar. Move on to something more complex, and consider your options again. Experimentation is good. Unless you're trying to make a living next month, you don't need to become a specialist yet.

I've written some in Scheme, F#, Emacs Lisp, and Common Lisp, and read at least a bit of Haskell, at least occasionally over the last few years. I can't say I'm an expert in any of them, but each excursion into those languages has benefited me in all the other languages that I work in professionally (C#, Java, Ruby, and occasionally Boo, Perl and Python). Curiosity will build you a more enduring, fulfilling career than anything else.


问:
Is it beneficial to study past the basics of a core language when the primary goal is to rely on its framework?
Please keep in mind this is not another 'How much [insert programming language here] should I know before moving onto [insert framework here]?' What I'd like to know is how beneficial is it to learn the those advanced concepts of a programming language when your intention is to heavily rely on its framework the majority of the time. So for example I've began to use jQuery and first took the time out to really grasp the core concepts of Javascript. Additionally I have a few beyond the basics books (Secrets of a Javascript Ninja for instance) on the shelf that really delve into the language. As I skim through the pages though I find that a fair bit of it doesn't carry over to jQuery being that my main intention is DOM manipulation.

The same can be said for Ruby and RoR. Will these books make me a better programmer overall? Probably. Can these topics help me become that much better with its framework? That's what I'm having a hard time understanding.

答:
It's more important to study the language than it is to study the framework.  Learn the language well, and you'll use the framework well.

In order of importance (most important first):

Fundamental programming principles - Algorithms, data structures, etc.

Language paradigms - OOP, Functional, etc.

Language features.

Syntax and frameworks.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Are functional languages a kind of program derivation?
Program derivation is defined as the derivation of a program from it's specifications. Usually this specification language is some form of propositional logic, but from what I understand, it need not be. For the sake of specificity, I'm only dealing with purely functional languages like Haskell here.

When you write a program in Haskell, you aren't describing how the computation is done, but what things are. For example, in this function that produces Fibonacci numbers, all this is given is a specification for Fibonacci numbers, not how the function should be implemented.

```<code>fib :: int -> int
fib n = (fib n-1) + (fib n-2)
fib 1 = 1
fib 0 = 1
</code>```

To make this code run, the Haskell compiler must convert this declarative specification of the function to imperative machine code. Isn't this by definition a kind program derivation?

答:
To derive a program means to write a formal specification, which is usually non-executable, and then apply mathematically correct rules in order to obtain an executable program satisfying that specification. That describes a compiler, basically.

Haskell is a programming language that uses mathematical rules to help you verify program correctness.  It is a tool that helps you derive a program.  You still have to perform the derivation process, within the confines of the programming language.

The notion that you are describing what things are, rather than how the computation is done, is what declarative vs. imperative programming means.  Imperative programming is programming in the small, by specifying a recipe; a series of steps.  Declarative programming is where you essentially tell the computer what you want, and it figures out how to get it done.

Declarative programming is characterized by referential transparency, mathematical correctness, the lack of side effects, laziness and concurrency; all of the things that Haskell excels in.


问:
When should the programmer's spoken language be used during development?
I'm an Italian developer, but I have a good understanding of English.

Sometimes, when developing an application targeted for an Italian audience, I wonder whether it is correct to use the Italian language in my code or not.
By "Italian language in my code" I mean the names of methods, classes, comments, variables and so on.

For example, when I write code like this:

```<code>/* Attenzione: metodo esageratamente complicato */
public double calcolaImposteDeiServizi() { ... }
</code>```

Do I break any sacred law of programming because I didn't write that code as follows?

```<code>/* Caution: overly complicated method */
public double calculateTaxesOfServices() { ... }
</code>```

I remember a project I worked on some time ago. It was about calculating VAT/taxes/bonuses. Some of this code was dealing with concepts that existed only in the Italian economy at that moment.

I preferred to write that project using only Italian names for methods, otherwise it would clearly have become a mess understanding that VAT was Italian's IVA and so on.

By using this example, should there be some kind of rule for deciding whenever to use your language or not in code?

Did any highly authoritative programmer ever said something about this issue?

How do you make this kind of decision in your projects?

答:
As quite a few other people say, English is pretty standard.  You might have to think of what the lifetime of your code could possibly be.

Some time ago I worked in the Indian development office of a multi-national European company and my team members were interspersed amongst some developers from another team on an unrelated project, but we all got to hear each others' team's discussions and issues.  The problem the other team had is that this gigantic company had bought a tiny Finnish start-up (or just bought their software, I'm not clear) that wrote all their code in Finnish.

None of the Indian team members spoke a word of Finnish.  They spent months and months trying to translate the code, or at least, the non domain specific parts of the code.  Lots of search and replace, recompilation, errors, fixing, errors, recompilation.

All in all, due to Finnish vs English, the company didn't get any productive use out of their purchase.


答:
Haskell code can certainly be read as a description of how to perform the computation (the STG machine is basically a stripped-down, more explicit Haskell-style functional language but has direct, obvious execution semantics). But yes, the more common reading is a declarative one, and declarative programming is closer to formal specifications than imperative languages.

However, you'd have to stretch the definitions of program derivation to include functional programming in it. For one, if you call any kind of transformation from a language into machine code, then even a C compiler is a program derivation tool. Second, (most) functional languages are in no sense specification languages: Code is written to make obvious what is being computed rather than how, but it still spells out the computation (although it does this in different terms than, say, C, and perhaps leaves more room for compiler optimizations) rather than letting the compiler search for a program. The distinctions are blurry, but people tend to draw the line somewhere between Haskell and full-on propositional logic.

Title: Are functional languages a kind of program derivation?

Body:
Program derivation is defined as the derivation of a program from it's specifications. Usually this specification language is some form of propositional logic, but from what I understand, it need not be. For the sake of specificity, I'm only dealing with purely functional languages like Haskell here.

When you write a program in Haskell, you aren't describing how the computation is done, but what things are. For example, in this function that produces Fibonacci numbers, all this is given is a specification for Fibonacci numbers, not how the function should be implemented.

```<code>fib :: int -> int
fib n = (fib n-1) + (fib n-2)
fib 1 = 1
fib 0 = 1
</code>```

To make this code run, the Haskell compiler must convert this declarative specification of the function to imperative machine code. Isn't this by definition a kind program derivation?


问:
How to split large, tightly coupled classes?
I have some huge classes of more than 2k lines of code (and growing) that I would like to refactor if possible, to have some more light and clean design.

The reason it is so big is mainly because these classes handle a set of maps that most methods need to access, and methods are very connected to each other.

I will give a very concrete example: I have a class called Server that handles incoming messages.
It has methods like joinChatroom, searchUsers, sendPrivateMessage, etc.
All of these methods manipulate the maps such as users, chatrooms, servers, ...

Maybe it would be nice if I could have a class handling messages concerning Chatrooms, another handling all about Users, etc.
but the main problem here is that I need to use all of the maps in most of the methods.
That's why for now they are all sticked in the Server class as they all rely on these common maps and the methods are very connected to each other.

I would need to create a class Chatrooms, but with a reference to each of the other objects.
A class users again with a reference to all the other objects,
etc.

I feel like I would be doing something wrong.

答: I would use the same answer I provided elsewhere: take the monolithic class and divide its responsibilities among other classes.  Both DCI and the Visitor Pattern provide good options for doing so.</p>

OwnerDisplayName: Matthew


答:
If it's possible to algorithmically generate imperative machine code from your specification, then your specification is, by definition, itself a program - most likely a Domain Specific Language.

What about the converse, is a program a specification?  Part of the definition of a specification is probably that it be understandable to humans what it does and why it does it.  Clearly this is pretty fuzzy.  What humans, what degree of understanding?  Arguably functional languages declarative nature makes them more understandable to humans, but the state of affairs today is that most programmers are more familiar with imperative languages and understand them better, so it's pretty hard to take that as a proven fact.


答:
Probably need a little balance in the amount you should learn. It's not all or nothing, so put as much time in it as you can. You have to ask yourself what risks you are wiling to accept by relying on the framework.

It's great if all you need is to get some Minimum Viable Product up and running. There aren't going to be huge performance or complex requirement gotchas. This assumes you picked a framework that can handle what it is you're trying to build.

On the other side of the spectrum is if you are working on a fairly large/complex application and you find something that the framework handles poorly. No big deal, so you end up having to learn more JavaScript. You would have had to spend that time on it if you learned it from the beginning. But do you have the time? Will you be able to learn the fundamentals under the stress of not getting something done on time? No one can answer that.

Balancing it out is probably the best bet. Pace yourself. Learn some JavaScript if you can. You may not become an expert, but that is no reason to ignore it. Frameworks were created by people who needed to solve a problem similar to yours, but not exactly like yours.

Title: Is it beneficial to study past the basics of a core language when the primary goal is to rely on its framework?

Body:
Please keep in mind this is not another 'How much [insert programming language here] should I know before moving onto [insert framework here]?' What I'd like to know is how beneficial is it to learn the those advanced concepts of a programming language when your intention is to heavily rely on its framework the majority of the time. So for example I've began to use jQuery and first took the time out to really grasp the core concepts of Javascript. Additionally I have a few beyond the basics books (Secrets of a Javascript Ninja for instance) on the shelf that really delve into the language. As I skim through the pages though I find that a fair bit of it doesn't carry over to jQuery being that my main intention is DOM manipulation.

The same can be said for Ruby and RoR. Will these books make me a better programmer overall? Probably. Can these topics help me become that much better with its framework? That's what I'm having a hard time understanding.


问:
Do you have your own 'misc utils' library? What part are you most proud of?
I know that many of us maintain our own little personal library with tools and utilities that we use often.

I've had mine since I was 16 years old so it has grown to quite a considerable size. Some of the stuff I've written has since been added to the framework. I wrote my own little implementation of expression trees for use with genetic algorithms long before LINQ, which I quite like and was proud of at the time - of course its pretty useless now. But recently I have been going through it and upgrading to .NET 4.0 and re-kindled an interest.

So I'm curious as to what you use your library for. Maybe we could get some cool ideas going for useful little snippets and share them amongst ourselves.

So my questions are:

Do you have a miscellaneous utility library?

Which part are you most proud of and why?

Give an example of code if you like :-)

答:
No.

I do most of my coding in Java, and best practice is to reuse "utils" from Apache Commons libraries and similar projects.

If you are objective about it, there are few cases where your own "utils" collection will be a significant improvement on what other people have already done.  And if it is not an improvement, then your utils library is probably a waste of development time, and a nuisance / burden for future maintainers.

ContentLicense: CC BY-SA 2.5


答:
I would say never.

Is better for you and for the maintainer to have a common language (english). you don't know when your language will not be able to express what are you doing, I speak 4 different languages. I don't master english, is not even my best language but any commentary or definition fits better in english than any other.

And I must add, this can help improve your understanding of technical English , your ability to understand global forums which probably will not be in italian.

Title: When should the programmer's spoken language be used during development?

Body:
I'm an Italian developer, but I have a good understanding of English.

Sometimes, when developing an application targeted for an Italian audience, I wonder whether it is correct to use the Italian language in my code or not.
By "Italian language in my code" I mean the names of methods, classes, comments, variables and so on.

For example, when I write code like this:

```<code>/* Attenzione: metodo esageratamente complicato */
public double calcolaImposteDeiServizi() { ... }
</code>```

Do I break any sacred law of programming because I didn't write that code as follows?

```<code>/* Caution: overly complicated method */
public double calculateTaxesOfServices() { ... }
</code>```

I remember a project I worked on some time ago. It was about calculating VAT/taxes/bonuses. Some of this code was dealing with concepts that existed only in the Italian economy at that moment.

I preferred to write that project using only Italian names for methods, otherwise it would clearly have become a mess understanding that VAT was Italian's IVA and so on.

By using this example, should there be some kind of rule for deciding whenever to use your language or not in code?

Did any highly authoritative programmer ever said something about this issue?

How do you make this kind of decision in your projects?


问:
How to list open source license owner
I am releasing software developed in a university under the Apache 2.0 license.  I would like advice on who to list as the license owner.  Would I list only my boss who co-authored the software and maintains the code base, or both my boss and the institution, or just the institution?

I'm inclined to put my bosses name and institution, but I wanted to find out of that was an acceptable practice.

Also do you know if multiple individuals are ever listed as license owners?

答:
The usual situations are

The copyright holders are one or more individuals. This is often the case with small to medium sized projects that got started as a personal project, or

The copyright holder is a legal entity such as a company, institution or foundation. This is usually the case with large open source projects and projects started by an organization.

This means that it is very unusual to list both an organization (like your institution) and some individuals as copyright holders, especially if those individuals are also employed by the organization.

To get a definitive answer on who is the copyright holder, you must ask your boss or the administrators of your university. Most likely, the copyright lies with the university.

Title: How to list open source license owner


问:
How to check the space complexity of this program?
I have written my version of strstr function in c. I am using a temporary array of size 26. Then is the space complexity O(1) or O(n)?
This is my code :

```<code>void strcheck(char t[], int n, char p[], int m)
{
    int i, j, k;
    int temp[26];

    for (i = 0; i < 25; ++i)
        temp[i] = 0;
    for (i = 0; i < n; ++i)
    {
        k = t[i] - 'a';
        temp[k]++;
    }
    for (j = 0; j < m; j++)
    {
        k = p[j] - 'a';
        if (temp[k] > 0)
            temp[k]--;
        else
            break;
    }
    if (j == m)
        printf("string occured\n");
    else
        printf("not occured\n");
}
</code>```

The program is working correctly just wanna know about space complexity. Thanks

答: This is using O(1) (also Big-Theta(1), as the best-case and worst-case use are the same figure) space-complexity as the the amount of space needed to perform the operation does not increase with n.</p>


问:
Functional Programming vs. OOP
I've heard a lot of talk about using functional languages such as Haskell as of late. What are some of the big differences, pros and cons of functional programming vs. object-oriented programming?</p>

答:
An analogy:

You're handed a job application.  You fill in your name, contact information, and work history.  When you're finished you no longer have a blank application.

Now imagine instead that before writing you overlay it with a clear sheet of cellophane.  You write your name.  You add another sheet of cellophane.  You write your contact information.  More cellophane.  You write your work history.  When you're finished you still have the blank application untouched.  You also have three sheets of cellophane each having captured the effect of a single, discrete change.

The former (OOP) embraces the idea of changing things in place while the latter (FP) shuns it.  Both are state management paradigms.  Both can, using different strategies, capture the effect of completing a job application.  OOP changes the starting instrument directly, while FP overlays what came before to effect the appearance of change.

Title: Functional Programming vs. OOP


答:
I'd say use English, but it's more complicated than just saying that. I'd not use public Money calcolaIVA() for the same reason that I would not use public Money calculateVAT(), they're too specific to the domain.

IVA and VAT are domain specific terminology that only applies to each respective country. Even when different countries use the same terminology, they often have slightly different rules that it  does not really make sense to use domain-specific terminology here.

Instead, I would use public Tax[] getAllTaxes(), and use an strategy pattern to choose, in runtime, between ItalianTaxRules(), UnitedKingdomTaxRules(), USTaxRules(), some_country = SimplePercentageTaxRule(0.05), etc.

Each strategy then can use domain specific terminologies in the target language for nouns in comments and class names, because translating domain-specific nouns would almost always introduce confusion and ambiguities even for people who do not speak the language.

Public methods between the Strategy and Context should always use generic terminologies in English. Private methods within the Strategy itself can use domain specific language as appropriate, but I would have just used English verbs with localized nouns private Money calculateIVA() {} rather than private Money calcolaIVA() {}.

PS: replace English above with "The Common Language". "The Common Language" is the language you expect ALL maintainers of the program now and in the future will speak. In most situations, the only reasonable choice for this is English, but there may be situations where it make sense that "The Common Language" be another language.


问:
How to get money from reluctant client?
I completed this website 4 months ago. (I would like to keep the website anonymous - if this post comes up on google search by customers, it will have a negative impact on their business). We did several iterations, the client was very demanding (and nosy), I complied with every single thing that was wanted, including the font-size of the footer which destroyed the aesthetic looks by quite a bit; (and they messed with the colours too, making it look dangerously childish and unprofessional).

Anyway, the client was very friendly during the whole process. After getting all the requirements I accepted to build the website for £950 and I charged him £150 in advance so he wouldn't want to bail out after I started the work. The requirements kept changing quite a lot, I made adjustments as and completed the website just 5 days late, w.r.t. the agreed date, in-spite all the changes in requirements.

That was four months ago. They have never returned my calls nor replied to my emails since then. How do I get the money back from them? I really need some advice on this, this is the second time someone has not paid me.

Points to be noted:

We did not sign any contract - the client was a friend of a friend.

I still hold the passwords for ftp, cpanel and everything. I don't want to bring the site down; somehow it doesn't seem ethical to me.

I posted this on Stack Overflow and it was closed, I was redirected here.

EDIT

Thank you everyone, for your enormous support. I thought I should include some more details: The client is hosting the site; as in, I made them register and use their own debit card to buy the domain name, webspace and everything, I just have the passwords for his cpanel, and ftp (well, I have access to cpanel that pretty much gives me access to many things).

Now, if I give them a warning, he might change the password to cpanel, but I am fairly sure they doesn't know about ftp's.

UPDATE

I followed Anna Lear's advice and sent the final invoice, on Saturday, with a warning that I will take the site down if he doesn't respond to my email before this Tuesday. They havn't replied to my emails yet, but I will let you know how this goes. Thanks much for your support. I plan to put up a holding page as Darknight suggested after Tuesday.

Points

I don't have a server space of my own, however I have few web spaces of my clients but I don't want to use them for this kind of purpose.

RESULTS

After my follow up of final invoice and warning, the client refused to anything. workman's advice seemed to be the most sensible to me. I mirrored the site to my own webspace, logged into his CPanel and forwarded the website to my site. Once that was done, I put up a holding page on my site so anyone going to the website would see a holdup page (nothing fishy, just an Under Construction page). Of course, this was all very weak in the sense that if my client knew about CPanel he could just remove the redirection. But, I had this second chance to get back to him and I was relying on him not knowing anything.

Two hours later, I got a call from the said client, (and  acting as if they did not get any of my voice mails or emails) and asked me to get the site back up. I, of-course, said I had to be paid and two days after that I received a bank transfer. The site's back up and running now.

Just wanted to say thank you all very much, I was very desperate when I had started this question. You are the best, not only you told me to learn the lesson (which I did) you also gave me a very very good solution that seemed to be very ethical (almost) to me.

A BIG thank you to workman!

If I could choose more than once answer, I would have chosen Anna Lear  too, but since I followed workman's advice I had to pick that up. People who made a point about not taking the site down without consulting a lawyer, thanks a lot.

答:
I think a call to an attorney may be premature. You may want to consult with a collection agency.

They may not be able to help you with your current case, unless you have documentary evidence to support your claim (invoices and account statements may work for some agencies; signed contracts plus invoice history may be required for others). However, even if you can't find one who will help you with this one, they'll probably tell you what kind of documentation you'd need to engage them for future projects, should that ever become necessary again.

If you do engage a collection agency, they'll probably take a cut of whatever they recover; some will simply purchase the debt at a (substantial) discount. Some of them simply add a fee that they bill to the recipient, and they may even recover interest charges. Most likely they will be meaner than you, and they'll probably be more persistent than you if they do take on the case. They're likely to be as effective as an attorney, and the cost burden will be pretty clear to you up front, whereas an attorney is more likely to bill as many hours as it takes until you give up.

Title: How to get money from reluctant client?


问:
Responsibility for delegation of stories in agile
I've recently worked on a project where the Team lead was commenting he needed to figure out which stories we are going to be working on in a scrum.  It was my understanding that stories are prioritized and perhaps a number of stories are added to a sprint from that list.  At this stage during our scrum the developers each pick a story they are going to implement and off they go.

I suppose if a number of stories have dependencies them the team lead might help facilitate the story priority within the sprint itself but not actually dictate which developer does which?

None of us are juniors in the team and we all have equal knowledge about the domain.  Our experience of particular facets of the layers i.e. UI, database, infrastructure vary but not dramatically so.

So my main question is as to the role of a Team lead (and other developers I guess) within a sprint itself and delegation of stories.

If it helps, the project was a MVC .NET application with some database backing.  Our team consisted of 4 developers, 1 tester and a Project manager.

答:
Let me try and address your question as it relates to agile and Scrum (for more details review the Scrum Guide and the Agile Manifesto):

In Scrum stories are for the entire team not for individuals.  During sprint planning the team and the product owner decide which stories would be tackled during the sprint.

In Scrum there is no team lead.

A Scrum team is self-organizing, that is no one tells the Scrum team how to work on a particular problem.

In Scrum there is no project manager.  There is a Scrum Master, a Product Owner, and the Team.

The Product Owner is responsible for the backlog, it's content and ordering.  The team is responsible for all estimates for the backlog.

Agile is a set of guiding principles for software development.  Agile doesn't specify any specific practices.  Agile methodologies such as Extreme Programming specify practices that meet the spirit of agile.

All that said, it is typical that organizations will have their own "flavour" of "Scrum" or "Agile".  If your boss is your team lead and he wants you to work in a certain way it is important to understand that is what you're trying to address rather than the details how how Scrum or Agile are supposed to work.  Going to your Team Lead and telling them there's no "Team Lead" in Scrum, though true, isn't going to be useful.  It's extremely unlikely that a team lead would resign their position upon hearing that bit of information.  In many situations, taking the position that Scrum is supposed to be done a certain way will be counter-productive to impacting change.  Ideally you should be able to persuade others that a certain change is good on it's own merit rather than referring to some standard way of doing something.

To conclude it sounds like you should approach your team lead and suggest that you and the other developers are capable and should be able to select the stories/tasks they work on during the sprint.  You'll need to be able to articulate the benefits of this without appearing to criticize the way you currently work.  You can suggest to try out doing things differently for the next sprint and see how it works out.  Typically this sort of activity would occur during the sprint retrospective which I'm guessing your team does not do.


答:
A general area that suffers from delving in the framework(s) before knowing the core language well is performance. This is true for all languages/platforms (Hibernate n+1 selects etc). Here's a lot of JQuery tips and tricks which  rely (among other things) on good knowledge of the core language in relation to performance:

Use For Instead of Each Native functions are always faster than any
  helper counterparts. Whenever you're looping through an object
  received as JSON, you'd better rewrite your JSON and make it return an
  array through which you can loop easier.

Use IDs Instead of Classes It's much better to select objects by ID
  because of the library's behavior: jQuery uses the browser's native
  method, getElementByID(), to retrieve the object, resulting in a very
  fast query.


答:
I think your question is based on a false premise. You start by saying that you're planning to rely on a framework, and then you ask if it's beneficial to learn beyond the framework. So of course you come to the conclusion it's not worth it. But that premise is flawed. You shouldn't focus on using a framework. You should focus on using the right tool for the right job. jQuery is really good at certain tasks, and so is Ruby on Rails or any other framework. But they aren't always the right tool for everything. Learning about the language beyond the framework, and even learning about other frameworks or microframeworks or other tools, helps you identify when your framework is getting in your way more than it's helping, and it gives you the ability to seek other, better solutions.

So my answer is: yes, it's absolutely worth it because the framework isn't the right tool for every job.


问:
Making server logic independent of client interaction
I'm trying to make a realtime multiplayer web-game in node.js with express framework and socket.io library.
But I can't seem to make my server-side logic independent of client interactions.
I want client to interact only when I (server side logic) want but I can't seem to be able to do that. For example:

I want 2 users to
start playing a game. I have to first initialize the game, like set up environment, variables and stuff.. all in a separate, call it: The Game Logic. Only then can I "allow" the clients to interact.

But how am I supposed to carry on with my Game logic when my socket.on event is "calling the shots"?
With socket.io you have to define triggers like

```<code>io.sockets.on('connection', function(socket) {
    socket.on('event', function(data) {
        //supposed this is fired when client hits an "interact with X" button
    });
}
</code>```

All my logic seem to be dependent on these triggers. I only wanted client to be able to fire that event when I want (after I've set up the game env etc), but defining it like so, separated from my game logic, it creates problems like how am I supposed to transfer the execution control from socket into my game logic? And even if I managed to, there's that whole client "calling the shots" problem. I then have no control when client could want to interact.

Any advice what should I do?

答:
Your game object would typically be a separate prototype function (class). It might look like this:

```<code>Game = function() {
  var sockets = [];
  var pendingEvents = [];
  var interval = 500; // Process every 0.5s

  var init = function() {
    // Do game initialization stuff here

    // Start the game timer
    setInterval(function() {
      gameLoop();
    });
  };

  // Do the actual game loop
  gameLoop = function() {
     // Do some work

     // Handle user events, starting with the oldest
     var message = pendingEvents.shift();
     while ( null != message ) {
         handleMessage(message.socket, message.data);
         var message = pendingEvents.shift();
     }

     // Do other stuff
  };

  // Process a player's message event
  handleMessage = function(socket, data) {
  };

  addSocket = function(socket) {
      sockets.push(socket);
  };

  queueEvent = function(event) {
      pendingEvents.queue(event);
  };

  return {
    queueEvent: queueEvent,
    addSocket: addSocket
  };
}
</code>```

This game class gives you a skeleton that holds all the connected sockets (loop through to send a message to everyone) and does some game logic every 500ms. During the game loop it looks in the message queue for player events  it needs to handle.

Now going back to your original socket code, you can inject player events into the game like this:

```<code>// This happens anywhere
var gameInstance = new Game();

// Now watch for sockets
io.sockets.on('connection', function(socket) {
  // Add the socket to the game
  gameInstance.addSocket(socket);

  socket.on('event', function(data) {
    // Push the client event to the game, game will handle it on its own terms
    gameInstance.queueEvent({
      socket: socket,
      data: data
    });
  });
}
</code>```

Body:
Your game object would typically be a separate prototype function (class). It might look like this:

Game = function() {
  var sockets = [];
  var pendingEvents = [];
  var interval = 500; // Process every 0.5s

  var init = function() {
    // Do game initialization stuff here

    // Start the game timer
    setInterval(function() {
      gameLoop();
    });
  };

  // Do the actual game loop
  gameLoop = function() {
     // Do some work

     // Handle user events, starting with the oldest
     var message = pendingEvents.shift();
     while ( null != message ) {
         handleMessage(message.socket, message.data);
         var message = pendingEvents.shift();
     }

     // Do other stuff
  };

  // Process a player's message event
  handleMessage = function(socket, data) {
  };

  addSocket = function(socket) {
      sockets.push(socket);
  };

  queueEvent = function(event) {
      pendingEvents.queue(event);
  };

  return {
    queueEvent: queueEvent,
    addSocket: addSocket
  };
}

This game class gives you a skeleton that holds all the connected sockets (loop through to send a message to everyone) and does some game logic every 500ms. During the game loop it looks in the message queue for player events  it needs to handle.

Now going back to your original socket code, you can inject player events into the game like this:

// This happens anywhere
var gameInstance = new Game();

// Now watch for sockets
io.sockets.on('connection', function(socket) {
  // Add the socket to the game
  gameInstance.addSocket(socket);

  socket.on('event', function(data) {
    // Push the client event to the game, game will handle it on its own terms
    gameInstance.queueEvent({
      socket: socket,
      data: data
    });
  });
}


问:
Mental Models or Real-World-Metaphors for Functional Programming
Does anyone have a good mental model or metaphor for functional programming which references something in the real world?

Object Oriented programing intuitively makes sense to me. There are things that have properties and sometimes they also can do stuff or perform calculations on their properties (methods). (Ex: Car, Shape, Cat).

I bear functional programming no ill will whatsoever and I am not interested in a debate about the virtues of the two. I just need a metaphor or mental model to work with as I have with Object Oriented programming.

What are some good mental models or real world metaphors for programming in a functional paradigm? There is something about functions composed of functions processing functions which leaves one without a firm place to stand and cogitate.

答:
You can think of functional programming as about behaviours. A program is a description of the behaviour that you want the computer to enact. Functions are the basic unit of behaviour, and function composition is one way to build larger behaviours out of smaller ones.

In OOP, a code object is intended to be the state of an object in the problem domain; it changes over time to reflect changes in that domain object. In FP, a value represents the state of a domain object; it never changes, you simply create different values to represent different states.

I find the functional model a bit more honest about what computers are actually doing—representing. After all, I can’t just conjure a new Tesla() out of thin air. :)


问:
ORM domain design pitfalls
Are there any patterns which seem sensible when designing an object oriented domain, but do not translate nicely onto a relational database schema?  If so, are there standard patterns that can be used instead?</p>

答:
Referencing data that can change, in a record that shouldn't.

I've seen a number of implementations that had something like:

```<code>Order
    Id : int
    OrderDate : DateTime

OrderProduct
    Id : int
    OrderId : FK of Order
    ProductId : FK of Product
    Quantity : int
    Cost : Decimal

Product
    Id : int
    Description : string
</code>```

The code ends up looking something like:

```<code>class Order
{
    int Id;
    DateTime OrderDate;
    List<OrderProduct> OrderLines;

    AddProduct(Product p, int quantity)
    {
        this.OrderLines.Add(new OrderProduct(this, p, q));
    }
}

class OrderProduct
{
    int Id;
    Product Product;
    Order Order;
    int Quantity;
    Decimal Cost;

    OrderProduct(Order o, Product p, int quantity)
    {
        this.Order = o;
        this.Product = p;
        this.Quantity = q;
        this.Cost = p.Cost * quantity * applicableTax;
    }
}

class Product
{
    int Id;
    string Description;
}
</code>```

It seems correct at first glance, the code works fine, and the data ends up being nicely normalized, and you can create and read orders correctly.

Except that if you sell an order today, and you receive info from a supplier tomorrow that the description of something on the product has changed, those systems usually just update the product with the change. Now if you were to reproduce that order 2 days from now the contents of the order will have changed, and you'll be none the wiser.

There's some easy ways to solve this problem but I've seen it a number of times in varying degrees of severity.

Title: ORM domain design pitfalls

Body:
Referencing data that can change, in a record that shouldn't.

I've seen a number of implementations that had something like:

Order
    Id : int
    OrderDate : DateTime

OrderProduct
    Id : int
    OrderId : FK of Order
    ProductId : FK of Product
    Quantity : int
    Cost : Decimal

Product
    Id : int
    Description : string

The code ends up looking something like:

class Order
{
    int Id;
    DateTime OrderDate;
    List<OrderProduct> OrderLines;

    AddProduct(Product p, int quantity)
    {
        this.OrderLines.Add(new OrderProduct(this, p, q));
    }
}

class OrderProduct
{
    int Id;
    Product Product;
    Order Order;
    int Quantity;
    Decimal Cost;

    OrderProduct(Order o, Product p, int quantity)
    {
        this.Order = o;
        this.Product = p;
        this.Quantity = q;
        this.Cost = p.Cost * quantity * applicableTax;
    }
}

class Product
{
    int Id;
    string Description;
}

It seems correct at first glance, the code works fine, and the data ends up being nicely normalized, and you can create and read orders correctly.

Except that if you sell an order today, and you receive info from a supplier tomorrow that the description of something on the product has changed, those systems usually just update the product with the change. Now if you were to reproduce that order 2 days from now the contents of the order will have changed, and you'll be none the wiser.

There's some easy ways to solve this problem but I've seen it a number of times in varying degrees of severity.


问:
How do you keep track of the meaning of your SQL fields?
The more SQL fields I add to my tables and the more primary/foreign keys I add the more I lose the overview for specific fields for certain scenarios like Get/Add/Delete/Update data.

I use SQL Management Studio (SQL Server) to design my database in the database diagram designer.

Maybe there is a better tool or good approach how to keep track of the meaning of all those fields?

答: The best naming in the world can't help you to know the details of why a field exists or what to look out for in the data. Check out Database Note Taker which is a free lighter weight tool enabling you to add an explanation to your database objects. Could be a short note, could be a longer description with example queries and using markdown syntax for formatting. It keeps your comments in a separate project file which is source control friendly.</p>


问:
What is the Enterprise Architecture Pattern called for a web service wrapping a web service?
As part of a service orientated architecture (SOA) I've been asked to create a
 web service which itself acquires data from a third party web service.  I'm to hide any implementation specific details of the third party web service and map the data returned so as to avoid leaking any implementation details of the third party service.

I'm new to SOA.  I would colloquially call this project something like "a web service bridge".

What is the correct SOA enterprise architecture pattern term for this?

I'm very confused as many of the enterprise architecture patterns seem to be describing the same thing (service facade?, message broker? message channel? proxy?).  I don't think I'm quite in tune with the level of abstraction required.

答:
What you're describing is essentially the Adapter design pattern. You have an external component that you want to use, but it's implementation and interface is not what you want to use within your enterprise. </p>

<p>The fact that you're exposing your wrapper as a web service is irrelevant as the pattern is still the same. You're essentially wrapping an existing service with a new interface. </p>

Body:
What you're describing is essentially the Adapter design pattern. You have an external component that you want to use, but it's implementation and interface is not what you want to use within your enterprise.

The fact that you're exposing your wrapper as a web service is irrelevant as the pattern is still the same. You're essentially wrapping an existing service with a new interface.


问:
Is storing pointer (of new'd object) in static collection from object constructor a common idiom in C++
I am reviewing an approach I see commonly used in storing objects (e.g. a socket client object). Namely, usage of a static container to hold the objects. Said objects are created by some helper function as follows:

```<code>create_client(params) {
  ...
  client* cl = new client(...);
  return cl;
}
</code>```

The thing that confused me at first was function called like this:

```<code>if (!create_client (...))
   //generate error message
</code>```

i.e. a copy of the pointer just seems to be thrown away.

But on investigation I see this in the client constructor:

```<code>client::client(...) {
    ...
    coll[id] = this;
}
</code>```

Where coll is a map of id to a pointer to the object. But anyway, just a collection.  coll is static (not sure if that is relevant).

Is there a name for this idiom?  Is it good practice?

答: This thing is called a multiton, so, yes, it is an idiom. It's not a good practice, though.


问:
Do I need an IDE to develop Android apps?
After reading some articles on Google, I decided to start working on Android apps since it's an open source platform from Google.

So I wanted to create some apps.I have Android 2.2 Os So I just googled it to find the things and I finally found this link to create Android apps.

Is this the link that enables me to create apps or does we need any other IDE? Like we have gcc for c and VC++ for C++. What other things to do I need to set up to get going on this?

答: Yes you need IDE for android app development. You can use Eclipse because they provide a plugin, which makes it easy to use android sdk tools for your IDE and also they are improving android studio.</p>


问:
How should I unit test a bitmap modifying method?
My Sprite class has a method:

private void updateWithBitmap(Bitmap b, int x, int y)

This will 'lay on top' the bitmap that's passed in, the top left corner of the passed in bitmap being at the x,y position of the parent bitmap.

Now I want write unit tests to check that this method is working correctly.

For example, we'll need to check that an exception is thrown when the passed in bitmap is larger, or is out of bounds of the parent bitmap.

```<code>    [TestMethod]
    [ExpectedException(typeof(System.ArgumentOutOfRangeException))]
    public void TestUpdateWithBitMap_SmallerParent_ThrowsOutOfRangeException()
    {
       Sprite parent =  new Sprite(new Bitmap(10,10));
       Bitmap child = new Bitmap(20, 20);
       parent.updateWithBitmap(child,0,0)

    }

    [TestMethod]
    [ExpectedException(typeof(System.ArgumentOutOfRangeException))]
    public void TestUpdateWithBitMap_PassedBitMapOutOfBounds_ThrowsOutOfRangeException()
    {
        Sprite parent =  new Sprite(new Bitmap(10,10));
        Bitmap child = new Bitmap(3, 3);
        parent.updateWithBitmap(child, 9,9)

    }
</code>```

Good so far.

But also we want to test that the method genuinely is updating correctly.

For example, if the left most image is our parent bitmap, and the middle is the child bitmap, and we call our method with:

parent.updateWithBitmap(child, 3,3);

we get the rightmost bitmap as a result.

The question is:

Is it appropriate to store these bitmaps as resources, and then check the results are equal?

eg.

```<code>    [TestMethod]
    public void TestUpdateWithBitMap_UpdatesCorrectly()
    {
        Sprite parent =  new Sprite(Properties.Resources.TestBitmapParent1);
        Bitmap child = Properties.Resources.TestBitmapChild1;
        parent.updateWithBitmap(child, 3,3)
        #something like Assert.Equal(parent.getBitmap(), Properties.Resources.TestBitmapResult1);

    }
</code>```

答:
As I understand you are using your own custom sprite and not some sprite from DirectX or from DirectXMobile.

What you could try:

1) If your class provides some per-pixel indexer like SomeColorInfo this[int x, int y] or the ToBitmap() method:

You could try to use small parent and child (like few pixels per few pixels) where you could manually calculate all desired pixels and compare resulting and desired images(sprites). For example, supposing for simplicity that you are using greyscale pictures:

```<code>[TestMethod]
void Test_Sprite_UpdateWithBitmap_GreyScaleSprite3x3_GreyScaleBitmap2x2()
{
    // Create 3 x 3 greyscale Sprite from
    Sprite sprite = new Sprite(3,
    3,
    new Byte {
    1, 2, 3,
    4, 5, 6,
    7, 8, 9});

    // Create 3 x 2 bitmap to update with
                Bitmap bitmap = new Bitmap(2,
    2,
    new Byte {
    101, 102
    103, 104});

    // Coordinates of update point
    Int32 x = 1;
    Int32 y = 1;

    // Expected sprite
    Sprite expectedSprite =  new Sprite(3,
    3,
    new Byte {
    1, 2, 3,
    4, 101, 102,
    7, 103, 104});

    // Update  sprite
    sprite.updateWithBitmap(child, 3,3);

    // Assert
    CollectionAssert.AreEqual(expectedSprite, sprite);
}
</code>```

Well your sprite and bitmap should have constructors like Sprite(Int32,Int32, IEnumerable<Byte>); and your Sprite should be IEnumerable(you will just have to make sprite.ToList() in assert) or ICollection

2) If your sprite cannot be calculated(painted) other than in the actual user interface environment or you do not want to add some unneeded members, you should consider some way to get his pixels through other channels. I don't know what UI you use, but most of them provide some sort of a PaintingContext for your custom painting objects. Such an object can be an interface like:

```<code>public interface IPaintingContext : IDisposable
{
    void PutPixel(Int32 x, Int32 y);

    void PutImage(IImage image);

    //... And so on
}
</code>```

that will allow you to mock it and use in your test method like:

```<code>...
IPaintingContext expectedPaintingContext = new MockPaintingContext(3, 3, new Byte[]{...});
...
IPaintingContext paintingContext = new MockPaintingContext();
...
sprite.PaintOn(paintingContext);
...
CollectionAssert.Assert(expectedPaintingContext, paintingContex);
</code>```

If your environment provides such functionality in a not an interface way, then you could create your own custom infrastructure of a such kind: IPaintingContext context = new MyUiPaintingContextWrapper(UI.GetPaintingPlane())

Body:
As I understand you are using your own custom sprite and not some sprite from DirectX or from DirectXMobile.

What you could try:

1) If your class provides some per-pixel indexer like SomeColorInfo this[int x, int y] or the ToBitmap() method:

You could try to use small parent and child (like few pixels per few pixels) where you could manually calculate all desired pixels and compare resulting and desired images(sprites). For example, supposing for simplicity that you are using greyscale pictures:

[TestMethod]
void Test_Sprite_UpdateWithBitmap_GreyScaleSprite3x3_GreyScaleBitmap2x2()
{
    // Create 3 x 3 greyscale Sprite from
    Sprite sprite = new Sprite(3,
    3,
    new Byte {
    1, 2, 3,
    4, 5, 6,
    7, 8, 9});

    // Create 3 x 2 bitmap to update with
                Bitmap bitmap = new Bitmap(2,
    2,
    new Byte {
    101, 102
    103, 104});

    // Coordinates of update point
    Int32 x = 1;
    Int32 y = 1;

    // Expected sprite
    Sprite expectedSprite =  new Sprite(3,
    3,
    new Byte {
    1, 2, 3,
    4, 101, 102,
    7, 103, 104});

    // Update  sprite
    sprite.updateWithBitmap(child, 3,3);

    // Assert
    CollectionAssert.AreEqual(expectedSprite, sprite);
}

Well your sprite and bitmap should have constructors like Sprite(Int32,Int32, IEnumerable<Byte>); and your Sprite should be IEnumerable(you will just have to make sprite.ToList() in assert) or ICollection

2) If your sprite cannot be calculated(painted) other than in the actual user interface environment or you do not want to add some unneeded members, you should consider some way to get his pixels through other channels. I don't know what UI you use, but most of them provide some sort of a PaintingContext for your custom painting objects. Such an object can be an interface like:

public interface IPaintingContext : IDisposable
{
    void PutPixel(Int32 x, Int32 y);

    void PutImage(IImage image);

    //... And so on
}

that will allow you to mock it and use in your test method like:

...
IPaintingContext expectedPaintingContext = new MockPaintingContext(3, 3, new Byte[]{...});
...
IPaintingContext paintingContext = new MockPaintingContext();
...
sprite.PaintOn(paintingContext);
...
CollectionAssert.Assert(expectedPaintingContext, paintingContex);

If your environment provides such functionality in a not an interface way, then you could create your own custom infrastructure of a such kind: IPaintingContext context = new MyUiPaintingContextWrapper(UI.GetPaintingPlane())


问:
How could your company's learning/development department best serve you?
I'll preface my question with a disclaimer - I am not an engineer, I'm just someone who works with them full-time, in a learning and development capacity.

Given that, one of the comments I get regularly from the engineers I'm tasked with developing is that they feel that they're having solutions (both technical and non-technical) for development "pushed" at them vs. anyone from my field consulting with them to determine what they really need.

So my question is - if you could give your company a list of the top 3-5 things they could do - in a classroom, or elsewhere - to develop meaningful skills that would help you be a better engineer, a better employee, and one more likely to STAY with the company for the long haul, what would make the cut and why?

Thanks in advance for your responses.

答: One of the thing to do will be to give the developers some free time to work on their favorite technology and/or personal project in the office time. Create a forum for such ideas and let the developers share their ideas with each other. </p>


答:
Is it appropriate to store these bitmaps as resources

Well, whatever will work for you is appropriate, isn't it? Your unit tests should run quick, be functional, should be easy to maintain and to extend, and if they fail, they should make root cause analysis easier for you.

"quick" can be fulfilled by using very small bitmaps

"functional": to include significant cases, the bitmaps must be actually not too small. For your case, I guess bitmaps with a side length of minimum of 3 or 4 will probably make sense.

easy to maintain and to extend: well, as long as your tool set allows easy bitmap manipulation, storing of bitmaps in a resource and retrieving it again, that should not be much of an issue

"make root cause analysis easy": for this, you may have to make some provisions. If you just "check if the results of a bitmap comparison are equal", you might not easily see how your "testBitmap" looks like and why it does not match the expected results. But it should be pretty simple to add some code which in case the equality test fails, writes your test bitmap to disk so you can check it easily with an imager viewer (either just visually, or by creating something like a "difference image" between the expected bitmap and your test bitmap)

Of course, the alternative would be to create some per-pixel tests with hard-encoded colors and coordinates, but though that will surely work, IMHO that's not easier to maintain and can become very tedious.

Some related posts on other SE sites:

https://stackoverflow.com/questions/16217982/comparing-images-as-byte-arrays-for-unit-tests

https://sqa.stackexchange.com/questions/3136/how-to-test-the-graphical-contents-of-a-bitmap-or-a-pdf-file

Title: How should I unit test a bitmap modifying method?

Body:
My Sprite class has a method:

private void updateWithBitmap(Bitmap b, int x, int y)

This will 'lay on top' the bitmap that's passed in, the top left corner of the passed in bitmap being at the x,y position of the parent bitmap.

Now I want write unit tests to check that this method is working correctly.

For example, we'll need to check that an exception is thrown when the passed in bitmap is larger, or is out of bounds of the parent bitmap.

```<code>    [TestMethod]
    [ExpectedException(typeof(System.ArgumentOutOfRangeException))]
    public void TestUpdateWithBitMap_SmallerParent_ThrowsOutOfRangeException()
    {
       Sprite parent =  new Sprite(new Bitmap(10,10));
       Bitmap child = new Bitmap(20, 20);
       parent.updateWithBitmap(child,0,0)

    }

    [TestMethod]
    [ExpectedException(typeof(System.ArgumentOutOfRangeException))]
    public void TestUpdateWithBitMap_PassedBitMapOutOfBounds_ThrowsOutOfRangeException()
    {
        Sprite parent =  new Sprite(new Bitmap(10,10));
        Bitmap child = new Bitmap(3, 3);
        parent.updateWithBitmap(child, 9,9)

    }
</code>```

Good so far.

But also we want to test that the method genuinely is updating correctly.

For example, if the left most image is our parent bitmap, and the middle is the child bitmap, and we call our method with:

parent.updateWithBitmap(child, 3,3);

we get the rightmost bitmap as a result.

The question is:

Is it appropriate to store these bitmaps as resources, and then check the results are equal?

eg.

```<code>    [TestMethod]
    public void TestUpdateWithBitMap_UpdatesCorrectly()
    {
        Sprite parent =  new Sprite(Properties.Resources.TestBitmapParent1);
        Bitmap child = Properties.Resources.TestBitmapChild1;
        parent.updateWithBitmap(child, 3,3)
        #something like Assert.Equal(parent.getBitmap(), Properties.Resources.TestBitmapResult1);

    }
</code>```


问:
Repository matrix pattern?
I'm trying really hard to refactor some of my legacy code in the project using best practices and design patterns + DDD so I'd love some feedback on an issue I'm currently having.

Let's assume that I have two entity classes:

class Dog
{
    protected $name;

    function __construct($name)
    {
        $this->name = $name;
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    function bark()
    {
        echo 'Rawr';
    }
}

class Husky extends Dog
{
    /**
     * @var Sledge
     */
    protected $sledge;

    function __construct($name, Sledge $slegde)
    {
        parent::__construct($name);
        $this->sledge = $slegde;
    }

    function pull()
    {
        echo $this->sledge->pull();
    }
}
```

Dog is my regular entity and his only responsibility is to map database fields.
Husky on the other hand has same responsibilities as dog but also delegates Sledge pulling.

Normally, both entities would have different repositories (should they? Since one inherits from one another) to call for, however business requirement implies that client does not have to specify dog's type (so it can either be a "basic" Dog or special Husky), just its name http://localhost/animal/fluffy.

What is more, currently they both reside in the same database table (recognized by type field) and right now there are no technical plans to change that (performance and time reasons).

What is the best way to do it?

Should I create some AnimalRepository, pull the data and treat it as DTO, detect it's type and then create appropriate class?

Should I create some kind of higher abstraction level mapper? How should it look like?

答:
I am not an expert on this subject, but will try an answer.
According to this article the Repository pattern is specifically designed to solve your problem. So in my understanding you should have one repository that will return the concrete or abstract Animal required.</p>

Title: Repository matrix pattern?


答:
Just by the question, one cannot pinpoint a single pattern because there are multiple aspects to a pattern. Depending on how your service is architected, the pattern can vary. In general, however, what you specified is the overarching Service Abstraction design principle.

Also, quite often a piece of software, especially at the scope of a web-service, is composed of multiple design patterns. Thus a web service may be designed with Model-View-Controller pattern while has a set of adapters, data mappers, (explained below) etc. in its various layers. You can still identify its primary business value and map that to a design pattern if that is important for your project. Thus, even though not all the patterns I talk about below may be considered enterprise design patterns by everyone, I find it more useful to use the pattern that conveys what the service does more than whether it is necessarily an enterprise design pattern or not.

From what you stated in your question, it seems most likely to be a Façade or its specialization Remote Façade. It would be a Façade if its primary purpose were to simplify the underlying API and hide the complexity (which is what you are stating). Remote Façade additionally also aims to reduce the number of calls between two systems if that's a concern.

An Adapter pattern is usually architected with an assumption that there are going to be multiple adapters (whether in present or in future). Thus, if your primary concern is to create a web service such that it would provide a consistent interface and be able to perform various operations on underlying service(s), then you are designing an adapter. A typical example would be when you are offering a new deployment service, and expose a method called Compile(). It implements two adapters, one for MSBuild and the other for nmake. Depending on which system a particular project is written in, it will pick up the correct adapter and issue appropriate commands.

A similar pattern is the Data Mapper which is mapping of a consistent set of data types to data types of various underlying data stores. Let's say if your service was exposing a UserId field to its client such that it mapped to a UserName and an UserPrincipal field in two different data stores, then this is what you are looking at. It does not mean that you necessarily have multiple data stores, it means that you are architecting with that possibility in mind.

The Bridge pattern is usually applied where there is an abstraction and its implementation, and yet both need to be varied. Typically, the implementation is achieved using an adapter pattern, so you end up with the Abstraction and its subclasses, as well as a set of adapters.

A Gateway is more around providing a consistent interface between services. So you could have a www.myservice.com which exposes a REST API, which in turn calls other services which may be using various protocols. It is the responsibility of the Gateway to ensure that clients always get the same interface, even when any of those services decides to change its protocols.

Title: What is the Enterprise Architecture Pattern called for a web service wrapping a web service?

Body:
As part of a service orientated architecture (SOA) I've been asked to create a
 web service which itself acquires data from a third party web service.  I'm to hide any implementation specific details of the third party web service and map the data returned so as to avoid leaking any implementation details of the third party service.

I'm new to SOA.  I would colloquially call this project something like "a web service bridge".

What is the correct SOA enterprise architecture pattern term for this?

I'm very confused as many of the enterprise architecture patterns seem to be describing the same thing (service facade?, message broker? message channel? proxy?).  I don't think I'm quite in tune with the level of abstraction required.


问:
A new i/o library: a good idea or a really bad one?
For a long time I worked almost exclusively with input/output streams in java. However a few years ago I started exploring async I/O as well (e.g. running on jboss netty).

However when working in the async I/O world, I could not reuse any of my sync utilities. I also had to start on a rather large library of new I/O utilities and wasn't sure whether to aim for blocking or non-blocking.

As things go...I wrote an API on top of the existing I/O which supports both blocking and non-blocking and the utilities are written against that.

However because I/O is such a pervasive thing, I am unsure whether it is a wise thing to do. As an example take a Base64 encoder. Yes apache has a sync I/O version and yes java 8 finally has an async encoder. But I needed an encoder that could do both.

Same for quoted-printable, deflate,... and of course it should work for sockets (regular & ssl), files,... in single-threaded and multithreaded situations,... I needed utilities to chain together I/O sources, use delimiter-based or fixed-length I/O wrappers,... I needed protocol handlers for http, ftp,...

Many of these problems can be expressed in a blocking-neutral fashion or -given enough thought- could support both async and sync, allowing wide reusability.

In short: is it wise to introduce an abstraction on top of I/O, forcing basically every library that uses it (directly or indirectly) to use it as well?

UPDATE

At the core are the ReadableByteContainer and WritableByteContainer that -to the discerning eye- will look like a cross between stream I/O and channel I/O.

```<code>public interface ReadableByteContainer extends Closeable {
    public int read(byte [] bytes);
    public int read(byte [] bytes, int offset, int length);
}

public interface WritableByteContainer extends Closeable {
    public int write(byte [] bytes);
    public int write(byte [] bytes, int offset, int length);
    public void flush();
}
</code>```

One of the utils built on it is the "Transcoder" api:

```<code>public interface ByteTranscoder {
    public void transcode(ReadableByteContainer in, WritableByteContainer out);
    public void flush(WritableByteContainer out);
}
</code>```

which allows you to do something like:

```<code>ByteContainer container = IOUtils.newByteContainer();
container = IOUtils.wrap(
    container,
    TranscoderUtils.wrapOutput(container, new Base64Encoder())
);
container.write("test".getBytes());
System.out.println(new String(IOUtils.toBytes(container)));
</code>```

This code will output the base64 encoded bytes of "test".

The thing is, the Base64Encoder is capable of encoding the data in an asynchronous manner, it won't block if the output container reports that no data was written nor will it block if the input container reports that no data is available. You can continue the transcoding by calling "transcode()" again.

This works both in a jboss netty context where you get the content piece by asynchronous piece and in the streaming world where everything blocks until it can read/write.

答:
Perhaps an interesting follow-up to this is the actual library that has recently been added to github: https://github.com/nablex/utils-io

Note that the library has gone through an extensive rewrite since this question was asked.

Other libraries based on this one:

https://github.com/nablex/utils-codec : adds encoding/decoding for base64, deflate, gzip & quoted printable

https://github.com/nablex/utils-mime : uses the other libraries to perform low-level mime & s/mime parsing and formatting. As a proof of concept I also wrote a lightweight HTTP client on top of it that might make it to github at some point.


问:
Do you have your own 'misc utils' library? What part are you most proud of?
I know that many of us maintain our own little personal library with tools and utilities that we use often.

I've had mine since I was 16 years old so it has grown to quite a considerable size. Some of the stuff I've written has since been added to the framework. I wrote my own little implementation of expression trees for use with genetic algorithms long before LINQ, which I quite like and was proud of at the time - of course its pretty useless now. But recently I have been going through it and upgrading to .NET 4.0 and re-kindled an interest.

So I'm curious as to what you use your library for. Maybe we could get some cool ideas going for useful little snippets and share them amongst ourselves.

So my questions are:

Do you have a miscellaneous utility library?

Which part are you most proud of and why?

Give an example of code if you like :-)

答:
I have a Java Type Converter. It has a public signature

```<code>public static <T> T convert(Object sourceValue, Class<T> destinationType)
</code>```

and it does its best to convert the source value to the destination type. It essentially lets you do dynamic typing within a statically typed language :-)

It's actually useful with boxed numeric types. How irritating it is that you can't put an Integer to where Long is expected? No problem, just convert it. Or what if your function expects a double, but you have a null to put there? Kaboom, a NPE. But put it through convert,  and you get a NaN.

Body:
I have a Java Type Converter. It has a public signature

public static <T> T convert(Object sourceValue, Class<T> destinationType)

and it does its best to convert the source value to the destination type. It essentially lets you do dynamic typing within a statically typed language :-)

It's actually useful with boxed numeric types. How irritating it is that you can't put an Integer to where Long is expected? No problem, just convert it. Or what if your function expects a double, but you have a null to put there? Kaboom, a NPE. But put it through convert,  and you get a NaN.


问:
How to develop a product compare page
I want to develop a product comparison page, where a user can compare 2 or 3 products. I was thinking about a 3 column list displaying every specification. But I want to highlight the differences.

I could use a list and sort them alphabetically. And then if element x of list 1 is not equal to element x of list 2 then highlight it. But I 'm not sure every product has the same elements. Maybe element x is missing in list 2.

What could be a good method to develop this? Should I mark some elements on every product that can be compared (like a sort of element classes) ? So that I can check if elements from elements class x differ on 2 products. Any other suggestions?

答:
To detect differences between two lists (lets call them A and B), generally you make two passes.  The first pass checks each item of A and checks if it is in B, and if so, if the item in B has been changed in some fashion (if item is mutable at least).  The second pass involves checking each item of B to see if it is not in A.

At the end of these two passes, you're left with a list of all items in A and not in B, all items in B and not in A, and all items that are in both but differ.

What you're talking about is a different, but only slightly.  Rather than 2 lists, you have n.  I'm assuming some specifications won't apply to some products and may hence be missing.

So in order to have to perform a pass for each list, it would be simpler to combine all specifications into a single Set (eliminate duplicates).  Then, for each specification, cycle through each product.  Take the first product as a frame of reference and check its value.  Compare that value to every other product for that specification until you find a difference.  If you find a difference, break and continue with the next specification.  In this way, you only have to make a single pass for each product and for each specification (ok, two if you count getting a complete list of specifications assuming you don't have it already).

In this way, you know which specifications differ between products.  However in general, in a product comparison, you exclude specifications which do not differ between products, so rather than highlight those which are different, I would simply suggest to remove it entirely.  However that's just my 10 cents.  ;)

Title: How to develop a product compare page


答:
I found I was writing a lot of the same code in django, Do this common thing, then this common thing, and finally that common thing.  Basically get one or more items from the database, or save the results of a form.

If Each one of these things occurs just once in a view, then I can use the django generic views.  Unfortunately, those are not really composable, and I needed to do several things in sequence.

So I went and wrote an even more generic views library, one that worked by first building a list of actions from relevant querysets (or whatever), and then wrapped the list into a view.

I still have to write some views by hand, but these are usually complex enough that there's not much that's reusable in them.  All of the boilerplate just lands elsewhere, either a generic view, or as a view decorator (often a decorated generic view).  This typically ends up being about 10% of the handlers I write, since some generic handler can do everything else.

Title: Do you have your own 'misc utils' library? What part are you most proud of?

Body:
I know that many of us maintain our own little personal library with tools and utilities that we use often.

I've had mine since I was 16 years old so it has grown to quite a considerable size. Some of the stuff I've written has since been added to the framework. I wrote my own little implementation of expression trees for use with genetic algorithms long before LINQ, which I quite like and was proud of at the time - of course its pretty useless now. But recently I have been going through it and upgrading to .NET 4.0 and re-kindled an interest.

So I'm curious as to what you use your library for. Maybe we could get some cool ideas going for useful little snippets and share them amongst ourselves.

So my questions are:

Do you have a miscellaneous utility library?

Which part are you most proud of and why?

Give an example of code if you like :-)


问:
Why was C# made with "new" and "virtual+override" keywords unlike Java?
In Java there are no virtual, new, override keywords for method definition. So the working of a method is easy to understand. Cause if DerivedClass extends BaseClass and has a method with same name and same signature of BaseClass then the overriding will take place at run-time polymorphism (provided the method is not static).

BaseClass bcdc = new DerivedClass();
bcdc.doSomething() // will invoke DerivedClass's doSomething method.
```

<hr>

<p>Now come to C# there can be so much confusion and hard to understand how the <code>new</code> or <code>virtual+derive</code> or new + virtual override is working. </p>

<p>I'm not able to understand why in the world I'm going to add a method in my <code>DerivedClass</code> with same name and same signature as <code>BaseClass</code> and define a new behaviour but at the run-time polymorphism, the <code>BaseClass</code> method will be invoked! (which is not overriding but logically it should be). </p>

<p>In case of <code>virtual + override</code> though the logical implementation is correct, but the programmer has to think which method he should give permission to user to override at the time of coding. Which has some <em>pro-con</em> (let's not go there now).</p>

<p>So why in C# there are so much space for <em>un</em>-logical reasoning and confusion. So may I reframe my question as in which real world context should I think of use <code>virtual + override</code> instead of <code>new</code> and also use of <code>new</code> instead of <code>virtual + override</code>?</p>

<hr>

<p>After some very good answers especially from Omar, I get that C# designers gave stress more about programmers should think before they make a method, which is good and handles some rookie mistakes from Java. </p>

<p>Now I've a question in mind. As in Java if I had a code like</p>

<pre class="lang-java prettyprint-override"><code>Vehicle vehicle = new Car();
vehicle.accelerate();
</code>```

and later I make new class SpaceShip derived from Vehicle. Then I want to change all car to a SpaceShip object I just have to change single line of code

```<code>Vehicle vehicle = new SpaceShip();
vehicle.accelerate();
</code>```

This will not break any of my logic at any point of code.

But in case of C# if SpaceShip does not override the Vehicle class' accelerate and use new then the logic of my code will be broken. Isn't that a disadvantage?

答:
Standard situation:

You are the owner of a base class that is used by multiple projects. You want to make a change to said base class that will break between 1 and countless derived classes, which are in projects providing real-world value (A framework provides value at best at one remove, no Real Human Being wants a Framework, they want the thing running on the Framework). Good luck stating to the busy owners of the derived classes; "well, you have to change, you shouldn't have overridden that method" without gaining a rep as a "Framework: Delayer of Projects and Causer of Bugs" to the people who have to approve decisions.

Especially as, by not declaring it non-overridable, you've implicitly declared they were okay to do the thing that now prevents your change.

And if you don't have a significant number of derived classes providing real world value by overriding your base class, why is it a base class in the first place? Hope is a powerful motivator, but also a very good way to end up with unreferenced code.

End result: Your framework base class code becomes incredibly fragile and static, and you can't really make the necessary changes to stay current/efficient. Alternatively, your framework gets a rep for instability (derived classes keep breaking) and people won't use it at all, since the main reason to use a framework is to make coding faster and more reliable.

Simply put, you cannot ask busy project owners to delay their project in order to fix bugs that you are introducing, and expect anything better than a "go away" unless you're providing significant benefits to them, even if the original "fault" was theirs, which is at best arguable.

Better to not let them do the wrong thing in the first place, which is where "non-virtual by default" comes in. And when someone comes to you with a very clear reason why they need this particular method to be overridable, and why it should be safe, you can "unlock" it without risking breaking anyone else's code.


问:
What is the ideal length of a method for you?
In object-oriented programming, there is of course no exact rule on the maximum length of a method , but I still found these two quotes somewhat contradicting each other, so I would like to hear what you think.

In Clean Code: A Handbook of Agile Software Craftsmanship, Robert Martin says:

The first rule of functions is that they should be small. The second
  rule of functions is that they should be smaller than that. Functions
  should not be 100 lines long. Functions should hardly ever be 20 lines
  long.

and he gives an example from Java code he sees from Kent Beck:

Every function in his program was just two, or three, or four lines
  long. Each was transparently obvious. Each told a story. And each led
  you to the next in a compelling order. That’s how short your functions
  should be!

This sounds great, but on the other hand, in Code Complete, Steve McConnell says something very different:

The routine should be allowed to grow organically up to 100-200 lines,
  decades of evidence say that routines of such length no more error
  prone then shorter routines.

And he gives a reference to a study that says routines 65 lines or long are cheaper to develop.

So while there are diverging opinions about the matter, is there a functional best-practice for you?

答:
I'll just throw in yet another quote.

Programs must be written for people to read, and only incidentally for
  machines to execute

-- Harold Abelson

It is very improbable that functions that grow to 100-200 follow this rule

OwnerDisplayName: iPhoneDeveloper


问:
Is there a standard way of cleaning data files?
Having spent quite a lot of time working in software companies that deal in medium to large data sets, I've seen that a choke point in their processes is often prepping data files for loading into databases. For example, searching for formatting errors, peculiar whitespace or line-end characters, wrangling with Unicode formats, that sort of thing.

Everyone I've ever known deals with this in a bespoke manner because the requirements are so varied and often unique to the companies involved.

I normally just fiddle about in a combination of hex editors, excel, powershell and SQL to get the job done. But this is such a perennial problem that I find it hard to believe that there isn't some standards already in place to take some of the basic grunt-work out of the process.

Is there a standard technique that is tailored for the purpose of cleaning data files?

答:
This is what XML Schemas were designed to do, albeit for XML files specifically.  The overall technique is easily replicable, though.

Given a needs for data of shape, first write a file that defines shape that you can provide to your users and expect their computers to understand.

When you need to ask someone for a file of shape, give them said definition.

Once you get their file back, before you do anything else run the appropriate tool to ensure that it meets the requirements.

I begin with XML Schemas because there are several patters to choose from, many of which are either open standards or freely available.  Most of the tools you mentioned can attach an XSD file to an XML document, and both determine if the file is valid or not and specify how the file isn't.

If you don't want to use XML, the same basic process can be applied to any form of data.

If it's a relational database file, write some CREATE SCHEMA / CREATE TABLE commands.

For a flat file like a CSV or space-delimited "text" file, you could write a RegEx expression which defines each line.

A more complex data format (JSON or YAML) may have their own schema functionality, or you could write a simple test script to parse and evaluate the file.

If you're gathering data that's more or less manually combined, send an example document.  An empty Microsoft Access would be appropriate if your users are all in the Windows world.


问:
How would you know if you've written readable and easily maintainable code?
How would one know if the code one has created is easily readable, understandable, and maintainable? Of course from the author's point of view, the code is readable and maintainable, because the author wrote it and edited it, to begin with. However, there must be an objective and quantifiable standard by which our profession can measure code.

These goals are met when one may do the following with the code without the expert advice of the original author:

It is possible to read the code and understand at a basic level the flow of logic.

It is possible to understand at a deeper level what the code is doing to include inputs, outputs, and algorithms.

Other developers can make meaningful changes to the original code such as bug fixes or refactoring.

One can write new code such as a class or module that leverages the original code.

How do we quantify or measure code quality so that we know it readable, understandable, and maintainable?

答:
Without being puritanical: prefer functional style.  Most languages these days (.NET, Ruby, Python, Javascript, etc.) support and promote it (e.g. LINQ, underscorejs).

It is exceedingly easy to read.

```<code>var recentTopCustomers = OrderList
    .Where(o => o.Date >= DateTime.Now.AddDays(-5))
    .Where(o => o.Amount > 1000)
    .OrderBy(o => -o.Amount)
    .Take(10)
    .Select(o => o.Customer);
</code>```

It forces each node to have single, focused intent lending to clarity of purpose.  And because each discrete task is isolated popping out, plugging in, and rearranging nodes (operations) to different ends is trivial.  This lends to ease of maintenance.

Body:
Without being puritanical: prefer functional style.  Most languages these days (.NET, Ruby, Python, Javascript, etc.) support and promote it (e.g. LINQ, underscorejs).

It is exceedingly easy to read.

var recentTopCustomers = OrderList
    .Where(o => o.Date >= DateTime.Now.AddDays(-5))
    .Where(o => o.Amount > 1000)
    .OrderBy(o => -o.Amount)
    .Take(10)
    .Select(o => o.Customer);

It forces each node to have single, focused intent lending to clarity of purpose.  And because each discrete task is isolated popping out, plugging in, and rearranging nodes (operations) to different ends is trivial.  This lends to ease of maintenance.


问:
Sprint Planning Meetings - determine if a work item is "planned"?
We've been working with Scrum for a while now, generally successfully. However of late, as the pressure has started to mount up we've encountered several situations where items came through planning meetings but when it actually came time to code, it became apparent they were woefully under-specified.

This is an annoying and awkward waste of time. So I'm wondering, is there anything we can do to make sure that a work item is properly understood and planned before it's included in a sprint?

We don't use TDD, but my experiences with it suggest that it's a good way of ensuring a programmer understands a task before beginning work. So I did consider trying to work out some automated testing as a possible approach to this. But not all work items are amenable to automated tests, and it's likely to be difficult/boring for non-programmers in the meeting.

As an aside, out of curiosity, is when one has decided on acceptance criteria, should they go on a work item, or a user story, or both?

答:
Individuals and interactions over processes and tools

Go back to the user and ask for more clarification, details, etc. I know this isn't always possible and can be annoying to both sides, but it's better than coding in the blind. It may help both sides understand what everybody really needs to know before coding.

There are plenty of techniques to make sure you have a good story, but it still requires a little practice on both sides.

It will seem inefficient early on, but it won't waste as much time in the long-run. If you feel like you have to be perfect coming out of every single planning session, they'll never end, so take on a little risk knowing you can always go back and ask. Hopefully, there is time for these contingencies and soon they'll be the exception rather than the rule.


问:
Live search/filter as you type in client approach
As an exercise for myself to practice my JavaScript "skills" I'm trying to write a client-side filter. It should be able to filter "content blocks" as the user types.

By "content block", I mean a list of DomElements that each contain at least one text node - it is possible that they contain more, and even a different amount of text nodes, nested inside other nodes, etc.

I've thought of 2 approaches:

On page initialization, scan all nodes and store all the text in some kind of Map or a tree.

Simply iterate over every item and check whether it has the string to search/filter for. One could add performance here by caching, only filtering the current remaining items if text is added, etc.

Obviously, if the number of nodes is really big, option 1 will take a while to build the 'index' but it will perform faster once it is built. Option 2 however will be available right on page load since no initialization is performed. But of course it will take longer to search.

So my question is: what is the best approach here? And how would one implement 'caching' and/or 'index'?

答:
I believe that, a mix between both would be great.

First time it will build the index while doing the search. It will take a little more time to search, but after it will search much faster by the built indexed cache.

Thinking in the nested data situation, and considering that the search will be done a lot of times, i would make a cache not indexed, in the same tree disposition of the data, and a cache of search results.

e.g.

The result cache should be indexed by search results (less first)

User search first time for javascript, in the end of the search there will be

a list of all texts to search linearly

a result list for javascript

User search for nodejs, in the end of the search there will be

a list of all texts to search linearly

2 result list (1 for javascript and 1 for nodejs)

User search for javascript nodejs, it will search in the smallest list and, in the end of the search there will be

a list of all texts to search linearly

3 result list (1 for javascript, 1 for nodejs and 1 for javascript nodejs)


问:
How can my team avoid frequent errors after refactoring?
To give you a little background: I work for a company with roughly twelve Ruby on Rails developers (+/- interns). Remote work is common. Our product is made out of two parts: a rather fat core, and thin up to big customer projects built upon it. Customer projects usually expand the core. Overwriting of key features does not happen. I might add that the core has some rather bad parts that are in urgent need of refactorings. There are specs, but mostly for the customer projects. The worst part of the core are untested (not as it should be...).

The developers are split into two teams, working with one or two PO for each sprint. Usually, one customer project is strictly associated with one of the teams and POs.

Now our problem: Rather frequently, we break each other's stuff. Someone from Team A expands or refactors the core feature Y, causing unexpected errors for one of Team B's customer projects. Mostly, the changes are not announced over the teams, so the bugs hit almost always unexpected.  Team B, including the PO, thought about feature Y to be stable and did not test it before releasing, unaware of the changes.

How to get rid of those problems? What kind of 'announcement technique' can you recommend me?

答:
Primarily, you have a communication problem (probably also linked with a team building problem), so I think a solution to your case should be focused on... well, communication, instead of development techniques.

I take for granted that it is not possible to freeze or fork the core module when starting a customer project (otherwise then you simply need to integrate in your company schedules some non-customer-related projects that aim at updating the core module).

So we're left with the issue of trying to improve the communication between the teams. This can be addressed in two ways:

with human beings. This means that your company designates someone as the core module architect (or whatever lingo is good for the top management) who will be responsible for the quality and availability of the code. This person will incarnate the core. Thus, she will be shared by all the teams and ensure proper sync between them. Furthermore, she should also act as a reviewer of code committed to the core module to maintain its coherence;

with tools and workflows. By imposing Continuous Integration on the core, you will make the core code itself the communication medium. This will require some effort first (by the addition of automated test suites on it) but then the nightly CI reports will be a gross status update of the core module.

You can find more about CI as a communication process here.

Finally, you stil have a problem with the lack of team work at the company level.
I'm not a big fan of team building events, but this seems like a case where they would be useful.
Do you have developer-wide meetings on a regular basis ? Can you invote people from other teams to your project retrospectives ? Or perhaps have some Friday evening beer sometimes ?


问:
best practice to inter widget communication in javascript
I have quit a lot of javascript widget and I would like to have a good decoupled way to communicate between them. Something like signals and slots in QT probably? Most of my widgets are written in JQuery using widget factory.

What is the correct way to achieve that, without ending with a spaghetti code?

答:
JavaScript has a built in event system. This gives you an easy way of listening to Events and firing.

You then bind EventListeners to the things you want to listen to (click, myCustomEvent, ...)

When your widget is a pure DOM-enhancing/editing-widget. You will often add eventlisteners to the HTML the widget is enhancing.

Non related widgets could subscribe to the document object that is also a EventTarget thus it can also be used to listen to/fire events.

I tend to often use mootools, thus giving me a powerfull Events mixin in my object. No idea how this is done in jQuery :(


问:
Why is the “app” folder now a (more) common pattern in web projects?
It might be related to the Yeoman project, or they might have adopted this from somewhere else, but it seems to be the default for all of their generators. Aside from Yeoman generators I've also noticed it in other projects that have nothing to do with Yeoman (this one for example).

Where did this convention come from, and what are the reasons for using this over a src folder, for example (which used to be more common)? Or is it just random preference?

p.s.: As far as I can tell it doesn't seem to be strictly related to it being a web-app instead of a web-site (which is rather subjective anyway).

答:
I will not call it a "pattern" per se. It's only a convention that has stuck over the years with web developers. There is no benefit from naming a folder something else other than app, and vice versa.

I can only think back to Rails when thinking of the start of this convention.

I think it was a means to separate the app's source code from the cource code of the framework.boilerplate you use in supporting the app.


问:
Use of malloc in C
Is it necessary to call free function every time we use malloc in C.
I am asking this because I have seen many times that it is not called .

Thank you

答: If the object lives to the end of the program, then you don't need to call free, but I would hold that it is still good practice to do so. The reason here is that, at the end of your code's execution, all of the memory will be free'd anyway, so there's no need to do so explicitly. Otherwise, yes; use free always.

Title: Use of malloc in C


答:
Each call to malloc allocates memory on the heap and returns a pointer to it. If you do not call free on the returned pointer, the memory is not freed (so you get a memory leak).

In most trivial cases it is not really necessary to call free (i.e. the application will probably run fine without it), but most people (rightly) consider not freeing the memory a bug.

There are also cases when you allocate memory with malloc and leave it in a static or global variable, relying on the operating system to release this memory when the application finishes running. Normally you shouldn't do this. If you have need of a memory block to remain allocated as long as a library has work to do, consider adding a Finalize/Close/Finish/Uninitialize API to your library that de-allocates this memory (such an API should be called as the last call of your program into your library API).

TLDR: While in most cases it may not be strictly necessary, omitting free-ing the memory is a bug and you (probably) should avoid it (i.e. ensure you always call free for malloc-ed memory).

Title: Use of malloc in C

Body:
Is it necessary to call free function every time we use malloc in C.
I am asking this because I have seen many times that it is not called .

Thank you