答:
I was in the same boat as you for the first couple of years of my programming career. I managed to get on fine without creating my own interfaces. You cant really remove the concept entirely however as using most libraries will involve consuming interfaces. </p>

<p>I would strongly recommend spending the time to research what they are and some basic use cases. You will miss out on a lot of powerful tools such as dependency injection if you don't learn how to use them. It will also make your code more decoupled and simpler to change if you rely on interfaces rather than concrete types. </p>

Body:
I have been programming for many years but I am still not comfortable with the concept of "Interfaces". I try to use interfaces but many times I don't see a mandatory use for it. I think this is probably because the projects weren't so big, or because interfaces are more useful when teamwork is involved.

So, making another attempt to understand the importance of interfaces, here is my question:

What problems will I face if I remove the concept of interfaces from my code?

Body:
I was in the same boat as you for the first couple of years of my programming career. I managed to get on fine without creating my own interfaces. You cant really remove the concept entirely however as using most libraries will involve consuming interfaces.

I would strongly recommend spending the time to research what they are and some basic use cases. You will miss out on a lot of powerful tools such as dependency injection if you don't learn how to use them. It will also make your code more decoupled and simpler to change if you rely on interfaces rather than concrete types.


问:
Dependency Management tool for REST endpoints
I work in a Rest Oriented environment. The number of endpoints is quite large and span multiple applications. The dependencies between the endpoints are large in number as well and not very well planned. Applications have cyclic dependencies amongst each other.   Unfortunately, there is no central location where all the endpoints are documented and declare dependencies (the endpoints that they inturn call).

Is there a tool that will help in such dependency management. I tried searching for a tool online, but not know what such a thing would be called, I am unable to find anything.

答:
My own search, via "service dependency discovery", yields a very few select results.  IEEE give a couple of hits to papers that talk about SOA service dependency discovery, and perhaps you can use or adapt the described technique to fit your purpose.  Aside from that...

IBM Tivoli and a yet to be released Microsoft Orion sound by their descriptions to be up that alley, if not a bit heavyweight for what you are probably looking for.  They look to be targeted to network management for operational concerns.  These, it appears, work off live network packet inspection.

Perhaps as a kludge, analyzing and aggregating service or host log files, you might have some opportunity to 'discover' who wants and needs what without digging into the guts of each through the respective sources or various project and deployment descriptors.  Of course this presumes that the logging level of each service feels it is important enough to log those cross service requests and the log level isn't filtering those info events out of the log.

To fully understand the breadth and depth of each dependency, you'll probably need to delve into the service source.

ContentLicense: CC BY-SA 3.0


问:
What problems will I face if I remove the concept of interfaces from my code?
I have been programming for many years but I am still not comfortable with the concept of "Interfaces". I try to use interfaces but many times I don't see a mandatory use for it. I think this is probably because the projects weren't so big, or because interfaces are more useful when teamwork is involved.

So, making another attempt to understand the importance of interfaces, here is my question:

What problems will I face if I remove the concept of interfaces from my code?

答:
If you don't understand what interfaces offer then you don't understand interfaces.  So you probably won't loose much if you stop using them because it is apparent you don't use them to their fullest potential.

The three major things I would miss would be

Multiple inheritance. If I inherit from a base class in a framework to get the plumbing benefits how does the class easily tell the world it can do x? Interfaces.

Related to #1 is that I can define the behavior of the application in a component that has no dependency on anything.  You can do this with abstract classes to a point but you can run into problems pretty quick if you work with third parties, other divisions or even legacy code.

Those two things make testing new classes that rely on interfaces so much easier.

If you don't understand those three benefits (and there are others) then you either work with a language that allows true multiple inheritance and accept the problems that introduces, use scripting languages that are much more flexible or you simply do not understand what interfaces represent.


问:
How is Agile different from XP?
I read few articles on web to find out how Agile, XP, Scrum, pair programming are different from each other / related to each other and I derived the following line:

Scrum and XP are almost same. XP has shorter period of releases than Scrum

Pair programming is employed in both Agile and XP methodologies

But I was unable to identify how Agile is different from XP.

More than providing a URL, I would be happy to read your experience and thoughts on this.

答:
Agile is a class of software-development methodology, of which XP is one instance

Scrum is a project-management methodology, not a software-development methodology. While it is common to use an Agile development methodology with Scrum, it is not a requirement. They are not the same thing.

ContentLicense: CC BY-SA 2.5

Title: How is Agile different from XP?


问:
Should I write HTML or CSS first?
There are a lot of analogies for HTML/CSS development; which can be a bit confusing for a beginner.

HTML = foundations/house

CSS = walls/blueprint/wallpaper

Is there any best practice here? Which one should we write first?

答: I believe that working with the websites structure (HTML) first makes more sense as you then will have an idea of the elements and there names for when it comes to styling and formatting your website.</p>

ContentLicense: CC BY-SA 4.0

Title: Should I write HTML or CSS first?


答:
Removing interfaces from your code, whether they're done explicitly (e.g., Java's interface construct) or implicitly (e.g., a C++ abstract class), removes your ability to take advantage of some forms of inheritance.  (I say "some forms" because in general terms, interfaces are equivalent to abstract classes but are treated differently by different languages.)

Take this example, written in no particular language:

```<code>class Juice { ... };  // Represents any kind of juice.

interface Fruit {
    Boolean is_edible();
    Juice   make_juice();
};

class Apple implements Fruit {
    Boolean is_edible() { return true; }
    Juice make_juice() { ... ; return juice; }
}

class Banana implements Fruit {
    Boolean is_edible() { return true; }
    Juice make_juice() { ... ; return juice; }
}

// Processes and accumulates the juices of many fruits.
class Juicer {
    Vector<Juice> accumulated_juice;  // Where all the juice goes

    // Process a Fruit for consumption.  Complain if it's
    // not an edible fruit.
    Void process(Fruit f) {
      if ( ! f.is_edible() ) throw_exception;
      accumulated_juice.add(f.make_juice());
    }
}
</code>```

This is pretty straightforward.  The Juicer can process() any Fruit you hand it because the interface guarantees that:

There's an is_edible() method determine if the Fruit is edible

There's a make_juice() method to produce the juice

You can develop a Kumquat or a Mango or a StarFruit and you'll never have to modify the Juicer to understand them.  Juice is juice.

If you remove interfaces, all of that simplicity goes away:

```<code>// Assume same class declarations as above without "implements xxx" clause.

class Juicer {
    Vector<Juice> accumulated_juice;  // Where all the juice goes

    // Process a Fruit for consumption.  Complain if it's
    // not an edible fruit.
    Void process_apple(Apple a) {
        if ( ! a.is_edible() ) throw_exception;
        accumulated_juice.add(a.make_juice());
    }
    Void process_banana(Banana b) {
        if ( ! b.is_edible() ) throw_exception;
        accumulated_juice.add(b.make_juice());
    }
    // Add methods for additional fruits here.
}
</code>```

All of the process_xxx() methods are identical except for what type they take as an argument.  Even though Apple and Banana have methods called is_edible() and make_juice() with identical signatures, the language won't just let you call them by name because they're part of different classes.  This means your Juicer has to have more code added every time you develop a new fruit.

Once this grows to more than these few classes, it becomes a maintenance nightmare if you need to make changes to how the process() method works internally.  Further, any other code that handles your fruits has to have all of this additional code

HTH.

Title: What problems will I face if I remove the concept of interfaces from my code?

Body:
Removing interfaces from your code, whether they're done explicitly (e.g., Java's interface construct) or implicitly (e.g., a C++ abstract class), removes your ability to take advantage of some forms of inheritance.  (I say "some forms" because in general terms, interfaces are equivalent to abstract classes but are treated differently by different languages.)

Take this example, written in no particular language:

class Juice { ... };  // Represents any kind of juice.

interface Fruit {
    Boolean is_edible();
    Juice   make_juice();
};

class Apple implements Fruit {
    Boolean is_edible() { return true; }
    Juice make_juice() { ... ; return juice; }
}

class Banana implements Fruit {
    Boolean is_edible() { return true; }
    Juice make_juice() { ... ; return juice; }
}

// Processes and accumulates the juices of many fruits.
class Juicer {
    Vector<Juice> accumulated_juice;  // Where all the juice goes

    // Process a Fruit for consumption.  Complain if it's
    // not an edible fruit.
    Void process(Fruit f) {
      if ( ! f.is_edible() ) throw_exception;
      accumulated_juice.add(f.make_juice());
    }
}

This is pretty straightforward.  The Juicer can process() any Fruit you hand it because the interface guarantees that:

There's an is_edible() method determine if the Fruit is edible

There's a make_juice() method to produce the juice

You can develop a Kumquat or a Mango or a StarFruit and you'll never have to modify the Juicer to understand them.  Juice is juice.

If you remove interfaces, all of that simplicity goes away:

// Assume same class declarations as above without "implements xxx" clause.

class Juicer {
    Vector<Juice> accumulated_juice;  // Where all the juice goes

    // Process a Fruit for consumption.  Complain if it's
    // not an edible fruit.
    Void process_apple(Apple a) {
        if ( ! a.is_edible() ) throw_exception;
        accumulated_juice.add(a.make_juice());
    }
    Void process_banana(Banana b) {
        if ( ! b.is_edible() ) throw_exception;
        accumulated_juice.add(b.make_juice());
    }
    // Add methods for additional fruits here.
}

All of the process_xxx() methods are identical except for what type they take as an argument.  Even though Apple and Banana have methods called is_edible() and make_juice() with identical signatures, the language won't just let you call them by name because they're part of different classes.  This means your Juicer has to have more code added every time you develop a new fruit.

Once this grows to more than these few classes, it becomes a maintenance nightmare if you need to make changes to how the process() method works internally.  Further, any other code that handles your fruits has to have all of this additional code

HTH.


问:
Should I use a config file or database for storing business rules?
I have recently been reading The Pragmatic Programmer which states that:

Details mess up our pristine code—especially if they change frequently. Every time we have to go in and change the code to accommodate some change in business logic, or in the law, or in management's personal tastes of the day, we run the risk of breaking the system—of introducing a new bug.

Hunt, Andrew; Thomas, David (1999-10-20). The Pragmatic Programmer: From Journeyman to Master (Kindle Locations 2651-2653). Pearson Education (USA). Kindle Edition.

I am currently programming a web app that has some models that have properties that can only be from a set of values, e.g. (not actual example as the web app data confidential):

light->type = sphere / cube / cylinder

The light type can only be the above three values but according to TPP I should always code as if they could change and place their values in a config file. As there are several incidents of this throughout the app, my question is:

Should I store possibly values like these in:

a config file:

'light-types' => array(sphere, cube, cylinder),

'other-type' => value,

'etc' => etc-value

a single table in a database with one line for each config item

a database with a table for each config item (e.g. table: light_types; columns: id, name)

some other way?

Many thanks for any assistance / expertise offered.

答:
If your data will be in a database, i'd recommend having a table of 'light_types' in the same DB.  This gives you the ability to use foreign keys to enforce a constraint that light->type can only be one of those values, so even if the code messes up, the data in the DB will always be valid.

If the data won't be stored in a DB, creating one just for a bunch of enums doesn't do a whole lot of good.  I might recommend a config file, if you really want to avoid hard-coding the values.

(I'd warn against going too far in avoiding hard-coding, though.  In any non-trivial system, there will be assumptions about business rules and requirements, whether the authors realize it or not.  Even if you somehow manage to avoid all assumptions and soft-code absolutely everything, you basically just end up with a "rules engine", a sort of system-within-a-system and/or meta-language, and you have a bunch of stuff in the meta-language to implement the rules.  You haven't saved any work or gained any flexibility; you've just had to build and/or learn another language.

Now, if you want to find and use an existing rules engine, that might save you a bit of work (along with answering the question of where to store enums).  But building your own just doubles the workload and inevitably gets you a half-assed system built by people who really don't know how to make a decent rules engine.)


答:
In general a database should be used for data and a config file should be used for configuration. (as the name suggests :) ). Keeping configuration in the database is bad separation of concerns and should only be done if you have a good use case to justify it.

There is a balance to be struck when deciding how much configuration to use. You should treat your config files as much as a part of an application as the code. Keep it as terse as possible. Its very easy for applications to suffer from configuration bloat where you end up with a huge xml file full of magic strings.

In the case you describe it would be reasonable to have a configuration element to define which css file to use. (you could then just change it if requirements change).  It would be overkill to configure the style of each element in the config file

Title: Should I use a config file or database for storing business rules?

Body:
I have recently been reading The Pragmatic Programmer which states that:

Details mess up our pristine code—especially if they change frequently. Every time we have to go in and change the code to accommodate some change in business logic, or in the law, or in management's personal tastes of the day, we run the risk of breaking the system—of introducing a new bug.

Hunt, Andrew; Thomas, David (1999-10-20). The Pragmatic Programmer: From Journeyman to Master (Kindle Locations 2651-2653). Pearson Education (USA). Kindle Edition.

I am currently programming a web app that has some models that have properties that can only be from a set of values, e.g. (not actual example as the web app data confidential):

light->type = sphere / cube / cylinder

The light type can only be the above three values but according to TPP I should always code as if they could change and place their values in a config file. As there are several incidents of this throughout the app, my question is:

Should I store possibly values like these in:

a config file:

'light-types' => array(sphere, cube, cylinder),

'other-type' => value,

'etc' => etc-value

a single table in a database with one line for each config item

a database with a table for each config item (e.g. table: light_types; columns: id, name)

some other way?

Many thanks for any assistance / expertise offered.


答:
You've picked a really poor framing for learning and building.

There are two orthogonal issues at hand here.

How do i build a site that serves my needs?

How do i learn to build a website?

Those are two very different tasks can (and often do) require different potentially conflicting approaches.

If you are familiar with the skills, technologies, and requirements of a project, one starts with a discussion about the needs of a site, and go through design exercises in order to determine what it is that needs to be implemented. That often means markups and design stuff, which will often have nothing to do with either HTML or CSS (although some people do mockup with HTML & CSS).

If you are trying to learn how to build a site, while also building a site, there is a process of exploration and learning that you must engage in before you know what is even possible to build.

This is where a modular and iterative design and build strategy has become popular. When you don't necessarily know where you're going with your end product (because you don't know what's possible), you build small chunks of functionality, experiment with whether it meets your requirements, and then incorporate that smaller experiment into the larger whole.

So, what does that actually mean in concrete terms? Building a site can be like building a house, where you draw up architectural plans (design mockups) and then start doing the engineering to calculate whether your house will stand up and meet your aesthetic needs. But building a site can (and often should) look more like building a series of small experiments, and taking a step by step approach to reaching a product that meets your original concept.

As a very practical matter, almost everyone futzes with both their HTML and their CSS at the same time.

Title: Should I write HTML or CSS first?

Body:
There are a lot of analogies for HTML/CSS development; which can be a bit confusing for a beginner.

HTML = foundations/house

CSS = walls/blueprint/wallpaper

Is there any best practice here? Which one should we write first?


答:
The same question arises in most of the projects I work on. Usually, I do this:

If the set of possible values is unlikely to change any time soon, I use class/interface constants or enums in the code and enumerable fields in the database. Example: state of publishing of blog entries: 'not published', 'under moderation', 'published', etc.

Values will probably change, but changes will not affect program logic - config files. Example: list of "how did you find our website?" options for a dropdown list in online purchasing form.

Values are likely to change frequently and/or meant to be edited by non-developers, but yet these changes will not affect the logic - a database or at least a key-value storage with some user-friendly interface for editing.

Changing the values will affect the logic - probably the system needs redesign (often true) or some business rules engine is needed. The most difficult case I've seen so far was psychological tests constructor my colleague worked on. Each type of test may have its own scoring system which may vary from simple addition to multiple characteristics scales with positive and negative values or even human evaluation of answers. After some discussion about this project, we ended up using Lua as a scripting engine, which totally conflicts with the ability of non-developers to create new tests (even though Lua is a relatively simple language you shouldn't expect that a non-programmer will learn it).

About the quote from TPP. I think it's true for pristine code, but in real life, you better start simple (KISS principle) and add features later if they're really needed (YAGNI).


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

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

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

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

For example:

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

答:
Memory-as-a-Grid Diagram

Usually what I do is represent memory as a "grid", so that I can make up addresses, highlight different memory spaces and write in the cells values (or even further, their binary representations) and link the pointers in memory to the values they point at.
(And then still mention that it's a simplification).

Usually it's a "ohhhh" moment for most of my students.

Symbol Juggling

Then when it comes to have them stop forgetting how to use & and *, it's very simple: present it the same way they do math or physics calculations. If you divide a distance in km by a time in hour, you get a speed in km/h. What's in needs to be out. Simple.

printf to the Rescue

Doing just a few basic examples that visually represent what you explained with these will comfort them in what they think they understood, or give them the opportunity to say "ah, I don't get this one".

Be Extensive

Cover pointers for simple types and make sure they understand the difference between addressing and the size of a data type, then structs, then arrays, and multiple levels.

Then start pointer arithmetic.

Addendum: Recursion

I usually explain recursion similarly, using a visual representation.
Have them print the alphabet using a pre-made function that writes a single char, and then ask them to print it in reverse order by just changing two lines.

Usually there's a "what the...?" moment, and when you add just another parameter to your printf to print numeric values and indent the steps, it becomes a sigh of relief.

Alternatives: The Play-Doh Model and the Water Cups

I actually had some co-workers in a university who showed students a video explaining pointers and memory accesses using play-doh paste. It was incredibly clever and well done, though I never really used that technique myself, except for very young learners interested in grasping programming (but usually those I wouldn't lead them towards a language using pointers too early). Basically using tiny balls of play-doh which you can attach to other bigger balls of play-doh representing memory spaces, and that you can combine together to either link them (like in a linked data structure) or merge together (as in a contiguous memory space). Using different colors for the memory spaces pointed to and the pointers help as well. But I still think the Memory-as-a-Grid thing works better, as you can clearly show that the pointing is really a matter of "addressing", as on a "map/grid". Whereas the Play-doh mode still confuses them into thinking that things really "touch" each other in memory.

The Water Cup thing was used directly by a colleague as well, but I don't know if she came up with it. It was an interesting approach, but I noticed many students were left puzzled by the explanation. Something alike to DevSolo's Coffee Cup technique. But I think it's actually a misleading one as you make the students confuse containers, data structures, pointers and arrays. It might be an interesting approach to explain arrays at the beginning I assume, but I wouldn't stick to it very long.

Title: What's a nice explanation for pointers?


问:
What are the downsides of leaving automation tags in production code?
I've been setting up debug tags for automated testing of a GWT-based web application. This involves turning on custom debug id tags/attributes for elements in the source of the app. It's a non-trivial task, particularly for larger, more complex web applications. Recently there's been some discussion of whether enabling such debug ids is a good idea to do across the board.

Currently the debug ids are only turned on in development and testing servers, not in production. There have been points raised that enabling debug ids does cause performance to take a hit, and that debug ids in production may lead to security issues.

What are benefits of doing this? Are there any significant risks for turning on debug tags in production code?

答:
Those flags should really only be turned on in DEV but it seems like you are using QA as your build integration instance. PRD absolutely not. If there is an issue with PRD you need to restore it down to QA, if you have a project ongoing thats using QA then you build another set of instances.

I have to fight tooth an nail about this with most clients but segregation and proper promotion polices need to be put in place from the start. QA is intended to be a real world assessment of your dev assets with full data capabilities. DEV environments are disposable and PRD goes untouched.

You should never be modifying PRD directly unless an impact/downtime assessment has been done and its been approved. The best way to answer your own question would be to restore PRD into a similar environment and start running performance tests against it.

However its unlikely if debug flags are causing noticeable delays - its more likely the hardware those environments are sitting on may be underpowered or over burdened.


答:
This is the common problem in any software development project imho and as such you could benefit from using any of the concepts such as Rapid Prototyping, DSDM. Combinable with any style e.g. agile (extreme programming or Feature Driven Design (my favourite)). Sticking to common principles that you decide at the beginning as you face them, and hang on to them (KISS, YAGNI).

So for me it is:
- build a basic functional 'prototype' first, covering one functional block of the demand
 Restrict yourself from diving into 'this might be nice'/ 'i may need to reuse this later' things unless they are OBVIOUS. Tell yourself, you aren't gonna need it! (YAGNI).
- Write down decisions you make as a 'coding convention' and stick to them
 e.g. php tags: I use short ones because for my scenario argument .. applies and ... does not.
- add basic styling but restrict yourself again.

Then expand your code until you reach a higher-level prototype which covers more functional blocks. In line with it, make your css model grow. As soon as you face decisions that affect all you already did (you will), read up on it, make a decision and write down in your coding conventions why you went left or right.

'Circle' your way towards a more mature and final product.

Don't be afraid about the big decisions you may be facing, because worrying about them may cost you more time than fixing it down the road.
Also, don't worry about the internet community looking over your shoulder with a frown, in the end when you have a product that works, you have learned a lot, and the imaginative judge of bad source code is going to be pleased more by the next thing you build (notice the iteration here).

Just my 50cts

Title: Should I write HTML or CSS first?


问:
License for available for free, but closed source web app
Anyone know of a free license that offers the user the right to use the software freely, but not modify it or share it?

In other words, it is closed source, but it's free. And since it's gonna be a website it can only be used on this one website.

What would be a good simply license for this? If possible that it's not too long, simple as the MIT license for example.

答:
There is no free software license that forbids modification or redistribution, since the software would not be free / open source software.

So, just do an “All Rights Reserved”, or get a lawer for further fine-tuning.


答:
I found several example freeware licenses with a simple search.  Excerpting:

You may

install and use any or all Product Elements included in the Product, as specified in the individual Terms of Use or License for each Product Element;

copy the Product, provided that such copies contain all the original Product's contents and proprietary notices. You may collect a reimbursement for the costs of producing the copy, but you may not charge a licensing fee for the Product;

place the Product or any Product Element on the Internet or any other public access network as long as you also acknowledge SIL and place a link back to the SIL product web page (if available);

permit other individuals to use the Product under the terms listed above.

You may not

extract portions of a Product Element not permitted by the Terms of Use or Licenses for the Product Element;

sell licenses for the Product;

include the Product or any Product Element in any other collection or other product;

remove any proprietary notices on the Product or on any Product Element.

From SIL.

Freeware

You may use the SOFTWARE without charge. We may place announcement of other products into SOFTWARE. Intelligent-Digital.com will not monitor the content of your use (e.g., sites selected or files used).

...

RESTRICTIONS

3.1 You may not reverse engineer, de-compile, or disassemble the SOFTWARE.

3.2 You may not rent, lease, or lend the SOFTWARE.

3.3 You may permanently transfer all of your rights under this EULA, provided the recipient agrees to the terms of this EULA.

3.4 You may not use the SOFTWARE to perform any unauthorized transfer of information or for any illegal purpose.

From Intelligent-digital.com.

YOU MAY:
  1. Install and use an unlimited number of copies for personal  use.

YOU MAY NOT:
  1. Sell Starz or any portion of it.
  2. Decompile, disassemble, reverse engineer or modify the Starz executable or any portion of it.
  3. Distribute Starz in any form.

From ayretek.

Title: License for available for free, but closed source web app

Body:
Anyone know of a free license that offers the user the right to use the software freely, but not modify it or share it?

In other words, it is closed source, but it's free. And since it's gonna be a website it can only be used on this one website.

What would be a good simply license for this? If possible that it's not too long, simple as the MIT license for example.


问:
Why is multithreading often preferred for improving performance?
I have a question, it's about why programmers seems to love concurrency and multi-threaded programs in general.

I'm considering 2 main approaches here:

an async approach basically based on signals, or just an async approach as called by many papers and languages like the new C# 5.0 for example, and a "companion thread" that manages the policy of your pipeline

a concurrent approach or multi-threading approach

I will just say that I'm thinking about the hardware here and the worst case scenario, and I have tested this 2 paradigms myself, the async paradigm is a winner at the point that I don't get why people 90% of the time talk about multi-threading when they want to speed up things or make a good use of their resources.

I have tested multi-threaded programs and async program on an old machine with an Intel quad-core that doesn't offer a memory controller inside the CPU, the memory is managed entirely by the motherboard, well in this case performances are horrible with a multi-threaded application, even a relatively low number of threads like 3-4-5 can be a problem, the application is unresponsive and is just slow and unpleasant.

A good async approach is, on the other hand, probably not faster but it's not worst either, my application just waits for the result and doesn't hangs, it's responsive and there is a much better scaling going on.

I have also discovered that a context change in the threading world it's not that cheap in real world scenario, it's in fact quite expensive especially when you have more than 2 threads that need to cycle and swap among each other to be computed.

On modern CPUs the situation it's not really that different, the memory controller it's integrated but my point is that an x86 CPUs is basically a serial machine and the memory controller works the same way as with the old machine with an external memory controller on the motherboard. The context switch is still a relevant cost in my application and the fact that the memory controller it's integrated or that the newer CPU have more than 2 core it's not bargain for me.

For what i have experienced the concurrent approach is good in theory but not that good in practice, with the memory model imposed by the hardware, it's hard to make a good use of this paradigm, also it introduces a lot of issues ranging from the use of my data structures to the join of multiple threads.

Also both paradigms do not offer any security abut when the task or the job will be done in a certain point in time, making them really similar from a functional point of view.

According to the X86 memory model, why the majority of people suggest to use concurrency with C++ and not just an async approach ? Also why not considering the worst case scenario of a computer where the context switch is probably more expensive than the computation itself ?

答:
Microsoft's asynchronous approach is a good substitue for the most common of the purposes for multithreaded programming: improving responsiveness with respect to IO tasks.

However, it's important to realize that the asynchronous approach is not capable of improving performance at all, or improving responsiveness with respect to CPU intensive tasks.

Multithreading for Responsiveness

Multithreading for responsiveness is the traditional way to keep a program responsive during heavy IO tasks or heavy computation tasks. You save files on a background thread, so that the user can continue their work, without having to wait for the hard drive to finish its task. The IO thread often blocks waiting for some portion of a write to finish, so context switches are frequent.

Similarly, when performing a complex calculation, you want to allow regular context switching so the UI can remain responsive, and the user doesn't think the program has crashed.

The goal here is not, in general, to get the multiple threads to run on different CPUs. Instead, we're just interested in getting context switches to happen between the long-running background task and the UI, so that the UI is able to update and respond to the user while the background task is running. In general, the UI won't take up much CPU power, and the threading framework or OS will usually decide to run them on the same CPU.

We actually lose overall performance due to the extra cost of context switching, but we don't care because performance of the CPU wasn't our goal. We know that we usually have more CPU power than we need, and so our goal with regard to multithreading is to get a task done for the user without wasting the user's time.

The "Asynchronous" Alternative

The "asynchronous approach" changes this picture by enabling context switches within a single thread. This guarantees that all of our tasks will run on a single CPU, and may provide some modest performance improvements in terms of less thread creation/cleanup and fewer real context switches between threads.

Instead of creating a new thread to await the receipt of a network resource (e.g. downloading an image), an async method is used, which awaits the image becoming available, and, in the meantime, yields to the calling method.

The main advantage here is that you don't have to worry about threading issues like avoiding deadlock, as you aren't using locks and synchronization at all, and there's a bit less work for the programmer setting up the background thread, and getting back on the UI thread when the result comes back in order to update the UI safely.

I haven't looked too deeply into the technical details, but my impression is that managing the download with occasional light CPU activity becomes a task not for a separate thread, but rather something more like a task on the UI event queue, and when the download completes, the asynchronous method is resumed from that event queue. In other words, await means something akin to "check whether the result I need is available, if not, put me back in this thread's task queue".

Note that this approach would not solve the problem of a CPU-intensive task: there's no data to await, so we can't get the context switches we need to happen without creating an actual background worker thread. Of course, it might still be convenient to use an asynchronous method to start the background thread and return the result, in a program that pervasively uses the asynchronous approach.

Multithreading for Performance

Since you talk about "performance", I'd also like to discuss how multithreading can be used for performance gains, something that's entirely impossible with the single-threaded asynchronous approach.

When you're actually in a situation where you don't have enough CPU power on a single CPU, and want to use multithreading for performance, it's actually often difficult to do. On the other hand, if one CPU isn't enough processing power, it's also often the only solution that could enable your program to do what you'd like to accomplish in a reasonable timeframe, which is what makes the work worthwhile.

Trivial Parallelism

Of course, sometimes it can be easy to get real speedup from multithreading.

If you happen to have a large number of independent computation-intensive tasks (that is, tasks whose input and output data are very small with respect to the calculations that must be performed to determine the result), then you can often get significant speedup by creating a pool of threads (sized appropriately based on the number of available CPUs), and having a master thread distribute the work and collect the results.

Practical Multithreading for Performance

I don't want to put myself forward as too much of an expert, but my impression is that, in general, most practical multithreading for performance that happens these days is looking for places in an application that have trivial parallelism, and using multiple threads to reap the benefits.

As with any optimization, it's usually better to optimize after you've profiled your program's performance, and identified the hot spots: it's easy to slow down a program by deciding arbitrarily that this part should run in one thread and that part in another, without first determining whether both parts are taking up a significant portion of CPU time.

An extra thread means more setup/teardown costs, and either more context switches or more inter-CPU communication costs. If it's not doing enough work to make up for those costs if on a separate CPU, and doesn't need to be a separate thread for responsiveness reasons, it will slow things down for no benefit.

Look for tasks that have few interdependencies, and that are taking up a significant portion of the runtime of your program.

If they have no interdependencies, then it's a case of trivial parallelism, you can easily set up each with a thread and enjoy the benefits.

If you can find tasks with limited interdependence, so that locking and synchronization to exchange information doesn't slow them down significantly, then multithreading can give some speedup, provided you're careful to avoid the dangers of deadlock due to faulty logic when synchronizing or incorrect results due to not synchronizing when it's necessary.

Alternatively, some of the more common applications for multithreading aren't (in a sense) looking for speedup of a predetermined algorithm, but instead for a larger budget for the algorithm they're planning to write: if you're writing a game engine, and your AI has to make a decision within your frame rate, you can often give your AI a bigger CPU cycle budget if you can give it its own CPU.

However, be sure to profile the threads and ensure that they're doing enough work to make up for the cost at some point.

Parallel Algorithms

There are also a lot of problems that can be sped up using multiple processors, but that are too monolithic to simply split between CPUs.

Parallel algorithms have to be carefully analyzed for their big-O runtimes with respect to the best available non-parallel algorithm, as it's very easy for the inter-CPU communication cost to eliminate any benefits from using multiple CPUs. In general, they must use less inter-CPU communication (in big-O terms) than they use calculations on each CPU.

At the moment, it's still largely a space for academic research, in part because of the complex analysis required, in part because trivial parallelism is quite common, in part because we don't yet have so many CPU cores on our computers that problems which can't be solved in a reasonable time frame on one CPU could be solved in a reasonable time frame using all of our CPUs.


问:
Desktop application, dependency injection
I am thinking of applying a real dependency injection library to my toy C#/GTK# desktop application. I chose NInject, but I think this is irrelevant to my question.

There is a database object, a main window and several utility window classes. It's clear that I can inject the database into every window object, so here DI is useful. But does it make sense to inject utility window classes into other window classes?

Example: I have classes such as:

```<code>class MainWindow {…}
class AddItemWindow {…}
class AddAttachmentWindow {…}
class BrowseItemsWindow {…}
class QueryBuilderWindow {…}
class QueryBrowserWindow {…}
class PreferencesWindow {…}
…
</code>```

Each of the utility classes can be opened from MainWindow. Some utility windows can also be opened from other utility windows. Generally, there might be a really complex graph of who can open whom. So each of those classes might need quite a lot of other window classes injected. I'm worried that such usage will go against the suggestion not to inject too many classes at once and become a code smell. Should I use some kind of a service locator object here?

答: I'd suggest a UtilityWindowOpener class. Its methods will open the various utility windows. Then you can just inject a UtilityWindowOpener anywhere you may need to open a utility window. The UtilityWindowOpener will then have the various utility windows injected (or possibly create them on demand, that's hidden behind the interface). It'll also bring all navigation logic into fewer locations.


问:
Is Extreme Programming (XP) the best way of learning from experts?
I have been involved in many development models, and have found XP to be the best for a new programmer from the aspect of learning, as the collaboration between the team members is very high and the opportunities to share knowledge are great.

What are the expert opinions on this?

答: I would say that listening and watching closely is the best way of learning from experts. You can do this without XP. You can even do it when they don't know you're doing it.


答:
To avoid overinjection instead of injecting all Window's objects of classes *Window into MainWindow you could use Ninject.Extension.Factory. In this case Abstract Factory could has following interface:

```<code>public interface IWindowFactory
{
    AddItemWindow CreateAddItemWindow();
    AddAttachmentWindow CreateAddAttachmentWindow();
    /* etc */
}
</code>```

And then add binding to Load implementation of Ninject.NinjectModule:

```<code>Bind<AddItemWindow>()
    .ToSelf()
    .NamedLikeFactoryMethod<AddItemWindow, IWindowFactory>(f => f.CreateIWindowFactory());

Bind<AddAttachmentWindow>()
    .ToSelf()
    .NamedLikeFactoryMethod<AddItemWindow, IWindowFactory>(f => f.CreateIWindowFactory());

/* etc */

// and factory binding
Bind<IWindowFactory>()
    .ToFactory()
    .InSingletonScope();
</code>```

Two additional points:

There is an excelent article by Mark Seemann Pattern Recognition: Abstract Factory or Service Locator? — so this solution is ok, if you care about Serice Locator anti-pattern, and …

To make it 100% not the Serice Locator anti-pattern make sure that Abstract Factory creates only Windows objects, not everything.

Title: Desktop application, dependency injection

Body:
I am thinking of applying a real dependency injection library to my toy C#/GTK# desktop application. I chose NInject, but I think this is irrelevant to my question.

There is a database object, a main window and several utility window classes. It's clear that I can inject the database into every window object, so here DI is useful. But does it make sense to inject utility window classes into other window classes?

Example: I have classes such as:

```<code>class MainWindow {…}
class AddItemWindow {…}
class AddAttachmentWindow {…}
class BrowseItemsWindow {…}
class QueryBuilderWindow {…}
class QueryBrowserWindow {…}
class PreferencesWindow {…}
…
</code>```

Each of the utility classes can be opened from MainWindow. Some utility windows can also be opened from other utility windows. Generally, there might be a really complex graph of who can open whom. So each of those classes might need quite a lot of other window classes injected. I'm worried that such usage will go against the suggestion not to inject too many classes at once and become a code smell. Should I use some kind of a service locator object here?

Body:
To avoid overinjection instead of injecting all Window's objects of classes *Window into MainWindow you could use Ninject.Extension.Factory. In this case Abstract Factory could has following interface:

public interface IWindowFactory
{
    AddItemWindow CreateAddItemWindow();
    AddAttachmentWindow CreateAddAttachmentWindow();
    /* etc */
}

And then add binding to Load implementation of Ninject.NinjectModule:

Bind<AddItemWindow>()
    .ToSelf()
    .NamedLikeFactoryMethod<AddItemWindow, IWindowFactory>(f => f.CreateIWindowFactory());

Bind<AddAttachmentWindow>()
    .ToSelf()
    .NamedLikeFactoryMethod<AddItemWindow, IWindowFactory>(f => f.CreateIWindowFactory());

/* etc */

// and factory binding
Bind<IWindowFactory>()
    .ToFactory()
    .InSingletonScope();

Two additional points:

There is an excelent article by Mark Seemann Pattern Recognition: Abstract Factory or Service Locator? — so this solution is ok, if you care about Serice Locator anti-pattern, and …

To make it 100% not the Serice Locator anti-pattern make sure that Abstract Factory creates only Windows objects, not everything.


问:
Java-style package naming and second-level country domains
I own a .co.uk domain, and I whenever I've dealt with Java-style package naming, I've gone with uk.co.domainname. Once I encountered package that did the following: co.uk.domainname.

Is one of these right, or is it something that's up to the developer's discretion? Is there some sort of convention that deals with this?

答:
There's no real rule here, just the conventions that Sun created with the com.sun.* packagers.  The only real requirement is uniqueness and that the co.uk... convention defines a folder/file structure.

What will be the decider in your case is what name you want for a 'root' folder - 'uk' or 'co'?


问:
What are some non-MS languages that can write xlsx (Excel 2007+) documents efficiently?
Unfortunately, Excel format is required for the project I am working on. I have no problems getting the data I need in objects and arrays, and currently PHPExcel is doing handling the document generation. It works, but it's slow and loopy. Was wondering if there is a more efficient server language to generate Excel documents (not CSVs).

This is a pure Linux environment so I need to stay away from .NET. I am open to any programming language that does it cleanly and efficiently.

答:
Try Perl's Spreadsheet::WriteExcel. The Developer, John McNamara, sometimes hangs out on stackoverflow.com.

I'm using the module for my own projects, it's really fast even for large files > 65000 rows. You cannot open pre-existing files and update data. You must start out with an empty XLSX file that you can fill up with data and/or formulas.  You can append data from many files as long the newly created file is  open in-memory.
(I have never tried to embed OLE documents and more complex objects in the XLSX files, though )


问:
Is the copy/paste approach professionally viable when working with the Google Maps API?

	I find that I understand much of the Javascript concepts used in the Google Maps API code, but then again there is quite a bit that is way over my head in syntax.

For example, the geocoder syntax seems to be of Ajax form, though I don't understand what is happening under the hood (especially with lines like results[0].geometry.location). I am able to modify the body of if (status == google.maps.GeocoderStatus.OK) for different purposes though.

	So, being that I am able to take various code from the Developer's Guide and rework it to an extent for my own purposes, all the while not fully understanding what Google Maps is actually doing, does this make me a copy-paste programmer?

	Is this a bad practice, or is this professionally viable? I am, of course, interested in learning as much as I can, but what if time-constraints outweigh the learning process?

答:
I wouldn't be concerned.  When using an API there are different modes or reasons in using the API - all of them geared at helping developers complete their task in using the API.  Google provides documentation for just this purpose - to use the tool in the way that you need.

Web APIs can also be a special case of publishers providing the 'boilerplate', letting you focus on the task rather than digging into the API design, etc.


答:
What problems will I face if I remove the concept of interfaces from my code?

What you will get is the tight coupling of your system.
As the saying goes "In pursuit of code quality: Beware the tight couple!"

What is tight coupled software system?

You probably have at least heard the term coupling used in the context of object-oriented programming. Coupling refers to the interrelationship(s) of components (or objects) in an application. A loosely coupled application is more modularized than a tightly coupled one. Its components rely on interfaces and abstract classes as opposed to concrete ones, as they would in a tightly coupled system. In a loosely coupled system, components are interrelated using abstractions instead of implementations.

A common schema of tightly coupled software system (GUI and DB without abstraction layer in between)

The GUI's dependence on an implementation rather than an abstraction limits the system. You cannot operate the GUI without having the database up and running. This design doesn't seem so bad from a functional standpoint -- we've been writing apps like this for years and planes aren't falling out of the sky, after all -- but testing it is another story.

OK, how to tight coupling? - will Interfaces do the trick? - Turn the coupling to be loose!

The GUI in above software system relies on an abstraction - a data access object or DAO. The DAO's implementation is directly dependent on the database, but the GUI itself is not entangled. Adding an abstraction in the form of a DAO decouples the database implementation from the GUI implementation. In place of the database, an interface is now coupled to the GUI code.

In conclusion - One thing developers have come to agree on is that well-written code is maintainable, and the Dependency Inversion Principle is a sure way to design for maintainability. Dependency inversion stresses reliance on abstractions over implementations, which creates a great deal of flexibility within a code base. Applying this technique with the help of a DAO, ensures that not only will you be able to modify your code base when you need to, but so will other developers.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Computers are useless.  They can only give you answers.

    — Pablo Picasso

LastEditorDisplayName: Roger Pate

OwnerDisplayName: Roger Pate


问:
How do people read big technical books?
I see that most of the good programmers have the habit of reading big books for learning about technology.

What does it really take to read technical books, apart from the real interest on the technology?

How can I improve my ability to read these books?

答:
The following is how it usually happens in my case.

"X tech sounds really cool where can I learn more"
I then google said tech absorbing as much as possible, I try to if possible to produce a small scale effort at using the new hype.
If I am still interested I buy a good book on the subject, most recently for me it is a foray into WCF.

In order to read it I keep my book of choice (usually the most recent purchase I have made) handy for my private time in the bathroom away from kids and distractions. Takes me longer to read it this way but at least I get through them.

Title: How do people read big technical books?


问:
Are there bots that download new iOS apps without being asked?
I noticed on the first day my iOS app hit the app store I got a download from Albania and another one from China.   The app is only useful to a specific group, all of which are in a certain U.S. city.  Are there bots that automatically download every new app?  If so, to what end?</p>

答:
Many developers suspect that there exist people who download and run apps from the iOS app store without reading (or be able to read the language of) the apps description.  Tire kickers perhaps.

Some bots may be collecting icon artwork or other bundle assets.


问:
Is jQuery an example of "god object" antipattern?
I want to ask – I am slowly learning jQuery.

What I see is an exact example of a God Object anti-pattern. Basically, everything goes to the $ function, whatever it is.

Am I right and is jQuery really an example of this anti-pattern?

答: No - the <code>$</code> function is actually only overloaded for three tasks. Everything else are child functions that just use it as a namespace. </p>

Body: No - the $ function is actually only overloaded for three tasks. Everything else are child functions that just use it as a namespace.


答:
http://www.creativecommons.org is a nice simple way to build a license.  It has a short and simple version (i.e. layman version) and a lengthier legal version of each license.

You just pick things like "yes/no - people can modify my work", etc.


答:
The main jQuery function (e.g. $("div a")) is essentially a factory method that returns an instance of the jQuery type that represents a collection of DOM elements.

These instances of the jQuery type have a large number of DOM manipulation methods available which operate on the DOM elements represented by the instance. While this could conceivably be considered a class that's grown too large, it doesn't really fit the God Object pattern.

Finally, as Michael Borgwardt mentions, there are also a large number of utility functions that use $ as a namespace and are only tangentially related to the DOM collection jQuery objects.

Title: Is jQuery an example of "god object" antipattern?

Body:
I want to ask – I am slowly learning jQuery.

What I see is an exact example of a God Object anti-pattern. Basically, everything goes to the $ function, whatever it is.

Am I right and is jQuery really an example of this anti-pattern?


答:
When in doubt, set a breakpoint or call console.log and examine the data.  It's better (in my opinion) to take a little while to learn the basics than to change things blindly and hope for the best.  You don't need to have a full understanding of how the API works, but the more that you know, the easier it will be to make it work for you.

In the case of results[0].geometry.location results is an array that contains at least one object which has a field named geometry containing an object.  This geometry object has a field named location which is most likely an object with two fields for latitude and longitude.

Title: Is the copy/paste approach professionally viable when working with the Google Maps API?

Body:
	I find that I understand much of the Javascript concepts used in the Google Maps API code, but then again there is quite a bit that is way over my head in syntax.

For example, the geocoder syntax seems to be of Ajax form, though I don't understand what is happening under the hood (especially with lines like results[0].geometry.location). I am able to modify the body of if (status == google.maps.GeocoderStatus.OK) for different purposes though.

	So, being that I am able to take various code from the Developer's Guide and rework it to an extent for my own purposes, all the while not fully understanding what Google Maps is actually doing, does this make me a copy-paste programmer?

	Is this a bad practice, or is this professionally viable? I am, of course, interested in learning as much as I can, but what if time-constraints outweigh the learning process?


问:
What is the difference between a Program Manager and a Project Manager?
Is a Program Manager a person who manages mutiple projects (under a single program) which are in turn managed by Project Managers?

Or is a Program Manager a person as defined by Joel Spolsky here.

NOTE: I am not referring to this.

答:
To add to @Robert's answer...

Different companies may use titles in different ways, so if you're asking because you want to know what a title means at a certain company, you may want to inquire on a case-by-case basis as not everyone will use the same reasoning.


问:
Fastest Functional Language
I've recently been delving into functional programming especially Haskell and F#, the prior more so. After some googling around I could not find a benchmark comparison of the more prominent functional languages (Scala,F# etc).

I know it's not necessarily fair to some of the languages (Scala comes to mind) given that they are hybrids, but I just wanna know which outperforms which on what operations and overall.

答:
According the Great Benchmarks Game, ATS is faster than the rest with Haskell, Scala, and one of the variants of Common Lisp in a rough tie for speed close behind that. After that Ocaml and F# are in roughly the same speed category with Racket and Clojure lagging behind...

However, almost none of this means anything at all really. It's all a question of problem, machine, compiler, coding techniques, and in some cases, plain luck. Generally speaking, Directly machine coded languages like Haskell will outperform VM compiled languages like F# and vastly outperform purely interpreted languages. Also generally, Statically typed languages are faster than Dynamically typed due to static analysis allowing all type operations to be calculated at compile rather than run time. Again, these are general rules, there will always be exceptions. "Paradigms" have little to do with it.

Title: Fastest Functional Language


问:
What problems will I face if I remove the concept of interfaces from my code?
I have been programming for many years but I am still not comfortable with the concept of "Interfaces". I try to use interfaces but many times I don't see a mandatory use for it. I think this is probably because the projects weren't so big, or because interfaces are more useful when teamwork is involved.

So, making another attempt to understand the importance of interfaces, here is my question:

What problems will I face if I remove the concept of interfaces from my code?

答:
Short answer: As result, your classes will have both unhealthy high headcount and very high method count. (look at early UI libraries, they are loaded with classes with, say 100 methods - ugly)

Interfaces are nice compact (usually 0-5 methods) purely abstract classes. They are easy to inherit by any class in any place, in hierarchies of any size. The sole purpose of interfaces is multiple inheritance, but without evil parts of multiple inherictance. Interfaces naturally bring good compression to badly bloated piles of classes.

Removing interfaces will disallow multiple inheritance from purely abstract classes.
The remaining classes, instead of being multirooted shallow and compact hive, will form forest of trees of inheritances.
Over time, with refactorings, forest will tend to collapse to single super tree with root "Object" class. The tree will be no more pretty. It will have lengthy root with many unnecessary abstract classes close to root and wide crown of nearly identical leaf classes, where it is hard to tell one class from another. Simple functions introduced at root classes will have too much of impact on everything and make the code unmaintainable, unlearnable, overfunctional and useless. Every special treatment of common methods will require specialization tricks, like "reintroduce".

There will be unnecessary visibility for overly public methods. Lot of dead methods, which are needed to stay near root classes, but making no sense for most of leaf classes. At some point the pile will reach the size, complexity and amount of inner conflicts, when there will be no more possible to bring change, fix or improvement without breaking something somewhere.


答:
To answer that question, I'm going to ask you a rhetorical question about another structure that have similar property to the DOM elements that jQuery manipulates, that is the good old iterator. The question is:

How many operation do you need on a simple iterator?

The question can be answered easily by looking at any Iterator API in a given language. You need 3 methods:

Get the current value

Move the iterator to the next element

Check if the Iterator has more elements

That's all you need. If you can perform those 3 operations, you can go trough any sequence of elements.

But that is not only what you usually want to do with a sequence of elements, is it? You usually have a much higher level goal to achieve. You may want to do something with every element, you may want to filter them according to some condition, or one of several other methods. See the IEnumerable interface in the LINQ library in .NET for more examples.

Do you see how many there are? And that is just a subset of all the methods they could have put on the IEnumerable interface, because you usually combine them to achieve even higher goals.

But here is the twist. Those methods are not on the IEnumerable interface. They are simple utility methods that actually take a IEnumerable as input and do something with it. So while in the C# language it feels like there are a bajillion methods on the IEnumerable interface, IEnumerable is not a god object.

Now back to jQuery. Lets ask that question again, this time with a DOM element.

How many operation do you need on a DOM element?

Again the answer is pretty straightforward. All the methods you need are methods to read/modify the attributes and the child elements. That's about it. Everything thing else is only a combination of those basic operations.

But how much higher level stuff would you want to do with a DOM elements? Well, same as an Iterator: a bajillion different things. And that's where jQuery comes in. jQuery, in essence provide two things:

A very nice collections of utilities methods that you may want to call on a DOM element, and;

Syntactic sugar so that using it is a much better experience than using the standard DOM API.

If you take out the sugared form, you realise that jQuery could easily have been written as a bunch of functions that select/modify DOM elements. For example:

```<code>$("#body").html("<p>hello</p>");
</code>```

...could have been written as:

```<code>html($("#body"), "<p>hello</p>");
</code>```

Semantically it's the exact same thing. However the first form has the big advantage that the order left-to-right of the statements follow the order the operations will be executed. The second start in the middle, which makes for very hard to read code if you combine lots of operations together.

So what does it all mean? That jQuery (like LINQ) is not the God object anti-pattern. It's instead a case of a very respected pattern called the Decorator.

But then again, what about the override of $ to do all those different things? Well, that is just syntactic sugar really. All the calls to $ and its derivatives like $.getJson() are completely different things that just happen to share similar names so that you can immediately feel that they belong to jQuery. $ performs one and only one task: let you have an easily recognizable starting point to use jQuery. And all those methods that you can call on a jQuery object are not a symptom of a god object. They are simply different utility functions that each perform one and only thing on a DOM element passed as an argument. The .dot notation is only here because it make writing code easier.

Body:
To answer that question, I'm going to ask you a rhetorical question about another structure that have similar property to the DOM elements that jQuery manipulates, that is the good old iterator. The question is:

How many operation do you need on a simple iterator?

The question can be answered easily by looking at any Iterator API in a given language. You need 3 methods:

Get the current value

Move the iterator to the next element

Check if the Iterator has more elements

That's all you need. If you can perform those 3 operations, you can go trough any sequence of elements.

But that is not only what you usually want to do with a sequence of elements, is it? You usually have a much higher level goal to achieve. You may want to do something with every element, you may want to filter them according to some condition, or one of several other methods. See the IEnumerable interface in the LINQ library in .NET for more examples.

Do you see how many there are? And that is just a subset of all the methods they could have put on the IEnumerable interface, because you usually combine them to achieve even higher goals.

But here is the twist. Those methods are not on the IEnumerable interface. They are simple utility methods that actually take a IEnumerable as input and do something with it. So while in the C# language it feels like there are a bajillion methods on the IEnumerable interface, IEnumerable is not a god object.

Now back to jQuery. Lets ask that question again, this time with a DOM element.

How many operation do you need on a DOM element?

Again the answer is pretty straightforward. All the methods you need are methods to read/modify the attributes and the child elements. That's about it. Everything thing else is only a combination of those basic operations.

But how much higher level stuff would you want to do with a DOM elements? Well, same as an Iterator: a bajillion different things. And that's where jQuery comes in. jQuery, in essence provide two things:

A very nice collections of utilities methods that you may want to call on a DOM element, and;

Syntactic sugar so that using it is a much better experience than using the standard DOM API.

If you take out the sugared form, you realise that jQuery could easily have been written as a bunch of functions that select/modify DOM elements. For example:

$("#body").html("<p>hello</p>");

...could have been written as:

html($("#body"), "<p>hello</p>");

Semantically it's the exact same thing. However the first form has the big advantage that the order left-to-right of the statements follow the order the operations will be executed. The second start in the middle, which makes for very hard to read code if you combine lots of operations together.

So what does it all mean? That jQuery (like LINQ) is not the God object anti-pattern. It's instead a case of a very respected pattern called the Decorator.

But then again, what about the override of $ to do all those different things? Well, that is just syntactic sugar really. All the calls to $ and its derivatives like $.getJson() are completely different things that just happen to share similar names so that you can immediately feel that they belong to jQuery. $ performs one and only one task: let you have an easily recognizable starting point to use jQuery. And all those methods that you can call on a jQuery object are not a symptom of a god object. They are simply different utility functions that each perform one and only thing on a DOM element passed as an argument. The .dot notation is only here because it make writing code easier.


答:
If you're not seeing a need for interfaces, then they may not be necessary. I would say, don't create an interface until you have a good reason to do so. (This goes under the principal of every character of your code having a purpose.)

I've done a lot of work in the Java world. Interfaces are all over. There are several reasons for these interfaces including

Some libraries requires interfaces e.g. if you want to create a dynamic proxy, you have to use interfaces to define types

Implementation hiding - this is the classic reason

"Because we may need it later" - not necessary and maybe a waste of developer time

"Because somebody told me that I should create interfaces" - not a good reason


答:
It should also be pointed out that you cannot measure / quantify the performance of a programming language.  The best you can do is measure the performance of a specific implementation of the language on specific platforms, running specific programs.

So when you ask about "the fastest functional language", what you are really asking about the best of the current implementations of the language(s).

@igouy's comment raises the point that there are other performance measures for language implementation; e.g. compilation time.  But that doesn't change the fact that application program's run time is an (indirect) measure of a language's implementation, not a measure of the language itself.

Consider Java for example.  Suppose I write a single-threaded benchmark using solely language features of classic (Java 1.0) Java.  If I compile and run using JDK 1.0, I will get a poor performance ('cos JDK 1.0 didn't have a native code compiler).  If I go from JDK 1.1 to ... JDK 1.7, I will most likely get progressively better results.  But this is not due to changes to the Java language ... because my benchmark is using the same language subset.  Rather the speedup is due to improvements in the compilers, the runtime system and / or the implementation of class libraries.  These are all implementation issues.

The other point is that these implementation differences can be really significant (e.g. orders of magnitude) for the same language.  So the fact that the best implementation for language X is faster than the best (or only) implementation of language Y doesn't necessarily tell you a lot about the language itself.

Title: Fastest Functional Language

Body:
I've recently been delving into functional programming especially Haskell and F#, the prior more so. After some googling around I could not find a benchmark comparison of the more prominent functional languages (Scala,F# etc).

I know it's not necessarily fair to some of the languages (Scala comes to mind) given that they are hybrids, but I just wanna know which outperforms which on what operations and overall.


问:
How can I get my progress reviewed as a solo junior developer
I am currently working for a 2 person company, as the solo primary developer. My boss gets the clients, mocks up some png design templates and hands them over to me.

This system has been working fine and i'm really enjoying it.

The types of projects I work on are for small - medium sized businesses and they usually want a CMS system. Developed from scratch i'll build a customised backend for the client to add/edit/remove categories, tags, products etc and then output them to the front end according to the design template handed to me. As time has gone on, the projects have increased in complexity, with shopping cart / ordering features and other common e-commerce type features.

Again, this system has been working fine and i'm really enjoying it.

My issue is my personal development as a programmer. I spend a lot of my spare time reading programming blogs, checking through stackexchange, reading suggested programming books (currently on 'The Pragmatic Programmer', really good so far), doing brain exercises (lumosity.com and khanacademy math problems), doing lots of physical exercise and other personal development type activities.

I can't help but feel though, that I'm missing out on feedback, critique. My boss is great and never holds back on praise in regards to my work, but he unfortunately is either to busy to check my code, or to be honest, I don't think it's one of his specialties and so can't provide feedback.

I want to know what i'm doing wrong and what i'm doing right. Should I be putting that much logic in the controller, am I modulating my code enough etc.

So what I have done is developed a little 'Family Budgeting' app and tried to do it as cleanly and effectively as I currently know how.

What i'm wanting to know is, is there somewhere I can submit this app, and have some seasoned developers provide feedback. It's not just a subsection of my code like 'codereview.stackexchange' appears to require, it's my entire workflow that I want critiqued.

I know this is a lot to ask, and I expect the main advice given will be to look for a job within a team, which is certainly something I will look into later down the track, but for now I want to persist with my current employment situation, but just don't want to develop too many bad habits.

Let me know if I can provide any further information to help clarify, or if this isn't the right place for this type of question I apologise in advance. Didn't want to use reddit as I felt this community fosters more well thought out responses.

答:
Leave. Find a new employer where you will work in a larger team of developers, including some shit hot guys whom you can learn from.

You clearly have all the right motivations in wanting to.


问:
"A good programmer can be as 10X times more productive than a mediocre one"
I had read an interview with a great programmer (it is not in English) and in it he said that "a great programmer can be as 10 times as good as a mediocre one" giving reason for why good programmers are very well paid and why programming companies give many facilities for their employees. The idea was that there is a very large demand for good programmers, because of the above reason and that's why companies pay very much to bring them.

Do you agree with this statement? Do you know any objective facts that could support it?

Edit: The question has nothing to do with experience; if you talk about one great programmer with 1 year experience then s/he should be 10 times more productive than a mediocre programmer with 1 year experience. I agree that from certain experience years onwards, things start to dissipate but that's not the purpose of the question.

答:
A genuinely terrible programmer can have sub-zero productivity (the bugs they introduce take longer to fix than it would take to just do all of their work for them).

And a genuinely great programmer can do things that poor and average programmers would simply never achieve, regardless of how much time you gave them.

So for these reasons, it's hard to talk about "10x as productive" or "100x as productive".

The thing to remember, though, is that most employers of programmers do not have any need for them to do the difficult tasks that average programmers could not manage. Most code being written is websites, line of business apps, intranet apps, etc., much of it really not that difficult. The productive programmer in that environment is the one who is best at understanding and implementing the users' needs, not the one who can write the cleverest code.

Indeed, most employers of programmers would be better off with a good programmer rather than a great one, because the great one will just get bored and leave. Gotta find a good match between programmers and jobs.


问:
How do you rate Hosting?
1) Up-time
2) Latency
3) Throughput
4) Server software such as SQL, etc.
5) $$$ -- transfer, overages, etc.

What else?

And is there a web site rating hosts by this criteria that is actually reliable and not simply a dishonest advertising site... or do you guys have any recommendations?

(BTW, someone with 150+ rep should create "hosting" and "web hosting" tags.)

答: Thanks for the input, guys.  There was a list of hosts & basic details about them on the webhostingtalk.com site, and it said hostgator is 100% green hosting, and seeing as how my web site will be about solar installation, that's a nice little tidbit that I can toss onto the site alongside my W3C validation tag.  I contacted their tech support about a few things -- guy spoke English great, etc.  It seems like hostgator is a great choice for me.</p>

Title: How do you rate Hosting?


答:
Facts and Fallacies of Software Engineering states (Fact 2, available in amazon preview):

The best programmers are up to 28 times better than the worst programmers, according to "individual differences" research. Given that their pay is never commensurate, they are the biggest bargains in the software field.

(look sources list there for research)

Of course, if you compare the productivity of a non-programmer (or a very bad programmer) with the good one (in terms of experience and knowledge), the difference can be infinitely large (n/0 == infinity for any positive n), but it is neither fair nor sensible comparison.

Your salary may depend on multiple factors (in random order):

Technologies used

Country/state you work in

Wealth of the company

Company's business type

Number of developers in the company

How long do you work in the company

Office politics

together with your personal...

productivity

knowledge and experience

involvement in company's business (for startups)

negotiating skills

sexual attractiveness and skills, lol (well, intelligence is sexy)

Title: "A good programmer can be as 10X times more productive than a mediocre one"

Body:
I had read an interview with a great programmer (it is not in English) and in it he said that "a great programmer can be as 10 times as good as a mediocre one" giving reason for why good programmers are very well paid and why programming companies give many facilities for their employees. The idea was that there is a very large demand for good programmers, because of the above reason and that's why companies pay very much to bring them.

Do you agree with this statement? Do you know any objective facts that could support it?

Edit: The question has nothing to do with experience; if you talk about one great programmer with 1 year experience then s/he should be 10 times more productive than a mediocre programmer with 1 year experience. I agree that from certain experience years onwards, things start to dissipate but that's not the purpose of the question.


问:
Benefit of C++ to System Administrators
What benefit could C++ bring to system administrators?

I am working on Windows and Ubuntu. If I learn C++, where could I implement it in system administration, Please specify some of its benefits.

答:
To sum up, I don't see much benefit if you do ONLY administrative tasks.

The only case it would be of benefit is if these conditions are true:

the tasks you want to automate requires maximum performance on each platforms (like processing very high quantity of data, but that's not an usual administrator task);

you have enough experience, knowledge of modern C++ and confidence to not see the language itself as a barrier;

you are allowed to spend more time coding than if it was python for example;

you don't fear the C++ lack of text encoding help/utilities and the potential traps related to this;

Basically that means it's not really suited for this. I would use Python for cross-platform admin tasks. Maybe occasional c++ for very very demanding tasks or if you already wrote the task in Python and it blows the memory or take too much time - that can happen but it's rare.

Title: Benefit of C++ to System Administrators


问:
How to test if a hashing algorithm is good?

Possible Duplicate:

  Which hashing algorithm is best for uniqueness and speed?

I have created a hash algorithm and would like to test if it is usable. What do I need to test and how?

答:
Short Answer: It depends on many-many factors.

There is no such thing as a good hash function for universal hashes (although there is such a thing as “universal hashing” but it has different meaning).

Depending on the context different criteria determine the quality of a hash. Some people may thing about SHA, however it is a cryptographic hash and it isn't at all good for hash tables which you probably mean.

Longer Answer:
Each hash tables has very specific requirements, and still finding a good hash function universally is hard because different data types expose different information that can be hashed. As a rule of thumb it is good to consider all information a type holds equally. This is not always easy or even possible. For reasons of statistics (and hence collision), it is also important to generate a good spread over the problem space, i.e. all possible objects. This means that when hashing numbers between 100 and 1050 it's no good to let the most significant digit play a big part in the hash because for ~ 90% of the objects, this digit will be 0. It's far more important to let the last three digits determine the hash.

Another important thing when hashing strings is to consider all characters (except when it's known in advance that the first three characters of all strings will be the same: because it would be a waste)

Edit:

1) Just to eliminate the confusion between hashing and encryption look here - Fundamental difference between Hashing and Encryption algorithms

2) Also a good discussion on - What is the difference between a Hash Function and a Cryptographic Hash Function?

References to look:

For detailed guidance you may look what Knuth has to say in The Art of Computer Programming*, vol. 3.

Julienne Walker's book on - The Art of Hashing

Good post by by Paul Hsieh - Hash functions


问:
Could a programming language work as well without statements?
As programming in JavaScript, I've noticed everything that can be done with statements and blocks can be done with expressions alone. Can a programming language work fine with only expressions? And, if yes, why are statements used at all?</p>

答:
Sure. The simplest way is to assign a result value to every construct that's currently a statement and thereby turn it into an expression. That's not necessarily useful or meaningful though. The only potential gain is a bit of conceptual simplicity. However, if you then proceed to remove things like semicolons and loops (requiring chaining via other operators and functions instead), programs heavily using statements become ugly.

A more radical but meaningful way to do this is to design the language such that almost everything has a meaningful value, and use it in a way that you almost always use an expression for that meaningful value, not for other effects. Functional programming languages do this (to some degree; for example, Haskell has declarations, which aren't expressions).

Statements are used because in the imperative paradigm, there are many common operations which don't have a useful result value, and because the notion of sequential instructions (rather than calculations) fits that paradigm quite well. If a large percentage of your program is mutating state, rather than calculating new values, it doesn't make sense to require producing a value (what's the result of a for loop?). In contrast, when your entire paradigm (FP) is built around the calculation of values, outliers that don't have a result value don't warrant an exception: Instead you give them a sentinel result that doesn't mean a thing.


问:
Is the separation of program logic and presentation layer going too far?
In a Drupal programming guide, I noticed this sentence:

The theme hook receives the total number of votes and the number of votes for just that item, but the template wants to display a percentage. That kind of work shouldn't be done in a template; instead, the math is performed here.

The math necessary to calculate a percentage from a total and a number is (number/total)*100. Is this application of two basic arithmetic operators within a presentation layer already too much? Is the maintenance of the entire system severely compromised by this amount of mathematics?

The WPF (Windows Presentation Framework) and its UI mark-up language, XAML, seem to go to similar extremes. If you try to so much as add two numbers in the View (the presentation layer), you have committed a cardinal sin. Consequently, XAML has no operators for any arithmetic whatsoever.

Is this ultra-strict separation really the holy grail of programming? What are the significant gains to be had from taking the separation to such extremes?

答:
I see nothing wrong with documentation being a tad pedantic, especially considering the typical target audience, even more so when it comes to things like templates, given that it's not exactly rare for non developers (graphic artists, for example) to dabble with them. Prior to your quote, the wording suggests that, although a bit silly, the example is used to illustrate the concept, I don't think the authors really meant to suggest that you should blindly follow their suggestion, but more to make a point.

Furthermore when it comes to documentation that targets PHP developers (and non developers), extreme pedantry is almost required, PHP has a notoriously low entry barrier and consequently the ecosystem is filled with crap code. I haven't looked at Drupal's codebase in years, but the last time I remember doing so, it was mostly super glue and duct tape, not Wordpress bad mind you, but still I was amazed it even worked. I'll venture a guess and say that the pedantry in the documentation is probably a direct consequence of the... not ideal state of the project's codebase.

At the same time though, you make a fair point, and the quote you isolated feels a bit dogmatic. Separating logic from presentation is an abstract principle, and thus open to interpretation and affected by various constraints. Similarly, MVC, the main expression of the principle, at least in web development, is an architectural pattern, or perhaps more accurately a tiered architectural model with three main components and without a canonical, or "pure", implementation. There are no "holy grails" in this, as there are no "holy grails" in anything in software development, our profession is one of trade-offs.

It's nearly impossible to say how much the application of two basic arithmetic operators within a presentation layer will actually affect your application, unless we know exactly what you're building and what exactly will depend on that math. Will the math need to change at a later time, for example? And if so, will you remember that this small, but perhaps crucial piece of code is not where it's supposed to be, two years after you've written it? I'm assuming here that you practice separation of program logic and presentation in general, and because of that you've trained yourself, perhaps unwittingly, to expect things to be in a certain place.

If you are confident that you are just doing a simple operation, that will probably never change and nothing important depends on it, I'd say feel free to put it wherever you want. Sure, purists will bark, some of them will probably feint, but who cares? I've said it before and I'll say it again, perfectionism is not a goal in itself, keep it simple, stupid!


答:
Depends on how you define "statement" and "expression".

A very strict definition would distinguish between statements as "things that have side effects, and maybe a return value" and expressions as "things that have return values, but cannot have side effects". With such a definition, no meaningful program can be written without at least one statement (which would have to evaluate an expression and output its return value) - pure expressions alone cannot interact with the world outside the program. A language alone can still be completely pure (i.e., not have any statements), if the impure part is moved out of the language and into the supporting ecosystem (which is exactly what Haskell does, although the language has definitions as well as expressions).

If, however, you allow for side effects in expressions, then the distinction between statements and expressions becomes arbitrary and much less interesting - of course you can invent a programming language that consists of expressions only; most Lisp dialects work much like that. In such a situation, evaluating an expression for its side effects is pretty much exactly the same as executing a statement, and one could argue that in such a language, expressions and statements are the same thing. The difference between a statement and an expression, then, is only syntactic.

Many languages still make this syntactic distinction, because it is useful not for technical reasons, but for readability. Making something an expression signals that you are interested in its return value, less so its side effects; making it a statement tells the reader that you intend it to cause side effects, and the return value may or may not be interesting.

Title: Could a programming language work as well without statements?

Body: As programming in JavaScript, I've noticed everything that can be done with statements and blocks can be done with expressions alone. Can a programming language work fine with only expressions? And, if yes, why are statements used at all?</p>


答:
If you are looking at languages only on speed of execution you are missing some major points. Speed is a good thing, but it is not the only thing.

Haskell uses a very robust type system to create programs that will be much more likely to be bug free and robust.

Erlang uses its built in monitoring system to allow you to create fault systems that can give you a huge level of reliability in the face of various types of faults. In addition Erlang can give you a level of concurrency that is hard to match in other languages.

In truth I would consider speed of execution in the modern day to be rather far down on the list of what I would consider in most cases. (OK if I was doing massive numeric computation I would probably want to use fortran for speed but otherwise Its just not important enough to matter)

Title: Fastest Functional Language


问:
What is the difference between technical specifications and design documents?
What are technical specifications? Are they the same as design documents. If not, what is the difference and some examples?</p>

答:
A software design document can be at the level of a system or component, and generally includes:

relevant goals or requirements (functional and non-functional);

static structure (e.g., components, interfaces, dependencies);

dynamic behavior (how components interacts);

data models or external interfaces (external to the system/component described in the document); and

deployment considerations (e.g., runtime requirements, third-party components).

Note that all of these descriptions are at an abstract level. The purpose is to give the reader a broad general understanding of the system or component. There may be many levels of design documents (e.g., system- or component-level).

A technical specification describes the minute detail of either all or specific parts of a design, such as:

the signature of an interface, including all data types/structures required (input data types, output data types, exceptions);

detailed class models including all methods, attributes, dependencies and associations;

the specific algorithms that a component employs and how they work; and

physical data models including attributes and types of each entity/data type.


问:
Should business services cross bounded contexts?
Firstly, I am following the convention that a bounded context is synonymous to a department, or possibly one department has 1 to many bounded contexts.

We have a client consultancy department that has a Documentation Service. Documents are stored in the Document Store Service (which is where all documents in the company are stored - it is a utility service), and the Documentation Service stores information about that document (a business service). As it was designed for the client consultancy, it is information relevant to them.

Now health and safety need somewhere to store information about a document. This is different information to client consultancy, but I have been instructed to extend the existing service to account for this extra information. I feel this service is now crossing a bounded context. My worry is that all departments will eventually store there information in here and the service will become bloated, trying to be all things to all departments. Each document record will only store a subset of the information because it will only belong to one department.

It will get worse when different departments want to store the same information but refer to it in a diferent ways, or when two departments want to store different information that they refer to in the same way. In my understanding, this is exactly the reason for bounded contexts.

I feel each department should have it's own business service for information about a document, but use the same utility service to actually store the document.

What would be the correct approach?

答:
You probably have just identified the need for a function that is not specific to any one department, but rather forms kind of a basic infrastructure. Consider forming a bounded context "Basic Infrastructure", and assign the Documentation service there. This way, there are clear boundaries and dependencies between the different context. The basic Documentation service can still be consumed by any department, without messing up your design.

Consider specific implementations on top of the more generic Documentation service to deal with functions specific to a department (or rather: business function). Those specific implementations would then belong to the respective bounded context. E.g.

Basic Infrastructure: GenericDocumentationService(document, attributes) - where document is the document to be stored, attributes is a list of key/value paris

Client Consultancy: ConsultancyDocumentationService(document, client)

Health and Safety: HealthSafetyDocumentationService(document, risk, mitigation)

The client and health&safety implementations would e.g. validate and process their specific arguments, then use the generic service to finally store the document.

NB: In general, business organizational structure such as departments do not make for good boundaries. Rationale: organizational structures tend to change over time and such changes are likely to invalidate previously identified boundaries. Instead it is advisable to identify the core business functions and group those into logically cohesive blocks.


问:
Is a functional spec a part of the System requirement spec?
I wonder, sources like wikipedia or templates I found shows that Functional spec is a part of System requirement documents. I always thought that SRD is just overall decsription of the system, with all functional and non functional requirements. Yet I thought that Functional spec is more detailed and it is a separate document, while SRD is high level customer-created description (how is this one called then?)
Could anyone help to make this clear for me?

答: SRS broadly defines customer requirements and describes what is expected from the system.  Functional specification further describes what functions are expected from domain and sub-domains described in SRS.  SRS is the building block of any SDLC.</p>


问:
What are the downsides of leaving automation tags in production code?
I've been setting up debug tags for automated testing of a GWT-based web application. This involves turning on custom debug id tags/attributes for elements in the source of the app. It's a non-trivial task, particularly for larger, more complex web applications. Recently there's been some discussion of whether enabling such debug ids is a good idea to do across the board.

Currently the debug ids are only turned on in development and testing servers, not in production. There have been points raised that enabling debug ids does cause performance to take a hit, and that debug ids in production may lead to security issues.

What are benefits of doing this? Are there any significant risks for turning on debug tags in production code?

答: Keeping debug tags in code used in production environment is not a bad idea.  Though, these should only be enabled as and when required, in case of customer issues etc., leaving debug mode ON on production machine is not recommended.  Further if it is needed to implement debug mode, then debug levels should be defined, and upper level debug mode may be enabled in production environment with the possibility to change that level as and when needed.</p>