答:
You could argue that a curve is simple if there are no two line segments between points such that the lines intersect, meaning you could check if a curve is simple by verifying the absence of this condition.

The algorithm would look something like:

```<code>for each p1, p2 in pointlist
  for each p3, p4 in pointlist
     if line_segment(p1, p2) intersects line_segment(p3, p4)
        return false
return true
</code>```

Note that p2 would be the successive point after p1 and similarly, p4 would be the successive point after p3.  In order to avoid redundancy, points p3 and p4 could start after points p1 and p2.  This should be easily done in O(n^2) time.  Be careful in your check for intersection since at least once the lines will be the same (no dividing by zero).

If you have many such points, you could skip every other point and this algorithm will run 4 times faster at the small risk that a truly intersecting line may not be detected should the curve approach a tangent.

Title: How to determine if set of ordered coordinates form a simple curve?

Body:
I hope it is the right place to ask this. I wasn't sure if it belongs to Stack Overflow or Computer Science.

Eventually this seemed more suitable.

Anyway, some background first:

A closed curve, is a curve with no endpoints and which completely encloses an area.

A simple curve, is a curve that does not cross itself.

Example:

Now, given n ordered (x,y) coordinates that represents mouse movement, it is easy to determine if they form a closed curve (given an upper bound on the allowed distance between two points, of-course), but is there an algorithm that will determine whether or not the coordinates form a simple curve?

I tried to look online for an answer, but couldn't find relevant solutions.

Body:
You could argue that a curve is simple if there are no two line segments between points such that the lines intersect, meaning you could check if a curve is simple by verifying the absence of this condition.

The algorithm would look something like:

for each p1, p2 in pointlist
  for each p3, p4 in pointlist
     if line_segment(p1, p2) intersects line_segment(p3, p4)
        return false
return true

Note that p2 would be the successive point after p1 and similarly, p4 would be the successive point after p3.  In order to avoid redundancy, points p3 and p4 could start after points p1 and p2.  This should be easily done in O(n^2) time.  Be careful in your check for intersection since at least once the lines will be the same (no dividing by zero).

If you have many such points, you could skip every other point and this algorithm will run 4 times faster at the small risk that a truly intersecting line may not be detected should the curve approach a tangent.


问:
Resetting vs. re-sending forgotten passwords
When a user forgets their password, is it better practice to reset the password and email that to the user or just to email the current password to the user's email address.</p>

答:
You should never be in a position to send a user their password. All passwords should be stored in a hashed format, with a sufficiently good hash function that recovering the original password is computationally infeasible.

As for password resets, it depends on the application. If it's a web application, send a time-limited, use-once password reset link and have the user give you a new password. If it's not a web application, it gets a little bit trickier.

ContentLicense: CC BY-SA 3.0


问:
Which patterns/architecture to apply for "Import Data, Process Data, Export Result"
I was wondering which architecture/patterns to choose for the following problem divided into three steps:

Import TestScript Description from File (e.g. .xls, .txt)

Process Described TestScript

Export Description with processed Results as .xml

Here is what I got so far:

Importer that reads in xls and creates a hierarchical object structure

Parser that creates an Abstract Syntax Tree (If,then,else,end,command) from the object structure

A Processor (VisitorPattern) of the AST. This Processor instantiates the command implementation, executes the command, collects the results and controls the flow (if, then, else)

Currently the imported object structure already contains a field for the result and can just be serialized out as xml. But in my opinion it's not very elegant having a result field in the input objects.

The main reason I don't like it is that I can not reuse the imported object structure in order to process it multiple times. I would like to divide the whole component also into three parts:

Import, which creates an hierarchical object structure that describes the TestScript (containing a fileparser and a preprocessor)

Process, which creates an AST and processes it

Export, which takes the results and the descriptions and writes it out

Here a few other conditions:

Not every AST Node represents an object in the object structure (description)

But each result object is connected to an description object

Description and Results are hierarchical

答:
Outputting results embedded in the TestScript Description seems excessive. If the results thus written are preventing the TestScript Description from being reused without an edit to remove them, then, the architecture is silly.

Output specifications belong in the Description. The typical test pattern I've seen all my life is that the test has a name, that name is included in the output to identify what the test does. An individual test result should identify what was done, what was expected, what was actually found. The test name usually suffices for what was done, but the expected value, accepted range and actual value are good things to see in the output.

If there's doubt or uncertainty that the expected setup from the Description results in the right objects, a very verbose output mode might cause the Abstract Syntax Tree to be written out to the output. Pause-on-fail or a single step mode that pauses at the point the pass/fail evaluation is made can freeze the system at the moment of decision, and allow the developer or another developer or test maintainer, etc, to look around and be sure the setup from the Description has been correctly assembled.

Reproducing the Description, verbatum, in the output, saves a putative user from having to open an edit/display window for the Description as well as the Output. I sense good will, but unexpressed desires.


问:
Should points of tech debt be counted in a team's velocity?
Tech debt doesn't have a direct business value until the improvements are seen against other stories being delivered quicker.  Achieving or failing sprints affects morale and delivery in the long run too, so if necessary tech debt causes sprints to fail or velocity to drop.

While it's going to be different for each organisation, is velocity a measure for the team or for the business and is "pure" tech debt with no business impact expected to be measured in a team's velocity?

答:
Velocity is defined as "number of units of work completed in a certain interval". To implement a unit of work, you typically have an existing part of software and add some new code and/or change some existing code. When the existing part of software contains a lot of technical debt, and you have to deal with it to implement a change, one would expect to need more time to complete a unit of work. On the other hand, the creation of new technical debt happens often in expectation to need less time to complete a unit of work in the current sprint.

So what is measured here depends always on the team and the actual code base (and probably the whole organization around it). There is nothing like an absolute "velocity of the team".

However, if your question is if there should be units of work dealing only with the removal of technical debt, and if they should be counted the same way as units-of-work for business requirements, then it should be obvious that mixing those two things up might give you a wrong picture about your team's real development speed. In fact, you have to decide for yourself if you want to measure how fast your team works, or how fast your team can deliver new business value. To my experience, most customers prefer to pay for the business value they get.

ContentLicense: CC BY-SA 4.0


问:
Domain object model: query by id vs object
Let assume I have two simple model classes: Product and Brand

It is obvious I have a query method in Product  class like this

```<code>Product product = Product.findById(123);
</code>```

What if, I want to query products by brand?

```<code>ArrayList<Product> products = Product.findByBrand(234);
// or
ArrayList<Product> products = Product.findByBrand(new Brand("ABC", 234));
</code>```

Assume 234 is the brand ID in the database.

I assume the 2nd way of writing make the method more easy to test as I can mock the Brand class in my unit test, right?

答:
For unit-testing the findByBrand method, there is no real difference between passing in a Brand object or just an ID.

The difference is more relevant for the code calling findByBrand.

In the large majority of cases, that code should already be dealing with Brand objects, so passing that as an argument to findByBrand makes the most sense.

The only reason for findByBrand to accept a plain ID would be if (nearly) all current and expected callers are already naturally working with Brand-IDs without having corresponding Brand objects.


问:
How should an API or server respond when a device connects with a different account than it is bound to?
In my system we have users accounts and user devices. Rules:

A user can have only one user account.

Each user can have many devices.

A device can be bound to only one user account.

Upon initial installation, when adding new device, or after a "master reset", the user must provide the login and password to his/her account to bind this particular device to the account. After that, the device sends a unique token with each request and is recognized by that token.

So the normal situation is that Device A is bound to User A and time goes on. This question pertains to the situation later on, when a request from Device A is made using the credentials for User B.

What should happen in this situation? How should the API / server respond when it detects that a device already bound to one user account is trying to rebind itself to another account?

Let's use Dropbox as an example. What would happen when someone uninstalls the Dropbox client on one of their computers previously used with account A, then reinstalls it with credentials for account B? The local client would be pointing to a Dropbox folder containing some files but trying to sync it with an account that has a completely different set of files. Note that I haven't tested such a situation. I'm not willing to and I'm not interested in learning how Dropbox handles this; I'm only using this as an example to help describe my situation.

What I have come up with so far:

Treat this as a normal situation and automatically rebind the device to the account as requested. But wouldn't this make a mess in the database in terms of what user sees or has access to (stats, data, history etc.)?

Treat this as an error situation. Assume that to rebind a device to another account, it must first be unbound from its previous account. If user can't access their "old" (previous) account due to lost password etc., he/she should use the password reset form or contact support.

Something different. Not mentioned above.

After doing some thinking and a little research I'm pretty convinced that option two is the best solution for me, but I'd like to know anyone foresees any major problems with this approach. Is there any reason I shouldn't follow option 2?

Edit: This system deals with non-computer devices; Dropbox is just an example. In my scenario 95% of devices are always used by the same user and are not shared among others. My assumption is that this situation can only occur as an result of error or intentional, but unsupported actions (hacking, checking what will happen if, etc.).

答:
The scenario you describe assumes that when the software is re-installed on a device, that your system will recognize that device as having been seen before. This will only happen if, as part of the registration, the device must send some hardware identification.

If you don't use such pre-existing hardware identifications, but you assign an ID after registration, then your scenario will not occur. In that case, if the software is re-installed and registered with a different account, then it will just appear that a new Device B is registered (for user B) and that Device A never connects again.

If you do use pre-existing hardware identification to identify devices, then you are putting up a serious barrier for people that share a computer (with each their own account) to use your services.


答:
A lot of questions of this kind depend heavily on the actual business domain, and it's not clear that we have enough information to make a good decision.

any rebind is treated as non-normal situation

This comment suggests that it may make the most sense to send back a error response (e.g. 400 Bad Request) with a description of the reason you're not processing the request.

Having said that, is there any real benefit in requiring a manual process to deal with this situation? Do you for example require some kind of audit to determine if the device transfer is valid? Is the information that the user works with in your application tied to the device to an extent that you want to protect that information from another user who may not have authorized access to the device? In other words, the answer really depends on your business rules.

As an example to show that the answer depends on the business, in a system I'm working on we also link a unique device ID (mostly for phones) to a user account. If we receive a request from a device for a different user account than it is currently linked, we rebind and move on, because specific device ownership isn't really relevant in our system, only that it is bound to some account.

Title: How should an API or server respond when a device connects with a different account than it is bound to?

Body:
In my system we have users accounts and user devices. Rules:

A user can have only one user account.

Each user can have many devices.

A device can be bound to only one user account.

Upon initial installation, when adding new device, or after a "master reset", the user must provide the login and password to his/her account to bind this particular device to the account. After that, the device sends a unique token with each request and is recognized by that token.

So the normal situation is that Device A is bound to User A and time goes on. This question pertains to the situation later on, when a request from Device A is made using the credentials for User B.

What should happen in this situation? How should the API / server respond when it detects that a device already bound to one user account is trying to rebind itself to another account?

Let's use Dropbox as an example. What would happen when someone uninstalls the Dropbox client on one of their computers previously used with account A, then reinstalls it with credentials for account B? The local client would be pointing to a Dropbox folder containing some files but trying to sync it with an account that has a completely different set of files. Note that I haven't tested such a situation. I'm not willing to and I'm not interested in learning how Dropbox handles this; I'm only using this as an example to help describe my situation.

What I have come up with so far:

Treat this as a normal situation and automatically rebind the device to the account as requested. But wouldn't this make a mess in the database in terms of what user sees or has access to (stats, data, history etc.)?

Treat this as an error situation. Assume that to rebind a device to another account, it must first be unbound from its previous account. If user can't access their "old" (previous) account due to lost password etc., he/she should use the password reset form or contact support.

Something different. Not mentioned above.

After doing some thinking and a little research I'm pretty convinced that option two is the best solution for me, but I'd like to know anyone foresees any major problems with this approach. Is there any reason I shouldn't follow option 2?

Edit: This system deals with non-computer devices; Dropbox is just an example. In my scenario 95% of devices are always used by the same user and are not shared among others. My assumption is that this situation can only occur as an result of error or intentional, but unsupported actions (hacking, checking what will happen if, etc.).


答:
One way of looking at velocity is to think of it as "the amount of work that can be completed in a given amount of time". Assuming that fixing technical debt is actual work, it should be counted.

You must remember that velocity is just a tool to help you work better. If adding technical debt to you velocity helps you, do it. If it doesn't, don't. The only reason to track velocity s to help you plan better. If you ignore work that you actually do, that doesn't help IMHO.

Title: Should points of tech debt be counted in a team's velocity?

Body:
Tech debt doesn't have a direct business value until the improvements are seen against other stories being delivered quicker.  Achieving or failing sprints affects morale and delivery in the long run too, so if necessary tech debt causes sprints to fail or velocity to drop.

While it's going to be different for each organisation, is velocity a measure for the team or for the business and is "pure" tech debt with no business impact expected to be measured in a team's velocity?


问:
Do serialization functions belong in a model or a controller?
I'm developing an application where:

Models keep data as a multi-dimensional array, which are saved as-is to a MongoDB database. The model is used to provide methods to manipulate the data, and outside of those methods, the data properties are read-only.

The model factory instantiates each object in a standardized way and allows shorthand "queries" to look up a database entry and instantiate an object with it at once.

The "view" is Javascript, and all it does it ask the controller for certain things, and the controller responds over HTTP with JSON.

The controller uses the model factory to instantiate model objects and do whatever the view is requesting, if possible. It always returns JSON.

Generating that JSON is currently in a "helper" class, which I'm trying to eliminate. The serialization of MongoDB data involves converting MongoDates, MongoIDs, and other Mongo objects to strings. It's needed in the controller to output these to the browser as strings - for the most part, the controller knows how to output data to the view. But in some cases, it's needed in the model to tabulate multi-dimensional array data into a list before the controller gives it to the browser. The controller doesn't know enough about the model to do that tabulation.

Is a helper class unavoidable here? Or should 100% of serialization take place inside of the model? Should I leave the serialization function in the abstract model and use it from the controller with a static call?

答:
I think the serialization to JSON is a web concern (infrastructure), not necessarily a model concern. So invoking a helper from the controller to do the serialization is fine, I would regard it as desirable. It handles a pretty clear concern, I think it's a valid component.

The tabulation you mention however sounds like it is a model thing, I would avoid doing implicit model tranforms during the serialization step. See if the controller can ask for this tabulated model directly or if the model can supply it transparently if you don't want the controller to know about it. Either way make sure the data is fully prepared before you give it to the serializer. If the tabulation is specific to one view I might do this tabulation in a 'view model' that I situate between the views and the (domain) model.


问:
Decrypt data on any Windows computer by same user
I have a license system which currently locks licenses to a physical computer using CryptProtectData (with CRYPTPROTECT_LOCAL_MACHINE) and CryptUnprotectData. This is of course not the entire license system, it's just the part that confirms if the license can run on this computer (the license itself is encrypted with another encryption method).

Currently I take something like a string "allowed" and encrypts it on the client machine with CryptProtectData. This is then sent together with other data as a "license request" to a license server. A license is then returned with this data untouched and saved on the client machine. If the client license system then runs CryptUnprotectData and gets "allowed" back when using that license on that machine it knows it's a valid machine.

However I've come to the conclusion that it would be better if the license could follow the user instead of the machine. This can be done with CryptProtectData but only on a roaming profile which I don't think is very common.

So what I'm looking for is some method other than CryptProtectData where a Windows user can encrypt data on computer A and then successfully decrypt it on computer B (A and B being in the same Windows domain) without any roaming profiles. Maybe some user id can be requested from Windows and used as a key for encryption?

I was looking around and came across the Windows domain user SID. Could this be used to securely identify a user or can it be manipulated? Perhaps it's not unique over separate networks?

答:
This is a fundamental problem for licensing: there is simply no way to enforce that it is the same user once you allow multiple machines, because there is no credential to verify identity.

It is also a heavily studied problem.  It is unlikely that you are going to improve on the solutions that major software companies have invested millions in.  I would just survey existing solutions and pick one that meets your needs best (none is going to be perfect).

A couple of examples of fairly heavyweight solutions that allow software to follow a user:

Require a physical USB key for use of the software. This is probably the strongest way to do it, but obviously expensive and a pain for you and users.

Encryption based on machine, but allow multiple machines in a managed way.  The user is required to register with you online for each new machine.  You can limit the number of machines per user. Or you can revoke access to old copies (requiring them to move the software rather than just unlock a new copy) if you are willing to require internet connectivity for license verification on an ongoing basis.


问:
Is Visitor Pattern valid in this scenario?
The goal of my task is to design a small system which can run scheduled recurring tasks. A recurring task is something like "send an email to administrator every hour from 8:00 am to 5:00 pm, Monday through Friday".

I have a base class called RecurringTask.

```<code>public abstract class RecurringTask{

    // I've already figured out this part
    public bool isOccuring(DateTime dateTime){
        // implementation
    }

    // run the task
    public abstract void Run(){

    }
}
</code>```

And I have several classes which are inherited from RecurringTask. One of them is called SendEmailTask.

```<code>public class SendEmailTask : RecurringTask{
    private Email email;

    public SendEmailTask(Email email){
        this.email = email;
    }

    public override void Run(){
        // need to send out email
    }
}
</code>```

And I have a EmailService which can helps me to send out an email.

The last class is RecurringTaskScheduler, it's responsible for loading tasks from cache or database and run the task.

```<code>public class RecurringTaskScheduler{

    public void RunTasks(){
        // Every minute, load all tasks from cache or database
        foreach(RecuringTask task : tasks){
            if(task.isOccuring(Datetime.UtcNow)){
                task.run();
            }
        }
    }
}
</code>```

Here is my problem: where should I put EmailService?

Option1: Inject EmailService into SendEmailTask

```<code>public class SendEmailTask : RecurringTask{
    private Email email;

    public EmailService EmailService{ get; set;}

    public SendEmailTask (Email email, EmailService emailService){
        this.email = email;
        this.EmailService = emailService;
    }

    public override void Run(){
        this.EmailService.send(this.email);
    }
}
</code>```

There are already some discussions on whether we should inject a service into an entity, and most people agree it's not a good practice. See this article.

Option2: If...Else in RecurringTaskScheduler

```<code>public class RecurringTaskScheduler{
    public EmailService EmailService{get;set;}

    public class RecurringTaskScheduler(EmailService emailService){
        this.EmailService = emailService;
    }

    public void RunTasks(){
        // load all tasks from cache or database
        foreach(RecuringTask task : tasks){
            if(task.isOccuring(Datetime.UtcNow)){
                if(task is SendEmailTask){
                    EmailService.send(task.email); // also need to make email public in SendEmailTask
                }
            }
        }
    }
}
</code>```

I've been told If...Else and cast like above is not OO, and will bring more problems.

Option3: Change the signature of Run and create ServiceBundle.

```<code>public class ServiceBundle{
    public EmailService EmailService{get;set}
    public CleanDiskService CleanDiskService{get;set;}
    // and other services for other recurring tasks

}
</code>```

Inject this class into RecurringTaskScheduler

```<code>public class RecurringTaskScheduler{
    public ServiceBundle ServiceBundle{get;set;}

    public class RecurringTaskScheduler(ServiceBundle serviceBundle){
        this.ServiceBundle = ServiceBundle;
    }

    public void RunTasks(){
        // load all tasks from cache or database
        foreach(RecuringTask task : tasks){
            if(task.isOccuring(Datetime.UtcNow)){
                task.run(serviceBundle);
            }
        }
    }
}
</code>```

The Run method of SendEmailTask would be

```<code>public void Run(ServiceBundle serviceBundle){
    serviceBundle.EmailService.send(this.email);
}
</code>```

I don't see any big problems with this approach.

Option4: Visitor pattern.

The basic idea is create a visitor which will encapsulate services just like ServiceBundle.

```<code>public class RunTaskVisitor : RecurringTaskVisitor{
    public EmailService EmailService{get;set;}
    public CleanDiskService CleanDiskService{get;set;}

    public void Visit(SendEmailTask task){
        EmailService.send(task.email);
    }

    public void Visit(ClearDiskTask task){
        //
    }
}
</code>```

And we also need to change the signature of Run method. The Run method of SendEmailTask is

```<code>public void Run(RecurringTaskVisitor visitor){
    visitor.visit(this);
}
</code>```

It is a typical implementation of Visitor Pattern, and the visitor will be injected into RecurringTaskScheduler.

In summary:
Among these four approaches, which one is the best for my scenario? And are there any big difference between Option3 and Option4 for this problem?

Or do you have better idea on this problem? Thanks!

Update 5/22/2015: I think Andy's answer summarizes my intention really well; if you are still confused about the problem itself, I suggest reading his post first.

I just found out my problem is very similar to Message Dispatch problem, which leads to Option5.

Option5: Convert my problem to Message Dispatch.

There is a one-to-one mapping between my problem and Message Dispatch problem:

Message Dispatcher : Receive IMessage and dispatch sub classes of IMessage to their corresponding handlers. → RecurringTaskScheduler

IMessage : An interface or an abstract class. → RecurringTask

MessageA : Extends from IMessage, having some additional information. → SendEmailTask

MessageB : Another subclass of IMessage. → CleanDiskTask

MessageAHandler : When receive MessageA, handle it → SendEmailTaskHandler, which contains EmailService, and will send out an email when it receives SendEmailTask

MessageBHandler : Same as MessageAHandler, but handle MessageB instead. → CleanDiskTaskHandler

The hardest part is how to dispatch different kind of IMessage to different handlers. Here is a useful link.

I really like this approach, it doesn't pollute my entity with service, and it doesn't have any God class.

答:
I would say Option 1 is the best route to take. The reason you should not dismiss it is that the SendEmailTask is not an entity. An entity is an object concerned with holding data and state. Your class has very little of that. In fact, it is not an entity, but it holds an entity: the Email object you are storing. That means that Email should not take a service, or have a #Send method. Instead, you should have services that take entities, such as your EmailService. So you are already following the idea of keeping services out of entities.

Since SendEmailTask is not an entity, it is therefore perfectly fine to inject the email and the service into it, and that should be done through the constructor. By doing constructor injection, we can be sure that SendEmailTask is always ready to perform it's job.

Now let's look at why not to do the other options (specifically with respect to SOLID).

Option 2

You've been rightly told that branching on type like that will bring more headaches down the road. Let's look at why. First, ifs tend to cluster and grow. Today, it's a task to send emails, tomorrow, every different type of class needs a different service or other behavior. Managing that if statement becomes a nightmare. Since we are branching on type (and in this case explicit type), we are subverting the type system built into our language.

Option 2 is not Single Responsibility (SRP) because the formerly reusable RecurringTaskScheduler now has to know about all these different types of tasks, and about all the different kinds of services and behaviors they might need. That class is much harder to reuse. It is also not Open/Closed (OCP). Because it needs to know about this kind of task or that one (or this kind of service or that one), disparate changes to tasks or services could force changes here. Add a new task? Add a new service? Change the way email is handled? Change RecurringTaskScheduler. Because the type of task matters, it does not adhere to Liskov Substitution (LSP). It can't just get a task and be done. It has to ask for the type and based on the type do this or do that. Rather than encapsulating the differences into the tasks, we are pulling all of that into the RecurringTaskScheduler.

Option 3

Option 3 has some big problems. Even in the article you link to, the author discourages doing this:

You can still use a static service locator…

I avoid service locator when I can, especially when the service locator must be static…

You are creating a service locator with your ServiceBundle class. In this case, it doesn't appear to be static, but it still has many of the problems inherent in a service locator. Your dependencies are now hidden away under this ServiceBundle. If I give you the following API of my cool new task:

```<code>class MyCoolNewTask implements RecurringTask
{
    public bool isOccuring(DateTime dateTime) {
        return true; // It's always happenin' here!
    }

    public void Run(ServiceBundle bundle) {
        // yeah, some awesome stuff here
    }
}
</code>```

What are the services I am using? What services need to be mocked out in a test? What's to stop me from using every service in the system, just because?

If I want to use your task system to run some tasks, I now am dependent on every service in your system, even if I only use a few or even none at all.

The ServiceBundle is not really SRP because it needs to know about every service in your system. It is also not OCP. Adding new services means changes to the ServiceBundle, and changes to the ServiceBundle may mean disparate changes to tasks elsewhere. ServiceBundle does not Segregate its Interface (ISP). It has a sprawling interface of all these services, and because it's just a provider for those services, we could consider its interface to encompass the interfaces of all of the services it provides as well. Tasks no longer adhere to Dependency Inversion (DIP), because their dependencies are obfuscated behind the ServiceBundle. This also does not adhere to the Principle of Least Knowledge (aka the Law of Demeter) because things know about many more things than they have to.

Option 4

Previously, you had lots of small objects that were able to operate independently. Option 4 takes all of these objects and smashes them together into a single Visitor object. This object acts as a god object over all of your tasks. It reduces your RecurringTask objects to anemic shadows that simply call out to a visitor. All of the behavior moves to the Visitor. Need to change behavior? Need to add a new task? Change Visitor.

The more challenging part is that, because all of the different behaviors are all in a single class, changing some polymorphicly drags along all of the other behavior. For example, we want to have two different ways to send email (they should use different servers maybe?). How would we do it? We could create an IVisitor interface and implement that, potentially duplicating code, like #Visit(ClearDiskTask) from our original visitor. Then if we come up with a new way to clear a disk, we have to implement and duplicate again. Then we want both kinds of changes. Implement and duplicate again. These two different, disparate behaviors are inextricably linked.

Maybe instead we could just subclass Visitor? Subclass with new email behavior, subclass with new disk behavior. No duplication so far! Subclass with both? Now one or the other needs to be duplicated (or both if that's your preference).

Let's compare to option 1: We need a new email behavior. We can create a new RecurringTask that does the new behavior, inject in its dependencies, and add it to the collection of tasks in the RecurringTaskScheduler. We don't even need to talk about clearing disks, because that responsibility is somewhere else entirely. We also still have the full array of OO tools at our disposal. We could decorate that task with logging, for example.

Option 1 will give you the least pain, and is the most correct way to handle this situation.

Body:
I would say Option 1 is the best route to take. The reason you should not dismiss it is that the SendEmailTask is not an entity. An entity is an object concerned with holding data and state. Your class has very little of that. In fact, it is not an entity, but it holds an entity: the Email object you are storing. That means that Email should not take a service, or have a #Send method. Instead, you should have services that take entities, such as your EmailService. So you are already following the idea of keeping services out of entities.

Since SendEmailTask is not an entity, it is therefore perfectly fine to inject the email and the service into it, and that should be done through the constructor. By doing constructor injection, we can be sure that SendEmailTask is always ready to perform it's job.

Now let's look at why not to do the other options (specifically with respect to SOLID).

Option 2

You've been rightly told that branching on type like that will bring more headaches down the road. Let's look at why. First, ifs tend to cluster and grow. Today, it's a task to send emails, tomorrow, every different type of class needs a different service or other behavior. Managing that if statement becomes a nightmare. Since we are branching on type (and in this case explicit type), we are subverting the type system built into our language.

Option 2 is not Single Responsibility (SRP) because the formerly reusable RecurringTaskScheduler now has to know about all these different types of tasks, and about all the different kinds of services and behaviors they might need. That class is much harder to reuse. It is also not Open/Closed (OCP). Because it needs to know about this kind of task or that one (or this kind of service or that one), disparate changes to tasks or services could force changes here. Add a new task? Add a new service? Change the way email is handled? Change RecurringTaskScheduler. Because the type of task matters, it does not adhere to Liskov Substitution (LSP). It can't just get a task and be done. It has to ask for the type and based on the type do this or do that. Rather than encapsulating the differences into the tasks, we are pulling all of that into the RecurringTaskScheduler.

Option 3

Option 3 has some big problems. Even in the article you link to, the author discourages doing this:

You can still use a static service locator…

I avoid service locator when I can, especially when the service locator must be static…

You are creating a service locator with your ServiceBundle class. In this case, it doesn't appear to be static, but it still has many of the problems inherent in a service locator. Your dependencies are now hidden away under this ServiceBundle. If I give you the following API of my cool new task:

class MyCoolNewTask implements RecurringTask
{
    public bool isOccuring(DateTime dateTime) {
        return true; // It's always happenin' here!
    }

    public void Run(ServiceBundle bundle) {
        // yeah, some awesome stuff here
    }
}

What are the services I am using? What services need to be mocked out in a test? What's to stop me from using every service in the system, just because?

If I want to use your task system to run some tasks, I now am dependent on every service in your system, even if I only use a few or even none at all.

The ServiceBundle is not really SRP because it needs to know about every service in your system. It is also not OCP. Adding new services means changes to the ServiceBundle, and changes to the ServiceBundle may mean disparate changes to tasks elsewhere. ServiceBundle does not Segregate its Interface (ISP). It has a sprawling interface of all these services, and because it's just a provider for those services, we could consider its interface to encompass the interfaces of all of the services it provides as well. Tasks no longer adhere to Dependency Inversion (DIP), because their dependencies are obfuscated behind the ServiceBundle. This also does not adhere to the Principle of Least Knowledge (aka the Law of Demeter) because things know about many more things than they have to.

Option 4

Previously, you had lots of small objects that were able to operate independently. Option 4 takes all of these objects and smashes them together into a single Visitor object. This object acts as a god object over all of your tasks. It reduces your RecurringTask objects to anemic shadows that simply call out to a visitor. All of the behavior moves to the Visitor. Need to change behavior? Need to add a new task? Change Visitor.

The more challenging part is that, because all of the different behaviors are all in a single class, changing some polymorphicly drags along all of the other behavior. For example, we want to have two different ways to send email (they should use different servers maybe?). How would we do it? We could create an IVisitor interface and implement that, potentially duplicating code, like #Visit(ClearDiskTask) from our original visitor. Then if we come up with a new way to clear a disk, we have to implement and duplicate again. Then we want both kinds of changes. Implement and duplicate again. These two different, disparate behaviors are inextricably linked.

Maybe instead we could just subclass Visitor? Subclass with new email behavior, subclass with new disk behavior. No duplication so far! Subclass with both? Now one or the other needs to be duplicated (or both if that's your preference).

Let's compare to option 1: We need a new email behavior. We can create a new RecurringTask that does the new behavior, inject in its dependencies, and add it to the collection of tasks in the RecurringTaskScheduler. We don't even need to talk about clearing disks, because that responsibility is somewhere else entirely. We also still have the full array of OO tools at our disposal. We could decorate that task with logging, for example.

Option 1 will give you the least pain, and is the most correct way to handle this situation.


问:
C# obtain derived class from base
I am trying to build a dashboard that allows a variety of widgets to be displayed on the home screen.  They are structured as follows:

```<code>public abstract class Widget {}
public abstract class GraphWidget : Widget {}
public class PieWidget : GraphWidget : Widget {}
public class BarWidget : GraphWidget : Widget {}
public class TextWidget : Widget {}
</code>```

I wanted to give my viewmodel an IENumerable<Widget> Widgets {get;set;} property so that I can loop through them on the dashboard and display them properly.  Since I am using JavaScript to display the graphs, the type of graph determines the JavaScript that will be output.

Is there a way to loop through all the widgets, but determine what type of widget it is?

答:
If you want to separate the java script creation from your widgets you could also use the visitor pattern:</p>

```<code>public interface IWidgetVisitor
{
    public void Visit(PieWidget widget);
    public void Visit(BarWidget widget);
    public void Visit(TextWidget widget);
    ...
}

public abstract class Widget
{
    public abstract void Accept(IWidgetVisitor visitor);
}

public class SomeWidget : Widget
{
    public override void Accept(IWidgetVisitor visitor)
    {
        visitor.Visit(this);
    }
}

public class WidgetToJavaScriptConverter : IWidgetVisitor
{
    public void Visit(PieWidget widget)
    {
        // Do your conversion here
    }

    public void Visit(BarWidget widget)
    {
        // Do your conversion here
    }

    public void Visit(TextWidget widget)
    {
        // Do your conversion here
    }
    ...
}
</code>```

Title: C# obtain derived class from base

Body:
If you want to separate the java script creation from your widgets you could also use the visitor pattern:

public interface IWidgetVisitor
{
    public void Visit(PieWidget widget);
    public void Visit(BarWidget widget);
    public void Visit(TextWidget widget);
    ...
}

public abstract class Widget
{
    public abstract void Accept(IWidgetVisitor visitor);
}

public class SomeWidget : Widget
{
    public override void Accept(IWidgetVisitor visitor)
    {
        visitor.Visit(this);
    }
}

public class WidgetToJavaScriptConverter : IWidgetVisitor
{
    public void Visit(PieWidget widget)
    {
        // Do your conversion here
    }

    public void Visit(BarWidget widget)
    {
        // Do your conversion here
    }

    public void Visit(TextWidget widget)
    {
        // Do your conversion here
    }
    ...
}


问:
Short circuit evaluation, is it bad practice?
Something that I've known for a while but never considered is that in most languages it is possible to give priority to operators in an if statement based on their order. I often use this as a way to prevent null reference exceptions, e.g.:

if (smartphone != null && smartphone.GetSignal() > 50)
{
   // Do stuff
}
```

In this case the code will result in first checking that the object is not null and then using this object knowing that it exists. The language is clever because it knows that if the the first statement if false then there is no point even evaluating the second statement and so a null reference exception is never thrown. This works the same for and and or operators.

This can be useful in other situations too such as checking that an index is in the bounds of an array and such a technique can be performed in various languages, to my knowledge: Java, C#, C++, Python and Matlab.

My question is: Is this sort of code a representation of bad practice? Does this bad practice arise from some hidden technical issue (i.e. this could eventually result in an error) or does it lead to a readability issue for other programmers? Could it be confusing?

答:
While I generally agree with dan1111's answer, there is one particularly important case it does not cover: the case where smartphone is used concurrently. In that scenario, this sort of pattern is a well known source of hard to find bugs.

The problem is that short circuit evaluation is not atomic. Your thread can check that smartphone is null, another thread can come in and nullify it, and then your thread promptly tries to GetSignal() and blows up.

But of course, it only does that when the stars align and your threads' timing is just right.

So while this sort of code is very common and useful, it is important to know about this caveat so that you can accurately prevent this nasty bug.


答:
That is a great question and an interesting problem. I propose that you use a combination of Chain of Responsibility and Double Dispatch patterns (pattern examples here).

First lets define the task hierarchy. Notice that there are now multiple run methods to implement the Double Dispatch.

```<code>public abstract class RecurringTask {

    public abstract boolean isOccuring(Date date);

    public boolean run(EmailService emailService) {
        return false;
    }

    public boolean run(ExecuteService executeService) {
        return false;
    }
}

public class SendEmailTask extends RecurringTask {

    private String email;

    public SendEmailTask(String email) {
        this.email = email;
    }

    @Override
    public boolean isOccuring(Date date) {
        return true;
    }

    @Override
    public boolean run(EmailService emailService) {
        emailService.runTask(this);
        return true;
    }

    public String getEmail() {
        return email;
    }
}

public class ExecuteTask extends RecurringTask {

    private String program;

    public ExecuteTask(String program) {
        this.program = program;
    }

    @Override
    public boolean isOccuring(Date date) {
        return true;
    }

    public String getName() {
        return program;
    }

    @Override
    public boolean run(ExecuteService executeService) {
        executeService.runTask(this);
        return true;
    }
}
</code>```

Next lets define the Service hierarchy. We will use Services to form the Chain of Responsibility.

```<code>public abstract class Service {

    private Service next;

    public Service(Service next) {
        this.next = next;
    }

    public void handleRecurringTask(RecurringTask req) {
        if (next != null) {
            next.handleRecurringTask(req);
        }
    }
}

public class ExecuteService extends Service {

    public ExecuteService(Service next) {
        super(next);
    }

    void runTask(ExecuteTask task) {
        System.out.println(String.format("%s running %s with content '%s'", this.getClass().getSimpleName(),
                task.getClass().getSimpleName(), task.getName()));
    }

    public void handleRecurringTask(RecurringTask req) {
        if (!req.run(this)) {
            super.handleRecurringTask(req);
        }
    }
}

public class EmailService extends Service {

    public EmailService(Service next) {
        super(next);
    }

    public void runTask(SendEmailTask task) {
        System.out.println(String.format("%s running %s with content '%s'", this.getClass().getSimpleName(),
                task.getClass().getSimpleName(), task.getEmail()));
    }

    public void handleRecurringTask(RecurringTask req) {
        if (!req.run(this)) {
            super.handleRecurringTask(req);
        }
    }
}
</code>```

The final piece is the RecurringTaskScheduler which orchestrates the loading and running process.

```<code>public class RecurringTaskScheduler{

    private List<RecurringTask> tasks = new ArrayList<>();

    private Service chain;

    public RecurringTaskScheduler() {
        chain = new EmailService(new ExecuteService(null));
    }

    public void loadTasks() {
        tasks.add(new SendEmailTask("here comes the first email"));
        tasks.add(new SendEmailTask("here is the second email"));
        tasks.add(new ExecuteTask("/root/python"));
        tasks.add(new ExecuteTask("/bin/cat"));
        tasks.add(new SendEmailTask("here is the third email"));
        tasks.add(new ExecuteTask("/bin/grep"));
    }

    public void runTasks(){
        for (RecurringTask task : tasks) {
            if (task.isOccuring(new Date())) {
                chain.handleRecurringTask(task);
            }
        }
    }
}
</code>```

Now, here is the example application demonstrating the system.

```<code>public class App {

    public static void main(String[] args) {
        RecurringTaskScheduler scheduler = new RecurringTaskScheduler();
        scheduler.loadTasks();
        scheduler.runTasks();
    }
}
</code>```

Running the application outputs:

EmailService running SendEmailTask with content 'here comes the first email'

EmailService running SendEmailTask with content 'here is the second email'

ExecuteService running ExecuteTask with content '/root/python'

ExecuteService running ExecuteTask with content '/bin/cat'

EmailService running SendEmailTask with content 'here is the third email'

ExecuteService running ExecuteTask with content '/bin/grep'

Title: Is Visitor Pattern valid in this scenario?

Body:
The goal of my task is to design a small system which can run scheduled recurring tasks. A recurring task is something like "send an email to administrator every hour from 8:00 am to 5:00 pm, Monday through Friday".

I have a base class called RecurringTask.

```<code>public abstract class RecurringTask{

    // I've already figured out this part
    public bool isOccuring(DateTime dateTime){
        // implementation
    }

    // run the task
    public abstract void Run(){

    }
}
</code>```

And I have several classes which are inherited from RecurringTask. One of them is called SendEmailTask.

```<code>public class SendEmailTask : RecurringTask{
    private Email email;

    public SendEmailTask(Email email){
        this.email = email;
    }

    public override void Run(){
        // need to send out email
    }
}
</code>```

And I have a EmailService which can helps me to send out an email.

The last class is RecurringTaskScheduler, it's responsible for loading tasks from cache or database and run the task.

```<code>public class RecurringTaskScheduler{

    public void RunTasks(){
        // Every minute, load all tasks from cache or database
        foreach(RecuringTask task : tasks){
            if(task.isOccuring(Datetime.UtcNow)){
                task.run();
            }
        }
    }
}
</code>```

Here is my problem: where should I put EmailService?

Option1: Inject EmailService into SendEmailTask

```<code>public class SendEmailTask : RecurringTask{
    private Email email;

    public EmailService EmailService{ get; set;}

    public SendEmailTask (Email email, EmailService emailService){
        this.email = email;
        this.EmailService = emailService;
    }

    public override void Run(){
        this.EmailService.send(this.email);
    }
}
</code>```

There are already some discussions on whether we should inject a service into an entity, and most people agree it's not a good practice. See this article.

Option2: If...Else in RecurringTaskScheduler

```<code>public class RecurringTaskScheduler{
    public EmailService EmailService{get;set;}

    public class RecurringTaskScheduler(EmailService emailService){
        this.EmailService = emailService;
    }

    public void RunTasks(){
        // load all tasks from cache or database
        foreach(RecuringTask task : tasks){
            if(task.isOccuring(Datetime.UtcNow)){
                if(task is SendEmailTask){
                    EmailService.send(task.email); // also need to make email public in SendEmailTask
                }
            }
        }
    }
}
</code>```

I've been told If...Else and cast like above is not OO, and will bring more problems.

Option3: Change the signature of Run and create ServiceBundle.

```<code>public class ServiceBundle{
    public EmailService EmailService{get;set}
    public CleanDiskService CleanDiskService{get;set;}
    // and other services for other recurring tasks

}
</code>```

Inject this class into RecurringTaskScheduler

```<code>public class RecurringTaskScheduler{
    public ServiceBundle ServiceBundle{get;set;}

    public class RecurringTaskScheduler(ServiceBundle serviceBundle){
        this.ServiceBundle = ServiceBundle;
    }

    public void RunTasks(){
        // load all tasks from cache or database
        foreach(RecuringTask task : tasks){
            if(task.isOccuring(Datetime.UtcNow)){
                task.run(serviceBundle);
            }
        }
    }
}
</code>```

The Run method of SendEmailTask would be

```<code>public void Run(ServiceBundle serviceBundle){
    serviceBundle.EmailService.send(this.email);
}
</code>```

I don't see any big problems with this approach.

Option4: Visitor pattern.

The basic idea is create a visitor which will encapsulate services just like ServiceBundle.

```<code>public class RunTaskVisitor : RecurringTaskVisitor{
    public EmailService EmailService{get;set;}
    public CleanDiskService CleanDiskService{get;set;}

    public void Visit(SendEmailTask task){
        EmailService.send(task.email);
    }

    public void Visit(ClearDiskTask task){
        //
    }
}
</code>```

And we also need to change the signature of Run method. The Run method of SendEmailTask is

```<code>public void Run(RecurringTaskVisitor visitor){
    visitor.visit(this);
}
</code>```

It is a typical implementation of Visitor Pattern, and the visitor will be injected into RecurringTaskScheduler.

In summary:
Among these four approaches, which one is the best for my scenario? And are there any big difference between Option3 and Option4 for this problem?

Or do you have better idea on this problem? Thanks!

Update 5/22/2015: I think Andy's answer summarizes my intention really well; if you are still confused about the problem itself, I suggest reading his post first.

I just found out my problem is very similar to Message Dispatch problem, which leads to Option5.

Option5: Convert my problem to Message Dispatch.

There is a one-to-one mapping between my problem and Message Dispatch problem:

Message Dispatcher : Receive IMessage and dispatch sub classes of IMessage to their corresponding handlers. → RecurringTaskScheduler

IMessage : An interface or an abstract class. → RecurringTask

MessageA : Extends from IMessage, having some additional information. → SendEmailTask

MessageB : Another subclass of IMessage. → CleanDiskTask

MessageAHandler : When receive MessageA, handle it → SendEmailTaskHandler, which contains EmailService, and will send out an email when it receives SendEmailTask

MessageBHandler : Same as MessageAHandler, but handle MessageB instead. → CleanDiskTaskHandler

The hardest part is how to dispatch different kind of IMessage to different handlers. Here is a useful link.

I really like this approach, it doesn't pollute my entity with service, and it doesn't have any God class.

Body:
That is a great question and an interesting problem. I propose that you use a combination of Chain of Responsibility and Double Dispatch patterns (pattern examples here).

First lets define the task hierarchy. Notice that there are now multiple run methods to implement the Double Dispatch.

public abstract class RecurringTask {

    public abstract boolean isOccuring(Date date);

    public boolean run(EmailService emailService) {
        return false;
    }

    public boolean run(ExecuteService executeService) {
        return false;
    }
}

public class SendEmailTask extends RecurringTask {

    private String email;

    public SendEmailTask(String email) {
        this.email = email;
    }

    @Override
    public boolean isOccuring(Date date) {
        return true;
    }

    @Override
    public boolean run(EmailService emailService) {
        emailService.runTask(this);
        return true;
    }

    public String getEmail() {
        return email;
    }
}

public class ExecuteTask extends RecurringTask {

    private String program;

    public ExecuteTask(String program) {
        this.program = program;
    }

    @Override
    public boolean isOccuring(Date date) {
        return true;
    }

    public String getName() {
        return program;
    }

    @Override
    public boolean run(ExecuteService executeService) {
        executeService.runTask(this);
        return true;
    }
}

Next lets define the Service hierarchy. We will use Services to form the Chain of Responsibility.

public abstract class Service {

    private Service next;

    public Service(Service next) {
        this.next = next;
    }

    public void handleRecurringTask(RecurringTask req) {
        if (next != null) {
            next.handleRecurringTask(req);
        }
    }
}

public class ExecuteService extends Service {

    public ExecuteService(Service next) {
        super(next);
    }

    void runTask(ExecuteTask task) {
        System.out.println(String.format("%s running %s with content '%s'", this.getClass().getSimpleName(),
                task.getClass().getSimpleName(), task.getName()));
    }

    public void handleRecurringTask(RecurringTask req) {
        if (!req.run(this)) {
            super.handleRecurringTask(req);
        }
    }
}

public class EmailService extends Service {

    public EmailService(Service next) {
        super(next);
    }

    public void runTask(SendEmailTask task) {
        System.out.println(String.format("%s running %s with content '%s'", this.getClass().getSimpleName(),
                task.getClass().getSimpleName(), task.getEmail()));
    }

    public void handleRecurringTask(RecurringTask req) {
        if (!req.run(this)) {
            super.handleRecurringTask(req);
        }
    }
}

The final piece is the RecurringTaskScheduler which orchestrates the loading and running process.

public class RecurringTaskScheduler{

    private List<RecurringTask> tasks = new ArrayList<>();

    private Service chain;

    public RecurringTaskScheduler() {
        chain = new EmailService(new ExecuteService(null));
    }

    public void loadTasks() {
        tasks.add(new SendEmailTask("here comes the first email"));
        tasks.add(new SendEmailTask("here is the second email"));
        tasks.add(new ExecuteTask("/root/python"));
        tasks.add(new ExecuteTask("/bin/cat"));
        tasks.add(new SendEmailTask("here is the third email"));
        tasks.add(new ExecuteTask("/bin/grep"));
    }

    public void runTasks(){
        for (RecurringTask task : tasks) {
            if (task.isOccuring(new Date())) {
                chain.handleRecurringTask(task);
            }
        }
    }
}

Now, here is the example application demonstrating the system.

public class App {

    public static void main(String[] args) {
        RecurringTaskScheduler scheduler = new RecurringTaskScheduler();
        scheduler.loadTasks();
        scheduler.runTasks();
    }
}

Running the application outputs:

EmailService running SendEmailTask with content 'here comes the first email'

EmailService running SendEmailTask with content 'here is the second email'

ExecuteService running ExecuteTask with content '/root/python'

ExecuteService running ExecuteTask with content '/bin/cat'

EmailService running SendEmailTask with content 'here is the third email'

ExecuteService running ExecuteTask with content '/bin/grep'


问:
How to determine if set of ordered coordinates form a simple curve?
I hope it is the right place to ask this. I wasn't sure if it belongs to Stack Overflow or Computer Science.

Eventually this seemed more suitable.

Anyway, some background first:

A closed curve, is a curve with no endpoints and which completely encloses an area.

A simple curve, is a curve that does not cross itself.

Example:

Now, given n ordered (x,y) coordinates that represents mouse movement, it is easy to determine if they form a closed curve (given an upper bound on the allowed distance between two points, of-course), but is there an algorithm that will determine whether or not the coordinates form a simple curve?

I tried to look online for an answer, but couldn't find relevant solutions.

答:
The concept may be simple, but there are many devilish details.

To begin with, you have to stipulate that the numbers representing the points are exact,
not approximations to some real curve, and that the outline consists of straight line segments, not an actual curve.

Second, boundary conditions are everywhere; if line AB touches line DEF only at point E,
does that count as a cross or not?  You need to consider the overall geometry of the
figure.  Consider a "C" shaped figure with a pseudopod extending from the back, around
to enter the "mouth" of the C, and now gradually close the jaws of the C to meet
at a single point.


答:
Of course you can. You can use the is keyword to check if an item in the list is of a certain subtype. This is usually an anti-pattern.

Or you can implement a method in each subtype that returns an identifier that you will use to decide what to do with that item.

Or the method for each subtype can do whatever you deem desirable that will bring about the required functionality.

Title: C# obtain derived class from base

Body:
I am trying to build a dashboard that allows a variety of widgets to be displayed on the home screen.  They are structured as follows:

```<code>public abstract class Widget {}
public abstract class GraphWidget : Widget {}
public class PieWidget : GraphWidget : Widget {}
public class BarWidget : GraphWidget : Widget {}
public class TextWidget : Widget {}
</code>```

I wanted to give my viewmodel an IENumerable<Widget> Widgets {get;set;} property so that I can loop through them on the dashboard and display them properly.  Since I am using JavaScript to display the graphs, the type of graph determines the JavaScript that will be output.

Is there a way to loop through all the widgets, but determine what type of widget it is?


问:
How to deal with static utility classes when designing for testability
We are trying to design our system to be testable and in most parts developed using TDD. Currently we are trying to solve the following problem:

In various places it is necessary for us to use static helper methods like ImageIO and URLEncoder (both standard Java API) and various other libraries that consist mostly of static methods (like the Apache Commons libraries). But it is extremely difficult to test those methods that use such static helper classes.

I have several ideas for solving this problem:

Use a mock framework that can mock static classes (like PowerMock). This may be the simplest solution but somehow feels like giving up.

Create instantiable wrapper classes around all those static utilities so they can be injected into the classes that use them. This sounds like a relatively clean solution but I fear we'll end up creating an awful lot of those wrapper classes.

Extract every call to these static helper classes into a function that can be overridden and test a subclass of the class I actually want to test.

But I keep thinking that this just has to be a problem that many people have to face when doing TDD - so there must already be solutions for this problem.

What is the best strategy to keep classes that use these static helpers testable?

答:
Sometimes I use option 4

Use the strategy pattern. Create a utility class with static methods that delegate implementation to an instance of pluggable interface. Code a static initializer that plugs in a concrete implementation. Plug in a mock implementation for testing.

Something like this.

```<code>public class DateUtil {
    public interface ITimestampGenerator {
        long getUtcNow();
    }

    class ConcreteTimestampGenerator implements ITimestampGenerator {
        public long getUtcNow() { return System.currentTimeMillis(); }
    }

    private static ITimestampGenerator timestampGenerator;

    static {
        timestampGenerator = new ConcreteTimeStampGenerator;
    }

    public static DateTime utcNow() {
        return new DateTime(timestampGenerator.getUtcNow(), DateTimeZone.UTC);
    }

    public static void setTimestampGenerator(ITimestampGenerator t) {...}

    // plus other util routines, which may or may not use the timestamp generator
}
</code>```

What I like about this approach is that it keeps the utility methods static, which just feels right to me when I am trying to use the class throughout the code.

```<code>Math.sum(17, 29, 42);
// vs
new Math().sum(17, 29, 42);
</code>```

OwnerDisplayName: Benedikt

Body:
Sometimes I use option 4

Use the strategy pattern. Create a utility class with static methods that delegate implementation to an instance of pluggable interface. Code a static initializer that plugs in a concrete implementation. Plug in a mock implementation for testing.

Something like this.

public class DateUtil {
    public interface ITimestampGenerator {
        long getUtcNow();
    }

    class ConcreteTimestampGenerator implements ITimestampGenerator {
        public long getUtcNow() { return System.currentTimeMillis(); }
    }

    private static ITimestampGenerator timestampGenerator;

    static {
        timestampGenerator = new ConcreteTimeStampGenerator;
    }

    public static DateTime utcNow() {
        return new DateTime(timestampGenerator.getUtcNow(), DateTimeZone.UTC);
    }

    public static void setTimestampGenerator(ITimestampGenerator t) {...}

    // plus other util routines, which may or may not use the timestamp generator
}

What I like about this approach is that it keeps the utility methods static, which just feels right to me when I am trying to use the class throughout the code.

Math.sum(17, 29, 42);
// vs
new Math().sum(17, 29, 42);


问:
Ternary operator considered harmful?
For example, would you prefer this one-liner

```<code>int median(int a, int b, int c) {
    return (a<b) ? (b<c) ? b : (a<c) ? c : a : (a<c) ? a : (b<c) ? c : b;
}
</code>```

or an if/else solution involving multiple return statements?

When is ?: appropriate, and when is it not? Should it be taught to or hidden from beginners?

答:
Anything that makes your code uglier is evil.

If you use ternary to make your code cleaner then sure use it. Sometimes in like php it's great to do inline substitutions, e.g.

```<code>"Hello ".($Male?"Mr":"Ms")." $Name
</code>```

That saves a few lines, and it pretty clear, but your example needs at least better formatting to be clear, and ternary isn't really good for multi-line, then you might as well use if/else.

Title: Ternary operator considered harmful?

Body:
Anything that makes your code uglier is evil.

If you use ternary to make your code cleaner then sure use it. Sometimes in like php it's great to do inline substitutions, e.g.

"Hello ".($Male?"Mr":"Ms")." $Name

That saves a few lines, and it pretty clear, but your example needs at least better formatting to be clear, and ternary isn't really good for multi-line, then you might as well use if/else.

ContentLicense: CC BY-SA 2.5


问:
What is the difference between writing test cases for BDD and TDD?
I have been learning writing test cases for BDD (Behavior Driven Development) using specflow. If I write comprehensive tests with BDD, is it necessary to write TDD (Test Driven Development) test separately? Is it necessary to write test cases for both TDD and BDD separately, or are they effectively the same thing?

It seems to me that both are same, the only difference being that BDD test cases can be understood by non developers and testers.

答:
Just to keep it confusing, realize that a lot of people now associate BDD with cucumber. They consider any tests you write using gherkin-derived syntax to be a BDD check, and anything written using a unit test framework (junit, unittest.py, etc) to be TDD.

It's wrong. The medium doesn't define the message in this case. Nor does the use of mocks (IMHO).

The main difference was already given: BDD is a feature-driven technique, using ubiquitous language and an outside-in approach. We write specifications (which will later run as tests) for a story or a slice of a story. Smallness and concreteness matter, and it is an "explanation by example" of what is needed/expected from this aspect of the story.

BDD specs are frequently written in a gherkin-like language if the people who need to specify the feature do not all read/write code (frequent case in larger orgs or where a real customer is part of the team). Otherwise, gherkin-ese is not necessary. These tend to be the output of the famous 3 Amigos meeting: business, test, dev all do these together. When using a BDD framework (fit, cucumber, etc) the test are slower and require a bit more infrastructure, so we keep these relatively sparse -- a few per story.

TDD is used when creating code. The purpose is to give an orderly progression of writing the feature with lots of opportunity for refactoring and with a reasonable confidence that you're not breaking anything accidentally while writing the new code. It doesn't need to describe features of the system, only of a method (or a few with a common effect). Nobody but devs need to read the tests written here, but they have to run crazy fast and isolate errors. They run crazy fast because there may be many tests per class member function ('method').

If you do BDD at the outer layer, it is still useful to do TDD in the inner loop because of refactoring and the ability to spot and avoid errors more quickly.

Neither is proof of correctness for a large system. Neither replaces pen and perf testing. Neither ensures thread-safety. The tests are aid in developing, not guarantees of perfect bug-proof-ness.


问:
Code maintenance: keeping a bad pattern when extending new code for being consistent, or not?
I have to extend an existing module of a project. I don't like the way it has been done (lots of anti-pattern involved, like copy/pasted code). I don't want to perform a complete refactor for many reasons.

Should I:

create new methods using existing
convention, even if I feel it wrong,
to avoid confusion for the next
maintainer and being consistent with
the code base?

or

try to use what I feel better even if
it is introducing another pattern in
the code ?

Precison edited after first answers:

The existing code is not a mess. It is easy to follow and understand. BUT it is introducing lots of boilerplate code that can be avoided with good design (resulting code might become harder to follow then). In my current case it's a good old JDBC (spring template inboard) DAO module, but I have already encounter this dilemma and I'm seeking for other dev feedback.

I don't want to refactor because I don't have time. And even with time it will be hard to justify that a whole perfectly working module needs refactoring. Refactoring cost will be heavier than its benefits. Remember: code is not messy or over-complex. I can not extract few methods there and introduce an abstract class here. It is more a flaw in the design (result of extreme 'Keep It Stupid Simple' I think)

So the question can also be asked like that:

You, as developer, do you prefer to maintain easy stupid boring code OR to have some helpers that will do the stupid boring code at your place ?

Downside of the last possibility being that you'll have to learn some stuff and maybe you will have to maintain the easy stupid boring code too until a full refactoring is done)

答:
Consistency has a high priority. Obviously everyone in their right mind would prefer an elegant DRY solution everywhere instead of copy-pasted boilerplate everywhere, but would you really prefer two different approaches in the same codebase to having one consistently applied? What if someone invents an even smarter solution and also applies it inconsistently? Then you have three different ways of doing the same thing.

I have seen much messy code resulting from developers finding a "better way" to do something, but not applying it consistently over a codebase. If it is part of a planned and coordinated strategy to apply a new pattern gradually over time it may work, but every pattern implemented inconsistently have the risk of making the overall system worse.

Maybe you could consider refactoring in smaller steps, such that each step can be applied over the whole codebase in one go. Eg. extracting a smaller part of the boilerplate to a helper function in each iteration. Over time you end up with all the boilerplate in a helper class. It may look really ugly because it wasn't designed but grown, but you can fix that now because you have all the code in one place.


问:
How to incorporate a database into a branch-per-issue version control process?
We're hoping to move to a new branch-per-issue process with development.  To prepare for this, a lot of research and experimenting has been happening in terms of version control, CI, and process of promotion.  The one thing I don't want to fall off the project is the database and it's schema.

The current process we have in place puts us into an expensive position.  We have four SQL Server boxes, each with their own environment worth of data.  There is Staging (for development), Quality (for QA), Beta (for client prototyping), and Production.  We're wanting to begin switching out some of our database model with MariaDB as we implement this new process as well.  However, I'm having trouble putting my head around how we'll go about putting our SQL changes into version control.

Our new process will start off with a master branch, which will be our main code, followed by an integration branch and issue branches.  Each developer will have their own web instance installed to make the needed changes on whatever branch they're working on at the time.  However, we've always worked on the global Staging server for our SQL.  This doesn't seem viable to me in the new process we plan on having.  My guess for this is that each person will have a version of a database (MariaDB) that they make any schema changes to.  So, that's my main question.

Do I use a process of only committing and merging schema changes?  I wouldn't think that committing an entire database is a good idea.  And at that point, how would this be stored in version control (we'll be using Git as our version control)?  Would each schema change be stored as a separate file?

For clarity-sake, what we're thinking of using is a PHP/Apache server to serve out our web content, a Java API back-end, a MariaDB (which we'll move the SQL Server away from) and a Git repository for the version control on the web code and API code.

答:
I propose looking into in code migrations for your language or technology. I have .NET stack and I can use Entity Framework Migrations where every schema change is single migration that can be automatically applied to database when needed. What is also possible is downgrading database, so pattern for db migration is that you have method for Up() and Down() this is really time saver when you have to deal with test, staging, production to keep changes in one place and don't bother with updating things manually.

But you could update question with technology stack you have available, then someone could provide you with your technology specific details.


问:
How is called the reciprocal operation of the join on two tables
Consider two tables in a relational database

```<code>1|A
2|B

1|X
1|Y
2|Z
</code>```

whose join on the first column is (if we drop the column used for the join)

```<code>A|X
A|Y
B|Z
</code>```

How is called the converse operation yielding the original tables from the result of the join?

In the general case, we may want to distinguish between the various flavours of joins and to tell the operation which columns belong to the left table and which to the right table. I do not want to go into these details here – unless this is of critical importance to give a name to this operation!

答: If I were given a file with the information you want o break back apaort, ti woudl be part of an ETL operations (exptract, transform, load) hetransaformation step. And yes, you mighte well be normalizing the data depanding on the dat table structure (certainly your example would be).  Theload part would come into play when you actually move teh dat to the differnt tables and could involve intermediate steps such as loading to eh parent table, getting the autogenreated ids and tehn loading to the child tables using those ids.  It is not necessary that this transformation and load process strictly speaking have completly normalized tables at the end. Normalization happens when you design table structures (Or normally should). Transformation happens when you manipulate the data so that is can fit into those strucures.</p>


问:
Spartan programming... What is it good for?
We are being forced to use Spartan programming on a project, to everybody's dismay. So I get it, it makes the methods really short and it handles the simple cases first. But is it really worth the price of the code looking like something out of the Obfuscated C Code contest? </p>

<p>Can you see it being useful for something? </p>

答:
Wow, I actually program like this, didn't know it had a name. I would say it benefits readability but more in a spatial way... meaning you don't get lost in a soup of code even if you have few lines that are kind of hard to read.

However, I'd say that when you get used to certain constructs you find your way easier in less time than at the very start.


问:
How much should I concern myself with hiding the IDs of my database in URLs?
I keep coming across questions and articles on the internet suggesting that it's not a good practice to have the IDs of your database records visible to the public. Yet I've never taken it seriously myself nor have (in my professional career) come across an application that actively attempted to hide IDs. I've recently been working on an MVC application and have my public URLs in the following format:

```<code>/Book/55/title-of-book
</code>```

Should I make efforts to change the Id part of the URL (55) into a hash of some sort? For example here's how Reddit has its URLs:

```<code>/r/subreddit/comments/36v4kb/title_of_article/
</code>```

If I were to keep the IDs hidden in my URLs I'd also have to strip them from all places where they publicly appear in my code and do changes in my database. That's not an easy task but I have no problem doing it if it's considered good practice.

What are the benefits of keeping IDs hidden and what are the best ways of going about hiding them?

答:
I think the biggest benefit of hiding IDs and presenting a hash-like string instead, is to prevent records being harvested simply by incrementing the value. This isn't so much a security concern, but a deterrence to would-be data harvesters who may wish to collect or index data from your service.

As for implementing this, it would be better to generate a random ID when the data object is created than to perform some sort of hashing on an incrementing, numeric ID each time it's served.


答:
The /Book/55/title-of-book pattern has an important benefit: it contains the title of the book, which is helpful for SEO, but also the ID, which:

Won't change (unless you change the type of the ID, say uniqueid instead of int).

Is the only thing needed to locate the corresponding resource. This is important when you need a shorter URI, especially when the URI has to be typed by hand. I rather prefer entering http://example.com/book/55 than http://example.com/book/a90K3DYb7.

Might be easier to index and parse (although it probably would be premature optimization in 99.9% of the cases).

This being said, auto-incremented IDs have those issues:

If the last added book has an ID 55, it's not difficult to deduce that there are approximately 55 books in the system. This may have a negative impact on your customers, especially if your marketing department claims that you have the largest database of books (or that you have dozens of thousands of books).

It is possible to enumerate the books one by one. This may not be what you want: you may prefer that your users pass through the search engine or other parts of the website in order to find a specific book. You may also want to make it more difficult for the bots to get every page for every book.

By enumerating the books, it is possible to determine how many were removed or hidden from the public. For instance, this is an issue I have in my blog: since the URIs contain the auto-incremented ID, anyone can tell by scanning through all articles which ones were removed or never released (i.e. still remaining as drafts).

Title: How much should I concern myself with hiding the IDs of my database in URLs?

Body:
I keep coming across questions and articles on the internet suggesting that it's not a good practice to have the IDs of your database records visible to the public. Yet I've never taken it seriously myself nor have (in my professional career) come across an application that actively attempted to hide IDs. I've recently been working on an MVC application and have my public URLs in the following format:

```<code>/Book/55/title-of-book
</code>```

Should I make efforts to change the Id part of the URL (55) into a hash of some sort? For example here's how Reddit has its URLs:

```<code>/r/subreddit/comments/36v4kb/title_of_article/
</code>```

If I were to keep the IDs hidden in my URLs I'd also have to strip them from all places where they publicly appear in my code and do changes in my database. That's not an easy task but I have no problem doing it if it's considered good practice.

What are the benefits of keeping IDs hidden and what are the best ways of going about hiding them?


问:
How to securely store user credentials from external website
I'm developing an application where I'd like to use credentials from external websites. This will be used to login with the website API and get information for the user.

Example: I want to use the user Reddit's account to warn him if more than X people reply to one of his comment.

How would I go about storing the user's Reddit credentials on my end securely so I only ask once and can automate this process. Or is that even possible?

答: You shouldn't store a user's login credentials to a third-party service. Instead, reddit provides an oAuth API to acquire access to parts of the website that require user authentication. See: https://www.reddit.com/dev/api/oauth.</p>


问:
Why do all <algorithm> functions take only ranges, not containers?
There are many useful functions in <algorithm>, but all of them operate on "sequences" - pairs of iterators. E.g., if I have a container and like to run std::accumulate on it, I need to write:

```<code>std::vector<int> myContainer = ...;
int sum = std::accumulate(myContainer.begin(), myContainer.end(), 0);
</code>```

When all I intend to do is:

```<code>int sum = std::accumulate(myContainer, 0);
</code>```

Which is a bit more readable and clearer, in my eyes.

Now I can see that there might be cases where you'd only want to operate on parts of a container, so it's definitely useful to have the option of passing ranges. But at least in my experience, that's a rare special case. I'll usually want to operate on whole containers.

It's easy to write a wrapper function which takes a container and calls begin() and end() on it, but such convenience functions are not included in the standard library.

I'd like to know the reasoning behind this STL design choice.

答:
By now, http://en.wikipedia.org/wiki/C++11#Range-based_for_loop is a nice alternative to std::for_each.  Observe, no explicit iterators:

```<code>int a[5] = {1, 2, 3, 4, 5};
for (auto &i: a) { i *= 2; }
</code>```

(Inspired by https://stackoverflow.com/a/694534/2097284 .)

Body:
By now, http://en.wikipedia.org/wiki/C++11#Range-based_for_loop is a nice alternative to std::for_each.  Observe, no explicit iterators:

int a[5] = {1, 2, 3, 4, 5};
for (auto &i: a) { i *= 2; }

(Inspired by https://stackoverflow.com/a/694534/2097284 .)


问:
File validation rules
I have an application that can accept CSV files to run some operations. The files look like:

```<code>CREATE USER:username,last_name,first_name,age
user1,Smith,John,23
user2,Poppins,Mary,257
</code>```

There are a number of commands that can be used, each with a specific "syntax" in terms of what columns are required / authorised, the type of data in each column, valid values as well as more complex rules (e.g. 2 users can't have the same username, the username must not already be present in the database, etc.).

At the moment, each of those commands correspond to a specific class in my OO model which runs the validation with code (if (type(column) != STRING) blabla) before executing the commands.

This is becoming cumbersome and I would like to extract the validation rules in human readable format, say:

```<code>Command=CREATE USER
Field='username', required, text, max_length=255, min_length=1,
      unique, not exists in db table 'User'
Field='age', optional, number, min=0, max=120
....
</code>```

My code could then become:

```<code>List<Error> errors = validate(csvFile, rulesFile);
if (errors.isEmpty()) //good to go
</code>```

However the more I think about it, the more it seems like it's going to be a major headache to code and effectively a whole project in itself, possibly not worth the time spent.

What approach could I take to extract rules in human readable format without unduly complicating the validation code?

答:
Smart data structures and dumb code works a lot better than the other way around. -- Eric S. Raymond, The Cathedral and the Bazaar

You can use XML or JSON with schemas. Validation rules should be machine-readable first, and human-readable if possible. Consider not inventing your own format and using XML Schema or JSON Schema instead. Switching to XML/JSON should not be very difficult, since there are a lot of libs available.

What you have now is basically some form of RPC based on CSV format. Maybe you should look into JSON-RPC or something similar.

Title: File validation rules


问:
DLL or web service for common functions?
We have a variety of basic functions (date utilities, email sending, internal math calculations, etc) that are currently in an old VB.NET project.

We're going to move towards C# and I'm wondering if we should write a new library that our applications can reference as a DLL or should we create a web service that our applications can call to do these things?

My current thought is for basic functions that return simple objects we can create a web service.

Edit: the main debate for us is that if we use a DLL that we deploy with various apps we have to then redeploy the DLL to all of them if we update it in the future. With a web service since the apps would all hit an endpoint we just update that.

答:
If your entire stack is .net there is not much value to creating web services.  Just reference the DLLs in the .net components that need them, it will be faster as there is no serialization or extra network hop involved.

However, for cross platform purposes, web services are the way to go.  Then you can have a .net client (ASP MVC app), java client, native mobile client, etc. that all consume the functionality provided by your .net service.

This adds tremendous value when you don't know what clients will be using your functionality or if your organization has several technology stacks.  However, the addition of web services does add some overhead to your architecture in regards to network and serialization of messages.  Web services are more flexible/future/forward thinking so you can swap out or use multiple front ends for the same service.


答: Having a separate business tier needs justification as it involves lots more work and costs more in performance (see: MS-Business Layer). According to one definition of Web Services, a Web Service is not generally required unless you are communicating between different physical tiers. Accordingly, a DLL may fit best for what you describe. It is common to use Web Services to communicate across systems for database/file access. The difference between a tier and a layer is important (see Tiers vs. Layers).</p>

Title: DLL or web service for common functions?

Body:
We have a variety of basic functions (date utilities, email sending, internal math calculations, etc) that are currently in an old VB.NET project.

We're going to move towards C# and I'm wondering if we should write a new library that our applications can reference as a DLL or should we create a web service that our applications can call to do these things?

My current thought is for basic functions that return simple objects we can create a web service.

Edit: the main debate for us is that if we use a DLL that we deploy with various apps we have to then redeploy the DLL to all of them if we update it in the future. With a web service since the apps would all hit an endpoint we just update that.


问:
Key bindings war in my brain
How many key bindings are there in your brain? I personally use Intellij Idea as my primary IDE for development, but sometimes switch to Eclipse and Netbeans a bit, and sometimes I use Jedit,Notepad++, Emacs, Vim.

I am always trying to find a perfect key bindings that I can use crossing all the editors.
What's your idea to solve this problem?

答:
Choose Vim (or I guess Emacs, if you're that kind of person)

Set your bindings in everything else to mimic that.

Alternative 2.: Why are you using a separate IDE? Just stick with Vim.

Title: Key bindings war in my brain


答:
The approach that I follow is based on the following premises:

Developers are not to be bothered with production data. That's for the operations department to worry about.

Configuration xml files, scripts, etc must be kept at a minimum.

Everything must be in the source code repository.

The source code repository is to contain only diff-able text files, nothing binary.

RDBMSes are nothing but tools that we use to persist our data: they exist to serve us, we should not be wasting our time curating them.

So, what I do is that I treat the database files as something completely expendable.

I have a set of classes describing my "model", from which the database schema is automatically computed, and upon instantiation the model also populates the database with all necessary predefined data if it is missing. So, as a developer you are always working on your own local database, (which, incidentally, may be HSQLDB for speed,) and you can at any moment drop all the tables of your database, or even the entire catalog, and re-run the application, at which point the application will re-create anything that it does not find to exist. This means that you can revert to any revision or switch to any branch at any moment, and you are immediately good to go.

The tests also create their own throw-away catalogs that they additionally populate with the sample data that they need in order to run. They make use of the model classes, so the database is first automatically created for them, and then each one of them adds the test data that it needs.  I use the package name of the test (namespace name in .Net parlance) as the name of the catalog for each test, so that one test suite does not foul up the data of another test suite.

Maintaining the actual business data for the production environment is the sole responsibility of the operations department. When a release is made by the developers to the operations, it is the operations who need to convert any old data that they have to the new database format. Developers could in theory help them by providing entry points that can be invoked to convert an old version to a new version, but it turns out that this causes more trouble than it saves, so in actuality the operations are left completely on their own. They have engineers, they know how to write scripts for the RDBMS that they use, they can handle it just fine.  They are also the ones who have the knowledge of precisely how the old information should be converted to the new information, and what kinds of values are suitable as defaults for newly introduced columns.

From this it follows that the only kinds of files that need to be stored into the version control system are the code, and a minimal amount of configuration files.

One more thing as a bonus:

You might be tempted to maintain the structure of your database as an SQL file containing all the DDL necessary to describe your schema, and all the DML necessary to populate the new schema with predefined data.  Don't do it.

Information contained within configuration files and scripts must never overlap or duplicate information represented in code. A schema file which lists the tables of the database and the columns of each table is evil, because your code will presumably have to be written to also have knowledge of these same entities, so altering the schema file will not do you any good unless the corresponding changes are made in the code, and changing the code is also pointless without reflecting the changes to the schema file with painstaking attention to doing it exactly right. Clearly, one of the two must go.  You cannot get rid of the code, so the schema file is the one that must go.

Not only "Code first", but also "Code only".

Title: How to incorporate a database into a branch-per-issue version control process?

Body:
We're hoping to move to a new branch-per-issue process with development.  To prepare for this, a lot of research and experimenting has been happening in terms of version control, CI, and process of promotion.  The one thing I don't want to fall off the project is the database and it's schema.

The current process we have in place puts us into an expensive position.  We have four SQL Server boxes, each with their own environment worth of data.  There is Staging (for development), Quality (for QA), Beta (for client prototyping), and Production.  We're wanting to begin switching out some of our database model with MariaDB as we implement this new process as well.  However, I'm having trouble putting my head around how we'll go about putting our SQL changes into version control.

Our new process will start off with a master branch, which will be our main code, followed by an integration branch and issue branches.  Each developer will have their own web instance installed to make the needed changes on whatever branch they're working on at the time.  However, we've always worked on the global Staging server for our SQL.  This doesn't seem viable to me in the new process we plan on having.  My guess for this is that each person will have a version of a database (MariaDB) that they make any schema changes to.  So, that's my main question.

Do I use a process of only committing and merging schema changes?  I wouldn't think that committing an entire database is a good idea.  And at that point, how would this be stored in version control (we'll be using Git as our version control)?  Would each schema change be stored as a separate file?

For clarity-sake, what we're thinking of using is a PHP/Apache server to serve out our web content, a Java API back-end, a MariaDB (which we'll move the SQL Server away from) and a Git repository for the version control on the web code and API code.