问:
What's wrong with circular references?
I was involved in a programming discussion today where I made some statements that basically assumed axiomatically that circular references (between modules, classes, whatever) are generally bad.  Once I got through with my pitch, my coworker asked, "what's wrong with circular references?"

I've got strong feelings on this, but it's hard for me to verbalize concisely and concretely.  Any explanation that I may come up with tends to rely on other items that I too consider axioms ("can't use in isolation, so can't test", "unknown/undefined behavior as state mutates in the participating objects", etc.), but I'd love to hear a concise reason for why circular references are bad that don't take the kinds of leaps of faith that my own brain does, having spent many hours over the years untangling them to understand, fix, and extend various bits of code.

Edit: I am not asking about homogenous circular references, like those in a doubly-linked list or pointer-to-parent.  This question is really asking about "larger scope" circular references, like libA calling libB which calls back to libA.  Substitute 'module' for 'lib' if you like.  Thanks for all of the answers so far!

答:
A circular reference construct is problematic, not just from a design standpoint, but from an error catching standpoint as well.

Consider the possibility of a code failure.  You haven't placed proper error catching in either class, either because you haven't developed your methods that far yet, or you're lazy.  Either way, you don't have an error message to tell you what transpired, and you need to debug it.  As a good program designer, you know what methods are related to what processes, so you can narrow it down to those methods relevant to the process that caused the error.

With circular references, your problems have now doubled.  Because your processes are tightly bound, you have no way of knowing which method in which class might have caused the error, or from whence the error came, because one class is dependent on the other is dependent on the other.  You now have to spend time testing both classes in conjunction to find out which one is really responsible for the error.

Of course, proper error catching resolves this, but only if you know when an error is likely to occur.  And if you're using generic error messages, you're still not much better off.

ContentLicense: CC BY-SA 2.5

Title: What's wrong with circular references?


问:
Is the use of one-letter variables encouraged?
Is the use of one-letter variables encouraged in Java? In code snippets or tutorials, you often see them. I cannot imagine using them is encouraged because it makes the code relatively harder to read and I never see them being used in other programming languages!</p>

答:
Reading the code in Kilian's answer, I don't think "there is a loop, and there is a variable, and it has type int, and it has a name, and the name is i, and it is initialised to 0, ...". I just think "loop..." where the three dots stand for unimportant details that I don't even think about. In my programmer's mind, that variable doesn't really exist, it is just an artefact that I have to type, like the for (;;) {} that makes it a loop. </p>

<p>Since that variable doesn't even exist in my mind, why would I give it a name, beyond what is absolutely necessary? </p>

ContentLicense: CC BY-SA 3.0

Body:
Reading the code in Kilian's answer, I don't think "there is a loop, and there is a variable, and it has type int, and it has a name, and the name is i, and it is initialised to 0, ...". I just think "loop..." where the three dots stand for unimportant details that I don't even think about. In my programmer's mind, that variable doesn't really exist, it is just an artefact that I have to type, like the for (;;) {} that makes it a loop.

Since that variable doesn't even exist in my mind, why would I give it a name, beyond what is absolutely necessary?


答:
Properly naming things is hard. Very hard. If you look at it the other way, you can also take this to mean that properly named things are important. (Otherwise, why would you have spent the effort naming it?)

But, sometimes, the names of things just aren't important. That's why we have stuff like anonymous functions ("lambdas"), for example: because sometimes it just isn't worth it naming stuff.

There are a lot of examples, where single letter (or very short) variable names are appropriate:

i, j, k, l for loop indices

k and v for the key and value in a map

n for a number (e.g. in Math.abs(n))

a, b, c for arbitrary objects (e.g. in max(a, b))

e for the element in a generic for each loop

f for the function in a higher-order function

p for the predicate function in a filter

T, T1, T2, … for type variables

E for type variables representing the element type of a collection

R for a type variable representing the result type of a function

ex for the exception in a catch clause

op for the operation in a map or fold

appending the letter s to indicate the plural, i.e. a collection (e.g. ns for a collection of numbers, xs and ys for two arbitrary collections of generic objects)

I never see them being used in other programming languages!

They are very common in pretty much every language I know (and likely also in those I don't know.) Haskell, F#, ML, Ruby, Python, Perl, PHP, C#, Java, Scala, Groovy, Boo, Nemerle, D, Go, C++, C, you name it.

Title: Is the use of one-letter variables encouraged?

Body: Is the use of one-letter variables encouraged in Java? In code snippets or tutorials, you often see them. I cannot imagine using them is encouraged because it makes the code relatively harder to read and I never see them being used in other programming languages!</p>


问:
Is normalization all that's needed to ensure data integrity and quality reporting?
I've gotten out into the real world recently, and for the first time have had to really think about database design, as I've been developing across the entire Java stack. With that I've realized that I don't fully understand the data-store side of things in terms of design, and I haven't seen much of the relationship between data-stores and reporting.

When I got started in my programming diploma we were taught the basics of database design, such as the importance of normalization and naming conventions, but I've never done much of this in the real world. So I wonder:

Is a correctly normalized database the only consideration when attempting to deliver a data store with solid data integrity, and that is easily reported on?

and

If so, does more normalization tend to lead to more reportable data?

答:
"Normalization" has multiple meanings, and they lead to different answers for your question.

The normalization you learn in database classes is a well-defined theoretical concept. Whenever you read of data being in "1st normal form", "2nd normal form" etc., this is what's meant. This is fundamentally a good thing for several reasons, but it's not always the best thing to do for ease of reporting. Quite the contrary, a huge data store (data warehouse) might be deliberately de-normalized so that reporting will work better. (Example: a completely normalized system might contain every sale and its amount as a single record somewhere, but for yearly reporting it's much more efficient to have the monthly sums precomputed and stored as well.)

But data integrity can also mean data that are free from spurious duplicates, misspellings, missing field content, etc. Whenever you have customer records for both "Wiley Coyote" and "Wiley E. Coyote", that's probably an error that decreases the quality of your data, and probably the quality of your reports as well, although no normalization algorithm will catch it. Getting rid of such problems can also be called normalization (or deduplication, or many other things). It is much more difficult, but it almost always improves the value of your data - the question is whether it improves enough to pay for the effort.


问:
How to use one web page to create and edit database entries
My team and I are developing a java web application which allows our admins to create and edit "methods" which can later be viewed by other users.

We are currently discussing the best way to implement this and aim for a screenflow similar to creating / editing events in google calendar.

I.e. The admin starts on a page which shows all current "methods" and a "create new method" button. If he chooses to edit a "method" he is redirected to page "EDIT" where he can change the method's attributes (editing and then sending it via AJAX to update the attribute).
If he chooses to create a new method he should be redirected to a page looking the same, changing attributes, etc. But if he does not change anything and goes back / closes the browser the method should not be saved.

We currently have 2 ideas to do this, both with some drawbacks:

A) Create the "method" with default values and redirect the user to the edit-page. Drawback: Should the user go back or close the browser, we have created an unnecessary entry in the db, which our product owner would like to avoid. (There is a 'delete' button, but this would require another action by the admin)

B) We create separate pages for create and edit (and the corresponding handlers). Drawback: We have to create and maintain 2 (or even 4) files which do basically the same thing.

Is there any way to negate our drawbacks or another alternative how to implement this? We are using Java Web Projects, JSPs and Servlets as technology.

答: Can you create a dummy record in the database with the default values, then pass a flag to the edit page to indicate it should create instead of update on save? If it's not possible to pass a flag, would it be possible to give the dummy record a unique ID that you would then hard-code into the edit page to indicate that the record should be created instead of updated?</p>


答:
There are two aspects to the question, and each have slightly different concerns.

Is a correctly normalized database the only consideration when attempting to deliver a data store with solid data integrity, and that is easily reported on?

No. Data integrity also demands constraints.

Primary key constraints uniquely identify a record. This helps guard against duplicates, but does not necessarily prevent them.

Foreign key constraints help ensure that related data is kept in sync: a table for "customer phone numbers" should have a corresponding "customer," for example. Orphaned records and missing data harm data integrity.

Field/column constraints can help ensure data is valid. For example, perhaps a phone number is stored in a VARCHAR field but should not store letters or formatting, only numbers. A constraint can guarantee that if the data exists, it meets arbitrary criteria that make it valid for the given schema.

If so, does more normalization tend to lead to more reportable data?

Normalization tends to lead to less reportable data. The reason is that a typical RDBMS schema is designed around ORM, meaning "application objects." What looks like one object may require several tables:

A class that uses inheritance (i.e. has subclasses) requires one table per inheritance level in practice because child data members are not applicable to the superclass and should have their own table.

Related objects may have their own table. A customer with multiple phone numbers may be List<String> in the application, but the phone numbers may be in their own table in the schema forming a 0..* relationship.

Reports often are record based where a record is specific to the report. They often denormalize data to give a view of a specific table with related data mixed in. This is normally at odds with normalization and ORM.

What this means is that an object that you use quite easily in the application may explode into many table in the database schema, adding relationships with varying cardinality. This requires joins when writing a report query, some of which may be complex or require subqueries. I have seen report SQL queries with ten or more joins, correlated subqueries, aggregates, and other intermediate to advanced SQL features which add complexity and can harm query performance.

The typical way to deal with this as I have seen professionally is to have a separate set of denormalized reporting tables built for your reports. Use triggers or stored procedures to populate them. This is more work during persistence, but saves a lot of time and hair pulling when writing SQL for your reports.

You can also use application code: when you save an object and have it and its related objects in memory, construct a query to insert or update a record into your reporting tables. This may be easier and have faster run-time performance than relying on triggers.

Title: Is normalization all that's needed to ensure data integrity and quality reporting?

Body:
I've gotten out into the real world recently, and for the first time have had to really think about database design, as I've been developing across the entire Java stack. With that I've realized that I don't fully understand the data-store side of things in terms of design, and I haven't seen much of the relationship between data-stores and reporting.

When I got started in my programming diploma we were taught the basics of database design, such as the importance of normalization and naming conventions, but I've never done much of this in the real world. So I wonder:

Is a correctly normalized database the only consideration when attempting to deliver a data store with solid data integrity, and that is easily reported on?

and

If so, does more normalization tend to lead to more reportable data?


问:
What's the proper way to model this real-world activity that seems to need circular references in OOP?
I've been wrestling with a problem in a Java project about circular references.  I'm trying to model a real-world situation in which it seems the objects in question are interdependent and need to know about each other.

The project is a generic model of playing a board game.  The basic classes are non-specific, but are extended to deal with specifics of chess, backgammon and other games.  I coded this up as an applet 11 years ago with half a dozen different games, but the problem is that it's full of circular references.  I implemented it back then by stuffing all the intertwined classes in a single source file, but I get the idea that that's bad form in Java.  Now I want to implement a similar thing as an Android app, and I want to do things properly.

The classes are:

RuleBook: an object that can be interrogated for such things as the
initial layout of the Board, other initial game State information
like who moves first, the Moves that are available, what happens to
the game State after a proposed Move, and an evaluation of a current
or proposed board position.

Board: a simple representation of a game board, which can be
instructed to reflect a Move.

MoveList: a list of Moves.  This is dual-purpose: a choice of moves
available at a given point, or a list of moves that have been made in
the game.  It could be split into two near-identical classes, but
that's not relevant to the question I'm asking and may complicate it
further.

Move: a single move.  It includes everything about the move as a list
of atoms: pick up a piece from here, put it down there, remove a
captured piece from there.

State: the full state information of a game in progress.  Not only
the Board position, but a MoveList, and other state information such
as who is to move now.  In chess one would record whether the king
and rooks of each player have been moved.

Circular references abound, for example: the RuleBook needs to know about the game State to determine what moves are available at a given time, but the game State needs to query the RuleBook for the initial starting layout and for what side effects accompany a move once it is made (e.g. who moves next).

I tried organising the new set of classes hierarchically, with RuleBook at the top as it needs to know about everything.  But this results in having to move lots of methods into the RuleBook class (such as making a move) making it monolithic and not particularly representative of what a RuleBook should be.

So what's the proper way to organise this?  Should I turn RuleBook into BigClassThatDoesAlmostEverythingInTheGame to avoid circular references, abandoning the attempt to model the real-world game accurately?  Or should I stick with the interdependent classes and coax the compiler into compiling them somehow, retaining my real-world model?  Or is there some obvious valid structure I'm missing?

Thanks for any help you can give!

答:
Is there any need for a rulebook object to be bound to a particular game state, or would it make more sense to have a rulebook object with a method that, given a game state, will report what moves are available from that state (and, having reported that, remember nothing about the state in question)?  Unless there is something to be gained by having the object which is asked about available moves retain a memory of the game state, there's no need for it to persist a reference.

It's possible in some cases there would be advantages to having the rules-evaluating object maintain state.  If you think such a situation may arise, I would suggest adding a "referee" class, and having the rulebook provide a "createReferee" method.  Unlike the rulebook, which cares nothing whether it's asked about one game, or fifty, a referee object would expect to officiate one game.  It wouldn't be expected to encapsulate all of the state related to the game it's officiating, but could cache whatever information about the game it deemed useful.  If a game supports "undo" functionality, it may be helpful to have the referee include a means of producing a "snapshot" object which could be stored along with earlier game states; that object should, given a copy of the game state when it was created, be able to in turn produce a new referee which whose state should match the state the original referee had when the snapshot was created.

If some coupling might be necessary between the rules-processing and game-state-processing aspects of the code, using a referee object will make it possible to keep such coupling out of the main rulesbook and game-state classes.  It may also make it possible to have new rules consider aspects of game state that the game-state class wouldn't consider relevant (e.g. if a rule was added which said "Object X can't do Y if it's ever been to location Z", the referee could be changed to keep track of which objects have been to location Z without having to change the game-state class).


问:
Auto-save user input - the smartest way?
I'm developing a social network website and I'm working with php/mysql/jquery and I want users to have the most user-friendly website experience. That's why I try to avoid a save (submit) button at all. So, when they're on their own profile and enter information like what languages they speak or where do they live, I want to auto-create a page entry, if it doesn't exist already.

For example if somebody speaks german and that entry isn't available in the database yet (it's called pages with rows title, text, date_added). This is most likely comparable with a Facebook page you can create on Facebook, but this should be about everything (languages, companies, locations, activities).

So my specific problem now is, how to implement this feature the most smartest way. I mean on what event should this save be triggered, because I obviously can't save a new entry on every letter that has been typed. I've already implemented an autocomplete function, so they can choose from entries that already exist, but as mentioned I want them to create new entries (pages), too. Most preferably without "flooding" the database with new entries.

The things I thought of:

When a user switches from one input to another and input has been
made. Can this even be registered by JQuery? But here's the
question, what if he leaves the page without switching to another
input.

Save all data only then if he leaves the current page. I think
    there is this onunload function in JQuery.

Get confirmation from the user: "This entry hasn't been made yet.
    Do you want to save this entry?". But when should I ask this? I
    can't predict when the user is finished with typing.

答:
Have a save button.

There are very good reasons why applications use explicit save/submit buttons:

Gives the user a chance to change their mind about the edit.  Unless you provide some sort of undo mechanism with auto-save, the user has no way to abort a modification.

Protects against accidental modification.  In the world of multi-monitor and multi-window setups it is common for a user to lose track of where the keyboard focus is and start typing the wrong window.

Efficiency.  If the user is going to make changes to 5 fields at once, it's better to perform one save operation rather than 5.


问:
Which style to use for unused return parameters in a Python function call
Is there any recommended/generally accepted coding style for handling situations where a function returns a tuple of values but only one of those values is used afterwards (note that this is mostly meant for library functions I can't change -- writing a wrapper around the call is probably a bit of overkill…)?
Instead of doing

```<code>a, b, c = foo()
</code>```

and then just not using b and c, which of the following variants should be preferred (or is there another one?):

Variant 1 (underscore)

```<code>a, _, _ = foo()
</code>```

(which is very clear and simple but might clash with _ = gettext.gettext used in many applications that use translation)

Variant 2 (dummy name)

```<code>a, unused, unused = foo()
</code>```

(not very appealing, I think, same goes for other names like dummy)

Variant 3 (index)

```<code>a = foo()[0]
</code>```

(to me the ()[0] looks un-pythonic…)

答:
As others have said, underscore (_) is the standard. But if underscore is being used for translations, I think double underscore is the best alternative.

var, __, value = "VAR=value".partition('=')

Better than these:

var, unused, value = "VAR=value".partition('=')

var, unused_del, value = "VAR=value".partition('=')

var, _del, value = "VAR=value".partition('=')

ContentLicense: CC BY-SA 4.0


答:
If you are referring to the letters i,j,k as indices within a loop, that is a common practice in Java and other programming languages.  Though there its probably better to use a for each style loop, such as

```<code>for(User user: users) {
  doSomethingWithTheUser(user);
}
</code>```

instead of

```<code>for(int i=0; i<users.size(); i++) {
  doSomethingWithTheUser(users.get(i));
}
</code>```

In Java that style of looping was only introduced fairly recently.  That may be why you are noticing it more for Java, as looping over the indices used to be the most common way to loop over an array or list.

There are a few other cases where single letters may be appropriate, such as when implementing a mathematical function where single letters such as n, x, or y, may already be common.  But in general, no, name your variables something meaningful.

Body:
If you are referring to the letters i,j,k as indices within a loop, that is a common practice in Java and other programming languages.  Though there its probably better to use a for each style loop, such as

for(User user: users) {
  doSomethingWithTheUser(user);
}

instead of

for(int i=0; i<users.size(); i++) {
  doSomethingWithTheUser(users.get(i));
}

In Java that style of looping was only introduced fairly recently.  That may be why you are noticing it more for Java, as looping over the indices used to be the most common way to loop over an array or list.

There are a few other cases where single letters may be appropriate, such as when implementing a mathematical function where single letters such as n, x, or y, may already be common.  But in general, no, name your variables something meaningful.


问:
Java Action Listener
Actually, I've got a confusion in Java while implementing action listener event. I can add action listener event by implementing the class with ActionListener and by

```<code>someButton.addActionListener(this);
</code>```

But, I came to know this also does the same thing.

```<code>someButton.addActionListener(new ActionListener() {
 public void actionPerformed(ActionEvent evt) {
              //some code...
            }
 });
</code>```

But I could not get it. We cannot use new on an interface but it uses it. I get error if I just use try to instantiate the object using new only what I expected but it works when I create a block for it using {} braces. Could somebody please explain it.

答:
The second construct that you use is called an anonymous class.

It's both a declaration and instantiation of a class at the same time. Although ActionListener is an interface, you're creating a new instance of a class that implements that interface along with providing an implementation of its methods (in this case, there's only one method in the interface) and then providing that to the addActionListener() method.

Title: Java Action Listener


问:
Strategy for keeping secret info such as API keys out of source control?
I'm working on a website that will allow users to log in using OAuth credentials from the likes of Twitter, Google, etc.  To do this, I have to register with these various providers and get a super-secret API key that I have to protect with pledges against various body parts.  If my key gets ganked, the part gets yanked.

The API key has to travel with my source, as it is used at runtime to perform authentication requests.  In my case, the key must exist within the application in a configuration file or within the code itself.  That isn't a problem when I build and publish from a single machine.  However, when we throw source control into the mix, things get more complicated.

As I'm a cheap bastard, I'd much prefer to use free source control services such as TFS in the cloud or GitHub.  This leaves me with a slight conundrum:

How can I keep my body intact when my API keys are in my code, and my code is available in a public repository?

I can think of a number of ways to handle this, but none of them are that satisfying.

I could remove all private info from code, and edit it back in after deployment.  This would be a severe pain to implement (I won't detail the many ways), and isn't an option.

I could encrypt it.  But as I have to decrypt it, anyone with the source could figure out how to do so.  Pointless.

I could pay for private source control.  LOL j/k spend money?  Please.

I could use language features to segregate sensitive info from the rest of my source and therefore keep it from source control.  This is what I'm doing now, but it could easily be screwed up by mistakenly checking in the secret file.

I'm really looking for a guaranteed way to ensure I don't share my privates with the world (except on snapchat) that will work smoothly through development, debugging and deployment and be foolproof as well.  This is completely unrealistic.  So what realistically can I do?

Technical details:  VS2012, C# 4.5, source control is either going to be TF service or GitHub.  Currently using a partial class to split the sensitive keys off in a separate .cs file that won't be added to source control.  I think GitHub may have the advantage as .gitignore could be used to ensure that partial class file isn't checked in, but I've screwed that up before.  Am hoping for a "oh, common issue, this is how you do it" but I may have to settle for "that doesn't suck as much as it could have", :/

答:
This is very Android/Gradle specific but you could define the keys in your global gradle.properties file located in user home/.gradle/. This is also useful as you can use different properties depending on buildType or flavour i.e API for dev and different one for release.

gradle.properties

```<code>MY_PRIVATE_API_KEY=12356abcefg
</code>```

build.gradle

```<code>buildTypes {
        debug{
            buildConfigField("String", "GOOGLE_VERIFICATION_API_KEY", "\"" + MY_PRIVATE_API_KEY +"\"")
            minifyEnabled false
            applicationIdSuffix ".debug"
            }
        }
</code>```

In code you'd reference like this

```<code>String myAPI = BuildConfig.GOOGLE_VERIFICATION_API_KEY;
</code>```

Body:
This is very Android/Gradle specific but you could define the keys in your global gradle.properties file located in user home/.gradle/. This is also useful as you can use different properties depending on buildType or flavour i.e API for dev and different one for release.

gradle.properties

MY_PRIVATE_API_KEY=12356abcefg

build.gradle

buildTypes {
        debug{
            buildConfigField("String", "GOOGLE_VERIFICATION_API_KEY", "\"" + MY_PRIVATE_API_KEY +"\"")
            minifyEnabled false
            applicationIdSuffix ".debug"
            }
        }

In code you'd reference like this

String myAPI = BuildConfig.GOOGLE_VERIFICATION_API_KEY;


问:
Is there a performance benefit to using the method reference syntax instead of lambda syntax in Java 8?
Do method references skip the overhead of the lambda wrapper?  Might they in the future?

According to the Java Tutorial on Method References:

Sometimes... a lambda expression does nothing but call an existing method.
In those cases, it's often clearer to refer to the existing method by
name. Method references enable you to do this; they are compact,
easy-to-read lambda expressions for methods that already have a name.

I prefer the lambda syntax to the method reference syntax for several reasons:

Lambdas are clearer

Despite Oracle's claims, I find the lambda syntax easier-to-read than the object method reference short-hand because the method reference syntax is ambiguous:

```<code>Bar::foo
</code>```

Are you calling a static one-argument method on the class of x and passing it x?

```<code>x -> Bar.foo(x)
</code>```

Or are you calling a zero-argument instance method on x?

```<code>x -> x.foo()
</code>```

The method reference syntax could stand in for either one.  It hides what your code is actually doing.

Lambdas are safer

If you reference Bar::foo as a class method and Bar later adds an instance method of the same name (or vice-versa), your code will no longer compile.

You can use lambdas consistently

You can wrap any function in a lambda - so you can use the same syntax consistently everywhere.  The method reference syntax won't work on methods that take or return primitive arrays, throw checked exceptions, or have the same method name used as an instance and a static method (because the method reference syntax is ambiguous about which method would be called).  They don't work when you have overloaded methods with the same number of arguments, but you shouldn't do that anyway (see Josh Bloch's item 41) so we can't hold that against method references.

Conclusion

If there's no performance penalty for doing so, I'm tempted to turn off the warning in my IDE and use the lambda syntax consistently without sprinkling the occasional method reference into my code.

P.S.

Neither here nor there, but in my dreams, object method references look more like this and apply invoke-dynamic against the method directly on the object without a lambda wrapper:

```<code>_.foo()
</code>```

答:
It's all about the metafactory

First, most method references do not need desugaring by the lambda metafactory, they are simply used as the reference method. Under the section "Lambda body sugaring" of the Translation of Lambda Expressions ("TLE") article:

All things being equal, private methods are preferable to nonprivate, static methods preferable to instance methods, it is best if lambda bodies are desugared into in the innermost class in which the lambda expression appears, signatures should match the body signature of the lambda, extra arguments should be prepended on the front of the argument list for captured values, and would not desugar method references at all. However, there are exception cases where we may have to deviate from this baseline strategy.

This is further highlighted further down in TLE's "The Lambda Metafactory":

```<code>metaFactory(MethodHandles.Lookup caller, // provided by VM
            String invokedName,          // provided by VM
            MethodType invokedType,      // provided by VM
            MethodHandle descriptor,     // lambda descriptor
            MethodHandle impl)           // lambda body
</code>```

The impl argument identifies the lambda method, either a desugared lambda body or the method named in a method reference.

A static (Integer::sum) or unbounded instance method (Integer::intValue) references are the 'simplest' or the most 'convenient', in the sense that they can be optimally handled by a 'fast-path' metafactory variant without the desugaring. This advantage is helpfully pointed out in TLE's "Metafactory variants":

By eliminating arguments where they are not needed, classfiles become smaller. And the fast path option lowers the bar for the VM to intrinsify the lambda conversion operation, enabling it to be treated as a "boxing" operation and faciliating unbox optimizations.

Naturally, an instance-capturing method reference (obj::myMethod) needs to provide the bounded instance as an argument to the method handle for invocation, which may mean the need of desugaring using 'bridge' methods.

Conclusion

I'm not exactly sure what is the lambda 'wrapper' you are hinting at, but even though the ultimate result of using your user-defined lambdas or method references are the same, the way that is reached seems to be quite different, and can be different in the future if that's not the case now. Hence, I suppose it's more likely than not that method references can be handled in a more optimal way by the metafactory.

Body:
It's all about the metafactory

First, most method references do not need desugaring by the lambda metafactory, they are simply used as the reference method. Under the section "Lambda body sugaring" of the Translation of Lambda Expressions ("TLE") article:

All things being equal, private methods are preferable to nonprivate, static methods preferable to instance methods, it is best if lambda bodies are desugared into in the innermost class in which the lambda expression appears, signatures should match the body signature of the lambda, extra arguments should be prepended on the front of the argument list for captured values, and would not desugar method references at all. However, there are exception cases where we may have to deviate from this baseline strategy.

This is further highlighted further down in TLE's "The Lambda Metafactory":

metaFactory(MethodHandles.Lookup caller, // provided by VM
            String invokedName,          // provided by VM
            MethodType invokedType,      // provided by VM
            MethodHandle descriptor,     // lambda descriptor
            MethodHandle impl)           // lambda body

The impl argument identifies the lambda method, either a desugared lambda body or the method named in a method reference.

A static (Integer::sum) or unbounded instance method (Integer::intValue) references are the 'simplest' or the most 'convenient', in the sense that they can be optimally handled by a 'fast-path' metafactory variant without the desugaring. This advantage is helpfully pointed out in TLE's "Metafactory variants":

By eliminating arguments where they are not needed, classfiles become smaller. And the fast path option lowers the bar for the VM to intrinsify the lambda conversion operation, enabling it to be treated as a "boxing" operation and faciliating unbox optimizations.

Naturally, an instance-capturing method reference (obj::myMethod) needs to provide the bounded instance as an argument to the method handle for invocation, which may mean the need of desugaring using 'bridge' methods.

Conclusion

I'm not exactly sure what is the lambda 'wrapper' you are hinting at, but even though the ultimate result of using your user-defined lambdas or method references are the same, the way that is reached seems to be quite different, and can be different in the future if that's not the case now. Hence, I suppose it's more likely than not that method references can be handled in a more optimal way by the metafactory.


问:
How to treat bugs that users thought were a feature?
Question:

What is the proper way to address a bug that an end-user thought was a feature?

Elaboration:

I'm guessing that if a large percentage of users expected it as a feature, it should be left "unfixed" or "fixed" to be more stable? However, what if a very small percentage of users expect it to be a feature... say 0.1% or 1%, and this bug must be fixed.

Theoretically, since this is a minor bug fix it can qualify as PATCH as considered by semantic versioning: x.y.Z. However, since it does break backwards compatibility (even just for a few users) it should be a MAJOR increase: X.y.z. Correct? Could it still qualify as a PATCH (since it was not intended as a feature) as long as it's documented?

EDIT: In this specific case, it's a bug in an API of an internally-used library that other developers use.

答:
I'd recommend making it more stable. Users are the canonical source of what your software does. If they want it, and have come to rely on it, I'd think twice about yanking it.

A good example of this is the "Skiing" mechanic in the video game "Tribes". Originally a bug in how the physics engine handled jumping on a hill, it ended up one of the core game mechanics. You can read a bit more about it here, if you're curious.


问:
What do you do when a user asks for a feature you will not implement?
What do you do when a user asks for a complex feature that you could implement, but you aren't going to do it because 1) it adds unnecessary complexity to other users 2) you are not going to do it as an option either because you don't want your settings panel to be complicated.

I wrote an iOS app and there are a few users that asked me for some complex features that I can't do because of the reasons above. Most of the time I just answered them that "We will take that into consideration." Explaining them that they are in the minority that wants this feature is not going to help either. So, what do you do in the case like this?

答:
For each of our products, we have a "list of ideas for future versions". So what we tell our users is "we will put your suggestion on that list" - and that is honest, we actually do that.

The list has no priorities, but we regularly pick things from it and use them to feed our backlog. We do not take them "in order", instead we try to identify which ideas give the "most bang for the buck" - the most benefit for as many of our users as possible, for a reasonable development effort.

Feature requests against the conceptual integrity of the product are likely to stay there forever.  But occasionally, it happens that at least some of the ideas buried in those feature requests can be realized, maybe not exactly the way the person who suggested it was thinking of, but in a way which fits better into the product's architecture.

So my suggestion here is: do not just say "We will take that into consideration." and forget the idea as soon as you end up the phone call. Instead, have a tool where you store ideas and feature requests, maybe in an issue tracker, maybe in a Wiki, maybe in a spreadsheet, whatever suits your needs best.


问:
how to modularize wcf services?
I am working on a WCF application that supports 4 different applications.

lets call those 4 application: App1, App2, App3, and App4.

this WCF Application has 4 services. one for each application.  4 services are very similar, thats why I want to combine them together into 1 wcf application.  Here's the problem, if I need to change the service for App1, I need to redeploy the entire application. even tho, services for App2, App3, and App4 have no changes.  I try to avoid that, but I dont want to create 4 different WCF applications because they are very similar, if there's a change, I probably have to change it 4 times and redeploy 4 times.

I am thinking about using WCF and MEF. I just want to know what other options out there I can explore.

答:
You would need more information to know for certain what to do here.

My natural inclination would be towards using WCF web methods that takes an identifier parameter.  Your web method would have any number of parameters you need based on your requirements (though my preference in this situation would be to provide logic-related parameters as an array containing key/value pairs and all identifier parameters are separate arguments) with one parameter being a version number or app ID.

Your WCF web method's internal code would act as a router, routing the retrieved values to the correct internal method to process your results based on the target application or version number.

For example, it may turn out that app1, app2, and app3 all use the same version of a hypothetical method DoSomething() whereas app4 has some additional logical requirement.  They can all share the same operation contract and web service, while actually being handled differently under the hood..  The good thing about this approach is that if app5, 6, and 7 emerge in the future you do not need to break your existing operation contracts.

Consider the following:

[ServiceContract]

public interface IApplicationService
{
    [OperationContract]
    [WebGet(UriTemplate = "/DoSomething?appId={appId}&parms={parms}")]
    ResponseObj DoSomething(string appId, string[] parms);
}

public class ApplicationService: IApplicationService {
public ResponseObj DoSomething(string appId, string[] parms)
{
    ResponseObj retVal;
    switch(appId)
    {
         case "app1":
         case "app2":
         case "app3":
             retVal = DoSomething(parms);
             break;
         case "app4":
             retVal = DoSomethingElse(parms);
             break;
         default:
             // Handle case
             break;
    }
    return retVal;
}
private ResponseObj DoSomething(string[] parms) { /**logic!**/ }
private ResponseObj DoSomethingElse(string[] parms) { /**logic!**/ }
}

[DataContract]
public class ResponseObj { /**data members**/ }
```

With something like this your operation contract is never changing.  If you change something for the logic in App4, for example, it does not affect 1, 2, or 3.  However, your API documentation would need to be clear on the format of your expected array and your private methods would have to validate the retrieved data.

Depending on how things are configured you can do things in other ways.  For example, if your web service has a login() method that returns a session, you could tie the version to the session.  Now your routing is based on the session state you're tracking on the server, and you can easily abstract it away in framework code without needing to clutter up your business logic methods.

Personally I have not used MEF with WCF, only MVC4, so I can't comment on how well it would suit your use case here. The solution I've provided does not rely on MEF but is somewhat expensive to maintain over time as you start scaling out to more apps using a shared service.  I've built something similar for a former employer elsewhere, though it was an abstraction to a control database that provided configuration data for different registered apps via appId.

Title: how to modularize wcf services?

Body:
You would need more information to know for certain what to do here.

My natural inclination would be towards using WCF web methods that takes an identifier parameter.  Your web method would have any number of parameters you need based on your requirements (though my preference in this situation would be to provide logic-related parameters as an array containing key/value pairs and all identifier parameters are separate arguments) with one parameter being a version number or app ID.

Your WCF web method's internal code would act as a router, routing the retrieved values to the correct internal method to process your results based on the target application or version number.

For example, it may turn out that app1, app2, and app3 all use the same version of a hypothetical method DoSomething() whereas app4 has some additional logical requirement.  They can all share the same operation contract and web service, while actually being handled differently under the hood..  The good thing about this approach is that if app5, 6, and 7 emerge in the future you do not need to break your existing operation contracts.

Consider the following:

[ServiceContract]

public interface IApplicationService
{
    [OperationContract]
    [WebGet(UriTemplate = "/DoSomething?appId={appId}&parms={parms}")]
    ResponseObj DoSomething(string appId, string[] parms);
}

public class ApplicationService: IApplicationService {
public ResponseObj DoSomething(string appId, string[] parms)
{
    ResponseObj retVal;
    switch(appId)
    {
         case "app1":
         case "app2":
         case "app3":
             retVal = DoSomething(parms);
             break;
         case "app4":
             retVal = DoSomethingElse(parms);
             break;
         default:
             // Handle case
             break;
    }
    return retVal;
}
private ResponseObj DoSomething(string[] parms) { /**logic!**/ }
private ResponseObj DoSomethingElse(string[] parms) { /**logic!**/ }
}

[DataContract]
public class ResponseObj { /**data members**/ }

With something like this your operation contract is never changing.  If you change something for the logic in App4, for example, it does not affect 1, 2, or 3.  However, your API documentation would need to be clear on the format of your expected array and your private methods would have to validate the retrieved data.

Depending on how things are configured you can do things in other ways.  For example, if your web service has a login() method that returns a session, you could tie the version to the session.  Now your routing is based on the session state you're tracking on the server, and you can easily abstract it away in framework code without needing to clutter up your business logic methods.

Personally I have not used MEF with WCF, only MVC4, so I can't comment on how well it would suit your use case here. The solution I've provided does not rely on MEF but is somewhat expensive to maintain over time as you start scaling out to more apps using a shared service.  I've built something similar for a former employer elsewhere, though it was an abstraction to a control database that provided configuration data for different registered apps via appId.


问:
How can I create a model to efficiently answer the question of - where to place my db-interaction code I am about to write?
I am seeking the right model for storing and retrieving data, when working with any specific class, while keeping in mind the bigger picture.

Details:

I have some SQL code in (one) of my classes and I would like to use Separation of Concerns (SoC) to remove dealing with direct-database-specific code in that class.

Simplest thing will be to create DBCodeForOneSpecificClass class, but thinking globally, I may end up with too many classes - I think creating a DB handling class for each Business logic is wasteful.

So I need to find a way to consolidate those DB-access functions properly.

I recall there was an advice in a book on refactoring SQL specifically and it was "pull all SQL code in your entire codebase and consolidate it in a single space, away from all other non-direct-SQL-dealing classes".  I do not recall specifics.  I presume all SQL-code was to go into its own separate folder, where perhaps there was some kind of strategy or philosophy to keep a happy medium between the extremes of

create a single separate db-handling class for all classes in your entire codebase

create a single separate db-handling class for each BusinessLogic class

My question is -- can you help fill some specifics into the space between the extremes -- what are some heuristics / models / ways I could use to make a decision on how to structure my DB-handling classes, so that I pretty much immediately know what to do, when handling a question of "Where do I place my db-handling code I currently find myself writing in this BusinessLogicClass?"

Because right now I seem to solve this question on a case-by-case basis, either having SQL right inside the class, or in a separate class made just for one class, or grouping SQL by an aspect.  In the end, ending up with various models mixed up, and that is not good.  I am thinking that maybe may need help defining what an aspect is, or identifying clearer boundaries of what my domain objects are, which perhaps means identifying larger moving parts of the codebase, and then structuring my DB-interaction classes around those parts.

My satisfaction with the answers will depend on whether I am able to get closer to answering question of "Where do I put my d--n SQL while writing this specific new feature in this specif class...?", while supporting SoC principle, and without being wasteful (too specific) or creating a big ball of mud (too general).

答:
In general, there are several ways to handle CRUD-operations for db-persisted entities.

Active Record vs Data Mapper

An Active Record is the object-representation of a database row that contains domain logic and persistence logic. It's the simplest form - and to avoid duplicated, boilerplate code  you can use abstract base classes, traits/mixins or modular composition to define basic db-interactions in one place and have every active record use the methods provided. This is the wikipedia-entry on the active record pattern.

This pattern comes in handy because it's quick and straightforward to implement. But it has some drawbacks. As you noted, it's note separating concerns as well as alternatives and therefore is somewhat harder to reason about. When dealing only with basic objects for table-rows, containing only scalar values, and when done efficiently - the increase in conceptual complexity can be negligible.

This is one huge drawback, though - most interesting business-logic involves composite  objects, for example sales documents with a header, lines and relational constraints (foreign keys). Unless you employ database-technology that can simply map both non-scalar values and relations, that makes relying on the active record-pattern for persistence-logic problematic... and even with such technology it has potential to be cumbersome.

If you are working with a relational database constrained to scalar values (for relevant intents and purposes) in the persistence of your domain objects, you need *some form of  ORM - Object-Relational-Mapping. This can be achieved with the easy-to-use, easy-to-implement active record-pattern. In the PHP-world, Laravel's Eloquent ORM-tool does just that.

The main contender is the Data Mapper-pattern (Wiki), where mapping is handled by separate classes, like Repositories that can return individual objects, collections, or even composite objects - through repositories using other repositories, or by specifying operations, including joins on the basic stored data in the composition of objects in a single repository. This pattern is used by the doctrine ORM-tool (PHP, again).

The key to making this idea work elegantly and with minimal repeated effort is to maintain meta-data about the object and its relation to columns and rows in database tables explicit - including keys, field types and mapping to object properties. It's possible to automate some parts or even the entirety of the production of code for such meta-data containing entities in database procedures or a specific application object, for example by using SHOW CREATE TABLE results - and/or reflection on classes.

But it's also possible to build your own, domain-specific, lightweight version of such an ORM, too. I have implement the data-mapper pattern in one of my own projects. Using SHOW CREATE TABLE, results, I can quickly construct meta-data classes for every domain-class. Using abstract base classes or traits (in fact, I wrote two versions), I can quickly implement a repository for every domain-class that uses the meta-data class, implements persistence, relational-access and the identity map pattern in virtue of keeping a cache of fetched db-rows and being a single instance used in the construction of all classes needing db-access for the respective domain-object. In turn, all repositories are constructed with a basic wrapper on the PDO-Class, that allows for easy logging and implementation of the observer pattern (for example to keep dependent foreign entities current).

Though the initial effort for setup and configuration is certainly higher than with active records, the increased separation of concerns and flexibility is mostly worth it when your project exceeds a certain level of complexity.

A related concern - the Unit of Work:

In many cases, some interactions will affect multiple entities, including domain-entities with regard to their persisted data. Often, such access has to have transactional integrity - meaning that while a modification-cascade is unfinished, modifying operations on the involved entities must not be permitted. A way to handle this - and an important tool in any case, is the Unit of Work-pattern. On a basic level, the Unit of Work provides a way to keep track of which entities are 'clean' or 'dirty' and which are scheduled for insert, update, delete, modify.

Additional sources:

MSDN - Peristence Patterns

Sitepoint - Implementing the Unit of Work pattern

Catalog of Patterns of Enterprise Application Architecture

doctrine

Eloquent


答:
I'm guessing that if a large percentage of users expected it as a feature, it should be left "unfixed" or "fixed" to be more stable?

Does the bug add value? If so, it's more of a feature. Sometimes a "bug" can end up as a value-add "feature."

It's hard to really answer this conclusively because every single situation will be different.

In this specific case, it's a bug in an API of an internally-used library that other developers use.

In this case, I would include a fix as part of your next breaking change with respect to backwards compatibility. You can't really just do this consistently in most environments and there's probably a schedule/timeframe for this.

As a developer the last thing I want to deal with is an API which has incorrect or inconsistent behavior. Bugs are considered this.

At the very least, create some sort of "known bugs with current version" document/wiki internally and so you can ensure all your internal users know the functionality is bug-like. Hopefully you have enough tests covering the areas where people are using the bug-as-a-feature so you will see where/when things break when/if you fix the bug.

Title: How to treat bugs that users thought were a feature?

Body:
Question:

What is the proper way to address a bug that an end-user thought was a feature?

Elaboration:

I'm guessing that if a large percentage of users expected it as a feature, it should be left "unfixed" or "fixed" to be more stable? However, what if a very small percentage of users expect it to be a feature... say 0.1% or 1%, and this bug must be fixed.

Theoretically, since this is a minor bug fix it can qualify as PATCH as considered by semantic versioning: x.y.Z. However, since it does break backwards compatibility (even just for a few users) it should be a MAJOR increase: X.y.z. Correct? Could it still qualify as a PATCH (since it was not intended as a feature) as long as it's documented?

EDIT: In this specific case, it's a bug in an API of an internally-used library that other developers use.


答:
The circular dependency isn't necessarily a technical problem, but it should be considered a code smell, that usually is a violation of the Single Responsibility Principle.

Your circular dependency comes from the fact that you're trying to do too much from your State object.

Any stateful object should only provide methods that directly relate to managing that local state. If it requires anything more than the most basic logic, then it should probably be broken out into a larger pattern. Some people have different opinions about this, but as a general rule of thumb, if you're doing anything more than getters and setters on data, you're doing too much.

In this case, you'd be better off having a StateFactory, which could know about a Rulebook. You'd probably have another controller class which uses your StateFactory to create a new game. State definitely shouldn't know about Rulebook. Rulebook might know about a State depending on the implementation of your rules.

Title: What's the proper way to model this real-world activity that seems to need circular references in OOP?

Body:
I've been wrestling with a problem in a Java project about circular references.  I'm trying to model a real-world situation in which it seems the objects in question are interdependent and need to know about each other.

The project is a generic model of playing a board game.  The basic classes are non-specific, but are extended to deal with specifics of chess, backgammon and other games.  I coded this up as an applet 11 years ago with half a dozen different games, but the problem is that it's full of circular references.  I implemented it back then by stuffing all the intertwined classes in a single source file, but I get the idea that that's bad form in Java.  Now I want to implement a similar thing as an Android app, and I want to do things properly.

The classes are:

RuleBook: an object that can be interrogated for such things as the
initial layout of the Board, other initial game State information
like who moves first, the Moves that are available, what happens to
the game State after a proposed Move, and an evaluation of a current
or proposed board position.

Board: a simple representation of a game board, which can be
instructed to reflect a Move.

MoveList: a list of Moves.  This is dual-purpose: a choice of moves
available at a given point, or a list of moves that have been made in
the game.  It could be split into two near-identical classes, but
that's not relevant to the question I'm asking and may complicate it
further.

Move: a single move.  It includes everything about the move as a list
of atoms: pick up a piece from here, put it down there, remove a
captured piece from there.

State: the full state information of a game in progress.  Not only
the Board position, but a MoveList, and other state information such
as who is to move now.  In chess one would record whether the king
and rooks of each player have been moved.

Circular references abound, for example: the RuleBook needs to know about the game State to determine what moves are available at a given time, but the game State needs to query the RuleBook for the initial starting layout and for what side effects accompany a move once it is made (e.g. who moves next).

I tried organising the new set of classes hierarchically, with RuleBook at the top as it needs to know about everything.  But this results in having to move lots of methods into the RuleBook class (such as making a move) making it monolithic and not particularly representative of what a RuleBook should be.

So what's the proper way to organise this?  Should I turn RuleBook into BigClassThatDoesAlmostEverythingInTheGame to avoid circular references, abandoning the attempt to model the real-world game accurately?  Or should I stick with the interdependent classes and coax the compiler into compiling them somehow, retaining my real-world model?  Or is there some obvious valid structure I'm missing?

Thanks for any help you can give!


问:
How to handle overlapping classes
I'm putting together a program to try and recreate a board game. My goal was to keep the rules and actually actions of the game separate from its presentation, so I am creating a library that contains the objects and methods that define what you can do as you play the game. Besides the classes that define the games objects, I was planning to create two classes to "front" the game. The first class GameRunner was the class that the presentation layer would use to call actions on the game such as AddPlayer, TakeGems, BuildCard etc. Then I wanted a second class to handle the game state, aptly named GameState, that would keep track of the players and their field, as well as the market for the game. In GameState I created the methods that would affect the game state to define how players are added and cards are purchased.

What I have noticed is that all of the game logic is being defined in GameState and GameRunner now is essentially just turning into a pass through class, in other words, all it does is call the appropriate method in GameState and return the state object:

```<code>public GameState AddPlayer(string name)
{
    gameState.AddPlayer(name);
    return gameState;
}
</code>```

This just seems repetitive to me. Does this make sense as a design? A separation of concerns between actions and what they do? Or should I just make GameState a class that has the objects that make the state of the game, and just have GameRunner manipulate those state fields from it's methods instead. Example:

```<code>public GameState AddPlayer(string name)
{
    if(Players.Count < 4)
    {
        gameState.Players.Add(new Player(name))
        gameState.Success = true;
    }
    else
    {
        gameState.Success = false;
    }

    return gameState;
}
</code>```

答:
By returning GameState from your GameRunner functions, you are making the client of GameRunner dependent on GameState as well. IE the GameRunner client knows the details of GameRunner's implementation.

I think the delegation of tasks to the GameState (as in the first example) is the better of the two options, thus when the logic of (in this instance) adding a player to a Game changes, it's only required to be updated in one place: the GameState itself.

The GameRunner acts as an Anti Corruption Layer translating between the concerns of the Presentation Layer and that of the game's engine. As such it should contain presentation logic, and delegate changes to the game to GameState. If the GameRunner were to be concerned with the logic of the game as well, it would violate the Single Responsibility Principle. (There should be only one reason for a module, class, or function to change). It would now have to change if the presentation logic needed an update, or if the game logic needed to change.

Title: How to handle overlapping classes


问:
Is there something more behind MVC in web develop frameworks
I just started my career in the web development about two months ago. During the two months, I wrote one web service in php Symfony2, get involed investigation of one project written in Python Flask and also help debugging a web service using Java Spring MVC.

OK, here is the summary.

php Symfony2

python Flask

java Spring MVC

After getting a touch with these three frameworks, I've got to know that they are following the same pattern, MVC.

Controller

one front controller to recieve requests from clients and transform those requests to calls to functions within controller objects which are wriitten by developers.

View

after processing the requests, the framework uses the processing results to generate the pages that will be sent back the clients or just return some data to clients to response to ajax calls.

Model

I have not quite got the idea of Model. Perhaps it is the way of handling database?

Questions:

Is this workflow that I wrote above a standard way of writing web services? If so, could you give me some useful links that contain the offcial documments?

or is it just a custom followed by developers? or just an industrial standard.

I think there are still some other factors behind the MVC pattern, like filters. (I haven't got the chance to use filters in my project, but I think there is more than filters behind the scene.)

I was told that these frameworks get ideas from ruby on rails which introduces this workflow. Is that true? where can I get the full introduction or documents about this kind of web services workflow?

Thanks very much.

答:
You're asking a lot of questions here.  Forgive me while I focus on clearing up just one thing.

Model View Controller is an architectural pattern that is not unique to web development.  Anything with a user interface might make use of the MVC pattern.  It's a pattern that organizes flow of control into a loop as seen here:

Each step is a level of indirection.  The controller turns user input into manipulations of the model.  The model turns those manipulations into updates to the view.  The view turns those updates into something the user can see.  The user turns what they see into user input.  And so on.

Each step is also an abstraction. The model may be implemented as a database, data structure, file, etc.  The model should abstract much of this detail away with a simple API for changing it's state.  That way a change, from say file to database, wouldn't affect any code besides model code.

The controller may take input from a mouse, keyboard, touch screen, voice recognition, etc.  The controller should abstract much of that detail away by transforming it into requests to manipulate the state of the model.  That way a change from, say mouse to touch screen, wouldn't affect any code besides the controller code.

The view takes the representation of the model (which might be numbers or such) and presents it as something the user can see (which might be a GUI or a pie chart or such).  There might be multiple views that each represent a way to present the model.

MVC is a very old pattern and has been implemented in many different ways, for example:

 https://developer.chrome.com/apps/app_frameworks

Here the flow has changed drastically but each component should still have the same basic responsibilities and protect the others from changes.

I'm trying to take it back to basics.  THIS is what MVC really is.  There are a great many things that use it that add plenty of bells and whistles but the indirection and abstraction are what I think of as the "something more" behind MVC.


问:
How does garbage collection compare to reference counting?
I starting working through an online course on iOS development in the new language from Apple, Swift.  The instructor made a point that raised this question in my mind.  He said something to the effect of:

There's no need to worry about memory management because it's all
  taken care of for you by reference counting, and this means there's no
  need to worry about understanding how garbage collection works.

When I heard this I thought to myself, "why would anyone use garbage collection when you can simply use reference counting?"

So how do the two approaches compare?

答:
To understand how the two approaches compare we need to first examine how they work and the weaknesses of each.

Automatic Reference counting or ARC, is a form of garbage collection in which objects are deallocated once there are no more references to them, i.e. no other variable refers to the object in particular. Each object, under ARC, contains a reference counter, stored as an extra field in memory, which is incremented every time you set a variable to that object (i.e. a new reference to the object is created), and is decremented every time you set a reference to the object to nil/null, or a reference goes out of scope (i.e. it is deleted when the stack unwinds), once the reference counter goes down to zero, the object takes care of deleting itself, calling the destructor and freeing the allocated memory. This approach has a significant weakness, as we shall see below.

"There's no need to worry about memory management because it's all taken care of for you by reference counting," that's actually a misconception you still do need to take care to avoid certain conditions, namely circular references, in order for ARC to function correctly. A circular reference is when an object A holds a strong reference to an object B, which itself holds a strong reference to the same object A, in this situation neither object is going to be deallocated because in order for A to be deallocated its reference counter must be decremented to zero, but at least one of those references is object B, for object B to be deallocated, its reference counter must also be decremented to 0, but at least one of those references is object A, can you see the problem? ARC solves this by allowing the programmer to give compiler hints about how different object references should be treated, there are two types of references: strong references and weak references. Strong references are, as I mentioned above, a type of reference which prolongs the life of the referenced object (increments its reference counter), weak references are a type of reference which does not prolong the life of an object (that is, it does not increment the object's reference counter), but that would mean the referenced object could get deallocated and you'd would be left with an invalid reference pointing to junk memory. In order for this situation to be avoided, the weak reference is set to a safe value (e.g. nil in Objective-C) once the object is deallocated, thus the object has an extra responsibility of keeping track of all weak references and setting them to a safe value once it deletes itself. Weak references are usually used in a child-parent object relation, the parent holds a strong reference to all it's child objects, whereas the child objects hold a weak reference to the parent, the rationale being that in most cases if you no longer care about the parent object, you most likely no longer care about the child objects either.

Tracing garbage collection (i.e. what is most often referred to as simply garbage collection) involves keeping a list of all root objects (i.e. those stored in global variables, the local variables of the main procedure, etc) and tracing which objects are reachable (marking each object encountered) from those root objects. Once the garbage collector has gone through all the objects referenced by the root objects, the GC now goes through every allocated object, if it is marked as reachable it stays in memory, if it is not marked as reachable it is deallocated, this is known as the mark-and-sweep algorithm. This has the advantage of not suffering from the circular reference problem as: if neither the mutually referenced object A and object B are referenced by any other object reachable from the root objects, neither object A nor object B are marked as reachable and are both deallocated. Tracing garbage collectors run in certain intervals pausing all threads, which can lead to inconsistent performance (sporadic pauses). The algorithm described here is a very basic description, modern GC's are usually much more advanced using an object generation system, tri-color sets etc, and also perform other tasks such as defragmentation of the program's memory space by moving the objects to a contiguous storage space, this is the reason why GC'ed languages such as C# and Java do not allow pointers. One significant weakness of tracing garbage collectors is that class destructors are no longer deterministic, that is the programmer cannot tell when an object is going to be garbage collected in-fact GC'ed languages do not even allow the programmer to specify a class destructor, thus classes can no longer be used to encapsulate the management of resources such as file handles, database connections, etc. The responsibility is left on the programmer to close open files, database connections manually, hence why languages such as Java have a finally keyword (in the try,catch block) to make sure the cleanup code is always executed before the stack unwinds, whereas in C++ (no GC) such resources are handled by a wrapper object (allocated on the stack) which acquires the resource in the constructor and releases it in the destructor, which is always called as the object is removed from the stack.

As for performance, both have performance penalties. Automatic reference counting delivers a more consistent performance, no pauses, but slows down your application as a whole as every assignment of an object to a variable, every deallocation of an object, etc, will need an associated incrementation/decrementation of the reference counter, and taking care of reassigning the weak references and calling each destructor of each object being deallocated. GC does not have the performance penalty of ARC when dealing with object references; however, it incurs pauses while it is collecting garbage (rendering unusable for real-time processing systems) and requires a large memory space in order for it to function effectively such that it is not forced to run, thus pausing execution, too often.

As you can see both have their own advantages and disadvantages, there is no clear cut ARC is better or GC is better, both are compromises.

PS: ARC also becomes problematic when objects are shared across multiple threads requiring atomic incrementation/decrementation of the reference counter, which itself presents a whole new array of complexities and problems. This should answer your question as to "why would anyone use garbage collection".


答:
In this specific case, it's a bug in an API of an internally-used library that other developers use.

If those other developers thought the behaviour to be a feature, it is likely they have used it and have build working software upon it. Fixing the bug will probably break their existing code, and they will blame you for this. This makes fixing the bug a trade-off, and you have to consider

is it really important to fix the bug, for example because there is a high risk of letting users of your API crash their applications in case the bug is not fixed? Or is this just about consistency of the API?

or is it more important to keep the existing software stable, and your library backwards-compatible?

The answer to the question is not always simple, you have to take the number of possible users of your API into account, the potential amount of work they will have to change their software, the amount of software which will break if you change your API, but also the risks of what might happen if you do not fix the API.

Just because you document the bugfix change in a "list of breaking changes in your next major release" does not make your customers happy - if you do this, there should be at least some bullet proof reasoning why you could not let the API as it was before. Often keeping backwards compatibility is more important than fixing a bug. So fix it only if you can estimate the impact on your user base and their software and you are sure you are not going to produce unreasonable efforts for them when they try to update to your latest library release. And if you do not have enough information to make a good estimate on this, it will probably be better not to change the behaviour.

(And yes, if you are going to make an API change which is not backwards compatible, your version numbers must express this clearly, does not matter if you name it a "bugfix" or not).


答:
Manual memory management, reference counting, and garbage collection all have their pro's and con's:

Manual memory management: Unbeatable fast, but prone to bugs due to errors in freeing the memory. Also, oftentimes you will need to implement at least reference counting on top of manual memory management yourself when you get several objects that all require a single object to remain alive.

Reference counting: Small overhead (incrementing/decrementing a counter and a zero check is not that expensive), allows easy management of quite complex data structures, where every object may be referenced by several others. The deficiency is that reference counting requires references not to be circular. Once you get reference circles, you leak memory.

Weak references may be used to break some reference cycles, however, they come with quite a bit of additional costs:

Weak references require a second reference count to manage the weak reference itself. Likely, the weak reference is another object that needs to be allocated independently, incurring a significant overhead in memory consumption.

Destroying an object in the presence of weak references requires atomically resetting the weak reference that belongs to the object and decrementing the reference count. Otherwise you get erratic behavior of the weak references. I'm not into the details, but I believe this can be hard to achieve in a lock-free fashion.

This can all be done, but it's not as simple as reference counting without weak references.

Garbage collection: Can cope with all possible dependency graphs, but has quite severe performance impact. After all, the garbage collector has to prove somehow that an object is not reachable anymore before it can collect it. Modern garbage collectors are quite good at avoiding long lags while they do their work, but the work needs to be done somehow. This is especially bad for real-time applications that need to guarantee a response within a given time frame.

As you see, the three methods all have situations where they are best: If you can easily do manual management and your program has tight performance constraints, manual memory management may be the way to go. And as long as you can use reference counting over garbage collection, that's considerably faster and does not incur spurious lags. Nevertheless, sometimes you must use garbage collection because you cannot guarantee cycle free references.

Languages that use garbage collection for everything have just decided that ease of use is more important to them than allowing for performance sensitive applications.

Title: How does garbage collection compare to reference counting?

Body:
I starting working through an online course on iOS development in the new language from Apple, Swift.  The instructor made a point that raised this question in my mind.  He said something to the effect of:

There's no need to worry about memory management because it's all
  taken care of for you by reference counting, and this means there's no
  need to worry about understanding how garbage collection works.

When I heard this I thought to myself, "why would anyone use garbage collection when you can simply use reference counting?"

So how do the two approaches compare?


问:
Ternary operator considered harmful?
For example, would you prefer this one-liner

```<code>int median(int a, int b, int c) {
    return (a<b) ? (b<c) ? b : (a<c) ? c : a : (a<c) ? a : (b<c) ? c : b;
}
</code>```

or an if/else solution involving multiple return statements?

When is ?: appropriate, and when is it not? Should it be taught to or hidden from beginners?

答:
One difference that (I think) no-one has pointed out is that if-else can't return a value, whereas the ternary operator can.

Coming from F#, I sometimes like to use the ternary operator to mimic pattern matching.

```<code>match val with
| A -> 1
| B -> 3
| _ -> 0
</code>```

vs

```<code>return val == A ? 1 :
       val == B ? 3 :
       0;
</code>```

Title: Ternary operator considered harmful?

Body:
One difference that (I think) no-one has pointed out is that if-else can't return a value, whereas the ternary operator can.

Coming from F#, I sometimes like to use the ternary operator to mimic pattern matching.

match val with
| A -> 1
| B -> 3
| _ -> 0

vs

return val == A ? 1 :
       val == B ? 3 :
       0;


问:
What is the algorithmic time complexity of this program?
I wrote a simple program in java to create and maintain Dynamic Arrays:

```<code>public class DynamicArrays {
    private Integer[] input = new Integer[1];
    private Integer length = 0;
    private Integer capacity = 1;

    /**
    * Big O Analysis of add:
    * 1+1+addBulk
    * 2+O(n)
    * So it seems add is an O(n) operation!
    * But add is only called when capacity is full and how many times can that happen?
    * Let's say there are 8 elements added.
    * so capacity will become full after 1st, 2nd, 4th additions. so its is Log(n) times?
    */
    public void add(Integer i) {
        input[length] = i;
        length++;
        if(capacity <= length)
            addBulk();
    }

    /**
    * Big O: O(n)
    */
    public void addBulk() {
        Integer[] newInput = new Integer[2*capacity];
        for(int i=0;i<input.length;i++)
            newInput[i] = input[i];
        input = newInput;
        capacity = capacity*2;
    }
}
</code>```

Now I wonder what is the time complexity of the add operation? If addBulk() is not called, it is O(1). Else it is O(n) because addBulk() copies all the elements. However addBulk is called log(n) times of the total input.

So is the complexity O(n*log(n)) ?

I also read somewhere that the amortized complexity of dynamic arrays addition is O(2*n), hence O(n). I couldn't relate to that point from the code.

Can you please clarify?

答:
The n log(n) calculation is a lower bound. It is correct in this case, but not tight - that is, it will really be O(n log(n), due to the reasoning you stated, but it will not be Theta( n log(n)).

see here why it is Theta(n).


答:
Since the bug is in a library, here is another approach that you can take:

Make a clone of the erroneous library function. In many cases people just append a 2 to the function name in these cases, but, if you have other changes that you would like to apply to the interface of that function, you might also give it a completely different name.

Fix the bug in the clone only (and implement all other interface changes that you want while you're at it).

Declare the original function as deprecated.

Remove the original function in some upcoming major release.

This approach is especially useful for functions whose interface is fundamentally broken: You don't break user code right away, but you give due warning to whoever relies on the broken code to transition to using the fixed code. And even if people don't heed the warning, they can't really blame you once you actually remove the broken function.


问:
Why does a custom action filter need to inherit from both ActionFilterAttribute and IActionFilter?
I m first time creating a custom action filter and following this link http://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-custom-action-filters

They are saying to Extend ActionFilterAttribute class and also implement IActionFilter interface. ActionFilterAttribute already implement IActionFilter. I  m wondering why I need to implement Interface again in my attribute class. Is is something a must to do ? Will highly appreciate if you please can clear this ambiguity.

答:
Or maybe it`s simply a mistake. for instance you can eather inherit from

FilterAttribute, IActionFilter

Or

ActionFilterAttribute

the first one provides low level behavior of MVC Attributes plus Order and AllowMultiple properties.

and the second one provides less details plus OnResultExecutingand OnResultExecuted capabilities.


问:
Emulate 12bit uint in c#
I recently had to do a codility test. The question itself was reasonably easy. take a string of numbers and +, * loop through it, if the character is a number, add it to a stack, if its an operation pop two items off the stack, perform the operation and put the result back on the stack.

The tricky small print however, specifed that the stack store values as 12 bit unsigned ints.

This gave me a lot of trouble I tried bitwise shifting back and forth but got negative numbers and eventualy I had to just do % 4096 before I ran out of time.

Also I realised that really I might have to create a special 12bit add and multiply operators, or would I be ok just converting a 16bit result?

Have I missed a trick?

What is the best way to emulate 12 bit uint math in c#?

答:
A simple operation like

```<code>  PushToStack(uint32 value)
  {
     _stack.Add(value % 4096);
  }
</code>```

should be sufficient, as long as you use this function exclusively for pushing values to your stack.

Note that (a+b)%n == (a%n + b%n)%n and (a*b)%n == ((a%n) * (b%n))%n for a and b >=0 and n>0.

Furthermore, when you add or multiply two values from the stack, the input values are already 12 bit, so the output has at maximum 24 bit, so you can do this using unsigned or signed 32bit arithmetics without getting an overflow. Thus there will be never any negative value occur, and any kind of bit shifting is unnecessary. And as soon as the result is pushed to the stack again, it becomes 12 bits again.

Title: Emulate 12bit uint in c#

Body:
A simple operation like

  PushToStack(uint32 value)
  {
     _stack.Add(value % 4096);
  }

should be sufficient, as long as you use this function exclusively for pushing values to your stack.

Note that (a+b)%n == (a%n + b%n)%n and (a*b)%n == ((a%n) * (b%n))%n for a and b >=0 and n>0.

Furthermore, when you add or multiply two values from the stack, the input values are already 12 bit, so the output has at maximum 24 bit, so you can do this using unsigned or signed 32bit arithmetics without getting an overflow. Thus there will be never any negative value occur, and any kind of bit shifting is unnecessary. And as soon as the result is pushed to the stack again, it becomes 12 bits again.


问:
Design Pattern - DLL per Strategy
I usually found myself designing my application in the following way:

One DLL containing interfaces for a desired subsystem. For example, Company.Framework.Persistence.dll.

One new DLL per each strategy (or implementations) of the said subsystem. For example:

Company.Framework.Persistence.MSSQL.dll

Company.Framework.Persistence.MySQL.dll

Company.Framework.Persistence.FileSystem.dll

This will result in a very big solution with a lot of projects, but on the other hand, would give the consumer the chance to choose the appropiate DLL for his needs.

If we had a single DLL called Company.Framework.Persistence.dll, the consumer would have to load a lot of strategies that he may never use. Having modularized DLL would solve this problem.

Is this good practice? Is there a disadvantage with this design?

答:
I think that the advantages of this approach far, far outweigh any disadvantages.

What you're achieving here is more ore less a perfect "implementation" of the I in SOLID by way of the Stairway pattern - that is to say, your application depends "down" on an interface defined in Company.Framework.Persistence.dll and the individual implementations themselves also depend "up" on this abstraction.

This means your application is highly decoupled from any implementation details (of course you'll typically want to compose the actual runtime graph using an IOC Container of some sort)
I have shamelessly linked to an existing picture of this pattern from another answer on the subject on Stack Overflow:

In the book Adaptive Code via C# the author talks about this approach and specifically calls it out as something that should always be done because it provides such a high level of decoupling. (example)

Another possible advantage is being able to patch individual implementations without worrying that you might have affected others, although this is a fairly minor one once you have been diligent with your regression tests; also being able to deploy the individual implementations in sub-folders which can also contain the specific versions of any 3rd party dependencies they might need is probably going to help keep things nicely organised.

About the only real disadvantage I can think of with this approach is that is that it's possible in theory to change the interface in Company.Framework.Persistence.dll (along with your application's binaries) and neglect to update the corresponding implementation dlls which will lead to runtime errors for your users.

Having been guilty of doing exactly this in the past, I can say that this is really only something that can happen if you are very careless :)

Title: Design Pattern - DLL per Strategy


答:
The instructor is wrong. You better know how garbage collection and reference counting works.

With garbage collection, the problem is that you may still have left some reference to an object around somewhere. There was a case where an early self-driving vehicle crashed because references to information about previous locations were stored in an array and never became garbage, so after 45 minutes it ran out of memory and crashed. I think not literally, it stopped driving, but it might have crashed as well.

With reference counting, the problem is that you may have cyclic references A->B->A or A->B->C->...->Z->A, and no reference count ever goes to zero. That's why you have weak references and you need to know when to use them.

Both ways, you need to understand how things work, or you will get into trouble. Performance wise, if you ask Java developers they say garbage collection is faster; if you ask say Objective-C developers they say reference counting is faster. Studies prove what they want to prove. If it makes a difference, you should reduce the number of allocations, not switch languages.

You also need to know about weak references, basically a reference to an object that doesn't keep the object alive. And you need to know what happens exactly once it has been decided that an object should be thrown out; in Java I think there are ways how an object could become alive again, in Objective-C / Swift once the reference count is zero, that object is going to go away no matter what you try to hold on to it. Well, unless you add a line for (;;) ; in the dealloc / deinit method :-(


问:
Storing data in code
A few times in my past I've wanted to store data in code. This would be data that seldom changes and is used in places where access to a database isn't possible, practical, or desirable. A small example would be storing a list of countries. For that you could do something like:

```<code>public class Country
{
    public string Code { get; set; }
    public string EnglishName {get;set;}
}

public static class CountryHelper
{
    public static List<Country> Countries = new List<Country>
        {
            new Country {Code = "AU", EnglishName = "Australia"},
            ...
            new Country {Code = "SE", EnglishName = "Sweden"},
            ...
        };

    public static Country GetByCode(string code)
    {
        return Countries.Single(c => c.Code == code);
    }
}
</code>```

I've got away with doing this in the past because the data sets were relatively small and the objects pretty simple. Now I'm working with something that will have more complex objects (5 - 10 properties each, some properties being dictionaries) and around 200 objects total.

The data itself changes very rarely and when it does change it's really not even that important. So rolling it into the next release version is perfectly fine.

I'm planning to use T4 or ERB or some other templating solution to turn my data source into something that is stored statically in the assembly.

It seems my options are

Store the data in XML. Compile the XML file as an assembly resource. Load data as needed, store loaded data into a Dictionary for repeat-use performance.

Generate some kind of static object or objects that are initialized at startup.

I'm pretty sure I understand the performance implications of option 1. At least, my hunch is that it wouldn't have stellar performance.

As for option 2, I don't know what to do. I don't know enough about the internals of the .NET framework to know the best way to actually store this data in C# code and the best ways to initialize it. I poked around using .NET reflector to see how System.Globalization.CultureInfo.GetCulture(name) works, since this is actually a very similar workflow to what I want. Unfortunately that trail ended at an extern, so no hints there. Is initializing a static property with all the data, as in my example, the way to go? Or would it be better to create the objects on demand and then cache them, like this?

```<code>    private static readonly Dictionary<string, Country> Cache = new Dictionary<string,Country>();

    public static Country GetByCode(string code)
    {
        if (!Cache.ContainsKey(code))
            return Cache[code];

        return (Cache[code] = CreateCountry(code));
    }

    internal static Country CreateCountry(string code)
    {
        if (code == "AU")
            return new Country {Code = "AU", EnglishName = "Australia"};
        ...
        if (code == "SE")
            return new Country {Code = "SE", EnglishName = "Sweden"};
        ...
        throw new CountryNotFoundException();
    }
</code>```

The advantage to creating them at once in a static member is that you can use LINQ or whatever else to look at all the objects and query them if you want. Though I suspect doing this has a startup performance penalty. I'm hoping someone has experience with this and can share their opinions!

答:
The decision is really: Do you want only the developer (or anyone with access to a build system) to modify the data when it needs modifying, or should an end user or possibly someone in the organisation of the end user be able to modify the data?

In the latter case, I'd suggest that a file in user-readable and user-editable format would be stored in a place where the user can access it. Obviously when you read the data you need to be careful; whatever you find cannot be trusted to be valid data. I'd probably prefer JSON to XML; I find it easier to understand and get right. You might check if there is an editor available for the data format; for example if you use a plist on MacOS X then every user who should ever go near the data will have a decent editor on his computer.

In the first case, if the data is part of your build, it doesn't really make a difference. Do what's most convenient for you. In C++, writing the data with minimal overhead is one of the few places where macros are allowed. If the work of maintaining the data is done by a third party, you can send them the source files, let them edit them, and you are then responsible for checking them and using them in your project.

Title: Storing data in code


问:
Dependency inversion without static methods?
It's clear that the dependency inversion principle and the use of interfaces makes software components less coupled and promotes maintainability. On the other hand, these principles make using static methods and factories necessary.
I think static methods should be out of any good object-oriented design, since they pollute the code with imperative programming practices that don't have anything to do with pure OOP.

My question is the following: is there a way to accomplish the DIP and effectively use interfaces to decouple components  without using static factory methods? Is it so hard to design maintainable software with pure and simple OOP? Are encapsulation, inheritance and polymorphism really not enough?

答:
On the other hand, these principles make using static methods and factories necessary.

Since when?

I think static methods should be out of any good object-oriented design, since they pollute the code with imperative programming practices that don't have anything to do with pure OOP.

You could, but you'd be wrong. Modern OO design often includes static methods to incorporate functional programming concepts where appropriate. Remember that your job is to get stuff done, not purity. Sometimes the solution calls for a standalone (pure) function, so doing something else is making worse code.

Are encapsulation, inheritance and polymorphism really not enough?

These are not OO. They are the OO taught by Java schools, the foundation laid over a decade ago that people have reiterated since. They are really not enough, since they have very little impact on coupling, the key measure of code quality. Hell, inheritance itself is frowned upon these days in many situations.

Anyways, back to your code question:

is there a way to accomplish the DIP and effectively use interfaces to decouple components without using static factory methods?

Yes, it is super simple. You make a class that takes its dependencies (as interfaces) in its constructor. The code that uses that class either knows what concrete type to make, or has an instance of the interface itself (since it is a dependency). The code that uses that class passes the dependency in as a parameter. The class itself can then be wholy ignorant of the concrete type, getting the decoupling you want. No needless factories, no static methods.