问:
How do I access databases from a mobile device securely?
I have been doing some research on accessing a DB from mobile devices. There are so many different ways of doing it. There are also multiple ways to make it secure. What is a good way to access a database from a mobile device securely?

Also considering my specific case, where I have an existing WCF service which does everything I would need for the app, I would like to re-use it. I have been working on using jsonp calls to the service and develop apps for iOS, Android and windows phone. The calls are secured by HTTPS and I would be implementing some authentication policy for the calls. But how secure would all this be?

I have some really sensitive data to worry about. I am using HTML5 and JS for app development to keep it uniform and less difficult to manage for all platforms.

How do I access the database and keep my data secure?

答:
You shouldn't be accessing any external database from a mobile device at all.

From the network's point of view, connection to a database should only be done within a local network where connection is reliable and fast, which is something you will not get with mobile connections.

From the design point of view, exposing a database directly is simply a bad idea, not only it's too lower level, also it will be a nightmare when users are using different versions of your app and trying to do different things to your database. You should provide RESTful web services with appropriate high API abstraction for your mobile app instead.


问:
Finding lowest cost path - dynamic
I have to write a dynamic algorithm for finding lowest cost path. So I have a point that I have to visit. I can jump only between points by distance - 5 I have an array of distance from 0-point for example (1 3 5 10 15 20 21 22). Each move cost me 1. So the best path will be to move 1->5->15->20->22 (3 and 21 I can skip).

Can you give me so hints, how to program it dynamically? I was thinking to make something like this: Find the solution for array[0] and array[1] (that's easy there is only one solution from to 1 (1->3)) then add array[2], and find the best solution (1->5 also there is a solution 1->3->5 but that's going to cost me 2 moves) then for 4 points, 5 etc.

But don't know how to start to make my algorithm to be written correct and dynamic. I know I can make greedy algorithm, but that's not the point of the task... Can you give me any hints? How to start? How to keep solutions? and find the best ones?

答:
It would seem to me that, for the problem given, greedy is always the best.

However, in general, I would progress from left to right through the list, keeping a complete list of all the possibilities; if there are two or more possibilities that would land you at the same point, prune every possibility that is not the most efficient (depending on the question, you may also prune all but one of identically efficient solutions). Also regularly prune any solution which is a dead end.

So, for your example (I will list each possibility in brackets):

Move to the first item in your array - 1. You have to start here, so make this your list of possibilities: (1)

Move to the next item in your array - 3

For each item in your list of possibilities, copy it, add the item in your array, and then add it to the list of possibilities: (1),(1,3)

Eliminate any invalid possibilities, or possibilities which can never be valid (none yet)

For any pair of possibilities which end in the same place, strip all but the most efficient (none yet)

Move to the next item in your list - 5

For each item in your list of possibilities, copy it, add the item in your array, and then add it to the list of possibilities: (1),(1,3),(1,5),(1,3,5)

Eliminate any invalid possibilities, or possibilities which can never be valid (none yet)

For any pair of possibilities which end in the same place, strip all but the most efficient. (1,5) and (1,3,5) both end on 5, and (1,5) is more efficient, so delete (1,3,5).

Move to the next item in your list - 10

For each item in your list of possibilities, copy it, add the item in your array, and then add it to the list of possibilities: (1),(1,3),(1,5),(1,10),(1,3,10),(1,5,10)

Eliminate any invalid possibilities, or possibilities which can never be valid. (1,10) and (1,3,10) are invalid, and (1) and (1,3) will never be valid (hypothetically, (1,5) could be valid, if this 10 is followed by another 10). This leaves (1,5),(1,5,10)

For any pair of possibilities which end in the same place, strip all but the most efficient (none found).

Move to the next item in your list - 15

For each item in your list of possibilities, copy it, add the item in your array, and then add it to the list of possibilities: (1,5),(1,5,10),(1,5,15),(1,5,10,15),

Eliminate any invalid possibilities, or possibilities which can never be valid. (1,5,15) is invalid, and (1,5) will never be valid. This leaves (1,5,10),(1,5,10,15)

For any pair of possibilities which end in the same place, strip all but the most efficient (none found).

Wash, rinse, repeat.

So the general method is:

make things a little more complicated

remove any you can remove

ContentLicense: CC BY-SA 3.0

Title: Finding lowest cost path - dynamic


问:
How do I deal with global variables in existing legacy code (or, what's better, global hell or pattern hell)?
So... We have this fairly complex project (~10k LOC, but there's duplicated code so it's hard to tell) with hundreds of global variables. The project has more dependencies on other projects, and many other projects depend on it too. I have mostly inherited the responsibility to refactor just a part of this project by myself, an "enclosed section" of modules. None of the original developers remain.

I have devised a way to structure the routines in classes (breaking up megamoths, forming some class hierarchies, a little Strategy here and there, nothing too fancy (I hope); the objective is to make it easier for other developers to add functionality and make it possible to add proper unit tests).

My new classes provide calculations applied to currently-global arrays of data that are updated, and the calculations themselves need to maintain a state (a sum, the last value of the last processed vector, etc). You could see them as functors.

I'm unsure on how to deal with globals, though. I don't think I will be able change all globals to non-global because of the dependencies to other modules, which I'm not going to refactor just now. Also, many of my new classes will need to share data. So, I can...

For the globals that are not shared between my new classes, leave them as they are. I was thinking of using a Registry, or at the very least use some #define's or other variables to limit scope and provide context wherever they're used.

For the globals that will be shared between my new classes, either make a base class with the references, or use a Singleton to pass them around, or a combination of both.

I'm not sure if using these patterns will do more harm than good.

So, my question is: what's better, live with existing global variables or aggressively tune them with patterns like Singleton or Registry? Do you have any suggestions to these schemes, or have a better scheme?

答:
How far you go largely depends on the nature of the Globals. If they are mostly read and rarely modified (from only a few easy to find locations) , I would hesitate to make sweeping changes, and provide a framework around modifications, relying on documentation, programmer discipline and code review to ensure the framework is used.

If however the globals are changed from many locations or all the time (or both), you definitively need to get more aggressive with the refactor.

Singletons - IMHO a fancy name for a global to work around the "Globals are route of all evil" dogma and for languages such as Java that has no concept of global.  They will not assist significantly in this case, unless the pattern of use naturally tends towards a Singleton (From reading between the lines I doubt this is the case).

Registry - Better option, but less than ideal unless the items truly need to be global, and far from ideal if they are being written to regularly.

Have a careful look at these globals and firstly work out if they should be global. If there is no clear reason, any attempt to fix it is dealing with the symptom, not the cause - it will just be a pretty global. If you decide that fixing it (as in, making it not global) is not an option, valid reasons being "its not worth the effort" and "it might break other code in unexpected ways" etc, then putting a sticking plaster on it might be a good idea.

5K SLOC is not a large project - try dealing with 5 million SLOC in this state. With only 5K SLOC, a major refactor is not a large effort if you have good tool support.


答:
One way to slowly and relatively safely move from globals to no-globals might be to group globals into semi-reasonable classes as best you can.  Declare a global instance of the new class, with members that correspond to the globals you are replacing.  Remove the globals.  Wade through possibly massive numbers of compiler errors, changing each reference to the global to a reference to the corresponding member of the global instance.

Now you can gradually switch from having your classes know about the global instance of your new class directly, and instead kick the can down the road by having the global instance passed into them.  Over time you can hope to kick the can all the way to the end of the road, by removing all direct knowledge of the global instance from every class, and finally getting rid of the global instance, having effectively slowly replaced it by a registry or dependency injection (depending on what you did each time you removed direct knowledge of the global instance from one of your classes).

Note that every time one of your classes loses direct knowledge of how to find the global instance it becomes more modifiable and testable, even if the global instance still exists out there in your code base.  So you get some benefits without having to do all the work up front, which could take too long with a large code base if the global(s) are widely referenced.

Of course, you do have to finish doing everything in the first paragraph.  With a large code base you and your compiler could get to spend a lot of quality time together.

Title: How do I deal with global variables in existing legacy code (or, what's better, global hell or pattern hell)?

Body:
So... We have this fairly complex project (~10k LOC, but there's duplicated code so it's hard to tell) with hundreds of global variables. The project has more dependencies on other projects, and many other projects depend on it too. I have mostly inherited the responsibility to refactor just a part of this project by myself, an "enclosed section" of modules. None of the original developers remain.

I have devised a way to structure the routines in classes (breaking up megamoths, forming some class hierarchies, a little Strategy here and there, nothing too fancy (I hope); the objective is to make it easier for other developers to add functionality and make it possible to add proper unit tests).

My new classes provide calculations applied to currently-global arrays of data that are updated, and the calculations themselves need to maintain a state (a sum, the last value of the last processed vector, etc). You could see them as functors.

I'm unsure on how to deal with globals, though. I don't think I will be able change all globals to non-global because of the dependencies to other modules, which I'm not going to refactor just now. Also, many of my new classes will need to share data. So, I can...

For the globals that are not shared between my new classes, leave them as they are. I was thinking of using a Registry, or at the very least use some #define's or other variables to limit scope and provide context wherever they're used.

For the globals that will be shared between my new classes, either make a base class with the references, or use a Singleton to pass them around, or a combination of both.

I'm not sure if using these patterns will do more harm than good.

So, my question is: what's better, live with existing global variables or aggressively tune them with patterns like Singleton or Registry? Do you have any suggestions to these schemes, or have a better scheme?


问:
Include ignored file in the git repository
Suppose I'm setting up a website, and there are loads of images. These images won't change. But I would like that when any members of the team clone the project, they get the images so that they run the website immediately. Does this mean that I should add track the images as well? I'm just taking an example, it could be a jar in a java project or something else.</p>

答:
Yes, absolutely.  Track any file you need.  Git is more than happy to let you track non-source code files.

If you need something really big, you can also consider git annex. That versions which files are needed in git, but the files themselves are fetched separately, so their history does not take up space in everybody's repository.


问:
How is the publish-subscribe pattern different from gotos?
My understanding is that Goto statements are generally frowned upon. But the publish-subscribe pattern seems to be conceptually similar in that when a piece of code publishes a message, it performs a one-way transfer of control. The programmer may have no idea what parts of the program are subscribing to this message.

I have see something similar in a lot of JavaScript programs in which events are used to conveniently "hop" across modules. Am I missing something about the publish-subscribe or event-driven patterns?

答:
Yep, you are definitely missing something.  Gotos would typically be used, like you said, to  perform a one-way transfer of control.

However, events do not do that. When the code fires the event, it knows full well that once event is published (or processed, queued, fired... etc) code execution will resume on the very next line in the code that generated the event.

The use of goto creates a very tight coupling between the code that calls that statement and the code that's on the receiving end. Developer has to have intimate knowledge of both places in order to use goto.

On the other hand, code that fires events would typically not know or care who is interested in listening for that event. There could be a listener. Or there could be a 100 listeners or 0. Those listeners could be in the same program where event was fired, or they could be in a completely different application, or they could be on a different machine.  As far as the publisher is concerned, as soon as he generates the event his job is done.

If you are with me so far, what I described above is the ideal case of pub/sub pattern. Unfortunately in the real world things aren't always ideal and there are cases where publishers generates an event, a subscriber gets invoked, changes a whole bunch of state and by the time code execution returns back to the publisher "the world" appears to have been turned upside down.  And I'm sure you've run into this in the past, because this condition often arises when pub/sub pattern is implemented in a very simple fashion (e.g. via use of delegates or events in C#, or function/interface pointers in C/C++).

But this problem isn't necessarily pub/sub pattern but rather the implementation of it.  This is why many systems rely on queues so that when an event is published, it is simply queued up to be invoked later giving the publisher a chance to finish execution while the world is still intact.  When publisher is done doing it's work, an event loop (aka dispatch loop) will pop off the events and invoke subscribers.


问:
Design pattern for bidirectional signals/events
This problem feels rather basic, yet I've never known a great solution. I'm looking for a way for components in an application to notify each other while being as decoupled as possible (both at build/compile and run time), but also avoiding circular notifications in a way that components do not need to self-mitigate against. I happen to be hitting this issue (for the hundredth time) in JavaScript right now, but that is incidental.

Some means of decoupling include:

Dependency injection (DI). In this case I use require.js which allows, for instance, substituting mock implementations in unit tests by creating alternate require.config() setups.

Event dispatching. E.g. fooInstance.listen('action string', barInstance.actionHandler)

Publish/subscribe (aka pub/sub).

The last two are basically variants of the Observer pattern with different pros and cons.

The problem I want to solve is not specifically addressed by these patterns, and I'm not sure if its an implementation detail or if there is a pattern to apply:

fooObj sends a message (fires an event, whatever) that the "baz" property has changed

barObj.bazChanged() handles this event by calling its own setBaz() method

barObj.setBaz() fires an event that "baz" has changed

fooObj.bazChanged() handles this event ...

As a real case, imagine fooObj is a GUI component, with a slider for "tempo", and barObj is a music sequencing component that plays back a score. The slider should affect the tempo of the sequencer, but the score can contain tempo changes so when playing the sequencer should affect the slider position. A solution should be modeless.

One approach is to add guards, for example:

```<code>function handleTempoChanged(tempo) {
    if (this.tempo == tempo) return;
    ...
}
</code>```

This works but feels like a poor solution because it means every event handler needs to either assume it needs a guard, which is ugly boilerplate and often not required, OR needs to be aware of the other components in the system that would make a cycle possible. Arguably, this point is wrong, guards should always be used if the handler is going to fire a changed event directly or indirectly, but this still feels like boilerplate logic. This may be the only answer to my question...

Is there general case pattern to deal with potential cycles as described? Note that this is not about synchronous vs. asynchronous; either way the cycles can occur.

EDITED to reflect insight from commenters:

I realize it is possible to eliminate the boilerplate, using some sort of mixin. In pseudo-code:

```<code>class ObservablePropsMixin:

    // generic setter with gaurd
    function set(propName, value):
        if this[propName] = value: return
        this[propName] = value
        _fire(propName, value)

    // generic method to add listeners
    function observe(propName, handler):
        _observers[propName].add(handler)

    // private event dispatching method
    function _fire(propName, value):
        foreach observer in _observers[propName]:
            observer.call(propName, value)

    ...
</code>```

This is simplified to focus on my question, but a real mixin would implement other pubsub or event or signal semantics, analogous to any event dispatcher implementation. Components needing to be observers or observables would inherit/extend from the mixin (the above assumes some form of multiple or aggregate inheritance is possible in the language. This could be modified to work with composition instead, e.g. ObservableMixin.constructor(observedObject) rather than using "this".

答:
This is just a brief idea. I have not used or tested it myself.

In addition to a guard based on comparison of the current and the new value, circular notifications could be prevented by this scheme:

When a handler originates a property change, it asks the system for a unique event ID, and associate this property change with the event ID.

When another handler receives this property change, if it finds necessary to issue further property changes, it must "chain" the additional property changes with the original event ID, as well as attaching new event IDs to each additional property change. Thus, the event IDs will form a tree, with the original event at the root.

Each handler can store the event IDs it had finished processing, and thus prevent double-processing.

In some cases, a similar effect could be achieved by using a timestamp instead of a unique ID.

Note that this is a very heavy-weight option. I have not actually tested or used it, so it might not work as I had wished.

OwnerDisplayName: Jason Boyd


答:
There are a couple of differences. First, when a code executes GOTO, it gives up control, and there's no guarantee that it will regain control. A publisher in pub/sub, however, will keep running and performing its logic, sending off messages as appropriate. Its behavior is understandable and predicable.

Secondly, the subscriber will receive messages, and unlike with GOTO, the message itself carries context. Both the type of message, and any properties it carries, help tell the subscriber perform its role. And, after handling a message, the subscriber is still able to take new messages. So it's behavior too is understandable and predictable.

The big difference is that the publisher and subscriber have a well-defined flow of execution, and they will, in essence, keep looping and doing their jobs, while sending and receiving messages. Code with GOTOs can be well-written and orderly, but it can also degrade, and there isn't the same guarantee of clearly understood behavior.

You're right, though. Someone could write a pub/sub system with so many messages and so many little jumps that keeping track of the processing flow could become a nightmare. And on the other hand, you could write a system with GOTOs that behaves extremely orderly and is easily understood. (I'm thinking of assembly code for very complex systems before symbolic languages took over.)

But typically, the decoupling you gain from pub/sub simplifies the problem of distributed processing and decouples logic within your system. Also typically, straight-up GOTOs tend to create complicated systems where understanding the flow of control becomes problematic.

Title: How is the publish-subscribe pattern different from gotos?

Body:
My understanding is that Goto statements are generally frowned upon. But the publish-subscribe pattern seems to be conceptually similar in that when a piece of code publishes a message, it performs a one-way transfer of control. The programmer may have no idea what parts of the program are subscribing to this message.

I have see something similar in a lot of JavaScript programs in which events are used to conveniently "hop" across modules. Am I missing something about the publish-subscribe or event-driven patterns?


问:
How does jQuery's mechanism of event handlers work
I'm in the need of widen my perspective on the framework libraries, to be able to make well aware choices of if/which/when to add a framework to a website.

One thing that got my attention was event handlers, as they seems to be somewhat more complex structured.

For me, in the early days, an event handler were added inline with its element ...

Later on they were removed from being inline and added globally document/element.onlick = "DoSomethingOnClick or document/element.onlick = "function() {...}

As of today, the frameworks add their own mechanism on top and I am trying to grasp what/how that actually means/is done.

By studying code parts it appears to me, and here describe in a VERY simple way, that they add the onclick event similar to above global and then pass the event when raised, into their own handler, which itself is an object structure containing stored/added functions and elements and their relationships.

Is this a correct observation? If not, then how is it done?

Can this be showed with a simple written sample in Javascript?

Based on the following quote,

"You can use the jQuery on method to attach an event handler to the document, and pass it a filter string that will cause your handler only to fire when the event happens on an element that match the filter, and with the matched element as this value."

how is the element that triggered the event identified in the handler (by the event object or ?) and how are the elements to be fired stored/identified?

Do the other frameworks, other than jQuery, have a very much different structure of their implementation of event handlers?

答:
jQuery has an internal queue of all the handlers it has attached for a particular event on a particular element. The first time you bind an event to that element it initializes the queue and uses addEventListener to bind the event to jQuery's generic event-handling function. When the event is triggered, the function uses event.target to determine which element it is, and then finds the queue of handlers associated with it and calls them in the order that they were added.

The on method of delegation is nested on top of this. It takes advantage of event bubbling: when an event occurs, it's triggered on the specific target element and also all its containing elements. You bind the handler to a container, and it saves the selector string in the queue entry. When it's processing that entry in the handler queue, it tests whether event.target (which is still the specific element that you clicked on) matches the selector, and then executes the handler function. This mechanism allows you to bind handlers for elements that have not yet been added to the DOM; it's particularly useful when you have a list of elements that is updated dynamically (e.g. adding rows to a table).

ContentLicense: CC BY-SA 4.0


问:
Is it bad practice to update an object in a static method?
Still learning .net and OOP and have a basic question I hope. This is an asp.net mvc app.

Looking at the code below, I am most concerned with the line in CheckShippingVendor that says ValidateDelivery(shipmentItem). Is it okay to pass in an object as a parameter and have the private static method update that item.

When I did a resharper Extract Method refactoring this is what it did for me.

Class is instantiated and call the CheckShippingVendor method:

```<code>var packageStatus = _inventoryService.CheckShippingVendor(shipmentId, shipmentFile);
</code>```

Here is the rest of the code:

```<code>public PackageStatus CheckShippingVendor(string shipmentId, mvFile shipmentFile)
{
        var packageStatus = new PackageStatus();
        using (var shipmentItem = shipmentFile.Read(shipmentId))
        {
                ValidateDelivery(shipmentItem);
                shipmentFile.Write(shipmentId, shipmentItem);
        }
        return packageStatus;
}

private static void ValidateDelivery(mvItem shipmentItem)
{
        int shipped;
        var shippedResult = Int32.TryParse(shipmentItem[1].ToString(), out shipped);
        if (!shippedResult)
            return;

        int delivered;
        var deliveredResult = Int32.TryParse(shipmentItem[57].ToString(), out delivered);
        if (!deliveredResult)
            return;

        shipmentItem.Message = "NO INFORMATION AT THIS TIME";
}
</code>```

答:
It is acceptable for a static method to modify a class passed in as a parameter.  After all, this is what extension methods do.

Where people get into trouble is attempting to store state in static variables and modifying and using that state through static methods.

In your specific case, the ValidateDelivery method is doing three things - validating shipment, validating delivery and assigning delivery status.

I would consider placing the validation code on the object (mvItem) itself.  If this can't be done, then consider writing an extension method to do so.  In my mind it makes a lot more sense to ask the item itself whether it's a valid delivery or not.

```<code>private static void ValidateDelivery(mvItem shipmentItem)
{
  if (shipmentItem.IsShipped() && shipmentItem.IsDelivered())
  {
    shipmentItem.Message = "NO INFORMATION AT THIS TIME";
  }
}

public static bool IsShipped(this mvItem shipmentItem)
{
    int shipped;
    return Int32.TryParse(shipmentItem[1].ToString(), out shipped);
}

public static bool IsDelivered(this mvItem shipmentItem)
{
    int delivered;
    return Int32.TryParse(shipmentItem[57].ToString(), out delivered);
}
</code>```

This, to me, separates out your concerns much more nicely.

Body:
It is acceptable for a static method to modify a class passed in as a parameter.  After all, this is what extension methods do.

Where people get into trouble is attempting to store state in static variables and modifying and using that state through static methods.

In your specific case, the ValidateDelivery method is doing three things - validating shipment, validating delivery and assigning delivery status.

I would consider placing the validation code on the object (mvItem) itself.  If this can't be done, then consider writing an extension method to do so.  In my mind it makes a lot more sense to ask the item itself whether it's a valid delivery or not.

private static void ValidateDelivery(mvItem shipmentItem)
{
  if (shipmentItem.IsShipped() && shipmentItem.IsDelivered())
  {
    shipmentItem.Message = "NO INFORMATION AT THIS TIME";
  }
}

public static bool IsShipped(this mvItem shipmentItem)
{
    int shipped;
    return Int32.TryParse(shipmentItem[1].ToString(), out shipped);
}

public static bool IsDelivered(this mvItem shipmentItem)
{
    int delivered;
    return Int32.TryParse(shipmentItem[57].ToString(), out delivered);
}

This, to me, separates out your concerns much more nicely.


问:
Are object oriented programming languages procedural?
Procedural programming means coding the application is a series of tasks. Do A, then do B, then Do C. And often wrap these tasks in procedures or functions that can be easily called and run several times in the code.

Object Oriented Programming is also often done by doing A, then doing B, then doing C. But objects are used (and correct me if I'm wrong because I'm not sure) as sophisticated ways to store, manipulate and hide data. This affects significantly the design of the program. But the overall flow of the application is still do A, then do B, then do C.

Do you agree? If so, would you say that OOP is essentially a type of Procedural Programming?

答:
Object Oriented languages are not required to be procedural, OCaml (or F#) is an Object Oriented language that is fundamentally functional.

Now most Object Oriented languages are imperative and procedural but possess features or frameworks that allows some Aspect / Behavioral / Functional programming inside them, in C# for instance you can use lambda and anonymous methods for functional programming, attributes (annotations) for declarative programming, and post-compilation IL modifications for Aspect programming.


答: There's no harm in updating objects in static methods, Static methods belong to class, not to object. You need static method when you need to provide common functionality to all objects or  memory optimization, because if you create a new object for accessing only a single method, it's memory wasting and increasing overhead in memory management. </p>

Title: Is it bad practice to update an object in a static method?

Body:
Still learning .net and OOP and have a basic question I hope. This is an asp.net mvc app.

Looking at the code below, I am most concerned with the line in CheckShippingVendor that says ValidateDelivery(shipmentItem). Is it okay to pass in an object as a parameter and have the private static method update that item.

When I did a resharper Extract Method refactoring this is what it did for me.

Class is instantiated and call the CheckShippingVendor method:

```<code>var packageStatus = _inventoryService.CheckShippingVendor(shipmentId, shipmentFile);
</code>```

Here is the rest of the code:

```<code>public PackageStatus CheckShippingVendor(string shipmentId, mvFile shipmentFile)
{
        var packageStatus = new PackageStatus();
        using (var shipmentItem = shipmentFile.Read(shipmentId))
        {
                ValidateDelivery(shipmentItem);
                shipmentFile.Write(shipmentId, shipmentItem);
        }
        return packageStatus;
}

private static void ValidateDelivery(mvItem shipmentItem)
{
        int shipped;
        var shippedResult = Int32.TryParse(shipmentItem[1].ToString(), out shipped);
        if (!shippedResult)
            return;

        int delivered;
        var deliveredResult = Int32.TryParse(shipmentItem[57].ToString(), out delivered);
        if (!deliveredResult)
            return;

        shipmentItem.Message = "NO INFORMATION AT THIS TIME";
}
</code>```


问:
Security in Authentication in single page apps
What's the most secure method of performing authentication in a single paged apps? I'm not talking about any specific client-side or server-side frameworks, but just general guidelines or best practices. All the communications are transfered primarily through sockJS.

Also, OAuth is out of the question.

答: Check this post Using OAuth2 in HTML5 Web App. @jandersen answer gives a good explanation on using Resource owner password credentials flow in single page applications. In any case, the prefered flow for this apps should be the Implicit grant. In fact, @jandersen 's response on the referenced post is about tweaking Resource owner password credentials to act as something close to the Implicit grant.</p>


问:
"Property Container" design-pattern in-depth definition
Could anybody, please, explain what is a Property Container or at least where can I get information about that pattern on the Internet?

I've found that it exists as one of the Fundamental patterns in this article.
Unfortunately, it is not described in the corresponding English article.
The only thing is a short description in Wikipedia that I've tried to approximately translate below:

This pattern allows to add additional properties for the class in
  container (inside the class), instead of extending the class with the
  new properties.

If a short example is possible in PHP / C# / C++ or Java, it would be quite useful for understanding.

P.S.: It seems like it has been described in "SanFrancisco(TM) Design Patterns: Blueprints for Business Software", but I don't have access to it. Google does not help or I'm searching with the wrong keywords...

答:
I've written my PHP implementation for “Property Container” design-pattern.
(https://codereview.stackexchange.com/q/43485/36845)

Be sure to check recommendations that were suggested in the "answer" post as well.


答:
Another approach (graph search):

Step 1: Parse initial data

Consider each point is a node of and each possible move is a path between two nodes.

Create a N*N matrix(graph) and compute the path value between each nodes.

path(A,B) = 1 : if abs(nodeA - nodeB) <= 5

else

path(A,B) = MAXINT

Step 2: Compute the shortest path

Apply a fast graph search algorithm (eg: Dijkstra's algorithm) to your matrix.

Title: Finding lowest cost path - dynamic

Body:
I have to write a dynamic algorithm for finding lowest cost path. So I have a point that I have to visit. I can jump only between points by distance - 5 I have an array of distance from 0-point for example (1 3 5 10 15 20 21 22). Each move cost me 1. So the best path will be to move 1->5->15->20->22 (3 and 21 I can skip).

Can you give me so hints, how to program it dynamically? I was thinking to make something like this: Find the solution for array[0] and array[1] (that's easy there is only one solution from to 1 (1->3)) then add array[2], and find the best solution (1->5 also there is a solution 1->3->5 but that's going to cost me 2 moves) then for 4 points, 5 etc.

But don't know how to start to make my algorithm to be written correct and dynamic. I know I can make greedy algorithm, but that's not the point of the task... Can you give me any hints? How to start? How to keep solutions? and find the best ones?


问:
Where to keep track of batch editing scripts?
It is sometime useful to write a script to perform a batch editing on
several files in a source tree.  Such a script is usually very
specific and used only once.

Such scripts can be used to rework some identifiers in code, modify
file header comments, edit the path of a resource or the like.  I want
to stress that I am concerned by the case where the script addresses
an exceptional problem, so that it does not fit in the usual workflow
of the project.

I think it is important to keep record of these scripts and reference
the usage of the script in the RCS logbook.  Where is the appropriate
place to keep this record?

Should they be added to the commit description in the RCS logbook?
Should they be added to the ticket description of the item being
processed when they are used?  Should they be saved as regular files
in the project and added to the RCS, despite the fact their usage is
deemed to be unique? Is there another way?

答:
Description of a usage scenario of a script should not be buried in the log record of your RCS, it should be part of the documentation of the script. For small scripts, its not unsual that this doc is just a few line of comments at the beginning of the script itself.

Where you keep the script itself depends on your general source code structure. Maybe you have special a "tools" or "scripts" folder in your source code tree and keep the script there. Its not even necessary to keep "throw away" scripts in your RCS as part of your regular source code; if you have a different versioning strategy for your development tools in general, the scripts may be placed in the environment of those tools.

Make sure you choose a place which fits nicely into your existing structure, where you can find the scripts when you need them again, and where they don't disturb your working process as long as you don't need them.


问:
Architecture of a "website generator" web application
What is the most maintainable and efficient way to architect a web application who's purpose is to host and generate websites which can be customized to a certain degree?

There are a lot of these style of applications in the wild that generate all kinds of sites, from sites that host World of Warcraft guilds to other sites that do wedding site hosting. My question is, what is the basic architecture that these sites operate on?

I imagine there are two ways of thinking about this. A central set of code that all sites on the host run against, and it acts differently based on which site was visited. In this manner, when the base code is updated all sites are updated simultaneously.

Or, the code for an individual site exists in a silo, and is simply replicated to a new directory each time a site is created.  When an update needs to be applied, the code is pushed out to each site silo.

In my case, I am working in PHP with the CodeIgniter framework, however the answer need not be limited to this case. Which method (if any) creates a more maintainable and efficient architecture to manage this style of web application?

答:
There is a third option that is a hybrid of the two you expose.

The sites are generated dynamically from the database and the result is stored in a cache for a defined period of time. You can view this architecture in two ways:

Dynamic system with a cache.

Static system that its runs to regenerate the website in a defined period of time.

The funny thing its that its the same thing, You have the scalability of a static system and the flexibility of a dynamic system, a think that this is the way the majority of this sites are build. Very similar to CQRS architectural pattern.


问:
Regarding interpreters
I understand that an interpreter could do one of the following things (and probably more):

Execute programming-language source code directly.

First translate the source code to some intermediate code (which is less human-readable and more efficient or easier for the interpreter to execute), and then execute this code.

My questions are:

Is this assumption true? Am I understanding correctly the general function of an interpreter? Or is something I wrote wrong?

If my assumptions are true, which one of these two possible functions are more common? Please show examples.

答:
An interpreter is generally understood to execute a program without compiling the program in a separate step. However, most modern interpreters do not interpret the source code directly – this isn't really possible anyway for anything more complex than BASIC. Instead, they first parse the code, then produce an intermediate representation, and finally execute this representation.

Common intermediate representations are:

bytecode, which is a high-level cousin of machine code. They are executed on a virtual machine that uses this bytecode. The bytecode is not generally human-readable, although a human-readable serialization may exist (e.g. Jasmin assembler for JVM bytecode).

A language implementation may choose bytecode because it's essentially similar to most existing architectures, albeit more restricted, and thus safer. It is also really simple to store bytecode in a file, or interchange it otherwise. Most VMs execute bytecode (starting with the original P-Code, over CPython to the JVM).

other opcodes, e.g. in-memory data structures like ASTs. These sometimes do not have any permanent serialization.

A language implementation may choose to represent the code as a data structure because this is a lot more flexible (just as Lisp is more flexible than C), and because it removes the need to decode bytecodes inside the VM – making it simpler to implement. This route is most useful for simple projects, but is also used in some serious interpreters like perl.

In practice, the boundary between compilers and interpreters has been blurred beyond recognition, and most interpreters could also be considered compilers because they compile to some intermediate representation (even if it isn't stored anywhere). The two useful distinguishing characteristics are:

when the source is compiled – ahead of time, or before each execution

what the compilation target is – machine code, some intermediate representation executed by a VM

Some implementations like the primary Java implementations defy overly simple categorization: Here, code is compiled ahead of time to a bytecode which is interpreted on a VM which may also perform JIT compilation to machine code.

Title: Regarding interpreters


答:
Object Oriented languages is more a clarification on how data is encapsulated, not how the flow of control is programmed. Scala for instance supports both functional and procedural programming styles, where one may manually run a function on each item in a array through a loop

```<code>var arr = Array(<data>)
for(item <- arr) {
   foo(item)
}
</code>```

Or one could simply tell the array it should run the function

```<code>arr.foreach(foo)
</code>```

OOP is encapsulating and separating code, which should allow better finding of bugs, and keeping bugs more confined.

Procedural is programming one thing after another, where in functional one would rather tell what should happen rather then the exact order that it should happen.

Maybe look at this question What exactly is procedural programming? How exactly is it different from OOP? Is it the same as functional programming?

Title: Are object oriented programming languages procedural?

Body:
Procedural programming means coding the application is a series of tasks. Do A, then do B, then Do C. And often wrap these tasks in procedures or functions that can be easily called and run several times in the code.

Object Oriented Programming is also often done by doing A, then doing B, then doing C. But objects are used (and correct me if I'm wrong because I'm not sure) as sophisticated ways to store, manipulate and hide data. This affects significantly the design of the program. But the overall flow of the application is still do A, then do B, then do C.

Do you agree? If so, would you say that OOP is essentially a type of Procedural Programming?

Body:
Object Oriented languages is more a clarification on how data is encapsulated, not how the flow of control is programmed. Scala for instance supports both functional and procedural programming styles, where one may manually run a function on each item in a array through a loop

var arr = Array(<data>)
for(item <- arr) {
   foo(item)
}

Or one could simply tell the array it should run the function

arr.foreach(foo)

OOP is encapsulating and separating code, which should allow better finding of bugs, and keeping bugs more confined.

Procedural is programming one thing after another, where in functional one would rather tell what should happen rather then the exact order that it should happen.

Maybe look at this question What exactly is procedural programming? How exactly is it different from OOP? Is it the same as functional programming?


问:
Should a class validate argument using external method/service with unit testing?
I have a class that runs as a service and returns html code of a website when supplied with a URL.

The code:

```<code>public interface IHtmlDownloader
{
    IWebProxy Proxy { get; set; }
    string UserAgent { get; set; }

    string GetHtml(string url)
}

public class HtmlDownloader : IHtmlDownloader
{
    WebClient _client;

    public IWebProxy Proxy
    {
        get { return _client.Proxy; }
        set { _client.Proxy = value; }
    }

    public string UserAgent
    {
        get
        { return _client.Headers[HttpRequestHeader.UserAgent].ToString(); }
        set
        { _client.Headers[HttpRequestHeader.UserAgent] = value; }
    }

    public HtmlDownloder()
    {
        _client = new WebClient();
    }

    public string GetHtml(string url)
    {
        this.CheckValidity(url);

        var htmlOfWebsite = _client.DownloadString(url);

        return htmlOfWebsite;
    }
}
</code>```

Now I am not sure how exactly I should validate the URL. I know that it should not be null or whitespace or anything else, but should I validate that it is indeed a properly built URL?

Doing so would result in a method which would perform the validation. I could simply create a public static method inside HtmlDownloader so that the caller can validate the URL, or maybe even not a static one (GetUrl(string url) is after all called after the object has been instantiated), but it would be wrong for at least two reasons:

It would be a validator applicable in so many places, and it should be available to other classes.

I can't contract a static method with an interface.

Furthermore, it shouldn't be made static, but rather a service, so I could unit test HtmlDownloader (service would be injected through the constructor).

All of those ideas are quite dreadful and I am starting to think, that I shouldn't validate anything, but simply create a try/catch block that would catch the proper exception and then throw a UrlNotFoundException with the original exception supplied through InnerException.

Still, it would be nice to check for the validity of the URL. But to whom and how? Should the caller be injected with the proper service? But then, what if the URL is generated higher than the caller and the caller simply passes it on to the HtmlDownloader? Where should I validate the URL? Or is the simple fact that the URL have to passed through a few levels a code smell?

答:
In my opinion the service should validate the URL so that it can return an error describing the misuse. You can't rely on the caller running validation and ensuring it passes you valid parameters.  I imagine that's probably taken as read and you weren't suggesting that the thing calling the service defines the validation.

Moving on, validation of generic properties should be handled with a generic mechanism.

Assuming first of all that you're implementing a small number of services:

If your language provides you with the construct then use it directly in this code.

If it's not available I'd say implement one that can be called statically and call that instead - I.E. treat it as if it was a standard language construct.

It's simple and straightforward and only starts to cause a problem if you have a lot of services and a lot of duplication.

In terms of TDD:

Let's say you implemented the static method UrlValidator::validate - either it's a full blown implementation or it wraps up the available language construct to make it nicer to use.  That's not important - it's just a static method.

This can be tested exhaustively in its own unit test.  You can throw a thousand test cases at it to make sure it behaves exactly as you require.

Then, when you are testing the service HtmlDownloader you then only need to test the validation enough to convince yourself that you are correctly using the UrlValidator.  For example, ensure an obviously valid email address passes, an obviously invalid email address fails.

This is kind of similar to what you would do with Dependency Injection except you have an assumption - you test enough to convince yourself that your assumption is correct.  With DI you directly test that the assumption is correct.

And fair enough, DI might make this a little easier to test and the test more robust, but it seems like overkill for such a simple issue - particularly if you are only implementing a small number of services.

In my opinion it should be HtmlDownloaders responsiblity to define that it needs a valid URL, and if that's the case it's not just the case of injecting a UrlValidator, but of injecting something that can validate whatever you ask it to.

Which leads me onto to the "if you're implementing a lot of services" case.

In this situation it is probably worthwhile implementing a generic parameter validation package.  Something that you can inject into HtmlDownloader, so that it can pass in a configuration and the data received and get back a validation state.

E.g. you might pass in something like (pseudo-code):

```<code>{ url = { required = true
        , dataType = ValidationTypes::URL }
}
</code>```

The implementation of the validation lives outside the service, but the service cleanly defines what needs to be validated, and what the requirements are.

This massively reduces the testing required because you now only need to test that the configuration is correct, rather than testing the effect of it.

I like implementations like this, it's just that it's sometimes overkill for the kind of solution you need.

It a question of scale and required flexibility.

Body:
In my opinion the service should validate the URL so that it can return an error describing the misuse. You can't rely on the caller running validation and ensuring it passes you valid parameters.  I imagine that's probably taken as read and you weren't suggesting that the thing calling the service defines the validation.

Moving on, validation of generic properties should be handled with a generic mechanism.

Assuming first of all that you're implementing a small number of services:

If your language provides you with the construct then use it directly in this code.

If it's not available I'd say implement one that can be called statically and call that instead - I.E. treat it as if it was a standard language construct.

It's simple and straightforward and only starts to cause a problem if you have a lot of services and a lot of duplication.

In terms of TDD:

Let's say you implemented the static method UrlValidator::validate - either it's a full blown implementation or it wraps up the available language construct to make it nicer to use.  That's not important - it's just a static method.

This can be tested exhaustively in its own unit test.  You can throw a thousand test cases at it to make sure it behaves exactly as you require.

Then, when you are testing the service HtmlDownloader you then only need to test the validation enough to convince yourself that you are correctly using the UrlValidator.  For example, ensure an obviously valid email address passes, an obviously invalid email address fails.

This is kind of similar to what you would do with Dependency Injection except you have an assumption - you test enough to convince yourself that your assumption is correct.  With DI you directly test that the assumption is correct.

And fair enough, DI might make this a little easier to test and the test more robust, but it seems like overkill for such a simple issue - particularly if you are only implementing a small number of services.

In my opinion it should be HtmlDownloaders responsiblity to define that it needs a valid URL, and if that's the case it's not just the case of injecting a UrlValidator, but of injecting something that can validate whatever you ask it to.

Which leads me onto to the "if you're implementing a lot of services" case.

In this situation it is probably worthwhile implementing a generic parameter validation package.  Something that you can inject into HtmlDownloader, so that it can pass in a configuration and the data received and get back a validation state.

E.g. you might pass in something like (pseudo-code):

{ url = { required = true
        , dataType = ValidationTypes::URL }
}

The implementation of the validation lives outside the service, but the service cleanly defines what needs to be validated, and what the requirements are.

This massively reduces the testing required because you now only need to test that the configuration is correct, rather than testing the effect of it.

I like implementations like this, it's just that it's sometimes overkill for the kind of solution you need.

It a question of scale and required flexibility.


问:
What makes a language Turing-complete?
What is the minimal set of language features/structures that make it Turing-complete?</p>

答:
A programming language is turing complete if you can do any calculation with it.  There isn't just one set of features that makes a language turing complete so answers saying you need loops or that you need variables are wrong since there is languages that has neither but are turing complete.

Alan Turing made the universal turing machine and if you can translate any program designed to work on the universal machine to run on your language it's also Turing complete. This also works indirectly so you can say language X is turing complete if all programs for turing complete language Y can be translated for X since all universal turing machine programs can be translated to a Y program.

The time complexity, space complexity, easy of input/output format and easy of writing any program is not included in the equation so such machine can theoretically do all calculations if the calculations are not halted by power loss or Earth being swallowed by the sun.

Usually to prove turing completeness they make an interpreter for any proven to be turing complete language but for it to work you need means of input and output, two things that are really not required for a language to be turing complete. It's enough that your program can alter it's state at startup and that you can inspect the memory after the program is halted.

To make a successful language it needs more than turing completeness though and this is true for even turing tarpits. I don't think BrainFuck would have been popular without , and ..

Title: What makes a language Turing-complete?


答:
Is this assumption true? Am I understanding correctly the general function of an interpreter? Or is something I wrote wrong?

It is true, in theory.  But a practical interpreter will do at least some work to translate the source code into an intermediate code of some kind.

If my assumptions are true, which one of these two possible functions are more common? Please show examples.

The latter.  In fact, I'm not aware of any real-life examples that directly execute the source code ... though some primitive BASIC interpreters might have worked that way.

Of course, the intermediate code could take a variety of forms.  It code take the form of instructions for an (imaginary) machine; e.g. Java bytecodes, Pascal PCODE, Microsoft CLR, and so on.  Or it could take the form of an abstract syntax tree ... with decorations.

Title: Regarding interpreters

Body:
I understand that an interpreter could do one of the following things (and probably more):

Execute programming-language source code directly.

First translate the source code to some intermediate code (which is less human-readable and more efficient or easier for the interpreter to execute), and then execute this code.

My questions are:

Is this assumption true? Am I understanding correctly the general function of an interpreter? Or is something I wrote wrong?

If my assumptions are true, which one of these two possible functions are more common? Please show examples.


答:
what's better, live with existing global variables or aggressively tune them with patterns like Singleton or Registry? Do you have any suggestions to these schemes, or have a better scheme?

A better scheme would be dependency injection with no globals (or statics) whatsoever.

Old code:

```<code>int DEFAULT_QUUX = 5;

int main() {
    Blip b;
    b.do_stuff(); // makes DEFAULT_QUUX = 6
    Qlip q;
    q.do_things(); // reads DEFAULT_QUUX
}
</code>```

New code:

```<code>int main() {
    int quux = 5; // no longer global
    Blip b{quux};
    quux = b.do_stuff(); // returns 6
    Qlip q;
    q.do_things(quux); // quux is dependency injected.
}
</code>```

If the hypothetical Blip and Qlip use or communicate with other objects in their implementation, and those objects need "quux" or other globals, these should be injected into the call chain from the top.

Body:
what's better, live with existing global variables or aggressively tune them with patterns like Singleton or Registry? Do you have any suggestions to these schemes, or have a better scheme?

A better scheme would be dependency injection with no globals (or statics) whatsoever.

Old code:

int DEFAULT_QUUX = 5;

int main() {
    Blip b;
    b.do_stuff(); // makes DEFAULT_QUUX = 6
    Qlip q;
    q.do_things(); // reads DEFAULT_QUUX
}

New code:

int main() {
    int quux = 5; // no longer global
    Blip b{quux};
    quux = b.do_stuff(); // returns 6
    Qlip q;
    q.do_things(quux); // quux is dependency injected.
}

If the hypothetical Blip and Qlip use or communicate with other objects in their implementation, and those objects need "quux" or other globals, these should be injected into the call chain from the top.


问:
Mocking static methods
Having recently returned from a Test Driven Development (TDD) course I had the following thought.

While writing unit tests using Mockito we came up against of the problem of mocking static methods. It was suggested by one developer we use PowerMock, which allows mocking of static methods, and then we got into a big discussion on how we should approach this problem.

However, in my experience static methods should only really be used as utility type methods. The classic example in java being Math.random().

So a static method should only, execute one defined action regardless of any interaction with a class instance. If this is not the case, and you require class instance interaction, your method should not be static and you need to rethink your design.

So my question is, with this in mind should you need to mock static methods at all? If they are always performing a simple action, then surely you should just call them as you would in real code.

答:
So my question is, with this in mind should you need to mock static
  methods at all? If they are always performing a simple action, then
  surely you should just call them as you would in real code.

Yes, if the code is properly written. Sometimes it isn't, and you still need to test it. Refactoring can be very time-consuming (statics are typically associated with high coupling and other no-nos), so this is kind of a workaround.

Refactoring could be not only unfeasible, but impossible. The static method might be out of your reach - what if your code has to call a static method from a third party library, and it's not stateless, takes a long time to execute, has special requirements (database, web access)... In order to test your code you need to mock this method.

Title: Mocking static methods


问:
How do you respond to "Tell me a little bit about yourself." question in interviews?
I've been asked this in a few interviews. And it always catches me off guard.My professional and academic background are already in the resumé, which the interviewer has obviously looked at. What more to tell him/her? Should I start with my hobbies? I like gardening, or looking at NSFW pictures on reddit in my free time?

What and how do you answer to this specific question? Do you have a prepared answer for it? Am I wrong if I think this question is a bit silly?

UPDATE There have been a lot of great answers to this question. I'm in pickle which to choose as the 'correct' answer, because most of them are very insightful. I found a great writing on this subject matter. It's a bit crazy for my taste, but it's interesting:

How To Introduce Yourself… I Mean Practically

答:
Talk about you, your studies, your hobbies, your ambitions, your past projects...

Sometimes it's hard to talk about yourself, but don't worry!

We're all humans so it doesn't have to be completely strict, privacy has died, just don't show you're a fool.

ContentLicense: CC BY-SA 2.5


答:
Generally speaking, @KonradMorawski's answer is good and complete. However, I would like to add that there is one scenario that I would consider it valuable to mock static methods - the static factory method.

Personally, in my code I very infrequently use static factory methods; I only use them if the created object is stateless, the factory is stateless, and the created object has no dependencies - and even then I'm still not very likely most of the time. Otherwise, I use an instance of a factory object, which can then be mocked.

The issue with using a static factory method as provided is that the created objects will not be mocks or spys, which means you will not be able to call verify on them, and you will not control access to these objects in advance. For example consider a math application like the following:

```<code>public abstract class ComplexNumber {
    private double realPart;
    private double imaginaryPart;
    ComplexNumber(double realPart, double imaginaryPart) {
        this.realPart = realPart;
        this.imaginaryPart = imaginaryPart;
    }
    public static ComplexNumber create(double realPart, double imaginaryPart) {
        return new ComplexNumber(realPart, imaginaryPart);
    }
}

public class RootCalculator {
    // Whatever is appropriate
    public List<ComplexNumber> roots(double... coefficients) {
        // somewhere in the code
        ComplexNumber number = new ComplexNumber(something, somethingElse);
        // blah blah
    }
}

public class RootCalculatorTest {
     @Test
     public testCalculator() {
         RootCalculator calc = new RootCalculator();
         List<ComplexNumber> roots = calc.roots(1, 0, 1); // equivalent to x^2 + 1 = 0
         for(ComplexNumber number : roots) {
             // verify(...);
         }
     }
}
</code>```

Note that you can't call verify on the returned complex numbers, nor can you verify that the factory method itself was called the correct number of times. With PowerMock you can do both. Note that using PowerMock here is superior to just calling new ComplexNumber().

Of course the best way to do it is just inject an instance of a factory, which can then be mocked, avoiding PowerMock and allowing you to do all the normal testing behavior.

Title: Mocking static methods

Body:
Having recently returned from a Test Driven Development (TDD) course I had the following thought.

While writing unit tests using Mockito we came up against of the problem of mocking static methods. It was suggested by one developer we use PowerMock, which allows mocking of static methods, and then we got into a big discussion on how we should approach this problem.

However, in my experience static methods should only really be used as utility type methods. The classic example in java being Math.random().

So a static method should only, execute one defined action regardless of any interaction with a class instance. If this is not the case, and you require class instance interaction, your method should not be static and you need to rethink your design.

So my question is, with this in mind should you need to mock static methods at all? If they are always performing a simple action, then surely you should just call them as you would in real code.

Body:
Generally speaking, @KonradMorawski's answer is good and complete. However, I would like to add that there is one scenario that I would consider it valuable to mock static methods - the static factory method.

Personally, in my code I very infrequently use static factory methods; I only use them if the created object is stateless, the factory is stateless, and the created object has no dependencies - and even then I'm still not very likely most of the time. Otherwise, I use an instance of a factory object, which can then be mocked.

The issue with using a static factory method as provided is that the created objects will not be mocks or spys, which means you will not be able to call verify on them, and you will not control access to these objects in advance. For example consider a math application like the following:

public abstract class ComplexNumber {
    private double realPart;
    private double imaginaryPart;
    ComplexNumber(double realPart, double imaginaryPart) {
        this.realPart = realPart;
        this.imaginaryPart = imaginaryPart;
    }
    public static ComplexNumber create(double realPart, double imaginaryPart) {
        return new ComplexNumber(realPart, imaginaryPart);
    }
}

public class RootCalculator {
    // Whatever is appropriate
    public List<ComplexNumber> roots(double... coefficients) {
        // somewhere in the code
        ComplexNumber number = new ComplexNumber(something, somethingElse);
        // blah blah
    }
}

public class RootCalculatorTest {
     @Test
     public testCalculator() {
         RootCalculator calc = new RootCalculator();
         List<ComplexNumber> roots = calc.roots(1, 0, 1); // equivalent to x^2 + 1 = 0
         for(ComplexNumber number : roots) {
             // verify(...);
         }
     }
}

Note that you can't call verify on the returned complex numbers, nor can you verify that the factory method itself was called the correct number of times. With PowerMock you can do both. Note that using PowerMock here is superior to just calling new ComplexNumber().

Of course the best way to do it is just inject an instance of a factory, which can then be mocked, avoiding PowerMock and allowing you to do all the normal testing behavior.


答:
Mock static methods is a bad idea, i use only if i'm testing legacy code and i can't refactor for whatever reason. But in a normal development TDD cycle its a bad smell.

I always remembers one phrase from Ian Cooper "test things you want to preserve", when you are mocking a static you are stating in our test that do you want to preserve not the functionality, you want to preserve this design with a static method call. Are you sure you want to preserve this?

Title: Mocking static methods


问:
Most efficient data structure for implementing inheritance structure without classes
I have a number of types that all relate to each other in terms of them being 'derived' from one another. I'd need a way to do is relationships, which made me initially think of classes, but I realized that other than the is relationships, there would be no reason to use classes as each 'type' of data function the exact same way. I'd also thought of enums, but since there is no way to extend or inherit from enums it was a poor choice.

For context (this being my specific example):
I have a number of different kinds of resources that all are 'types' so that they can be used in conjunction with an int to denote how much of that resource is available. I have several different kinds of these resources, such as foods, metals, building materials etc. Within the food category would be something like wheat or corn; under metals would be copper, iron, gold etc. Since all of these are still just 'resources' and have no actual functionality other than typing, it seems pointless to use classes and OO inheritance.

How would I implement this kind of data type without resorting to using classes?

答:
If there are no functions to inherit, composition of structs may be more favorable than class inheritance.  The concept of "composition over inheritance" may apply here, see:

Wikipedia

Popular SO Answer to this issue

Although the above examples use classes, an alternative implementation could use structs:

Composition with C structs


问:
Which license retains copyright while allowing work to be shared and derived from?
I am working on an academic research project whose results and some code we intend to publish. Research journals and conferences explicitly require that the authors have copyright over the work done in a paper. However, I would like to share the code with the community as it progresses using an open source license.

Is there a license that explicitly retains copyright while allowing sharing, redistribution and derivative works based on the original work?

Alternatively, which license would be suitable for such projects?

答:
The only "license" where you don't retain copyright is when you release a work as public domain. With all other copyright licenses, you retain copyright to your work.

Additionally, you are also allowed to publish your own work under multiple licenses, so you can distribute the source under one license to the magazine and under a different license to the general public.

The only thing you have to keep in mind is, if you accept contributions from the public to your code, the copyright on those contributions is retained by the respective contributers, unless they explicitly assign the copyright over to you. This means that you might not be able to use the contributions in your article.


答:
What you described is very much possible without checking is relationships.

An object oriented design should rely on interfaces, not implementations. That means, code like this:

```<code>if (o is Derived1)
{
    do_something_with_derived1(o);
}
else if (o is Derived2)
{
    do_something_with_derived2(o);
}
</code>```

Should be turned into

```<code>o.do_something_virtual(context);
</code>```

Essentially, you move the responsibility of "doing something" from the caller to the callee. The caller only triggers this action. The callee knows its own type and can act accordingly. If there is any context on the calling site that you would use in the operation, you pass that as a parameter.

The key here is the virtual method, which allows for a dynamic dispatch. This removes the strong dependency to each implementation and "type checking" boilerplate on the calling site. The calling site can even call future implementations.

Another possible approach is a data driven design. Entity Component systems are a flexible solution that can be used to avoid complicated class hierarchies when each base class would only add a little bit of functionality (in your example: the kind and amount of resource).

Title: Most efficient data structure for implementing inheritance structure without classes

Body:
I have a number of types that all relate to each other in terms of them being 'derived' from one another. I'd need a way to do is relationships, which made me initially think of classes, but I realized that other than the is relationships, there would be no reason to use classes as each 'type' of data function the exact same way. I'd also thought of enums, but since there is no way to extend or inherit from enums it was a poor choice.

For context (this being my specific example):
I have a number of different kinds of resources that all are 'types' so that they can be used in conjunction with an int to denote how much of that resource is available. I have several different kinds of these resources, such as foods, metals, building materials etc. Within the food category would be something like wheat or corn; under metals would be copper, iron, gold etc. Since all of these are still just 'resources' and have no actual functionality other than typing, it seems pointless to use classes and OO inheritance.

How would I implement this kind of data type without resorting to using classes?

Body:
What you described is very much possible without checking is relationships.

An object oriented design should rely on interfaces, not implementations. That means, code like this:

if (o is Derived1)
{
    do_something_with_derived1(o);
}
else if (o is Derived2)
{
    do_something_with_derived2(o);
}

Should be turned into

o.do_something_virtual(context);

Essentially, you move the responsibility of "doing something" from the caller to the callee. The caller only triggers this action. The callee knows its own type and can act accordingly. If there is any context on the calling site that you would use in the operation, you pass that as a parameter.

The key here is the virtual method, which allows for a dynamic dispatch. This removes the strong dependency to each implementation and "type checking" boilerplate on the calling site. The calling site can even call future implementations.

Another possible approach is a data driven design. Entity Component systems are a flexible solution that can be used to avoid complicated class hierarchies when each base class would only add a little bit of functionality (in your example: the kind and amount of resource).


问:
UI design for changing multiple records at once
I have a desktop application where the user has tabular views on some data records. Now we got the requirement to let the user select multiple of these records at the same time and let the him edit some properties of the selected records all at once in a separate edit dialog. The idea is

to change only the properties the user really want change

to keep all other properties unchanged

Furthermore, when the user has selected the records and opens the edit dialog, the properties with equal values in all of the selected records are shown in the corresponding UI fields, the other properties should be shown as "undefined" as long as the user does not start to enter something there. After pressing "Ok", the changes are applied to the records. This kind of UI behaviour is not "rocket science", we already found this, for example, in diagram editors (where you can select multiple drawing elements at once and change their properties.)

The problem is how to visualize the "undefined" state in an intuitive manner, especially for text properties. For boolean values, this is easy: we use just a tri-state check box. For number values, this is easy, too: the "undefined" state is displayed as an empty numeric UI field, and if there is actually a number in there, the state is "defined".

But how shall one design this for text properties? An empty text box field is actually not an "undefined" state, since many of the text properties can actually be empty. One could add a separate check box beside each text box to indicate the difference between "undefined" and "defined", but since our edit dialog contains already check boxes for boolean properties, this seems to be counterintuitive and confusing to the user.

If this matters, we are using Winforms (but I think this problem is not specfic to the actual UI framework).

答:
I agree that a checkbox could puzzle the user.

My reaction to the problem of how to display an undefined text box and differentiate it from a valid but empty one is to use a placeholder for the undefined one and an empty one for the other.

The valid empty box will look normal to the user and the normal-ness will be reinforced when the user tries to use it.  The placeholder box will have a placeholder message "type something here" that is greyed out or muted in some way so that it's clear to the user that it's not an actual value.  This notion that it's temporary will be reinforced when the user enters the box and the placeholder text vanishes.

We see this behaviour frequently on the web so it should seem intuitive to the user and shouldn't make them think.

The other thing is that you could consider IF the users need to know there's a difference.  If not, then both boxes could be left empty.


问:
What's the difference between lists constructed by quote and those constructed by cons in Scheme?
```<code>(define ls1 '((1 . 2) 1 . 2))
(set-car! (car ls1) 6)
ls1
(define ls2 (cons '(1 . 2) '(1 . 2)))
(set-car! (car ls2) 6)
ls2
</code>```

After set-car!ing, ls1 will be ((6 . 2) 1 . 2) and ls2 ((6 . 2) 6 . 2). It seems that ls1 and ls2 have different storage model, and what does it mean when someone says x is bound to a list? is x stand for a starting address or location like that a is the starting address of a[10] in C?

答:
Quote

Quote returns data which you should not modify, and which may share structure between themselves.
E.g. if you have a file which contains

```<code>(define l1 '(1 2 3))
(define l2 '(4 2 3))
</code>```

then the compiler is permitted to allocate l1 and l2 in a way that they share their common tail (cdr l1) and (cdr l2) and/or in the read-only memory.

Modification of such lists is undefined behavior.
Do not do it.

list

list and cons create fresh objects (different from everything which already exist), they allocate and populate memory. You own them - you can modify them as much as you want.

Your case

Both your set-car! calls are wrong - you are modifying read-only data and thus triggering undefined behavior (i.e., you are lucky your computer did not blow up in your face :-).

Specifically, in the first case, ls1, you get what you would get if you did the right thing, i.e.,

```<code>(define ls1
  (cons (cons 1 2)
        (cons 1 2)))
</code>```

while in the second case the implementation allocated only one cons cell (1 . 2) and re-used it in creating ls2, i.e., you see what you would see if you evaluate the following (legal) code:

```<code>(define ls2
  (let ((l (cons 1 2)))
    (cons l l)))
</code>```

If there were print-circle in scheme, you could see the data re-use:

```<code>[1]> (let ((l (cons 1 2)))
        (cons l l))
((1 . 2) 1 . 2)
[2]> (setq *print-circle* t)
T
[3]> (let ((l (cons 1 2)))
        (cons l l))
(#1=(1 . 2) . #1#)
</code>```

Binding

x is bound to a value means that the name x refers to the object, the same way in all languages.

The difference in Lisp/Scheme is what the object is.

Here it is the first cons cell of the list - as you have probably seen many times, a (linked) list is a chain of cons cell, where car contains the value and cdr contains the next cons cell in the list.

Body:
Quote

Quote returns data which you should not modify, and which may share structure between themselves.
E.g. if you have a file which contains

(define l1 '(1 2 3))
(define l2 '(4 2 3))

then the compiler is permitted to allocate l1 and l2 in a way that they share their common tail (cdr l1) and (cdr l2) and/or in the read-only memory.

Modification of such lists is undefined behavior.
Do not do it.

list

list and cons create fresh objects (different from everything which already exist), they allocate and populate memory. You own them - you can modify them as much as you want.

Your case

Both your set-car! calls are wrong - you are modifying read-only data and thus triggering undefined behavior (i.e., you are lucky your computer did not blow up in your face :-).

Specifically, in the first case, ls1, you get what you would get if you did the right thing, i.e.,

(define ls1
  (cons (cons 1 2)
        (cons 1 2)))

while in the second case the implementation allocated only one cons cell (1 . 2) and re-used it in creating ls2, i.e., you see what you would see if you evaluate the following (legal) code:

(define ls2
  (let ((l (cons 1 2)))
    (cons l l)))

If there were print-circle in scheme, you could see the data re-use:

[1]> (let ((l (cons 1 2)))
        (cons l l))
((1 . 2) 1 . 2)
[2]> (setq *print-circle* t)
T
[3]> (let ((l (cons 1 2)))
        (cons l l))
(#1=(1 . 2) . #1#)

Binding

x is bound to a value means that the name x refers to the object, the same way in all languages.

The difference in Lisp/Scheme is what the object is.

Here it is the first cons cell of the list - as you have probably seen many times, a (linked) list is a chain of cons cell, where car contains the value and cdr contains the next cons cell in the list.


答:
If you wrote the code, you are the copyright owner. If you are writing the code in a "work for hire" situation, they are the copyright owners. As of 1989, copyright ownership is automatic, and stating it is optional. I believe it is also prudent.

As a copyright owner, you can (according to Wikipedia):

produce copies or reproductions of the work and to sell those copies (including, typically, electronic copies)

import or export the work

create derivative works (works that adapt the original work)

perform or display the work publicly

sell or cede these rights to others

transmit or display by radio or video.

You may license your work to somebody else, and in the license, you can grant any or all of the rights of copyright to the licensee. You can also make these copyright grants free, or conditional upon payment of license fees. Licenses can also be time-limited.

In your case, you want to share. Assuming that there are no patents involved in your work, I would go with:

the GPLv2 license if you want your code to be forever free to study and improve, and all derivative works to also be free to study and improve. (Programmers and academics usually prefer this one).

the MIT license if you want anybody to be able to freely use your code, but allow them to keep their derivative works secret. (Commercial software vendors tend to like this one better).

If there are patents involved, the licensee is responsible for also acquiring patent licenses for relevant patents.

If there are patents (which you own) which you also want to freely release with this software, use:

the GPLv3 license - For the same reasons as GPLv2.

the Apache 2.0 license - For the same reasons as the MIT license.

In all of these cases you retain copyright ownership, and the code can be shared.

Title: Which license retains copyright while allowing work to be shared and derived from?

Body:
I am working on an academic research project whose results and some code we intend to publish. Research journals and conferences explicitly require that the authors have copyright over the work done in a paper. However, I would like to share the code with the community as it progresses using an open source license.

Is there a license that explicitly retains copyright while allowing sharing, redistribution and derivative works based on the original work?

Alternatively, which license would be suitable for such projects?


问:
How do I deal with global variables in existing legacy code (or, what's better, global hell or pattern hell)?
So... We have this fairly complex project (~10k LOC, but there's duplicated code so it's hard to tell) with hundreds of global variables. The project has more dependencies on other projects, and many other projects depend on it too. I have mostly inherited the responsibility to refactor just a part of this project by myself, an "enclosed section" of modules. None of the original developers remain.

I have devised a way to structure the routines in classes (breaking up megamoths, forming some class hierarchies, a little Strategy here and there, nothing too fancy (I hope); the objective is to make it easier for other developers to add functionality and make it possible to add proper unit tests).

My new classes provide calculations applied to currently-global arrays of data that are updated, and the calculations themselves need to maintain a state (a sum, the last value of the last processed vector, etc). You could see them as functors.

I'm unsure on how to deal with globals, though. I don't think I will be able change all globals to non-global because of the dependencies to other modules, which I'm not going to refactor just now. Also, many of my new classes will need to share data. So, I can...

For the globals that are not shared between my new classes, leave them as they are. I was thinking of using a Registry, or at the very least use some #define's or other variables to limit scope and provide context wherever they're used.

For the globals that will be shared between my new classes, either make a base class with the references, or use a Singleton to pass them around, or a combination of both.

I'm not sure if using these patterns will do more harm than good.

So, my question is: what's better, live with existing global variables or aggressively tune them with patterns like Singleton or Registry? Do you have any suggestions to these schemes, or have a better scheme?

答:
One serious issue with globals all over the place can be that the global variable is reused to control different "subsystem" depending on the current context of your program.
So what can you do:

Add a global Registry class for the global variables.

Check if the resposibility for the global variable is really only for one domain by testing the software ( for instance in a debugger or a unittest ).

Check if it makes sense to split the resposibility of the global variable.

And you should try to build automatic tests when you are refactoring this on unit- or integration-test-level.

Kim


问:
Correct Seam for Stub

In Chapter 3 of his book The Art of Unit Testing: with Examples in C#, Roy Osherove illustrates the issue of undesirable external dependencies in code under test.

He shows this with a method named IsValidLogFileName which takes in a filename string as an argument, reads in a config file from the local filesystem and checks whether the given filename extension exists in the config file. Here's what such a class would look like:

```
   public class LogAnalyzer
    {
        public bool IsValidLogFileName(string fileName)
        {

            string [] extensions = System.IO.File.ReadAllLines(@"C:\Users\Public\ext.config");

            foreach (string ext in extensions)
            {
                if (fileName.EndsWith(ext))
                {
                    return true;
                }
            }
            return false;
        }
    }
```

The issue here is that testing IsValidLogFileName has a dependency on the local filesystem.

The author introduces the concept of stubs as a means of removing this dependency. In particular,
he describes the following design:

Create an interface:

```
    interface IExtensionManager
    {
        bool IsValid(string fileName);
    }
```

an implementing production class:

```
    class FileExtensionManager : IExtensionManager
    {
        bool IsValid(string fileName)
        {
            string [] extensions = System.IO.File.ReadAllLines(@"C:\Users\Public\ext.config");

            foreach (string ext in extensions)
            {
                if (fileName.EndsWith(ext))
                {
                    return true;
                }
            }
            return false;
        }
    }
```

a stub:

```
    class FakeExtensionManager : IExtensionManager
    {
        bool IsValid(string fileName)
        {
            string [] extensions = { "txt", "c", "cpp", "cs"};

            foreach (string ext in extensions)
            {
                if (fileName.EndsWith(ext))
                {
                    return true;
                }
            }
            return false;
        }
    }
```

refactor LogAnalyzer as follows:

```
   public class LogAnalyzer
    {
        IExtensionManager em;

        public LogAnalyzer(IExtensionManager extensionManager)
        {
            em = extensionManager;
        }

        public bool IsValidLogFileName(string fileName)
        {
            return em.IsValid(fileName);
        }
    }
```

run production code like this:

```
    LogAnalyzer la = new LogAnalyzer(new FileExtensionManager);
```

and test code like this:

```
    LogAnalyzer la = new LogAnalyzer(new FakeExtensionManager);
```

The part I don't understand is why we have to extract the validation logic
from the original IsValidLogFileName by making an ExtensionManager interface.
Wouldn't it make more sense to create something like a ConfigManager interface
and refactor as follows:

interface:

```
    interface IConfigManager
    {
        string [] GetFileExtensionConfig();
    }
```

an implementing production class:

```
    class LocalConfigManager : IConfigManager
    {
        string [] GetFileExtensionConfig( )
        {
            return System.IO.File.ReadAllLines(@"C:\Users\Public\ext.config");
        }
    }
```

a stub:

```
    class FakeConfigManager : IConfigManager
    {
        string [] GetFileExtensionConfig( )
        {
            string [] extensions = { "txt", "c", "cpp", "cs"};
            return extensions;
        }
    }
```

refactor LogAnalyzer as follows:

```
    interface IExtensionManager
    {
        bool IsValid(string fileName);
    }
```0

run production code like this:

```
    interface IExtensionManager
    {
        bool IsValid(string fileName);
    }
```1

and test code like this:

```
    interface IExtensionManager
    {
        bool IsValid(string fileName);
    }
```2

答:
It does, and this type of thing is roughly what Dependency Injection is all about, but.. as you've seen it starts to get really quite complex even for such a simple, simple function that you're describing. Imagine what it would be like if every class in a large program was made as complex as this!

Now its not so bad using DI in practice as you tend to use it for certain layers of configuration and they have tools to help you manage it all, but it still is more complex than just writing the code.

The problem really is that you cannot just replace the System.IO.File.ReadAllLines call in your tests using the traditional unit testing tools. Ideally, you'd write a test and simply tell the compiler to use a different ReadAllLines call temporarily. Turns out you can do this, use Fakes from Microsoft. This uses a low-level approach to rewrite the compiled code (in a way reminiscent of hackers replacing calls to copy protection with nothing). So you can literally replace the system calls in your tests. The classic example is replacing calls to DateTime.Now() with whatever you want the current time to be.

Frankly, I would scrap all your stub creation testing tools and use Fakes across the board. The old-technology tools that rely on interfaces are obsolete and need to die so you can write the code the way you started (nice and simple) without having to mangle it in artificial ways just to please the tools. Fakes allows you all the benefits of simple, clean code with all the benefits of isolated unit tests!

Title: Correct Seam for Stub


问:
Organisation by business function vs technical function
I am designing a large application (a static code analyser) and I have a choice in how to organise the code into modules:

One approach is by what I'd call by technical function. This is where you have a package for data objects, another for service functions, views, controllers, etc.

Another approach is what I'd call by business function. This where you'd have a package for, say, stock control, another for product listings, customer orders, etc.

Most frameworks tend to push me towards the first approach. Sometimes there are technical reasons for this, e.g. if the view is written in JavaScript and the rest in Python, you really need to keep it separate. But mostly it is just a matter of convention.

Sometimes organising by technical function results in spreading related code across the application. If I have code to support a product, I end up with ProductModel, ProductService, ProductView, etc. Often I feel it would be neater to simply have a Product object that does all these.

Organising by business function has issues too. Some classes are borderline and it's quite arbitrary which package you put them in. And there are some support objects that are used across all business functions.

Which approach will be the most effective for making a scalable and maintainable application?

答:
I usually organize by "business function" (problem domain).  If you are trying to use objects to represent relationships between "things" in the "real world", then "Products", "Orders", etc. more directly map to what the user knows (the domain language) and should be more intuitive for you to discuss, write, and maintain.

There will always be cross-cutting concerns.  Easy examples would be exceptions, logging, and database connections.  You can usually extract those "services" to objects or interfaces of their own.

Essentially you end up with two types of classes: domain specific objects (products, orders) and cross-cutting objects (exceptions, persistence, data views).  I don't know if this is the official best-practice, but you can see a similar concept in the .NET framework organization.  Domain-specific objects would be like Strings, Data Adapters, etc.  Cross-cutting objects and interfaces would be like IEnumerable or Exceptions.


问:
Is the Adapter the correct design pattern for this situation?
I have an instance of a class UntouchableClass of which I need to access the member variables to use in my DotLiquid template. Problem is, UntouchableClass has to inherit from Drop if I want to use it in my template, but I can't change it since it is from an existing library.

I've read about the Adapter pattern, but UntouchableClass does not have an interface from which to inherit the Adapter.

Also, I can't use multiple inheritance (I would create a class which inherits from both UntouchableClass and Drop but this is C# and from what I know this isn't possible).

Is there a design pattern that would suit this situation? Or is there a particular way to do this using DotLiquid?

答:
Yes, the adapter pattern is appropriate here. Looking at the wikipedia article for the Adapter pattern, there are two versions, the 'Object Adapter Pattern' and the 'Class Adapter Pattern'. In the Object Adapter Pattern, the adapter contains an instance of the adapted class, whereas in the Class Adapter Pattern, the adapter inhereits from the adaptee.

The limitation you describe would most likely prevent you from using the Class Adapter Pattern. However, you should still be able to use the Object Adapter Pattern. You simply need to have an instance of the class you want to adapt (the appropriate way to instantiate and persist it would most likely depend on the situation). Every method you want to override or implement from Drop could then be a method call on the wrapped adaptee object.

OwnerDisplayName: Deinonychus

OwnerDisplayName: Ben Aaronson