答:
Rather than directly answer the question, my response questions the assumption made in the question. That is, the assumption that Razor was built for MVC is incorrect. I work at Microsoft on the ASP.NET team and have first-hand knowledge of this.

Razor did not start out as a view engine for MVC. It was created for ASP.NET Web Pages, which is probably as far as you can go towards the least-separated-concerns side of the spectrum. It was created as a modern alternative to ASP.NET Web Forms / Classic ASP and of course many other similar server programming frameworks. The idea of Razor was to create nearly seamless transitions between HTML (markup) and C# (code).

Only later did the team (which includes myself) decide that the Razor syntax would make a lot of sense for the sake of a view engine for MVC, which was being written by the same team.

As to whether Razor enables, hinders, improves, or alters the concept of separation of concerns in ASP.NET MVC, Oded's answer is spot on.

Title: If MVC is "Separation of Concerns" then why was Razor Syntax introduced?

Body:
My question is related to MVC design pattern and Razor Syntax introduced by Microsoft.

While learning MVC design pattern I was told that the idea is based upon a principle known as Separation of Concerns.

But Razor Syntax allows us to use C# in Views directly.

Isn't this intersection of concerns?


问:
What is the correct Object Design/Architecture for the following scenario?
I am developing some custom controls in an Object Oriented language (using Swift/Cocoa but this is a technology agnostic question). In particular, I have a horizontal and vertical set of buttons that behave very similarly except for the fact that one is oriented vertically and the other horizontally.

My question: what is the correct way to structure these two 'things' in my project:

Should I have a (abstract) parent class that has common functionality and then two derived concrete classes for the specifics needed for horizontal-ness vs vertical-ness. This feels the most correct but given that the object is composed of other objects you are then going to have proliferated throughout the view hierarchy going downwards.

Alternately, should I design one highly generalised class that has a property for orientation and then a lot of if/switch logic in the code to drive behaviour based on this. This feels like a code-smell.

Just go and create two separate similar but technically unrelated classes and just do a little more repeated typing. Since so many things are driven by the orientation this almost seems simpler than 1 above.

Or is there another alternative?

Other canonical examples where this would arise could be horizontal vs vertical:
    - scrollers
    - stacking panels

To attempt to clarify on regarding design goals and requirements, I would like the question answered in terms of how Apple Software Architects might have approached the NSScrollView class (or how any large organization might approach similar UI library code with "mirror" horizontal and vertical components).

The answer impacts several related vertical vs horizontal classes that aggregate these buttons into rows and columns respectively as the rows and columns themselves are also very similar save for the vertical vs horizontal orientation.

答:
two derived concrete classes for the specifics needed for horizontal-ness vs vertical-ness. This feels the most correct

Well, to me this feels mostly wrong. Your button can have a dozen properties or more like the orientation, for example it could be resizable, have a specific color, it could be labeled with an image, text or both, and so on. If you are going to create derivations for each property, even when you restrict yourself to properties which don't change over the lifetime of the object, you will need an additional derivation for each combined property (for example, a VerticalResizableImageButton, HorizontalResizableImageButton, VerticalResizableTextButton, HorizontalResizableTextButton, each of those also in a non-resizable variant, and so on). Imagine how many different derivations this will mean in the end - each new property will multiply the number of needed derivations by a factor. I don't think this is feasible.

should I design one highly generalised class that has a property for orientation and then a lot of if/switch logic in the code to drive behaviour

I would try to design one highly generalised class that has a property for the orientation, but as few conditional logic as possible. If the part of the code which depends on the orientation really ends up in many if/else statements, it can probably be encapsulated into one or more strategy objects, which are initialized once in the button constructor. For example, a "DragStrategy" (with derived classes "VerticalButtonDragStrategy" and "HorizontalButtonDragStrategy") for controlling the drag-resizing.

ContentLicense: CC BY-SA 3.0


答:
Answering in a very abstract and technology/framework agnostic manner, my thinking is as follows

What a GUI control is (ie. volume up, volume down) not equates to how it is positioned in a window (a frame of visual reference).

Therefore separate the functionality of laying-out from the controls themselves.

Use a factory to create various layout managers for Controls (Control can be a common interface that all controls implements or provides - I suggest use composition - and provides information as required by the layout manager. For example a particular component may have a preferred width or height, similarly layout manager may want to instruct the control/component that it is now in a Horizontal layout thus dimensions are so..etc.)

in this case a LayoutFactory.createHorizontalLayoutManager().layout(List controls)

What does this facilitate

in the future you just need to modify / add / factories or methods in them to create more layout options.

LayoutFactory.createHorizontalLayoutManager().layout(List controls) is a Control (various controls like Button, ScrollBar..etc) agnostic. It just knows how to layout a component/control.

The control themselves are agnostic to target device (phone,TV,BillBoards,Laptop..etc)..that information can be incorporated into layout manager (even better, an concrete implementation of a Device interface would take a layout manager and it would know what a horizontal layout means in that particular device and render it accordingly)

Title: What is the correct Object Design/Architecture for the following scenario?

Body:
I am developing some custom controls in an Object Oriented language (using Swift/Cocoa but this is a technology agnostic question). In particular, I have a horizontal and vertical set of buttons that behave very similarly except for the fact that one is oriented vertically and the other horizontally.

My question: what is the correct way to structure these two 'things' in my project:

Should I have a (abstract) parent class that has common functionality and then two derived concrete classes for the specifics needed for horizontal-ness vs vertical-ness. This feels the most correct but given that the object is composed of other objects you are then going to have proliferated throughout the view hierarchy going downwards.

Alternately, should I design one highly generalised class that has a property for orientation and then a lot of if/switch logic in the code to drive behaviour based on this. This feels like a code-smell.

Just go and create two separate similar but technically unrelated classes and just do a little more repeated typing. Since so many things are driven by the orientation this almost seems simpler than 1 above.

Or is there another alternative?

Other canonical examples where this would arise could be horizontal vs vertical:
    - scrollers
    - stacking panels

To attempt to clarify on regarding design goals and requirements, I would like the question answered in terms of how Apple Software Architects might have approached the NSScrollView class (or how any large organization might approach similar UI library code with "mirror" horizontal and vertical components).

The answer impacts several related vertical vs horizontal classes that aggregate these buttons into rows and columns respectively as the rows and columns themselves are also very similar save for the vertical vs horizontal orientation.


问:
If MVC is "Separation of Concerns" then why was Razor Syntax introduced?
My question is related to MVC design pattern and Razor Syntax introduced by Microsoft.

While learning MVC design pattern I was told that the idea is based upon a principle known as Separation of Concerns.

But Razor Syntax allows us to use C# in Views directly.

Isn't this intersection of concerns?

答: You are confusing "separation of technologies" with "separation of concerns". The basic idea behind the "View" portion of MVC is that code in the "View" is not performing any data access or heavy logic directly, rather that is left to the "Model" and "Controller" portions respectively. The "Controller" transforms the data, performs any necessary logic, and routes it to the correct "View". The view can also do data transformations, but I tend to keep them purely cosmetic, such as the date transform mentioned above.</p>


问:
Summarize terms of service?
What's your opinion on summarizing the ToS?

Example:

```<code>[ToS here]
Basically, it means you won't sue me.
[I accept][I don't accept]
</code>```

Is this good practice or will this just get you sued more?

答:
Bad idea.

Essentially it creates ambiguity about what the user is agreeing to which is a bad thing for you (assuming that you have your ToS to protect you).

Something that sweeping almost certainly has no legal validity (it's too broad), so the summary offers you no additional protection and potentially just undermines the genuine content of the ToS.

ContentLicense: CC BY-SA 2.5

Title: Summarize terms of service?


问:
Workaround for Java checked exceptions
I appreciate a lot the new Java 8 features about lambdas and default methods interfaces. Yet, I still get bored with checked exceptions. For instance, if I just want to list all the visible fields of an object I would like to simply write this:

```<code>    Arrays.asList(p.getClass().getFields()).forEach(
        f -> System.out.println(f.get(p))
    );
</code>```

Yet, since the get method might throw a checked exception, which does not agrees with the Consumer interface contract, then I must catch that exception and write the following code:

```<code>    Arrays.asList(p.getClass().getFields()).forEach(
            f -> {
                try {
                    System.out.println(f.get(p));
                } catch (IllegalArgumentException | IllegalAccessException ex) {
                    throw new RuntimeException(ex);
                }
            }
    );
</code>```

However in most cases I just want the exception to be thrown as a RuntimeException and let the program handle, or not, the exception without compilation errors.

So, I would like to have your opinion about my controversial workaround for checked exceptions annoyance. To that end, I created an auxiliary interface ConsumerCheckException<T> and an utility function rethrow (updated according to the sugestion of Doval's comment) as follows:

```<code>  @FunctionalInterface
  public interface ConsumerCheckException<T>{
      void accept(T elem) throws Exception;
  }

  public class Wrappers {
      public static <T> Consumer<T> rethrow(ConsumerCheckException<T> c) {
        return elem -> {
          try {
            c.accept(elem);
          } catch (Exception ex) {
            /**
             * within sneakyThrow() we cast to the parameterized type T.
             * In this case that type is RuntimeException.
             * At runtime, however, the generic types have been erased, so
             * that there is no T type anymore to cast to, so the cast
             * disappears.
             */
            Wrappers.<RuntimeException>sneakyThrow(ex);
          }
        };
      }

      /**
       * Reinier Zwitserloot who, as far as I know, had the first mention of this
       * technique in 2009 on the java posse mailing list.
       * http://www.mail-archive.com/javaposse@googlegroups.com/msg05984.html
       */
      public static <T extends Throwable> T sneakyThrow(Throwable t) {
          throw (T) t;
      }
  }
</code>```

And now I can just write:

```<code>    Arrays.asList(p.getClass().getFields()).forEach(
            rethrow(f -> System.out.println(f.get(p)))
    );
</code>```

I am not sure that this is the best idiom to turn around the checked exceptions, but as I explained, I would like to have a more convenient way of achieving my first example without dealing with checked exceptions and this is the simpler way that I found to do it.

答:
You may want to have a look at this project; I created it specifically because of the problem of checked exceptions and functional interfaces.

With it you can do this instead of writing your custom code:

```<code>// I don't know the type of f, so it's Foo...
final ThrowingConsumer<Foo> consumer = f -> System.out.println(f.get(p));
</code>```

Since all those Throwing* interfaces extend their non Throwing counterparts, you can then use them directly in stream:

```<code>Arrays.asList(p.getClass().getFields()).forEach(consumer);
</code>```

Or you can just:

```<code>import static com.github.fge.lambdas.consumers.Consumers.wrap;

Arrays.asList(p.getClass().getFields())
    .forEach(wrap(f -> System.out.println(f.get(p)));
</code>```

And other things.

Title: Workaround for Java checked exceptions

Body:
You may want to have a look at this project; I created it specifically because of the problem of checked exceptions and functional interfaces.

With it you can do this instead of writing your custom code:

// I don't know the type of f, so it's Foo...
final ThrowingConsumer<Foo> consumer = f -> System.out.println(f.get(p));

Since all those Throwing* interfaces extend their non Throwing counterparts, you can then use them directly in stream:

Arrays.asList(p.getClass().getFields()).forEach(consumer);

Or you can just:

import static com.github.fge.lambdas.consumers.Consumers.wrap;

Arrays.asList(p.getClass().getFields())
    .forEach(wrap(f -> System.out.println(f.get(p)));

And other things.


问:
GPL covers the linguistic data in *spell dictionaries?
There are good annotated vocabulary in {a,i,my}spell dictionaries, giving the lexical class et all.

I'm writing a program that  needs a large vocabulary, but with a reduced scope, so I don't need all the information on the *spell dictionaries. Then, I'm reading this dictionary data, processing it and rewriting in my own format.
The dictionary I'm using is GPLv2 and I want to release my program in BSD.

As the data itself [the idiom] is public domain, but the representation of data [*spell .dic files] is not, maybe I must follow GPL.

But as I'm not using the GPLd code itself, but a derived trough machine processing from it, maybe I must not.

Additional info:

I'm already making my derived own word list, mostly because the original word list have too much semantic information, like this:
"ripostar/#vi/XYL/" or "ritualizar/#vt/XYPLnc/".
But the resulting world list must be manually curated afterwards. This lead to a situation where I will distribute my word list and not require the original to works.

答:
Its fuzzy.  You're going to need to talk to someone who is familiar with the intellectual property of copyrights and word lists in your jurisdiction.

Lists of facts doesn't enjoy copyright in the United States.  The court case for this is Feist v. Rural where it was ruled that copyrightability is based on originality.  In this case, a collection of phone numbers doesn't meet that threshold of originality.

Note that in other countries the governing principle is sweat of the brow.

Word lists themselves are hazy.  Scrabble has some history about a particular word list and who owns it - is the selection of words minimally creative? or is it a rote compilation?  I don't know.  I can't really say.  You could argue it either way.  If it isn't protectable by copyright, then the word list isn't able to be licensed... though that does get back into the protected by copyright where aspect.

For this, your best bet would to contact an organization that can answer some questions about the GPL.  From http://www.fsf.org/about/contact/email

For any questions about the GNU GPL, LGPL, AGPL and Free Documentation Licenses:

  licensing@fsf.org

And they would be able to give you about as an authoritative answer you can get before you start paying money to a lawyer.

You may also wish to consider the format of the file being something that is open.  Write a program that can handle any {a,i,my}spell dictionary format.  Just don't include the GPL files with it.  Include a minimally useful dictionary with it.  Other people can use other dictionaries if they so desire.

You may find other word lists that have a BSD compatible license.


问:
Mac OS X preferences saving, when to apply/save changes made by user
It is typical for Mac OS X apps to have preferences that apply seamlessly, and preferences dialogs don't have "OK" or "Apply" button. I want to implement this behavior in my project, but I can't decide when to apply/save changes made by user.

It's quite clear that checkboxes and drop-downs can be saved immediately upon change, but when it comes to text fields, this approach seems questionable. For example, entering "programming.stackexchange.com" as host address will trigger 29 HDD writes, which seems just wrong. Moreover, in my simple implementation this will cause the entire settings file to be rewritten.

So is there any standard way to implement MacOS-like preferences?

答:
One reasonable way to accomplish this is as follows:

For an input type that has a discrete selection such as a check box, radio button, or list: save the setting as soon as the user makes the selection.

For an input type that has freeform selection such as a text box: save the setting as soon as the input element loses focus or the dialog is dismissed. For longer text boxes (e.g. a rich text element that might contain complex data and a lot of it) it might make sense to save data every few seconds in addition to the previous criteria. In fact this is the same method used when writing questions and answers here on Stack Exchange.

It is important to be mindful that in addition to saving to persistent storage (i.e. hard disk) updating preferences may also trigger events in your application that update the UI elsewhere in the program. Handling these events may also consume resources such as CPU and memory. While not strictly addressing your question, it is closely related and worth thinking about while you implement a solution such as this.


答:
So what’s your question? Would your work count as a derivative work from (work based on) a dictionary or not?

I am not a lawyer (and you should get one, if you are concerned about possible legal issues), so you probably would not interested in my opinion about that, but I really do not understand why it bothers you.

Copyleft of GNU GPL protects free software against becoming bound with additional restrictions, not the otherwise.

Since both of modern¹ BSD Licenses (2-clause and 3-clause) are compatible with GNU GPL, i. e. their sets of restrictions are subsets of that of GNU GPL, it is nothing wrong to combine your code under the terms of one of them along with GPL’ed one in a single product. As a whole for the sake of simplicity it might and should be considered as covered by GNU GPL, but that by no means would affect copyright conditions your own part of work alone – it remains under terms of lax permissive license, your chose for it.

¹ I hope, you are not going to use 4-clause BSD License with obnoxious advertising clause.

Title: GPL covers the linguistic data in *spell dictionaries?

Body:
There are good annotated vocabulary in {a,i,my}spell dictionaries, giving the lexical class et all.

I'm writing a program that  needs a large vocabulary, but with a reduced scope, so I don't need all the information on the *spell dictionaries. Then, I'm reading this dictionary data, processing it and rewriting in my own format.
The dictionary I'm using is GPLv2 and I want to release my program in BSD.

As the data itself [the idiom] is public domain, but the representation of data [*spell .dic files] is not, maybe I must follow GPL.

But as I'm not using the GPLd code itself, but a derived trough machine processing from it, maybe I must not.

Additional info:

I'm already making my derived own word list, mostly because the original word list have too much semantic information, like this:
"ripostar/#vi/XYL/" or "ritualizar/#vt/XYPLnc/".
But the resulting world list must be manually curated afterwards. This lead to a situation where I will distribute my word list and not require the original to works.


问:
Starting a big application with unit testing
I am learning test driven develeopment and read some books about TDD. I learned rules of unit testing. How can I write unit test, how can I select test method names, Act, Assert, Action and like this.

In real word I developed applications that have layered architecture. Domain Layer, Data Layer, Service Layer, UI Layer, ....

How can I start an application with TDD. Is there a rule or way or else. For example starting Service Layer.

答:
The size of a project should make no difference whatsoever when doing test driven development. The point of unit testing is that you are testing isolated units of functionality completely independently of other areas of the code.

This is achieved by using mocks to fake out the expected behavior of other parts of the program. This can be most easily achieved by always coding against interfaces instead of concrete types.

For example, say you have two classes ClassA and ClassB. ClassA calls ClassB, but you want to test ClassA independently as it is a separate unit from ClassB. Instead of directly referencing ClassB from within ClassA, you instead make ClassB implement interface IClassB. Then when writing unit tests for ClassA, you simply mock the behavior of methods on IClassB. You may then proceed to write isolated unit tests for ClassB.

This process can be facilitated with the use of dependency injection which allows the intended concrete type to be decided at application runtime.

Taking this approach, you are only ever testing each individual part of the system in isolation, so it makes no difference whatsoever where you begin. This is pretty much the definition of unit testing.

What is probably more important at the start of the project is to pick a mocking framework and a dependency injection framework to allow you to work this way. There will be a variety available for whichever language you are working in.

The act of testing multiple tiers of the software at the same time is called Integration Testing. These tests cannot reasonably be expected to be fully written before all the parts of the system are at least in place (if not fully).


问:
How do you explain the source of an identifed problem without making it an "excuse"?
As practicing (as much as I can at least) "egoless programming", I'm focused on solving problems whoever wrote the code related (if that person don't make dangerous code) and I like to understand the problem fully to be sure to solve the source of this problem.

However, when someone point my code to show an error, I often try to remember what was my mindset while writing the defect code and I try to explain it to the guy pointing the error to make clear what was the error source (for example when some names are badly choosen, you might use them in a way they were not intended too and with apparent success...).

Now, I do this by reflex and most of my coworkers does understand this reflex. But I also worked in companies where coworkers were in a mentality of blaming the people that made the identified problems, with or without humour (for me it have the same not-sane effect anyway).

In this kind of environnement, explaining why you got to write wrong code makes others think that you're trying to build an excuse. I remarked that most non-technical people (or non domain-expert, not sure, it's only personal experience) also react exactly like that when you try to explain why you did something wrong.

So, when dealing with this kind of people/environnement, how do you manage to explain the real source of the error without looking like "making an excuse"? (and is it even worth trying to explain?)

答:
Regardless, you made a mistake, so you should admit it. You may have had an infinitely small chance avoiding it, but you wrote it and it got released. </p>

<p>When dealing with people with no domain or technical expertise, why are you giving detailed explanations? It either sounds like an excuse or an explanation that is over their heads which they'll interpret as an excuse. </p>

Body:
Regardless, you made a mistake, so you should admit it. You may have had an infinitely small chance avoiding it, but you wrote it and it got released.

When dealing with people with no domain or technical expertise, why are you giving detailed explanations? It either sounds like an excuse or an explanation that is over their heads which they'll interpret as an excuse.


问:
Should I use friend classes in C++ to allow access to hidden members?
Here is my situation (a simple example).

Say I have a class called HiddenData

Then I have another class called StoreHiddenData

And finaly a class called OperateHiddenData

Here's the thing, my class called HiddenData has private members that I don't want to be visible to the  rest of the world, but I still need classes to be able to operate on private members of this HiddenData class (StoreHiddenData and OperateHiddenData for example).  I would like to be able to pass this object around to different classes that do different things on it.

Another thing I was thinking of is to create a form of handle to these HiddenData objects, but I can't think of a way to use handles without using friend classes again (as to give the other classes access to a table that contains what the handles point to, without exposing it to the rest of the world as well).

I was reading this question on this site just a while ago as I was researching the use of friend classes, and it has me thinking if using friends is the best way to go.

If anyone has any suggestions for how to accomplish this task without the use of friend classes in C++, or if the use of friend classes is an OK OOP practice, please provide me with any suggestions.  Thanks.

EDIT:
I figure I should add a little bit more information about my problem.  For one thing, I am trying to create an API that consists of several classes that hide their functionality from the outside and only allow public functions to be accessed.  On the inside I have data structures (or classes, doesn't really matter), that need to be passed around to these different classes with public functions.  I don't want the outside to have access to anything inside these data structures other than being able to pass them around to functions of the API.  I kind of think of it like the Windows API, where you pass around Handles to API functions, but you can't actually dissect the handles in your own code.  Well I would like to do something very similar, but while remaining object oriented, and NOT passing these private data structures around by value because they will be BIG.  Thanks again.

答:
No, you should not use friend classes. Expose public API that so that your clients (at this point, you, via StoreHiddenData and OperateHiddenData) are able to modify the contents of Hidden Data with the use of an API. As a last resort, use getters and setters.Make sure you design your public interface to be cohesive, don't just expose functionality to be able to write fast code.

But before you do anything, read Effective C++ by Scott Meyers. It will answer a lot of your questions, and it's always useful as a reference book.


答:
Here's what you say:

"I take full responsibility. I'll do my best to correct it and not do it in the future."

What can someone say then?  They either accept what you have said and move on or they discipline you.  That's it.  It puts the onus back on them to do something or, as I said, move on.

Title: How do you explain the source of an identifed problem without making it an "excuse"?

Body:
As practicing (as much as I can at least) "egoless programming", I'm focused on solving problems whoever wrote the code related (if that person don't make dangerous code) and I like to understand the problem fully to be sure to solve the source of this problem.

However, when someone point my code to show an error, I often try to remember what was my mindset while writing the defect code and I try to explain it to the guy pointing the error to make clear what was the error source (for example when some names are badly choosen, you might use them in a way they were not intended too and with apparent success...).

Now, I do this by reflex and most of my coworkers does understand this reflex. But I also worked in companies where coworkers were in a mentality of blaming the people that made the identified problems, with or without humour (for me it have the same not-sane effect anyway).

In this kind of environnement, explaining why you got to write wrong code makes others think that you're trying to build an excuse. I remarked that most non-technical people (or non domain-expert, not sure, it's only personal experience) also react exactly like that when you try to explain why you did something wrong.

So, when dealing with this kind of people/environnement, how do you manage to explain the real source of the error without looking like "making an excuse"? (and is it even worth trying to explain?)


答:
The following is from the "Copyright" file included in the Aspell distribution:

This English word list is comes directly from SCOWL 7.0 (up to level
  60, using the speller/make-aspell-dict script,
  http://wordlist.sourceforge.net/)  and is thus under the same
  copyright of SCOWL.  The affix file (only included in the aspell6
  package) is based on the Ispell one which is under the same copyright
  of Ispell.  Part of SCOWL is also based on Ispell thus the Ispell
  copyright is included with the SCOWL copyright.

The collective work is Copyright 2000-2011 by Kevin Atkinson as well
  as any of the copyrights mentioned below:

This specifies the origins of the files. It then goes on to state in no uncertain terms that what you are trying to do is explicitly allowed (emphasis added):

Copyright 2000-2011 by Kevin Atkinson

Permission to use, copy, modify, distribute and sell these word

  lists, the associated scripts, the output created from the scripts,

  and its documentation for any purpose is hereby granted without fee,

  provided that the above copyright notice appears in all copies and

  that both that copyright notice and this permission notice appear in

  supporting documentation. Kevin Atkinson makes no representations

  about the suitability of this array for any purpose. It is provided

  "as is" without express or implied warranty.

I admit that I had to dig for this info. It was not listed on the web site directly, but I figured it would be in the distribution files somewhere. That really is the authoritative place that has to contain copyright and license details.


答:
If you're using NSDefaults (or CFPreferences), you can update the default settings immediately. They get pushed to the background process cfprefsd (short for Core Foundation PREFerenceS Daemon) which holds them in RAM and writes to disk at its leisure. Killing your app does not kill cfprefsd, so the settings don't get lost.

(Killing cfprefsd, which I've actually seen people suggest as a way to keep it from overwriting a .plist that they've just modified behind its back, can wreak unbounded collateral damage. That would be a no-no.)

Title: Mac OS X preferences saving, when to apply/save changes made by user

Body:
It is typical for Mac OS X apps to have preferences that apply seamlessly, and preferences dialogs don't have "OK" or "Apply" button. I want to implement this behavior in my project, but I can't decide when to apply/save changes made by user.

It's quite clear that checkboxes and drop-downs can be saved immediately upon change, but when it comes to text fields, this approach seems questionable. For example, entering "programming.stackexchange.com" as host address will trigger 29 HDD writes, which seems just wrong. Moreover, in my simple implementation this will cause the entire settings file to be rewritten.

So is there any standard way to implement MacOS-like preferences?


问:
Relatively large data on client side in web application
We are discussing on building a web application where (as per clients requirement), there will be relatively large data (60,000 items) to be shown as tree view.

Let's assume each item is string of 500 characters .

My questions is about maintaining such data on client side.

Basically this is an overkill to be used in asp.NET web form with viewstate (correct me if I am wrong).

What are better options of handling such huge list of items with providing sorting and searching ability on them?

I was thinking to bring them once and keep them in local storage but then found out local storage to be limited to 5MB and it's clear that we need more.

答:
I had a similar problem where we needed to display information about cars and other products that was structured like a tree (car brand -> model -> type -> build year). Even if the browser would hold that much data (not sure about that) it would take forever to download it.

What I did: Load the first level and load other levels via Ajax only when actually needed for display. Since we needed to display this as a menu and show the next level very fast on mouse over the possible results where cached on the server (if you need specific sorting this may become a problem).

Same goes for searching and sorting. Let the server do it and load the results. You won't sort over the whole structure in a tree view, but only on one level. Obviously this may be the most difficult part depending on how exactly your data is structured and what types of searching and sorting you want to do.

Also in a tree view people won't have open all nodes at once, this makes it bad to handle and you would need to scroll all the time. You could still load the first two levels if the amount of data allows it and then load level three if level two is opened for some item. So this can be handled as you need it.

Even if loading on demand would not work for you, you could still just load level one and after that when the document is loaded start some process in the background that loads the deeper levels one by one. This would most likely work faster than the user can scroll down.


问:
Message Queue for RTOS for microcontrollers
I'm currently writing an RTOS for microcontrollers. The whole thing is written in C++11 - if anyone is interested, and the link to the repository is at the bottom.

Currently I'm writing a class that is a simple data queue for passing objects between threads (or between interrupt handlers and threads or interrupt handlers and other interrupt handlers). Usually I try to follow some common APIs found on other projects, yet I didn't find any example of concurrent queue that has emplace() function AND supports timeouts.

My general "problem" is that I cannot decide between these two interfaces:

(std::chrono::duration<Rep, Period> is a templated type, I omit the template boilerplate for clarity)

First version:

```<code>template<typename T>
class FifoQueue
{
public:
    ...
    template<typename... Args>
    int tryEmplaceFor(std::chrono::duration<Rep, Period>, Args&&... args);
    int tryPopFor(T&, std::chrono::duration<Rep, Period>);
    int tryPushFor(const T&, std::chrono::duration<Rep, Period>);
    int tryPushFor(T&&, std::chrono::duration<Rep, Period>);
    ...
}
</code>```

Second version:

```<code>template<typename T>
class FifoQueue
{
public:
    ...
    template<typename... Args>
    int tryEmplaceFor(std::chrono::duration<Rep, Period>, Args&&... args);
    int tryPopFor(std::chrono::duration<Rep, Period>, T&);
    int tryPushFor(std::chrono::duration<Rep, Period>, const T&);
    int tryPushFor(std::chrono::duration<Rep, Period>, T&&);
    ...
}
</code>```

(there will be a second set of these functions with ...Until suffix - these would use timepoint instead of duration)

The first version follows a "common style" of having the timeout as the last parameter (examples are POSIX message queues, std::condition_variable, simple queues in any RTOS for microcontrollers). The issue is that it's not possible to have this timeout argument as the last one for tryEmplaceFor() function, because in case of variadic templates "known" arguments must be first (*). So the second version is "consistent" - all functions with timeout have the timeout as the first argument. This variant has an obvious problem of being probably the first example of having timeout as the first argument for such functionality.

Which interface would serve the OS better:

established standard of having the timeout as the last argument (with exception of tryEmplaceFor() and tryEmplaceUntil() - where it must be the first argument (*))?

consistency - prefer the timeout to be the first argument?

(*) - I know that technically I could have the timeout as last argument for tryEmplaceFor() and tryEmplaceUntil(), but I'd rather avoid using such template magic for such simple scenario - doing all these recursive instantiations just to get the last argument seems a bit overkill, especially when I visualize the errors compiler would produce in case user does something wrong...

Repository

Parts already implemented

答:
As suggested by an answer that was deleted (unfortunately) and comments, I followed the "consistency" line (second presented variant) - in all "try...For" and "try...Until" functions the timeout (duration or time point) is the first argument.

This is the code at current stage - link

OwnerDisplayName: Freddie Chopin


答:
Short answer: you don't

Chances are that whoever is pointing out the error is not interested in why it's wrong, they just want it fixed. That fact that you want to discover why the error was made and what you can learn from it and thus improve upon is laudable, but again whoever is pointing out the error is probably not interested in hearing your internal monologue.

keep doing what you're doing, it helps you improve. But don't do it out loud in front of the user.


答:
I can think of a perfect Don't do it example.

Lets say we have a ProductController:

```<code>public class ProductController()
{
    public ViewResult Discontinued()
    {
        var db = new ProductsDb();
        var products = db.Products.Where(x => x.Discontinued).ToList();
        return new ViewResult(products);
    }
}
</code>```

With razor we have an alternative

```<code>public class ProductController()
{
    public ViewResult Discontinued()
    {
        var db = new ProductsDb();
        var products = db.Products.ToList();
        return new ViewResult(products);
    }
}
</code>```

and in our view:

```<code>@model IEnumerable<Product>

@foreach (var item in Model.Where(x => x.Discontinued)) {
    ....
}
</code>```

I think it is pretty obvious that the second solution just feels so wrong. If you do something like this, don't blame razor - blame yourself.

And don't forget: Being able to use C# in views is not a razor feature, it was possible with ASP.NET views, too. With razor it's just a little bit simpler.

If you are searching for a template engine which is more rails like you should take a look at nancy.fx with the Super simple view engine.

Body:
I can think of a perfect Don't do it example.

Lets say we have a ProductController:

public class ProductController()
{
    public ViewResult Discontinued()
    {
        var db = new ProductsDb();
        var products = db.Products.Where(x => x.Discontinued).ToList();
        return new ViewResult(products);
    }
}

With razor we have an alternative

public class ProductController()
{
    public ViewResult Discontinued()
    {
        var db = new ProductsDb();
        var products = db.Products.ToList();
        return new ViewResult(products);
    }
}

and in our view:

@model IEnumerable<Product>

@foreach (var item in Model.Where(x => x.Discontinued)) {
    ....
}

I think it is pretty obvious that the second solution just feels so wrong. If you do something like this, don't blame razor - blame yourself.

And don't forget: Being able to use C# in views is not a razor feature, it was possible with ASP.NET views, too. With razor it's just a little bit simpler.

If you are searching for a template engine which is more rails like you should take a look at nancy.fx with the Super simple view engine.


问:
Confusion between F# and C#
I am fairly new to functional programming and C#/F#.

What is unclear to me is: Can you do functional programming in C# and/or in F#?
Or is it something like, you write some OO code in C#, and some FP code in F#, and use them together?

答:
Both F# and C# are .NET languages, meaning they both compile to IL code (which is similar to Java bytecode).

If you write your code to use a specific subset of IL (called CLS compliant - meaning it only uses features that are compatible with all .NET languages), you can use a library written in one .NET language in all other .NET languages.

Now, C# was created as an object oriented language - it has evolved over time and now has some functional features, meaning one can write in a functional style in C#.

F# was created as a functional language. It isn't pure and can have side effects (in particular when using libraries written in other .NET languages, including the base class libraries).

There are no hard rules as to what style to use with which language, but yes, using F# for functional code and C# for OO code makes sense as that is what either language was created for and lends itself to.

And one can use them together, provided the code is written with interoperation in mind (not a hard requirement either, but it can make life easier).

Title: Confusion between F# and C#


问:
What is exclusive arc in database and why it's evil?
I was reading most common database design mistakes made by developer Q&A on stackoverflow. At first answer there was phrase about exclusive arc:

An exclusive arc is a common mistake where a table is created with two
  or more foreign keys where one and only one of them can be non-null.
  Big mistake. For one thing it becomes that much harder to maintain
  data integrity. After all, even with referential integrity, nothing is
  preventing two or more of these foreign keys from being set (complex
  check constraints notwithstanding).

I really don't understand why exclusive arc is evil. Probably I didn't understand the basics of it. Is there any good explanation on exclusive arcs?

答:
As far as I understood it a long time ago, in an exclusive arc a table contains a number of columns that are foreign keys to other tables, but only one of these can be set at a time (due to some logical constraint on the domain following from the real world). As this rule cannot be enforced on the database a corrupt record could be created where more than one of these foreign keys has a value.

I'll make an example. Consider an application where a company keeps track of the trucks it uses to deliver goods. A truck can only be in one of three places at the same time: it can be with an employee, it can be in a parking garage or it can be in a maintenance shop. This could be modeled by having a Truck-table with employeeId, parkingGarageId and maintenanceShopId, referencing the Employee, ParkingGarage and MaintenanceShop-tables. There is no way to enforce the rule that only one of these fields is filled out on the level of the database. Bad code or somebody with direct access to the database could insert a record that has two or three fields filled, which amounts to data corruption in the database.


答:
If you're worried about being sued, find a lawyer.  A quick consultation will cost a whole lot less than any lawsuit that comes up because you were mistaken, and that's true regardless of whether you win or lose.

Moreover, if you try to write such a thing yourself, and you're not a lawyer, you're likely to screw it up in some way.  You will overstep yourself and ask the user for more than is legally permissible, or you will leave ambiguities (and the courts are likely to resolve all ambiguities against you), or provide loopholes, or some combination of the three.

A simple disclaimer of responsibility, with no button for acceptance, is the most I'd dare do without legal advice, and I'd probably copy the disclaimer on the GPLv3, almost word for word.

(There's also the question of what this is a disclaimer for.  Will it appeal to businesses or will it be recreational, or something else?  Web service or software?  There's all sorts of possibilities, and they can't all be treated the same.)

Title: Summarize terms of service?

Body:
What's your opinion on summarizing the ToS?

Example:

```<code>[ToS here]
Basically, it means you won't sue me.
[I accept][I don't accept]
</code>```

Is this good practice or will this just get you sued more?


问:
Providing production code samples as part of an invited freelance work proposal?
I have only recently started to market myself as a 'programmer' rather than an analyst or something else entirely.  In a recent search of freelance/part-time/contract work, I came across an ad for a contract "R Programmer".  I was well qualified for the position and submitted my technical resume.  I had an interview and was asked to submit a proposal for some contract work for the company, a well-funded start up that has an interesting--and useful--product.

As part of the proposal, they would like, among other things, an R package that gives them the means to analyze their customer's data along with a write up of what the output(s) of my package means and how it would help their customers.  The company also provided five samples of their client's data (along with an NDA that I was required to sign) so I could write and test out my code.

I'm curious as to how I protect myself and the code/R package I've written from being used commercially?  In other words, I'll be providing this R package as part of a proposal; in other parts of my business, a technical proposal doesn't contain any sort of tool that could be used immediately as part of a commercial business.  Is there some sort of copyright I could attach to the package or proposal documentation, similar to their NDA I was required to sign, that could afford me some sort of protection should they decide to use my R package without payment?

What is there that prevents a company from using a code sample commercially without paying the author?

答:
Your best bet is probably to write a clear statement in everyday language that the code is your copyright; is provided for information only without warranty to be read not used; and you forbid it to be used or disseminated without your express permission. You could say you would transfer the copyright to the client for some modest fee or if they engage you for a contract. There - perhaps I've done it for you :)

If you want to spend money, and probably some extra time, find a software lawyer, explain what you want, and pay them to write you a license agreement. Personally I'd suggest it's probably not worth it. Realistically, are you actually going to sue them if they use your code? If not, perhaps the best thing is if the intention of your copyright statement is clear, and not so much whether it would actually stand up in court (whether it has the correct legal phrasing).

What prevents a company from using a code sample commercially without paying the author? You probably have no way of telling whether they used your code internally. So, mostly, honesty. If they are organised (e.g. large, profitable, and have been in existence for a long time) they may have internal procedures/auditing that will prevent them using code illegally.


问:
Heredoc or an external template file in my bash script - how it affects readibility/maintanance?
I realise that this question may be down to personal preference but I'm pretty new to Bash / shell scripting so thought it'd be worth some research to see if there's some sort of standard/best practise or agreeable consensus.

I'm working on a few scripts that I'd eventually like to release open source (probably MIT license) so I'd like the scripts to be "done right", if there is such a thing.

The script in question has to produce an output text file from a template using variable substitution/expansion to 'fill in the blanks' as it were. At present I am using the heredoc method but I'd like to preserve TAB indents, both in my script and in the output (for readability).

Whilst I have achieved this to a certain extent using cat <<-EOF to strip the leading tabs (from my script) and by using a variable to store the TAB space (e.g. T="$(printf '\t')") which I then reference with $T which is then interpreted correctly within the heredoc back in to a TAB character, I can't help but think if an external file would just be simpler?

What do any of you more experienced bash scripters can say about it? Which of those practices is better when it comes to the code readibility/maintanance?

Here's a quick example of what I mean...

```<code>my_function() {
    T="$(printf '\t')"
    cat <<- EOF
        This is my template for $something
        $T  I'm indented with the TAB space variable...
        $T  ...but actually I'm indented twice because the "<<-" only strips the 'leading' tabs
        There's something else that I need, but it might be \${printed_literally}/$or_expanded which is cool!
    EOF
}
</code>```

It's nothing special really, I'm not looking for a 'solution' as such, more just some guidance on which solution to use -- i.e. heredoc in the script or an external template file?

答:
It seems simpler to include all the text relevant to the script inside the script itself,
inside the heredoc, as you did.

Bash scripts are meant to be glue code, nothing too serious and complicated.
If your script is getting serious or complicated,
that's a sign to consider using a more advanced scripting or programming language.


问:
Flexible and easy to use settings class
I am thinking about a way to create a flexible "settings class" in C#. The question is: How to provide a confortable way to provide default values to the settings. I want the programmer to access the default settings as easy as possible using intellisense. Therefore I encapsulated the default values in a subclass of the actual settings class (instead of defining them directly in the settings class).

```<code> public class ServerSettings
 {
    public ServerSettings(int port = ServerSettings.Default.Port,
                          string anotherSetting = ServerSettings.Default.AnotherSetting)
    {
        this.Port = port;
        this.AnotherSetting = anotherSetting;
    }

    public int Port { get; set; }
    public string AnotherSetting { get; set; }

    public class Default
    {
        public const int Port = 7000;
        public const string AnotherSetting = "abcd";
    }
}
</code>```

The programmer now is able to access the default values like this:

```<code>ServerSettings.Default.Port
</code>```

And after typing ServerSettings.Default a list with all available default settings will show up. It's like a "multitype enum".

What do you think of this solution? Do you have any alternative ideas? Or some criticism?

答:
What do you think of this solution? Do you have any alternative ideas? Or some criticism?

It's fine. Personally, I would just have a public static readonly instance on ServerSettings rather than the nested type. Then you can pass around ServerSettings.Default (or use it if someone passes in null somewhere). Plus it seems to be a little cleaner to me.

In C#, there's the built in stuff that people are used to, though I think is highly overrated.

You should probably mark this class as Serializable or with DataContract to make it clear that it's meant to be used that way. I would also make the object itself read only. Modifying settings at runtime is a dicey prospect that can easily go bad and is hard to reproduce.

All that said, I would encourage you to use settings infrequently. Too often people make their code configurable when it's never going to change. It's straightforward, but it's also one more tidbit of complexity - one more thing that can go wrong. It makes your code more brittle.

I would also encourage you to break up your settings. Having one giant settings blob is convenient, but it's also a short and easy path to a coupling nightmare. Let things know about what they need to know about and no more, just like any other data.

Title: Flexible and easy to use settings class


答:
It sounds like you're recreating the Configuration Management class that the .NET framework already provides.

One thing that I've seen done is to provide a wrapper class around the ConfigurationManager so that a default value can be specified in case the requested configuration parameter isn't present or isn't readable in the configuration file.

Using the .NET configuration class buys you a couple of benefits such as caching of the application properties, compatibility with threaded programs, and atomic operations with reading / writing to the configuration file.

Title: Flexible and easy to use settings class

Body:
I am thinking about a way to create a flexible "settings class" in C#. The question is: How to provide a confortable way to provide default values to the settings. I want the programmer to access the default settings as easy as possible using intellisense. Therefore I encapsulated the default values in a subclass of the actual settings class (instead of defining them directly in the settings class).

```<code> public class ServerSettings
 {
    public ServerSettings(int port = ServerSettings.Default.Port,
                          string anotherSetting = ServerSettings.Default.AnotherSetting)
    {
        this.Port = port;
        this.AnotherSetting = anotherSetting;
    }

    public int Port { get; set; }
    public string AnotherSetting { get; set; }

    public class Default
    {
        public const int Port = 7000;
        public const string AnotherSetting = "abcd";
    }
}
</code>```

The programmer now is able to access the default values like this:

```<code>ServerSettings.Default.Port
</code>```

And after typing ServerSettings.Default a list with all available default settings will show up. It's like a "multitype enum".

What do you think of this solution? Do you have any alternative ideas? Or some criticism?


问:
Redundant ElseIf-Else Blocks
These types of if-elseif-else blocks appear all over the place, and in no small number (so the less the better). Every time I have to think and decide: Do I want the simpler or the more thorough of the two... and I don't want to think about it anymore.

For example, if I am expecting only one of three integers (0, 1, 2)... don't I want to know (throw or terminate) if I get something else? (In the case of Example #2, the function do_two() could be triggered by any value other than 0 or 1). Obviously, this may depend on if I want my code to break or to continue upon encountering an anomaly, which rigorous testing should detect anyways (but who can ever be sure?). But I am looking for an answer that is appropriate in all, or most, cases. Please explain your answer, if your reasoning differs from my own.

NOTE REGARDING DUPLICATE: I don't think this is a duplicate for two reasons: The answers to the question suggest using switch statements and code abstraction. I don't use switch statements for something this small due to the overhead, nevermind not liking them much at all. Second, if the code can be abstracted, I may still vary well need to run these checks... plus more overhead. My question is aimed at the necessity in covering corner cases using the final else. Most people, in my experience (which is minimal), would jump to using Example #1 if SCRUMing. I think the best point (comment -> answer?) is yes there is a difference and it depends on whether or not I am coding defensively.

Example #1:

```<code>if(!is_null(variable) && is_integer(variable))
{
    if(variable == 0)
        do_zero();
    elseif(variable == 1)
        do_one();
    elseif(variable == 2)
        do_two();
    else
        throw_error();
}
</code>```

Example #2:

```<code>if(!is_null(variable) && is_integer(variable))
{
    if(variable == 0)
        do_zero();
    elseif(variable == 1)
        do_one();
    else
        do_two();
}
</code>```

答:
Ask yourself, what is the expected behavior of your method when the variable is outside the range? Should it:

Silently discard it and do nothing? Then your second approach is fine.

Inform the caller that the variable is wrong? My answer focuses on this case.

Although I would prefer the first approach, it can be improved. The second approach, on the other way, should be avoided, because it makes debugging difficult, since nothing happens when the value is outside the allowed range.

If the variable is outside the range, you may want to know this early in order to terminate (for example by throwing an exception) early too.

For example, this Python code:

def demo(something):
    if something == 0:
        do_zero()
    elif something == 1:
        do_one()
    elif something == 2:
        do_two()
    else:
        raise ValueError("Something is out of range.")
```

<p>can be rewritten this way:</p>

<pre class="lang-py prettyprint-override"><code>def demo(something):
    if something < 0 or something > 2:
        raise ValueError("Something is out of range.")

    if something == 0:
        do_zero()
    elif something == 1:
        do_one()
    elif something == 2:
        do_two()
</code>```

The if block at the beginning of the method is called the guard clause, a refactoring technique used to remove nested conditionals. Here, we don't have nested conditionals, but it is still useful to move arguments validation at the beginning of the method.

Depending on your language, there may be more to do. Most obvious in some languages, such as Python, is the replacement of if/elif/else by a map. The previous method becomes:

def demo(something):
    if something < 0 or something > 2:
        raise ValueError("Something is out of range.")

    # Creating the map between the values of `something` and the corresponding methods to call.
    map = {
        0: do_zero,
        1: do_one,
        2: do_two,
    }

    # Invoking the method.
    map[something]()
```

<p>From there, you may want to remove the guard clause to obtain a more compact piece of code:</p>

<pre class="lang-py prettyprint-override"><code>def demo(something):
    map = {
        0: do_zero,
        1: do_one,
        2: do_two,
    }

    if something in map:
        map[something]()
    else:
        raise ValueError("Something is out of range.")
</code>```

A positive side effect is also the removal of code duplication: you don't have to specify the allowed range separately from the values, which can be the cause of a mistake where you change the list of values but forget to change the corresponding range.

In order to reduce the code even further, you may rely on the framework. In Python, for instance, accessing a value in a dictionary with a key which doesn't exist throws an exception, which means that this piece of code:

def demo(something):
    {
        0: do_zero,
        1: do_one,
        2: do_two,
    }[something]()
```

does the same thing, except that the type of exception is different (KeyError instead of ValueError). Given that the method is small and it's easy to understand what's going here when receiving the KeyError, this last refactoring is acceptable. On the other hand, if you're dealing with a larger method or the types of exceptions are more distant, avoid relying on the framework and throw the exception explicitly (and preferably early).

Title: Redundant ElseIf-Else Blocks

Body:
Ask yourself, what is the expected behavior of your method when the variable is outside the range? Should it:

Silently discard it and do nothing? Then your second approach is fine.

Inform the caller that the variable is wrong? My answer focuses on this case.

Although I would prefer the first approach, it can be improved. The second approach, on the other way, should be avoided, because it makes debugging difficult, since nothing happens when the value is outside the allowed range.

If the variable is outside the range, you may want to know this early in order to terminate (for example by throwing an exception) early too.

For example, this Python code:

def demo(something):
    if something == 0:
        do_zero()
    elif something == 1:
        do_one()
    elif something == 2:
        do_two()
    else:
        raise ValueError("Something is out of range.")

can be rewritten this way:

def demo(something):
    if something < 0 or something > 2:
        raise ValueError("Something is out of range.")

    if something == 0:
        do_zero()
    elif something == 1:
        do_one()
    elif something == 2:
        do_two()

The if block at the beginning of the method is called the guard clause, a refactoring technique used to remove nested conditionals. Here, we don't have nested conditionals, but it is still useful to move arguments validation at the beginning of the method.

Depending on your language, there may be more to do. Most obvious in some languages, such as Python, is the replacement of if/elif/else by a map. The previous method becomes:

def demo(something):
    if something < 0 or something > 2:
        raise ValueError("Something is out of range.")

    # Creating the map between the values of `something` and the corresponding methods to call.
    map = {
        0: do_zero,
        1: do_one,
        2: do_two,
    }

    # Invoking the method.
    map[something]()

From there, you may want to remove the guard clause to obtain a more compact piece of code:

def demo(something):
    map = {
        0: do_zero,
        1: do_one,
        2: do_two,
    }

    if something in map:
        map[something]()
    else:
        raise ValueError("Something is out of range.")

A positive side effect is also the removal of code duplication: you don't have to specify the allowed range separately from the values, which can be the cause of a mistake where you change the list of values but forget to change the corresponding range.

In order to reduce the code even further, you may rely on the framework. In Python, for instance, accessing a value in a dictionary with a key which doesn't exist throws an exception, which means that this piece of code:

def demo(something):
    {
        0: do_zero,
        1: do_one,
        2: do_two,
    }[something]()

does the same thing, except that the type of exception is different (KeyError instead of ValueError). Given that the method is small and it's easy to understand what's going here when receiving the KeyError, this last refactoring is acceptable. On the other hand, if you're dealing with a larger method or the types of exceptions are more distant, avoid relying on the framework and throw the exception explicitly (and preferably early).


问:
How to make a legacy system time-zone sensitive?
I need to implement time zones in a very large and old Delphi system, where there's a central SQL Server database and possibly hundreds of client installations around the world in different time zones. The application already interacts with the database by only using the date/time of the database server. So, all the time stamps saved in both the database and on the client machines are the date/time of the database server when it happened, never the time of the client machine.

So, when a client is about to display the date/time of something (such as a transaction) which is coming from this database, it needs to show the date/time converted to the local time zone. This is where I get lost.

I would naturally assume there should be something in SQL to recognize the time zone and convert a DateTime field dynamically. I'm not sure if such a thing exists though. If so, that would be perfect, but if not, I need to figure out another way.

This Delphi system (multiple projects) utilizes the SQL Server database using ADO components, VCL data-aware controls, and QuickReports (using data sources). So, there's many places where the data goes directly from the database query to rendering on the screen, without any code to actually put this data on the screen. In the end, I need to know when and how should I get the properly converted time?

What is the proper way to ensure that I handle Dates and Times correctly in a legacy application?

答:
The problem here is that the views are connected directly to the models.

Although this sounds horrible to achieve in delphi, the first step is to enforce a separation of concerns.

You could use a MVVM approach and have intermediary view-models that perform localised transformation of database values for display.  These same view-models can transform localised input into the timezone the database expects when storing data.

MVP or some other MV* variant might be better suited depending on how you're currently set up and your exact requirements, but you get the picture.  The upside of all this work is that future localised changes will be much, much easier to accomplish.


问:
Why are mostly 9999, 99999.... are used for making comparisons
I (I am sure everyone else also) have always seen comparisons of some value to 999 or 9999 .... etc.
for e.g.:

in CSS

```<code>z-index: 9999
</code>```

or some times

```<code>str.length < 99999
</code>```

I wonder if there is some fact behind it or its a trend.

答:
Code readability.

While the number 99999 isn't very meaningful for the computer, it is meaningful for people. It says "some really, really high value which should be larger than any other". However, in many situations, this is usually bad style because

it is often not the largest number possible and in some edge-cases the program might encounter a larger one during normal operation and

many programming languages offer special constructs for the largest possible numbers. C has the INT_MAX macro in limits.h, Java has Integer.MAX_VALUE.

Even when such features are not available, a good programmer would look up the largest possible value supported by their environment and use that as a syntactical value for "really, really large", but many are too lazy and just hammer the "9" key on their keyboard.


问:
Declaring lambdas in Java8
What would be the best practice to declare lambdas in Java8 code? How it was designed to be used?

For example, let's say that we have a method that accept a Function. I want to provide function implementation that can be reusable. So I can do this:

[A] Implement a Function interface:

```<code>public class Foo implements Function<A,B> {
    public B apply(A a) {...}
}
...
useFunction(new Foo());
</code>```

[B] Declare Function as lambda in some static field:

```<code>public interface Foo {
    Function<A,B> bar = it -> { ....}
}
...
useFunction(Foo.bar);
</code>```

[C] Use method reference:

```<code>public class Foo {
    public static B bar(A a) {...}
}
...
useFunction(Foo::bar);
</code>```

Until functional programing in java8, I tried not to pollute code with statics. However, now I am somehow 'forced' to use statics (or global singletons) for storing reusable lambdas.

EDIT

I have code that returns the following on several places:

```<code>return CompletableFuture.supplyAsync(() -> {
...
}
.exceptionally(FooExceptionWrapper::wrap);
</code>```

As you see, I want to share the wrapper (that is a Function) instances, and yet to remain fluent with the code. There are many ways how we can share this.

If I create new instance every time (like in A) then we are going to create new instance on every call, which is fine; yet GC is going to be called more frequently. I can instead create a singleton and since this is a Function, sharing it across the threads is not going to be a problem. So I might store it in some variable. Now, I would like to put the handling code out of this class (simple to reduce the size and the responsibility of the class). So I use approach A - but still want to see if there is more 'proper' way for this. There are not many java8 projects out there, and lot of people simple use static fields (like in B); Im just questioning all that.

答:
I would generally prefer method A because it is the most familiar idiom to Java programmers (being the only one of your options that was available before Java 8) and because it generates slightly better bytecode than C (which involves an extra automatically generated adapter class) which may result in more efficient code.

I would choose method C if (and only if) some aspect of the problem being solved made it more readable, for instance if you have a large family of related functions to choose from that could sensibly all be implemented in one class.

I would never use option B, which seems to me to be using lambdas for the sake of it.

Title: Declaring lambdas in Java8


问:
What is different between the internal design of Java and C++ that lets C++ have multiple inheritance?
It's drilled into the newbie Java programmers that Java (pre-Java 8) has no multiple class inheritance, and only multiple interface inheritance, because otherwise you run into diamond inheritance problem (Class A inherits from classes B and C, both of which implement method X. So which of those classes' implementation is used when you do a.X() call?)

Clearly, C++ successfully addressed this, since it has multiple inheritance.

What's different between the internal design of Java and C++ - (i'm guessing in the method dispatch methodology, and vaguely recall that it had to do with vtables from my long-ago computer languages class) that allows this problem to be solved in C++ but prevents in Java?

To rephrase:

What is the methodology of the language design/implementation used in C++ to avoid the ambiguity of diamond inheritance problem, and why couldn't the same methodology be used in Java?

答:
The diamond inheritance problem is not solved in C++, in the sense that C++ does allow you to shoot yourself in the foot this way.

The problem is solved in Java because a deliberate design decision was made to disallow multiple inheritance of implementations, thereby omitting the design element from which the problem arises.

The real problem with multiple inheritance is that its complexity outweighs its potential benefit.  That's principally why it was omitted from Java, not because of the diamond inheritance problem.


答:
There's nothing fundamental in the internal design which causes this. The lack of multiple inheritance is a deliberate design decision in Java, not an external manifestation of a shortcoming in the internal design.

(I'm deliberately avoiding getting into the flame war as to whether multiple inheritance is a good idea or not).

Title: What is different between the internal design of Java and C++ that lets C++ have multiple inheritance?

Body:
It's drilled into the newbie Java programmers that Java (pre-Java 8) has no multiple class inheritance, and only multiple interface inheritance, because otherwise you run into diamond inheritance problem (Class A inherits from classes B and C, both of which implement method X. So which of those classes' implementation is used when you do a.X() call?)

Clearly, C++ successfully addressed this, since it has multiple inheritance.

What's different between the internal design of Java and C++ - (i'm guessing in the method dispatch methodology, and vaguely recall that it had to do with vtables from my long-ago computer languages class) that allows this problem to be solved in C++ but prevents in Java?

To rephrase:

What is the methodology of the language design/implementation used in C++ to avoid the ambiguity of diamond inheritance problem, and why couldn't the same methodology be used in Java?


答:
Clearly, C++ successfully addressed this, since it has multiple inheritance.

Actually no, exactly the opposite.  C++ did not successfully address this, and the diamond inheritance problem is a serious issue for C++ developers.  There are techniques for dealing with it using "virtual inheritance", but often they make things more complicated.

Java and other languages that came after C++ didn't fail to implement multiple inheritance because they couldn't solve it the same way C++ did; they learned from C++'s mistakes and didn't implement a feature that introduces problems that are not easily solveable.


答:
If you expect a function to be reused or shared, make it a method and use a method reference. If you just need a short, throwaway piece of logic, make it a lambda. Explicitly creating instances of a functional interface has no advantages and has disadvantages:

Less idiomatic

More boilerplate

You commit to types up front, while a method reference or lambda will match any functional interface with the right signature.

Most likely less efficient

Title: Declaring lambdas in Java8

Body:
What would be the best practice to declare lambdas in Java8 code? How it was designed to be used?

For example, let's say that we have a method that accept a Function. I want to provide function implementation that can be reusable. So I can do this:

[A] Implement a Function interface:

```<code>public class Foo implements Function<A,B> {
    public B apply(A a) {...}
}
...
useFunction(new Foo());
</code>```

[B] Declare Function as lambda in some static field:

```<code>public interface Foo {
    Function<A,B> bar = it -> { ....}
}
...
useFunction(Foo.bar);
</code>```

[C] Use method reference:

```<code>public class Foo {
    public static B bar(A a) {...}
}
...
useFunction(Foo::bar);
</code>```

Until functional programing in java8, I tried not to pollute code with statics. However, now I am somehow 'forced' to use statics (or global singletons) for storing reusable lambdas.

EDIT

I have code that returns the following on several places:

```<code>return CompletableFuture.supplyAsync(() -> {
...
}
.exceptionally(FooExceptionWrapper::wrap);
</code>```

As you see, I want to share the wrapper (that is a Function) instances, and yet to remain fluent with the code. There are many ways how we can share this.

If I create new instance every time (like in A) then we are going to create new instance on every call, which is fine; yet GC is going to be called more frequently. I can instead create a singleton and since this is a Function, sharing it across the threads is not going to be a problem. So I might store it in some variable. Now, I would like to put the handling code out of this class (simple to reduce the size and the responsibility of the class). So I use approach A - but still want to see if there is more 'proper' way for this. There are not many java8 projects out there, and lot of people simple use static fields (like in B); Im just questioning all that.


答:
Both the Java and C++ underlying systems are powerful enough to allow/support multiple inheritance.

Neither system provides any baked in solutions (or other assistance) to help developers deal with the consequences/potential problems.

In C++, the conscious decision was made to expose as much of the power of the underlying system to developers as possible, and allow them to decide which subsets of the system are worth using, and which are not. A good part of the decision, initially, probably had to do with the initial compiler implementations not having to do much extra work to support multiple inheritance. The decision stuck.

As far as Java goes, see here for an early (1995) explanation. The explicit decision was made to prevent multiple inheritance from being possible, at the language level - it was deemed to be too much of a "foot gun".


问:
How to package static content outside of web application?
Our web application has static content packaged as part of WAR. We have been planning to move it out of the project and host it directly on Apache to achieve the following objectives.

It's getting too big and bloating the EAR size resulting in slower deployment across nodes. Faster deployment times.

Take the load of Application Server

Host the static content on a sub domain allowing some browsers (IE) to load resources simultaneously

Give us an option to use further caching such as Apache mod_cache apart from the cache headers we send out to browsers.

We use yuicompressor-maven-plugin to aggregate and minimize JS file.

My question is how to package and manage this static content outside of the web application?

My current options are:

New maven war project. Still use the same plugin for aggregation and compression.

Just a plain directory in SVN and use YUI/Google compressor directly.

Or is there a better technology out there to manage static content as a project?

答:
It sounds like the static resources change rarely, if ever, and require significant additional space and time to process.

I would have a separate WAR file. There are several benefits to doing this:

You can easily hook into automated processes such as build servers, artifact repositories, and deployments. For example, you could add a Maven dependency to your parent POM and Jenkins can easily build and deploy the new project with minimal configuration changes.

The distribution file is still a single archive in a standard format. That makes it easy to maintain and easy to pass around if necessary.

You can update static resources and the web application independently, saving time for both when they update. Code updates do not require packaging a ton of static resources: resource updates do not require compiling code and running code unit tests.

By reusing existing deployment processes you maintain the same number of failure points while not increasing the training work load.

OwnerDisplayName: chinto


答:
The fundamental difference is that Java defines conversions from a type to any of its supertype as being identity-preserving.  This is a useful property to have, but it is incompatible with multiple inheritance.  If d1 and d2 both derive from b, and thing is of a type which derives from both d1 and d2, then in the absence of severe restrictions on what d1 and d2 can do, it's possible that (b)(d1)thing and (b)(d2)thing should behave differently.  If all casts from thing to b are required to go through d1 or d2, then it's possible for (b)(d1)thing and (b)(d2)thing to yield different objects, but that would imply that the casts are not identity-preserving.

Another difficulty which arises is that C++ is designed to be statically linked, which means that anything in the design of types d1 and d2 which would make use of common members ambiguous would be caught at link time.  If the suppliers of d1 and d2 simultaneously add new features which are incompatible with each other, even though each would be compatible with the previous version of the other class, the person supplying the program that uses both would have to find a combination of classes that would work before the program could be linked, but consumers of the program would then be assured that the bundled versions of d1 and d2 would be compatible with each other.

In Java, it's expected that different parts of a program may be upgraded separately.  If the author of a class releases a new version, code which uses that class can be made to use the new version without having to involve the original programmer of the consuming code.  A consequence of this is that if certain combinations of versions of different classes will work, but a few combinations will generate troublesome ambiguities, it's likely that some such problems will only be discovered by a few unlucky end users who happen to have the exact troublesome combinations of versions.

While such versioning issues could arise in any case, multiple inheritance adds some kinds of failure which would be very hard to predict.  If code is allowed to use a member which exists in one superclass but not the other without having to specify the superclass, then adding a like-named member to the other superclass would become a breaking change.  Since the author of a class will generally have no idea with which other classes it may be combined, such an author would have no way of knowing what names were "safe" to use.

To be sure, some of the aforementioned problems can arise with Java's new "default interface implementations" feature; the value of the feature was judged sufficient to justify accepting them.  Still, it's worthwhile to note that the dynamic linking of Java classes makes the tradeoffs very different from what they would be in a statically-linked language like C++.


问:
Ideal export in terms of size for asynchronous module definitions in JavaScript?
When creating AMD modules you can export whatever you like whether it be an object or a function.  I vaguely recall reading a recommendation somewhere to export just one thing; the idea being "keep it small."

Using this philosophy means that one might go as far as to export single functions.  And when this is coupled with the idea of composition, one will very likely use one function to build up another function.  As a result, when loading a page that uses a highly-composed function one might end up asynchronously downloading a handful of little modules in order to build up a composed function.

Take underscore.js which has many functions built in.  There are web pages where I just need one or two of it's functions but I find myself a little at odds with pulling the whole library in as a module just for that.  I am half tempted to rewrite the one or two functions to avoid that, but that goes against the idea of reuse.  Still, because underscore has several dozen function, pulling it down with an AMD loader like RequireJS is often going to mean pulling down more than necessary.  If one goes to the other extreme, decomposing a library like underscore into single function modules, one can run into the aforementioned issue of pulling a couple couple handfuls of tiny modules when highly-composed functions are needed.

So what's the verdict?  How does one draw the line when deciding how much to export from an AMD module?  A function is the smallest composable unit.  An object that gets exported is often really a namespace which offers a suite a functions, many of which won't get used.

I searched online for discussions surrounding this, but apparently I couldn't find the right search terms to locate them.  If you're aware of any, please include any links where this has been discussed to support your answer.

答:
Don't worry about your exports being too fine-grained or too broad. This is what we have build-time tools for.

If you want to export many small modules (or individual functions), we have tools like RequireJS Optimizer to merge everything into a single resource. If you want to export a large namespace object with some functions that may be unused, we have tools like Closure Compiler to remove the dead code.

Organize your modules in a way you are comfortable with and have each individual script export whatever it needs to export. Let the tooling handle the rest.

Also note that while AMD allows multiple defines in a single source file, via explicitly named modules, this is not recommended. Each source file should only define a single module, and it should be anonymous. Named modules are only intended for use in a compiled script, such as those produced by Optimizer.


问:
How to manage data flow between UI components?
I have been trying to use classes that implement ActionListener to respond to user input.  I'm consistently noticing that for an action listener to communicate the event to other objects, it has to contain the object.  Like,

The object I want to get updated when action_src is clicked:

```<code>public class Display_Field {
    JTextField display;

    public Display_Field ( JButton action_src ) {
        action_src.addActionListener( new Open_Dialog_Click( this ) );
    }

    public void setText( String text ) {
        display.setText( text );
    }
}
</code>```

The ActionListener I plan to add to action_src:

```<code>public class Open_Dialog_Click implements ActionListener {
    private Display_Field display;

    public void actionPerformed( ActionEvent action ) {
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog( null );
        display.setText( chooser.getSelectedFile().getName() );
    }

    public Open_Dialog_Click( Display_Field display ) {
        this.display = display;
    }
}
</code>```

There is so many convolutions! Like, the display needs to be constructed with a button that adds an ActionListener that needs to be constructed with the display...

Is there a less convoluted way to allow data to flow between components?

I have considered making a central class that houses all the listeners, acting as wiring for any and all intercomponent communication, but that seems like the class is doing too much for its own good.  ...or is that how it is done after all?

答:
Is there a less convoluted way to allow data to flow between components?

Yes.  It's called a model.  In a model / view / controller pattern (MVC), an instance of the model is passed to the view so that the values in the model can be read by the view.  The values in the model are updated by controller classes.

In a Java Swing application, you generally have many controller classes, each responsible for a portion of the view.

Take a look at my John Conway’s Game of Life in Java Swing article, to see how a fairly simple Java Swing application makes use of the MVC pattern.


问:
Using higher order functions to apply m out of M filter's and then transform data of size n?
Total no: of filters possible is M . User can select m filters where m <= M . A typical example is files from a folder , he could say modified between so and so date , start with so and so and so on.

```<code>meets = []
for each in something:
    if user_filter1:
       if user_filter1_condition_met:
          meets.append(True)
    #hardcode all other filters here
    if all(meets):
          do_something(each)

    else:
       meets = True
       for each in something:
           do_something(each)
</code>```

Here I am repeating the entire code again which is against DRY principles.

```<code>for each in something:
    if user_filter:
       if not filter_condition_met:
          continue
    do_something(each)
</code>```

Here I am doing the filter check for all items in the loop, while essentially it needs to be done just once.

Can I use higher order functions to check the filter condition once and generate a code that does the job? It looks like a filter and then transform operation. Can someone give some ideas?

An addendum to the question with a similar essence:

```<code>def function(inner,outer):
      for each in outer:
           for each in inner:
                 print "Something"

#Border condition inner doesn't exist I need a code object that goes like this:

def function(inner,outer):
      for each in outer:
           print "Something"

#Inner doesn't exist , so I want to to not go a for each in inner operation i.
#I mean it won't change the complexity of the problem at hand
#But suppose there are billions elements , I save billion for each in [].
</code>```

答:
Here I am doing the filter check for all items in the loop, while essentially it needs to be done just once.

Why is that a problem?

Write code in the cleanest way possible. If it makes sense to structure the code with the boolean test made multiple times, then write it that way.

Avoid unneeded optimizations, to quote Knuth, "premature optimization is the root of all evil".


答:
To answer the OP's original question, there is a significant implementation feature in C++ not present in Java that allows multiple inheritance. The difference is that C++ must employ special tricks to fix up the 'this' pointer before entering a virtual function in a class with multiple concrete base classes. These tricks are vtable thunking and double-wide vtables.

C++ objects are arranged in memory as a contiguous block. Each derived class appends data to the block. Classes with a single inheritance chain start at one point in memory and all base classes and ancestors of the most derived class have the same 'this' pointer. Interfaces don't have any data so they don't affect the object layout. The 'this' pointer of all bases remains the same. This is true in C++, Java, C# and other languages that support objects with a single chain of concrete class inheritance along with any number of interfaces.

For a class with multiple concrete bases, only the layout of the first inheritance chain can be contiguous and coincident with the most derived class. The actual layout is implementation dependent and can become quite complex especially when there are several chains and several repeated copies of some base objects. In any case, the 'this' pointer changes depending on the point of view of each member function. This is not a problem for static or non-virtual functions, as the 'this' pointer is calculated at compile time. However, C++ must employ special tricks to fix up the 'this' pointer before entering a virtual function.

There were two popular strategies for this in the early days of C++. One was vtable thunking and the other was double-wide vtables.  You can read more details about them in Inside the C++ Object Model by Stanley B Lippman. Essentially:
1) vtable thunking replaces the actual function address in the vtable with the address of a runtime thunk (an anonymous chunk of code) that adjusts the 'this' pointer then JMPs into the member function. The cost is a slight additional overhead for calling a virtual function in a class with multiple base classes.
2) double-wide vtables still store the member function address in the vtable but also the relevant 'this' pointer for that function (or a way to calculate it). The cost is that the vtable takes twice as much space for classes with multiple bases.

NOTE: Virtual Base Classes, including multiple virtual base classes, is an entirely different concept that uses an entirely different implementation. The common strategy for implementing VBCs is extending the vtable backward into negative offsets with pointers to the (not necessarily contiguous) data blocks of the virtual classes.

Of course, a class that has both virtual base classes and multiple concrete base classes will be quite a hairy monster indeed. I always marvel that C++ even compiles.


答:
Something like this is what I wanted: (Applying a sample use case I could come up with)

```<code>predicates = []

if filenamme:
   predicates.append(lambda x,filename: x.name == filename)
if from_dt and to_dt:
   predicates.append(lambda x, from_dt, to_date: from_dt <= x.mod_dt <= to_dt)

for file in files:
    if all(predicate(file) for each in predicates):
       do_something(file)
</code>```

I wanted to generate my predicates outside.

Title: Using higher order functions to apply m out of M filter's and then transform data of size n?

Body:
Total no: of filters possible is M . User can select m filters where m <= M . A typical example is files from a folder , he could say modified between so and so date , start with so and so and so on.

```<code>meets = []
for each in something:
    if user_filter1:
       if user_filter1_condition_met:
          meets.append(True)
    #hardcode all other filters here
    if all(meets):
          do_something(each)

    else:
       meets = True
       for each in something:
           do_something(each)
</code>```

Here I am repeating the entire code again which is against DRY principles.

```<code>for each in something:
    if user_filter:
       if not filter_condition_met:
          continue
    do_something(each)
</code>```

Here I am doing the filter check for all items in the loop, while essentially it needs to be done just once.

Can I use higher order functions to check the filter condition once and generate a code that does the job? It looks like a filter and then transform operation. Can someone give some ideas?

An addendum to the question with a similar essence:

```<code>def function(inner,outer):
      for each in outer:
           for each in inner:
                 print "Something"

#Border condition inner doesn't exist I need a code object that goes like this:

def function(inner,outer):
      for each in outer:
           print "Something"

#Inner doesn't exist , so I want to to not go a for each in inner operation i.
#I mean it won't change the complexity of the problem at hand
#But suppose there are billions elements , I save billion for each in [].
</code>```

Body:
Something like this is what I wanted: (Applying a sample use case I could come up with)

predicates = []

if filenamme:
   predicates.append(lambda x,filename: x.name == filename)
if from_dt and to_dt:
   predicates.append(lambda x, from_dt, to_date: from_dt <= x.mod_dt <= to_dt)

for file in files:
    if all(predicate(file) for each in predicates):
       do_something(file)

I wanted to generate my predicates outside.


问:
Is having a parent controller to manage a set of tabbed sections an anti-pattern for an angular application?
A lot of times, I have long forms that I divide into multiple tabbed sections. Each section is managed by it's own controller and there is a parent controller that manages the whole view. I use ui-router for dividing such sections into states.

Should I make a service instead of a controller to manage the all the sections but generally, I don't have business logic in their. It's mostly done for collection data altogether and passing  it to an API using ng-resource.

I know

答: This is a good use case for a parent controller. If your tabbed panel behavior is general enough, you might consider abstracting it further into a directive. But generally there is nothing wrong with creating a top-level controller to coordinate several related child controllers.</p>


问:
How to access secure web services from a desktop application?
I'm writing a Java desktop application that will be available to the public. It will contact backend APIs via HTTPS using Jersey client.

I don't know anything about using certificates in desktop apps but from what I've found out so far I'll need to create an SSLContext that reads a public certificate from a KeyStore that is protected by a password.

I'm assuming I can distribute the contents of the KeyStore by packaging it in the Jar of my app. But I don't see how I can securely make the key store password available to the app. I don't want the users to have to enter it manually.

答:
You can generally read public keys without the password.  The default cacerts file comes with the password changeit but can be read without the password.

If you use a commercial certificate, Java may be able to connect without needing significant setup.


问:
Range of values based on key values
I'm trying to implement a method of searching trough a large amount of 2D points for those that match a certain range. I'm thinking of creating HashMaps for <X, Point> and <Y, Point> but I'm wondering is HashMap good for doing this, because I will be taking points in a range, based on values from x_min to x_max and y_min to y_max.

So I will basically take all points from <X,Point> searching from x_min to x_max and compare them to points taken from <Y,Point> from y_min to y_max...

```<code>HashMap<Integer,Point> x_coordinates = new HashMap<Integer,Point>();
for(int i=x_min;i<=x_max;i++){
    if(x_coordinates.containsKey(i))
        x_coordinates.get(i);
}

HashMap<Integer,Point> y_coordinates = new HashMap<Integer,Point>();
for(int i=y_min;i<=y_max;i++){
    if(y_coordinates.containsKey(i))
         y_coordinates.get(i);
}
</code>```

Is there a faster way to get a range of values from a HashMap, or some other type of data structure?

For example, if range = 200, select all points that match the range from x-200 to x+200 and from y-200 to y+200

I'm trying to avoid iteration through all of the points, but also I want to avoid making a huge 2D matrix, because the points in question are scattered around a large area.

After some testing and based on MichaelT's answer, I've written this code:

```<code>TreeMap<Integer, TreeMap<Integer, Integer>> values;
for (int x : values.subMap(x_min, x_max).keySet()) {
        for (int y : values.get(x).subMap(y_min, y_max).values()) {
            // y here, represents the values of points in range...
        }
    }
</code>```

答:
What you are describing is a sparse matrix upon which you wish to do a range select.

I'm going to start out with no, neither a HashMap nor a LinkedHashMap will do what you want optimally.  The reason for this to find the elements in a range HashMap is effectively walking an unordered list - O(n).  The LinkedHashMap may be slightly more optimal than awful if the elements are put into the LinkedHashMap in sorted order and no new ones are added afterwards.  Its still not an optimal approach because instead of O(n) you're getting O(n/m) (because you stop walking the list once you get past the range) which is still effectively O(n).  You can't do a binary search on the LinkedHashMap list.

So, lets look at some other structures.  What you are really after is the SortedMap interface.  It allows you to quickly pull out the sub map from one key to another with SortedMap subMap(K fromKey, K toKey) which is what you want to do.  Pick one of those classes and you will have what you are after.

You could then get the values for each of the submaps and do a boolean retainAll(Collection c) of one set to the other.

That's the easy answer. It is effectively the lists of lists approach for the sparse matrix.  You could, however encode the matrix instead in some other format that gives you a more direct sub range option.  This isn't something that is part of the Java standard library and you may find yourself going down this path for writing your own implementation in that case.

If you see the possibility in the future that this may be the case, you should consider writing your own interface for the sparse matrix and then implement a class behind it that does the lookups that you want.  This way if you later decide that you need to change the implementation for some reason, its a matter of changing the implementation (a new class that wraps something else) rather than changing all the code to handle a different structure.

Title: Range of values based on key values