问:
When would you need "hundreds of thousands" of threads?
Erlang, Go, and Rust all claim in one way or another that they support concurrent programming with cheap "threads"/coroutines.  The Go FAQ states:

It is practical to create hundreds of thousands of goroutines in the same address space.

The Rust Tutorial says:

Because tasks are significantly cheaper to create than traditional threads, Rust can create hundreds of thousands of concurrent tasks on a typical 32-bit system.

Erlang's documentation says:

The default initial heap size of 233 words is quite conservative in order to support Erlang systems with hundreds of thousands or even millions of processes.

My question: what sort of application requires so many concurrent threads of execution?  Only the busiest of web servers receive even thousands of simultaneous visitors.  Boss-worker/job-dispatching type applications I've written hit diminishing returns when the number of threads/processes is much greater than the number of physical cores.  I suppose it might make sense for numerical applications, but in reality most people delegates parallelism to third party libraries written in Fortran/C/C++, not these newer generation languages.

答:
My question: what sort of application requires so many concurrent threads of execution?

1) The fact that a language "scales" means there is less chance you'll have to ditch that language when things get more complex down the road.  (This is called the "Whole Product" concept.) Many people are ditching Apache for Nginx for this very reason. If you're anywhere close to the "hard limit" imposed by thread overhead, you'll get scared and start thinking about ways to get past it. Web sites can never predict how much traffic they will get, so spending a little time making things scalable is reasonable.

2) One goroutine per request just the start. There are plenty of reasons to use goroutines internally.

Consider a web app with 100's simultaneous requests, but each request generates 100's of back-end requests. The obvious example is a search engine aggregator. But pretty any app could create goroutines for each "area" on screen, then generate them independently instead of sequentially. For example, every page on Amazon.com is made up of 150+ back-end requests, assembled just for you. You don't notice because they are in parallel, not sequential, and each "area" is it's own web service.

Consider any app where reliability and latency are paramount. You probably want each incoming request to fire off a few back-end requests, and return whichever data comes back first.

Consider any "client join" done in your app. Instead of saying "for each element, get data", you can spin off a bunch of goroutines. If you have a bunch of slave DBs to query, you will magically go N time faster.  If you don't, it won't be any slower.

hit diminishing returns when the number of threads/processes is much greater than the number of physical cores

Performance isn't the only reason to break up a program into CSP.  It can actually make the program easier to understand, and some problems can be solved with a lot less code.

As in the slides linked above, having concurrency in your code is a way to organize the problem.  Not having goroutines is like not having a Map/Dictonary/Hash data structure in your language. You can get by without it. But once you have it, you start using it everywhere, and it really simplifies your program.

In the past, this meant "roll your own" multithreaded programming. But this was complex and dangerous -- there still aren't a lot of tools to make sure you're not creating races. And how do you prevent a future maintainer from making a mistake?  If you look at big/complex programs, you'll see they expend a LOT of resources in that direction.

Since concurrency isn't a first-class part of most languages, today's programmers have a blind spot for why it would be useful to them.  This will only become more apparent as every phone and wristwatch heads towards 1000 cores. Go ships with a built-in race-detector tool.


问:
Are 'The Pragmatic Programmer' and 'The Mythical Man Month' good books for people with limited practical experience programming
I was once told to read the books titled 'The Pragmatic Programmer' and 'The Mythical Man Month'. I have very little experience programming (basic HTML, CSS and JS).

If I were to purchase these books, read through them, would it be beneficial to me with such a limited understanding or would I benefit from them?

I ask because I am currently learning HTML5 and CSS3 from an online source and want some general reading material to add to my kindle.

答:
There are only 2 books I keep from my school days:

Design Patterns, (Gamma et. al)

This book is all practical. It's not a meta book like Clean code or The Pragmatic Programmer (both of which are great books). DP is all about how to manage 'the mess' and how to keep your code flexible. Spring IOC IS the factory pattern on steroids. This book is the one that I continuously apply in my career. (ToolKit.getToolKit(), Iterator, Collection.unmodifiableList()) And I personally end up rolling delegate and composite patterns a lot

Introduction to Algorithms (Cormen et. al)

This book is the theoretical. Many of the algorithms contained there-in form the bedrocks of libraries (Collections.sort()), auto-complete, library dependency resolution. But also major BigData apps like Cassandra. I rarely crack this book open but on an occasion I blow the dust off, look up a couple of algos that might solve my current quandary (almost always these are graph algos) and roll one out.

ContentLicense: CC BY-SA 3.0


问:
What is right choice of Data Access Layer for large application
I am using Singleton pattern for my application, I have used ADO.NET Entity framework as my Data Access Layer, after login to my application, it's taking 3 to 5 minutes to load the dashboard.

Is there a way to reduce the time? Or I have to look for some other methods instead of Entity framework?

答:
Feel free to downvote since ORMs seem popular these days, but...

WHY are you using Entity Framework?  Is there a possibility that the backend database might change?  Are you nervous about writing SQL stored procedures to deliver your data?

Or possibly does it seem that writing a lot of transforms from DbDataReader rows to your objects might be a lot of work?

I'm asking because I've had the misfortune to work on a couple of projects where the developer went for Entity Framework and specifically, was ordered by management to rip it out and go to decent SQL Stored Procs (which can be optimized and have an execution plan) and datareaders PURELY because of the godawful performance you have also experienced.

Where a dashboard requires (according to SQL Profiler) in excess of 48,500 database calls to return before it ever loads, there is an issue.  I never see this addressed, so I'm hoping some kind soul will enlighten me.


问:
Entity Framework limitation
I was wondering if anyone had the same need and why (if possible).

My problem is: I can't create a model in EF using two tables from different DBs without some weird workarounds. For my scope that is very much necessary.

Did any of you ever needed to do this?
What did you do? And, like me, do you think MS should add this feature?

Thank you all.

答:
About the only way to do this is with Synonyms.

In SQL Server, if I were to use the MSDN example

```<code>    USE tempdb;
GO
-- Create a synonym for the Product table in AdventureWorks2012.
CREATE SYNONYM MyProduct
FOR AdventureWorks2012.Production.Product;
GO

-- Query the Product table by using the synonym.
USE tempdb;
GO
SELECT ProductID, Name
FROM MyProduct
WHERE ProductID < 5;
GO
</code>```

Then EF would be able to see MyProduct if it were aimed at tempdb.

ContentLicense: CC BY-SA 2.5

Title: Entity Framework limitation

Body:
About the only way to do this is with Synonyms.

In SQL Server, if I were to use the MSDN example

    USE tempdb;
GO
-- Create a synonym for the Product table in AdventureWorks2012.
CREATE SYNONYM MyProduct
FOR AdventureWorks2012.Production.Product;
GO

-- Query the Product table by using the synonym.
USE tempdb;
GO
SELECT ProductID, Name
FROM MyProduct
WHERE ProductID < 5;
GO

Then EF would be able to see MyProduct if it were aimed at tempdb.


答:
A simple example for Erlang, which was designed for communication: transferring network packets. When you do one http request, you might have thousands of TCP/IP packets. Add to this that everyone connects at the same time, and you have your use case.

Consider many applications used internally by any big company to handle their orders or whatever they might need. Web servers are not the only thing needing threads.

Title: When would you need "hundreds of thousands" of threads?

Body:
Erlang, Go, and Rust all claim in one way or another that they support concurrent programming with cheap "threads"/coroutines.  The Go FAQ states:

It is practical to create hundreds of thousands of goroutines in the same address space.

The Rust Tutorial says:

Because tasks are significantly cheaper to create than traditional threads, Rust can create hundreds of thousands of concurrent tasks on a typical 32-bit system.

Erlang's documentation says:

The default initial heap size of 233 words is quite conservative in order to support Erlang systems with hundreds of thousands or even millions of processes.

My question: what sort of application requires so many concurrent threads of execution?  Only the busiest of web servers receive even thousands of simultaneous visitors.  Boss-worker/job-dispatching type applications I've written hit diminishing returns when the number of threads/processes is much greater than the number of physical cores.  I suppose it might make sense for numerical applications, but in reality most people delegates parallelism to third party libraries written in Fortran/C/C++, not these newer generation languages.


问:
Is there any practical algorithm / data-structure that can't be done with non-recursive Lambda Calculus augmented with foldl?
In my search for a practical non-turing complete programming language, I've been paying attention to lambda-calculus with disallowed self-application - that is, x x forbidden. After taking that language and augmenting it with lists and the foldl and range operations, pretty much any algorithm I've tried so far is implementable. It is trivial to implement filter, reverse, head, tail, map, scanl, zip and many others - foldl replaces the need for recursion.

Can you think in any practical, important algorithm that would be undoable in that language?

It is no coincidence that all of them use self-application—the
  application of an expression to itself. It is through
  self-application that repetitive computation can be simulated in the
  lambda calculus. Indeed, the third of the previous three examples is
  famous because it can encode recursive function deﬁnitions.

From http://people.cis.ksu.edu/~schmidt/705s13/Lectures/ch6.pdf .

答:
tl;dr (or I don't know what a Y combinator is)

This question is based on the assumption that the above defined language is not Turing-complete, it actually is Turing-complete and therefore the question is invalid - all algorithms can be expressed in the language defined above as is the meaning of Turing-completeness.

Ok. Well apparently this has to be explicitly written out.

Proof of turing completeness follows trivially from unbounded recursion which can be derived from a fixpoint combinator.

Note the traditional Y combinator

```<code>Y f = (\x -> f (x x)) (\x -> f (x x))
</code>```

Define

```<code>cons = \a b f -> f a b
car  = \x y -> x
cdr  = \x y -> y

fst  = \p -> p car
snd  = \p -> p cdr
</code>```

This is just the standard encoding of church pairs.

```<code>nil = \x -> x -- Or anything really
fold = \x -> cons x nil
unfold = \x -> fst x
</code>```

Then

```<code>Y f = (\x -> f (unfold x x)) (fold (\x -> f (unfold x x)))
</code>```

No self application, but this still correctly encodes the Y combinator. I previously wrote this out in Haskell. There fold and unfold require more interesting jiggery-pokery because of types, but since lambda calculus has none we can safely ignore it :)

We've just proven we have a Turing-complete language. Every algorithm is therefore exactly as efficient as can be encoded in a Lambda Calculus. This also invalidates the question's original premise that the language is Turing-incomplete.

Body:
tl;dr (or I don't know what a Y combinator is)

This question is based on the assumption that the above defined language is not Turing-complete, it actually is Turing-complete and therefore the question is invalid - all algorithms can be expressed in the language defined above as is the meaning of Turing-completeness.

Ok. Well apparently this has to be explicitly written out.

Proof of turing completeness follows trivially from unbounded recursion which can be derived from a fixpoint combinator.

Note the traditional Y combinator

Y f = (\x -> f (x x)) (\x -> f (x x))

Define

cons = \a b f -> f a b
car  = \x y -> x
cdr  = \x y -> y

fst  = \p -> p car
snd  = \p -> p cdr

This is just the standard encoding of church pairs.

nil = \x -> x -- Or anything really
fold = \x -> cons x nil
unfold = \x -> fst x

Then

Y f = (\x -> f (unfold x x)) (fold (\x -> f (unfold x x)))

No self application, but this still correctly encodes the Y combinator. I previously wrote this out in Haskell. There fold and unfold require more interesting jiggery-pokery because of types, but since lambda calculus has none we can safely ignore it :)

We've just proven we have a Turing-complete language. Every algorithm is therefore exactly as efficient as can be encoded in a Lambda Calculus. This also invalidates the question's original premise that the language is Turing-incomplete.


答:
I had a similar scenario recently for a Entity Framework Database First project. I had to create an Entity from data spread across multiple tables, in-fact some of the data came from another database (but on the same Db server).

To get around this I created stored procedures for the required data and imported the procedure to Entity Framework using the Function Imports in Model Browser.

Now when I use that Entity, it calls a stored procedure in the background to retrieve the data. Your question about Microsoft adding this as a feature is answered, they already have. That is what the Function Imports are for.

Title: Entity Framework limitation

Body:
I was wondering if anyone had the same need and why (if possible).

My problem is: I can't create a model in EF using two tables from different DBs without some weird workarounds. For my scope that is very much necessary.

Did any of you ever needed to do this?
What did you do? And, like me, do you think MS should add this feature?

Thank you all.


问:
Interface at the class or function level?
I have been falling into a pattern lately where I have been defining routines that rely on an interface defined by a function that is specified as a parameter to the routine. (The language is C#, but this can be applied to any language with first-class functions.)

For example, I have an API that exposes CRUD operations against a backing store. In the case of a GET operation on a particular resource, I can generalize the routine into:

get the resource we are looking for

return a not found response if resource does not exist

return the resource if found

What I ended up doing is defining a routine that accepts a delegate function for finding the resource. It's this delegate that defines the interface contract.

This happens to work well for my situation because the information required to locate the resource can vary. In my case, it's looking up data in a database by keys, but the type and number of keys can vary. I can capture these in a closure in the calling routine and satisfy the delegate function interface. For example:

```<code>// Locate a simple record that only has one key
public SimpleRecord GetSimpleRecord(int recordID) {
   return getResource(repository => repository.SimpleRecords.Find(recordID));
}

// Locate a complex record that has many keys
public ComplexRecord GetComplexRecord(int recordID, int userID, string token) {
   return getResource(repository => repository.ComplexRecords.Find(recordID, userID, token));
}
</code>```

This work, but seems like is a mix of OOP and functional style programming. If I need more than one delegate passed, it starts to get a bit messy. Some routines that I need everywhere I ended up defining as abstract methods that all sub-classes need to implement. So I have a hybrid.

Does this type of technique have a name or pattern that I'm missing? Should the delegates be implemented in a defined class interface that gets passed to the caller?

UPDATE with more concrete example:

I'm trying to adhere to the DRY principal. I'm talking about controllers in a C# Web API application. Each and every request has some commonality which I have implemented in a base controller class:

Handle all exceptions by returning the correct HTTP status code, (404 for resources that are not found, 201 for created resources, etc.)

Map database entities to-and-from data transport objects that the client deals with

I want to express what to do in this base class, and delegate how to the concreate class. The how ends up being implemented by delegate functions. I may need to get a person from the database, by first name and last name, or a purchase order, by an integer id. In both cases, if the resource is not found, a 404 must be returned. One returns a person, one a purchase order. How to look them up and how to map the data to a client object differs.

The base function may look like this:

```<code>T getResource<T> (Func<IRepository, T> find) {
    T data = find(getRepository());
    if (data == null) {
        throw new DataNotFoundException();
    }
    return data;
}
</code>```

Now, in the person controller and purchase order controller, I don't have to repeat the logic of what do to when the resource is not found--just implement the find delegate. (This is a simple example without mapping, adding, removing or other details that differ resource to resource).

```<code>public Person Get(string first, string last) {
   return getResource<Person>(repository => repository.People.Find(first, last));
}

public PurchaseOrder Get(int id) {
   return getResource<PurchaseOrder>(repository => repository.POs.Find(id));
}
</code>```

Note how the closures above neatly deal with varying number and types of parameters for finding things, but satisfy the interface defined by the delegate find function. Is this possible to do with standard class interfaces?

(And this question is not about the repository. That is resolved with dependency injection and is implemented with Entity Framework.)

答:
I immediately think of two patterns that can be of use for your case.

Template method pattern

Everything that is the same for all concrete implementations resides in a single abstract class. All that is more concrete is delegated to subclasses. If I were you, I would first try this one.

Builder pattern

If you need more flexibility, e.g. if using the Template Method Pattern you would have to create a broad hierarchy of abstract classes, you may benefit from the builder pattern. Turning imperative code into a more descriptional object is exactly what you obtain with this pattern. All that remains for client applications is then to create and pass a concrete description of what you want to CRUD from the backing store.


问:
what's the proper way to organize code that straddles multiple objects?
Let's say I have the following classes: person, widget, foo_bars.

A person can have multiple widgets and foo_bars.

When an admin deletes a person, I want my code to do a cascading delete... and remove all related records in the database for this person
In my widget class, I have a delete method... and the same is true for my foo_bars class

But in order to accomodate something like the person delete function, I feel like I should be creating "Person Manager" class, that will actually repeat a version all the logic inside both the delete methods in the widgets / foo_bars classes.  (instead of just calling the existing methods on the classes.

Here's what I'm thinking:

Example 1

```<code> public class PersonManager{

     delete_person(personID as int)
     {
        // assume that I've queried for list of all widget and foobars IDs.
        //1.  delete all widgets for personID
        success = true
        dim obj_widget = new widget;
        loop through all widgets
            result = obj_widget.delete(widgetID)
            if not result then
               success = false
               exit with error
            end if
        end loop

        //2.  delete all foo bars for personID
        if success then
            dim objfoobar= new foo_bars;
            loop through all foobars
                result = objfoobar.delete(foobarid)
                 if not result then
                    success = false
                    exit loop
                  end
            end loop
         end

        //3. delete person record.
        if success then
             result = databaseobj.deleteperson(personID)
             if not result then
                 return false, "Delete person failed because...."
             else
                 return true
             end
        end
     }
 }
</code>```

In the above example, I'm trying to demo the reuse of existing the existing delete methods on each class... and then if it successfully deletes all widgets and foobars for the person, then i delete the person record itself.

The problem with this is that if the widgets delete properly, but the foo_bars don't, how do I rollback?
Each delete method has it's own transaction defined within, because deleting a widget or foo bar involves, let's say 2 - 3 steps.  So, in other words, the delete method on the widget class currently looks like this:

```<code>    public class widget{
         delete_widget{
                 database.execute("BEGIN TRANSACTION")
                 database.execute("DELETE FROM XYX ...")
                 if successful then
                        database.execute("DELETE FROM yyy...")
                 else
                        database.execute("ROLL BACK")
                        return false
                 end if
                 database.execute("COMMIT")
                 return true
              }
      }
</code>```

For each widget, I'll be calling this method...
So what if all the widgets delete, but it dies deleting the first foobar?
I think I have to rewrite the code to delete everything right inside the Person manager class and wrap it in a transaction, instead of calling the existing delete methods on the classes.
At least, that's what I'm thinking.
If there's another way to look at this problem, please let me know.
I could just write a cascading delete SQL statement in the PersonManager class, and not call the methods on the two classes.
But I don't know if using SQL cascading deletes is a good thing...
Thanks!

答:
So your problem are nested transactions. I think this could be solved by separating the transaction logic from the data logic.

Something like Command pattern, where commands represent the operations and the one executing the command is in charge of transactions is good fit. You could even nicely compose the commands of various deletes. And even the ugly success testing and setting could be nicely encoded in some specific composite command that handles the success logic.


问:
Implementation of algorithm to generate chess positions
I am interested in developing a program that generates an endgame table-base for the chess.

I have gone through the technical papers of the greats like Shannon and Ken Thompson. I have found that retrograde analysis is used for the generation.

How can I generate all positions in a KBBK chess endgame which are mates in 0?

答:
Already a good answer here, but I try to highlight the problem from a slightly different point of view. When you are going to implement a full retrograde analysis for KBBK, you have to generate all KBBK positions, which are less than 32*32*62*61*2. The "32" is the number of squares for the bishops, the "*2" takes into account which player moves next; and not all 32*32*62*61 theoretical placements of the four pieces are legal (obviously, you can exclude any positions where the kings have a positional distance <2).

For the analysis, take these positions as the vertices of a directed graph, and the edges are the legal transitions from one position to the next (according to the possible moves).

Now, mark the positions where white moves next and the black king could be captured by a white bishop.  Technically, capturing the king is not legal according to the classic chess rules, but lets assume for a moment it were legal and call these positions "mate in -1". The "mate in 0" positions then are the vertices in the graph where black moves next, having only "mate in -1" sucessors, and where the black king is already checked (when there are just "mate in -1"-successors, and the black king is not checked, it is a remis situation).

More generally, a position where black moves next is a "mate in x+1", when x is the maximum of all y among the successors in the graph with a "mate in y" position, and there is no remis situation. When black moves next and there is at least one remis position amoung the successors, the current position is a remis situation, too.  A position where white moves next is a "mate in x+1", when x is the minimum of all y among the successors with a "mate in y" position (regardless of remis positions). When white moves next, a position is only a remis position when all successors are remis positions, too.

So "mate in 0" positions can be simply identified by applying the first step of your retrograde analysis.


问:
Why not embed styles/scripts in HTML instead of linking?
We concatenate CSS and JavaScript files to reduce the number of HTTP requests, which improves performance. The result is HTML like this:

```<code><link rel="stylesheet" href="all-my-css-0fn392nf.min.css">
<!-- later... -->
<script src="all-my-js-0fn392nf.min.js"></script>
</code>```

If we've got server-side/build logic to do all this for us, why not take it one step further and embed those concatenated styles and scripts in the HTML?

```<code><style>.all{width:100%;}.my{display:none;}.css{color:white;}</style>
<!-- later... -->
<script>var all, my, js;</script>
</code>```

That's two fewer HTTP requests, yet I've not seen this technique in practice. Why not?

答:
The latest version of HTTP was created way back in 1999. In 1999, everybody connected to the Internet with dial-up. The Internet was very slow. 16 years later, things have moved on a great deal, but the protocols we use have not.

The answers that we shouldn't inline 'because it interferes with caching' is a little misleading, particularly in the era of superfast Internet. When you actually do the calculations, there is often negligible difference between loading times with cache-warm and cache-cold users if you have inlined. The fact that there is a small difference is not inherently because you have inlined, but because of the inflexible design of HTTP/1.1.

The SPDY protocol implements something called server push. This essentially takes inlining out of the HTML document itself, and into the protocol. An intelligent server will know what resources the client already has. A dumb server will just send everything regardless -- that will still be a performance benefit, but may cost in terms of bandwidth. If the browser has the contents in its cache, it can simply discard the incoming copies. The server waits until the HTML is loaded before sending the additional resources -- in theory the browser can send a signal to cancel the server push.

HTTP/2.0 is based on SPDY and will most likely implement server push, but you can in theory start using SPDY today. So the real reason we don't inline is one of legacy -- the protocols that currently exist are old and are not flexible enough to achieve 'protocol-level inlining'.


答:
Why not just use assert-like function?

```<code>public T Exists<T>(T val) where T : class
{
    if (val == null)
        throw new DataNotFoundException();
    return val;
}
</code>```

And then use it:

```<code>public Person Get(string first, string last) {
   return Exists(repository.People.Find(first, last));
}
</code>```

But this probably applies only for your simple example. But we don't know how complex your requirements are if you don't describe your complex cases. I think you are approaching this problem from bad side. While C# has few functional properties, it is not a functional language. Trying to solve problems in functional way is never going to look nicely.

Title: Interface at the class or function level?

Body:
I have been falling into a pattern lately where I have been defining routines that rely on an interface defined by a function that is specified as a parameter to the routine. (The language is C#, but this can be applied to any language with first-class functions.)

For example, I have an API that exposes CRUD operations against a backing store. In the case of a GET operation on a particular resource, I can generalize the routine into:

get the resource we are looking for

return a not found response if resource does not exist

return the resource if found

What I ended up doing is defining a routine that accepts a delegate function for finding the resource. It's this delegate that defines the interface contract.

This happens to work well for my situation because the information required to locate the resource can vary. In my case, it's looking up data in a database by keys, but the type and number of keys can vary. I can capture these in a closure in the calling routine and satisfy the delegate function interface. For example:

```<code>// Locate a simple record that only has one key
public SimpleRecord GetSimpleRecord(int recordID) {
   return getResource(repository => repository.SimpleRecords.Find(recordID));
}

// Locate a complex record that has many keys
public ComplexRecord GetComplexRecord(int recordID, int userID, string token) {
   return getResource(repository => repository.ComplexRecords.Find(recordID, userID, token));
}
</code>```

This work, but seems like is a mix of OOP and functional style programming. If I need more than one delegate passed, it starts to get a bit messy. Some routines that I need everywhere I ended up defining as abstract methods that all sub-classes need to implement. So I have a hybrid.

Does this type of technique have a name or pattern that I'm missing? Should the delegates be implemented in a defined class interface that gets passed to the caller?

UPDATE with more concrete example:

I'm trying to adhere to the DRY principal. I'm talking about controllers in a C# Web API application. Each and every request has some commonality which I have implemented in a base controller class:

Handle all exceptions by returning the correct HTTP status code, (404 for resources that are not found, 201 for created resources, etc.)

Map database entities to-and-from data transport objects that the client deals with

I want to express what to do in this base class, and delegate how to the concreate class. The how ends up being implemented by delegate functions. I may need to get a person from the database, by first name and last name, or a purchase order, by an integer id. In both cases, if the resource is not found, a 404 must be returned. One returns a person, one a purchase order. How to look them up and how to map the data to a client object differs.

The base function may look like this:

```<code>T getResource<T> (Func<IRepository, T> find) {
    T data = find(getRepository());
    if (data == null) {
        throw new DataNotFoundException();
    }
    return data;
}
</code>```

Now, in the person controller and purchase order controller, I don't have to repeat the logic of what do to when the resource is not found--just implement the find delegate. (This is a simple example without mapping, adding, removing or other details that differ resource to resource).

```<code>public Person Get(string first, string last) {
   return getResource<Person>(repository => repository.People.Find(first, last));
}

public PurchaseOrder Get(int id) {
   return getResource<PurchaseOrder>(repository => repository.POs.Find(id));
}
</code>```

Note how the closures above neatly deal with varying number and types of parameters for finding things, but satisfy the interface defined by the delegate find function. Is this possible to do with standard class interfaces?

(And this question is not about the repository. That is resolved with dependency injection and is implemented with Entity Framework.)

Body:
Why not just use assert-like function?

public T Exists<T>(T val) where T : class
{
    if (val == null)
        throw new DataNotFoundException();
    return val;
}

And then use it:

public Person Get(string first, string last) {
   return Exists(repository.People.Find(first, last));
}

But this probably applies only for your simple example. But we don't know how complex your requirements are if you don't describe your complex cases. I think you are approaching this problem from bad side. While C# has few functional properties, it is not a functional language. Trying to solve problems in functional way is never going to look nicely.


问:
Would adding an @beta doc-comment tag be useful?
When a function has reached the end of its life, we add a @deprecated tag into its doc-comment to notify other developers that they should stop using this function, and then a couple years later it's removed.

I was just thinking about an @beta tag to signify this method is brand new and hasn't been tested in a variety of use-cases yet.

You might be thinking "you can write use-cases to ensure its correctness!" Of course you can, but its the API that concerns me, and how it behaves in edge-cases. Sometimes these decisions are not obvious until you have tried out the function in a variety of situations. Sometimes new parameters need to be added to cover more use-cases. Sometimes re-ordering them makes sense if you find that an argument is actually optional and needs to be moved to the end (or vice versa).

By adding the @beta tag, you are warning other developers that the API of this method might change yet, and they should use it with extreme caution. This gives you more granular control over your API instead of making the entire project 'beta'.

To get the most use out of this, however, IDEs and documentation-generators would need to pick up on this tag.

What do you guys think? Could you see this as being useful, is it a waste of time, or do you have other ways of dealing with this?

In the past, I have made such methods 'private' where possible, or prefixed them with an underscore.

答:
It is not just a waste of time, it is a huge waste of time.

There is a big difference between @beta and @deprecated. Using @deprecated is fine: it informs users of the API that the method, function or class will no longer be used in the future. The deprecated state will never change until the code block is deleted from the active source code. Deprecating code is the secondary result of newer code. The overhead of marking code as deprectated is reminding which code is replaced and planning when to remove it. It is impossible to forget to remove the @deprecated flag, because deprecated methods are in their end of life phase. You could argue that code can also be undeprecated, but then you should seriously consider the stability of your API.

@beta would inform users of the api that they can use a API member at their own risk. Forgetting to remove the flag from the documentation results in a huge waste of time for the users, since they will be reluctant to use newer methods that save them development time. It is also redundant from an API programmer perspective, because with a decent version control system (that is decently used), you can get an overview of what changed since the last stable release.

Which brings us to releases. If the quality of a code block is poor or too new or too unstable or too anything, then it shouldn't be released as stable code. In the minds of the API users, the weakest link in the API will tear its reputation down, even if marked as such in the documentation. The more adventurous users who like danger and hidden features may want to get hold of a beta release.

Oh, and don't say "but my users are very intelligent and will make the difference", because, well, let alone the intellect of the API users, which may be above moderate, they will prefer a clean, stable API over anything else for serious work.

The solution to this problem lies more in the lines of intelligent use of distributed version control and release scheduling than in documentation, which not always evolves in sync with the source code development.


问:
Log design approach
Logging was always a nightmare for me! Now I have to implement it again for a proxy system.
In this proxy application, some systems ask proxy system to call some other services.
What I have to log is

Request Time

Requester IP

Request Parameters as XML

Requested Service Name

Requested Service Method

Response Time

Response data as XML

Response Message (If any exception occurs it will logged as Message)

I considered to append two lines to my methods:

```<code>// Log Request
Task.Factory.StartNew(() => Logger.Log(RequestParameters.ToXML(),Assembly.GetCallingAssembly().FullName, MethodBase.GetCurrentMethod().Name, DateTime.Now));

// Invoke requested service and get response

// Log Response
Task.Factory.StartNew(() => Logger.Log(Response.ToXML(), DateTime.Now));
</code>```

I also want to log nested transactions.

Assume a transaction contains a request and a response. A transaction may contains many other internal transactions. When I receive a request, I should register a transaction, and insert a request for it, later, when response received, I should update the transaction response. Please note that I'm trying to store request and response relationship for better tracking.

How can I safely add this logging procedure to methods? I want to restrict developers to implement this logging systems in all methods, some thing like interface or inheritance for method body is required. Can I do this by attributes? Then how?

答:
To restrict developers to use the logging mechanism for anything they want, make its visibility only internal. You can then make it available only to your own projects by adding the InternalsVisibleTo assembly attribute.

To safely and uniformly add the logging mechanism to methods, implement only the functionality in the methods, and wrap the methods in delegates, somewhat like in the following C# like pseudocode:

```<code>internal Func<RequestParameters, Response> WrapServiceClientWithLogger(Func<RequestParameters, Response> callService)
{
    return requestParameters => {
        // Log Request
        Task.Factory.StartNew(() => Logger.Log(requestParameters.ToXML(),
            Assembly.GetCallingAssembly().FullName, GetMethodName(callService),
            DateTime.Now));

        var response = callService(requestParameters);

        // Log Response
        Task.Factory.StartNew(() => Logger.Log(Response.ToXML(), DateTime.Now));
        return response;
    }
}
</code>```

Title: Log design approach

Body:
To restrict developers to use the logging mechanism for anything they want, make its visibility only internal. You can then make it available only to your own projects by adding the InternalsVisibleTo assembly attribute.

To safely and uniformly add the logging mechanism to methods, implement only the functionality in the methods, and wrap the methods in delegates, somewhat like in the following C# like pseudocode:

internal Func<RequestParameters, Response> WrapServiceClientWithLogger(Func<RequestParameters, Response> callService)
{
    return requestParameters => {
        // Log Request
        Task.Factory.StartNew(() => Logger.Log(requestParameters.ToXML(),
            Assembly.GetCallingAssembly().FullName, GetMethodName(callService),
            DateTime.Now));

        var response = callService(requestParameters);

        // Log Response
        Task.Factory.StartNew(() => Logger.Log(Response.ToXML(), DateTime.Now));
        return response;
    }
}


问:
Is it a good idea to const-qualify the fields of structure in C?
Consider the following program:

```<code>#include <stdlib.h>
#include <stdio.h>

typedef struct S_s {
    const int _a;
} S_t;

S_t *
create_S(void) {
    return calloc(sizeof(S_t), 1);
}

void
destroy_S(S_t *s) {
    free(s);
}

const int
get_S_a(const S_t *s) {
    return s->_a;
}

void
set_S_a(S_t *s, const int a) {
    int *a_p = (int *)&s->_a;
    *a_p = a;
}

int
main(void) {
    S_t s1;
    // s1._a = 5; // Error
    set_S_a(&s1, 5); // OK
    S_t *s2 = create_S();
    // s2->_a = 8; // Error
    set_S_a(s2, 8); // OK

    printf("s1.a == %d\n", get_S_a(&s1));
    printf("s2->a == %d\n", get_S_a(s2));

    destroy_S(s2);
}
</code>```

I'm not aware of anything particularly bad with this kind of design, but there might be impact when compiler is heavily optimizing the code and some considerations I'm missing.

Is it a good idea to use const in C as a mechanism of write access control in such a way?

答:
C 2011 draft

6.7.3 Type qualiﬁers

...

6 If an attempt is made to modify an object deﬁned with a const-qualiﬁed type through use
of an lvalue with non-const-qualiﬁed type, the behavior is undeﬁned. If an attempt is
made to refer to an object deﬁned with a volatile-qualiﬁed type through use of an lvalue
with non-volatile-qualiﬁed type, the behavior is undeﬁned.133)

133) This applies to those objects that behave as if they were deﬁned with qualiﬁed types, even if they are
never actually deﬁned as objects in the program (such as an object at a memory-mapped input/output
address).

Emphasis mine.

So no, this isn't a good idea.  If you don't want anyone directly mucking with the contents of your struct type, make it opaque and provide an API to manipulate it.


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
All output in a PHP script must be echoed line by line.

```<code><?php
echo "<div id=\"foo\">";
echo "<h1>" . $title . "</h1>";
echo paragraphs($body); // just an example
echo "</div>";
?>
</code>```

(Disclaimer: I didn't have to follow it, but a team I worked with did.)

Body:
All output in a PHP script must be echoed line by line.

<?php
echo "<div id=\"foo\">";
echo "<h1>" . $title . "</h1>";
echo paragraphs($body); // just an example
echo "</div>";
?>

(Disclaimer: I didn't have to follow it, but a team I worked with did.)


问:
Do you really have to do BDD/TDD in a test first manner?
Even though I haven't been in a TDD or BDD project, or I have been in some that say they are doing TDD but are pretty far from it, these are things that I think about and really try to read as much as I can about.

Back to the question. When you're doing BDD you should write your "test" first and make it fail, right? And then implement that feature or what you call it. But if you take this to the extreme couldn't this be some kind of top-down development? You're looking at your UI and says, "I would like to have this feature/behavior here". Then you fix your UI to implement that feature and the code that supports the UI. At this point you haven't implemented any business logic or data access logic, you have just implemented your behavior. What I'm aiming at instead of writing the test first you write your UI code first. In some cases it should result in the same code for the data access and business layer, since you use your UI code to define what your business needs to support.

Of course you should complement this with tests that is used to make sure that the feature is working as it should in the feature.

Any thoughts?

答: If you want to work this way, go for it.  But it's not test-driven-development.</p>


问:
Usefulness of "milestones" in agile development
A lot of issue trackers support something called "milestones". I've never found a use for them. It seems that milestones are only useful when you do big, scheduled pushes, but not if you roll out new features and bug fixes as they're completed.

When/how would you use milestones to organize agile development?

答:
Milestones are useful for customer involvement, e.g: When developing a prototype, a milestone will allow the team to know what work items must be completed in order to have a prototype ready for presentation.

It's also useful for evolutionary implementations as well as providing an audit trail of development. In a team I worked in previously, the team leader would fork off of the main repository to keep a version of the product at that specific milestone. This allowed us to show upper management the evolution of the product and to justify budget.


答:
You already answered your own question. "... useful when you do big, scheduled pushes..."

Since you're only doing maintenance and update work then milestones don't make a whole lot of sense.  Except: even when choosing what features to iterate on it's nice to have an overview of where all the features are heading to keep agile development from spiraling out of control and for the project to feel cohesive.

Milestones give a point to measure how well long term goals are being met and a point to stop and consider what direction future iteration should follow.

Title: Usefulness of "milestones" in agile development

Body:
A lot of issue trackers support something called "milestones". I've never found a use for them. It seems that milestones are only useful when you do big, scheduled pushes, but not if you roll out new features and bug fixes as they're completed.

When/how would you use milestones to organize agile development?


答:
Some agile team use them to communicate with the customer when he can expect to have a new version of the software (even if that version is incomplete). This allow the customer to plan the migration to the new version, before it is released.

For example, for a software developped in an agile way and released every 6 month, the following could be the milestones.

Alpha 1 - December 19th

The first set of feature arriving, usually buggy. This is useful for trying them out and giving feedback

Alpha 2 – January 23rd

Next set of features, plus some fixes for the feedback in Alpha

Beta 1 – February 27th

All the feature for the current version are there, and no one will be added until the final release. New development will be in the next version. You can still suggest some small tweak to existing one though.

Final Beta – March 27th

The behavior of the feature is completely frozen, unless a critical flaw is found. Only bug will be fixed.

Release Candidate – April 10th

The final version to be released. No bug are supposed to be found here. If some are found, a new release candidate is created.

Final Release - April 17th

The supported version is released to the general public, since no bug have been found the release candidate

(Note : I didn't follow exactly the ubuntu semantic here)

With that release plan in hand, a customer can plan ahead. If a new feature is really expected, he can test it during the alpha stage to ensure that it fit what is required. Programmers can start experimenting with the new feature during the beta stage. Regression testing can start during the release candidate stage.

Knowing when the software will be released and what will it contain is hugely important for a lot of user. Using milestone, you can know what is going to happen and when. The agile mindset is still there, manifested by the fact that before a certain date the feature set is variable. This is unlike the waterfall way, where you plan both the features and the release date. And of course the next version isn't set, again unlike the waterfall method.

So to answer your question : In agile, milestone are used to indicate when important decision and action are going to be taken, even if those actions and decision themselves can change.


答: What you describe sounds much like the Front-Ahead Design approach. Unfortunately, Front-Ahead Design is Alex Papadimoulis' satirical stab at agile methods.</p>

Title: Do you really have to do BDD/TDD in a test first manner?

Body:
Even though I haven't been in a TDD or BDD project, or I have been in some that say they are doing TDD but are pretty far from it, these are things that I think about and really try to read as much as I can about.

Back to the question. When you're doing BDD you should write your "test" first and make it fail, right? And then implement that feature or what you call it. But if you take this to the extreme couldn't this be some kind of top-down development? You're looking at your UI and says, "I would like to have this feature/behavior here". Then you fix your UI to implement that feature and the code that supports the UI. At this point you haven't implemented any business logic or data access logic, you have just implemented your behavior. What I'm aiming at instead of writing the test first you write your UI code first. In some cases it should result in the same code for the data access and business layer, since you use your UI code to define what your business needs to support.

Of course you should complement this with tests that is used to make sure that the feature is working as it should in the feature.

Any thoughts?


问:
Sentence Tree vs. Words List
I was recently tasked with building a Name Entity Recognizer as part of a project. The objective was to parse a given sentence and come up with all the possible combinations of the entities.

One approach that was suggested was to keep a lookup table for all the known connector words like articles and conjunctions, remove them from the words list after splitting the sentence on the basis of the spaces. This would leave out the Name Entities in the sentence.

A lookup is then done for these identified entities on another lookup table that associates them to the entity type, for example if the sentence was: Remember the Titans was a movie directed by Boaz Yakin, the possible outputs would be:

 {Remember the Titans,Movie} was {a movie,Movie} directed by {Boaz
  Yakin,director}
 {Remember the Titans,Movie} was a movie directed
  by Boaz Yakin
 {Remember the Titans,Movie} was {a movie,Movie}
  directed by Boaz Yakin
 {Remember the Titans,Movie} was a movie
  directed by {Boaz Yakin,director}
 Remember the Titans was {a
  movie,Movie} directed by Boaz Yakin
 Remember the Titans was {a
  movie,Movie} directed by {Boaz Yakin,director}
 Remember the
  Titans was a movie directed by {Boaz Yakin,director}
 Remember the
  {the titans,Movie,Sports Team} was {a movie,Movie} directed by {Boaz
  Yakin,director}
 Remember the {the titans,Movie,Sports Team} was a
  movie directed by Boaz Yakin
 Remember the {the
  titans,Movie,Sports Team} was {a movie,Movie} directed by Boaz
  Yakin
 Remember the {the titans,Movie,Sports Team} was a movie
  directed by {Boaz Yakin,director}

The entity lookup table here would contain the following data:

Remember the Titans=>Movie
 a movie=>Movie
 Boaz
  Yakin=>director
 the Titans=>Movie
 the Titans=>Sports
  Team

Another alternative logic that was put forward was to build a crude sentence tree that would contain the connector words in the lookup table as parent nodes and do a lookup in the entity table for the leaf node that might contain the entities. The tree that was built for the sentence above would be:

The question I am faced with is the benefits of the two approaches, should I be going for the tree approach to represent the sentence parsing, since it provides a more semantic structure? Is there a better approach I should be going for solving it?

答:
Unless you have an extensive background in natural language processing, I might use an existing library versus rolling your own named-entity recognizer. Even if you're an NLP expert, a heavily-used library will likely have many more testing hours committed to it than your new recognizer. In addition, existing libraries are likely to be more flexible since they're used in diverse projects. Be aware that some libraries have restricted licenses for commercial projects.

It's not clear how your first approach would work since articles, conjunctions, and other "connector" words are often part of named entities. Splitting (tokenizing) the sentence on white space is also error-prone since many named entities contain more than one word (New York, Remember the Titans, For Whom the Bell Tolls...). Finally, if you're using a lookup table to determine which non-connector words are named entities, you'll have many false positives as shown in chapter 7.5 of Natural Language Processing with Python.

I think your second approach is a step in the right direction, though it also suffers from the aforementioned limitations. You do need a tree, but you need a tree that represents all parts of speech. As an example, the default NLTK named entity chunker gives you a rich tree:

```<code>sentence = "Remember the Titans was a movie by Boaz Yakin."
tokens = nltk.word_tokenize(sentence)
pos_tags = nltk.pos_tag(tokens)
print(nltk.ne_chunk(pos_tags))

# output:

(S
  Remember/NNP
  the/DT
  Titans/NNPS
  was/VBD
  a/DT
  movie/NN
  by/IN
  (PERSON Boaz/NNP Yakin/NNP)
  ./.)
</code>```

Of course, NLTK's default named entity chunker missed "Remember the Titans" as a single named entity (though it did recognize "Boaz Yakin"). This brings up the hardest part of named entity recognition. Even with a rich and well-tested library, you'll need to train your named entity recognizer with data that best fits your data. (NLTK's default named entity chunker is trained on the ACE corpus.) If you're interested, Matt Johnson takes a closer look at the default NLTK named entity chunker in Lifting the hood on NLTK's NE chunker.

Title: Sentence Tree vs. Words List

Body:
Unless you have an extensive background in natural language processing, I might use an existing library versus rolling your own named-entity recognizer. Even if you're an NLP expert, a heavily-used library will likely have many more testing hours committed to it than your new recognizer. In addition, existing libraries are likely to be more flexible since they're used in diverse projects. Be aware that some libraries have restricted licenses for commercial projects.

It's not clear how your first approach would work since articles, conjunctions, and other "connector" words are often part of named entities. Splitting (tokenizing) the sentence on white space is also error-prone since many named entities contain more than one word (New York, Remember the Titans, For Whom the Bell Tolls...). Finally, if you're using a lookup table to determine which non-connector words are named entities, you'll have many false positives as shown in chapter 7.5 of Natural Language Processing with Python.

I think your second approach is a step in the right direction, though it also suffers from the aforementioned limitations. You do need a tree, but you need a tree that represents all parts of speech. As an example, the default NLTK named entity chunker gives you a rich tree:

sentence = "Remember the Titans was a movie by Boaz Yakin."
tokens = nltk.word_tokenize(sentence)
pos_tags = nltk.pos_tag(tokens)
print(nltk.ne_chunk(pos_tags))

# output:

(S
  Remember/NNP
  the/DT
  Titans/NNPS
  was/VBD
  a/DT
  movie/NN
  by/IN
  (PERSON Boaz/NNP Yakin/NNP)
  ./.)

Of course, NLTK's default named entity chunker missed "Remember the Titans" as a single named entity (though it did recognize "Boaz Yakin"). This brings up the hardest part of named entity recognition. Even with a rich and well-tested library, you'll need to train your named entity recognizer with data that best fits your data. (NLTK's default named entity chunker is trained on the ACE corpus.) If you're interested, Matt Johnson takes a closer look at the default NLTK named entity chunker in Lifting the hood on NLTK's NE chunker.


答:
Every Feature is a milestone, by definition

an action or event marking a significant change or stage in development

The usefulness of tracking individual or groups of milestones for your project and your team and your customer is primarily a matter of taste/style

Some teams/customers like checking off milestones every day or so, others are content to do so less frequently

ADDENDUM: The key word is 'significant' - which is subjective. Your milestones may vary. :)


答:
Personally, I believe that it is critical to think about testing during the design stage. Its really great having a working implementation, but the only way you can be sure that you have a working product is if you have tested it piece by piece.  The way to cover this is by a combination of Unit tests and a skilled QA team working in partnership.

Now how you install this dicipline into your team is up to you.  TDD is one such strategy - and one that has its place, and there are plenty of other variations. However, TDD is not particularly suited to developing UI layout.


问:
Confused about ASP.NET Ajax, jQuery and JavaScript
Yesterday, I read couple of chapters on ASP.NET Ajax and jQuery from my ASP.NET 4 book and I found those frameworks pretty interesting and decide to learn more about them.

Today, I borrowed some books from library on Ajax and JavaScript. It seems ASP.NET Ajax is different from Ajax and jQuery seems like the "new" JavaScript.

Does it mean that I can skip JavaScript and learn jQuery directly?

On the other hand, the non-ASP.NET Ajax book I borrowed seems to apply to the client side web programming only and looks quite different from what I learned from ASP.NET Ajax. If I'm an ASP.NET developer, I guess I should stick with ASP.NET Ajax instead of client side Ajax right? What about PHP? Is there a "PHP Ajax" similar to ASP.NET Ajax?

It's not that I'm lazy to learn other tools, but I just want to focus on the right ones.

答:
JavaScript is a client side interpreted language that gives you control over browser page components; i.e. the HTML document and also the browser it self. jQuery is a library of cross browser JavaScript functions that makes it easier to interact with the DOM.

ASP.NET and PHP are both server side scripting languages, where as an ASP.NET built page is compiled into a .NET assembly DLL, by the ASP.NET JIT (Just In Time) Compiler, a page built in PHP is interpreted.

Technically, ASP.NET is not really a language, it's a framework and a run time, that exposes APIs that can be accessed using C# or VB.NET. Thus to develop ASP.NET apps, you need to know either C# or VB.NET.

From my experience, I will advice that you take out the time and learn JavaScript, then proceed to learning jQuery. Off course you could also do cross learning, i.e both jQuery and core JavaScript.

AJAX is a client side asynchronous programming technology, that can be used in both jQuery and ASP.NET AJAX. ASP.NET AJAX is Microsoft's implementation of the AJAX technology.


答:
When you start a development project - regardless of the methodology -, you should always have a rough plan you are following, about the "must-have" features, core features, "really-important" features you want to develop, and in which order. Ideally you also have a vision about the realization time. Writing down this plan in form of milestones makes this transparent for anyone involved in the project.

In any kind of real project, this plan has to be adapted to reality from time to time. Maybe one has to reassign features to different milestones, sometimes one identifies things as less important as thought to be beforehand, sometimes one has to add some missing requirements/features to your development plan, and sometimes one may have to change the list of milestones itself. IMHO the main difference between a "waterfall" and a "agile" project is that in an agile project you are honest to the customer about the need for adaption from day 1. In waterfall projects, you have no built-in mechanisms to change the plan before the product is "ready" (and probably faulty). In agile projects, it is an explicit duty of the customer to help the development team to adapt the plan to reality - continuously throughout the whole project, every week or even more often.

There is also a difference at which time you analyse the gory details of the requirements for any milestone. Waterfall projects tend to over-analyse every feature of each milestone beforehand, in agile projects you will typically analyse only one feature of the next milestone in-depth.

So I would say especially in agile projects a milestone plan helps the stakeholders to understand that the development is not completely arbitrary or random, and that you still follow an overall plan.

A different question is if you need the "milestones" feature from your issue tracker. A milestone plan is typically just a document in your favorite document format, so you can easily show it to any stakeholder of your project. You have to decide for yourself if it brings you any benefit to put the milestones into your issue tracking system, or if you prefer to maintain it in a completely different way.


问:
Open Close Principle (OCP) vs Dependency Inversion Principle (DIP)
I was trying to understand the difference between Open Closed Principle (OCP) and Dependency Inversion Princible (DIP).

Based on research I've made on the internet so far, I came to the conclusion that 'DIP is one option through which we can achieve OCP'.

I'm I right on this?

Can you give me an example which doesn't follow DIP but follows OCP ?

答:
I wrote an answer previously on Open-Closed Principle (OCP) vs Liskov's Substitution Principle (LSP) and both those principles relate to each other a lot, but are still conceptually different with some contrived examples of having one but not the other. Because of this answer I'll only touch on OCP briefly and dwelve deeper into DIP and what makes that tick.

Lets try discussing how OCP relates and differs with Dependency Inversion Principle (DIP) by first explaining the different principles first.

Dependency Inversion Principle

Reading Uncle Bob's Principles of OOD you'll find that DIP states the following:

Depend on abstractions, not on concretions.

An abstraction in Java is simply achieved with interface and abstract keywords, meaning you have a "contract" for some software entity that the code has to follow. Some programming languages do not have a facility to explicitly set behaviors for the code to follow so abstractions have to be followed in a more manual fashion rather than having the compiler help you enforce the contract. E.g. in C++ you have classes with virtual methods, and dynamic programming languages such as Javascript you have to make sure you use objects the same way (though in the case of Javascript this has been extended in TypeScript that adds a type system to help you out with writing contracts that is verified by the compiler).

The name includes the term "inversion" because traditionally (y'know in the old dark ages of programming) you wrote software structures that had higher level modules depending on low level modules. E.g. it made sense to have a ButtonAtKitchen handling inputs for a KitchenLamp1 and KitchenLamp2. Unfortunately that made software a lot more specific than it needed to be and the object graph would look like this:

So when you make the software more general, by adding "contracts". Notice how the arrows in the object graph "inverts" the direction. That kitchen lamps are now dependent on a Button. In other words the details are now dependent on abstractions instead of the other way around.

Thus we have a more general definition of DIP, also detailed in the original article of DIP by Uncle Bob.

A. High level modules should not depend on low level modules. Both should depend on abstraction.
  B. Abstractions should not depend upon details. Details should depend on abstractions.

Open-Closed Principle

Continued from Uncle Bob's principles you'll find that OCP states the following:

You should be able to extend a classes behavior, without modifying it.

One example of achieving this is to employ the Strategy pattern where a Context class is closed for modifications (i.e. you can't change it's internal code at all) but is also open for extension through it's collaborating dependencies (i.e. the strategy classes).

In a more general sense any module is built to be extensible through it's extension points.

OCP is similar to DIP, right?

No, not really.

Although they both are discussing abstractions they're conceptually different. Both principles are looking at different contexts, OCP on one particular module and DIP on several modules. You can achieve both at the same time as with most Gang of Four design patterns, but you can still steer away from the path.

In the DIP example mentioned above, with the button and kitchen lamps, none of the kitchen lamps are extensible (nor currently has any requirement explaining they need to be). The design is breaking OCP but follows DIP.

A reverse (and a contrived) example would be a kitchen lamp be extensible (with the extension point being something like a LampShade) but the button is still dependent on the lamps. It is breaking DIP but follows OCP.

Don't worry, it happens

This is actually something you'll see happen often in production code, that some part of it may break a principle. In larger software systems (i.e. anything larger than the examples above), you might break one principle but keeping the other usually because you need to keep the code simple. This is, in my mind, okay for small and self-contained modules, as they are in the context related to Single Responsibility Principle (SRP).

Once some module becomes complicated though you most likely need to look at it with all principles in mind and redesign or refactor it to some well-known pattern.


答:
I think the purpose of milestone to see big picture of release/feature candidate program/app (or anything else which team develop).

It could be useful for developers/workers:

I can imagine an issue tracking system with many task, bugfix, feature etc. It has milestone field. I think if your team has two milestone and only one prefer your customer, that your team start do these task, or fix these bugs or develop these features which are marked with this milestone.

It could be helpful for managers:

That is very important thing which release will be release to production environment of customer. In this case the milestone is release to production environment. But the milestone could be mark off package of features.

It could be helpful for customer:

May be, the customer want to show this program, or programs bugfixed version, or new features of program for another person/organization.  So, the customer need stable version of program. I think when program achieve this milestone It would be stable and releasable.

If the customer, managers and workers checks bugs, taks and features in issue tracker, I think It betters know milestone of them.


问:
Does Open Source lead to bad coding?
I have a thought that I tried asking at SO, but didnt seem like the appropriate place. I think that source sites like Google Code, GitHub, SourceForge... have played a major role in the history of programming. However, I found that there is another bad thing to these kind of sites and that is you may just "copy" code from almost anyone, not knowing if it is good(tested) source or not.

This line of thought has taken me to believe that source code websites tend to lead many developers (most likely unexperienced) to copy/paste massive amounts of code, which I find just wrong.

I really dont know how to focus the question well, but basic thought would be:

Is this ok? Is Open Source contributing to that or I'm just seeing ghosts...

Hope people get interested because I think this is an important theme.

答:
This question is impossible to answer.

However, if you are asking with respect to yourself, e.g. "does the presence of freely available code that solves problems that I'm dealing with make me a sloppier or worse developer," then there's a very simple and collaborative solution to your anxiety.

Find a project that you use, support, or find interesting, and see if you can involve yourself with it. Write some code, write some test cases, or provide some documentation. Whatever you end up doing, you'll be working with and evaluating the code you're using, and helping out a project you support.

Title: Does Open Source lead to bad coding?


问:
Support Vector Machines as Neural Nets?
This is more of a conceptual question.

I have learned about Neural Nets, and I have some clue as to how Support Vector Machines work. I read somewhere however that given the appropriate kernel (is that right?), the SVM is identical to the Neural Net. Could someone who understands this please enlighten me as to how that's possible?

答:
Context

two-layer neuronal networks and svms do linear classification = splitting good vectors into bad vectors by putting a line or flat layer between them which has one dimension less than the vector space. (line in 2d space; dot onto line).

When you have three layer neuronal networks they can classify the XOR (in a,b out a xor b).
So you can classify xor by chaining two linear classifiers.
From my point of view you can do this because you can train chained networks.

Hunch:
Because you usually do not train chained SVMs, YOU must provide the first classifiers that do the same job as the first neuronal networks.

Example:
In case of xor where you have the input vectors (a, b) for a three layer network,
you would not pass the (a, b) kernel to the svm because the space is not linearly separable. you would pass (a, b, not a, not b) which means thet you expand the kernel.
This way the SVM is as 'identical' to the neuronal network.

Title: Support Vector Machines as Neural Nets?


问:
Should db be mapped directly to the UI or should there be multiple layers of enties/models with mappings to/from each?
I would like to know arguments for/against this concept.

Technologies in use from the bottom up:

MSSQL 2012 DB (exclusively accessed via sprocs)

Entity Framework

WCF Web Service

ASP.NET Webforms

Someone on my team would like to use Entity Framework to map the sprocs to ComplexTypes, and then use those ComplexTypes as DTOs, eventually using them as a view model to display on the page.  His argument is that it's the fastest/easiest way and we'll get noticeable/valued changes more quickly.  Also, he does not like the idea of the numerous mappings that would be necessary to go from DB -> Entity -> DTO -> ViewModel.

Another consideration is, the majority of things from the DB are going one direction (db -> web), with only a few things actually needing to be changed on the UI and saved/persisted to the DB.

To scope this question, there are thousands of previously existing sprocs written against poorly designed database structure (think tables that are 276 columns wide and single rows actually contain multiple entities).  The poor structure isn't about to change soon because there are over 200 legacy apps written on top of it.

答:
Since your database is poorly designed, and you have a high legacy code base, ANY new project should employ as much abstraction as practical.  You will eventually want to replace that ugly database design with proper normalization, and replicate the existing lousy structure with a compatibility model.

Entity Framework itself may not be useful, but at least one layer of abstraction is appropriate and, if you're professional, necessary.


问:
Does immutability entirely eliminate the need for locks in multi-processor programming?

Part 1

Clearly Immutability minimizes the need for locks in multi-processor programming, but does it eliminate that need, or are there instances where immutability alone is not enough?  It seems to me that you can only defer processing and encapsulate state so long before most programs have to actually DO something (update a data store, produce a report, throw an exception, etc.).  Can such actions always be done without locks?  Does the mere action of throwing out each object and creating a new one instead of changing the original (a crude view of immutability) provide absolute protection from inter-process contention, or are there corner cases which still require locking?

I know a lot of functional programmers and mathematicians like to talk about "no side effects" but in the "real world" everything has a side effect, even if it's the time it takes to execute a machine instruction.  I'm interested in both the theoretical/academic answer and the practical/real-world answer.

If immutability is safe, given certain bounds or assumptions, I want to know what the borders of the "safety zone" are exactly.  Some examples of possible boundaries:

I/O

Exceptions/errors

Interactions with programs written in other languages

Interactions with other machines (physical, virtual, or theoretical)

Special thanks to @JimmaHoffa for his comment which started this question!

Part 2

Multi-processor programming is often used as an optimization technique - to make some code run faster.  When is it faster to use locks vs. immutable objects?

Given the limits set out in Amdahl's Law, when can you achieve better over-all performance (with or without the garbage collector taken into account) with immutable objects vs. locking mutable ones?

Summary

I'm combining these two questions into one to try to get at where the bounding box is for Immutability as a solution to threading problems.

答:
Encapsulating a bunch of related state in a single mutable reference to an immutable object can make it possible for many kinds of state modification to be performed lock-free using the pattern:

```<code>do
{
   oldState = someObject.State;
   newState = oldState.WithSomeChanges();
} while (Interlocked.CompareExchange(ref someObject.State, newState, oldState) != oldState;
</code>```

If two threads both try to update someObject.state simultaneously, both objects will read the old state and determine what the new state would be without each other's changes.  The first thread to execute the CompareExchange will store what it thinks the next state should be.  The second thread will find that the state no longer matches what it had previously read, and will thus re-compute the proper next state of the system with the first thread's changes taken into effect.

This pattern has the advantage that a thread which gets waylaid cannot block the progress of other threads.  It has the further advantage that even when there is heavy contention, some thread will always be making progress.  It has the disadvantage, though, that in the presence of contention a lot of threads may spend a lot of time doing work which they will end up discarding.  For example, if 30 threads on separate CPUs all try to change an object simultaneously, the one will succeed on its first attempt, one on its second, one on its third, etc. so that each thread ends up on average making about 15 attempts to update its data.  Using an "advisory" lock can improve things significantly: before a thread attempts an update, it should check whether a "contention" indicator is set.  If so, it should acquire a lock before doing the update.  If a thread makes a few unsuccessful attempts at an update, it should set the contention flag.  If a thread which tries to acquire the lock finds there was nobody else waiting, it should clear the contention flag.  Note that the lock here is not required for "correctness"; code would work correctly even without it.  The purpose of the lock is to minimize the amount of time code spends on operations which are not likely to succeed.

Body:
Encapsulating a bunch of related state in a single mutable reference to an immutable object can make it possible for many kinds of state modification to be performed lock-free using the pattern:

do
{
   oldState = someObject.State;
   newState = oldState.WithSomeChanges();
} while (Interlocked.CompareExchange(ref someObject.State, newState, oldState) != oldState;

If two threads both try to update someObject.state simultaneously, both objects will read the old state and determine what the new state would be without each other's changes.  The first thread to execute the CompareExchange will store what it thinks the next state should be.  The second thread will find that the state no longer matches what it had previously read, and will thus re-compute the proper next state of the system with the first thread's changes taken into effect.

This pattern has the advantage that a thread which gets waylaid cannot block the progress of other threads.  It has the further advantage that even when there is heavy contention, some thread will always be making progress.  It has the disadvantage, though, that in the presence of contention a lot of threads may spend a lot of time doing work which they will end up discarding.  For example, if 30 threads on separate CPUs all try to change an object simultaneously, the one will succeed on its first attempt, one on its second, one on its third, etc. so that each thread ends up on average making about 15 attempts to update its data.  Using an "advisory" lock can improve things significantly: before a thread attempts an update, it should check whether a "contention" indicator is set.  If so, it should acquire a lock before doing the update.  If a thread makes a few unsuccessful attempts at an update, it should set the contention flag.  If a thread which tries to acquire the lock finds there was nobody else waiting, it should clear the contention flag.  Note that the lock here is not required for "correctness"; code would work correctly even without it.  The purpose of the lock is to minimize the amount of time code spends on operations which are not likely to succeed.


问:
What is the difference between a macro and a script?
Aren't both just a set of instructions that get executed by some interpreter? (contrary to a full-fledged program, which runs (gets executed) at some computer system?</p>

答: Basically the difference is just one of degree.  A script tends to be a lot more formally defined, with a well-defined scripting language behind it, while a macro is usually something more simple and ad-hoc.  Macros are frequently "recorded" by telling a program "watch everything that I do" and then performing the action, whereas scripts are generally entered as text in the scripting language.</p>

ContentLicense: CC BY-SA 4.0


答:
Macros come in different flavors.

The original kind was macros in assembly language, where a group of instructions could be named and each time the name was used the instructions were substituted for the name.

C and C++ also have macros that work this way.

But as with most things in IT, why have one term or one meaning when we can make things more confusing? So some environments (starting with MS Word, I believe) introduced "macros" that were a recorded set of actions.

So there are two kinds of macro. The first gets substituted for the name and then compiled. The second is usually interpreted at runtime by the environment.

Title: What is the difference between a macro and a script?

Body: Aren't both just a set of instructions that get executed by some interpreter? (contrary to a full-fledged program, which runs (gets executed) at some computer system?</p>


问:
Gradual Typing: "Almost every language with a static type system also has a dynamic type system"
This claim by Aleks Bromfield states:

Almost every language with a static type system also has a dynamic type system. Aside from C, I can't think of an exception

Is this a valid claim? I understand that with Reflection or Loading classes at runtime Java gets a bit like this - but can this idea of 'gradual typing' be extended to a large number of languages?

答:
Well yes. You can have property bags in any statically typed language. The syntax will be terrible while at the same time you will gain all the disadvantages of dynamically typed system. So there is not really any advantage unless compiler allows you to use nicer syntax, something like C# with dynamic is doing.

Also, you can do that pretty easily in C too.

In reaction to other answers: I think people are mistaking static/dynamic typing with strong/weak typing. Dynamic typing is about being able to change the structure of data at runtime and code being able to used data that just fits what the code needs. This is called Duck Typing.

Mentioning reflection is not telling the whole story, because reflection does not allow you to change existing structure of data. You cannot add new field to a class or structure in either C, C++, Java or C#. In dynamic languages, adding new fields or attributes to existing classes is not only possible, but actually quite common.

For example, look at Cython, the Python-to-C compiler. It creates static C code, but the type system still retains it's dynamic nature. C is statically typed language, yet it is able to support dynamic typing from Python.


答:
Static vs. Dynamic typing basically refers on to how types are checked. Static typing means that the verification of the types of various variables or expressions are checked based on the actual code (usually by the compiler) while in a dynamic type system this verification is performed only at runtime, by the runtime environment.

What I believe the text is referring is that even if the types are actually checked statically, they are also checked at runtime, i.e. dynamically. You correctly mentioned Java Reflection; reflection only happens at runtime and the Java Runtime Environment (JVM) actually performs type checking when reflection is used, which basically means dynamic type checking.

Title: Gradual Typing: "Almost every language with a static type system also has a dynamic type system"

Body:
This claim by Aleks Bromfield states:

Almost every language with a static type system also has a dynamic type system. Aside from C, I can't think of an exception

Is this a valid claim? I understand that with Reflection or Loading classes at runtime Java gets a bit like this - but can this idea of 'gradual typing' be extended to a large number of languages?


答:
The difference between static and dynamic typing is when the type of a value is checked: compile time vs. run time. In languages where values carry their type with them (e.g. Java objects), then you can always resort to dynamic typing even when the language actually prefers static typing. Here is an example in Java, with a dynamically typed method:

```<code>void horribleJava(List untypedList) {
  for (Object o : untypedList)
    ((SpecificType) o).frobnicate();
}
</code>```

Notice how the type of each item is checked at runtime. The equivalent statically typed method is:

```<code>void goodJava(List<SpecificType> typedList) {
  for (SpecificType o : typedList) {
    o.forbnicate();
  }
}
</code>```

In C, values (and specifically pointers) do not retain their type during runtime – every pointer is equivalent to a void *. Instead, variables and expressions have a type. To achieve dynamic typing, you have to carry around the type information yourself (e.g. as a field in a struct).

Body:
The difference between static and dynamic typing is when the type of a value is checked: compile time vs. run time. In languages where values carry their type with them (e.g. Java objects), then you can always resort to dynamic typing even when the language actually prefers static typing. Here is an example in Java, with a dynamically typed method:

void horribleJava(List untypedList) {
  for (Object o : untypedList)
    ((SpecificType) o).frobnicate();
}

Notice how the type of each item is checked at runtime. The equivalent statically typed method is:

void goodJava(List<SpecificType> typedList) {
  for (SpecificType o : typedList) {
    o.forbnicate();
  }
}

In C, values (and specifically pointers) do not retain their type during runtime – every pointer is equivalent to a void *. Instead, variables and expressions have a type. To achieve dynamic typing, you have to carry around the type information yourself (e.g. as a field in a struct).


答:
Macro

The common usage of macros is in software applications, and they originated as a tool to map user input to a different set of user output. The key aspect here is the changing of user input/output at the application level. Since user input tends to be related to keyboards, mouse and other devices. The output changed by the macro was often previously recorded by one of those devices. There are also macros that can be written by the user but the goal is often to yield a desired output.

Script

If macros are to application output, then scripts are to application automation. Scripts are often an application specific programming language that automate tasks for the user. The key here is the role of the user as a programmer, and the fact that users are not programmers. If you categorize scripting languages as those that don't compile, are parsed and easy to use then there are many languages that fit those requirements. I argue that scripting languages are the ones easiest for application users to automate the software with the least amount of programming knowledge. That is how they should be categorized as scripts. Anything that requires specialized knowledge outside the domain of the application is just programming tool.


问:
Are there alternatives to stack+heap+static memory model?
All programs I have seen organize their data memory into one or more call stacks (usually fixed size, but sometimes not), the heap, and static memory.  Lately thread-local static storage has been added to this as well.

Have there been any attempts to organize data memory layout in a radically different way, e.g. without the call stack?  Or organize memory in a different way that accomplishes the same thing?

答:
The only cases I can think of are in specialised hardware where you might have everything running in fixed locations in memory. Pretty much everything in the current memory model is required if you want fully flexible programs.

Without the stack you can't have local variables, call stacks, etc. Anything else you write to implement that is going to end up looking a lot like the stack.

Static memory and the heap you could potentially drop for certain applications, but again you are going to need them back in some form or other to do anything more advanced.

So anything you invent to replace one of these three is going to end up looking a lot like one of these three in the end...

To approach it from the other angle, what might you add that is new? You could potentially argue things like graphics/physics processors/cpu caches/etc are a new memory location, but really they are just a separate instance of or a way of speeding up access to the existing models.

...so until someone comes up with a giant conceptual leap of some kind I think we are unlikely to see any major changes in this area for a long time...


问:
An alternative to having fields that might not be used in a class
I'm writing a card/ board game in Java.  Since the game has lots of cards that interact in different ways, my Player class has become sort of bloated with all these different fields used for keeping track of data that specific cards need.  However, not every card is used in every game, so many of these fields are not used.  Instead of having several fields that probably won't be used a majority of the time, I was thinking of writing sort of a field map class that could dynamically "create" fields when they were needed.  If one type of card required each player to store some data in a List, it could just create one and store it in that player's field map.  It could get a little messy, though: what types of keys should I use?  Strings?  Just plain Objects?  And the type of data won't always be a List, so it would probably have to be Map<String, Object>, and I would have to put in casts.  Should the keys be their own class whose identity is based on a String name, but also contain a Class<?> field, so that it could cast the result for me?

I kind of like this idea, since it means I don't have to mess with the Player class every time I make a new card, but it also seems kind of inefficient and inelegant.  Is this a terrible idea?

答:
Typically, you would solve this using inheritance.  You would have a Card parent class, with derived classes with specific fields for specific games.  This lets you use collections of Cards in generic code that is reusable across different games, but still gives you the type safety of the compiler in game-specific code.

The second thing to consider is that the fields might not actually be appropriate to the Card class, but actually fit better in another class.  For example, in "Hearts" the Queen of Spades has somewhat special behavior compared to other cards, but you could check for that behavior in the game's logic rather than the Card class.

If you really can't think of a way to use inheritance, I still would put something like a Map<Card, Integer> points in a specific game's class before considering putting a generic Map<String, Object> into a Card class.  Always calculating a String key, then casting the result value to the appropriate class would get tedious and error prone.


问:
Breaking the "ubiquitous language" by having an IoC Container in Domain Model?
I am a bit new to DDD and bear with me if my understanding seems way off.

My question is about Udi's solution to domain events, particularly the class DomainEvents (see code below)

An excerpt from Udi's code. It lives domain model as a static class.

```<code>public static class DomainEvents
{
   [ThreadStatic] //so that each thread has its own callbacks
   private static List<Delegate> actions;

   public static IContainer Container { get; set; } //as before

   //Registers a callback for the given domain event
   public static void Register<T>(Action<T> callback) where T : IDomainEvent
   {
      if (actions == null)
         actions = new List<Delegate>();

      actions.Add(callback);
  }

  //Clears callbacks passed to Register on the current thread
  public static void ClearCallbacks ()
  {
      actions = null;
  }

  //Raises the given domain event
  public static void Raise<T>(T args) where T : IDomainEvent
  {
     if (Container != null)
        foreach(var handler in Container.ResolveAll<Handles<T>>())
           handler.Handle(args);

     if (actions != null)
         foreach (var action in actions)
             if (action is Action<T>)
                 ((Action<T>)action)(args);
  }
}
</code>```

Based on the code above, in order for the DomainEvents to be used by the domain model, both must first be in the same assembly. Which makes the DomainEvents part of the domain model right? (I may be wrong here)

So my question is: Does DomainEvents itself breaks the rule "ubiquitous language of DDD"? Because it's implementation does not pertain to any domain.

My other concern is that the static member IContainer creates an ioc-container-dependency in the domain model. Though I am not really sure if Udi's IContainer is an interface or an actual IoC container.

My 2nd question is: What is this IContainer in the DomainEvents class? If it is truly an IoC container then doesn't it break the rule of "DDD should not have an infrastructure in the domain"? Is my understanding correct that an IoC-Container is considered an infrastructure? (Please correct me if I'm wrong)

If you may find any of this confusing, please say so.

EDIT:

I have built my projects where the domain model is separated on its own assembly (I call this business layer) with absolutely no references to any infrastructure components. See onion architecture.

Now I want to incorporate the domain events pattern. But doing so forces me to add infrastructure components to my business layer. Components being the DomainEvents and an IoC framework just to satisfy the IContainer, both having no relation to the domain whatsoever.

Isn't one of the idea of DDD is about separating the infrastructure from the domain?

Now I will play the pragmatic programmer, I just wanted to know that is it generally ok to do so? are there alternatives? What are you thoughts on this approach? Am I missing something basic here?

答:
The DomainEvents isn't part of the domain model, it's an infrastructure component used to support loosely-coupled domain models.

The container isn't strictly required (which is why the code as written allows it to be null), it just allows a declarative rather than imperative style of registering handles.

In other words, you can use it either like this:

```<code>public SomeClass()
{
    DomainEvents.Register<SomethingHappened>(() => RespondToSomething());

    void RespondToSomething() { ... }
}
</code>```

Or like this:

```<code>public class SomeHandler : Handles<SomethingHappened>
{
    public void Handle(SomethingHappened e) { ... }
}
</code>```

Both accomplish more or less the same thing, but the first version requires an instance to exist before the event is published. Each version has its place; the first version tends to be more useful in rich client applications, where it is essentially the well-known Event Broker pattern, and the second version is more useful in service applications, where in Udi's world the pattern is now actually formalized as the In-Memory Bus and is not a whole lot more than a generic in-process, non-durable message.

And yes, IContainer is in fact the IoC container, but again, this is an infrastructure component, nothing in the domain model itself depends on the container.

I'm not sure what you mean when you refer to "break[ing] the rule of not having infrastructure in the domain" - I'm not familiar with this rule, but even if you want to follow it, sometimes purity really needs to take a back seat to pragmatism. If the end result is collapsing 10 dependencies down into 1 dependency without a wrapper, that's a win, regardless of what architecture you're trying to follow.

Body:
The DomainEvents isn't part of the domain model, it's an infrastructure component used to support loosely-coupled domain models.

The container isn't strictly required (which is why the code as written allows it to be null), it just allows a declarative rather than imperative style of registering handles.

In other words, you can use it either like this:

public SomeClass()
{
    DomainEvents.Register<SomethingHappened>(() => RespondToSomething());

    void RespondToSomething() { ... }
}

Or like this:

public class SomeHandler : Handles<SomethingHappened>
{
    public void Handle(SomethingHappened e) { ... }
}

Both accomplish more or less the same thing, but the first version requires an instance to exist before the event is published. Each version has its place; the first version tends to be more useful in rich client applications, where it is essentially the well-known Event Broker pattern, and the second version is more useful in service applications, where in Udi's world the pattern is now actually formalized as the In-Memory Bus and is not a whole lot more than a generic in-process, non-durable message.

And yes, IContainer is in fact the IoC container, but again, this is an infrastructure component, nothing in the domain model itself depends on the container.

I'm not sure what you mean when you refer to "break[ing] the rule of not having infrastructure in the domain" - I'm not familiar with this rule, but even if you want to follow it, sometimes purity really needs to take a back seat to pragmatism. If the end result is collapsing 10 dependencies down into 1 dependency without a wrapper, that's a win, regardless of what architecture you're trying to follow.


问:
Why did Java make package access default?
I'm asking this question because I believe they did it for a very good reason and that most people do not use it properly, well from my experience in industry so far anyway.
But if my theory is true then I'm not sure why they included the private access modifier...?

I believe that if default access is properly used it provides enhanced testability whilst maintaining encapsulation. And it also renders the private access modifier redundant.

The default access modifier can be used to provide the same affect by using a unique package for methods that need to be hidden from the rest of the world, and it does this without compromising testability, as packages in a test folder, with the same are able to access all the default methods declared in a source folder.

I believe this is why Java uses package access as 'default'. But I'm not sure why they also included private access, I'm sure there is a valid use case...

答:
Encapsulation is a way of saying "you don't have to think about this".

```<code>                 Access Levels
Modifier    Class   Package  Subclass   World
public        Y        Y        Y        Y
protected     Y        Y        Y        N
no modifier   Y        Y        N        N
private       Y        N        N        N
</code>```

Putting these into nontechnical terms.

Public: everyone has to think about it.

Protected: default and subclasses have to know about it.

Default, if you're working on the package, you'll know about it (it's
right there in front of your eyes) might as well let you take advatage
of it.

Private, you only need to know about this if you are working on this class.

Body:
Encapsulation is a way of saying "you don't have to think about this".

                 Access Levels
Modifier    Class   Package  Subclass   World
public        Y        Y        Y        Y
protected     Y        Y        Y        N
no modifier   Y        Y        N        N
private       Y        N        N        N

Putting these into nontechnical terms.

Public: everyone has to think about it.

Protected: default and subclasses have to know about it.

Default, if you're working on the package, you'll know about it (it's
right there in front of your eyes) might as well let you take advatage
of it.

Private, you only need to know about this if you are working on this class.