问:
Member: Use unique IDs vs domain object
After a couple of useful answers on whether I should use domain object or a unique id as method/function parameter here Identifier vs domain object as a method parameter , I have a similar question re: members (the previous questions discussion didn't manage to cover this).
What are the pros and cons of using unique IDs as member vs object as member. I'm asking in reference to strongly typed languages, like Scala/C#/Java. Should I have
(1)

```<code>User( id: Int, CurrentlyReadingBooksId: List[Int])
Book( id: Int, LoanedToId: Int )
</code>```

or (2), preferred to (1) After going through: Should we define types for everything?

```<code>User( id: UserId, CurrentlyReadingBooksId: List[ BookId] )
Book( id: BookId, LoanedToId: UserId )
</code>```

or (3)

```<code>User( id: Int, CurrentlyReadingBooks: List[Book])
Book( id: Int, LoanedTo: User)
</code>```

While I cannot think of benefits to having the object (3), one benefits to having IDs (2) & (1) is that when I am creating the User object from DB, I don't have to create the Book object, which may in turn depend on the User object itself, creating an endless chain. Is there a generic solution to this problem for both RDBMS and No-SQL (if they are different)?

Based on some answers so far, rephrasing my question: (with use of IDs supposed to be in wrapped types)
1) Always use IDs?
2) Always use Objects?
3) Use IDs when there is a risk of recursion in serializing and deserializing, but use objects otherwise?
4) Anything else?

EDIT: If you answer that Objects should be used always or for some cases, please make sure to answer the biggest concern other answerers have posted => How to get data from DB

答:
Domain Objects as ids create some complex/subtle problems:

Serialization/Deserialization

If you store objects as keys it will make serializing the object graph extremely complicated. You will get stackoverflow errors when doing a naive serialization to JSON or XML because of the recursion. You will then have to write a custom serializer that converts the actual objects to use their ids instead of serializing the object instance and creating the recursion.

Pass in objects for type safety but only store ids, then you can have an accessor method that lazy loads the related entity when it is called. Second level caching will take care of subsequent calls.

Subtle reference leaks:

If you use domain objects in constructors like you have there you will create circular references that will be very difficult to allow memory to be reclaimed for objects not being actively used.

Ideal Situation:

Opaque ids vs int/long:

An id should be a completely opaque identifier that carries no information about what it identifies. But it should offer some verification that it is a valid identifier in its system.

Raw types break this:

int,long and String are the most commonly used raw types for identifiers in RDBMS system. There is a long history of practical reasons that date back decades and they all are compromises that either fit into saving space or saving time or both.

Sequential  ids are the worst offenders:

When you use a sequential id you are packing temporal semantic information into the id by default. Which is not bad until it is used. When people start writing business logic that sorts or filters on the semantic quality of the id, then they are setting up a world of pain for future maintainers.

String fields are problematic because naive designers will pack information into the contents, usually temporal semantics as well.

These make it is impossible to create a distributed data system as well, because 12437379123 is not unique globally. The chances that another node in a distributed system will create a record with the same number is pretty much guaranteed when you get enough data in a system.

Then hacks begin to work around it and the entire thing devolves into a pile of steaming mess.

Ignoring huge distributed systems ( clusters ) it becomes a complete nightmare when you start trying to share the data with other systems as well. Especially when the other system is not under your control.

You end up with the exact same problem, how to make your id globally unique.

UUID was created and standardized for a reason:

UUID can suffer from all the problems listed above depending on which Version you use.

Version 1 uses a MAC address and time to create a unique id. This is bad because it carries semantic information about location and time. That is not in itself a problem, it is when naive developers start relying on that information for business logic. This also leaks information which could be exploited in any intrusion attempts.

Version 2 uses a users UID or GID and domian UID or GUI in place of the time from Version 1 this is just as bad as Version 1 for data leakage and risking this information to be used in business logic.

Version 3 is similar but replaces the MAC address and time with a MD5 hash of some array of byte[] from something that definitely has semantic meaning. There is no data leakage to worry about, the byte[] can not be recovered from the UUID. This gives you a good way to deterministically create UUID instances form and external key of some sort.

Version 4 is based only on random numbers which is a good solution, it carries absolutely no semantic information, but it is not deterministically re-creatable.

Version 5 is just like Version 4 but uses sha1 instead of md5.

Domain Keys and Transactional Data Keys

My preference for domain object ids, is to use Version 5 or Version 3 if restricted from using Version 5 for some technical reason.

Version 3 is great for transaction data that might be spread across many machines.

Unless you are constrained by space use a UUID:

They are guaranteed unique, dumping data from one database and reloading into another you never had to worry about duplicate ids that actually reference different domain data.

Version 3,4,5 are completely opaque and that is they way the should be.

You can have a single column as the primary key with a UUID and then you can have compound unique indexes for what would have been a natural composite primary key.

Storage does not have to be CHAR(36) either. You can store the UUID in a native byte/bit/number field for a given database as long as it is still indexable.

Legacy

If you have raw types and can not change them, you can still abstract them away in your code.

Using a Version 3/5 of UUID you can pass in the Class.getName() + String.valueOf(int) as a byte[] and have a opaque reference key that is recreatable and deterministic.

Title: Member: Use unique IDs vs domain object


问:
Parameters are passed by value, but editing them will edit the actual object (like passed by reference)?
I've just discovered a huge hole in my Java knowledge. I knew that Java passes parameters by value. I thought I understand that and whenever I needed to edit the field object of a class, I create a field. For example,

```<code>private int mNumber;

void main(){
   mNumber = 1;
}

void otherMethod(){
   mNumber = 3;
}
</code>```

This would change the field object, everyone's happy.

I was debugging and had to review the classes inside Android SDK and I noticed this piece of code

```<code>public static String dumpCursorToString(Cursor cursor) {
    StringBuilder sb = new StringBuilder();
    dumpCursor(cursor, sb);
    return sb.toString();
}

public static void dumpCursor(Cursor cursor, StringBuilder sb) {
    sb.append(">>>>> Dumping cursor " + cursor + "\n");
    if (cursor != null) {
        int startPos = cursor.getPosition();
        cursor.moveToPosition(-1);
        while (cursor.moveToNext()) {
            dumpCurrentRow(cursor, sb);
        }
        cursor.moveToPosition(startPos);
    }
    sb.append("<<<<<\n");
}
</code>```

The are changing the local variable sb by passing it as a parameter to another method.

In my case, sb would be a field and I would change it from another method.

How is this possible? Is a reference (pointer) passed as a parameter so we are ALWAYS changing the source value (just like we pass it by reference in other languages)? Was my approach with field unnecessary all this time?

So my approach could be easily changed to

```<code>void main(){
   int number = 1;
   otherMethod(number)
}

void otherMethod(int number){
   number = 3;
}
</code>```

Don't be angry at me if this sound like a beginner question. It may actually be, but I have just discovered a huge hole in my Java knowledge.

答:
The statement that "java is always pass-by-value" is technically correct, but it can be very misleading, because as you have just witnessed, when you pass an object to a function, the function can modify the contents of the object, so it appears that the object has been passed by reference, and not by value.  So, what is happening?

Pointers.  That's what's happening.

One of the major selling points of Java was that "it is a safe language because it is free of pointers".

This statement is true in the sense that you cannot do most of the unsafe things like pointer arithmetic that have historically been the cause of many a monstrous bug in languages like C and C++.  However, this statement has also hindered the understanding of java for many a novice programmer.

You see, java is actually full of pointers; Novice programmers only begin to make sense out of the language once they realize that in java everything which is not a primitive is in fact a pointer;  pointers are everywhere;  you cannot declare an object statically, or on the stack, or as a element of an array as you can do in C++; the only way to declare and use an object is by pointer; even arrays of objects are in fact nothing but arrays of pointers to objects; everything that looks like an object in java is never really an object, it is always a pointer to an object.

Java makes a clear distinction between primitives and objects. Primitives, (int, boolean, float, etc.,) also known as value types, are always passed by value, and they behave precisely as you would expect according to the "java is always pass-by-value" maxim.

Objects, on the other hand, also known as reference types, are always accessed by reference, that is, via a pointer, so their behavior is a bit trickier.  When you call a method passing an object to it, java does not really pass the object itself; it passes a pointer to it.  This pointer is passed by value, so the maxim "java is always pass-by-value" still holds from a strictly technical perspective. If you set this pointer to null within the method, the pointer held by the caller is unaffected, so obviously, what you have inside the method is a copy of the pointer. But if you modify the object pointed by the pointer, the caller will always see these modifications, which means that both the caller and the callee are holding references to the exact same object.

So, the statement "java is always pass-by-value" is true from a strictly technical, but ultimately not very useful point of view, according to which objects are never really passed anywhere, only pointers to the objects are passed.

In reality, when you write code, when you think what the code does, it is very useful to think of objects as being passed to functions, and since java passes pointers (by value) under the hood, the objects themselves always appear to be passed by reference.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


答:
In short, you are confusing reassigning a local variable with modifying a shared object. sb.append() does not modify the variable sb, it modifies the object that the variable references. But number = 3 modifies the variable number by assigning it a new value. Objects are shared across method calls, but local variables are not. Therefore assigning a local variable a new value will not have any effect outside the method, but modifying an object will. A bit simplified: if you use a dot (.), you are modifying an object, not a local variable.

You confusion is probably due to confusing terminology. "Reference" means two different things in different context.

1) When talking about Java objects and variables, a reference is a "handle" to an object. Strictly speaking, a variable cannot hold an object, it holds a reference to an object. References can be copied, so two variables can get a reference to the same object. E.g.

```<code>StringBuilder a = new StringBuilder();
StringBuilder b = a; // a and b now references the same object
a.writeLine("Hello"); // modify the shared object
b.toString() // -> "Hello"
</code>```

When an objects is passed into a method as a parameter, it is also the reference that is copied, so the called method can modify the same object. This is also called "Call by sharing".

```<code>void main(){
   String builder b = new StringBuilder();
   otherMethod(b);
   b.toString(); // --> "Hello" because the shared object is modified
}

void otherMethod(StringBuilder b){
   b.write("Hello"); // modify the shared object
}
</code>```

But the otherMethod can only modify the shared object, it cannot modify any local variables in the calling method. If the called function assigns a new value to its own parameters, it doesn't affect the calling function.

```<code>void main(){
   String builder b = new StringBuilder();
   b.writeLine("Hello");
   otherMethod(b);
   b.toString(); // --> "Hello" because the shared object is NOT modified
}

void otherMethod(StringBuilder b){
   b = new StringBuilder(); // assign a new object to b
   b.write("Goodbye"); // modify the new object
}
</code>```

So you have to be clear on the distinction between modifying a shared object (through modifying fields or calling method on the object) and assigning a new value to a local variable or parameter.

2) When talking evaluation strategy (how parameters are passed into function) in general computer language theory, call-by-reference and call-by-value means something quite different.

Call-by-value, which Java supports, means that values from arguments are copied into parameters when calling methods. The value can be a reference, which is why the called function will get a reference to the shared object. Confusingly Java is said to "pass references by value", which is quite distinct from call-by-reference.

If a language supports call-by-reference, a function can change the value of a local variable in the calling function. Java does not support this, which is shown by the example above. Call-by-reference means the called function gets a reference to the local variable used as argument in the call. This notion is completely foreign to Java, where we simply do not have the concept of a reference to a local variable. We only have references to objects, never to local variables.

To show how call-by-reference works, we can look at C# which do support call-by-reference with the ref modifier:

```<code>void main(){
   String builder b = new StringBuilder();
   b.writeLine("Hello");
   otherMethod(ref b);
   b.toString(); // --> "Goodbye" because otherMethod changed b to point to the new object
}

void otherMethod(ref StringBuilder b){
   b = new StringBuilder(); // assign a new object to b
   b.write("Goodbye"); // modify the new object
}
</code>```

Here otherMethod() actually modifies the local variable b in main().

So what about primitives like integers, booleans etc.? These are immutable which means they cannot be modified like objects can. Since they cannot be modified, the question if they are shared or not is moot, since there is no observable difference whether they are shared or copied.

Note: I didn't invent the terminology, so don't blame the messenger. I much prefer the terms call-by-sharing or call-by-object which is more intuitive for Java, but the fact remains that the terms call-by-value and call-by-reference is established terminology, and the Java specification itself uses the term call-by-value.

Title: Parameters are passed by value, but editing them will edit the actual object (like passed by reference)?

Body:
I've just discovered a huge hole in my Java knowledge. I knew that Java passes parameters by value. I thought I understand that and whenever I needed to edit the field object of a class, I create a field. For example,

```<code>private int mNumber;

void main(){
   mNumber = 1;
}

void otherMethod(){
   mNumber = 3;
}
</code>```

This would change the field object, everyone's happy.

I was debugging and had to review the classes inside Android SDK and I noticed this piece of code

```<code>public static String dumpCursorToString(Cursor cursor) {
    StringBuilder sb = new StringBuilder();
    dumpCursor(cursor, sb);
    return sb.toString();
}

public static void dumpCursor(Cursor cursor, StringBuilder sb) {
    sb.append(">>>>> Dumping cursor " + cursor + "\n");
    if (cursor != null) {
        int startPos = cursor.getPosition();
        cursor.moveToPosition(-1);
        while (cursor.moveToNext()) {
            dumpCurrentRow(cursor, sb);
        }
        cursor.moveToPosition(startPos);
    }
    sb.append("<<<<<\n");
}
</code>```

The are changing the local variable sb by passing it as a parameter to another method.

In my case, sb would be a field and I would change it from another method.

How is this possible? Is a reference (pointer) passed as a parameter so we are ALWAYS changing the source value (just like we pass it by reference in other languages)? Was my approach with field unnecessary all this time?

So my approach could be easily changed to

```<code>void main(){
   int number = 1;
   otherMethod(number)
}

void otherMethod(int number){
   number = 3;
}
</code>```

Don't be angry at me if this sound like a beginner question. It may actually be, but I have just discovered a huge hole in my Java knowledge.

Body:
In short, you are confusing reassigning a local variable with modifying a shared object. sb.append() does not modify the variable sb, it modifies the object that the variable references. But number = 3 modifies the variable number by assigning it a new value. Objects are shared across method calls, but local variables are not. Therefore assigning a local variable a new value will not have any effect outside the method, but modifying an object will. A bit simplified: if you use a dot (.), you are modifying an object, not a local variable.

You confusion is probably due to confusing terminology. "Reference" means two different things in different context.

1) When talking about Java objects and variables, a reference is a "handle" to an object. Strictly speaking, a variable cannot hold an object, it holds a reference to an object. References can be copied, so two variables can get a reference to the same object. E.g.

StringBuilder a = new StringBuilder();
StringBuilder b = a; // a and b now references the same object
a.writeLine("Hello"); // modify the shared object
b.toString() // -> "Hello"

When an objects is passed into a method as a parameter, it is also the reference that is copied, so the called method can modify the same object. This is also called "Call by sharing".

void main(){
   String builder b = new StringBuilder();
   otherMethod(b);
   b.toString(); // --> "Hello" because the shared object is modified
}

void otherMethod(StringBuilder b){
   b.write("Hello"); // modify the shared object
}

But the otherMethod can only modify the shared object, it cannot modify any local variables in the calling method. If the called function assigns a new value to its own parameters, it doesn't affect the calling function.

void main(){
   String builder b = new StringBuilder();
   b.writeLine("Hello");
   otherMethod(b);
   b.toString(); // --> "Hello" because the shared object is NOT modified
}

void otherMethod(StringBuilder b){
   b = new StringBuilder(); // assign a new object to b
   b.write("Goodbye"); // modify the new object
}

So you have to be clear on the distinction between modifying a shared object (through modifying fields or calling method on the object) and assigning a new value to a local variable or parameter.

2) When talking evaluation strategy (how parameters are passed into function) in general computer language theory, call-by-reference and call-by-value means something quite different.

Call-by-value, which Java supports, means that values from arguments are copied into parameters when calling methods. The value can be a reference, which is why the called function will get a reference to the shared object. Confusingly Java is said to "pass references by value", which is quite distinct from call-by-reference.

If a language supports call-by-reference, a function can change the value of a local variable in the calling function. Java does not support this, which is shown by the example above. Call-by-reference means the called function gets a reference to the local variable used as argument in the call. This notion is completely foreign to Java, where we simply do not have the concept of a reference to a local variable. We only have references to objects, never to local variables.

To show how call-by-reference works, we can look at C# which do support call-by-reference with the ref modifier:

void main(){
   String builder b = new StringBuilder();
   b.writeLine("Hello");
   otherMethod(ref b);
   b.toString(); // --> "Goodbye" because otherMethod changed b to point to the new object
}

void otherMethod(ref StringBuilder b){
   b = new StringBuilder(); // assign a new object to b
   b.write("Goodbye"); // modify the new object
}

Here otherMethod() actually modifies the local variable b in main().

So what about primitives like integers, booleans etc.? These are immutable which means they cannot be modified like objects can. Since they cannot be modified, the question if they are shared or not is moot, since there is no observable difference whether they are shared or copied.

Note: I didn't invent the terminology, so don't blame the messenger. I much prefer the terms call-by-sharing or call-by-object which is more intuitive for Java, but the fact remains that the terms call-by-value and call-by-reference is established terminology, and the Java specification itself uses the term call-by-value.


问:
Why would a program use a closure?
After reading many posts explaining closures here I'm still missing a key concept: Why write a closure?  What specific task would a programmer be performing that might be best served by a closure?

Examples of closures in Swift are accesses of an NSUrl and using the reverse geocoder. Here is one such example. Unfortunately, those courses just present the closure; they do not explain why the code solution is written as a closure.

An example of a real world programming problem that might trigger my brain to say, "aha, I should write a closure for this", would be more informative than a theoretical discussion.  There is no shortage of theoretical discussions available on this site.

答:
Nothing that hasn't been said already, but maybe a simpler example.

Here's a JavaScript example using timeouts:

```<code>// Example function that logs something to the browser's console after a given delay
function delayedLog(message, delay) {
  // this function will be called when the timer runs out
  var fire = function () {
    console.log(message); // closure magic!
  };

  // set a timeout that'll call fire() after a delay
  setTimeout(fire, delay);
}
</code>```

What happens here, is that when delayedLog() is called, it returns immediately after setting the timeout, and the timeout keeps ticking down in the background.

But when the timeout runs out and calls the fire() function, the console will display the message that was originally passed to delayedLog(), because it is still available to fire() via closure. You can call delayedLog() as much as you want, with a different message and delay each time, and it'll do the right thing.

But let's imagine JavaScript doesn't have closures.

One way would be to make setTimeout() blocking - more like a "sleep" function - so delayedLog()'s scope does not go away until the timeout has run out. But blocking everything isn't very nice.

Another way would be to put the message variable in some other scope that'll be accessible after delayedLog()'s scope is gone.

You could use global - or at least "broader scoped" - variables, but you'd have to figure out how to keep track of what message goes with what timeout. But it can't just be a sequential, FIFO queue, because you can set any delay you want. So it might be "first in, third out" or something. So you'd need some other means to tying a timed function to variables it needs.

You could instantiate a timeout object that "groups" the timer with the message. An object's context is more or less a scope that sticks around. Then you'd have the timer execute in the object's context, so it'd have access to the right message. But you'd have to store that object because without any references it'd get garbage collected (without closures, there'd be no implicit references to it either). And you'd have to remove the object once it's fired its timeout, otherwise it'll just stick around. So you'd need some sort of list of timeout objects, and periodically check it for "spent" objects to remove - or the objects would add and remove themselves from the list, and...

So... yeah, this is getting dull.

Thankfully, you don't have to use a broader scope, or wrangle objects just to keep certain variables around. Because JavaScript has closures, you already have exactly the scope your need. A scope that gives you access to the message variable when you need it. And because of that, you can get away with writing delayedLog() like above.

Title: Why would a program use a closure?

Body:
Nothing that hasn't been said already, but maybe a simpler example.

Here's a JavaScript example using timeouts:

// Example function that logs something to the browser's console after a given delay
function delayedLog(message, delay) {
  // this function will be called when the timer runs out
  var fire = function () {
    console.log(message); // closure magic!
  };

  // set a timeout that'll call fire() after a delay
  setTimeout(fire, delay);
}

What happens here, is that when delayedLog() is called, it returns immediately after setting the timeout, and the timeout keeps ticking down in the background.

But when the timeout runs out and calls the fire() function, the console will display the message that was originally passed to delayedLog(), because it is still available to fire() via closure. You can call delayedLog() as much as you want, with a different message and delay each time, and it'll do the right thing.

But let's imagine JavaScript doesn't have closures.

One way would be to make setTimeout() blocking - more like a "sleep" function - so delayedLog()'s scope does not go away until the timeout has run out. But blocking everything isn't very nice.

Another way would be to put the message variable in some other scope that'll be accessible after delayedLog()'s scope is gone.

You could use global - or at least "broader scoped" - variables, but you'd have to figure out how to keep track of what message goes with what timeout. But it can't just be a sequential, FIFO queue, because you can set any delay you want. So it might be "first in, third out" or something. So you'd need some other means to tying a timed function to variables it needs.

You could instantiate a timeout object that "groups" the timer with the message. An object's context is more or less a scope that sticks around. Then you'd have the timer execute in the object's context, so it'd have access to the right message. But you'd have to store that object because without any references it'd get garbage collected (without closures, there'd be no implicit references to it either). And you'd have to remove the object once it's fired its timeout, otherwise it'll just stick around. So you'd need some sort of list of timeout objects, and periodically check it for "spent" objects to remove - or the objects would add and remove themselves from the list, and...

So... yeah, this is getting dull.

Thankfully, you don't have to use a broader scope, or wrangle objects just to keep certain variables around. Because JavaScript has closures, you already have exactly the scope your need. A scope that gives you access to the message variable when you need it. And because of that, you can get away with writing delayedLog() like above.


问:
Lazy loaded property signatures in business objects
Let's say I am designing business objects around a poorly optimized database that have no ability to change.

I have a Person object with a ShippingAddress property. The ShippingAddress is very expensive to load and located in a separate table, and a minority of pages use it. There are times when thousands of Person objects need to be loaded on a single page so eating the performance hit is not an option. This makes lazy loading the ShippingAddress ideal for this situation.

However, from a business logic/consumer/signature perspective there is no reason ShippingAddress should be any different the eagerly loaded Name property. For this reason, I have decided to make ShippingAddress' public property signature a regular string while its private backing field is C#'s Lazy. The question is, how should I set it? I have come up with two options that maintain separation of data access logic:

Option 1, using overloaded java style set method seems like better OO and more consistent from a internal perspective since I leverage method overloading:

```<code>    Lazy<string> _address;
    public string Address { get { return _address == null ? null : _address.Value; } }
    public void SetAddress(Func<string> address)
    {
        _address = new Lazy<string>(address);
    }
    public void SetAddress(string address)
    {
        SetAddress(() => address);
    }
</code>```

Option 2 seems much better/consistent from a consumer's perspective, but the two setting methods seem very disjointed in a way that bothers me:

```<code>    Lazy<string> _address;
    public string Address
    {
        get { return _address == null ? null : _address.Value; }
        set { SetAddress(() => value); }
    }
    public void SetAddress(Func<string> address)
    {
        _address = new Lazy<string>(address);
    }
</code>```

Does anyone with more experience than I (Most of you I assume) using C#'s lazy class have any ideas as to which is better and why?

答:
When it comes to a BO, the consumer should not see field is lazy loaded or not and it's better to present as any other property (without exposing methods accepting Func parameters)., I'd rather go with the second approach without having the public method SetAddress

```<code>Lazy<string> _address;

public string Address
{
    get { return _address == null ? null : _address.Value; }
    set { _address = new Lazy<string>(() => value); }
}
</code>```

Body:
When it comes to a BO, the consumer should not see field is lazy loaded or not and it's better to present as any other property (without exposing methods accepting Func parameters)., I'd rather go with the second approach without having the public method SetAddress

Lazy<string> _address;

public string Address
{
    get { return _address == null ? null : _address.Value; }
    set { _address = new Lazy<string>(() => value); }
}


问:
Do java .class files have a lexer/parser?
I've been learning ANTLR, by writing my own (extremely simple!) programming language

It made me curious about how the lexer/parser/AST is implemented for java. Obviously there is a grammar for .java files and this gets parsed down to ByteCode, which is then validated to check that all is syntactically and sementically correct and then finally a .class file is written out, but I wondered what happens when you run

java -cp '.' Foo

I assume Foo.class has to be read in - but does this (the bytecode in the .class file) then have a grammar of it's own? or is the AST that is formed when the .java file was compiled just written to disk in binary form, and then just slurped into memory when the java.exe program runs

I was thinking that it probably does have an AST, as this is probably the essence of what a JIT compiler really is.

答:
Technically speaking, there is a parser, but practically speaking, the parser is so trivial, that you typically don't call it a "parser". After all, the JVM bytecode format is specifically designed for being fast and easy to read by a machine and not at all to be readable by humans.

It's basically some fixed-size fields of fixed types and some variable-length arrays of fixed types whose length is provided in a fixed-size field of a fixed type at a fixed location.


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

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

Elaboration:

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

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

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

答:
Embrace it. It can make your entire your product.

GunZ: The Duel (an online game) had a bug that you could exploit and constantly abuse to change pretty much the entire gameplay (called K-Style; look it up on YouTube). It made the whole game way more challenging; it took skill and made it just amazing and fun.. so fun that even the moderators openly used it as their main play style.

It's what made the game.

I didn't play in years but to this day, as a gamer, it's one of my favorite games of all time because it's so skill-based and just so fun, and all of this awesomeness just because of a bug.

They did fix it eventually, but people hated that so much that the devs seriously bugged it back.

So my answer is stabilize and maintain it (refactor if needed).

That beautiful story being said, I don't think the same answer applies for anything that doesn't have a direct advantage. If your bug causes an event which causes the advantage, it will usually be smarter to fix the bug, and find another way to achieve whatever it could. If it's out of scope, consider leaving it out just for being out of scope, or create another module (maybe a small one) to introduce it. Basically: do not violate single responsibility principle.


问:
Is there any material difference between queries joined by WHERE clauses, and queries using an actual JOIN?
In Learn SQL the Hard Way (exercise six), the author presents the following query:

```<code>SELECT pet.id, pet.name, pet.age, pet.dead
    FROM pet, person_pet, person
    WHERE
    pet.id = person_pet.pet_id AND
    person_pet.person_id = person.id AND
    person.first_name = "Zed";
</code>```

and then goes on to say that:

There are actually other ways to get these kinds of queries to work called "joins". I'm avoiding those concepts for now because they are insanely confusing. Just stick to this way of joining tables for now and ignore people who try to tell [you] that this is somehow slower or "low class".

Is that true? Why or why not?

答:
It depends if you think in terms of sets and formal logic.....

If you do then not using the "join" keyword makes for more simple progression from formal logic to SQL.

But if like 99% of people, you did not enjoy formal logic in your maths degree, then the join keyword is a let easier to learn.   SQL used to be presented at university as just anther way to write down formal logic queries....


问:
C# Dependency Injection with Adapter Pattern
In the following code sample, I have a client that works through a controller. In my specific case the controller establishes a session to an address on a GPIB bus. An instance of this is then injected into the client class, which in my case is a device. The client class knows what to say to the device and uses the controller to pass those messages to the device.

Where I get into trouble is there are various ways to talk to the device. I have created so far ITextReader, ITextWriter, IBinaryReader, IBinaryWriter, and there may be more in the future. The implementations of these interfaces is done in the adapter assembly because that is the only assembly that knows how to talk to the adaptee. The controller and client only have references on the controller.api assembly.

How then does the client ask for an instance of the adapter's TextReader, for which it has no reference to? I figure there is some combination of using a factory pattern and an IoC container (using Unity), but I can't come up with a design where the client can get an instance of any of those reader\writer implementations.

Adapter Assembly:

```<code>public class Adapter : IAdapter
{
    public class Adapter(IAdaptee adaptee){..}
}

public class TextReader : TextReaderBase, ITextReader
{
    TextReader(IController controller)
    : base(controller)
    {..}

}
</code>```

Controller.Api Assembly:

```<code>public interface IAdapter{...}
public interface ITextReader{...}
public interface ITextWriter{...}
</code>```

Controller Assembly:

```<code>public class Controller : IController
{
    Controller (IAdapter adapter){...}
}

public abstract class TextReaderBase : ITextReader
{
    TextReaderBase(IController controller){..}
}
</code>```

Client Assembly:

```<code>public class Client : IClient
{
    Client (IController controller){...}
}
</code>```

Edited 6/6/2015:

I should make it clearer what I am trying to do. The 3rd party library (adaptee) has low level functions for reading, writing, opening connections, etc. The high level classes for establishing connections, reading, and writing is what I was referring to as the controller. The adapter adapts the 3rd party library to this controller. I made additional interfaces to represent the low level reader\writer like IAdapterReader and IAdapterWriter.

The clients work exclusively through the controller, knowing nothing of the low level adapter stuff. In my current design, I was planning to have a service that reads a config file to find which adapter to instantiate and the address of the device. It creates an instance of this adapter, injects this into the controller class and then injects the controller object into the client. I am calling the controller class here a "session" to represent a connection to a specific address on the bus. The idea is that the client knows what to say to the device (commands and such) and the controller knows how to say it (has access to the physical layer).

For the client to actually talk to the device, I was thinking they would ask for a reader and a writer instance, but clearly this is not then dependency injection. For the client to ask for a reader\writer it would have to know about the adapter as my high level reader\writers wrap the low level ones implemented by the adapter.

I guess the question then is how does the client get a reader\writer? I can think of a crude way by injecting into the client ISession, ITextReader, ITextWriter, IBinaryReader, IBinaryWriter and any other interfaces it may need? The other way is to inject only ISession and make ISession have a T Resolve<T>(Type type) method. The implementation of Resolve could be through an IoC container. I could change the design around so that when the adapter object is being created it also registers all of its implementations with interfaces with an IoC container passed in from the service layer.

答:
Right now what I see is the following chain of dependencies:

```<code>client->controller->adapter->reader->controller
</code>```

That does create a circular dependency.

You use Dependency Injection to achieve Dependency Inversion. That is, that higher level code does not dependent on the implementation of lower level code.

Looking at the chain, we can attest that there is a piece of code, either the controller or the text reader, that is both high and low level.

If the client does need to use directly the text reader then it cannot be that the adapter uses it as well, as you would need to inject it further up. Rather you will be injecting the adapter into the text reader. And then injecting the text reader into the client.

But if we do that, and we keep the injection of the controller both on the client and the text reader, are we not, then, exposing incorrectly functionality? Because you are saying both that the text reader is of the same level than the controller, and that the  controller is at a lower level than the text reader (as it is injected)

Finally, why does the client need to access the text reader used by the adapter? If there is really something that is needed you can provide a pass through method that doesn't expose the fact that you have the text reader  somewhere down there.

Check which functionality is going to be lower level (which one actually does the writing/reading) and which one does the high level stuff. Order them higher to level and inject lower into higher.

Without looking at the code,I am imagining that the actual order would be

```<code>client->controller->adapter->text read/write
</code>```

And that in fact the text reader/writer doesn't need to know about the controller because it is the one reading/writing directly from/to the device. Any information that the controller has that the text reader/writer needs will be passed through parameters.

Body:
Right now what I see is the following chain of dependencies:

client->controller->adapter->reader->controller

That does create a circular dependency.

You use Dependency Injection to achieve Dependency Inversion. That is, that higher level code does not dependent on the implementation of lower level code.

Looking at the chain, we can attest that there is a piece of code, either the controller or the text reader, that is both high and low level.

If the client does need to use directly the text reader then it cannot be that the adapter uses it as well, as you would need to inject it further up. Rather you will be injecting the adapter into the text reader. And then injecting the text reader into the client.

But if we do that, and we keep the injection of the controller both on the client and the text reader, are we not, then, exposing incorrectly functionality? Because you are saying both that the text reader is of the same level than the controller, and that the  controller is at a lower level than the text reader (as it is injected)

Finally, why does the client need to access the text reader used by the adapter? If there is really something that is needed you can provide a pass through method that doesn't expose the fact that you have the text reader  somewhere down there.

Check which functionality is going to be lower level (which one actually does the writing/reading) and which one does the high level stuff. Order them higher to level and inject lower into higher.

Without looking at the code,I am imagining that the actual order would be

client->controller->adapter->text read/write

And that in fact the text reader/writer doesn't need to know about the controller because it is the one reading/writing directly from/to the device. Any information that the controller has that the text reader/writer needs will be passed through parameters.


问:
Git(flow) workflow for web development
In my (small) company, we are currently thinking about dumping our current versioning system (svn) and release procedures, which are crap TBH, and switching to git. It will mainly be used for one large web project which we will be continously developing for some years, at least. Considering what I found on the web and some questions here on Programmers.SE, I came up with the following workflow (based on the gitflow workflow):

We have three web servers called live, webtest and webdev, and three main branches, master, testing (branched from master) and development (branched from testing). The code in master will always be exactly the one deployed in the live (production) system, and the code in testing will always be exactly the one deployed on the webtest server. The webdev server, however, will be continously used by the developers to upload their code, so it does not necessarily correspond to the development branch.

Whenever a developer starts working on a new feature, he creates a feature branch from development,  works on it (and frequently uploads his current progress to webdev), commits to development from time to time, and whenever he thinks he's done, he merges back his feature branch back into development (1).

Whenever a bunch of features is ready (and possibly reviewed by other developers), we merge development into testing (and this code is deployed on webtest), so it can be tested (2). When the testing in done and everything seems fine, we merge testing back into master (3), and the code in master is deployed on the live production server.

I have some questions about this: In (1), (2) and (3), would it make sense to create pull requests rather than just merging? How would we approach errors found in testing - by creating branches off testing or by fixing it in the respective feature branch and then merging back into development and testing? Are there any other major drawbacks or caveats I have overlooked? Do you have any other enhancements or suggestions?

答:
The standard git flow model should work fine for you based on what you've said. Here's how we use it:

All work is done on develop (or a feature branch if we might want to do a release before a given feature is complete).

When we are ready to call something a release, we create a release branch from develop and deploy this to test.

Any bugs that are raised in test are triaged and either fixed on the release branch or - if we can live without fixing them - tucked away for a later release. During this time, further work can be started on develop (with any release fixes being merged back down regularly to avoid a mega-merge later).

The release branch is deployed to our acceptance environment - the same cycle occurs, except with the testing done by clients.

When everyone is happy with the release branch, it's merged back down to master/develop and deployed to production.

This is pretty flexible - it's also very robust because your release -> master merge is always a fast-forward (so no regression or conflicts when you go to production) and it forces you only to test one release at a time, which means you don't end up with changes on an earlier release branch undermining test validity on a later one. It also means test is stable at any given time and not subject to a trickle of deployments that risk undermining testing.

Things would get quite complicated if you started doing bugfixes on feature branches - you've then got to merge those branches back into the release via develop which might have other work on it... Once your feature branches are merged, they are effectively "done" and any further work - even on that feature - should either be done on develop, a new feature branch or directly in a release branch prior to go-live.

Title: Git(flow) workflow for web development


问:
Abstract Property In Base Class To Force Programmer To Define It
I'm coding with a state pattern for an embedded device. I have a base/abstract class called State and then each discrete(concrete) state class implements the abstract State Class.

In the State Class I have several Abstract Methods. If I don't implement the abstract methods in the discrete(concrete) class, Visual Studio will give an error something like this:

...Error  1   'myConcreteState' does not implement inherited abstract member 'myAbstractState'

Now: I'm trying to create a String property for each State called StateName. Whenever I create a new concrete class, I need to define StateName. I want VS to throw an error if I don't use it. Is there a simple way to do this?

I've tried this in the abstract/base class:

```<code>public abstract string StateName { get; set; }
</code>```

But I don't need to implement the Get and Set methods in each State.

Revised Question:
In an ideal situation, each State Class would be required to have StateName defines and be inherited from the abstract base class.

StateName = "MyState1"; //or whatever the state's name is

If that statement is missing then Visual Studio will generate an error as described above. Is this possible and if so, how?

答:
Your requirements are a contradiction:

I'm trying to create a String property for each State called StateName.

vs.

But I don't need to implement all of that in each State.

There's no language feature that allows you to force the existence of a member in only a few sub classes. After all, the point of using a super class is to rely on the fact that all subclasses will have all the members of the super class (and possibly more). If you want to create classes that act as a State but dont have a name, then by definition, they should (/can) not be subclasses of State.

You either have to change your requirements or use something other than simple inheritance.

A possible solution with the code as it is could be to make the method in State non abstract and return an empty string.


问:
Pick highest score sum, but at least X from each region
Can you think of a solution to the following seemingly simple algorithmic problem?

I am given a list of data points with scores and regions they belong to: [(9, A), (8, B), (7, A), (3, C),  ...]. Scores are floats and each regions can have multiple data points assigned.

For each number N I'd like to select N data points from this list to maximize the total sum of these N scores. Without any restriction, you would chose the top scores, of course.

But now I have the constraint that in each region you have to pick at least X points or none at all. Therefore I cannot have a "sparse" region.

How would you solve this? An algorithm should output for each N the number of points chosen from each region.

答:
I read your question a couple of times, I hope I got it right.

Having the scores of each region sorted in a list seems to be a handy thing to have.

Compute if each region provides X data points. If it doesn't then it
can only contribute 0 to the overall sum and therefore should be
discarded.

From all the regions, compute the maximum score they can contribute
with only X data points. That means, find the X largest scores of A,
B, etc.

Now find the biggest of those X sums and add it to the overall sum You
have to add N-X more elements to the overall sum, which can come from two
sources, you should pick the bigger one that's possible with respect to the limitation that is imposed by N and add it to the overall sum:

The next biggest element of any of the already added areas. This element is not part of the X biggest elements already added to the overall sum. This will add 1 element.

The next biggest sum of X elements from another area. This is the sum of the biggest elements of that area. This will add X elements.

I keep mentioning the number of elements, because it might be tempting to add a whole new area, because that's likely to add a big number to the overall sum, but you have to be careful not to go beyond the N limit.


问:
Uniformly distributing GUIDS to bucket of size N
How can uniformly and deterministically distribute set of GUIDS to N buckets.

N can be as small as 2.

Need to make sure the same GUID is always mapped to the same bucket.

Can't use any additionally memory.

Input GUID set is not known in advance, and will be generated using common library functions available in standard libraries available in c#, java etc.

BucketId = GUID random part % N, would satisfy the consistency part, but, I don't think it will be uniform or not.

答:
(Note: you probably mean "to N buckets".  Or "to a group of buckets of size N".)

"GUID random part % N" is the most uniform you can ever hope for.

Lack of uniformity will only be evident in a small data set, in which performance does not matter anyway.  In a large data set, where performance matters, it will be quite uniform.

Of course, these are random numbers that we are talking about, so absolute uniformity (all buckets having the exact same load) is practically impossible.

So, when you speak of uniformity, and knowing that you cannot have absolute uniformity, you must be willing to accept some "good enough" uniformity.  Which in turn means that you must have some particular uniformity requirements in mind.  Please tell us your requirements, and why you arrived at them.

What, you don't have any such requirements?  You are just worried before you have an actual problem in your hands?  Well then, I would recommend that you stop worrying about the uniformity offered by "GUID random part % N".  In all likelihood it will be much better than what you would ever need.

(And, in any case, unbeatable.)


问:
How would I handle a set of differing event classes with differing handler interfaces in a single event processor?
I'm working on an event processor framework for a simple game I'm writing, in which multiple types of events are handled in a loop. Since these events carry distinct pieces of data (i.e. one carries a player and position, another carries a message and timestamp), I ended up creating different classes for them (though they still all implement a common interface, which is currently a marker interface).

Within my event processor, I have, for each type of event, a set of event handlers implementing a corresponding interface (e.g. anonymous class implementing PlayerInteractHandler that handles PlayerInteractEvents). Since these interfaces are being implemented through a Javascript engine (Rhino) I am unable to use a single generic interface.

In trying to implement the actual engine, I have currently code as follows (methods inlined to show idea behind code in a more compact representations):

```<code>if (recvdEvent instanceof FooEvent){
    // getHandlerList() returns a List<EventHandler> due to limitations of generics
    for(EventHandler eh : getHandlerList(FooHandler.class) {
        FooEvent eventAfterCast = (FooEvent) recvdEvent
    }
}
</code>```

Obviously there are a bunch more else if (recvdEvent instanceof BarEvent) blocks, and I catch and handle ClassCastExceptions.

The problem with this, is that it seems like a mis-use of an object-oriented language, and I have to stringently verify other code by hand to retain type safety.

The other alternatives I know of are for my event to return the Class<? extends EventHandler> in a certain method, to use polymorphism / dynamic dispatch, but that would require a reflective cast, or a polymorphic method in the handler class that would still break complete type safety (and another layer on top of the interface itself).

Multiple event processors would lead to code duplication, and would imply having separate threads for each as the current event processor is designed. If I were to retain a single thread and processor I would need a single queue, whose declared type is AbstractQueue<GameEvent>, and I'd be back at square one.

Am I approaching this in a completely incorrect manner?

答:
Visitor Pattern

It won't help here. The best scenario to adopt Visitor Pattern is you have a fixed number of subclasses. However, in your example, you could have a lot of Event in the future. So, if you choose to use Visitor Pattern, every time you add a new kind of Event, you have to modify the Visitor. It's a nightmare.

Reflection

It's the right way to go. You have to sacrifice type safety for more dynamic dispatching. But, we can do something to improve the safety.

Guava EventBus use reflection and annotation to provide both compiling and runtime safety. You can check the implementation if you are interested. In summary, it sacrifice a little safety(you may have an event which doesn't have corresponding handler, which I think is reasonable, but may not for your case), but what you gain is more clean and maintainable code.


问:
Are imperative events an anti-pattern?
Are events which are intended to tell listeners to carry out explicit actions an anti-pattern?

Imagine a worker service which raises the event WorkStarted at its beginning and the event WorkFinised at its end.

These events convey information about what that worker service did and they are not inherently imperative to any of the potential subscribers of that event.

Consider that it may be the intention of the application to use this event to show or hide a loading icon. Is it an anti-pattern for the worker service to raise a ShowLoadingIcon and HideLoadingIcon event instead?

In this case no information about what the worker service did is conveyed, only an instructive request is made.

In what cases, if any, are either these approaches inappropriate or preferred?

EDIT: To clarify, I'm asking about the existence of standards for event-driven programming. All standardization questions include some amount of opinion, and yet the site is littered with them because there is a different between a question of personal preference and one of generally accepted good practice.

答:
It is none of your business what I intend to do when your API raises an event.  Maybe I will show an icon, maybe I will order coffee for the lead developer, start a music video, whatever I do, it's my business not yours.  The point of the event is to notify those that are interested that something has happened, after that, it's no longer your conceern.

As a developer, it's your job to determine what events are usefully reported -- CompletedFirstStepOfSecondLoopInMethodA probably isn't of interest to anyone.  But once you have determined that something should be reported, your part is done.  What is done on the other end of the event isn't up to you.

Title: Are imperative events an anti-pattern?


答:
First, an alternative

The ShippingAddress is very expensive to load and located in a separate table, and a minority of pages use it.

In that case, perhaps ShippingAddress doesn't belong in Person in terms of the Business Object model?
For the cases where you need to involve ShippingAddress as a first-class concept then you can instead define a ShippingAddress business object, which can of course have a Person as a dependency if needs be, or better yet just represent Shipping Addresses as a service, load them when needed (based on PersonID or whatever) and directly attach them to the Person instance.

Second, an exceptional case

If that doesn't / can't float your goat, then let's stick with Lazy Loading.
I slightly disagree with your statement that "from a business logic/consumer/signature perspective there is no reason ShippingAddress should be any different the eagerly loaded Name property".

I totally see the perspective; and in general I would agree  - except that in this case you have a specific, real-world situation (horribly slow access to the Shipping Address data store, cannot be changed, these things happen) that unfortunately defies the normal expectancy that if you've seen one getter, you've seen 'em all :)

So I would say that a client accessing the Address** property would be surprised to find that it actually involves a separate database hit, especially considering

The other properties don't

This is a property on a Business Object, not an obviously "connected" entity.

TL;DR -  don't violate POLA - consider what might happen if someone throws a bunch of Person objects into an XmlSerialiser....

Third, a suggested approach

If you are going to use lazy loading from the database for Address, I'd recommend one of two approaches, both of which involve making the actual loader itself an explicitly modelled abstraction.

1. Make the loader function an explicit dependency of Person

public Person(int name, etc, IShippingAddressLoader addressLoader)

2. Make the loader function an explicit dependency of a LoadAddress() method

public void LoadAddress(IShippingAddressLoader addressLoader)
{
    _address=addressLoader.Load(_personID); //or whatever;
}

My reasoning is

In both ways, I think it's more obvious to client code using the Person class that there is "extra" code involved in getting the Shipping Address; and as a bonus it makes the Person class much more unit-testable because you can mock or stub the loader.

With either approach you don't need to declare _address itself as Lazy because you have shifted the "laziness" onto an explicit concept (the loader).

When you do find a nice way to cache all of the Addresses (maybe your server gets more RAM, so now it's feasible to load them all into memory at app startup, slap a SqlDependency on them and watch for changes), you only need to change the IShippingAddressLoader implementation, not the Person class.

Finally, a sneaky attempt

to sell you the first idea by suggesting that you just accept that Shipping Address is a tricky piece of data in your case, and that any code that had to deal with it (controllers or whatnot) just get their own IShippingAddressService service, e.g

```<code>public ShippingConfirmationModel GenerateConfirmationModel(Person person)
{
    var shippingAddress = _shippingAddressService.GetByPersonID(person.ID);
    person.SetShippingAddress(shippingAddress)
    return new ShippingConfirmationModel(person);
}
</code>```

This frees you from all shenanigans related to lazy loading in the Person class, allows you to implement caching really easily, and also allows you to pass Person objects around safe in the knowledge that you won't accidentally tip over the database when someone decides to serialise all the people :)

**Minor note - if this is the Person's "ShippingAddress" then I would make sure to refer to it always as "ShippingAddress" in the code, as opposed to just "Address" :)

Title: Lazy loaded property signatures in business objects

Body:
Let's say I am designing business objects around a poorly optimized database that have no ability to change.

I have a Person object with a ShippingAddress property. The ShippingAddress is very expensive to load and located in a separate table, and a minority of pages use it. There are times when thousands of Person objects need to be loaded on a single page so eating the performance hit is not an option. This makes lazy loading the ShippingAddress ideal for this situation.

However, from a business logic/consumer/signature perspective there is no reason ShippingAddress should be any different the eagerly loaded Name property. For this reason, I have decided to make ShippingAddress' public property signature a regular string while its private backing field is C#'s Lazy. The question is, how should I set it? I have come up with two options that maintain separation of data access logic:

Option 1, using overloaded java style set method seems like better OO and more consistent from a internal perspective since I leverage method overloading:

```<code>    Lazy<string> _address;
    public string Address { get { return _address == null ? null : _address.Value; } }
    public void SetAddress(Func<string> address)
    {
        _address = new Lazy<string>(address);
    }
    public void SetAddress(string address)
    {
        SetAddress(() => address);
    }
</code>```

Option 2 seems much better/consistent from a consumer's perspective, but the two setting methods seem very disjointed in a way that bothers me:

```<code>    Lazy<string> _address;
    public string Address
    {
        get { return _address == null ? null : _address.Value; }
        set { SetAddress(() => value); }
    }
    public void SetAddress(Func<string> address)
    {
        _address = new Lazy<string>(address);
    }
</code>```

Does anyone with more experience than I (Most of you I assume) using C#'s lazy class have any ideas as to which is better and why?

Body:
First, an alternative

The ShippingAddress is very expensive to load and located in a separate table, and a minority of pages use it.

In that case, perhaps ShippingAddress doesn't belong in Person in terms of the Business Object model?
For the cases where you need to involve ShippingAddress as a first-class concept then you can instead define a ShippingAddress business object, which can of course have a Person as a dependency if needs be, or better yet just represent Shipping Addresses as a service, load them when needed (based on PersonID or whatever) and directly attach them to the Person instance.

Second, an exceptional case

If that doesn't / can't float your goat, then let's stick with Lazy Loading.
I slightly disagree with your statement that "from a business logic/consumer/signature perspective there is no reason ShippingAddress should be any different the eagerly loaded Name property".

I totally see the perspective; and in general I would agree  - except that in this case you have a specific, real-world situation (horribly slow access to the Shipping Address data store, cannot be changed, these things happen) that unfortunately defies the normal expectancy that if you've seen one getter, you've seen 'em all :)

So I would say that a client accessing the Address** property would be surprised to find that it actually involves a separate database hit, especially considering

The other properties don't

This is a property on a Business Object, not an obviously "connected" entity.

TL;DR -  don't violate POLA - consider what might happen if someone throws a bunch of Person objects into an XmlSerialiser....

Third, a suggested approach

If you are going to use lazy loading from the database for Address, I'd recommend one of two approaches, both of which involve making the actual loader itself an explicitly modelled abstraction.

1. Make the loader function an explicit dependency of Person

public Person(int name, etc, IShippingAddressLoader addressLoader)

2. Make the loader function an explicit dependency of a LoadAddress() method

public void LoadAddress(IShippingAddressLoader addressLoader)
{
    _address=addressLoader.Load(_personID); //or whatever;
}

My reasoning is

In both ways, I think it's more obvious to client code using the Person class that there is "extra" code involved in getting the Shipping Address; and as a bonus it makes the Person class much more unit-testable because you can mock or stub the loader.

With either approach you don't need to declare _address itself as Lazy because you have shifted the "laziness" onto an explicit concept (the loader).

When you do find a nice way to cache all of the Addresses (maybe your server gets more RAM, so now it's feasible to load them all into memory at app startup, slap a SqlDependency on them and watch for changes), you only need to change the IShippingAddressLoader implementation, not the Person class.

Finally, a sneaky attempt

to sell you the first idea by suggesting that you just accept that Shipping Address is a tricky piece of data in your case, and that any code that had to deal with it (controllers or whatnot) just get their own IShippingAddressService service, e.g

public ShippingConfirmationModel GenerateConfirmationModel(Person person)
{
    var shippingAddress = _shippingAddressService.GetByPersonID(person.ID);
    person.SetShippingAddress(shippingAddress)
    return new ShippingConfirmationModel(person);
}

This frees you from all shenanigans related to lazy loading in the Person class, allows you to implement caching really easily, and also allows you to pass Person objects around safe in the knowledge that you won't accidentally tip over the database when someone decides to serialise all the people :)

**Minor note - if this is the Person's "ShippingAddress" then I would make sure to refer to it always as "ShippingAddress" in the code, as opposed to just "Address" :)


问:
Do you have any team guidelines regarding exceptions?
My team recently inherited a project from a team where the amount of developers dropped so low they had to offload some work. One of the projects we inherited was a project littered with nested code, and awful exception handling (Exceptions were in effect handled as goto statements and thus used as a part of the normal program flow.).

All in all it was a hairy code ball someone had been coughing up for a few years.

Now we've been having a few team guidelines in place for quite some time, but all of the regards to the structures of objects, coding styles and what not. But we haven't covered exception handling.

So I'm wondering if you have any guidelines in your teams regarding exception handling, and if so how you enforce them?

答:
We don't have specific exception handling rules for our team, except the usual ones: don't use exceptions for 'normal' behavior, don't just silently swallow exceptions, etc.

Static ananlysis may help you catch some of those (depending on the language you use) but you'll be safer with code reviews.

ContentLicense: CC BY-SA 2.5


问:
Graph visualization algorithm
I need a 2d or 3d graph visualization algorithm by which adding/removing a node or a relationship does not have a butterfly effect on the positions of other nodes. (We are talking about a directed cyclic graph with weighted nodes and relationships if that matters.)

For example by a regular force layout adding a new node affects the position of every other node. Do you have any idea which algorithm could help?

答:
A problem that may be related is one where I have program to show the changing process trees running on a computer, as a real-time animation.

In that context each level of the tree generally goes from narrow to wide. So to keep regularity, you could keep larger subdivisions around for a little while before reducing them.

For example. I have at the top level 1 item. Next level 3 items, next level 10 items. Suppose an item at level 2 and 3 children of that disappear. You could keep the positions they are at still around but now just as invisible items and lines so that nothing else changes. So visually it would be as one expects, they just disappear. Then slowly over time that gap could get closed up. But in my case, often a new set of processes would take its place. I'd have that then in the space occupied by the gap.

The paper describing my situation and solution is http://motif-pstree.sourceforge.net/xps-full.ps

The main idea is laying out a grid for each depth to put stuff in and keeping that around for a little bit of time.

Title: Graph visualization algorithm


问:
Why isn't lazy evaluation used everywhere?
I've just learnt how lazy evaluation works and I was wondering: why isn't lazy evaluation applied in every software currently produced? Why still using eager evaluation?</p>

答:
If we potentially have to fully evaluate an expression to determine it's value then lazy evaluation can be a disadvantage. Say we have a long list of boolean values and we want to find out if all of them are true:

```<code>[True, True, True, ... False]
</code>```

In order to do this we have to look at every element in the list, no matter what, so there is no possibility of lazily cutting off evaluation. We can use a fold to determine if all the boolean values in the list are true. If we use a fold right, which uses lazy evaluation, we don't get any of the benefits of lazy evaluation because we have to look at every element in the list:

```<code>foldr (&&) True [True, True, True, ... False]
> 0.27 secs
</code>```

A fold right will be much slower in this case than a strict fold left, which does not use lazy evaluation:

```<code>foldl' (&&) True [True, True, True, ... False]
> 0.09 secs
</code>```

The reason is a strict fold left uses tail recursion, which means it accumulates the return value and doesn't build up and store in memory a large chain of operations. This is much faster than the lazy fold right because both functions have to look at the entire list anyway and the fold right can't use tail recursion. So, the point is, you should use whatever is best for the task at hand.

Body:
If we potentially have to fully evaluate an expression to determine it's value then lazy evaluation can be a disadvantage. Say we have a long list of boolean values and we want to find out if all of them are true:

[True, True, True, ... False]

In order to do this we have to look at every element in the list, no matter what, so there is no possibility of lazily cutting off evaluation. We can use a fold to determine if all the boolean values in the list are true. If we use a fold right, which uses lazy evaluation, we don't get any of the benefits of lazy evaluation because we have to look at every element in the list:

foldr (&&) True [True, True, True, ... False]
> 0.27 secs

A fold right will be much slower in this case than a strict fold left, which does not use lazy evaluation:

foldl' (&&) True [True, True, True, ... False]
> 0.09 secs

The reason is a strict fold left uses tail recursion, which means it accumulates the return value and doesn't build up and store in memory a large chain of operations. This is much faster than the lazy fold right because both functions have to look at the entire list anyway and the fold right can't use tail recursion. So, the point is, you should use whatever is best for the task at hand.


答:
Here is a short comparison of the pros and cons of eager and lazy evaluation:

Eager evaluation:

Potential overhead of needlessly evaluating stuff.

Unhindered, fast evaluation.

Lazy evaluation:

No unnecessary evaluation.

Bookkeeping overhead at every use of a value.

So, if you have many expressions that never have to be evaluated, lazy is better; yet if you never have an expression that does not need to be evaluated, lazy is pure overhead.

Now, lets take a look at real world software: How many of the functions that you write do not require evaluation of all their arguments? Especially with the modern short functions that only do one thing, the percentage of functions fall into this category is very low. Thus, lazy evaluation would just introduce the bookkeeping overhead most of the time, without the chance to actually save anything.

Consequently, lazy evaluation simply does not pay on average, eager evaluation is the better fit for modern code.

Title: Why isn't lazy evaluation used everywhere?

Body: I've just learnt how lazy evaluation works and I was wondering: why isn't lazy evaluation applied in every software currently produced? Why still using eager evaluation?</p>


问:
Understanding dependency injection
I'm reading about dependency injection (DI). To me, it is a very complicated thing to do, as I was reading it was referencing inversion of control (IoC) as well and such I felt I was going to be in for a journey.

This is my understanding: Instead of creating a model in the class which also consumes it, you pass (inject) the model (already filled with interesting properties) to where it is needed (to a new class which could take it as a parameter in the constructor).

To me, this is just passing an argument. I must have miss understood the point? Maybe it becomes more obvious with bigger projects?

My understanding is non-DI (using pseudo code):

```<code>public void Start()
{
    MyClass class = new MyClass();
}

...

public MyClass()
{
    this.MyInterface = new MyInterface();
}
</code>```

And DI would be

```<code>public void Start()
{
    MyInterface myInterface = new MyInterface();
    MyClass class = new MyClass(myInterface);
}

...

public MyClass(MyInterface myInterface)
{
    this.MyInterface = myInterface;
}
</code>```

Could some one shed some light as I'm sure I'm in a muddle here.

答:
A lot of people said here that DI is a mechanism to out-source the initialization of an instance variables.

For obvious and simple examples you don't really need "dependency injection". You can do this by a simple parameter passing to the constructor, as you noted in question.

However, I think that a dedicated "dependency injection" mechanism is useful when you talk about application-level resources, where both caller and callee doesn't know nothing about these resources (and don't want to know!).

For example: Database connection, Security context, Logging facility, Configuration file etc.

Moreover, in general every singleton is a good candidate for DI. The more of them you have and use, the more chances you need DI.

For these kinds of resources it's quite clear that it doesn't make sense to move them all around via parameter lists and therefore the DI was invented.

Last note, you also need a DI container, that will do the actual injection... (again, to release both caller and callee from implementation details).

Title: Understanding dependency injection


答:
I guess the "correct" way to do this is to have a protected constructor on the base class which requires the state name as a parameter.

```<code>public abstract class State
{
    private readonly string _name;

    protected State(string name)
    {
        if(String.IsNullOrEmpty(name))
            throw new ArgumentException("Must not be empty", "name");

        _name = name;
    }

    public string Name { get { return _name; } }
}
</code>```

The concrete states then provide a public constructor which implicitly calls the base class constructor with the appropriate name.

```<code>public abstract class SomeState : State
{
    public SomeState() : base("The name of this state")
    {
        // ...
    }
}
</code>```

Since the base class does not expose any other constructors (neither protected nor public) each inheriting class needs to go through this single constructor and thus needs to define a name.

Note that you don't need to provide the name when you instantiate a concrete state because its constructor takes care of that:

```<code>var someState = new SomeState(); // No need to define the name here
var name = someState.Name; // returns "The name of this state"
</code>```

Title: Abstract Property In Base Class To Force Programmer To Define It

Body:
I'm coding with a state pattern for an embedded device. I have a base/abstract class called State and then each discrete(concrete) state class implements the abstract State Class.

In the State Class I have several Abstract Methods. If I don't implement the abstract methods in the discrete(concrete) class, Visual Studio will give an error something like this:

...Error  1   'myConcreteState' does not implement inherited abstract member 'myAbstractState'

Now: I'm trying to create a String property for each State called StateName. Whenever I create a new concrete class, I need to define StateName. I want VS to throw an error if I don't use it. Is there a simple way to do this?

I've tried this in the abstract/base class:

```<code>public abstract string StateName { get; set; }
</code>```

But I don't need to implement the Get and Set methods in each State.

Revised Question:
In an ideal situation, each State Class would be required to have StateName defines and be inherited from the abstract base class.

StateName = "MyState1"; //or whatever the state's name is

If that statement is missing then Visual Studio will generate an error as described above. Is this possible and if so, how?

Body:
I guess the "correct" way to do this is to have a protected constructor on the base class which requires the state name as a parameter.

public abstract class State
{
    private readonly string _name;

    protected State(string name)
    {
        if(String.IsNullOrEmpty(name))
            throw new ArgumentException("Must not be empty", "name");

        _name = name;
    }

    public string Name { get { return _name; } }
}

The concrete states then provide a public constructor which implicitly calls the base class constructor with the appropriate name.

public abstract class SomeState : State
{
    public SomeState() : base("The name of this state")
    {
        // ...
    }
}

Since the base class does not expose any other constructors (neither protected nor public) each inheriting class needs to go through this single constructor and thus needs to define a name.

Note that you don't need to provide the name when you instantiate a concrete state because its constructor takes care of that:

var someState = new SomeState(); // No need to define the name here
var name = someState.Name; // returns "The name of this state"


问:
Why are regular expressions so morbidly attractive?
Exhibit 1, Exhibit 2, I guess you won't find it hard to recall other examples.

Thing is: if there is more than one way to solve a problem, the PHP programmer (I usually browse the PHP tag on StackOverflow) will ask for help on the solution involving regular expressions.

Even when it will be less economic, even when the php manual suggests (link) to use str_replace instead of any preg_* or ereg_* function when no fancy substitution rules are required.

Does somebody have a clue about why this happens?

Don't get me wrong, some of my best friends are regular expressions and I don't despise Perl. What I don't get is why there is no looking for alternatives whatsoever, even when the overkill is obvious (regex to switch strings) or the code complexity rises exponentially (regex for getting data from html in PHP)

答: Hmmm, I can only guess. Maybe some people have experienced that 30 lines of their code were replaced by a 20-character-long regex, so it feels wrong to them to use anything else instead when regexes can be used.</p>


问:
Architecture: Should I schema validate incoming reply messages?
A web service I consume uses XSD to describe its API. Recently, they added a field to a reply message where no xsd:any had been, so when our schema validator tried to validate against the previous xsd, it failed. We considered this a backwards incompatibility and opened a ticket.

Their architect replied that we should validate our outgoing messages (requests), but not bother to validate replies. We should pick and choose the fields we want in the replies and ignore the rest. He also said that we should set our schema validator to ignore "new" fields and validate the rest.

If such a setting exists for some schema validators, then maybe this architect is not wrong, but on the other hand if my application breaks because a field I don't need to care about changed (or got created) doesn't that indicate a violation of the interface segregation principle? Is it really acceptable for me to validate the individual fields of the object piecemeal instead of expecting it to be all-or-nothing correct?

I realize that not validating incoming data from an external service has security implications as well, but in this question I'm trying to learn about the architectural principles more than the security aspects.

答:
I guess, if there is an XSD schema, you should be able to validate everything against it. Well, it is the purpose of itS existence ;)

So, I guess they just need to release a new version of their schema for you to update your software.

As for adding a new field into a reply... Well, if there was no schema, I would think that should not be considered a BC break.  When you design an API consumer, you should be as  agile as possible. Removing a field or changing its format should be a BC break for you. But adding a new one should not.


问:
When should I use a 2-property class over a pre-built structure like a KeyValuePair?
When should you put Key/Value type of data in it's own class instead of using a pre-built generic structure, such as a KeyValuePair or a Tuple?

For example, most ComboBoxes I create contain a DisplayName and a Value. This is the kind of data I am trying to decide when to put in a new class, and when to just use a KeyValuePair.

I am currently working on something that uses iCalendar, and the selected user's data ultimately gets combined into a key1=value1;key2=value2; type of string. I started out by putting the data in a KeyValuePair<string,string>, but now I am wondering if that should be it's own class instead.

Overall, I am interested in finding out what guidelines are used when deciding to use an existing structure/class like a KeyValuePair over a 2-property object, and in what kind of situations you would use one over another.

答:
I would perhaps agree with Wilding here.

I would suggest that the built-in types are often mechanism objects.  KeyValuePair for example, is part of the mechanism of a dictionary and hash tables, helping to ensure unique keys and they have properties that have meaningful names within the context of the mechanism itself.

On the other hand, using custom made data objects provides a better representation of your data and provide many benefits, including readability and extensibility.  There is nothing to stop reusing existing code in custom built objects as Sign suggested, but I would try and hide the wrapped class, and avoid abstraction leakage, so that you can change the underlying implementation at a later point without affecting the rest of your code.

So the real question: Are you representing data or are you using the data in a mechanism? (and I wouldn't advise mixing these concepts together).

In my experience there is nothing worse that seeing a Tuple[string, string] being passed into a method and having no immediate way of knowing what Item1 and Item2 are supposed to be.  Best to use Tuples within methods or as private members of a class only.


问:
how do websites detect my screen resolution
http://whatsmyuseragent.com/ tells you your screen resolution, javascript enabled,user agent and local time etc?

User agent is a part of HTTP header. How do they know about other information?
I installed Firefox addons "Live HTTP Header" to view this information but I was only able to see user agent.

答:
Because client-side Javascript code has access to that kind of information.

If you go to http://whatsmyscreenresolution.com/ (which your link links to) and press ctrl+u to view the page's (client-side) source code, you'll see things like this:

```<code>            <div class="col-md-4 col-md-offset-2 well">
                <h3>jQuery code to get window resolution:</h3>
                <p class="codeSection">
                    ; (function () {<br />
                         $(window).width();<br />
                         $(window).height();<br />
                    })();<br />
                </p>
            </div>
</code>```

If it's not obvious, the $(window).width(); and $(window).height(); are the important parts here.

Note that the "website" (i.e., the server that sent you this HTML page with bits of Javascript in it) does not have any direct access to this information. They can only get if your browser runs a piece of Javascript code that sends it back to them, which this page may or may not be doing.

The documentation for the window object lists several additional properties related to size and scroll position and other stuff that all Javascript code has access to.

Since you also mentioned local time, here's the documentation for the Date object. The key bit is that new Date() will create a Date object set to the current date and time in the user's local timezone.

On the website you linked, this is done (and then redone every 10 seconds) in:

```<code>    function UpdateTime() {
        $('.local-time').text(formatAMPM(new Date()));
        setTimeout(function () { UpdateTime() }, 10000)
    };
</code>```

And finally, a website can show whether or not you have Javascript enabled by displaying "No" by default:

```<code>            <td style="width: 50%;">JavaScript Enabled:</td>
            <td class="js-enabled bold">No</td>
</code>```

and having a piece of Javascript code that changes the "No" to a "Yes":

```<code>        $('.js-enabled').text('Yes');
</code>```

If your browser refuses to run Javascript, you see the "No". If it runs it, you see the "Yes".

Body:
Because client-side Javascript code has access to that kind of information.

If you go to http://whatsmyscreenresolution.com/ (which your link links to) and press ctrl+u to view the page's (client-side) source code, you'll see things like this:

            <div class="col-md-4 col-md-offset-2 well">
                <h3>jQuery code to get window resolution:</h3>
                <p class="codeSection">
                    ; (function () {<br />
                    &nbsp; &nbsp; &nbsp;$(window).width();<br />
                    &nbsp; &nbsp; &nbsp;$(window).height();<br />
                    })();<br />
                </p>
            </div>

If it's not obvious, the $(window).width(); and $(window).height(); are the important parts here.

Note that the "website" (i.e., the server that sent you this HTML page with bits of Javascript in it) does not have any direct access to this information. They can only get if your browser runs a piece of Javascript code that sends it back to them, which this page may or may not be doing.

The documentation for the window object lists several additional properties related to size and scroll position and other stuff that all Javascript code has access to.

Since you also mentioned local time, here's the documentation for the Date object. The key bit is that new Date() will create a Date object set to the current date and time in the user's local timezone.

On the website you linked, this is done (and then redone every 10 seconds) in:

    function UpdateTime() {
        $('.local-time').text(formatAMPM(new Date()));
        setTimeout(function () { UpdateTime() }, 10000)
    };

And finally, a website can show whether or not you have Javascript enabled by displaying "No" by default:

            <td style="width: 50%;">JavaScript Enabled:</td>
            <td class="js-enabled bold">No</td>

and having a piece of Javascript code that changes the "No" to a "Yes":

        $('.js-enabled').text('Yes');

If your browser refuses to run Javascript, you see the "No". If it runs it, you see the "Yes".


答:
The site shows how it's done, actually.  It has a link to http://whatsmyscreenresolution.com/ which shows two snippets down below:

JavaScript code to get screen resolution:

```<code><script type="text/javascript">
document.write(screen.width + 'x' + screen.height);
</script>
</code>```

jQuery code to get window resolution:

```<code>; (function () {
     $(window).width();
     $(window).height();
})();
</code>```

Title: how do websites detect my screen resolution

Body:
http://whatsmyuseragent.com/ tells you your screen resolution, javascript enabled,user agent and local time etc?

User agent is a part of HTTP header. How do they know about other information?
I installed Firefox addons "Live HTTP Header" to view this information but I was only able to see user agent.

Body:
The site shows how it's done, actually.  It has a link to http://whatsmyscreenresolution.com/ which shows two snippets down below:

JavaScript code to get screen resolution:

<script type="text/javascript">
document.write(screen.width + 'x' + screen.height);
</script>

jQuery code to get window resolution:

; (function () {
     $(window).width();
     $(window).height();
})();


问:
@Qualifier and Dependency Inversion Principle
I recently discovered SOLID principles and i'm trying to learn how to properly apply them. I have an application that had a huge interface:

```<code>public interface NotificationService {
  public void sendNewProjectRequestNotificationToDesigners(String projectId);
  public void sendNewProjectAcceptedNotificationToCustomer(String projectId);
  public void sendNewProjectRejectedNotificationToCustomer(String projectId);
  ...
  // and aboud 30 more methods like that
  // specifying the type of notification and who is going to be sent to
}
</code>```

This clearly violates:

SRP: so many different kind of notifications

OCP: Every new notification i just modified the class

ISP: In every single class that injects a NotificationService, will only want 1 of all the methods.

DIP: The clients of this class need to be aware of the exact method to use.

so i began my refactoring and came up with:

```<code>public interface NotificationSender {
  public void sendNotification(String projectId);
}

public class NewProjectRequestNotificationSender implements NotificationSender {
  public void sendNotification(String projectId) {
    ...
  }
}

// and many other classes, one for each method in the original interface
</code>```

Now to apply Dependency Injection, i declared each class that implements NotificationSender as a @Bean with a qualifier name.

And the classes that require a specific notification sender, the dependency is injected with @Qualifier.

Question 1: By having to use @Qualifier in the clases that require a specific NotificationSender, hence these clases are still forced to know details like the qualifier name of the given NotificationSender, am i still violating Dependency Inversion Principle?

Question 2: Is there a better approach?

答: Well you could add another layer of indirection by using a factory and injecting the concrete classes into the factory, then injecting the factory where you need the concrete classes.  The factory could have a method to which the caller is passed, and then the factory could figure out what to return based on that. </p>


问:
Flat files for events and alarms
So I'm working on a project that I was introduced to a year ago. One of the features of project involves alarming the users when certain events are triggered. There is also a log of these events. First you need to understand this:

Not all alarms generate event logs

Events can be logged without generating alarms.

The design of this involves flat files that hold a bunch of information about the events and the alarms. This includes everything from where the alarms are sent, priority levels, etc.

What happens in the code is when an event is trigger, it sends a message with a bunch of data attached to it to a process that reads in the flat files, replaces the data appropriately, and then routes it.

My question is this:

Is it normal design to save all this information outside of the code. We're running into problems when we deploy because we have to ensure that the flat files and the code are in sync. It's created some troubleshooting nightmares, and it honestly just feels like more hassle then just having a class dedicated to this stuff, and shipping it with the code.

答:
Is it normal design to save all this information outside of the code.

I think it is perfectly normal. You can use Observable pattern for handling events dispatching and store its configuration (actual subscriptions) inside, say, database.

I do not respect storing information in plain files. It is difficult to atomically change them and they are not intended for storing data of real complexity. Use at least SQLite database.

Title: Flat files for events and alarms


问:
Design review for refactoring a large function
Basic terminology:

Report - single report to generate

ReportGroup - group of Report(s) to generate

Request - contains one or more ReportGroup

I'm working on refactoring of the large function (~350 lines) in an even larger class (~2500 lines)

The function is responsible for a generation of report in various formats (txt,csv, xlsx, pdf, zip)

Currently, function supports extraction for a single Report or single ReportGroup.
My task is to extend the function to support extraction for multiple ReportGroups.

This function is essensially a series of steps that eventually generate a file in requested format.

Below are the steps I could identify for a single report:

Analyze/Validate input - return if not valid.

Get result (In form of a tree) - return if not valid.

Create ResultDescriptor - Poco containing tree result and additional
meta data calculates from request and result properties.

Create GenerationResultStatus and add it to the Response object

Pass result descriptor to the rendering engine and get the path to
file back.

Move generated file to shared location (location is determined based
on ResultDescriptor properties).

Generate Response object containing end result file location,
GenerationResultStatus, overallstatus (bool) and error message and
return it to the caller.

I've came up with the following classes:

Single report generation actors:

```<code>ResultDescriptorBuilder
GenerationResultStatusBuilder
StandartizedFileMover
ResponseBuilder
</code>```

 Report generators:

SingleReportGenerator - processes a single report and outputs a single file,
GroupedReportGenerator - Decorator on a SingleReportGenerator. Processes report group and outputs a single file (xlsx, pdf).

ZipedReportGenerator - Decorator on a SingleReportGenerator. Processes report group and outputs a single zip file .

GroupOfGroupedReportGeneratorPdf - Decorator on GroupedReportGenerator. Processes the whole request by looping each ReportGroup and passing it to GroupedReportGenerator.

The resulting files are then merged to a single pdf. Supports only pdf format.

I guess, the biggest question is should I even bother doing the refactoring (from a purely practical point of view)?

I could probably get away with a patch that calls current function in a loop and then merges the results.

The function doesn't change very often and I don't foresee any new changes.

I do have some unit and integration tests in place, but they're pretty basic and don't offer full coverage.

In case I do decide to go with the refactoring, Are there any issues I overlooked?

Is there a design pattern that can make this more generic?

Any naming suggestions are welcome. I think I overuse the Generator/Builder words.

答:
Your way of thinking is perfectly reasonable.

I guess, the biggest question is should I even bother doing the
  refactoring (from a purely practical point of view)?

That depends. From the artist's standpoint, the answer is YES. But there is money involved. So, you must estimate the impact of unrefactored code to your development cycle. If it will cause difficulties or damage system design in any way, the answer is again YES.

I could probably get away with a patch that calls current function in
  a loop and then merges the results.

Probably. Actually, that would make some facade over current code, that will just hide some ugly piece of it ;)

In case I do decide to go with the refactoring, Are there any issues I
  overlooked?
  Is there a design pattern that can make this more generic?

I don't think so.