答:
The main issue I have here is are the 720P, 480P, 240P... classes for defining video quality or do they unambiguously define the resolution of the video?

If you have a video file, and all you know is that it's 1080p then it's safe to assume it's 1920x1080. The 1080p and 720p formats are often 16:9 aspect ratio.

If you have a video file, and all you know is that it's 480p then it's safe to assume it's 720x480. The 480p formats are often 4:3 aspect ratio.

While it's true that 1080p only tells you scan lines you can assume the video resolution if the context is that of a regular video file.

There are exceptions. NetFlix uses HD Video but it's shown at 720p which isn't true HD. So later they came out with UltraHD which is 1080p. Still, the video compression is high so the quality is low.

Samsung has released new TVs that display UltraHD which is 4320p at 16:9.

Unless resolution is explicitly stated it's difficult to always know exactly what it is. One trick is to divide by 45. If you get an remainder then it's 4:3 and if no remainder it's 16:9.

```<code> 4320 / 45 = 96 (16:9)
 1080 / 45 = 24 (16:9)
 720 / 45 = 16 (16:9)
 480 / 45 = 10.6666 (4:3)
 240 / 45 = 5.3333 (4:3)
</code>```

Body:
The main issue I have here is are the 720P, 480P, 240P... classes for defining video quality or do they unambiguously define the resolution of the video?

If you have a video file, and all you know is that it's 1080p then it's safe to assume it's 1920x1080. The 1080p and 720p formats are often 16:9 aspect ratio.

If you have a video file, and all you know is that it's 480p then it's safe to assume it's 720x480. The 480p formats are often 4:3 aspect ratio.

While it's true that 1080p only tells you scan lines you can assume the video resolution if the context is that of a regular video file.

There are exceptions. NetFlix uses HD Video but it's shown at 720p which isn't true HD. So later they came out with UltraHD which is 1080p. Still, the video compression is high so the quality is low.

Samsung has released new TVs that display UltraHD which is 4320p at 16:9.

Unless resolution is explicitly stated it's difficult to always know exactly what it is. One trick is to divide by 45. If you get an remainder then it's 4:3 and if no remainder it's 16:9.

 4320 / 45 = 96 (16:9)
 1080 / 45 = 24 (16:9)
 720 / 45 = 16 (16:9)
 480 / 45 = 10.6666 (4:3)
 240 / 45 = 5.3333 (4:3)


问:
Plain old struct vs class in this case?
Stroustrup says that you should use structs unless you can specify an invariant for the data structure. I have to represent a physical object which holds things such as position, velocity, mass and inertia (and so on). I also want to render the object, for which I will need setup in the constructor and unloading stuff in the destructor. So I guess that's an invariant, but it feels wrong to put all this physics stuff into it that doesn't really have invariants.

The drawing parts are pretty trivial, so it doesn't feel worth it to separate them from the rigid body in this case.

Any advice?

edit: I suppose I just realized the answer to my own question. Rigid bodies do have invariants, namely that it has to follow the physical laws.

答:
Whilst a struct is just a class with all public members, semantically I tend to think of a struct as an aggregation of data, maybe with some constructors to enable the data to be initialised easily and provide default values.

Once you start getting "actions" on your data I usually think it is best to use a class, but actually in recent years I have sometimes created a struct of the data members, then used a class wrapper that has a private instance of the struct, so the data is still encapsulated, and performs the functions.

Doing this also makes it easy to store and retrieve the data without having to make the classes that do this into friends whilst giving direct access to data members.

You could well do something like this in your case too.

ContentLicense: CC BY-SA 3.0

Title: Plain old struct vs class in this case?


问:
Should I return Collection or ImmutableCollection from a method?
When writing an API in Java, returning an immutable collection of some sort, I've got the option of returning Collection (or List, Map, etc) from the method, or guava's ImmutableCollection (or ImmutableList, ImmutableMap, etc):

```<code>private final ImmutableMap<> _immutableMap = ...

public Collection<T> getValues() {
    return _immutableMap.values();
}
</code>```

or

```<code>public ImmutableCollection<T> getValues() {
    return _immutableMap.values();
}
</code>```

Which is better?

Setting the return value as ImmutableCollection constrains me to use that exact type forever more, so that I can't swap out _immutableMap for my own immutable type later on that returns, say, an immutable view of the values that isnt an ImmutableCollection (constructing one requires copying the values, and I can't subclass it to provide an immutable view of a mutable collection).

But there is benefit to people calling the method to see the return value is actually immutable, and have the add and remove methods marked as deprecated, rather than trying to add or remove items and have it fail at runtime.

Generally, I like to return the most-specific interface type from a method, so that I can change the underlying implementation later on if necessary without breaking contract. But there is benefit to callers returning an ImmutableCollection, at the cost of constraining future development of the method and causing future possible performance problems due to copying all the values into an ImmutableCollection rather than providing an immutable view.

答:
I would normally recommend using the more abstract types (Collection, List etc) in this case.

Reasons:

It provides more flexibility to return a different concrete type in the future. Somebody may come up with a better ImmutableList than Guava, for example.

Collection, List etc are more familiar to users.

It avoids a dependency on Guava in your public API. Avoiding external dependencies is generally good, use the standard APIs wherever you can.

If you are happy to commit to always using Guava collections, or if this is just an internal API that won't be widely used by different people then I guess it doesn't matter so much.

P.S. if your concern is signalling to the user that the return value is immutable, I would suggest finding another way to communicate this (annotations, documentation, method naming etc.). The Java type system isn't really designed for communicating arbitrary facts about types (some more sophisticated type systems attempt this, but it's still a research topic)


问:
Initializing properties that aren't parameters in a constructor: alternatives
A class loads properties from a file and uses those as it performs its duties.  For testing purposes I want to be able to modify said properties directly without having to use a test properties file.  I did the implementation, but it seems filled with smells -- I'm wrestling with keeping this thing small (avoiding frameworks like Spring that will wrap and inject the properties).

In particular, I cannot recall seeing a constructor that initializes itself via a statically loaded set of properties -- particularly that it sets variable values from somewhere other than passed-in parameters.

I'm looking for arguments for/against this approach, and hoping to hit upon some alternatives if this is really as uncool as I think it is.

```<code>private static final String CONFIG_FILE_NAME = String.format("config-%s.properties",
        null != System.getProperty("JAVA_ENV") ? System.getProperty("JAVA_ENV") : "development");
static {
    PROPERTIES = new Properties();
    try {
        PROPERTIES.load(MyClass.class.getClassLoader().getResourceAsStream(CONFIG_FILE_NAME));
        if (PROPERTIES.keySet().size() < 1) {
            LOGGER.error(String.format("failed to load %s: no properties", CONFIG_FILE_NAME));
        }
    }
    catch (final IOException ie) {
        LOGGER.error(String.format("failed to load %s", CONFIG_FILE_NAME), ie);
    }
}

private String property1;
private String property2;

public MyClass() {
    property1 = PROPERTIES.getProperty("prop.1");
    property2 = PROPERTIES.getProperty("prop.2");
}

/* public accessors for property1 and property2 go here */
</code>```

答:
To start with, static initializer of a named class or interface can not throw a checked exception (JLS 11.2.3. Exception Checking). That is, if application design somehow involves checked exceptions for various problems at initialization, static initializers are simply not an option.

Given your code snippet, you already noticed this - your catch block just logs IOException without re-throwing it. But even without checked exceptions, this is quite a troublesome practice. You can test that by adding code that re-throws runtime exception from your catch block (this will compile) and simulating the absence of config file.

Think of how it would feel to those maintaining your application when they get logs reporting an obscure ExceptionInInitializerError for a routine typo in config file name.

Yet another reason why this practice isn't convenient can be found in JLS 12.4.1. When Initialization Occurs

...Invocation of certain reflective methods in class Class and in package java.lang.reflect also causes class or interface initialization...

Above means that you give up a lot of control for when initialization occurs. Some framework may trigger it when you don't even expect it. If memory serves, in my practice this happened once when logging was't yet fully initialized - believe me, it was no fun to investigate why application crashes when log files were empty.

The last but not the least, this design is very inconvenient for unit testing purposes. Whenever you would want to use MyClass in unit tests, you'd have to ensure that 1) config file is there in file system and 2) that it is stuffed with desired values and properties.

Compare this design to constructor that simply takes Properties as a parameter:

```<code>    MyClass(Properties properties) {
        this.properties = properties; // initialize field from constructor parameter
    }
</code>```

Testing with class constructed like above is as easy as it gets. No messing with the filesystem, no messing with filling the file with desired properties and values, plain Java code. You create Properties object and stuff it however you want, straight from your test code, wherever it is, whenever it is convenient to you.

Summing up, there are plenty reasons why you cannot recall seeing a constructor that initializes itself via a statically loaded set of properties.

Body:
To start with, static initializer of a named class or interface can not throw a checked exception (JLS 11.2.3. Exception Checking). That is, if application design somehow involves checked exceptions for various problems at initialization, static initializers are simply not an option.

Given your code snippet, you already noticed this - your catch block just logs IOException without re-throwing it. But even without checked exceptions, this is quite a troublesome practice. You can test that by adding code that re-throws runtime exception from your catch block (this will compile) and simulating the absence of config file.

Think of how it would feel to those maintaining your application when they get logs reporting an obscure ExceptionInInitializerError for a routine typo in config file name.

Yet another reason why this practice isn't convenient can be found in JLS 12.4.1. When Initialization Occurs

...Invocation of certain reflective methods in class Class and in package java.lang.reflect also causes class or interface initialization...

Above means that you give up a lot of control for when initialization occurs. Some framework may trigger it when you don't even expect it. If memory serves, in my practice this happened once when logging was't yet fully initialized - believe me, it was no fun to investigate why application crashes when log files were empty.

The last but not the least, this design is very inconvenient for unit testing purposes. Whenever you would want to use MyClass in unit tests, you'd have to ensure that 1) config file is there in file system and 2) that it is stuffed with desired values and properties.

Compare this design to constructor that simply takes Properties as a parameter:

    MyClass(Properties properties) {
        this.properties = properties; // initialize field from constructor parameter
    }

Testing with class constructed like above is as easy as it gets. No messing with the filesystem, no messing with filling the file with desired properties and values, plain Java code. You create Properties object and stuff it however you want, straight from your test code, wherever it is, whenever it is convenient to you.

Summing up, there are plenty reasons why you cannot recall seeing a constructor that initializes itself via a statically loaded set of properties.


问:
Event-driven vs. 'reference'-driven programming (i.e. in JavaScript)
I haven't been able to find the appropriate terminology to search for content on the web related to what I'm asking, so I'm hoping someone on here can at least point me in the right direction.

I'm a fairly senior JavaScript developer, but I have a secret -- I don't like event-driven programming (aside from user-triggered event binding I mean). Something about it has never sat well with me, it's the feeling of a "disconnect" in the logic flow.

In the simple example of some module invoking arbitrary numbers of views, an event-driven friend would create event listeners for elements those views could have and keep any reference to the parent module out of the view code.

I, on the other hand, would pass reference to the parent module in to the views so that I could directly trigger the module's methods.

I go for the second approach because I know exactly what is going to happen and what method I'm triggering at all points in the code. In the event-driven case I'm separating the assignment of an event response from the element that would trigger it, putting things in to the 'listening ether'.

I know responsible event-driven programming should avoid any risks like double-binding, etc., but even when that care is taken I still see it all as a bit of a black-box ripe for debugging nightmares. While passing references may be a bit more cumbersome in the code, at least it's clear what things are going to happen and when.

Can anyone identify the pros and cons of these two methods, and in particular why JS seems to be pushing in general toward the event-driven stuff?

答:
Not 100% sure I know what you're asking. But, I get the sense you're at a point where event-driven programming doesn't feel "real" enough -- or like you're at the mercy of someone else's event system. Or like your application isn't really "doing" anything. Or like it's just a bunch of disparate methods that you're feeding another application.

So. Suppose a user-facing application creates and environment and waits for stuff to happen, which is what most applications do. There are two ways to receive those "happenings."

Periodically poll for evidence that something has happened.

Pros:

You can respond to happenings that aren't "events" in someone else's event-model.

The application is not interrupted when it's in the middle of something important. (Not generally relevant concern in JavaScript, because events are queued until the pipe is clear.)

The application retains more precise control over what's running; it has the flexibility to completely ignore input, only check for input every N cycles or seconds, etc.

It may give you a [mistaken] sense of satisfaction that you're writing more real, more thorough code. You're not relying on some silly, mysterious event system. You're doing all the work, dammit!

Cons:

Application is iteratively checking for event flags, often needlessly.

CPU usage is high and potentially running inefficiently due to frequent context switches, increasing likelihood of thrashing.

You likely end up writing and event-system and event-driven code anyway ...

E.g. ...

```<code>while (true) {
  var flags;
  if (flags = checkMouseFlags()) {
    doMouseInput(flags);
  }
  if (flags = checkKeyboardFlags()) {
    doKeyBoardInput(flags);
  }
}

function doMouseInput() {
  // stop lying to yourself. this is an event.
}

function doKeyboardInput() {
  // this is also an event.
}
</code>```

... Alternatively:

Let the host invoke the code when something happens.

Pros:

It's an extension of what happens at lower levels. Unless you're building the hardware, you're ultimately writing event handlers: The CPU is sleeping. It's woken up when something happens. The CPU interrupts the OS to say, "hey, something happened." The OS determines that Chrome should receive the event. The OS invokes Chrome's event-handler. Chrome sets some flags and stuff and invokes your event handlers.

You're not needlessly hogging CPU cycles and introducing context switches.

No need to (re)write and event-system [under the mistaken notion that it's not an event-system].

More reflective of reality, easier to wrap your head around, and easier maintain (once you embrace the model) (Even though you probably don't stop background thinking when you're in a conversation, you also don't "poll" for input. Input from your ears interrupts your thought-process and your respondToStupidRemark handler is triggered.)

Cons:

Puts you at the mercy of someone else's event-system.

Small chance you'll have to do some perverse looking stuff or poll for "events" anyway to respond to things that aren't "events" in your host's event-system.

Weird sense that your application isn't doing anything ...

... Or maybe a weird sense that it's not even an application; just a bunch of tangentially related event-handlers.

Notable: In other languages, and with the advent of worker processes in JavaScript, it's not an either-or paradigm. You can have a background process butchering the CPU and use the existing event-system to do as much or as little with each event as you like.

So, why is JavaScript event-driven?

Because it's reflective of the modeled reality, easy to think about, gentle on the CPU, and it simply extends the host environment to the script.

Body:
Not 100% sure I know what you're asking. But, I get the sense you're at a point where event-driven programming doesn't feel "real" enough -- or like you're at the mercy of someone else's event system. Or like your application isn't really "doing" anything. Or like it's just a bunch of disparate methods that you're feeding another application.

So. Suppose a user-facing application creates and environment and waits for stuff to happen, which is what most applications do. There are two ways to receive those "happenings."

Periodically poll for evidence that something has happened.

Pros:

You can respond to happenings that aren't "events" in someone else's event-model.

The application is not interrupted when it's in the middle of something important. (Not generally relevant concern in JavaScript, because events are queued until the pipe is clear.)

The application retains more precise control over what's running; it has the flexibility to completely ignore input, only check for input every N cycles or seconds, etc.

It may give you a [mistaken] sense of satisfaction that you're writing more real, more thorough code. You're not relying on some silly, mysterious event system. You're doing all the work, dammit!

Cons:

Application is iteratively checking for event flags, often needlessly.

CPU usage is high and potentially running inefficiently due to frequent context switches, increasing likelihood of thrashing.

You likely end up writing and event-system and event-driven code anyway ...

E.g. ...

while (true) {
  var flags;
  if (flags = checkMouseFlags()) {
    doMouseInput(flags);
  }
  if (flags = checkKeyboardFlags()) {
    doKeyBoardInput(flags);
  }
}

function doMouseInput() {
  // stop lying to yourself. this is an event.
}

function doKeyboardInput() {
  // this is also an event.
}

... Alternatively:

Let the host invoke the code when something happens.

Pros:

It's an extension of what happens at lower levels. Unless you're building the hardware, you're ultimately writing event handlers: The CPU is sleeping. It's woken up when something happens. The CPU interrupts the OS to say, "hey, something happened." The OS determines that Chrome should receive the event. The OS invokes Chrome's event-handler. Chrome sets some flags and stuff and invokes your event handlers.

You're not needlessly hogging CPU cycles and introducing context switches.

No need to (re)write and event-system [under the mistaken notion that it's not an event-system].

More reflective of reality, easier to wrap your head around, and easier maintain (once you embrace the model) (Even though you probably don't stop background thinking when you're in a conversation, you also don't "poll" for input. Input from your ears interrupts your thought-process and your respondToStupidRemark handler is triggered.)

Cons:

Puts you at the mercy of someone else's event-system.

Small chance you'll have to do some perverse looking stuff or poll for "events" anyway to respond to things that aren't "events" in your host's event-system.

Weird sense that your application isn't doing anything ...

... Or maybe a weird sense that it's not even an application; just a bunch of tangentially related event-handlers.

Notable: In other languages, and with the advent of worker processes in JavaScript, it's not an either-or paradigm. You can have a background process butchering the CPU and use the existing event-system to do as much or as little with each event as you like.

So, why is JavaScript event-driven?

Because it's reflective of the modeled reality, easy to think about, gentle on the CPU, and it simply extends the host environment to the script.


问:
Why do different java collections have different default capacity?
Looking at different collection constructors the question comes to mind. Why does ArrayList()
construct an empty list with an initial capacity of ten and ArrayDeque()
constructs an empty array deque with an initial capacity sufficient to hold 16 elements.</p>

答:
@Esailija's answer is good for this specific case.

More generally though, it is a trade-off that depends on many factors. I shall give a few examples:

How is the data structure typically used? Data structures that are used as data buffers would typically prefer a much higher capacity than data structures used for small tuples, for example.

What default size of data fits in a cache line on your target CPU platform? It can make a big difference to performance if the default fits in cache line. The choice of 10 is as a default in Java may well be because an array of 10 32-bit words plus the array/object overhead fits in a 64 byte cache line.

How much do you value space vs runtime efficiency? If you want better runtime performance, it is generally better to pre-allocate more space in order to avoid extra re-allocations later.

As a result of these trade-offs, it is quite understandable that different collection implementations may have a different optimal default capacity.


问:
Why do dynamic languages make it more difficult to maintain large codebases?
Large codebases are more difficult to maintain when they are written in dynamic languages. At least that's what Yevgeniy Brikman, lead developer bringing the Play Framework to LinkedIn says in a video presentation recorded at JaxConf 2013 (minute 44).

Why does he say this? What are the reasons?

答:
Because static typing enables better tooling, which improves the productivity of a programmer when he tries to understand, refactor or extend a large existing code base.

For instance, in a large program, we'll likely have several methods with the same name. We instance, we might have an add method that adds something to a set, another that adds two integers, another that deposits money into a bank account, ...). In small programs, such name collisions are unlikely to occur. In large programs worked on by several people, they occur naturally.

In a statically typed language, such methods can be distinguished by the types they operate on. In particular, a development environment can discover, for each method invocation expression, which method is being invoked, enabling it to show a tooltip with that method's documentation, find all call sites for a method, or to support refactorings (such as method inlining, method renaming, modifying the parameter list, ...).


答:
dynamic languages make for harder to maintain large codebases

Caveat: I have not watched the presentation.

I have been on the design committees for JavaScript (a very dynamic language), C# (a mostly static language) and Visual Basic (which is both static and dynamic), so I have a number of thoughts on this subject; too many to easily fit into an answer here.

Let me begin by saying that it is hard to maintain a large codebase, period. Big code is hard to write no matter what tools you have at your disposal. Your question does not imply that maintaining a large codebase in a statically-typed language is "easy"; rather the question presupposes merely that it is an even harder problem to maintain a large codebase in a dynamic language than in a static language. That said, there are reasons why the effort expended in maintaining a large codebase in a dynamic language is somewhat larger than the effort expended for statically typed languages. I'll explore a few of those in this post.

But we are getting ahead of ourselves. We should clearly define what we mean by a "dynamic" language; by "dynamic" language I mean the opposite of a "static" language.

A "statically-typed" language is a language designed to facilitate automatic correctness checking by a tool that has access to only the source code, not the running state of the program. The facts that are deduced by the tool are called "types". The language designers produce a set of rules about what makes a program "type safe", and the tool seeks to prove that the program follows those rules; if it does not then it produces a type error.

A "dynamically-typed" language by contrast is one not designed to facilitate this kind of checking. The meaning of the data stored in any particular location can only be easily determined by inspection while the program is running.

(We could also make a distinction between dynamically scoped and lexically scoped languages, but let's not go there for the purposes of this discussion. A dynamically typed language need not be dynamically scoped and a statically typed language need not be lexically scoped, but there is often a correlation between the two.)

So now that we have our terms straight let's talk about large codebases. Large codebases tend to have some common characteristics:

They are too large for any one person to understand every detail.

They are often worked on by large teams whose personnel changes over time.

They are often worked on for a long time, with multiple versions.

All these characteristics present impediments to understanding the code, and therefore present impediments to correctly changing the code. In short: time is money; making correct changes to a large codebase is expensive due to the nature of these impediments to understanding.

Since budgets are finite and we want to do as much as we can with the resources we have, the maintainers of large codebases seek to lower the cost of making correct changes by mitigating these impediments. Some of the ways that large teams mitigate these impediments are:

Modularization: Code is factored into "modules" of some sort where each module has a clear responsibility. The action of the code can be documented and understood without a user having to understand its implementation details.

Encapsulation: Modules make a distinction between their "public" surface area and their "private" implementation details so that the latter can be improved without affecting the correctness of the program as a whole.

Re-use: When a problem is solved correctly once, it is solved for all time; the solution can be re-used in the creation of new solutions. Techniques such as making a library of utility functions, or making functionality in a base class that can be extended by a derived class, or architectures that encourage composition, are all techniques for code re-use. Again, the point is to lower costs.

Annotation: Code is annotated to describe the valid values that might go into a variable, for instance.

Automatic detection of errors: A team working on a large program is wise to build a device which determines early when a programming error has been made and tells you about it so that it can be fixed quickly, before the error is compounded with more errors. Techniques such as writing a test suite, or running a static analyzer fall into this category.

A statically typed language is an example of the latter; you get in the compiler itself a device which looks for type errors and informs you of them before you check the broken code change into the repository. A manifestly typed language requires that storage locations be annotated with facts about what can go into them.

So for that reason alone, dynamically typed languages make it harder to maintain a large codebase, because the work that is done by the compiler "for free" is now work that you must do in the form of writing test suites. If you want to annotate the meaning of your variables, you must come up with a system for doing so, and if a new team member accidentally violates it, that must be caught in code review, not by the compiler.

Now here is the key point I have been building up to: there is a strong correlation between a language being dynamically typed and a language also lacking all the other facilities that make lowering the cost of maintaining a large codebase easier, and that is the key reason why it is more difficult to maintain a large codebase in a dynamic language. And similarly there is a correlation between a language being statically typed and having facilities that make programming in the larger easier.

Let's take JavaScript for example. (I worked on the original versions of JScript at Microsoft from 1996 through 2001.) The by-design purpose of JavaScript was to make the monkey dance when you moused over it. Scripts were often a single line. We considered ten line scripts to be pretty normal, hundred line scripts to be huge, and thousand line scripts were unheard of. The language was absolutely not designed for programming in the large, and our implementation decisions, performance targets, and so on, were based on that assumption.

Since JavaScript was specifically designed for programs where one person could see the whole thing on a single page, JavaScript is not only dynamically typed, but it also lacks a great many other facilities that are commonly used when programming in the large:

There is no modularization system; there are no classes, interfaces, or even namespaces. These elements are in other languages to help organize large codebases.

The inheritance system -- prototype inheritance -- is both weak and poorly understood. It is by no means obvious how to correctly build prototypes for deep hierarchies (a captain is a kind of pirate, a pirate is a kind of person, a person is a kind of thing...) in out-of-the-box JavaScript.

There is no encapsulation whatsoever; every property of every object is yielded up to the for-in construct, and is modifiable at will by any part of the program.

There is no way to annotate any restriction on storage; any variable may hold any value.

But it's not just the lack of facilities that make programming in the large easier. There are also features that make it harder.

JavaScript's error management system is designed with the assumption that the script is running on a web page, that failure is likely, that the cost of failure is low, and that the user who sees the failure is the person least able to fix it: the browser user, not the code's author. Therefore as many errors as possible fail silently and the program keeps trying to muddle on through. This is a reasonable characteristic given the goals of the language, but it surely makes programming in the larger harder because it increases the difficulty of writing test cases. If nothing ever fails it is harder to write tests that detect failure!

Code can modify itself based on user input via facilities such as eval or adding new script blocks to the browser DOM dynamically. Any static analysis tool might not even know what code makes up the program!

And so on.

Clearly it is possible to overcome these impediments and build a large program in JavaScript; many multiple-million-line JavaScript programs now exist. But the large teams who build those programs use tools and have discipline to overcome the impediments that JavaScript throws in your way:

They write test cases for every identifier ever used in the program. In a world where misspellings are silently ignored, this is necessary. This is a cost.

They write code in type-checked languages and compile that to JavaScript, such as TypeScript.

They use frameworks that encourage programming in a style more amenable to analysis, more amenable to modularization, and less likely to produce common errors.

They have good discipline about naming conventions, about division of responsibilities, about what the public surface of a given object is, and so on. Again, this is a cost; those tasks would be performed by a compiler in a typical statically-typed language.

In conclusion, it is not merely the dynamic nature of typing that increases the cost of maintaining a large codebase. That alone does increase costs, but that is far from the whole story. I could design you a language that was dynamically typed but also had namespaces, modules, inheritance, libraries, private members, and so on -- in fact, C# 4 is such a language -- and such a language would be both dynamic and highly suited for programming in the large.

Rather it is also everything else that is frequently missing from a dynamic language that increases costs in a large codebase. Dynamic languages which also include facilities for good testing, for modularization, reuse, encapsulation, and so on, can indeed decrease costs when programming in the large, but many frequently-used dynamic languages do not have these facilities built in. Someone has to build them, and that adds cost.

Title: Why do dynamic languages make it more difficult to maintain large codebases?

Body:
Large codebases are more difficult to maintain when they are written in dynamic languages. At least that's what Yevgeniy Brikman, lead developer bringing the Play Framework to LinkedIn says in a video presentation recorded at JaxConf 2013 (minute 44).

Why does he say this? What are the reasons?


问:
How to identify unstable floating point computations?
In numerics, it is very important to be able to identify unstable
schemes and to improve their stability.  How to identify unstable
floating point computations?

I am working on a very complex simulation where many numerical schemes work together and I am looking for a methodic to identify its weak parts.  I am working on a physical model involving differential equations.  A bird's eye view of the overall process is:

(Preliminary step) Gather physical observations P.

Determine initial parameters of the simulation. This uses an optimisation algorithm, where we walk in a parameter space and look for parameters C such that some error function E(F(C), P) is minimised, where F is some derived quantity of the parameters.

Plug C in the simulation engine. This is an Euler scheme of the EDP, so that at each time step, we compute the terms driving the dynamic (each of them is a complex function, potentially subject to instability) and feed the Euler scheme with these dynamic terms to compute the next state. This goes on for thousands time points.

At the end of the simulation, we compute some function Proof(S) of the final state S and compare to some quantities Require(P) deduced from the observed quantities. This is not a formal proof of the result, more a plausibility check.

Also, I see a tower of complex operations (computation of dynamic terms, within the Euler scheme, within the Proof). And would like to recognise “bad parts” and fix them.

I speculate that using a software implementation of floating point
numbers with reduced precision would magnify the unstability of
numerical schemes, thus easing the comparison between different
implementations.  Is this a common technique to investigate this
question?  Is it possible to use a virtual machine, as Bochs, to
achieve this without altering the program?

To deal appropriately with the stability question, it is sometimes
acceptable to target the typical input of the numerical procedure, so
that it can be tuned to do well on that input and maybe less well on
other valid, yet unlikely, input.  Given a sample of typical inputs,
it is possible to snoop some intermediate results and prepare a
statistical profile for them.  Again, is this a common technique to
study stability issues?  Is a virtual machine useful for this?

答:
Designing stable floating point algorithms is highly nontrivial. Those more mathematically skilled than myself suggest using well regarded libraries where possible rather than attempting to roll your own. The standard reference in the area seems to be:

N. J. Higham. Accuracy and Stability of Numerical Algorithms. Society for Industrial and Applied Mathematics, Philadelphia, PA, USA, second edition, 2002. ISBN 0-89871-521-0

Not knowing more about what types of computations, languages, etc. makes it hard to give much of a concrete answer.  There is a good lecture here: http://introcs.cs.princeton.edu/java/91float/ this may be a little basic, but it's a good introduction if you are using java.


问:
What are some examples of inverted classical inheritance?
Are there any examples of inheritance in languages where classes call their subclasses' methods rather than their super classes' methods?

It should not behave like traditional inheritance like the following.

```<code>Parent.method = function () {
    // Do things
}
Child.method = function () {
    // Do things
    super.method()
    // Do things
}
</code>```

It should instead behave like this.

```<code>Parent.method = function () {
    // Do things
    sub.method()
    // Do things
}
Child.method = function () {
    // Do things
}
</code>```

Does this pattern have a name?

答:
This is common in the Strategy Pattern:

abstract class Strategy {
  void stepA();
  void stepB();

  void execute() {
    stepA();
    stepB();
  }
}

class SpecificStategy extends Strategy {
  void stepA() { ... }
  void stepB() { ... }
}

new SpecificStrategy().execute();
```

<p>The concept of <em>traits</em> is also built around this: A trait is similar to an abstract base class in that it can define implementations plus interfaces of required methods, which an implementing class must provide.</p>

<p>Some object systems like <em>CLOS</em> (for Common Lisp) or <em>Moose</em> (for Perl) also have the ability that a method can refer to <code>inner</code>, which is this method's implementation in a subclass. If no subclass provides another implementation, then it is a no-op. Here, defining a method of the same name is different from overriding the method. Perl example:</p>

<pre class="lang-perl prettyprint-override"><code>package Report {
  use Moose;

  sub display {
    say "Some title:";
    say "";
    inner();
    say " - $_" for qw< foo bar baz >;
  }
}

package SpecificReport {
  use Moose;
  extends 'Report';

  # "augment" avoids overriding the parent implementation
  augment display => sub {
    say "some paragraph";
    say "";
    inner();
  };
}

SpecificReport->display;
</code>```

Output:

```<code>Some title:

some paragraph

 - foo
 - bar
 - baz
</code>```

Body:
This is common in the Strategy Pattern:

abstract class Strategy {
  void stepA();
  void stepB();

  void execute() {
    stepA();
    stepB();
  }
}

class SpecificStategy extends Strategy {
  void stepA() { ... }
  void stepB() { ... }
}

new SpecificStrategy().execute();

The concept of traits is also built around this: A trait is similar to an abstract base class in that it can define implementations plus interfaces of required methods, which an implementing class must provide.

Some object systems like CLOS (for Common Lisp) or Moose (for Perl) also have the ability that a method can refer to inner, which is this method's implementation in a subclass. If no subclass provides another implementation, then it is a no-op. Here, defining a method of the same name is different from overriding the method. Perl example:

package Report {
  use Moose;

  sub display {
    say "Some title:";
    say "";
    inner();
    say " - $_" for qw< foo bar baz >;
  }
}

package SpecificReport {
  use Moose;
  extends 'Report';

  # "augment" avoids overriding the parent implementation
  augment display => sub {
    say "some paragraph";
    say "";
    inner();
  };
}

SpecificReport->display;

Output:

Some title:

some paragraph

 - foo
 - bar
 - baz


问:
Specific and generic behaviour for derived objects that client doesn't need to be aware of
We have a database with tables that use an inheritance hierarchy. An entity in the derived table will have an ID that matches an entity in the base table and so on through the hierarchy.

We have repository classes for the derived types/tables so that you can get specific instances by ID. The problem we have at the moment is that we want the ability to apply specific behaviour to some of the entities, but we also want some generic behaviour applied to all the base entities. It would be good if a client could treat a collection of entities as the base entity and just call the method to perform this action on it, without having to know about the specific behaviour.

So the client will receive from the server a collection of entities, including their ID. The client will then call a method on the server with some of those IDs and somehow the server needs to be able to tell which derived types the IDs belong to.

I considered leaving the table inheritance in place so that data isn't duplicated, but having a "type" tag in the base-table. Is this defeating the purpose of the inheritance hierarchy?

答:
A type tag is perfectly normal. It really simplifies queries.

```<code> select p.type, p.foo, a.bar, b.baz
 from parent p
 join child a on p.id = a.id
 join child2 b on p.id = b.id
 where p.type = 'some type'
</code>```

The database doesn't have polymorphism and you will need an identifier at the global level (i.e. parent table) in order to make the transition from database to class objects

Body:
A type tag is perfectly normal. It really simplifies queries.

 select p.type, p.foo, a.bar, b.baz
 from parent p
 join child a on p.id = a.id
 join child2 b on p.id = b.id
 where p.type = 'some type'

The database doesn't have polymorphism and you will need an identifier at the global level (i.e. parent table) in order to make the transition from database to class objects


问:
How to mock method with hard coded object?
I am working on an application which have multiple layers. Data access layer to retrieve and save data from data source, business logic to manipulate data, user interface to show the data on screen.

I also doing unit testing of the business logic layer. The only requirement is to test the flow of business layer logic. So I use Moq framework to mock the data access layer and unit test the business logic layer with MS Unit.

I am using interface programming to make the design decouple as much as possible so that unit test can be done. Business layer call data access layer through interface.

I am facing a problem when I am trying to test one of the business logic method. That method does some work and create an object and pass it to data access layer. When I am trying to mock that data access layer method then it can not successfully mock.

Here I am trying to create a demo code to show my problem.

Model:

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

Data access layer:

```<code>public interface IDal
{
    string GetMessage(Employee emp);
}

public class Dal : IDal
{
    public string GetMessage(Employee emp)
    {
        // Doing some data source access work...

        return string.Format("Hello {0}", emp.Name);
    }
}
</code>```

Business logic layer:

```<code>public interface IBll
{
    string GetMessage();
}

public class Bll : IBll
{
    private readonly IDal _dal;

    public Bll(IDal dal)
    {
        _dal = dal;
    }

    public string GetMessage()
    {
        // Object creating inside business logic method.
        Employee emp = new Employee();

        string msg = _dal.GetMessage(emp);
        return msg;
    }
}
</code>```

Unit test:

```<code>[TestMethod]
    public void Is_GetMessage_Return_Proper_Result()
    {
        // Arrange.
        Employee emp = new Employee; // New object.

        Mock<IDal> mockDal = new Mock<IDal>();
        mockDal.Setup(d => d.GetMessage(emp)).Returns("Hello " + emp.Name);

        IBll bll = new Bll(mockDal.Object);

        // Act.

        // This will create another employee object inside the
        // business logic method, which is different from the
        // object which I have sent at the time of mocking.
        string msg = bll.GetMessage();

        // Assert.
        Assert.AreEqual("Hello arnab", msg);
    }
</code>```

In unit test case at the time of mocking I am sending an Employee object but when invoking the business logic method, it is creating different Employee object inside the method. That is why I can not mock the object.

In that case how to design so that I can solve the problem?

答:
Instead of creating an Employee object directly by using new, your class Bll could use an EmployeeFactory class for this, with a method createInstance, which is injected through the constructor:

```<code> class EmployeeFactory : IEmployeeFactory
 {
       public Employee createInstance(){return new Employee();}
 }
</code>```

The constructor should take the factory object through an interface IEmployeeFactory, so you can replace the "real" factory it easily by a mock factory.

```<code>public class Bll : IBll
{
    private readonly IDal _dal;
    private readonly IEmployeeFactory _employeeFactory;

    public Bll(IDal dal, IEmployeeFactory employeeFactory)
    {
        _dal = dal;
        _employeeFactory=employeeFactory;
    }

    public string GetMessage()
    {
        // Object creating inside business logic method
        // *** using a factory ***
        Employee emp = _employeeFactory.createObject();
        // ...
    }
    //...
}
</code>```

The mock factory can provide the test with any kind of Employee object you need for your test (for example, createInstance could always return the same object):

```<code> class MockEmployeeFactory : IEmployeeFactory
 {
       private Employee _emp;

       public MockEmployeeFactory()
       {
          _emp = new Employee();
          // add any kind of special initializing here for testing purposes
       }

       public Employee createInstance()
       {
          // just for testing, return always the same object
          return _emp;
       }
 }
</code>```

Now using this mock in your test should do the trick.

Body:
Instead of creating an Employee object directly by using new, your class Bll could use an EmployeeFactory class for this, with a method createInstance, which is injected through the constructor:

 class EmployeeFactory : IEmployeeFactory
 {
       public Employee createInstance(){return new Employee();}
 }

The constructor should take the factory object through an interface IEmployeeFactory, so you can replace the "real" factory it easily by a mock factory.

public class Bll : IBll
{
    private readonly IDal _dal;
    private readonly IEmployeeFactory _employeeFactory;

    public Bll(IDal dal, IEmployeeFactory employeeFactory)
    {
        _dal = dal;
        _employeeFactory=employeeFactory;
    }

    public string GetMessage()
    {
        // Object creating inside business logic method
        // *** using a factory ***
        Employee emp = _employeeFactory.createObject();
        // ...
    }
    //...
}

The mock factory can provide the test with any kind of Employee object you need for your test (for example, createInstance could always return the same object):

 class MockEmployeeFactory : IEmployeeFactory
 {
       private Employee _emp;

       public MockEmployeeFactory()
       {
          _emp = new Employee();
          // add any kind of special initializing here for testing purposes
       }

       public Employee createInstance()
       {
          // just for testing, return always the same object
          return _emp;
       }
 }

Now using this mock in your test should do the trick.


问:
How to know, with good performance, which areas a certain point is in?
I'm interested in build a prototype that needs this sort of thing:

Point A (xa, ya) with a radius of 500 meters.

Point B (xb, yb) with a radius of 700 meters.

Point C (xc, yc) with a radius of 1200 meters.

Point D (xd, yd) with a radius of 200 meters.

Person 123 is in some certain point.

Question: which points 123 is in? For example, the person is both inside A, B and D areas, but not on C.

All points are geographic coordinates, i.e. lat/long. I want to understand what are the best algorithms and strategies to implement a good index. My current idea (not implemented yet) is:

The hole map is divided in quadrants, small as (for example) 50~100 > meters. When a point is marked, all quadrants inside their area will > be marked as well. Then, when I search using "Person 123", I'll just > find its quadrant and retrieve all points marked into it.

Basically I'll build a huge prefix tree based on geohashes of all points (+10k points). Problem is, for a single point, there will be numerous entries inside the Tree (though it would be better for searching, I think). Note I lack the formal understanding of spatial indexes.

答:
Although the Quadtree suggested in the comments is the canonical solution, you might be able to get away with the design you propose yourself, except that I would store the points in a Hashtable-based Dictionary. The dictionary is nice as it only costs space proportional with the amount of Points Of Interest. You dont need to reseve memory for the empty sahara desert.

You simply define a numbering scheme for your quadrants, and the quadrant number is then the key for the hashtable. For each quadrant you store a list of POI's in the hashtable. Each of your points of interest will get an entry in the poi list in  each of the quadrants it touches.

If you reduce the resolution of your grid a bit, that will reduce the memory use even more, but you will need to iterate through more points, especcially if they are close together. I think your current grid is too dense as each poi touches about a 100 quadrants. i would strive for a figure below 10, on average.


答:
I would treat it as single unit to test.

As long as you control all inputs from which the Employee object is created, the fact that it is created in the tested object shouldn't matter. You just need a the mock method to return expected result if the content of the argument matches expectation.

Obviously it means you need to provide custom logic for the mock method. Advanced logic often can't be tested with just "for x return y" kind of mocks.

In fact, you should not make it return different object in the tests than it will in production, because if you did, you wouldn't be testing the code that should create it. But that code is integral part of the production code and therefore should be covered by the test case too.

Title: How to mock method with hard coded object?

Body:
I am working on an application which have multiple layers. Data access layer to retrieve and save data from data source, business logic to manipulate data, user interface to show the data on screen.

I also doing unit testing of the business logic layer. The only requirement is to test the flow of business layer logic. So I use Moq framework to mock the data access layer and unit test the business logic layer with MS Unit.

I am using interface programming to make the design decouple as much as possible so that unit test can be done. Business layer call data access layer through interface.

I am facing a problem when I am trying to test one of the business logic method. That method does some work and create an object and pass it to data access layer. When I am trying to mock that data access layer method then it can not successfully mock.

Here I am trying to create a demo code to show my problem.

Model:

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

Data access layer:

```<code>public interface IDal
{
    string GetMessage(Employee emp);
}

public class Dal : IDal
{
    public string GetMessage(Employee emp)
    {
        // Doing some data source access work...

        return string.Format("Hello {0}", emp.Name);
    }
}
</code>```

Business logic layer:

```<code>public interface IBll
{
    string GetMessage();
}

public class Bll : IBll
{
    private readonly IDal _dal;

    public Bll(IDal dal)
    {
        _dal = dal;
    }

    public string GetMessage()
    {
        // Object creating inside business logic method.
        Employee emp = new Employee();

        string msg = _dal.GetMessage(emp);
        return msg;
    }
}
</code>```

Unit test:

```<code>[TestMethod]
    public void Is_GetMessage_Return_Proper_Result()
    {
        // Arrange.
        Employee emp = new Employee; // New object.

        Mock<IDal> mockDal = new Mock<IDal>();
        mockDal.Setup(d => d.GetMessage(emp)).Returns("Hello " + emp.Name);

        IBll bll = new Bll(mockDal.Object);

        // Act.

        // This will create another employee object inside the
        // business logic method, which is different from the
        // object which I have sent at the time of mocking.
        string msg = bll.GetMessage();

        // Assert.
        Assert.AreEqual("Hello arnab", msg);
    }
</code>```

In unit test case at the time of mocking I am sending an Employee object but when invoking the business logic method, it is creating different Employee object inside the method. That is why I can not mock the object.

In that case how to design so that I can solve the problem?


问:
Storing large data in HTTP Session (Java Application)
I am asking this question in continuation with http-session-or-database-approach.

I am planning to follow this approach.

When user add product to cart, create a Cart Model, add items to cart and save to DB.

Convert Cart model to cart data and save it to HTTP session.

Any update/ edit update underlying cart in DB and update data snap shot in Session.

When user click on view cart page, just pick cart data from Session and display to customer.

I have following queries regarding HTTP Session

How good is it to store large data (Shopping Cart) in Session?

How scalable this approach can be ? (With respect to Session)

Won't my application going to eat and demand a lot of memory?

Is my approach is fine or do i need to consider other points while designing this?

Though, we can control what all cart data should be stored in the Session, but still we need to have certain information in cart data being stored in session?

答:
I'm going to assume you are referring to the HttpSession object and not a J2EE Session bean object.

If you have just one server, then the Session is just like a sort of global Map that can be accessed whenever your user makes a request. Large objects or small objects, either way, they can be put in the map, but depending on how long you leave them there they can be problematic.

Most application servers remove sessions that have expired, so if you expect visitors to leave the site after a while, then perhaps you don't need to do any session maintenance and you can just let the sessions expire, and the application server will clean up after you.

However, if you expect that a lot of users will remain on the site for a long time, and could potentially have these long-lasting objects in their sessions, and you might not have enough memory to handle this, then you need some other approach.

The simplest approach might be to use some kind of LRU cache. You could, for example, use the commons LRUMap which lets you set a maximum size on the map and removes items that it no longer needs. This way, you can have a global cache for your large objects, and if you have too many users then the cache simply drops data. Performance suffers if there are a lot of cache misses, but at least everything still functions properly.

At the end of the day, if you don't have enough ram to cache stuff and enough database bandwidth to handle the misses, your app is going to crash no matter what tricks you use.

The drawbacks to using the HttpSession:

If you have multiple servers, it complicates fail-over or load balancing.

Sessions, if long-lived, can be a sort of memory leak, where data is cached there and never read or cleaned up.

Sessions are not shared per-user, so they are not useful as general-purpose caches.

Drawbacks to a global Map as a cache:

You have to clean up the data yourself, or use a third-party library which does the cleanup.

If you have multiple servers, users need to stay on the same server in order to benefit from the cache.

However unlike Sessions, if there is data that can be shared per-user, it's easy with a global map.


问:
WCF and object-oriented programming
I am building a program which would have WCF support. I am using the MVC pattern. For each controller there is a WCF service class. e.g. I have CTRL.CTRLBooking, WCF.IWCFBooking and WCF.WCFBooking.

For each controller (total of 10) there is a WCF class and an endpoint.

Is this a good approach or should I keep all the methods I provide in one single class e.g. WCF.WCFService (considering their count would be no more than 25-30)?

答:
The service contracts should not be very fine grated, this is avoid chatty operations but at the same time we should not try to group everything in one service contract, which may become hard to maintain, later on.

I think you should design WCF service contracts based on functionality e.g., all booking related operations can go in IWCFBooking contract and so forth. Then you can have each contract implemented in a seperate class.

It is not necessary to have one-to-one mapping between controllers and WCF service contracts. Service are supposed to be independent and reusable across many applications.

Title: WCF and object-oriented programming


问:
Where does UI fit in a Multi Agent system
tl;dr

How would I represent GUI as agents in a multi agent system.

I am learning more about Multi Agent Systems.

I like the concepts of such systems, it makes a lot of sense and it sounds very useful when I want to create a large system devised of smaller parts for the Web.

So, I created a basic Agent class, taught my agents to negotiate and communicate, created an environment for them to be situated in and such.

So, in a simple app attempt I have:

Several "InfoBroker" Agents that handles communications with server services, wanting to obtain information about the world and willing to share it under certain terms (They hold an auction if that matters).

A few agents that coordinate the communication between my services on the client side (Also "InfoBroker" agents I guess).

A few working agents, that have a simple goal in their environment, performing calculations and performing (very basic) means-end reasoning in the environment. They're my 'manual labor' in the app.

A few other things specific to my application.

That's all great, but I have no idea where GUI fits in all that? I need to show information about my system to the user, the GUI isn't a small part (consider agents that speak to the DOM in a web app). How would  represent GUI as an agent in a multi agent system?

Note: I've implemented this in JavaScript, but this seems more language agnostic to me.

答:
From my point of view there seem to be 3 major ways of integrating the GUI into this multi-agent environment. These largely depend on the purpose and scope of the UI:

Gui as system/service

Since you already mentioned that you have agents capable of communicating with external
services, the GUI could be simply one such service to whom agents deliver information and if necessary fetch their input to complete a job. The Gui is not involved in the computation which is useful as the presentation of the work cannot interfere with the actual work of the agents. Interaction is limited to the communication with the agents. On the other hand it only knows what agents are willing to share and when, this could narrow the view of the system. Another drawback is that the Gui would become rather reactive, acting more as a I/O buffer to the system than an integral part of it.

Gui as Agent

The Gui might have their own agents directly talking to other agents. Within the same logic as the existing InfoBrokers exist, Gui-agents could compete for data (e.g. aforementioned auctions). This would allow the Gui to investigate further and show the state of the accomplished work. It would give the user a way to be pro-active and feel more in control and up-to-date. The parameters and logic when and how information should be shown to the user is distinct of that how the actual work should be accomplished.

Especially when dealing with external services with high latency an agent might only report back to the UI when done with the work. Or it would have to know how to behave while the job is not complete. In addition the GUI could be an integral part of the agent environment. Using the goal oriented reasoning, data could be processed by different agents until it fits the format a Gui-agent requested.

Monitor (a.k.a. Petri-dish)

This way seems more suited when a direct observation of the whole environment is required. Each agent and the environment have Gui components which allow manipulatation of each part of the system directly and can display the state as a whole. Logging comes to mind aggregating all output into a global view at each moment. Initially I thought of this as an top-down view, but the more I think about it, it seems as an inside out view, where the user is free to poke and prod around.

Nothing prevents these concepts to be used in conjunction. In the end it all depends what level of interaction you require.

OwnerDisplayName: Benjamin Gruenbaum


问:
If we only know that a video is 720P, 480P or 240P can that unambiguously tell us of the resolution?
The main issue I have here is are the 720P, 480P, 240P... classes for defining video quality or do they unambiguously define the resolution of the video?

For example, the wikipedia article about 240P refers to a family of resolutions.

答: It is not safe to assume the horizontal resolution. My camera (Sony Nex6) films 1080P. However, it records AVCHD using 1980x1080 using square pixels and MP4 at 1440x1080 using rectangular pixels. </p>


问:
How to represent a geometric line programmatically?
I have been trying to design a library to do some simple geometric computations in an Euclidean space regardless of its dimension. While it is easy to represent points, vectors, hyperspheres and hyperplanes in a generic fashion, I am still unable to find a generic way to represent a (infinite) line, even though lines share properties across dimensions.

My best guess is that I could store some of the parameters of its parametric equation since it is easy to extend a parametric equation to a line in a space of any dimension:

```<code>x = x0 + at
y = y0 + bt
z = z0 + ct
// can be extended to any dimension
</code>```

But even with this equation, I can't find what should be stored and what should not be in order to compare lines. With an ideal solution, two objects of type Line:

would be programmatically equal (with operator==),

would have equal representations in the memory.

What should I store in order to achieve that?

答:
I think you're on the right track with your parametric equation.

What you have there is the vector form of the line equation.

```<code>L = R + tV
</code>```

Where R is [x0, y0, z0] and V is [a, b, c].

You just need to normalize your equations. You would do that by finding the value of R such that |R| is at a minimum, which occurs when R is perpendicular to V, or R.V = 0.

Also, since t can be scaled by any value, without changing the line, you should normalize V by dividing every coefficient by |V|

Body:
I think you're on the right track with your parametric equation.

What you have there is the vector form of the line equation.

L = R + tV

Where R is [x0, y0, z0] and V is [a, b, c].

You just need to normalize your equations. You would do that by finding the value of R such that |R| is at a minimum, which occurs when R is perpendicular to V, or R.V = 0.

Also, since t can be scaled by any value, without changing the line, you should normalize V by dividing every coefficient by |V|


答:
The strategy pattern is more than just a parent class calling subclass methods. It is a generalized solution to inject behavior into objects. The point of Strategy and SpecificStategy is that objects of this type are injected into a context, which then calls Strategy's execute(). In amon's anwer, the implementations of the Strategy classes only incidentally implement the pattern that is the subject of the original question. It is called the Template method pattern.

I don't know why the question has been downvoted, the OP has good reasons to doubt that the classical 'call super' principle is the natural one, and many coding style guides nowadays forbid the use of it by requiring that methods have to be either final or abstract.

Title: What are some examples of inverted classical inheritance?

Body:
Are there any examples of inheritance in languages where classes call their subclasses' methods rather than their super classes' methods?

It should not behave like traditional inheritance like the following.

```<code>Parent.method = function () {
    // Do things
}
Child.method = function () {
    // Do things
    super.method()
    // Do things
}
</code>```

It should instead behave like this.

```<code>Parent.method = function () {
    // Do things
    sub.method()
    // Do things
}
Child.method = function () {
    // Do things
}
</code>```

Does this pattern have a name?


问:
What if I have no good ideas to implement a feature?
I'm working on my own application and I'm stuck.  I have to implement a feature but I can't find a good approach to implement this feature.  I was thinking about it for a couple of days, and no good thoughts came. Searching the Internet didn't give me any inspiration.

I need to move on, but I want to know, what's the best:

Think more, wait more, and keep on searching for the best approach

Stop wasting time and start with poor design, covering everything with tests

What do you think? As I said before, I'm working on my own application. I don't have any deadlines, but I also want to finish coding the app asap.

答:
A few ideas:

Brainstorm
Write every stupid idea you have down (on paper or whiteboard). Cross the ones off that you're sure won't work. Keep writing. Include solutions to potentially related real-world problems. E.g., does mixing paint, or putting a nail in the wall, or changing your oil solve a real-world simile?

Ask for help
Google it, ask here, ask your geek friends, etc.

Solve a related problem
You can't solve the problem, but can you solve a much simpler one? Or an equally complex, related one? Do that. Then make small, individual changes to bring your solution closer to the desired solution.

Just start writing from the outside in
Regardless of whether your interface is a web service, web page, native form, camera, keyboard, monitor, or whatever, there's an interface. Write a few lines of code/pseudocode to make the interface work. Use magic methods that don't exist yet. Recursively do the same for each nonexistent magical method. Optimize later.


问:
Stacking keywords on top of each other - poor style?
I have always wondered about this, especially in C/Java style languages. For example, consider the first 3 lines of this C# code:

```<code>lock (serviceLock)
using (var client = new ServiceClient())
try
{
    // Do something
    client.DoSomething();
}

catch (System.ServiceModel.FaultException ex)
{
    // Handle error
    addLog(ex.ToString());
}
</code>```

This usage has always seemed somewhat questionable to me. However, the alternative is not very practical either (3+ levels deep of indentation for a service call). Apart from pure aesthetics, is there any practical reason to add or not to add the extra brackets in this case?

答:
I would strongly suggested you use three levels of nested indentation. When I look at this code quickly, I only see the catch(){} block, see a match try{} block, and ignore the fact that there is a lock and using statement. Now, when I look at the code more carefully, I noticed that there are keywords hanging out above the try, but their scope may not be immediately apparent to me--are they just for the try block, or are they for the try/catch statement? If you need to add code at some point, I can almost guarantee someone will miss the lock or using statements (the same reason why most coding standards I've seen prohibit placing only one line after an if statement and not using curly braces). I would go with the most specific code, which is three levels of indentation using proper brackets so that the scope is immediately understandable.

If the indentation bothers you that much, I suggest using 2 spaces instead of tabs (which should be an option in your IDE). It's something I picked up at my job, and have really fallen for as I use it. It's much more concise than having a two inch gap because you indented four times.


问:
DbFirst vs Code First? what should I use if I rely on Stored procedures
This question is asked many times, and I always prefer code-first as I like to keep the logic in code.

But now I have a challenge to load screen under 5 seconds and very little time to do things.
I have large set of records, and I'm possibly going to retrieve them asynchronously.
There are a few doubts in my mind.

Does using db-first approach have any benefits in performance over code-first?

Should I write the logic in stored procedures or in code (Linq)?

Which has less latency: Linq or stored procedures?

答:
I'm pretty sure there isn't any impact in dbfirst or code first performance, because when using db first you create your model with edmx, and when using code first you define your own model, think of it as:

database => model(database first)

model => database(code first)

If you don't want to keep your logic in code then the right way is to use stored procedure, but if you want to keep logic in your code then don't use stored procedure with linq.

linq is always slower, because well query is created on runtime


问:
Is it normal to write all logs into a single file?
Our teamlead said that many files much worse than a single, despite of we are working on a big project.

He argued that our customers could more easily send logs to us if there will be just a single file.

To understand our log-file he wants to develope our own log-analyzer which will analyze a single log-file separating it to many

答:
Please note that "best practice" questions are discouraged, because they are too easily answered as if there were a single way of doing something that is superior to all others. Almost always, there isn't such a way.

When deciding whether to use one log stream or different ones simultaneously, you have to weigh what the cost and benefit is in the expected use case. Writing everything to one stream is easy when programming, but makes for more effort when you have to retrieve or analyse logs. Pre-sorting all log output takes more effort when programing every log message but saves some effort when reading logs.

In the situations I'm familiar with, log messages are programmed more often than they are reported by customers or searched by support staff, so it makes sense to make the common case (developing) easy at the cost of more effort in the rarer case (troubleshooting). Analysing a log involves searching anyway, and searching a longer file is not much more effort than searching one of several shorter files because the computer does the main work, not your brain.

But that is just my project and my worldview. If (lucky you!) you have millions of customers and a huge traffic in support requests, then logs will be analysed much more often than they are written. In that case it makes sense to make reporting, analysing and correlating logs as easy as possible at the cost of making it more difficult to program a new log message. Then you should put more effort into making the reporting and analysis workflow efficient. (For instance, if customers have trouble gathering all relevant logs, it's a good idea to program log retrieval into your software so that the admin user need only press a button to send everything relevant.)


答:
My opinion is: never write code that just works! It should be very difficult to refactor in the future.

It's a really common approach for developers (and of course PMs or bosses). I heard a lot of time "just make it working" or "I'll fix later" (later when??? never!) but, I think that quality isn't something you cannot obtain in the middle of the project.

My suggestion is, stop thinking to your problem for a while.... do something other, and, sometime, the solutions just comes out himself.

Btw, asking to a colleague is absolutely a great way to solve your trouble.

Title: What if I have no good ideas to implement a feature?

Body:
I'm working on my own application and I'm stuck.  I have to implement a feature but I can't find a good approach to implement this feature.  I was thinking about it for a couple of days, and no good thoughts came. Searching the Internet didn't give me any inspiration.

I need to move on, but I want to know, what's the best:

Think more, wait more, and keep on searching for the best approach

Stop wasting time and start with poor design, covering everything with tests

What do you think? As I said before, I'm working on my own application. I don't have any deadlines, but I also want to finish coding the app asap.


答:
I think I would even prefer a logfile with everything in it.

My experience so far is that logfiles are especially useful for bugs where there is a problem in the communication between your subsystems. If they all log to the same file, it makes the problem easier to diagnose, because you can see the timeline of what is happening.

Also for customer specific performance issues, it is often helpful to be able to correlate what is happening in all subsystems at the same time of the problem.

Title: Is it normal to write all logs into a single file?

Body:
Our teamlead said that many files much worse than a single, despite of we are working on a big project.

He argued that our customers could more easily send logs to us if there will be just a single file.

To understand our log-file he wants to develope our own log-analyzer which will analyze a single log-file separating it to many


答:
I have no problem with stacking the locks and usings, but the try-catch should be wrapped in braces. That will require you to think what the scope of the using statement is in this context.

```<code>lock (serviceLock)
using (var client = new ServiceClient())
{
  try
  {
      client.DoSomething();
  }
  catch (System.ServiceModel.FaultException ex)
  {
      addLog(ex.ToString());
  }
}
</code>```

I stack keywords all the time (mostly using bit also stuff like fixed and unsafe) because sometimes I would be adding six or more braces. There's no way you can read that at a glance and tell which brace matches which. Also it increases the risk that the code for your method won't fit on the screen. That's not good for readability either.

Title: Stacking keywords on top of each other - poor style?

Body:
I have always wondered about this, especially in C/Java style languages. For example, consider the first 3 lines of this C# code:

```<code>lock (serviceLock)
using (var client = new ServiceClient())
try
{
    // Do something
    client.DoSomething();
}

catch (System.ServiceModel.FaultException ex)
{
    // Handle error
    addLog(ex.ToString());
}
</code>```

This usage has always seemed somewhat questionable to me. However, the alternative is not very practical either (3+ levels deep of indentation for a service call). Apart from pure aesthetics, is there any practical reason to add or not to add the extra brackets in this case?

Body:
I have no problem with stacking the locks and usings, but the try-catch should be wrapped in braces. That will require you to think what the scope of the using statement is in this context.

lock (serviceLock)
using (var client = new ServiceClient())
{
  try
  {
      client.DoSomething();
  }
  catch (System.ServiceModel.FaultException ex)
  {
      addLog(ex.ToString());
  }
}

I stack keywords all the time (mostly using bit also stuff like fixed and unsafe) because sometimes I would be adding six or more braces. There's no way you can read that at a glance and tell which brace matches which. Also it increases the risk that the code for your method won't fit on the screen. That's not good for readability either.


答: There's nothing wrong with going with the bad solution. Often times you just don't know enough about the problem domain at that point in time. Going with a bad solution let's you move on and learn more about the problem. Then you can still go back and refactor your first solution.</p>


答:
Lets assume you are talking about log files with the purpose of reproducing error scenarios happening at your customers site (which you did not describe). Lets assume the log files are to be analysed by you, not by the customer himself. And lets assume the log files don't grow to a size of several hundreds MB. Then your team lead is correct, one log file is probably easier to handle than many.

The situation changes if there are many completely different kinds of logs, and different users of your customer (with different roles) have to look directly into the log files by themselves, and each user needs to see different kind of informations. Then it would make more sense to split the logs thematically. If log file size matters, it may be a good idea to split the logs to time intervals (for example, one log for each day, week or month).

Whatever you do, it is always a good idea to make the log information filterable. That means, add machine-readable tags to each log entry, for example, which application or subsystem produced the entry, was it a warning, a severe error message or just a status information, and of course add the exact time stamp. That will help you to find the information you need afterwards much more easily even when you have them all in one file.

And its often unnecessary to develop your own log analyser - there are great free tools like the MS log parser which can query and filter your log files for you. For some scenarios you don't need much more than a decent spreadsheet.


答:
At a minimum, all you need to compare lines for equality is the parametric equation you already have.

Given lines L,M expressed as Dancrumb suggests:

```<code>L = X + tV
M = Y + tW
</code>```

then L == M if V and W are parallel (or equal if they're normalized to unit length and some "positive" direction), and Y=X+tV for some t.

To get memberwise equality, normalizing the vector length & direction is the first step, but you also need some rule to normalize the point. You could, for example, choose the point on your line which is closest to the origin, and use that.

Pseudo code for normalizing your vectors and points:

```<code>vec normalize_vec(vec v) {
  // 1. force unit length
  v = v/v.length();
  // 2. force positive direction
  for (int i = 0; i < v.dimension(); ++i) {
    if (v[i] < 0) {
      v = v * -1;
      break;
    }
    if (v[i] > 0)
      break;
    // keep going until the first nonzero element
  }
  return v;
}

point closest(point p, line l) {
  return (a-p).dot(l.vec) * l.vec;
}

line normalize_line(line l) {
  point new_pt = closest(point::origin, l);
  vec new_vec = normalize(l.vec);
  return line(new_pt, new_vec);
}
</code>```

Title: How to represent a geometric line programmatically?

Body:
I have been trying to design a library to do some simple geometric computations in an Euclidean space regardless of its dimension. While it is easy to represent points, vectors, hyperspheres and hyperplanes in a generic fashion, I am still unable to find a generic way to represent a (infinite) line, even though lines share properties across dimensions.

My best guess is that I could store some of the parameters of its parametric equation since it is easy to extend a parametric equation to a line in a space of any dimension:

```<code>x = x0 + at
y = y0 + bt
z = z0 + ct
// can be extended to any dimension
</code>```

But even with this equation, I can't find what should be stored and what should not be in order to compare lines. With an ideal solution, two objects of type Line:

would be programmatically equal (with operator==),

would have equal representations in the memory.

What should I store in order to achieve that?

Body:
At a minimum, all you need to compare lines for equality is the parametric equation you already have.

Given lines L,M expressed as Dancrumb suggests:

L = X + tV
M = Y + tW

then L == M if V and W are parallel (or equal if they're normalized to unit length and some "positive" direction), and Y=X+tV for some t.

To get memberwise equality, normalizing the vector length & direction is the first step, but you also need some rule to normalize the point. You could, for example, choose the point on your line which is closest to the origin, and use that.

Pseudo code for normalizing your vectors and points:

vec normalize_vec(vec v) {
  // 1. force unit length
  v = v/v.length();
  // 2. force positive direction
  for (int i = 0; i < v.dimension(); ++i) {
    if (v[i] < 0) {
      v = v * -1;
      break;
    }
    if (v[i] > 0)
      break;
    // keep going until the first nonzero element
  }
  return v;
}

point closest(point p, line l) {
  return (a-p).dot(l.vec) * l.vec;
}

line normalize_line(line l) {
  point new_pt = closest(point::origin, l);
  vec new_vec = normalize(l.vec);
  return line(new_pt, new_vec);
}


问:
Entity Framework Entities - Some Data From Web Service - Best Architecture?
We are currently using Entity Framework as an ORM across a few web applications, and until now, it has suited us well as all our data is stored in a single database. We are using the repository pattern, and have services (the domain layer) which use these, and return the EF entities directly to the ASP.NET MVC controllers.

However, a requirement has come up to utilise a 3rd party API (through a web service) which will give us extra information that relates to the user in our database. In our local User database, we will store an external ID which we can provide the to API to get additional information. There is quite a bit of information available, but for the sake of simplicity, one of them relates to the user's company (name, manager, room, job title, location etc). This information will be used in various places throughout our web apps - as opposed to being used in a single place.

So my question is, where is the best place to populate and access this information? As it is used in various places, it's not really sensible to fetch it on an ad-hoc basis wherever we use in the web application - so it makes sense to return this additional data from the domain layer.

My initial thought was just to create a wrapper model class which would contain the EF entity (EFUser), and a new 'ApiUser' class containing the new information - and when we get a user, we get the EFUser, and then get the additional info from the API, and populate the ApiUser object. However, whilst this would be fine for getting single users, it falls over when getting multiple users. We can't hit the API when getting a list of users.

My second thought was just to add a singleton method to the EFUser entity which returns the ApiUser, and just populate it when needed. This solves the above problem as we only access it when we need it.

Or the final thought was to keep a local copy of the data in our database, and synchronise it with the API when the user logs in. This is minimal work as it's just a synchronisation process - and we don't have the overhead of hitting the DB and API every time we want to get user information. However, these means storing the data in two places, and also means the data is out of date for any user that hasn't logged in for a while.

Does anyone have any advice or suggestions on how best to handle this kind of scenario?

答:
One idea is to modify ApiUser to not always have the extra info. Instead, you put a method on ApiUser to fetch it:

```<code>ApiUser apiUser = backend.load($id);
//Locally available data directly on the ApiUser like so:
String name = apiUser.getName();
//Expensive extra data available after extra call:
UserExtraData extraData = apiUser.fetchExtraData();
String managerName = extraData.getManagerName();
</code>```

You could also modify this slightly to use lazy loading of extra data, so that you don't have to extract UserExtraData from the ApiUser object:

```<code>//Extra data fetched on first get:
String managerName = apiUser.lazyGetExtraData().getManagerName();
</code>```

This way, when you have a list, the extra data won't be fetched by default. But you can still access it while traversing the list!

Body:
One idea is to modify ApiUser to not always have the extra info. Instead, you put a method on ApiUser to fetch it:

ApiUser apiUser = backend.load($id);
//Locally available data directly on the ApiUser like so:
String name = apiUser.getName();
//Expensive extra data available after extra call:
UserExtraData extraData = apiUser.fetchExtraData();
String managerName = extraData.getManagerName();

You could also modify this slightly to use lazy loading of extra data, so that you don't have to extract UserExtraData from the ApiUser object:

//Extra data fetched on first get:
String managerName = apiUser.lazyGetExtraData().getManagerName();

This way, when you have a list, the extra data won't be fetched by default. But you can still access it while traversing the list!


问:
which pattern to use - if at all
I am fairly new to using patterns and although I understand some of them to a point  I find it difficult to work out which one(s) to use in a particular situation.

I am trying to wrap up an existing db schema into a number of objects and am not sure if I should simply be using inheritance or a mixture some patterns

I have an options table, holding the base properties for an item thus:

```<code>id
type
code
name
</code>```

These options also has availability - stored in another table

```<code>id (from option table)
fromdate
todate
</code>```

and prices in another table

```<code>id (from option table)
validfrom
fromdate
todate
price
</code>```

and lastly a booked table this time keyed on the option id and the person who has booked it

```<code>id (from option table)
personid
bookedPrice
</code>```

Just to add more into the mix, there are also a couple of particular option types which have additional properties that are unique to them.
Thinking maybe I should use inheritance for the most part - as the price/availability bits are used for ALL option types and then decorate the unique options with these extra bits in those particular cases.

So in different circumstances this data will need to be loaded into various objects
I wonder if its best to inherit from the base option - making an AvailabilityOption and a PricedOption etc and extending the base option like that
or decorating the base option with the extended properties.

Not sure if there is enough information here to answer that.
I wonder if someone could explain the benefits and pitfalls of each so I don't end up getting myself into a cul de sac?

答:
Never use a pattern when you are unsure whether to use it.

Design patterns are codifications of things that advanced practitioners have done often, and finally published under a canonical name. They are often useful to solve a recurring problem, but only if that is in fact the problem you are having. If you're not sure whether that is the case, implementing a pattern increases the difficulty of your work, because in addition to getting the details of your requirements right, you also have to get the details of the pattern right.

Applying pattern can make work easier, but in my opinion that only happens when you have already understood the pattern (not necessarily as well as its author, but certainly well enough that you could recreate the published description of problem/forces/solution/class structure etc. without having to look it up). Usually this is because you have also solved or at least encountered the same problem as the original author before. Then, when you read the pattern description and realise that it solves exactly the problem you're having, it is relatively easy to apply it, and (in my opinion) it then becomes quite easy to recognize other problems that call for exactly this pattern.

In other words, I think profiting from patters requires that you go through the same process of learning by doing, recognizing and mentally "bundling" the solution into a recognizable element of your thinking as the inventor did. Simply copying a class structure from a book and calling it a "Bridge" or whatever has little value except as quick documentation for others who will read your code.

Title: which pattern to use - if at all


答:
When you have to access a data model which was not designed with some object- or inheritance structure in mind, IMHO it is best to avoid any artifical "objectification" afterwards. The risk is high that with the next version of the DB model, the changes will collide with the object structure you have added. Even without a change of the DB schema, the real-world data may not conform to the additional constraints your class hierarchy induces on the system.

So keep it simple and stupid and create one class per table, one attribute per db column, avoid to use inheritance and try how far you can get with this approach.

Things are quite different when the DB design was made from class model, with an ORM in mind. Then the documentation of the ORM should suggest how the mapping from tables to classes may be and which options you have.

Title: which pattern to use - if at all

Body:
I am fairly new to using patterns and although I understand some of them to a point  I find it difficult to work out which one(s) to use in a particular situation.

I am trying to wrap up an existing db schema into a number of objects and am not sure if I should simply be using inheritance or a mixture some patterns

I have an options table, holding the base properties for an item thus:

```<code>id
type
code
name
</code>```

These options also has availability - stored in another table

```<code>id (from option table)
fromdate
todate
</code>```

and prices in another table

```<code>id (from option table)
validfrom
fromdate
todate
price
</code>```

and lastly a booked table this time keyed on the option id and the person who has booked it

```<code>id (from option table)
personid
bookedPrice
</code>```

Just to add more into the mix, there are also a couple of particular option types which have additional properties that are unique to them.
Thinking maybe I should use inheritance for the most part - as the price/availability bits are used for ALL option types and then decorate the unique options with these extra bits in those particular cases.

So in different circumstances this data will need to be loaded into various objects
I wonder if its best to inherit from the base option - making an AvailabilityOption and a PricedOption etc and extending the base option like that
or decorating the base option with the extended properties.

Not sure if there is enough information here to answer that.
I wonder if someone could explain the benefits and pitfalls of each so I don't end up getting myself into a cul de sac?


答:
I'd say I'm against it. I'll come around and add some code after try...catch without noticing that I should have extended the scope of lock.

And, more importantly, this version doesn't really reduce indentation!

It only hides it. Deep nesting is primarily a logical problem, not an aesthetical one.

The fact that we see it as ugly is a result of it being a bad programming practice; not the other way round.

(Aesthetics by itself is relative - eg. this highly upvoted answer claims that "deeply nested structural statements – "arrowheads" – were, in languages like Pascal, once seen as beautiful code.")

Three levels is still fine, but if you reach - say - seven levels, does removing braces from lock and using, and de-indenting, address the issue really?

Quite the contrary, it desensitizes the developer to the problem, thus reducing the chance someone will go ahead and refactor the thing.


问:
Efficient solution for dictionary updates
Let's start with the problem:

There is a large dictionary X that contains {key, value} pairs, i.e.:

```<code>X = [{100, 10}, {101, 0}, {103, 0}, {106, 2}, {110, 1}]
</code>```

Every t seconds, X has to be updated with values from sub dictionary U and 0 set to each value for a key that is not present in new updated U, but was in the previous update.

The most important requirements is, that an update has to be performed in such a way, that the minimum number of update operations of each {key, value} pair in dictionary X have been performed, ie.

X updated by U where

```<code>U = [{100, 10}, {102, 5}, {103, 0}, {105, 1}, {110, 0}]
</code>```

would become:

```<code>X = [{100, 10}, {101, 0}, {102, 5}, {103, 0}, {105, 1}, {106, 2}, {110, 0}]
</code>```

but only following pairs have been updated/added in X:

```<code>{102, 5}
{105, 1}
{110, 0}
</code>```

To make things a bit more interesting, there are few constraints:

it is very costly to iterate over dictionary X. Assume X is very large.

it is very costly to make an update to {key, value} pair so the task is to minimize this cost.

So that was the problem stated. Here is my solution:

First idea I had was to save the dictionary U after updating X.
On the next update I take each key from Uprev and set it to 0 in X.

```<code>foreach (var pair in Uprev)
{
    X[pair.Key] = 0;
}
</code>```

After this has been done, I would do a loop to set new values for keys present in new dictionary U:

```<code>foreach (var pair in U)
{
    if (X.ContainsKey(pair.Key))
       X[pair.Key] = pair.Value;
    else
       X.Add(pair.Key, pair.Value);
}
</code>```

So ... the question: is there a better solution for the problem I described above? Is it possible to better manage the updates?
Any ideas are welcome, so feel free to post anything that comes to mind.

Thank you for contribution

答:
Instead of

```<code>foreach (var pair in U)
{
    if (X.ContainsKey(pair.Key))
       X[pair.Key] = pair.Value;
    else
       X.Add(pair.Key, pair.Value);
}
</code>```

use

```<code>foreach (var pair in U)
{
     X[pair.Key] = pair.Value;
}
</code>```

(the index operator [] works like Add when the key does not exist so far). This saves you from one unneccessary dictionary lookup. Beyond that, I would not expect big improvements, since it is obvious that you must visit each element of U once, and your algorithm does that just twice, not more.

Body:
Instead of

foreach (var pair in U)
{
    if (X.ContainsKey(pair.Key))
       X[pair.Key] = pair.Value;
    else
       X.Add(pair.Key, pair.Value);
}

use

foreach (var pair in U)
{
     X[pair.Key] = pair.Value;
}

(the index operator [] works like Add when the key does not exist so far). This saves you from one unneccessary dictionary lookup. Beyond that, I would not expect big improvements, since it is obvious that you must visit each element of U once, and your algorithm does that just twice, not more.