问:
Is using for loop syntax for a "with(variable)" block an anti-pattern?
I fooled around with for-loops, remembered the with keyword from delphi and came up with following pattern (defined as a live template in IntelliJ IDEA):

```<code>for ($TYPE$ $VAR$ = $VALUE$; $VAR$ != null; $VAR$ = null) {
    $END$
}
</code>```

Should I use it in productive code? I think it might be handy for creating temporary shortcut variables like these one-character variables in lamdas and couting for loops. Plus, it checks if the variable you are going to use in the block is null first. Consider following case in a swing application:

```<code>// init `+1` button
for (JButton b = new JButton("+1"); b != null; add(b), b = null) {
    b.setForeground(Color.WHITE);
    b.setBackground(Color.BLACK);
    b.setBorder(BorderFactory.createRaisedBevelBorder());
    // ...
    b.addActionListener(e -> {
        switch (JOptionPane.showConfirmDialog(null, "Are you sure voting +1?")) {
            case JOptionPane.OK_OPTION:
                // ...
                break;
            default:
                // ...
                break;
        }
    });
}
</code>```

答:
It's not an anti-pattern, because that would mean it is a commonly used technique that's problematic somehow. This code fails to meet the "commonly used" criterion.

However, it is problematic. Here are some of its problems:

Misleading: it uses a loop structure, but never executes more than once.

Hiding a check: the != null check is easy to miss where it is placed. Hidden code is harder to understand. It's also not clear whether the condition is actually necessary or just there to terminate the loop after the first iteration. (Your statements about the check indicate that you have situations where it's necessary, whereas in your example it's not, as new never returns null.)

Hiding an action: the add(b) statement is hidden even better. It's not even sequentially at the position where you'd expect it.

Unnecessary: You can just declare a local variable. If you don't want its name to be visible, you can use a block statement to limit its scope, although that would be an anti-pattern (or at least a code smell), indicating that you should extract a function.


答:
What you are doing is obfuscating your code, not making it clearer. It takes a lot of effort to understand that this “loop” will only execute once. Instead, you could just use a statement block to restrict the variable's scope:

```<code>{
    JButton b = new JButton("+1");
    b.setForeground(Color.WHITE);
    ...
}
</code>```

If you're into lambdas, you could also define a static with function that allows usage such as

```<code>with(new JButton("+1"), b -> {
    b.setForeground(Color.WHITE);
    ...
});
</code>```

This may be a bit clearer, but is still a lot of indirection compared with the simple block that achieves the same thing, without any chance of introducing new errors.

ContentLicense: CC BY-SA 3.0

Title: Is using for loop syntax for a "with(variable)" block an anti-pattern?

Body:
I fooled around with for-loops, remembered the with keyword from delphi and came up with following pattern (defined as a live template in IntelliJ IDEA):

```<code>for ($TYPE$ $VAR$ = $VALUE$; $VAR$ != null; $VAR$ = null) {
    $END$
}
</code>```

Should I use it in productive code? I think it might be handy for creating temporary shortcut variables like these one-character variables in lamdas and couting for loops. Plus, it checks if the variable you are going to use in the block is null first. Consider following case in a swing application:

```<code>// init `+1` button
for (JButton b = new JButton("+1"); b != null; add(b), b = null) {
    b.setForeground(Color.WHITE);
    b.setBackground(Color.BLACK);
    b.setBorder(BorderFactory.createRaisedBevelBorder());
    // ...
    b.addActionListener(e -> {
        switch (JOptionPane.showConfirmDialog(null, "Are you sure voting +1?")) {
            case JOptionPane.OK_OPTION:
                // ...
                break;
            default:
                // ...
                break;
        }
    });
}
</code>```

Body:
What you are doing is obfuscating your code, not making it clearer. It takes a lot of effort to understand that this “loop” will only execute once. Instead, you could just use a statement block to restrict the variable's scope:

{
    JButton b = new JButton("+1");
    b.setForeground(Color.WHITE);
    ...
}

If you're into lambdas, you could also define a static with function that allows usage such as

with(new JButton("+1"), b -> {
    b.setForeground(Color.WHITE);
    ...
});

This may be a bit clearer, but is still a lot of indirection compared with the simple block that achieves the same thing, without any chance of introducing new errors.


问:
Is the word 'statement' in 'statement block' redundant?
Is the word 'statement' in 'statement block' redundant?

In other words is a block in a program composed, by definition, of statements?

答:
Many languages don't have statements, only expressions. Ruby, for example, doesn't have statements, but it does have blocks:

```<code>begin
  some_expression
  some_other_expression
  a_third_expression
end
</code>```

Since Ruby doesn't have statements, which means everything is an expression, which means everything has a value, obviously blocks are expressions and have values, too:

```<code>foo = begin
  some_expression
  some_other_expression
  a_third_expression
end
</code>```

There are no statements in this Ruby block, since there are no statements in Ruby, period.

[Note: Ruby has a construct called block, which is not the kind of block you are asking about. It is a syntactically light-weight anonymous first-class procedure. The word "block" is also sometimes used for "documentation blocks" or "comment blocks", again, these are not the kinds of "block" you are asking about.]

Body:
Many languages don't have statements, only expressions. Ruby, for example, doesn't have statements, but it does have blocks:

begin
  some_expression
  some_other_expression
  a_third_expression
end

Since Ruby doesn't have statements, which means everything is an expression, which means everything has a value, obviously blocks are expressions and have values, too:

foo = begin
  some_expression
  some_other_expression
  a_third_expression
end

There are no statements in this Ruby block, since there are no statements in Ruby, period.

[Note: Ruby has a construct called block, which is not the kind of block you are asking about. It is a syntactically light-weight anonymous first-class procedure. The word "block" is also sometimes used for "documentation blocks" or "comment blocks", again, these are not the kinds of "block" you are asking about.]


问:
The granularity level to repeat code: should downloading, unzipping etc. be handled by separate classes?
I make extensive use of DI, but I wonder, where is the 'granurality' limit, when some set of functionality should be separated to a class - lets take an example:

```<code>public class DownloadManager : IDownloadManager
{
    public Uri ResourceIdentifier { get; }
    public DownloadManager(Uri uniqueResourceIdentifier)
    {
        if (!uniqueResourceIdentifier.IsWellFormedOriginalString()) throw new ArgumentException(nameof(uniqueResourceIdentifier));
        ResourceIdentifier = uniqueResourceIdentifier;
    }
    public DownloadManager(string uniqueResourceIdentifier) : this(new Uri(uniqueResourceIdentifier)) { }

    public async Task<byte[]> GetBytesAsync(CancellationToken token = new CancellationToken())
    {
        using (var client = new HttpClient())
        using (var response = await client.GetAsync(ResourceIdentifier, token).ConfigureAwait(false))
        {
            var data = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
            return data;
        }
    }
}
</code>```

It looks for me that this class brings almost no additional benefit, and even hinders some operations:

what if we need a stream (ReadAsStreamAsync())?

it's not a great idea
to litter the code with async, as it spreads like GPL (also see Task
etiqutte).

may lead (but in this case it rather promotes composition) to yo-yo problem

and could be replaced with a static method like this (or even the extension to Uri class):

```<code>public static async Task<byte[]> GetBytesAsync(/*this */Uri uniqueResourceIdentifier, CancellationToken token = new CancellationToken())
{
    if (!uniqueResourceIdentifier.IsWellFormedOriginalString()) throw new ArgumentException(nameof(uniqueResourceIdentifier));
    using (var client = new HttpClient())
    using (var response = await client.GetAsync(uniqueResourceIdentifier, token).ConfigureAwait(false))
    {
        var data = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
        return data;
    }
}
</code>```

But one cannot simply DI a static method, so this will be wrapped in thin class implementing an interface.

Option 3: The third option would be, the code could be written just where it's needed (the API is great, almost no redundant configuration), risking, that if needed, the code will need to be refactored (or copied) in the future. Also, it could be tempting than to make a god-class like FileManager, which will download, unzip CRUD & all, but sacrificing freedom and 'S' from SOLID.

Which one is preferred in this specific case (almost the same goes
for file unzipping, using ZipArchive and couple more of great MS
APIs)?

Based on what, should I make a decision which one of this
three approaches to take?

答:
I'm not sure I follow all the code details, example and options you put in the text of your question. But I'll address the title of the question specifically, that is "The granularity level to repeat code":

There's not a fixed rule about granularity; design is not about fixed rules (otherwise we'd just write a computer program to do designs and a lot of developers would be... working for Über?). Design has heuristics, which are like rules of thumb that seem to have worked well in the past for certain types of problems.

The General Responsibility Assignment Software Patterns (GRASP) are pretty useful heuristics for design (no so different from SOLID). In your case, it sounds a lot like the problem solved by the Pure Fabrication principle (emphasis mine):

Who is responsible when you are desperate, and do not want to violate high cohesion and low coupling?

Assign a highly cohesive set of responsibilities to an artificial or convenience "behavior" class that does not represent a problem domain concept—something made up, in order to support high cohesion, low coupling, and reuse.

Your DownloadManager class is definitely reusable and it looks pretty cohesive. I'm not sure about the DI necessity, unless it's really something that varies in implementations (but that's another question).

I highlighted the word desperate above, because the granularity notion you seek is there. As you assign responsibilities to classes in your design, at some point you realize that giving the downloading (or unzipping) responsibility to other classes violates the strong cohesion principle, and so you're not satisfied by that (Larman's choice of the word "desperate" is probably hyperbole, as a way to get it to stick in your brain).

The solution is to essentially refactor that responsibility into a separate class that is very cohesive. Pure Fabrication is a lot like the Extract Class refactoring, except pure fabrications don't seem like problem-domain classes. The example for Extract Class has a new class called TelephoneNumber, which sounds like a problem-domain class. But your DownloadManager class sounds like a solution-domain class (especially the Manager part).

The Visitor classes in GoF pattern by the same name are also great examples of Pure Fabrications. They are highly cohesive, but came about only after developers got frustrated with adding non-cohesive responsibilities to classes in a data structure. It helps to think of the design before they existed.

OwnerDisplayName: Piotr Falkowski


问:
why are iframe-s so useful in HTML5 WYSIWIG applications?
 elements are documented as

The HTML Inline Frame Element () represents a nested browsing context, effectively embedding another HTML page into the current page.

However, most WYSIWYG editors HTML5 frameworks (such as tinymce, Aloha, Maqetta, etc...) are using a lot  but they intuitively do not need a new nested browsing context... (the canonical example of  is to show another website, but all the WYSIWYG editors in HTML I heard about are usable on the same website).

So why is  so important in that case? We know that contenteditable is terrible (so is probably not enough for WYSIWYG editors in HTML5).

(I guess it is related to event handling & capturing & bubbling, but I don't understand the relationship with s)

PS. This SO question gives the motivation and the context of my question, and this one explains why contenteditable is disappointing for me.

答:
Isolation

By having the editor inside an iFrame it is guaranteed to be isolated from the page it is used in. The containing page can have Javascript, CSS, HTML tags,... that might interfere with the editor if it is not in an iFrame because they might 'bleed into' it. The editor would need to set css styles for every possible element to make sure that the styling from the containing page does not bleed into it and get applied where it does not make sense. This is simply not possible.

It also works in the other direction: even if the markup of the editor itself becomes corrupted, using an iFrame means that the content of the editor can be broken, but not the editor itself. If you use the editor for a blog you don't want a broken post to completely kill your ability to edit the broken post. If the editor's save button breaks you lose any and all ability to remove the content.

That is not to say a targeted attack could not break the WYSIWYG editor as there are still ways you can interfere with an iFrame's contents...


问:
Why does the LGPL require combined works to include a copy of the GPL?
I was reading through the LGPL license and found a requirement that I was previously unaware of.

Section 4 (Combined Works) states:

You may convey a Combined Work [...] if you also do each of the
  following:

a) Give prominent notice with each copy of the Combined
  Work that the Library is used in it and that the Library and its use
  are covered by this License.

b) Accompany the Combined Work with a
  copy of the GNU GPL and this license document.

c) ...

Why must the GPL also be conveyed when linking to libraries licensed under the LGPL?  I fear that including both licenses in the distribution would confuse the user as to which one applies.  Am I interpreting this correctly?  If so, what is the reasoning behind this requirement?

答:
The likely reason is that the LGPL is considered a less restrictive license than the GPL.  In particular, it is possible to combine LGPL projects with other projects and not force those projects to be LGPL.  That's a lot more difficult to do with a GPL project.  Generally, if you combine a project with a GPL project, the combined project must be released as GPL.

In order to combine an LGPL project with a GPL project, the restrictions of the GPL project need to be maintained.

Taking a step back, and looking at it from the broader FSF philosophy of "Software is meant to be Free", you can see why they would have that clause within the LGPL.  LGPL doesn't have as much of a "viral effect" as the GPL does, and the FSF wants GPL'd software to be preserved as being under the GPL.


答:
The LGPL is not a license of its own, but an extension of the GPL. It states:

This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.

The LGPL license document only contains the extensions, so to provide the complete license you will also need to copy the vanilla GPL. It is reasonable to require a user of a LGPL library to provide the full license of the library they are using.

Title: Why does the LGPL require combined works to include a copy of the GPL?

Body:
I was reading through the LGPL license and found a requirement that I was previously unaware of.

Section 4 (Combined Works) states:

You may convey a Combined Work [...] if you also do each of the
  following:

a) Give prominent notice with each copy of the Combined
  Work that the Library is used in it and that the Library and its use
  are covered by this License.

b) Accompany the Combined Work with a
  copy of the GNU GPL and this license document.

c) ...

Why must the GPL also be conveyed when linking to libraries licensed under the LGPL?  I fear that including both licenses in the distribution would confuse the user as to which one applies.  Am I interpreting this correctly?  If so, what is the reasoning behind this requirement?


问:
How much should I be using 'let' vs 'const' in ES6?
I've been writing a lot of ES6 code for io.js recently. There isn't much code in the wild to learn from, so I feel like I'm defining my own conventions as I go.

My question is about when to use const vs let.

I've been applying this rule: If possible, use const. Only use let if you know its value needs to change. (You can always go back and change a const to a let if it later turns out you need to change its value.)

The main reason for this rule is it's easy to apply consistently. There are no grey areas.

The thing is, when I apply this rule, in practice 95% of my declarations are const. And this looks weird to me. I'm only using let for things like i in a for loop, or occasionally for things like accumulated Fibonacci totals (which doesn't come up much in real life). I was surprised by this – it turns out 95% of the 'variables' in my ES5 code to date were for values that do not vary. But seeing const all over my code feels wrong somehow.

So my question is: is it OK to be using const this much? Should I really be doing things like const foo = function () {...};?

Or should I reserve const for those kind of situations where you're hard-coding a literal at the top of a module – the kind you do in full caps, like const MARGIN_WIDTH = 410;?

答:
Don't worry about it. const is an amazing addition to JavaScript, and I would recommend you use it all the places it makes sense. It makes for more robust code.

When it comes to objects, const will protect your variable from reassignment, but if you need immutable objects, you will need the Object.freeze method, see below.

```<code>const immutableOject = Object.freeze({immutableProperty: 'foo'});
</code>```

const will protect only from reassignment, and the freeze method will protect all immediate properties. If you need all nested properties to be immutable also, then you will need to recursively freeze them.

Body:
Don't worry about it. const is an amazing addition to JavaScript, and I would recommend you use it all the places it makes sense. It makes for more robust code.

When it comes to objects, const will protect your variable from reassignment, but if you need immutable objects, you will need the Object.freeze method, see below.

const immutableOject = Object.freeze({immutableProperty: 'foo'});

const will protect only from reassignment, and the freeze method will protect all immediate properties. If you need all nested properties to be immutable also, then you will need to recursively freeze them.


问:
Testing base-62 converter
I have a converter module which encodes non-negative numerics to base 62 strings and vice versa.

I'm not very experienced with testing, and I got this so far:

Encode

Test for negative numbers

Test for non-numerics

Test result for basic input

Decode

Test for numerics

Test result for basic input

Codec - encode and decode

encoding randomly generated numbers and decoding them back to check the result

What is the best approach for testing such a module?

答:
You have most of what you should test. For most modules, you should focus your tests on

Behaviour for well-formed input: Verify that the encoder can convert numbers to their correct base-62 representation and that the decoder can convert a valid base-62 representation to the corresponding number. Pick your numbers such that you can verify as many features of the base-62 representation as possible.

Behaviour for malformed input: Verify that the encoder handles invalid input (negative numbers, wrong type, etc.) appropriately. The same for invalid input to the decoder (wrong type, a string that isn't a valid base-62 representation, etc.)

Boundary conditions: Test for edge-cases in valid input (for example, 0 or the largest possible number), or numbers that might be troublesome for your algorithm (for example, should the result of encode(10) be a or A?)

Title: Testing base-62 converter


问:
Functional programming: Compare all items in an array
In functional programming, how do I do an equality comparison of all items in an array?

I have an array of items that I want to compare, for example for equality. Is it possible to use a fold (also known as reduce) operation for this?

This code won't work, because after the first iteration, memo is a boolean:

```<code>[a, b, c].reduce((memo, item) => memo === item)
</code>```

I've tried this variant, which returns the last item if they are equal, but this is no good, since I need a boolean as the result:

```<code>[a, b, c].reduce((memo, item) => (memo === item) && item)
</code>```

Forcing a boolean !! is no good either, since the item itself may be falsy and so give the wrong result.

I would like to have a functional solution to this problem – saving the result outside of the fold is much more verbose.

答:
Well, I have over 10 years of functional programming experience, and here's how I would do it:

If the sequence is empty, return true

Otherwise, return true if and only if all of the elements of the sequence are equal to the first one.

In Haskell, that starts out like this:

```<code>-- | Return false if and only if there is a pair of unequal elements
-- in the list.
allEqual :: Eq a => [a] -> a
allEqual [] = True
allEqual (first:rest) = all (\elem -> elem == first) rest
</code>```

The all function tests whether all elements of a list satisfy a specified condition.  In this case, the condition is (\elem -> elem == first)—a function that tests whether the given elem is equal to first.

The all function is provided in the Data.List library module, but let's implement it ourselves:

```<code>-- | Apply the given test to every element in the list, and return
-- false if and only if at least one element tests false.
all :: (a -> Bool) -> [a] -> Bool
all test items = and (map test items)
</code>```

To implement all I used two other standard functions—map and and.  But let's just go and implement them ourselves:

```<code>-- | Return true if and only if there are no `False` elements in the list
and :: [Bool] -> Bool
and bools = foldr (&&) True bools

-- | Apply the given function to all elements of the list, collecting
-- the results in a list.
map :: (a -> b) -> [a] -> [b]
map f = foldr go []
  where go item rest = f item : rest
</code>```

And those two functions I wrote in terms of foldr ("fold right"), which is one such "reduce" operation that you're interested in.  For completeness, let's write that function:

```<code>foldr :: (a -> r -> r) -> r -> [a] -> r
foldr _ z [] = z
foldr f z (a:as) = f a (foldr f z as)
</code>```

And now let me point out something very important that I did: I wrote the function you wanted in terms of an utility function, that I then wrote in terms of two more utility functions, that I then wrote in terms of foldr, which I then wrote.  And also, since the library provides all those utility functions, I could have just stopped at the first definition.

That's a key thing that newcomers to functional programming often overlook—reduce/fold is a low level operation that you use to write a large library of easier to use, auxiliary operations, and you break down your problems in terms of those.  Look for example at the large number of functions in Haskell's Data.List library module.

The way you get good a functional-style list processing is to:

Learn how to break down problems in terms of library functions like those;

Learn how to write those library functions or new, similar ones that are missing from the library.

If you're always reaching for reduce right away you're going to end up with code that's harder to write and to read.  Whereas the reusable utility functions routinely cure this problem—the last line of my definition of allEqual basically reads like this: "test whether all elements after the first one in the list are equal to it."

Body:
Well, I have over 10 years of functional programming experience, and here's how I would do it:

If the sequence is empty, return true

Otherwise, return true if and only if all of the elements of the sequence are equal to the first one.

In Haskell, that starts out like this:

-- | Return false if and only if there is a pair of unequal elements
-- in the list.
allEqual :: Eq a => [a] -> a
allEqual [] = True
allEqual (first:rest) = all (\elem -> elem == first) rest

The all function tests whether all elements of a list satisfy a specified condition.  In this case, the condition is (\elem -> elem == first)—a function that tests whether the given elem is equal to first.

The all function is provided in the Data.List library module, but let's implement it ourselves:

-- | Apply the given test to every element in the list, and return
-- false if and only if at least one element tests false.
all :: (a -> Bool) -> [a] -> Bool
all test items = and (map test items)

To implement all I used two other standard functions—map and and.  But let's just go and implement them ourselves:

-- | Return true if and only if there are no `False` elements in the list
and :: [Bool] -> Bool
and bools = foldr (&&) True bools

-- | Apply the given function to all elements of the list, collecting
-- the results in a list.
map :: (a -> b) -> [a] -> [b]
map f = foldr go []
  where go item rest = f item : rest

And those two functions I wrote in terms of foldr ("fold right"), which is one such "reduce" operation that you're interested in.  For completeness, let's write that function:

foldr :: (a -> r -> r) -> r -> [a] -> r
foldr _ z [] = z
foldr f z (a:as) = f a (foldr f z as)

And now let me point out something very important that I did: I wrote the function you wanted in terms of an utility function, that I then wrote in terms of two more utility functions, that I then wrote in terms of foldr, which I then wrote.  And also, since the library provides all those utility functions, I could have just stopped at the first definition.

That's a key thing that newcomers to functional programming often overlook—reduce/fold is a low level operation that you use to write a large library of easier to use, auxiliary operations, and you break down your problems in terms of those.  Look for example at the large number of functions in Haskell's Data.List library module.

The way you get good a functional-style list processing is to:

Learn how to break down problems in terms of library functions like those;

Learn how to write those library functions or new, similar ones that are missing from the library.

If you're always reaching for reduce right away you're going to end up with code that's harder to write and to read.  Whereas the reusable utility functions routinely cure this problem—the last line of my definition of allEqual basically reads like this: "test whether all elements after the first one in the list are equal to it."


问:
Data Storage patterns for intermediate saving a web-based workflow form
Background: I am developing a wizard based web form where users can log in an fill in some details and press next and previous to go back and forth in the wizard before they actually submit. When the user submits I would make a service call that performs some processing on the data.

Issue: Not all data is available readily to the user, and the user may choose to “save” the data instead of “submitting” it, and then come back (if s/he chooses to) and finish it later. This intermediate data would be incomplete (and in some cases invalid) - but for convenience we would let the user save it.

Solutions I seen in the past: In the past I have dealt with this with 2 distinct solutions -

Save the intermediate data in the regular tables (where submitted data is saved) and mark that data as “inactive”. The data would be "activate"d only when the user clicks submit and all data is valid. This involves modifying the service that is called on submit to accept the data on save the intermediate and invalid data. Also this puts the burden on the team to remember to check for “active” flag in every query.

The other option is to storing the intermediate saved data in huge denormalized CLOBs. The data could be structured within the CLOBs as an XML or JSON. The intermediate data (saved) is completely disjoint from the completed (submitted). The downside here is that now the form needs to be able to work with 2 different sets of services based on the status of the workflow cycle (if in-progress read the XML from the CLOB – if completed read from the service that has valid data!)

Question:
Is there a better way to solve this problem since it does seem like a universal issue in the enterprise world at least? Could someone point me to any data or storage “patterns” that the community has been following to solve this storage issue in web workflows?

Note:
The underlying database technology can be thought of a system that supports tables and individual fields can contain very large strings like CLOBs.

答:
we had to implement a "subscription tunnel" for collecting and filtering potential clients from the web, implementing a subscription workflow.

What we did is implementing a "provider" pattern. Behind this pattern we had all workflow data to be stored in a single (and highly de-normalized) table. This was made to simplify the "processing cost" of the provider, and to allow the workflow steps to be re-arranged on demand. This table represents all "collectable" data. We did it using MSSQLServer. I can't say this technical choice was the better one for us, but it worked and our business people found agility concerning this strategic part of the system. The provider could be plugged from configuration files with a simple Dependency Injection.


问:
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>```

答:
There is one quite serious consequence when using lambda expressions that may affect performance.

When you declare a lambda expression, you are creating a closure over the local scope.

What does this mean and how does it affect performance?

Well I'm glad you asked. It means that each of those little lambda expressions is a small anonymous inner class and that means it carries with it a reference to all variables that are in the same scope of the lambda expression.

This means also this reference of the object instance and all of its fields. Depending on the timing of the actual invocation of the lambda, this can amount to a pretty significant resource leak as the garbage collector is unable to let go of these references as long as the object holding to a lambda is still alive...


问:
Is there really a fundamental difference between callbacks and Promises?
When doing single-threaded asynchronous programming, there are two main techniques that I'm familiar with. The most common one is using callbacks. That means passing to the function that acts asynchronously a callback-function as a parameter. When the asynchronous operation will finish, the callback will be called.

Some typical jQuery code designed this way:

```<code>$.get('userDetails', {'name': 'joe'}, function(data) {
    $('#userAge').text(data.age);
});
</code>```

However this type of code can get messy and highly nested when we want to make additional async calls one after the other when the previous one finishes.

So a second approach is using Promises. A Promise is an object that represents a value which might not yet exist. You can set callbacks on it, which will be invoked when the value is ready to be read.

The difference between Promises and the traditional callbacks approach, is that async methods now synchronously return Promise objects, which the client sets a callback on. For example, similar code using Promises in AngularJS:

```<code>$http.get('userDetails', {'name': 'joe'})
    .then(function(response) {
        $('#userAge').text(response.age);
    });
</code>```

So my question is: is there actually a real difference? The difference seems to be purely syntactical.

Is there any deeper reason to use one technique over the other?

答:
It is fair to say promises are just syntactic sugar. Everything you can do with promises you can do with callbacks. In fact, most promise implementations provide ways of converting between the two whenever you want.

The deep reason why promises are often better is that they're more composeable, which roughly means that combining multiple promises "just works", while combining multiple callbacks often doesn't. For instance, it's trivial to assign a promise to a variable and attach additional handlers to it later on, or even attach a handler to a large group of promises that gets executed only after all the promises resolve. While you can sort of emulate these things with callbacks, it takes a lot more code, is very hard to do correctly, and the end result is usually far less maintainable.

One of the biggest (and subtlest) ways promises gain their composability is by uniform handling of return values and uncaught exceptions. With callbacks, how an exception gets handled may depend entirely on which of the many nested callbacks threw it, and which of the functions taking callbacks has a try/catch in its implementation. With promises, you know that an exception which escapes one callback function will be caught and passed to the error handler you provided with .error() or .catch().

For the example you gave of a single callback versus a single promise, it's true there's no significant difference. It's when you have a zillion callbacks versus a zillion promises that the promise-based code tends to look much nicer.

Here's an attempt at some hypothetical code written with promises and then with callbacks that should be just complex enough to give you some idea what I'm talking about.

With Promises:

```<code>createViewFilePage(fileDescriptor) {
    getCurrentUser().then(function(user) {
        return isUserAuthorizedFor(user.id, VIEW_RESOURCE, fileDescriptor.id);
    }).then(function(isAuthorized) {
        if(!isAuthorized) {
            throw new Error('User not authorized to view this resource.'); // gets handled by the catch() at the end
        }
        return Promise.all([
            loadUserFile(fileDescriptor.id),
            getFileDownloadCount(fileDescriptor.id),
            getCommentsOnFile(fileDescriptor.id),
        ]);
    }).then(function(fileData) {
        var fileContents = fileData[0];
        var fileDownloads = fileData[1];
        var fileComments = fileData[2];
        fileTextAreaWidget.text = fileContents.toString();
        commentsTextAreaWidget.text = fileComments.map(function(c) { return c.toString(); }).join('\n');
        downloadCounter.value = fileDownloads;
        if(fileDownloads > 100 || fileComments.length > 10) {
            hotnessIndicator.visible = true;
        }
    }).catch(showAndLogErrorMessage);
}
</code>```

With Callbacks:

```<code>createViewFilePage(fileDescriptor) {
    setupWidgets(fileContents, fileDownloads, fileComments) {
        fileTextAreaWidget.text = fileContents.toString();
        commentsTextAreaWidget.text = fileComments.map(function(c) { return c.toString(); }).join('\n');
        downloadCounter.value = fileDownloads;
        if(fileDownloads > 100 || fileComments.length > 10) {
            hotnessIndicator.visible = true;
        }
    }

    getCurrentUser(function(error, user) {
        if(error) { showAndLogErrorMessage(error); return; }
        isUserAuthorizedFor(user.id, VIEW_RESOURCE, fileDescriptor.id, function(error, isAuthorized) {
            if(error) { showAndLogErrorMessage(error); return; }
            if(!isAuthorized) {
                throw new Error('User not authorized to view this resource.'); // gets silently ignored, maybe?
            }

            var fileContents, fileDownloads, fileComments;
            loadUserFile(fileDescriptor.id, function(error, result) {
                if(error) { showAndLogErrorMessage(error); return; }
                fileContents = result;
                if(!!fileContents && !!fileDownloads && !!fileComments) {
                    setupWidgets(fileContents, fileDownloads, fileComments);
                }
            });
            getFileDownloadCount(fileDescriptor.id, function(error, result) {
                if(error) { showAndLogErrorMessage(error); return; }
                fileDownloads = result;
                if(!!fileContents && !!fileDownloads && !!fileComments) {
                    setupWidgets(fileContents, fileDownloads, fileComments);
                }
            });
            getCommentsOnFile(fileDescriptor.id, function(error, result) {
                if(error) { showAndLogErrorMessage(error); return; }
                fileComments = result;
                if(!!fileContents && !!fileDownloads && !!fileComments) {
                    setupWidgets(fileContents, fileDownloads, fileComments);
                }
            });
        });
    });
}
</code>```

There might be some clever ways of reducing the code duplication in the callbacks version even without promises, but all the ones I can think of boil down to implementing something very promise-like.

Body:
It is fair to say promises are just syntactic sugar. Everything you can do with promises you can do with callbacks. In fact, most promise implementations provide ways of converting between the two whenever you want.

The deep reason why promises are often better is that they're more composeable, which roughly means that combining multiple promises "just works", while combining multiple callbacks often doesn't. For instance, it's trivial to assign a promise to a variable and attach additional handlers to it later on, or even attach a handler to a large group of promises that gets executed only after all the promises resolve. While you can sort of emulate these things with callbacks, it takes a lot more code, is very hard to do correctly, and the end result is usually far less maintainable.

One of the biggest (and subtlest) ways promises gain their composability is by uniform handling of return values and uncaught exceptions. With callbacks, how an exception gets handled may depend entirely on which of the many nested callbacks threw it, and which of the functions taking callbacks has a try/catch in its implementation. With promises, you know that an exception which escapes one callback function will be caught and passed to the error handler you provided with .error() or .catch().

For the example you gave of a single callback versus a single promise, it's true there's no significant difference. It's when you have a zillion callbacks versus a zillion promises that the promise-based code tends to look much nicer.

Here's an attempt at some hypothetical code written with promises and then with callbacks that should be just complex enough to give you some idea what I'm talking about.

With Promises:

createViewFilePage(fileDescriptor) {
    getCurrentUser().then(function(user) {
        return isUserAuthorizedFor(user.id, VIEW_RESOURCE, fileDescriptor.id);
    }).then(function(isAuthorized) {
        if(!isAuthorized) {
            throw new Error('User not authorized to view this resource.'); // gets handled by the catch() at the end
        }
        return Promise.all([
            loadUserFile(fileDescriptor.id),
            getFileDownloadCount(fileDescriptor.id),
            getCommentsOnFile(fileDescriptor.id),
        ]);
    }).then(function(fileData) {
        var fileContents = fileData[0];
        var fileDownloads = fileData[1];
        var fileComments = fileData[2];
        fileTextAreaWidget.text = fileContents.toString();
        commentsTextAreaWidget.text = fileComments.map(function(c) { return c.toString(); }).join('\n');
        downloadCounter.value = fileDownloads;
        if(fileDownloads > 100 || fileComments.length > 10) {
            hotnessIndicator.visible = true;
        }
    }).catch(showAndLogErrorMessage);
}

With Callbacks:

createViewFilePage(fileDescriptor) {
    setupWidgets(fileContents, fileDownloads, fileComments) {
        fileTextAreaWidget.text = fileContents.toString();
        commentsTextAreaWidget.text = fileComments.map(function(c) { return c.toString(); }).join('\n');
        downloadCounter.value = fileDownloads;
        if(fileDownloads > 100 || fileComments.length > 10) {
            hotnessIndicator.visible = true;
        }
    }

    getCurrentUser(function(error, user) {
        if(error) { showAndLogErrorMessage(error); return; }
        isUserAuthorizedFor(user.id, VIEW_RESOURCE, fileDescriptor.id, function(error, isAuthorized) {
            if(error) { showAndLogErrorMessage(error); return; }
            if(!isAuthorized) {
                throw new Error('User not authorized to view this resource.'); // gets silently ignored, maybe?
            }

            var fileContents, fileDownloads, fileComments;
            loadUserFile(fileDescriptor.id, function(error, result) {
                if(error) { showAndLogErrorMessage(error); return; }
                fileContents = result;
                if(!!fileContents && !!fileDownloads && !!fileComments) {
                    setupWidgets(fileContents, fileDownloads, fileComments);
                }
            });
            getFileDownloadCount(fileDescriptor.id, function(error, result) {
                if(error) { showAndLogErrorMessage(error); return; }
                fileDownloads = result;
                if(!!fileContents && !!fileDownloads && !!fileComments) {
                    setupWidgets(fileContents, fileDownloads, fileComments);
                }
            });
            getCommentsOnFile(fileDescriptor.id, function(error, result) {
                if(error) { showAndLogErrorMessage(error); return; }
                fileComments = result;
                if(!!fileContents && !!fileDownloads && !!fileComments) {
                    setupWidgets(fileContents, fileDownloads, fileComments);
                }
            });
        });
    });
}

There might be some clever ways of reducing the code duplication in the callbacks version even without promises, but all the ones I can think of boil down to implementing something very promise-like.


问:
How to design class model for specific products, some of which may contain groups of specific product models
Class Design Question

I am trying to figure out a good way to design my class system.

I have a class Product to compute various product specifications.  I have two product model groups, each containing several model numbers:  {10, 20, 30} and {50, 60, 70}.  They share some similar features (i.e. the way weight is computed) but have different product add-on computations (i.e. some features depend on product length and some do not, depending on the model group)

The class model I currently have is main Product for all models (actually originally for 50, 60, 70 only), and a specific model Product10 was added on later and works for model 10 only.   Now, a new addition brought on models 20, and 30, which are similar to model 10.  Instead of adding them as separate classes, nearly identical to 10, I thought it was time to redesign.

Problem

In my current implementation, class Product10 is feeding off the main Product class (responsible for "most models") and Product10 is being the odd one out.  Maybe it is fine, but now I am getting more model numbers similar to Product10 and I am seeking a better way to structure my code.

Currently I see that there are quite a few ways to design this.

create a class for each model (may be wasteful)

create a "god class" that contains code for all models (class may be bloated)

create subgroups for models, i.e. one class that covers a set of models like {10, 20, 30} or {50, 60, 70}

something else.

What I seek

I seek a good way to use OO design for my specific situation...  Namely,

I think it is a good idea to have a generic class of some sort

I am not sure whether I should create a class for to represent "a set of similar models" or whether to treat models separately

My goal is to create an appropriate class based on model number.

What could be a good class decomposition?

答:
Random Thoughts

The class model I currently have is main Product for all models (actually originally for 50, 60, 70 only) ... but have different product add-on computations

Design for the base case first. From there analyze carefully to identify precise differences with the one-off entities. Don't be so presumptive to tear things apart at the class level.

Now think how to conceptually abstract what's going on so as to see things that "are the same, but different."  This is distinct from things that are just different.

have different product add-on computations (i.e. some features depend on product length and some do not, depending on the model group)

Template Pattern?

This could be a virtual method in a base class. Especially if there is some basic process and this method is a different implementation of the same step.

class Product10 is feeding off the main Product class (responsible for "most models") and Product10 is being the odd one out.

static things are a great way to keep functionality in a base class without it being part of instance implimentation; without inheriting it where not needed.

Think constantly about single responsibility principle. Even to the point of the possibility of functionality being given to existing classes - even framework classes - via extension methods.

create a "god class" that contains code for all models (class may be bloated)

Visitor Pattern?

Specialized code/class(es) targeted to the Product variations. This is "do stuff" code - perhaps it even "plugs into" a template (pattern) in a base class.

OO Principles are fractal.

Principles apply at class, method, flow control structure, etc.

Don't quit designing useful classes just because:

It would be "too small"

I'm 2 (3, 4, ...) levels deep in my inheritance or composite structure.

It's easy to write the code right now, right here.

Classes are data structures too.

I find that when I design in discrete, focused pieces the act of designing is forgiving.

I had a class that was 3 properties: Days, Months, Years. Only 1 method - adding this STRUCTURE to DateTime objects.

Method parameters IS dependency injection.

delegate methods is composition


问:
Advantages and possible drawbacks of using Java for cross-platform development vs. .NET?
If I were to begin writing an application using Java with the intention of porting it to other platforms with little or no modification, would it be wise to consider using the .Net framework instead?

I have no specific targets in mind with respect to platform. At a minimum, Windows/Mac/Linux support would be nice. Also ease-of-use for the end-user is a consideration.

答:
Obviously Java does have some multiplaftorm capabilities, where .Net/Mono is risible.  You can say C is portable too, and you'd be roughly as right.

If it's desktop applications, I'd just do it in Qt.  By far the best GUI framework out there, and really multiplaftorm.

For non-desktop, a good scripting language is usually the way to go.

ContentLicense: CC BY-SA 2.5


问:
Hoisting in Javascript === Compiling?
I came across an interesting perspective at a recent job interview.

Hoisting in Javascript is about moving the variable declarations and function declaration at the top of the script. Can we call this phase as compilation?

I am aware about the fact that the Javascript interpreter has 2 passes over the input script where in the first pass it does hoisting and the second pass it actually executes the script. Having known that Javascript is an interpreted language, this question got me a bit confused.

答:
No.  Hoisting is not compilation.

Hoisting is a concept that was created by developers to explain what happens during compilation when variables and function declarations are moved to the top of their containing scope.

Compilation is what happens when your Javascript code is turned into some other representation (usually some kind of executable code), to be executed either now or later.  Chrome's V8 Javascript engine actually has two compilers; one to create quick and dirty executable code now, the other to create optimized code later.

Programming languages aren't defined as "compiled" or "interpreted" languages.  Rather, languages are interpreted or compiled as needed.

Further Reading

Hoisting in Javascript

How the V8 Engine Works

Title: Hoisting in Javascript === Compiling?


问:
Is it appropriate to use id-s in MongoDb subdocuments?
I'm currently familiarizing myself with NoSQL by building a simple web application using MongoDb with the official C# driver. If i have understood the NoSQL concept correctly, then only the aggregate root document should have an id and the child collections are without identity.

For example in C# code i would have the following 2 Poco-s:

```<code>public class User
{
    public BsonObjectId Id { get; set; }

    [BsonElement("pets")]
    public List<Pet> Pets { get; set; }
}

public class Pet
{
    public string Name { get; set; }
}
</code>```

How would i solve a case, where i want to have separate CRUD views for pets? With a relational database i would do this by having the pet id in the query string, with NoSQL i'm not sure.

This question arose from when i tried to add an Id field to the "Pet" subdocument. Instead of an id for pet, an object named "_csharpnull" was added to the database instead.

For example if i do this:

```<code>public class User
{
    public BsonObjectId Id { get; set; }

    [BsonElement("pets")]
    public List<Pet> Pets { get; set; }
}

public class Pet
{
    public BsonObjectId Id { get; set; }
    public string Name { get; set; }
}
</code>```

Then this document is inserted into the database:

```<code>{
    "_id" : ObjectId("5643a1f9766bcf0fc0b26f14"),
    "pets" : [
        {
            "_id" : {
                "_csharpnull" : true
            },
            "Name" : "T-Rex"
        }
    ]
}
</code>```

When my expected behavior would be something like:

```<code>{
    "_id" : ObjectId("5643a1f9766bcf0fc0b26f14"),
    "pets" : [
        {
            "_id" : ObjectId("56439adc766bcf49a0639992"),
            "Name" : "T-Rex"
        }
    ]
}
</code>```

答:
While I am not aware of a particular standard that says yes or no, in my experience this can and should in many cases be done.

The moment you want to be able to handle a Pet on it's own in various operations you need an ID. The simplest way in MongoDB is to just give it an ObjectID.

But I also have run into cases where this was not needed, such as when you have a sub document which always appears together with it's main document.

While I am not familiar with C# particularly, what you are trying to do definitely works in Java. Just make sure you actually initialize the ObjectID manually. While MongoDB creates object IDs for you on the top level documents of a collection it will not do the same for child documents.


问:
Why do people suggest not to use instance variable for views in Ruby on Rails
Why do I hear that it is not good to share instance variables between controllers and views.  I kind of like it because I can see immediately via the @ that something is coming from the controller.  I see a nice way to use helpers in controllers here: http://www.stephencelis.com/2008/09/06/rails-controllers-views-and-variables.html. But I am using cancan for that portion.</p>

答:
You can get the analogy from global variables or variables passed by reference, and think of partials as functions. So using instance variable is pretty much like variable passed to function as reference with all it's pro's and con's:

```<code># controller
def index
  @var = 1
end

#view index.html.erb
<%= @var %><br/>
<%= render 'foo' %><br/>
<%= @var %>

#partial _foo.html.erb
<%= @var = 2 %>
</code>```

result will be

```<code>1
2
2
</code>```

You may want such behavior, but in most cases you would not need it. And it's easier to introduce bugs this way and harder to track them. That's why this is recommended, because it separates the scopes of variables used in views and partials:

```<code>#view index.html.erb
<%= @var %><br/>
<%= render 'foo', var: @var %><br/>
<%= @var %>

#partial _foo.html.erb
<%= var = 2 %>
</code>```

result:

```<code>1
2
1
</code>```

Body:
You can get the analogy from global variables or variables passed by reference, and think of partials as functions. So using instance variable is pretty much like variable passed to function as reference with all it's pro's and con's:

# controller
def index
  @var = 1
end

#view index.html.erb
<%= @var %><br/>
<%= render 'foo' %><br/>
<%= @var %>

#partial _foo.html.erb
<%= @var = 2 %>

result will be

1
2
2

You may want such behavior, but in most cases you would not need it. And it's easier to introduce bugs this way and harder to track them. That's why this is recommended, because it separates the scopes of variables used in views and partials:

#view index.html.erb
<%= @var %><br/>
<%= render 'foo', var: @var %><br/>
<%= @var %>

#partial _foo.html.erb
<%= var = 2 %>

result:

1
2
1


问:
Difference between ESB and ETL
When should a ESB vs ETL tool be used? I have worked on ESB projects using Tibco Businessworks quite a few years ago. The message bus that we built used to consume messages from a source system , applying validation , perform transformation and send it to appropriate destination. The source could be a db , service , file etc and same with the destination. I was under the impression that ETL is primarily to extract , transform and load large volume of data & source / destination are primarily different databases. I recently looked at one pentaho project and it pretty much supported all the functions that I have seen in Tibco Businessworks and the project that I looked at was performing data extraction from a DB , but doing the same activities such a filter / transformation and routing. I also believe it has facility to route messages and consume messages from queues. When should we choose one over the other?</p>

答:
Enterprise Service Bus is a "software architecture" model used for designing and implementing communication between mutually interacting software applications in a service-oriented architecture (SOA).

Extract, Transform and Load (ETL) refers to a data warehousing process  that extracts data from various data sources, transforms it into the proper format, and loads it into the final target, usually a database.

The two things that they both have in common:

They both work with databases, and

They both allow heterogenous systems to be connected together,

But they have different purposes.  ESB is used for ongoing operations, whereas ETL is intended for one-time, ad-hoc or batch-like imports of data, much like the purposes of OLAP and OLTP.

Title: Difference between ESB and ETL


问:
Did labelled loops pre-date for loops?
Was the first implementation of looping control flow effectively the goto  (or something like a labelled JMP in assembler) or was there another syntactic construction?

for (für) was introduced in Superplan in 1949 IIRC.

答:
I'm not sure if your question title matches the actual question, as jump instructions in assembler may be relative, i.e. unlabelled as well. I'm also no historian, but I can at least subtract another century from your estimate.

The Analytical Engine devised by Charles Baggage in 1837 was extended in 1845 to contain a conditional jump instruction similar to modern assembler jump operations. See the linked wikipedia entry for an example code.

While that sets back the first implementation of such a control structure by a good century, I cannot say whether earlier versions exist. Most probably you may need to refine your question, as I believe there exists earlier work on the theoretical concept and it's hard to decide whether anything before the analytical engine is an implementation depending on your definition of it.

Title: Did labelled loops pre-date for loops?


问:
Good approach/Strategy to keep integration test database in-sync with production db?
I'm building a web application in Spring.
I'm using an in-memory (embedded) database for my integration test - HSQL
My production database is MySQL.

When i setup my integration tests a while back i took a SQL dump from production db and converted that to HSQL (DDL & inserts).

Now, my production database is going through an evolution of constant on-going change (the schema is constantly been updated with new functionalities from new business requirements)

How can i ensure my HSQL in-memory integration test DB is up to date with my Production?

答:
Well, you wrote

When i setup my integration tests a while back i took a SQL dump from production db and converted that to HSQL (DDL & inserts).

so automate this process - build some scripts or program which does what you did with as few manual steps as possible, then you can repeat the process of updating your test database much easier and as often as needed.

Side note to the commenters: Having the schema change first in production, and updating the OP's application afterwards can make perfectly sense if the application is not a production-critical part of an enterprise system. For example, an application which is used to make some data analysis on a production database at the end of a defined period like a quarter or a year. Under given time constraints, it does not make sense to stop the development/deployment of production critical apps, and wait until every minor important analysis tool was tested against the new schema.

(Don't get me wrong, I hope for your production critical apps there is something like a test database, and your colleagues test those applications first in that environment before deploying into production).


问:
Liskov principle with different constructor parameters
My first question is, is the Liskov principle applied even on constructor declaration?

I mean there, am I forced to have exactly the same number / types of parameter in my constructor for each (different) class?

Looking at this:

```<code>package com.apptest.test;

public class Application {

    public static void main(String[] args) {
        IRepository r = new RepositoryUser("toto");
        IRepository x = new BillingRepository("billing","super");

    }

}
</code>```

We can see that there are two implementations of IRepository, but one uses one more parameter.

Is this correct, and can I tell that the Liskov principle is respected ?

答:
As you may have already guessed, the constructor of your implementing class does not participate in the API of the interface.  In fact, you wouldn't want the constructor to be part of the interface.  Doing so would mean that your interface would have knowledge about how the class is instantiated, which would almost certainly foil design patterns such as Abstract Factory, Service Locator and Dependency Injection.

No, you want your interface to be constructor-agnostic, so that you can instantiate the implementing class in any way you see fit, whether that's through a Constructor, using Reflection, or by making use of an IoC container.


答:
The Liskov substitution principle is really referring to behavior more than anything else.  Subtypes of a class should extend functionality but only in ways that don't disrupt the current functionality in the context of your program.

In this regard, methods and constructors can take on additional parameters.  The trick is that you could use RepositoryUser and BillingRepository as IRepository instances interchangeabily throughout your program and they should both be used in the same way.  The difference, where it counts, should be in the implementation details and nowhere else.

The construction of an instance should also follow Liskov principle, but only in the case in which the constructor is performing logic of its own (calling methods and the like).  However it is usually best practice to avoid doing so in the constructor, and if that is your case, you need not worry about how the object is instantiated for what concerns Liskov principle.

Title: Liskov principle with different constructor parameters

Body:
My first question is, is the Liskov principle applied even on constructor declaration?

I mean there, am I forced to have exactly the same number / types of parameter in my constructor for each (different) class?

Looking at this:

```<code>package com.apptest.test;

public class Application {

    public static void main(String[] args) {
        IRepository r = new RepositoryUser("toto");
        IRepository x = new BillingRepository("billing","super");

    }

}
</code>```

We can see that there are two implementations of IRepository, but one uses one more parameter.

Is this correct, and can I tell that the Liskov principle is respected ?


问:
How are head first books?
I have never read any of them but I find their style interesting and unique.  I am not sure if they are worth giving money/time?</p>

答:
I love them. I have three of them, and enjoyed them all despite the fact they are from different authors.

The imposed structure is ideal for me as I tend to understand things better when I have drawings and exercises.

They also have the huge advantage to use humor a lot, which make learning fun!

Plain text doesn't work well with me. If you are in the same case, you'll love them.

Title: How are head first books?


问:
Understanding the difference between Webservices and Service Layer
My understanding of a webservice and service layer is as follows -

Service Layer: An abstraction layer which exposes a set of common operations which can be used by multiple consumers. For instance , I have a database containing customer data. Multiple applications may want to add / update / delete data in this data store. Each application will have logic to add / update / delete data in data store - hence duplication of logic. Instead, I would provide a service layer which exposes methods to add / update / delete customer information. So the logic isn't duplicated any longer and the applications have to just use my service layer in order to perform these activities. The specific domain where the service layer operates here is on customer information.

Webservices: Any machine to machine data transfer over the web can be performed using webservices. The implementation of webservice can be SOAP,   REST, vanilla RMI, etc... and the data can be serialized as XML, JSON, binary, etc... Assuming I expose a SOAP based webservice for the use case listed in my example above, I could provide a SOAP or REST based interface to add / delete / update customer information. The domain here is customer as well.

Based on my understanding, I feel that webservices are a subset of the service layer. The implementation for the example use case can be provided in the form a java .jar file or DLL which provides relevant APIs to perform the activity. All of the required applications will have to download the appropriate .jar or DLL to perform actions on customer data. Whereas webservice is specifically for machine-machine communication over web.

Is my understanding correct?

答:
A service layer is a layer in an application that hides away specific implementation details for a system and provides a uniform and consistent interface to the operations in that system.

A webservice is a communication pattern between devices.

The service layer defines a boundary for your system where external systems can interact with it. If you do this purely in code by providing a DLL, other systems interface with your service layer directly. Alternatively, you can provide a webservice on top of your DLL in which case other systems interface with the webservice, which interfaces with the DLL.

Compare this to a shop that has both a physical counter and an online store. Your salespeople are the 'service layer': they 'hide away' the implementation details that deal with registering a sale in the Point of Sale register, they handle the procedures that deal with performing additional purchases for a product that is out of stock, they put the cash from the customer in the right place and so on.

In the online store, your website acts as a 'web service': a customer no longer has to talk to a salesperson but instead places an order through the website. That order gets passed to a salesperson, who again performs the same things as outlined. The communication pattern is different, but the customer only cares about getting the product and knows that he has a variety of ways to do that.


问:
Are there any significant disadvantages to depending upon abstractions?
I was reading this wiki on the Stable Abstractions Principle (SAP).

The SAP states that the more stable a package the more abstract it should be. This implies that if a package is less stable (more likely to change) then it should be more concrete. What I don't really understand is why this should be the case. Surely in all cases regardless of stability we should be depending upon abstractions and hiding the concrete implementation?

答:
This implies that if a package is less stable (more likely to change)
  then it should be more concrete. What i don't really understand is why
  this should be the case.

Abstractions are things that are hard to change in the software because everything depend on them. If your package is going to change often and it provides abstractions, people who depend on it will be forced to rewrite a big bunch of their code when you change something. But if your unstable package provides some concrete implementations, much lesser code will have to be rewritten after changes.

So, if your package is going to change often, it should better provide concretes, not abstractions. Otherwise... who the hell will use it? ;)


答:
If i have understood the NoSQL concept correctly, then only the
  aggregate root document should have an id and the child collections
  are without identity.

I am not sure relational or even NoSQL document-oriented databases goes perfectly well with Domain Driven Design in all cases.

Will your document have an object id /primary key or not should be considered an implementation detail (though if you are not careful, it WILL affect your modelling process).

What is more important is the way you treat that particular document. Do you access it from outside of aggregate root boundaries by id? If you delete it and recreate the complete same object, but with different id will it affect your application logic somehow? Etc.

I think it would be better to have value object without ids so that there would be no temptation for you to address them  using ids. But if on some reason you should have, consider it an implementation detail and concentrate on following the domain logic first.

Title: Is it appropriate to use id-s in MongoDb subdocuments?

Body:
I'm currently familiarizing myself with NoSQL by building a simple web application using MongoDb with the official C# driver. If i have understood the NoSQL concept correctly, then only the aggregate root document should have an id and the child collections are without identity.

For example in C# code i would have the following 2 Poco-s:

```<code>public class User
{
    public BsonObjectId Id { get; set; }

    [BsonElement("pets")]
    public List<Pet> Pets { get; set; }
}

public class Pet
{
    public string Name { get; set; }
}
</code>```

How would i solve a case, where i want to have separate CRUD views for pets? With a relational database i would do this by having the pet id in the query string, with NoSQL i'm not sure.

This question arose from when i tried to add an Id field to the "Pet" subdocument. Instead of an id for pet, an object named "_csharpnull" was added to the database instead.

For example if i do this:

```<code>public class User
{
    public BsonObjectId Id { get; set; }

    [BsonElement("pets")]
    public List<Pet> Pets { get; set; }
}

public class Pet
{
    public BsonObjectId Id { get; set; }
    public string Name { get; set; }
}
</code>```

Then this document is inserted into the database:

```<code>{
    "_id" : ObjectId("5643a1f9766bcf0fc0b26f14"),
    "pets" : [
        {
            "_id" : {
                "_csharpnull" : true
            },
            "Name" : "T-Rex"
        }
    ]
}
</code>```

When my expected behavior would be something like:

```<code>{
    "_id" : ObjectId("5643a1f9766bcf0fc0b26f14"),
    "pets" : [
        {
            "_id" : ObjectId("56439adc766bcf49a0639992"),
            "Name" : "T-Rex"
        }
    ]
}
</code>```


问:
Bugs showing up with merge on the release branch
When trying to follow the the gitflow model, we have a branch for the releases.  However, we've had complicated merges when trying to merge from develop and bugs have crept in to that branch from this.

What are we doing wrong and how do we keep these merge bugs from showing up?

Our git tree looks like:

```<code>d  r  m
|  |  |
o  |  |
|\ |  |
| \|  |
|  1  |
o  |  |
|  2  |
|  |  |
o  3  |
| /|\ |
|/ | \|
o  |  4
|\ |  |
| \|  |
|  5  |
</code>```

where the o is a change on the development branch.  1 is where the development branch was merged into release, 2 and 3 are commits to fix bugs in the release branch, and then 4 is the release on master.  This then continues with 5 being the merge of development into the release branch again.

答:
As shown by your workflow link,
develop and master should always be there.

You create feature from develop.Feature branch should be created as per requirement and merged to develop and feature is deleted.

Similarly after release merged into master, its deleted.

The diagram you show is not clear.May be a detailed one can help to provide you an answer.


答: Yes -- buy one, they are excellent.  I read the Head First Design Patterns book, and I found it to be helpful with examples I could understand.  I also didn't get bored because of the fun style.  I recommended Head First Javascript to a friend, and she has also found it to be a great book.</p>

Title: How are head first books?

Body: I have never read any of them but I find their style interesting and unique.  I am not sure if they are worth giving money/time?</p>


问:
Abstracting out a module or using the Module Singleton directly?
I am working on a module which is dependent on other module for some functionality. Now the dependent module provides a lot of functionality and I need only few of them, hence got the idea to create an abstraction of the same in my module which is again be a singleton only.

My question is when to abstract out and when to use the modules singleton class directly? Is there any guidelines for the same? Or its depend upon project to project?

答:
If your dependent class only requires part of the functionality of the class depended upon (in your case a singleton) then it makes sense to abstract that functionality into an interface. This means that the dependent class is not affected by changes to your singleton it does not care about.

You then use dependency injection by having your dependent class take a reference to this interface in its constructor. Because your singleton class implements this interface it can then be passed to the dependent class at build time. Example in C++ below:

```<code>class TheInterface
{
  public:
  virtual void dependentOp1() = 0;
  virtual void dependentOp2() = 0;
};

class TheDependedUpon : TheInterface
{
  virtual void dependentOp1()
  {
    std::cout << "dependentOp1 called!" std::endl;
  }

  virtual void dependentOp2()
  {
    std::cout << "dependentOp2 called!" std::endl;
  }
};

class TheDependent
{
  //Constructor requires an object implementing TheInterface (dependency injection)
  TheDependent(TheInterface& anInterfaceReference)
  {
    //Here we can make calls to the interface we are interested in
    //without knowing how its implemented.
    anInterfaceReference.dependentOp1();
    anInterfaceReference.dependentOp2();
  };

void main()
{
  TheDependedUpon dependedUpon = TheDependedUpon();
  //Here we inject the dependedUpon as a dependency at build time
  TheDependent dependent = TheDependent(dependedUpon);
}
</code>```

Body:
If your dependent class only requires part of the functionality of the class depended upon (in your case a singleton) then it makes sense to abstract that functionality into an interface. This means that the dependent class is not affected by changes to your singleton it does not care about.

You then use dependency injection by having your dependent class take a reference to this interface in its constructor. Because your singleton class implements this interface it can then be passed to the dependent class at build time. Example in C++ below:

class TheInterface
{
  public:
  virtual void dependentOp1() = 0;
  virtual void dependentOp2() = 0;
};

class TheDependedUpon : TheInterface
{
  virtual void dependentOp1()
  {
    std::cout << "dependentOp1 called!" std::endl;
  }

  virtual void dependentOp2()
  {
    std::cout << "dependentOp2 called!" std::endl;
  }
};

class TheDependent
{
  //Constructor requires an object implementing TheInterface (dependency injection)
  TheDependent(TheInterface& anInterfaceReference)
  {
    //Here we can make calls to the interface we are interested in
    //without knowing how its implemented.
    anInterfaceReference.dependentOp1();
    anInterfaceReference.dependentOp2();
  };

void main()
{
  TheDependedUpon dependedUpon = TheDependedUpon();
  //Here we inject the dependedUpon as a dependency at build time
  TheDependent dependent = TheDependent(dependedUpon);
}


问:
Best way to design chess game
This is a theoretical question, and excuse me if it is not clear, I am new to this field.

Thing is, I was asked to design a chess game in an interview (java/ android.) And my intuition was that P. Norvig is a very good and known designer, and that pocker is very similiar to chess. So I tried to imitate his pocker design. As far as it was possible for me to remember and understand it.

However, the interviewer said that it is the first time he saw an implmentation of this problem by enumeration. And that a proper implementation should have class for every piece (why?!). I actually asked why, and the answer was that every piece has very complicated rules (but to me these rules seem to be simple.)

Is it bad to design chess game like that (with enumeration)?
What is the best approach to design a simple chess program in Java? And why?

I will thank very match anyone who can shed light on this topic.

答:
I am a chess engine developer so I can tell you - neither approach is acceptable. A professional chess game always almost do it in some kind of special data structure such as a mailbox or bitboard. Why? For example to find out the moves for a bishop, you would have to loop through the squares that the piece can move on an empty board while checking for enemy pieces. This is a very slow operation and you will need to repeat the same looping for rook. What if you want to generate all the squares that your pieces can attack but your opponents can't? This would involve lots of unnecessary looping. Bitboard allows you to do all of that in O(1). In bitboard you can simple do an AND operation to two boards which are represented by two 64 bits integer.

Having said that, it was likely your interviewer was merely expecting for a object oriented solution. I dont think that's a right or wrong answer but I would go for classes. Allowing object oriented design would make future updates easier. You can change the underlying implementation without affecting the rest of the program. You can also make easy to read function names like p.move whereas not possible with enumeration. Furthermore you would probably have to copy and paste a switch block everytime you have to do something to your piece. OO avoided that with an abstract interface.

Title: Best way to design chess game


答:
Service layer is a set of business functions available in an application. And it's more of a logical boundary.

Usually these functions are exposed in an application using one or more endpoints such as UI, webservice or data import job.

So a Web service is not a subset of a service layer,  but it's one way of exposing it.

Title: Understanding the difference between Webservices and Service Layer

Body:
My understanding of a webservice and service layer is as follows -

Service Layer: An abstraction layer which exposes a set of common operations which can be used by multiple consumers. For instance , I have a database containing customer data. Multiple applications may want to add / update / delete data in this data store. Each application will have logic to add / update / delete data in data store - hence duplication of logic. Instead, I would provide a service layer which exposes methods to add / update / delete customer information. So the logic isn't duplicated any longer and the applications have to just use my service layer in order to perform these activities. The specific domain where the service layer operates here is on customer information.

Webservices: Any machine to machine data transfer over the web can be performed using webservices. The implementation of webservice can be SOAP,   REST, vanilla RMI, etc... and the data can be serialized as XML, JSON, binary, etc... Assuming I expose a SOAP based webservice for the use case listed in my example above, I could provide a SOAP or REST based interface to add / delete / update customer information. The domain here is customer as well.

Based on my understanding, I feel that webservices are a subset of the service layer. The implementation for the example use case can be provided in the form a java .jar file or DLL which provides relevant APIs to perform the activity. All of the required applications will have to download the appropriate .jar or DLL to perform actions on customer data. Whereas webservice is specifically for machine-machine communication over web.

Is my understanding correct?


问:
CPOL License. Can I use it on my commercial application without distributing source code?
I'm considering using a project from http://www.codeproject.com that uses the CPOL license. Section 5e says:

"You may distribute the Executable Files and Source Code only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy of the Executable Files or Source Code You distribute and ensure that anyone receiving such Executable Files and Source Code agrees that the terms of this License apply to such Executable Files and/or Source Code. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute the Executable Files or Source Code with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License."

Is not clear to me if I should include their source code with my executable or not. Or even worse, if I should make my own source code available such as with GPL license.

The reason why is not clear to me is because I'm not sure if by compiling their source code together with mine I'm "distributing" either their "Source Code" or "Executable Files"?

答:
You don´t have to include source code, but you have to provide a link to the CPOL and let the users agree to it in your terms and conditions. Also see CPOL section 5.e:

... You must include a copy of, or the Uniform Resource Identifier for, this License with every copy of the Executable Files or Source Code You distribute and ensure that anyone receiving such Executable Files and Source Code agrees that the terms of this License apply to such Executable Files and/or Source Code.  ...

Code project has summarized the most important facts about their licences here: CodeProject´s License Information.

It mentions inter alia the following points:

Can be used in commercial applications: True

Can be used in proprietary (closed source) applications: True

Bug fixes / extensions must be released to the public domain: False

Is a viral licence: False


问:
Bad practice to define constants based on a function call?
In Python when writing file management scripts I will often have a base path that is a constant,

```<code>BASE = "C:/"
</code>```

Of course I'll be using that base path to create other paths later on, including other paths that will change in no other place. So I define constants like this:

```<code>SUB_FOLDER = os.path.join(PROJECT_BASE, "folder")
</code>```

However it feels like it may be contrary to define what is a constant based on the result of a function call, even if that call will return a fixed result and never be modified.

Is this considered poor style that would confuse people?

答:
Setting BASE and using its value this way is what you want to do.

Now if you need to tweak a few months from now it is only defined in one place in the code. Imagine if your boss told you to new store those files on the X drive; You would need to find all places where you mention "c:/" and change them to "x:/". Don't make a mistake or files will be written to the wrong place, and ones you need to read won't be found.

SUB_FOLDER isn't a constant. Its value is determined a split second after program execution starts. Again defining it this way helps in program maintenance.


答:
This would be considered a run-time constant: the value cannot be known before the program starts, but it is unchanging throughout the entire application once set.

The major advantage to a run-time constant is that it makes it obvious to a developer that the value is unchanging and that it enforces this in some way (to prevent erroneous assignments when the value has already been set), but you acknowledge that it cannot be known until run-time. Compare the value of Pi (which can be known and set before runtime) to the installation path of an application (which can only be figured out once the application starts, but not change when the application is running).

Your example perfectly fits the bill for this: it is a value that is set once and will never change throughout your application and therefore can look like a constant. Just note that this is not a true constant as Python does not have them and you will therefore need some kind of workaround to actually enforce their constant-ness.

Title: Bad practice to define constants based on a function call?

Body:
In Python when writing file management scripts I will often have a base path that is a constant,

```<code>BASE = "C:/"
</code>```

Of course I'll be using that base path to create other paths later on, including other paths that will change in no other place. So I define constants like this:

```<code>SUB_FOLDER = os.path.join(PROJECT_BASE, "folder")
</code>```

However it feels like it may be contrary to define what is a constant based on the result of a function call, even if that call will return a fixed result and never be modified.

Is this considered poor style that would confuse people?


问:
How to design class model for specific products, some of which may contain groups of specific product models
Class Design Question

I am trying to figure out a good way to design my class system.

I have a class Product to compute various product specifications.  I have two product model groups, each containing several model numbers:  {10, 20, 30} and {50, 60, 70}.  They share some similar features (i.e. the way weight is computed) but have different product add-on computations (i.e. some features depend on product length and some do not, depending on the model group)

The class model I currently have is main Product for all models (actually originally for 50, 60, 70 only), and a specific model Product10 was added on later and works for model 10 only.   Now, a new addition brought on models 20, and 30, which are similar to model 10.  Instead of adding them as separate classes, nearly identical to 10, I thought it was time to redesign.

Problem

In my current implementation, class Product10 is feeding off the main Product class (responsible for "most models") and Product10 is being the odd one out.  Maybe it is fine, but now I am getting more model numbers similar to Product10 and I am seeking a better way to structure my code.

Currently I see that there are quite a few ways to design this.

create a class for each model (may be wasteful)

create a "god class" that contains code for all models (class may be bloated)

create subgroups for models, i.e. one class that covers a set of models like {10, 20, 30} or {50, 60, 70}

something else.

What I seek

I seek a good way to use OO design for my specific situation...  Namely,

I think it is a good idea to have a generic class of some sort

I am not sure whether I should create a class for to represent "a set of similar models" or whether to treat models separately

My goal is to create an appropriate class based on model number.

What could be a good class decomposition?

答:
If classes from the set {10, 20, 30} have the same behaviour, create only 1 class that derives from Product. Same for {50, 60, 70}.

```<code>abstract class Product {
    public function getWeight() {
        //Some computation
    }

    abstract public function getVolume();
}

class Product102030 extends Product {
    public function getVolume() {
        //Compute volume based on something
    }
}

class Product506070 extends Product {
    public function getVolume() {
        //Compute volume based on something else
    }
}
</code>```

My goal is to create an appropriate class based on model number.

If I understand correctly, you also want a class able to instanciate the correct ProductXXXXXX based on a model number. This could typically be done into a factory.

```<code>class ProductFactory {
    public static function create($number) {
        switch($number) {
            case 10:
            case 20:
            case 30:
                return new Product102030;
            case 50:
            case 60:
            case 70:
                return new Product506070;
            default:
                throw new Exception ('Unsupported model number !');
        }
    }
}
</code>```

A typical usage would be:

```<code>$p1 = ProductFactory::create(10); //$p1 is a Product102030 instance
$p2 = ProductFactory::create(60); //$p2 is a Product506070 instance
</code>```

Body:
If classes from the set {10, 20, 30} have the same behaviour, create only 1 class that derives from Product. Same for {50, 60, 70}.

abstract class Product {
    public function getWeight() {
        //Some computation
    }

    abstract public function getVolume();
}

class Product102030 extends Product {
    public function getVolume() {
        //Compute volume based on something
    }
}

class Product506070 extends Product {
    public function getVolume() {
        //Compute volume based on something else
    }
}

My goal is to create an appropriate class based on model number.

If I understand correctly, you also want a class able to instanciate the correct ProductXXXXXX based on a model number. This could typically be done into a factory.

class ProductFactory {
    public static function create($number) {
        switch($number) {
            case 10:
            case 20:
            case 30:
                return new Product102030;
            case 50:
            case 60:
            case 70:
                return new Product506070;
            default:
                throw new Exception ('Unsupported model number !');
        }
    }
}

A typical usage would be:

$p1 = ProductFactory::create(10); //$p1 is a Product102030 instance
$p2 = ProductFactory::create(60); //$p2 is a Product506070 instance


问:
What's the ideal length of the sprint review/retrospective based on the length of the iteration?
I've been in several projects using scrum now.

The length of the sprint review and/or retrospective has varied from client to client, from project to project.
Some of the reviews became too long (2 days).

Sometimes, I've lost focus while being in this long meetings and just wanted to go back to my safe and happy place (my chair in front of my computer).

What is the ideal length of these meetings?
What's the best way to avoid long meetings?

答:
It depends on when you last held the meeting. My rule of thumb is one to two hours per week.

So a meeting for two a week sprint should be between two and four hours. That’s not a hard rule, but you should use at least an hour each time. It’s better to hold short meeting more often, rather than long meetings more seldom.

The reason for that is getting feedback quickly. I mean, after a month none will even remember what they did four weeks ago.

Also, remember to hold this meeting at regular intervals. Usually at the end of each week, month or sprint. You can also hold it at the end of a project or when you do a release or, well, when you need it.


问:
How useful are function points?
How useful is it to measure function points?

We use function points at my new job.  I've heard of function points but haven't had any training or experience... but I don't have much confidence in things that cannot be explained succinctly.

答:
Run away.

In my experience, the companies that I've seen use function points are only one step above pure madness.

Title: How useful are function points?


答:
A web service is a service, available on a web-based network, i.e. accessible using HTTP (not necessarily over the internet).

A service is a logical unit of software, deployed on a particular location in a network, meant to be used by other software units.

A service layer is an architectural layer, consisting of logically related services.

Elaboration:

Web service

In the pre-REST era, the most accepted definition of web service was the definition given by W3C

A Web service is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP-messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards.

Nowadays, the term is also used for REST-compliant services, so this definition needs to be broadened. The word "Web" is derived from the World-Wide Web, so it is a web like www, i.e. based on HTTP, but not necessarily world-wide. That's why I think the distinction between a web service and all other services is, that a web service can be accessed via HTTP.

Service

A service is the main entity of a service-oriented architecture.

Services, components and objects all share the properties of being loosely coupled units of software, offering a set of logically related methods, hiding their implementation behind an interface. Components/objects are included in applications as JARs, DLLs, or whatever. In other words, each application runs its own instances.

Services are different from components/objects in the sense that they are deployed separately. Multiple applications may use the same instance of the service. Each service has its own network location. This is comparable to what is meant by SaaS (Software as a Service): instead of shipping a copy of the software to the customer, multiple customers access the same service(s) via the internet.

Services typically consist of one or more components and components consist of one or more objects (see wikipedia).

Service layer

This is a combination of the word 'service', as defined above, and the word 'layer', which refers to one abstraction layer in a layered architecture. Typically, a central database is encapsulated by a number of services: each service in that layer may access the database, but all other software should access the database through that layer. However, services are not necessarily organized in service layers. On the contrary, to increase the independence of services, it would be better to let every service have its own storage, unaccessible by other services (although there may be reasons to relax this principle). A SOA usually does not have a service layer, but a network of services.


问:
Why do Android programmers use Hungarian notation?
I see Hungarian notation in almost all Android code I see. It is used in the source code, in the samples, in code from other programmers I get to see, in code that presenters show at Android conferences. They use mContext rather than context, mTextView rather than just textView.
Hungarian notation is useless in Java, especially when you use an IDE that uses color and typeface to indicate local and member fields. Joel Spolski wrote an excellent article supporting this view. Hungarian notation makes your code look messy.

So my question is: despite the fact there's no benefit in Hungarian notation in Java, why do several Android programmers use it?

edit: Android developer documentation used to advise you to do so. Thus my question has two parts: why would Google advise us to use the m notation, and if they do, why do people follow that advice even when no-one explains why you should?

答:
The Android codebase uses a highly modified notation that isn't strictly "Hungarian".

This notation is highly influenced by the entire Google codebase, in all languages, almost all of which contains domain-specific Hungarian-style notation. Code reviews at Google pretty much require this1, and there is a ripple effect to the public codebases.

why would Google advise us to use the m notation

Because this is their coding standard. When you have large codebases across many APIs shared by literally thousands of coders, you need standards. Google have decided that marking up their code in this manner leads to better and easier to maintain code.

Not everyone agrees, but every shop has its own rules you have to follow. As someone commented earlier, you often don't see this at Java shops. Though, you certainly do see it in Java at Google.

As for why to annotate your code at all in this manner, there are lots of links in the comments. But, at the end of the day, it is about code maintainability (and readability is a major part of that) and an effort to keep bugs from creeping in as the code is changed.

why do people follow that advice even when no-one explains why you should?

Well, open source projects are uneven in how they introduce new people to their processes and workflows. If you were working at Google, you would get a mentor who would shadow you and check all your code prior to acceptance, and this process would introduce you to all the things you would be expected to do as a coder. This includes following coding standards. If you had to ask why, you could ask your co-workers.

Open source public facing libraries and APIs are managed differently, and also have a different way of introducing you to their specific coding practices. In this case, my guess is that pushing code that doesn't follow a standard required by the "community" would cause the push to be annotated and flipped back to you for further grooming. Thus, you would learn.

1 Citation: me, and the chats I've had with colleagues that work for Google