问:
FP: Capturing the characteristics of a process which blocks, causes side-effects, and may fail
I have a driver function modifyFile that interacts with many sources in the outside world (e.g. HTTP, filesystem). Let's say the code is as such:

```<code>def downloadFile(from: String, to: String): Try[Unit]

def runUnixProcess(cmd: String): Boolean

def modifyFile = {
    downloadFile(from = "http://.../some/file.dat", to = "/tmp/file.dat") //
    val status = runUnixProcess("/usr/bin/somebinaries /tmp/file.dat")
    if (status == Status.OK) deleteFile("/tmp/file.dat")
}
</code>```

For the sake of the argument, let's consider that these functions abide to the Single Responsibility Principle rule, and that modifyFile is only a driver that "integrates" and facilitates communication between separate entities such as OS, File system and web service.

While this function will most likely sit in the higher level of the application logic, some other application function might be built on top of it. Hence, I want to have some kind of proper abstraction (e.g. by wrapping it with a monadic construct) so that we can still compose an even higher abstraction over it.

Now my question: What is the best language construct to abstract this kind of computation? Namely a computation that:

calls to many entities in the external world

may fail, either partially or completely at some steps due to various conditions. To name a few, we might be dealing with filesystem permission issue, network connection issue, unix binaries missing issue, etc.

might need to be ran asynchronously, considering that there are several blocking calls in it.

Is Scalaz's Task up for it?

Or should I simply wrap it as a Future[Try[T]], which basically captures most of the characteristics it exhibits?

答:
I'm not sure how easy this would be to implement in Scala, but here's how I'd look to structure it in Haskell:

To begin I'm going to review a couple of the monads which Haskell and F# provide -- You're probably familiar with them, but I'll review them just to set the stage.

In Haskell there is the IO monad which is used for doing IO operations (e.g. web calls, file-system access) and which keeps side-effects out of pure code.

There are also the Maybe and Either monads; these monads will short-circuit a chain of monadic functions when there's an error/failure in one of the functions, bypassing the remaining functions in the chain.

In F# there's the Async monad (aka workflow/computation expression) -- I'm sure there's some equivalent in Haskell, but I've not worked with one yet -- which lets you run asynchronous operations with code that looks like regular sequential calls. (Here's an intro tutorial on async programming in F#, and there's another tutorial on that site which goes more into the development of the workflow and how bind for it naturally arises from callbacks, but I can't find it at the moment.)

Now, what you're asking about is some way to use all of these at once. There is a way to do this, and it's a little more complex, but it's definitely a nice thing to have in your toolbox.

Beyond monads, there are monad transformers; these allow you to compose monads together, creating a kind of super monad that allows you to use the all capabilities of the monads composing it -- think of it as kind of a monad stack where you can access the individual monads at different levels (using the lift function).

Some example (return) type-signatures:

```<code>IO (Either String a) -- Either & IO
IO (Async (Maybe a)) -- Maybe, Async, IO
</code>```

If, for example, you have a bunch of IO operations you want to run sequentially, any of which might fail, then you'd probably create a transformer stack using the IO and Either monads.

I won't go into the details of them here, but the paper Monad Transformers Step-by-Step is a pretty good introductory resource.

Monad transformers have, IMO, a steep learning curve, so if you're in a hurry to get something implemented then this probably isn't the way to go, but maybe it'll give you some ideas. If you're looking for a long-lasting general abstraction then you probably should consider monad transformers, despite the large up-front investment.

Body:
I'm not sure how easy this would be to implement in Scala, but here's how I'd look to structure it in Haskell:

To begin I'm going to review a couple of the monads which Haskell and F# provide -- You're probably familiar with them, but I'll review them just to set the stage.

In Haskell there is the IO monad which is used for doing IO operations (e.g. web calls, file-system access) and which keeps side-effects out of pure code.

There are also the Maybe and Either monads; these monads will short-circuit a chain of monadic functions when there's an error/failure in one of the functions, bypassing the remaining functions in the chain.

In F# there's the Async monad (aka workflow/computation expression) -- I'm sure there's some equivalent in Haskell, but I've not worked with one yet -- which lets you run asynchronous operations with code that looks like regular sequential calls. (Here's an intro tutorial on async programming in F#, and there's another tutorial on that site which goes more into the development of the workflow and how bind for it naturally arises from callbacks, but I can't find it at the moment.)

Now, what you're asking about is some way to use all of these at once. There is a way to do this, and it's a little more complex, but it's definitely a nice thing to have in your toolbox.

Beyond monads, there are monad transformers; these allow you to compose monads together, creating a kind of super monad that allows you to use the all capabilities of the monads composing it -- think of it as kind of a monad stack where you can access the individual monads at different levels (using the lift function).

Some example (return) type-signatures:

IO (Either String a) -- Either & IO
IO (Async (Maybe a)) -- Maybe, Async, IO

If, for example, you have a bunch of IO operations you want to run sequentially, any of which might fail, then you'd probably create a transformer stack using the IO and Either monads.

I won't go into the details of them here, but the paper Monad Transformers Step-by-Step is a pretty good introductory resource.

Monad transformers have, IMO, a steep learning curve, so if you're in a hurry to get something implemented then this probably isn't the way to go, but maybe it'll give you some ideas. If you're looking for a long-lasting general abstraction then you probably should consider monad transformers, despite the large up-front investment.


问:
Is Red Star OS released under the GPL?
According to Wikipedia, Red Star OS is

is a North Korean Linux-based operating system

Does that mean it's covered by the GPL, or are there exceptions?

答:
My understanding would be: if you come into possession of copy of the Red Star Linux kernel (at least), then it legally must give you the rights enumerated under the GPL.

There is, however, no requirement that they allow you to come into possession of it.

The more usual example of this is internal corporate software. It might be built in such a way as to violate the GPL, e.g. incorporating non-GPL bits, but if it's never distributed to anyone, the GPL is powerless.

Another example: a web application, like, say, GMail, might never be actually distributed to anyone. (Thus the need for the AGPL.)

There are ethical debates about whether loading a non-GPL kernel module causes the running kernel to violate the GPL, but they also aren't distributed.

The GPL itself also explicitly exempts aggregation — so even if it's using a Linux kernel, it could be built to require non-GPL software to be useful.

Android is a bit like that, in most cases; you don't gain GPL rights to, e.g. the pre-loaded Facebook Katana application or radio chip set drivers.

(Not a lawyer and not particularly familiar with this OS)

ContentLicense: CC BY-SA 3.0

Title: Is Red Star OS released under the GPL?


问:
Structure project based on platform or design?
I have a medium sized project (~10,000 lines) that runs on Windows and Linux. However it is only specific components of the program that are platform dependent and are located in a folder called event_producers.

Now my main concern is to how go about organizing this folder since the project starts becoming more complicated and I would like to keep the organization at an optimal level.

Organization based on platform:

```<code>'-- event_producers
          |-- Linux
          |      '--- monitoring.py
          '-- Windows
                 '--- monitoring.py
</code>```

This looks more implementation agnostic which is a bonus since someone can change things in the future without creating any new files. The main problem is that no one can guarantee that every programmer follows the pattern of having a file with the same name in each platform folder.

Organization based on design:

```<code>'-- event_producers
          '-- Monitoring
                 |-- linux.py
                 '-- windows.py
</code>```

This doesn't leave much space from the programmer to organize things in the wrong way. What bothers me is that I have a module called linux.py and windows.py, something I never came across in any other project. Also if in the future a new folder (say Activator) needs to be created, no one can guarantee that the programmer will follow the pattern of naming files according to the platform.

Questions

How would you organize the project and why?

Is there some other advantages/disadvantages with each way that I missed?

答:
Good for you for factoring out the platform specific bits from the bulk of the code. I bet this helps keep the overall project manageable. I think your organization based on platform is the way to go. Platform-specific files go in platform-specific directories, and the files themselves can have names that match what they do. This keeps things very clear, which is a feature of a good design, IMO.

Yes, there is risk of someone omitting platform support when a new file/feature/event producer is added. You can mitigate this by adding a consistency check to your test suite that confirms that each platform has a corresponding set of files. This could be added to your build process so problems can be detected and surfaced early.

Alternatively, you could have a helper script that generates stub files for each (known) platform which are then edited to provide real functionality. You'll also need to replicate all files when a new platform is added, but that's a big job no matter how you approach it.

I think you are on the right track.


问:
Approach to designing a workflow web app that contains some automation
I have been tasked with creating a web application which will provide end-users with a self help workflow, asking them questions and skipping to another part of the workflow depending upon the responses until they reach the end.

This is fine, and I was considering creating a data driven application which administrators could create and save new workflows themselves. This would be based upon the following DB tables:

Categories

Workflows

Steps

Responses

However, I have now been told that these workflows would contain some automated check steps, such as checking a value in a DB somewhere, or a reg key value on the users workstation, or an LDAP value from Active Directory (ad inifinitum) against a known/desired value (which itself would be dynamic in some cases). This completely throws a spanner in the works as now it looks like I'm going to have to hard code all of the workflows into the application, which I was hoping to avoid.

Is there a way that I could approach this that I'm not seeing that will allow me to continue to make the application (somewhat) data driven? Or is it OK/standard to hard code these types of workflows into an app? The customer will be wanting to add new workflows regularly I am told.

For info, I will developing this in C# as we are a MS shop.

答:
I can think of two possible solutions here, but they both require a fair amount of development (but I really can't see a solution where this is not the case). I would also recommend not developing any specific kind of check step until it is actually needed. It's very easy to have requirements for 42 different kinds of automated steps that end up having only two or three of them actually used.

Option 1: Hard-code the Steps

You don't have to hard-code the workflows, but you have to hard-code the automated check steps. I'm assuming that your basic structure would have a Step with multiple Responses and each response sends the person filling out the questionnaire to a new Step right? In that case, you would create different types of Steps.

The basic step would be a 'QuestionStep' that simply has a list of possible Responses the user can define and add himself, with the associated step to jump to

Another step would be the 'DatabaseValueStep' that would allow the user to input a query to be executed and define a list of values that can be returned, with the associated step to jump to.

Another step would be the 'LDAPValueStep' that allows the user to input the AD-property to check and define a list of values that can be returned, with the associated step to jump to.

...

Each kind of automated check step requires development.

Option 2: Push data into a table in your application and check that

You could define a dynamic system of keys and values that are imported into a database. The keys are dynamic and can be added into the database, after which they become available in your application in a CheckStep. You have to create integrations between other systems and this system to get your data, but it offloads the work from your workflow application onto data providers.

For example, you can have a PersonData-table with a 'personid', 'key' and 'value' column. Another application fills the table with birthdates for people by adding rows with the key 'BirthDate'. A PersonCheckStep in your workflow application allows you to define what you want to do for the key 'BirthDate' and knows how to retrieve the data. You can expand this by having ComputerData for PC settings, LDAPData for LDAP Settings, and so on...


答:
JDT's answer is pretty good, but another option you might want to consider is a domain-specific language (DSL). In this approach you define a simple language to capture your workflows, provide primitives for specialized checks and steps, etc., and then write an engine to interpret and execute them.

By keeping everything in a database, or hard-coded, you calcify the system and make it difficult to introduce variation in workflow. By using a language, provided the language admits the richness you need, you push the complexity to the workflow scripts and keep your engine clean and relatively simple.

Adding more special checks and steps could be handled by something akin to libraries, which provide C# implementations for special work needed by the DSL. Again, you are separating the main workflow (in the DSL script), from the checks and steps (in the libraries), from the engine that runs it all. It should keep the complexity manageable.

As an example, a lot of video games have levels defined in a DSL that is interpreted by the game engine. The allows people without strong programming skills to be productive and create something valuable without requiring the most expensive developers to implement all the features of each particular level.

Title: Approach to designing a workflow web app that contains some automation

Body:
I have been tasked with creating a web application which will provide end-users with a self help workflow, asking them questions and skipping to another part of the workflow depending upon the responses until they reach the end.

This is fine, and I was considering creating a data driven application which administrators could create and save new workflows themselves. This would be based upon the following DB tables:

Categories

Workflows

Steps

Responses

However, I have now been told that these workflows would contain some automated check steps, such as checking a value in a DB somewhere, or a reg key value on the users workstation, or an LDAP value from Active Directory (ad inifinitum) against a known/desired value (which itself would be dynamic in some cases). This completely throws a spanner in the works as now it looks like I'm going to have to hard code all of the workflows into the application, which I was hoping to avoid.

Is there a way that I could approach this that I'm not seeing that will allow me to continue to make the application (somewhat) data driven? Or is it OK/standard to hard code these types of workflows into an app? The customer will be wanting to add new workflows regularly I am told.

For info, I will developing this in C# as we are a MS shop.


答:
The question you should be asking yourself is if the effort saved on maintenance (by not having to change code for future user requests) or the additional versatility (such as being able to easily convert and market the app to different users) are worth the additional effort of creating a more generalized system. Don't write a universal condiment dispensing factory when someone asks you to pass the salt.

Another option to think about is making sure the architecture can handle customization, but make a hardcoded version first and worry about creating an administrative interface later.


问:
Hidden dependencies - why not?
Hidden dependencies:

```<code>function __construct($dep_registry){
  $this->db = $dep_registry->get('db');
  $this->request = $dep_registry->get('request');
  ...
}
</code>```

Not so hidden:

```<code>function __construct(Db $db, Request $request, ....){
  $this->db = $db;
  $this->request= $request;
  ...
}
</code>```

The disadvantages of the last is that, if I need to change the class later and need another dependency, I have to change the constructor arguments. And if I change the constructor, I need to also change every file that uses it. With hidden deps the change would only be needed in the two places: the constructor and the registry class. Another fail of the 2nd method is that it's not possible to lazy load dependencies, i always have to pass the instances

So what's the disadvantage of hidden deps and why is it bigger than this disadvantage of not so hidden deps?

If you are using true Inversion of Control, then you shouldn't need
  to. If you need to add another dependency to the class, you should
  look back at what this class is doing. Perhaps you need a sub type
  instead. Adding dependencies could be an indication that you are
  breaking the Open-Closed Principal of programming (Open for extension,
  but closed for Modification).

OK, dependencies should not be hidden was/is a principle too. Principles are all cute and all, but what do they solve in reality, besides not violating other principles? So why is breaking the Open-Closed principle bad (assuming that this is what adding another argument to the constructor does)?

答:
As an outsider looking at this code, it is not clear how the "hidden dependencies" get created to begin with. What if there is no "db" dependency registered? Does it throw an exception, return null? If my class doesn't get a "db" dependency, how bad is that?

Many times people lean towards this pattern when there are too many dependencies to pass in the constructor without making the constructor look like complete garbage. If your class requires a large number of dependencies, consider using "setter injection" instead (for a property named "foo", call "setFoo(...)" to inject that dependency). Reserve constructor arguments for those dependencies that are absolutely required just to have the object exist -- not to use the object, but just to make it exist.

It also raises the question, is this class doing too much? Do you really need some of these dependencies injected at all? There is a balance between dependency injection and coupling. Too far either way and you create headaches for yourself.

Fine, but that still doesn't answer the question. Consider my class only has 1 argument, and on month later I need to add the 2nd one. So I still need to update the 346253453245 files that use my class, right?

If you are using true Inversion of Control, then you shouldn't need to. If you need to add another dependency to the class, you should look back at what this class is doing. Perhaps you need a sub type instead. Adding dependencies could be an indication that you are breaking the Open-Closed Principal of programming (Open for extension, but closed for Modification).

It's not to say you can't modify a class once it is written, but you should not modify the intended use of that class -- it's purpose.

Adding a new dependency tells me the purpose of this class has changed, and it's likely you need to break the class up into other classes, or create a child class extending your original one. That way existing code that does not need the functionality of the new class (and the new dependency) doesn't have to change.

Title: Hidden dependencies - why not?


问:
Dynamic Code Evaluation in Java - Clever or Sloppy?
I am trying to create a flexible ACL framework in Java for my application.

Many ACL frameworks are built on a whitelist of rules, where a rule is in the form of owner:action:resource.  For example,

"JOHN can VIEW resource FOOBAR-1"

"MARY can VIEW resource FOOBAR-1"

"MARY can EDIT resource FOOBAR-1"

This is attractive because the rules can easily be serialized/persisted to a database.  But my application has complex business logic.  For example,

"All users in department 1 with over 5 years of seniority can VIEW resource FOOBAR-1, else not authorized"

"All users in department 2, if the date is after 03/15/2016, can VIEW resource FOOBAR-2, else not authorized"

Upon first thought, it would be a nightmare to devise a database schema that could handle infinitely complex rules such as these.  Therefore, it seems as though I would need to "bake" them into the compiled application, evaluate them for each user, and then produce owner:action:resource rules as a result of the evaluation.  I want to avoid baking the logic into the compiled application.

So, I was thinking of representing a rule in the form of predicate:action:resource, where the predicate is a boolean expression that determines whether a user is allowed.  The predicate would be a string of a JavaScript expression that could be evaluated by Java's Rhino engine.  For example,

return user.getDept() == 1 && user.seniority > 5;

In doing so, the predicates could easily be persisted to the database.

Is this clever?  Is this sloppy?  Is this gimmicky?  Is this over-engineered?  Is this safe (apparently, Java can sandbox the Rhino engine).

答:
I would not have the database contain code.  But you can do something similar by having the database contain function names and then using reflection to call them.  When you add a new condition, you have to add it to your code and your database, but you can combine conditions and parameters that get passed to them to create quite complex evaluations.

In other words, if you have numbered departments, it would be easy to have a UserDepartmentIs check and a TodayIsAfter check and then combine them to have a Department=2 and Today>03/15/2016.  If you then want to have a TodayIsBefore check so that you can end date the permission, you have to write the TodayIsBefore function.

I haven't done this for user permissions, but have done it for data validation, but it should work.


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
First week - Have separate code base line for 2 different client (yes two copy of same code for 2 different client )

Second week (another boss) - No merge both codes and put IF - Else condition on every page

ContentLicense: CC BY-SA 2.5


问:
Many small requests vs. few large requests (API Design)
I'm currently working on a project with an organization as follows:

Client - Gets data from the main server via REST api.

Server - Requests data from various other servers via third-party APIs

Third-party APIs - Services out of my control that provide data to the server (Reddit, Hackernews, Quora, etc.)

For the sake of argument, let's say the client first needs a list of items from each of the third-party APIs. From this list, an item will be chosen at which point the client needs to see the full content of the item as well as responses (i.e. comments) to the item. I'm trying to decide between three options:

A la Carte

In this approach, I would have 3 separate endpoints on my server: one to get the list of items, one to get the main content for an item, and one to get the responses of the item.

Pros: I never make more requests than I need to, requests should be small so generally they should be faster.

Cons: I have to make a lot of requests. After choosing an item from the list, the user may have to wait before seeing the main content and then wait even longer to see the responses

Server-side cache

In this request, I would make a single call to my server to "fetch" all the data for all sources. The data would then be cached on the server. The client would then have the same REST endpoints as before, except there wouldn't be much waiting between calls since my server already has the data and just has to feed it to the client.

Pros: Still easy to implement on the client side, but without the latency issues

Cons: A bit more involved server side, and the first call could take really really long.

Client-side cache

This scenario is similar to the previous one except the client only ever makes one request to the server: give me all of the data. From here it's the client's responsibility to save the data and use it appropriately.

Pros: Easy server implementation, very speedy after the first call

Cons: First call will be very slow, more complicated client-side implementation

I'm not sure which is the best approach, or if maybe I'm missing the obvious solution. Any advice would be greatly appreciated!

答: These three options are not mutually exclusive, you can use an combination of both client-side and server-side caches. However some of data, like comments, may become stale, if kept in cache for too long. Considering you can't check whether that is the case, you should probably refrain from storing it at all. On the other hand content usually doesn't change drastically, so there would be no harm in caching it server-side and then prefetching some of it on the client-side to lower the latency. </p>


问:
When to use ANTLR and when to use a parsing library
I've always wanted to learn how to write a compiler - I've decided to use ANTLR, and am currently reading through the book (its very good by the way)

I'm pretty new to this, so go easy, but the jist seems to be that you write your grammar, transform this into a data structure (usually an AST) and then walk this one or more times actually executing the 'meat' of whatever you want your program to do.

If my input "language" was something like JSON or XML, i.e something that probably has a library that can turn it into a graph of pojos - does this negate the need to do the lexing and parsing with a compiler compiler like ANTLR? clearly if my input is very bespoke then I need to write my own lexer/parser - but could I and should I short-cut this if my input language is already broadly used.

Would be fair to say you could parse, say json, with Jackson,into POJO's and then drive your code of the resulting pojos? - or in this case, does a 'proper' compiler compiler offer some advantage?

Edited (based on the answers) to add

I probably should have pointed out that my question was slightly hypothetical - I wouldn't ever try and build a programming language in XML!

So I guess the deal is that AST != Pojo - and the tree walkers that antlr give you are more useful in the case where you need to 'walk' the data structure and execute code.

答:
You could use either to perform either task. The difference is what each is meant for. You can draw pictures or diagrams in Excel if you want to, but you can also draw a picture in something built for that purpose.

JSON and XML libraries are designed around general purpose loading of documents, pulling parts out of them, or transforming their structures into different structures, etc.

ANTLR on the other hand is a tool designed for generating parsers for compilers. It is tailored specifically to suit the needs of that task.

If you use an xml or json parser to parse either of those, you'll ultimately end up writing a bunch of code that transforms your input into an AST of some sort, for you to process. So, whether you want to write and debug all of that, or use something that gives it to you up front, that's up to you.


问:
Pattern for validating rules having different signatures
I have a class in charge of responding to an input event and maybe triggering another event. To decide, it has several rules to check.

I'm trying to get away from a class looking like this:

```<code>public class Translator {
    public void maybeTranslate() {
        if (!condition1 || !condition2 || !condition3) {
            return;
        }

        // All rules have passed
        translate();
    }
}
</code>```

I'd like this class to know that it has rules to pass, but not know about the implementations of rules. My attempt was to transform it like so:

```<code>public class Translator {
    private Rule[] rules;

    public Translator (Rule[] rules) { this.rules = rules; }

    public void maybeTranslate() {
        for (Rule rule : rules) {
            if (!rule.passes()) {
                return;
            }
        }

        translate();
    }
}
</code>```

where a Rule has this interface:

```<code>public interface Rule {
    boolean passes();
}
</code>```

Here comes my problem: I now have a new rule that takes in a parameter. Its passes method would require a String parameter. Is my foundation wrong with this new requirement? I don't see how I can adapt this pattern to accommodate rules having various parameters.

This parameter would indicate the source of the input event. I can modify maybeTranslate to receive this value from whoever calls it, and change the Rule interface to be boolean passes(String str). Only now, the majority of my rules are getting a parameter they don't care about.

This is in the context of an Android app, where Translator would be instantiated on different fragments.

UPDATE: Some changes from my original question.

This Translator will be used on multiple screens. There is only one screen active at a time, and each screen can have a different set of rules.

Instead of making a rule take in a parameter and act differently, I created multiple screen-dependent rules (ScreenOneRule, ScreenTwoRule, etc.).

Now I would use the class like this:

```<code>public class ScreenOne {
    Translator translator;

    public Screen(Translator translator) { ... }

    public void onSomeEvent() { translator.maybeTranslate(); }
}
</code>```

and I would create the set of rules for ScreenOne in my IoC configuration (this is an attempt at pseudo code):

```<code>Rule[] screenOneRules = new Rule[] { SharedRule1, SharedRule2, ScreenOneRule1 }
ScreenOne screenOne = new Screen(new Translator(screenOneRules))
</code>```

This solves my problem, though I feel like the design is not perfect. What if I get a rule later on that depends on a value only known after the screen has been instantiated? For example, say a rule needs to know the (x,y) coordinates of where the user tapped on screen to trigger onSomeEvent. I have a feeling ScreenOne would need to construct the rules itself in onSomeEvent. I think this is coming back to my original question.

In that case, I would want to have the instantiation of rules somewhere else. Is the solution to have a factory like this?

```<code>public class RuleFactory {
    public Rule[] getRulesForScreenOne(int x, int y, String anotherParameter) {
        return new Rule[] { new SharedRule1(x, y), new SharedRule2(anotherParameter) };
    }
}

public void onSomeEvent() {
    Rule[] rules = RuleFactory.getRulesForScreenOne(x, y, str);
    translator.maybeTranslate(rules);
}
</code>```

At that point, Translator would not receive rules in its constructor. I can't put my finger on it, but I feel like the factory implementation isn't right. Something about that method name.

答:
I guess your Rule class is an example of specification or command pattern. Definitely different rules will need different types of information to do its work, but if it were me, I would not pass those information during method invocation, I would use constructor instead. The information that is different from one rule to another is the implementation detail of that rule, the invoker of the rule should not need to know about that, the invoker just needs to know the public interface of the rule. The knowledge to construct the rule should be put on client or another class.

The client of MyClass is the one that pass array of rules to MyClass, so it can be the one who create the rule, or it can delegate to a factory class to create the rule, or if you use dependency injection, you can rely on IoC to inject the list of rules for you. Either case, the data that is different between each rule class should be passed in Rule at that time:

```<code>//Client
Rule[] rules = new Rule[2];
rules[0] = new AnExampleRule("some context information");
rules[1] = new AnotherRule(12);

MyClass myClass = new MyClass(rules);
</code>```

Body:
I guess your Rule class is an example of specification or command pattern. Definitely different rules will need different types of information to do its work, but if it were me, I would not pass those information during method invocation, I would use constructor instead. The information that is different from one rule to another is the implementation detail of that rule, the invoker of the rule should not need to know about that, the invoker just needs to know the public interface of the rule. The knowledge to construct the rule should be put on client or another class.

The client of MyClass is the one that pass array of rules to MyClass, so it can be the one who create the rule, or it can delegate to a factory class to create the rule, or if you use dependency injection, you can rely on IoC to inject the list of rules for you. Either case, the data that is different between each rule class should be passed in Rule at that time:

//Client
Rule[] rules = new Rule[2];
rules[0] = new AnExampleRule("some context information");
rules[1] = new AnotherRule(12);

MyClass myClass = new MyClass(rules);


问:
What causes floating point rounding errors?
I am aware that floating point arithmetic has precision problems. I usually overcome them by switching to a fixed decimal representation of the number, or simply by neglecting the error.

However, I do not know what are the causes of this inaccuracy. Why are there so many rounding issues with float numbers?

答:
the only really obvious "rounding issue" with floating-point numbers i think about is with moving average filters:

$$\begin{align}
y[n] & = \frac{1}{N}\sum\limits_{i=0}^{N-1} x[n-i] \
 & = y[n-1] + \frac{1}{N}(x[n] - x[n-N]) \
\end{align}$$

to make this work without the buildup of noise, you want to make sure that the $x[n]$ you add in the current samples is precisely the same as the $x[n-N]$ you will subtract $N$ samples into the future.  if it is not, then what is different is a little turd that gets stuck in your delay line and will never come out.  that is because this moving average filter is actually built with an IIR that has a marginally stable pole at $z=1$ and a zero that cancels it inside.  but, it's an integrator and any crap that gets integrated and not entirely removed will exist in the integrator sum forevermore.  this is where fixed-point does not have the same problem that floating-point numbers do.


问:
Deciding factors in pair programming
Are there specific things that you look out for before getting the team into pair programming? Obviously pairing someone who's great with C++ with another who knows ASP.NET best won't get me far, but how about someone who's great with C++ with another who knows Java best but can pick up C++ quick enough? </p>

<p>What else? Experience levels? Character traits? </p>

答: Heh, since my experience on the subject is merely theoretical and I haven't actually got any first-hand experience of any agile development methods, I'll still throw my thoughts to the mill. I would believe that the best outcome from pair programming would be in such situations where the two programmers have a slight difference in their experience and skill levels and have been working in slightly different areas. The "writer" should have less experience than the "reader" to utilize the teamwork the best way. The reason is that the "writer" gets to learn and become much more confident with his/her code and the "reader" gets to share his/her experience to benefit the team and the project. At no point should they feel unequal though; I would imagine that if the "reader" feels less experienced and somewhat lost, then his/her efforts won't be used to their full potential. Active switching of roles, both being able to give and acquire constructive feedback is the key; it's useless to try to pair persons who can't get along that well.</p>

Title: Deciding factors in pair programming

OwnerDisplayName: youngdood


问:
Advantage of Declaring and Initializing Different Object types?
I am learning how to use java to program, and am just learning about abstract classes and how they are useful.
Say I have a class which extends another abstract class, which has 2 methods, one of which is abstract. My other, nonabstract class has 4 methods, two of which are the same as in the abstract class, and also defines the abstract method. When initializing my second object, my course tells me to use: (abstract class) foo = new (nonabstract class)(); My question, is that using this code prevents you from using the methods that have been added in the nonabstract class, and as a result, what is the advantage of using that code over (nonabstract class) foo = new (nonabstract class), which lets you use both the methods in the abstract class and the methods added in the nonabstract class. Thanks for the help in advance.

答:
Containers (lists, etc.) that are defined to hold objects of a certain base class can hold any object extended from that base class. There are many situations in software design where this functionality is useful. The base class may specify that certain behaviors are going to be required, but we may not know exactly how they should be implemented because it will be different depending on the characteristics of the new classes that extend from it.

To borrow from a very common example of polymorphism, in a drawing program, say you have three classes:

abstract class Shape {
    private Point position;

    public Point getPosition(){ return position; }

    // Every Shape has an area, but we don't know
    // how to calculate it until we know what kind
    // of Shape it is. So this is defined, but it's
    // abstract.
    public abstract float getArea();
}

class Rectangle extends Shape {
    private float length;
    private float width;

    public float getArea(){ return length * width; }

    public float getLength(){ return length; }
    public float getWidth(){ return width; }
}

class Circle extends Shape {
    private float radius;

    public float getArea(){ return Math.PI * radius * radius; }

    public float getRadius(){ return radius; }
}
```

<p>Now, in your code, you may have a container that holds <code>Shape</code> objects. They could be <code>Circle</code> or <code>Rectangle</code> objects. By defining your container in terms of the base class, you can now hold both subclasses safely, and you can call both getPosition() and getArea() on anything in the container.</p>

<pre class="lang-java prettyprint-override"><code>List<Shape> shapes = new ArrayList<Shape>();
shapes.add(new Rectangle(5,10));
shapes.add(new Circle(5));

for (Shape s : shapes){
    s.getPosition();  // <-- this is OK
    s.getArea();      // <-- this is OK

    s.getRadius(); // <-- This produces a compiler error
    s.getWidth();  // <-- This produces a compiler error
}
</code>```

Calling getRadius() or getWidth() on a Shape causes a compiler error, since Shape doesn't provide those methods. You would have to know more about the object and cast the object to the correct type before calling the more specific methods.

if (s instanceof Rectangle){
    ((Rectangle)s).getWidth();
}

if (s instanceof Circle){
    ((Circle)s).getRadius();
}
```

Note that this example specifically uses an abstract base class with inheritance, since there is something the base class can actually implement (the position). In the case where the base class is purely abstract, and does not provide any concrete implementation to be inherited by the sub-classes, you would probably define an interface, rather than a class. And the sub-classes would implement the interfaces.

Body:
Containers (lists, etc.) that are defined to hold objects of a certain base class can hold any object extended from that base class. There are many situations in software design where this functionality is useful. The base class may specify that certain behaviors are going to be required, but we may not know exactly how they should be implemented because it will be different depending on the characteristics of the new classes that extend from it.

To borrow from a very common example of polymorphism, in a drawing program, say you have three classes:

abstract class Shape {
    private Point position;

    public Point getPosition(){ return position; }

    // Every Shape has an area, but we don't know
    // how to calculate it until we know what kind
    // of Shape it is. So this is defined, but it's
    // abstract.
    public abstract float getArea();
}

class Rectangle extends Shape {
    private float length;
    private float width;

    public float getArea(){ return length * width; }

    public float getLength(){ return length; }
    public float getWidth(){ return width; }
}

class Circle extends Shape {
    private float radius;

    public float getArea(){ return Math.PI * radius * radius; }

    public float getRadius(){ return radius; }
}

Now, in your code, you may have a container that holds Shape objects. They could be Circle or Rectangle objects. By defining your container in terms of the base class, you can now hold both subclasses safely, and you can call both getPosition() and getArea() on anything in the container.

List<Shape> shapes = new ArrayList<Shape>();
shapes.add(new Rectangle(5,10));
shapes.add(new Circle(5));

for (Shape s : shapes){
    s.getPosition();  // <-- this is OK
    s.getArea();      // <-- this is OK

    s.getRadius(); // <-- This produces a compiler error
    s.getWidth();  // <-- This produces a compiler error
}

Calling getRadius() or getWidth() on a Shape causes a compiler error, since Shape doesn't provide those methods. You would have to know more about the object and cast the object to the correct type before calling the more specific methods.

if (s instanceof Rectangle){
    ((Rectangle)s).getWidth();
}

if (s instanceof Circle){
    ((Circle)s).getRadius();
}

Note that this example specifically uses an abstract base class with inheritance, since there is something the base class can actually implement (the position). In the case where the base class is purely abstract, and does not provide any concrete implementation to be inherited by the sub-classes, you would probably define an interface, rather than a class. And the sub-classes would implement the interfaces.


问:
When to make a method part of an interface or a concrete implementation?
I create an interface for database access to a MySQL database.  Currently, this is the only way to access day, but to make it easier to test and in the event that the data access might change, I used an interface.

However, now I am faced with the dilemma of which methods I should put on the interface and which methods I should put on the concrete implementation" directly.  Is there a rule of thumb for this?

I will give an example below where I have some CRUD operations for a ICar interface, but then some other utility functions that are just on the concrete implementation.  Should these be on the interface as well?  I wouldn't want a user to have to implement every method if they didn't need to?

```<code>interface ICar {
   Car GetCar(int id);
   void DeleteCar(int id);
   void InsertCar(Car car)
   Car UpdateCar(Car car);
}

class Car : ICar {

  Car GetCar(int id) {}

  void DeleteCar(int id) {}

  void InsertCar(Car car) {}

  Car UpdateCar(Car car) {}

  // methods not on interface, but should they be

  public string GetCarVIN(Car car) {}

  public string GetCarColor(Car car) {}

  public string GetCarMake(Car car) {}

  public string GetCarModel(Car car) {}

  public string GetCarOwner(Car car) {}
}
</code>```

答:
The interface should be as generic as possible. So, while this is an interface of Cars, if we assume that any car will be capable of having an owner, then the method for getting the owner should be inside the interface.

However, any non-generic method, e.g. the method for taking the model of the Car's TV should not be inside the interface, since not all cars will have a TV.

Try to include the methods that any car can have inside the interface. All the other methods that only some cars will possess will be left outside the interface.


问:
Non-fixed-size Fenwick Tree implementation
I'm planning to implement a non-fixed-size Fenwick tree. That is, a Fenwick tree that allows interleaving range queries with adding/removing elements.

All implementations and samples I've seen so far are for fixed-size Fenwick trees, where the number of elements is known before preprocessing the frequencies. They use a fixed size array, so it's not possible to add or remove elements after preprocessing is done. (Well, it is possible, but I'd need to re-build the structure).

I thought of extending TreeMap or maybe AbstractMap, but as TreeMap is actually a red-black tree, I don't know how to implement the red-black mechanics (so that the tree remains balanced) without loosing the cumulative sums of nodes involved in the rebalancing process.

So I thought that maybe I should take another approach: why not extend or adapt a simple random access ArrayList and re-calculate all cumulative sums when the underlying array is resized? This would of course have an impact but, hey, that's exactly what a HashMapdoes.

This is why I wanted to ask here first, in case someone has already done it, and to check which approach you think is the best.

答:
This is the first time I heard of this data structure. What sized trees are you aiming for? Unless it's just thousands, it's probably not going to matter much which underlying data structure you start with.

From Wikipedia, I understand that index-based access to the structure is important. For that reason, I would go with an implementation based on plain ArrayList to start with.

Remember that the point of an ADT is that you can swap out the implementation details while keeping the interface intact.


问:
Stopping asynchronous systems
I have a system which has 5 services. Each are run in a separate process. They resemble an assembly line, in the sense that they mostly process messages in the same order 1->2->3->4->5, however it's not always the case that the processing is linear. There are cases where it can skip though the chain (e.g. 1->2->5) or go backwards (e.g. 1->2->4->3->1) or even zig-zag (1->2->4->3->5).

The system is fed payloads to process one by one, starting with service 1. Given the system is asynchronous and non-linear, I cannot really know when the whole system processed each of the payloads. On the other hand, I want the system to stop sometimes and the best choice is as soon as it processed all the payloads.

These solutions would not be too good:

A simple kill or using a poison-pill approach would not work (example https://stackoverflow.com/questions/13847963/akka-kill-vs-stop-vs-poison-pill), as then I could possibly end up not processing the payload completely (1->2->1 would fail, as 1 would have been stopped after 2 received the last payload)

I can do a timeout approach, however that would not work for two reasons: a) it will hinder development / testing (e.g. if I waited 1 minute for a 5-sec payload effective processing time), b) timeouts still can be too low, so I could run into issues if some services did not finishe processing

I was thinking about creating another service that would serve as a two-phase commit kind of stopper. The idea would go along these lines:

Any service could call stopper to say "I want the system to stop"

Stopper would call all other services and tell them "Stop has been requested"

Other services will wait till they process what they have in the queue and tell stopper "I can to be stopped"

Stopper will wait till it collects "I can be stopped" from all services, then broadcast "Perform stop"

All services will then go ahead and stop their respective processes in a graceful manner

I have issues with the above:

It looks overly complex for the benefit (compared to "just wait 1 minute then stop" and not adding any non-business code), not sure if worth the trade-off

I would have to infuse logic related to stopping into all services and it would have to be coupled to both the queuing mechanism (so it knows when there are not more payload messages) and business logic (so it knows when the payload itself is done processing)

There are still some edge cases to be considered. E.g. in 1->2->1 scenario, 1 could finish, 2 could be processing the last payload, when it's done it could send a message to 1 and to stopper service, stopper will send "Perform stop" and 1 could receive that message before it received a message from 2 that it should process, so it could stop prematurely

Are there best practices or examples of how to achieve this in some other way? Or maybe constraining the system in some other way that would make this problem disappear / easier to manage?

答:
Simply have a "STOP" control message.

Send it to process 1,

Process 1 should forward a STOP message to all the other processes.

Each process on receiving a STOP message should drain all messages from its queue, wait for more messages to appear on the queue (20 seconds or so) and if no more messages arrive in that time then shutdown otherwise process the remaining messages and wait another 20 seconds.

You will need some mechanism to differentiate a genuinely "new" message from outside the system arriving at process 1 (which you do not want to process) and messages generated internally by processes 2-5 which you do want to process before shutting down.

Title: Stopping asynchronous systems


Title: How to draw rectangles for 2D arrays

Body:
I have an 2D boolean array that looks like this:

```<code>[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][1][1][1][0][0][0][0]
[0][0][0][1][1][1][0][0][0][0]
[0][0][0][1][1][1][0][0][0][0]
[0][0][0][1][1][1][0][0][0][0]
[0][0][0][1][1][1][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
</code>```

(0 = false, 1 = true)

I've found a way to combine neighbouring zeros on the horizontal plane like like:

```<code>[----------------------------]
[----------------------------]
[----------------------------]
[-------][1][1][1][----------]
[-------][1][1][1][----------]
[-------][1][1][1][----------]
[-------][1][1][1][----------]
[-------][1][1][1][----------]
[----------------------------]
[----------------------------]
</code>```

The code for achieving this is as such:

```<code>for y = 0 to ySize
    for x = 0 to xSize
        if array[y][x] = 0
            set width = 1

            for x2 = x + 1 to xSize
                if array[y][x2] = 0
                    width++
                else
                    break

            add object at x, y and set width to width
            set x = x + width - 1
</code>```

So it loops the 2D array looking for zeros, and if it finds one, it loops until the end of the row to find where it is no longer a zero.

It then creates an object at the position where it first found a zero, and stretches it to fill the part until it is not a zero.

I want to adapt this code in order to make rectangles instead of long planks, like:

```<code> ____________________________
|                            |
|                            |   <------ rect at 0, 0 with size (10, 3)
|____________________________|
|       |[1][1][1]|          |
|       |[1][1][1]|          |
|       |[1][1][1]|          |   <------ rect at 6, 3 with size (4, 5)
|       |[1][1][1]|          |
|       |[1][1][1]|__________|
|       |                    |
|_______|____________________|   <------ rect at 3, 8 with size (7, 2)

   ^
   |
   |
  rect at 0, 3 with size (3, 7)
</code>```

So instead of making 15 horizontal planks, it makes 4 rectangles that surround the ones.

In short, I want to create an algorithm that will, when given an 2D array of ones and zeros, create rectangles around the ones.

For a smaller example:

```<code>             {
[0][0][0]         { 0, 0, 0 },
[0][1][0]         { 0, 1, 0 },
[0][0][0]         { 0, 0, 0 }
             }
</code>```

Will return the position and dimension of rectangles such as:

```<code>[-------]
[-][1][-]
[-------]

{
    {0, 0, 3, 1}, //rect at (0, 0) with width 3, height 1
    {0, 1, 1, 1}, //rect at (0, 1) with width 1, height 1
    {2, 1, 1, 1}, //rect at (2, 1) with width 1, height 1
    {0, 2, 3, 1}  //rect at (0, 2) with width 3, height 1
}
</code>```

What should this algorithm look like?

Edit: There should be some effort to minimize number of rectangles used (otherwise, it could just leave it as is).

Also, it doesn't matter if it prefers horizontal or vertical rectangles. Example:

```<code>[-------]
[-][1][-]
[-------]
</code>```

is the same as

```<code> _     _
| |[ ]| |
| |[1]| |
|_|[ ]|_|
</code>```

In the end, both have 4 rectangles surrounding the [1].

Body:
I think this is a not so easy problem, when handling more complex arrays, such as :

[0][0][0][0][0][0][1][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][1][0][0][0][0][0]
[0][0][0][0][0][0][0][1][0][0]
[0][0][0][0][0][1][0][0][1][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][1][0][0][0]
[0][0][0][0][1][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][1][0][0][0][0][0][0]

The real complexity lies in the attempt to use the least possible rectangles. One approach would be to calculate the column of the first '1' appearing in each row. Then, the minimum column is used to create a subarray. For instance :

[0][0][0][0][0][0][1][0][0][0] (6)              |--------|0][0][0][1][0][0][0]
[0][0][0][0][0][0][0][0][0][0] (-1)             |        |0][0][0][0][0][0][0]
[0][0][0][0][1][0][0][0][0][0] (4)              |        |0][1][0][0][0][0][0]
[0][0][0][0][0][0][0][1][0][0] (7)              |        |0][0][0][0][1][0][0]
[0][0][0][0][0][1][0][0][1][0] (5) -> min=3 ->  |        |0][0][1][0][0][1][0] --> ...
[0][0][0][0][0][0][0][0][0][0] (-1)             |        |0][0][0][0][0][0][0]
[0][0][0][0][0][0][1][0][0][0] (6)              |        |0][0][0][1][0][0][0]
[0][0][0][0][1][0][0][0][0][0] (4)              |        |0][1][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0] (-1)             |        |0][0][0][0][0][0][0]
[0][0][0][1][0][0][0][0][0][0] (3)              ---------|1][0][0][0][0][0][0]

Then continue iterating from the 1st row. However, I am not sure if this solution finds the smallest number of rectangles.

Another approach would be to start from the point that is the nearest to the center of the 2D array and execute a BFS algorithm, until you find a '1'. Then, this BFS will have created a rectangle and then the next iteration will be executed for the new point that is the nearest to the center. This approach is for sure sub-optimal, since a lot of small rectangles will be created in corners.


问:
What is a good speed for a webscraper?
I'm currently working on a webscraper that is going to be processing about 2 million pages in total. But I'm not entirely sure how to benchmark it.

Currently it processes about 100,000 pages in an hour at about 2mb/s.
It isn't saturating the the bandwidth of the server but I've tried a lot of ways to make it quicker but to no avail. CPU is running 50% or so on average.

答:
What is a good speed for a webscraper?

That's impossible to answer.  It depends on many things; e.g.

How rate at which the site you are scraping can (or is willing to) handle your requests.

The effective network latency and bandwidth when fetching web pages.

How much work your machine has to do to process each scraped page and record the information you extracted.

If you are running at 50% CPU, you may be able to do better, or you may not.  For instance, if your requests are being throttled / limited by the remote server, or if that's as fast as it can go, then you are stuck.  If you are running into network latency / bandwidth issues then you may need to upgrade your network connection ... or move to a data centre that is nearer the site you are trying to scrape.

OwnerDisplayName: Fredrik

Title: What is a good speed for a webscraper?


问:
Should I initialize a member variable in declaration when it is initialized by a constructor parameter?
Which is recommended for initialization of class fields in C#:

```<code>class Foo
{
    public X x = new X(); // or any default value...
    public Foo(X _x)
    {
       x = _x;
    }
}
</code>```

Or

```<code>class Foo
{
    public X x;
    public Foo(X _x)
    {
       x = _x;
    }
}
</code>```

Please note in the second version, it is probable that I introduce other constructors where x may not be initialized!

答:
You should choose between init in declaration or constructor, not both.

In a language that has a default constructor where you don't have to explicitly provide a constructor if the default is all you need, a declaration init may be fine. As soon as you need an explicit constructor with parameter, I tend to move everything to constructor(s), to ensure that init behaviour is in one place.

Too be honest, I hardly ever use declaration init, but that may just be preference. My perceived advantage is that all init behaviour is always encapsulated in constructors: I never have to look in two places (or miss it up in the variable declaration).

Re:

"it is probable that I introduce other constructors where x may not be initialized"

You should always code constructors to re-use another constructor as appropriate. E.g. in your example, adding another constructor with additional param could be done like this:

class Foo
{
    public X x;
    public Y y;

    public Foo(X _x)
    {
       x = _x ?? new X();
    }

    //WRONG!
    public Foo(X _x, Y _y)
    {
       x = _x;
       y = _y;
    }

    //Right
    public Foo(X _x, Y _y)
    {
       this(_x);
       y = _y ?? new Y();
    }
}
```

Finally, when delegating to another constructor, always prefer this() to base() (super() in Java) since it adds to local cohesion. For more detail on this() vs base() in C#, see e.g. https://stackoverflow.com/questions/3797528/base-and-this-constructors-best-practices

Body:
You should choose between init in declaration or constructor, not both.

In a language that has a default constructor where you don't have to explicitly provide a constructor if the default is all you need, a declaration init may be fine. As soon as you need an explicit constructor with parameter, I tend to move everything to constructor(s), to ensure that init behaviour is in one place.

Too be honest, I hardly ever use declaration init, but that may just be preference. My perceived advantage is that all init behaviour is always encapsulated in constructors: I never have to look in two places (or miss it up in the variable declaration).

Re:

"it is probable that I introduce other constructors where x may not be initialized"

You should always code constructors to re-use another constructor as appropriate. E.g. in your example, adding another constructor with additional param could be done like this:

class Foo
{
    public X x;
    public Y y;

    public Foo(X _x)
    {
       x = _x ?? new X();
    }

    //WRONG!
    public Foo(X _x, Y _y)
    {
       x = _x;
       y = _y;
    }

    //Right
    public Foo(X _x, Y _y)
    {
       this(_x);
       y = _y ?? new Y();
    }
}

Finally, when delegating to another constructor, always prefer this() to base() (super() in Java) since it adds to local cohesion. For more detail on this() vs base() in C#, see e.g. https://stackoverflow.com/questions/3797528/base-and-this-constructors-best-practices


问:
Upgrading inherited 3rd party code with changes
I inherited a php project of 3rd party code with a good deal of company-specific customization lumped on top of it.  Now I've got to upgrade it and the person who owned the project is the one I've replaced and no one else knows what changes are 3rd party changes and what changes are company specific.

It's not too terrible a situation because he did check in the initial version of the application from a few updates back.  But then he checked in 2 or 3 updates and about 10 or 15 patches.

So, say I've got a completely generic 3rd party version from the company we bought the code from.  How do I go about merging the changes the last developer made into a fresh version.  We're using git.

答:
There's a few approaches you might consider:

You could download a vanilla copy of the library from the same version as used in your project. Then use a diff utility to find what has been changed between your version and the vanilla version. This approach could work well if you know the version and there aren't too many changes.

You could use git log to find commits affecting the directory containing the library then use that to determine what changes have been made. This won't work if you're not 100% certain that no changes were made before the library was initially committed.

If you're really confident in your automated testing suite then you could try just swapping the libraries and seeing what fails. I wouldn't do this if you suspect there has been changes within the original methods of the library, but if only new methods have been added you'll probably find which are missing.

If you're reasonably confident that the patches made since won't interfere with the changes then you could use git format-patch to generate a patch file for all the changes since your local version, then git apply to make those changes to your local copy.

While options 2 - 4 are probably more sophisticated, option 1 is probably what I'd end up doing most often.


问:
How would a compiler turn an else-if cascade into a switch?
I don't like switch in C and its descendants. Maybe it's the need for a break or the clumsiness of the syntax requiring a shifting of mental gears, I don't know.

Whatever the reason, I will almost always write a sequence of else-if conditions examining the same variable rather than write a switch.

I see from Is there any significant difference between using if/else and switch-case in C#? that switch is more efficient in most cases and it got me wondering...

How would a compiler (for a language with C-like if, else and switch) detect a number of else-if conditions on the same value and internally re-write it into a switch?

答:
Your optimization wish (of transforming a sequence of if into the equivalent of a switch) makes sense only (as Jörg W Mittag wisely commented) for idempotent conditions (which are undecidable to detect in general). But we could restrict these conditions to be a disjunction of equality tests like x == k where x is always the same (SSA-form) simple scalar variable (e.g. some declared int local variable in C or C++) which is unmodified in then parts and k is a compile-time constant.

As far as I know, some versions of GCC in some optimizations modes have been able of such an optimization. And I just checked (in march 2015), my Clang 3.5 (invoked as clang -O3 -fverbose-asm -S) is doing such an optimization with the code below, while my GCC 4.9 don't do it (on GNU/Linux/Debian/Sid/x86-64) :

```<code> extern void f_a(int);
 extern void f_b(int);
 extern void f_c(int);
 extern void f_d(int);
 extern void f_e(int);
 extern void f_f(int);
 extern void f_g(int);
 extern void f_h(int);
 extern void f_i(int);
 extern void f_j(int);
 extern void f_k(int);
 extern void f_l(int);
 extern void f_m(int);
 extern void f_n(int);

 void f1(int x, int y)
 {
   if (x=='a') f_a(y);
   else if (x=='b') f_b(y);
   else if (x=='c') f_c(y);
   else if (x=='d') f_d(y);
   else if (x=='e') f_e(y);
   else if (x=='f') f_f(y);
   else if (x=='g') f_g(y);
   else if (x=='h') f_h(y);
   else if (x=='i') f_i(y);
   else if (x=='j') f_j(y);
   else if (x=='k') f_k(y);
   else if (x=='l') f_l(y);
   else if (x=='m') f_m(y);
   else if (x=='n') f_n(y);
 }
</code>```

I guess that GCC don't optimize like you want because it is not worth doing. GCC is often producing slightly faster code than Clang.

BTW, switch is not always compiled into an indirect jump. In particular a switch with a dozen of widely spread cases is not compiled using a jump table, e.g. code like

```<code>unsigned u = something(x); /// practically would be some hash function
switch (u) {
  case 3935272677: do_some_A(x); break;
  case 2389398680: do_some_B(x); break;
  case 1384792968: do_some_C(x); break;
  case 3957729125: do_some_D(x); break;
  case 4174747340: do_some_E(x); break;
  /// etc...
  default: do_other_thing(x); break;
}
</code>```

In practice with gcc -O3 -fverbose-asm -S such code is compiled as a tree of branches.

You should read the paper by Roger Anthony Sayle A Superoptimizer Analysis of Multiway Branch Code Generation (GCC Summit 2008)

Also, match expressions in Ocaml are perhaps relevant, they are not always compiled as naive sequence of tests, but usually as a tree of tests.

There is a significant literature on compiling pattern matching. See Rete algorithm for a start, and Luc Maranget & Fabrice Le Fessant paper on Optimizing Pattern Matching (ICFP2001); you'll find a lot of papers and conferences on the subject.

BTW, your implicit hypothesis that some indirect branch is always faster than a serie of jumps is naive (on current processors), because of TLB, CPU caches, branch predictors, instruction pipelines, conditional moves machine instructions, etc etc... Read also about threaded code and notice that both GCC and Clang/LLVM accept the (very useful) label as values and computed goto extension to C.

Read also about GNU gperf perfect hash generator.

At last, you should not care and leave such micro-optimizations to the compiler ! If you feel (but I don't) that a long series of if is more readable than a long switch code as you prefer.

Body:
Your optimization wish (of transforming a sequence of if into the equivalent of a switch) makes sense only (as Jörg W Mittag wisely commented) for idempotent conditions (which are undecidable to detect in general). But we could restrict these conditions to be a disjunction of equality tests like x == k where x is always the same (SSA-form) simple scalar variable (e.g. some declared int local variable in C or C++) which is unmodified in then parts and k is a compile-time constant.

As far as I know, some versions of GCC in some optimizations modes have been able of such an optimization. And I just checked (in march 2015), my Clang 3.5 (invoked as clang -O3 -fverbose-asm -S) is doing such an optimization with the code below, while my GCC 4.9 don't do it (on GNU/Linux/Debian/Sid/x86-64) :

 extern void f_a(int);
 extern void f_b(int);
 extern void f_c(int);
 extern void f_d(int);
 extern void f_e(int);
 extern void f_f(int);
 extern void f_g(int);
 extern void f_h(int);
 extern void f_i(int);
 extern void f_j(int);
 extern void f_k(int);
 extern void f_l(int);
 extern void f_m(int);
 extern void f_n(int);

 void f1(int x, int y)
 {
   if (x=='a') f_a(y);
   else if (x=='b') f_b(y);
   else if (x=='c') f_c(y);
   else if (x=='d') f_d(y);
   else if (x=='e') f_e(y);
   else if (x=='f') f_f(y);
   else if (x=='g') f_g(y);
   else if (x=='h') f_h(y);
   else if (x=='i') f_i(y);
   else if (x=='j') f_j(y);
   else if (x=='k') f_k(y);
   else if (x=='l') f_l(y);
   else if (x=='m') f_m(y);
   else if (x=='n') f_n(y);
 }

I guess that GCC don't optimize like you want because it is not worth doing. GCC is often producing slightly faster code than Clang.

BTW, switch is not always compiled into an indirect jump. In particular a switch with a dozen of widely spread cases is not compiled using a jump table, e.g. code like

unsigned u = something(x); /// practically would be some hash function
switch (u) {
  case 3935272677: do_some_A(x); break;
  case 2389398680: do_some_B(x); break;
  case 1384792968: do_some_C(x); break;
  case 3957729125: do_some_D(x); break;
  case 4174747340: do_some_E(x); break;
  /// etc...
  default: do_other_thing(x); break;
}

In practice with gcc -O3 -fverbose-asm -S such code is compiled as a tree of branches.

You should read the paper by Roger Anthony Sayle A Superoptimizer Analysis of Multiway Branch Code Generation (GCC Summit 2008)

Also, match expressions in Ocaml are perhaps relevant, they are not always compiled as naive sequence of tests, but usually as a tree of tests.

There is a significant literature on compiling pattern matching. See Rete algorithm for a start, and Luc Maranget & Fabrice Le Fessant paper on Optimizing Pattern Matching (ICFP2001); you'll find a lot of papers and conferences on the subject.

BTW, your implicit hypothesis that some indirect branch is always faster than a serie of jumps is naive (on current processors), because of TLB, CPU caches, branch predictors, instruction pipelines, conditional moves machine instructions, etc etc... Read also about threaded code and notice that both GCC and Clang/LLVM accept the (very useful) label as values and computed goto extension to C.

Read also about GNU gperf perfect hash generator.

At last, you should not care and leave such micro-optimizations to the compiler ! If you feel (but I don't) that a long series of if is more readable than a long switch code as you prefer.


问:
Change routing to comply with Law of Demeter
I have a Task, Owner and Plan. Charge values are kept in a plan, owner is on a particular plan and task knows its owner.

A task needs to setup its charges based on the knowledge the owner has. Owner however needs to consult a plan to get those done. According to the Law of Demeter I am not allowed to do:

```<code>class Task {

    /**
     * @var Owner
     */
    private $owner;

    public function prepareCharges() {
        $plan = $this->owner->getPlan();
        $plan->chargeFor(...);
    }
</code>```

So I am wondering if this sort of routing trick is a viable solution.

```<code>class Task {

    /**
     * @var Owner
     */
    private $owner;

    public function prepareCharges() {
        $this->owner->helpMeDoTheCharges($this);
    }

    public function doPlanCharges(Plan $plan) {
        $distanceCharge = new Money();
        $plan->chargeFor('distance', $distanceCharge);

        $fixedCharge = new Money();
        $plan->chargeFor('fixed', $fixedCharge);
    }

}
</code>```

Task basically tells its owner to push the plan to it so it can send it messages.

```<code>class Plan {

    public function chargeFor($type, Money $money) {

    }

}

class Owner {

    private $plan;

    public function helpTaskDoTheCharges(Task $task) {
        $task->doPlanCharges($this->plan);
    }

}
</code>```

答:
I think you should make the owner responsible for managing their charges, and simply pass the task to the owner. That way the task never has to touch the plan at all.

I don't think your alternative is really that much better because a task still has to know about a plan and know that it's responsible for determining the cost.

Here's an example, I'm assuming the task is responsible for determining the cost variable (execution time), the plan is responsible for determining the rate per unit of cost variable, and the customer is responsible for accounting for the cost accrued over time:

```<code>class Task {

    /**
     * @var Owner
     */
    private $owner;

    public function execute() {
        // Do whatever a task does
        $this->owner->charge($this);
    }

   public function getExecutionTime() {
       return 10; // Just an example
   }
}

class Owner {

    private $plan;
    private $bill = 0;

    public function charge(Task $task) {
        $taskCost = $this->plan->calculateCost($task->getExecutionTime());
        $bill += $taskCost;
    }

}

class Plan {

    private $rate = 0.5;

    public function calculateCost($time) {
        return $rate * $time;
    }

}
</code>```

If owners is responsible for invoking the task execution then you might be able to get away with not even passing the owner to the task at all, you could simply invoke the task and get the execution time from within the owner. That way the task wouldn't depend on an owner to run, although if other aspects of your task depend on having an owner then that wouldn't be practical.

Body:
I think you should make the owner responsible for managing their charges, and simply pass the task to the owner. That way the task never has to touch the plan at all.

I don't think your alternative is really that much better because a task still has to know about a plan and know that it's responsible for determining the cost.

Here's an example, I'm assuming the task is responsible for determining the cost variable (execution time), the plan is responsible for determining the rate per unit of cost variable, and the customer is responsible for accounting for the cost accrued over time:

class Task {

    /**
     * @var Owner
     */
    private $owner;

    public function execute() {
        // Do whatever a task does
        $this->owner->charge($this);
    }

   public function getExecutionTime() {
       return 10; // Just an example
   }
}

class Owner {

    private $plan;
    private $bill = 0;

    public function charge(Task $task) {
        $taskCost = $this->plan->calculateCost($task->getExecutionTime());
        $bill += $taskCost;
    }

}

class Plan {

    private $rate = 0.5;

    public function calculateCost($time) {
        return $rate * $time;
    }

}

If owners is responsible for invoking the task execution then you might be able to get away with not even passing the owner to the task at all, you could simply invoke the task and get the execution time from within the owner. That way the task wouldn't depend on an owner to run, although if other aspects of your task depend on having an owner then that wouldn't be practical.


问:
Is the target of 3 dependencies per class always achievable?
I'm reading the Clean Code book and a chapter says that if a class has more than 3 dependencies is a code smell of that class isn't doing one thing. Or what is the same, it isn't following SRP. I'm thinking in certain scenarios in which I am unable to reset the number of dependencies to stick to that number.

Let's say we have an app that connects to a public API REST what offers varied information about a lot entities in our domain. In our app we detect an use case repeated in many places where we request to the API the info about an entity with other dependent entities that it has.

The API REST doesn't offer the data in the format we want because the calls when can make are to get data from a single table on the web database, not offers the data agrouped with other tables as we want. So our use case have to make different Api Call's for to get all different data about the entities we need and then merge in the model we will use in the app.

To connect with the external subsystem we will hide implementation in a single Service class however this class has grown too much resulting a class with a lot methods to get data about all entities of the api rest. So we split this huge class into differents following the Repository pattern. Each class for each possible operations with an entity on the API.

Then, to hide all this concrete and common interaction with the service layer we will use a Facade class to coordinating all this calls. The problem I'm figuring it will have, is that it will have a lot dependencies in her constructor. Will have classes for each repository class and mapper classes to adapt the web data into app data.

The solution in these cases is merge all related dependencies in one so you reduce the number. One example is this: Refactoring to Aggregate Services. http://blog.ploeh.dk/2010/02/02/RefactoringtoAggregateServices/

But you merge when you see a clear relationship. What happend if in your class you can't see that? All classes are granulated but all of them are necesary to achieve the goal but can't not be merged in an aggregate service.

So my question is, the "rule" that more than three dependencies violates SRP is always applicable? Returning to our example, our facade needs to access many repository classes and mapper classes. The mapper classes can be hide on a agreggated service, maybe, but repository classes are fine like are. We could introduce a service locator to store them but it is a very bad practice.

答:
Yes. There is always a way to do this as you can always keep piling abstractions on top of each other. For example, you can combine a mapper and a repository into a service class. Or you can split a single class with different calls to the REST API into a separate class per call.

The real question is not if you can but if you should. Does your application benefit from this hard rule and the added complexity that might come with it?


答:
If your input is serialized as XML or JSON, then you should prefer an existing XML or JSON parser. This makes it ultimately more likely that your parser will be correct, and that aids compatibility and interoperability with other systems. Note that XML is not really a language, but a system for defining new languages sharing common syntax. Writing a correct and performant XML or YAML parser is highly non-trivial, and even JSON has a couple of minor pitfalls.

Once the parser returns a datastructure (e.g. the DOM in case of XML), it is fairly simple to translate that to an AST representation that suits your needs – much simpler than writing a parser of your own, since building the AST would be part of the parser anyway.

In my experience, data serialization formats are not very suitable as a primary input format for an interesting language (however, they might be very suitable for AST serialization). While XML and JSON are human-readable, they are difficult to write by hand. For example, JSON doesn't even have comments and XML has very verbose syntax. While – to a certain degree – syntax is not what ultimately makes or breaks a language, good syntax can often help to clearly convey intent, and a good language will map well to its problem domain in both semantics and syntax.

Title: When to use ANTLR and when to use a parsing library

Body:
I've always wanted to learn how to write a compiler - I've decided to use ANTLR, and am currently reading through the book (its very good by the way)

I'm pretty new to this, so go easy, but the jist seems to be that you write your grammar, transform this into a data structure (usually an AST) and then walk this one or more times actually executing the 'meat' of whatever you want your program to do.

If my input "language" was something like JSON or XML, i.e something that probably has a library that can turn it into a graph of pojos - does this negate the need to do the lexing and parsing with a compiler compiler like ANTLR? clearly if my input is very bespoke then I need to write my own lexer/parser - but could I and should I short-cut this if my input language is already broadly used.

Would be fair to say you could parse, say json, with Jackson,into POJO's and then drive your code of the resulting pojos? - or in this case, does a 'proper' compiler compiler offer some advantage?

Edited (based on the answers) to add

I probably should have pointed out that my question was slightly hypothetical - I wouldn't ever try and build a programming language in XML!

So I guess the deal is that AST != Pojo - and the tree walkers that antlr give you are more useful in the case where you need to 'walk' the data structure and execute code.


问:
Selecting between multiple actions in PHP
I have been programming for a number of years now and in PHP for about 4 of those years. I have always wondered what is the best approach when it comes your program deciding what action to take based on a user action.

Let me narrow this down a little bit. I have a small custom built CMS running, one of the pages allows an admin to view and edit user account details such as name, generate a new password, change payment dates and so on.

I have a number of different actions here:

View all users

View single user

View users (search string)

Edit user

Edit Subscription

Edit Name

Etc

Delete User

Blacklist

For all of these actions i provide a let with GET data, for exampele:

```<code>User A
</code>```

The links for the other things like editing a user would be "action=edit_subscription" for example.

When My page loads i usually use an IF ELSE statement to check if an action is present before doing on.

```<code>if($_GET['action'] == "show_user"){
}
else if($_GET['action'] == "edit_subscription"){
}
</code>```

Once the program matches the action it checks for other data such as UID and then sends that data off into a classes to be processed. Sometimes this can feel a little long winded and can be a little difficult to debug.

I don't know if this is the best way of doing it, i was recently looking into using a switch statement and wondered if this would be better but I'm not sure if it.

So if there a better way for me to achieve this selection process, maybe some sort of pattern that can be used?

Once last point is that i am trying to keep everything in once file (apart from classes) so the HTML and the PHP for matching actions are all in the same .php file, also not 100% sure if this is best practice as well.

Thanks for your time.

答:
I recommend looking at the router code in most modern MVC frameworks. The prevailing approach is to use reflection to invoke a particular function named after the action.

Here's the relevant code from Yii:

https://github.com/yiisoft/yii/blob/master/framework/web/CController.php#L413

https://github.com/yiisoft/yii/blob/master/framework/web/actions/CInlineAction.php#L45

Or from Laravel:

```<code>/**
 * Execute an action on the controller.
 *
 * @param  string  $method
 * @param  array   $parameters
 * @return \Symfony\Component\HttpFoundation\Response
 */
public function callAction($method, $parameters)
{
    return call_user_func_array(array($this, $method), $parameters);
}
</code>```

https://github.com/laravel/framework/blob/5.0/src/Illuminate/Routing/Controller.php#L246

In the Yii example it's looking for a function within the class called action<action name> and calling it if it exists. For example if you invoked the ViewUsers actions it would call the actionViewUsers() function. For friendly URLs there's also often a layer above that maps a path to a controller/action combination.

The advantages of this are numerous:

It avoids massive and unmanageable case or if statements

It keeps variables limited to the scope of their action function

The mapping of action -> function is done dynamically so you don't need to maintain a list of these mappings

Body:
I have been programming for a number of years now and in PHP for about 4 of those years. I have always wondered what is the best approach when it comes your program deciding what action to take based on a user action.

Let me narrow this down a little bit. I have a small custom built CMS running, one of the pages allows an admin to view and edit user account details such as name, generate a new password, change payment dates and so on.

I have a number of different actions here:

View all users

View single user

View users (search string)

Edit user

Edit Subscription

Edit Name

Etc

Delete User

Blacklist

For all of these actions i provide a let with GET data, for exampele:

```<code><a href="users.php?action=show_user&uid=12">User A</a>
</code>```

The links for the other things like editing a user would be "action=edit_subscription" for example.

When My page loads i usually use an IF ELSE statement to check if an action is present before doing on.

```<code>if($_GET['action'] == "show_user"){
}
else if($_GET['action'] == "edit_subscription"){
}
</code>```

Once the program matches the action it checks for other data such as UID and then sends that data off into a classes to be processed. Sometimes this can feel a little long winded and can be a little difficult to debug.

I don't know if this is the best way of doing it, i was recently looking into using a switch statement and wondered if this would be better but I'm not sure if it.

So if there a better way for me to achieve this selection process, maybe some sort of pattern that can be used?

Once last point is that i am trying to keep everything in once file (apart from classes) so the HTML and the PHP for matching actions are all in the same .php file, also not 100% sure if this is best practice as well.

Thanks for your time.

Body:
I recommend looking at the router code in most modern MVC frameworks. The prevailing approach is to use reflection to invoke a particular function named after the action.

Here's the relevant code from Yii:

https://github.com/yiisoft/yii/blob/master/framework/web/CController.php#L413

https://github.com/yiisoft/yii/blob/master/framework/web/actions/CInlineAction.php#L45

Or from Laravel:

/**
 * Execute an action on the controller.
 *
 * @param  string  $method
 * @param  array   $parameters
 * @return \Symfony\Component\HttpFoundation\Response
 */
public function callAction($method, $parameters)
{
    return call_user_func_array(array($this, $method), $parameters);
}

https://github.com/laravel/framework/blob/5.0/src/Illuminate/Routing/Controller.php#L246

In the Yii example it's looking for a function within the class called action<action name> and calling it if it exists. For example if you invoked the ViewUsers actions it would call the actionViewUsers() function. For friendly URLs there's also often a layer above that maps a path to a controller/action combination.

The advantages of this are numerous:

It avoids massive and unmanageable case or if statements

It keeps variables limited to the scope of their action function

The mapping of action -> function is done dynamically so you don't need to maintain a list of these mappings


答:
If you want to get fancy, you could consider a jump table.

Just have an array where the the key is "show_user", "edit_subscription", etc, and the corresponding value is a function to be called. After declaring your array, the actual code is just a single statement to call the function.

I don't have a PHP IDE at the moment, to code it for you, but you can base on the C example.

From memory, something like

```<code>$func = myArray[$_GET['action']];
$func();
</code>```

Title: Selecting between multiple actions in PHP

Body:
If you want to get fancy, you could consider a jump table.

Just have an array where the the key is "show_user", "edit_subscription", etc, and the corresponding value is a function to be called. After declaring your array, the actual code is just a single statement to call the function.

I don't have a PHP IDE at the moment, to code it for you, but you can base on the C example.

From memory, something like

$func = myArray[$_GET['action']];
$func();


问:
Why did Alan Kay say, "The Internet was so well done, but the web was by amateurs"?
OK, so I paraphrased. The full quote:

The Internet was done so well that most people think of it as a natural resource like the Pacific Ocean, rather than something that was man-made. When was the last time a technology with a scale like that was so error-free? The Web, in comparison, is a joke. The Web was done by amateurs. -- Alan Kay.

I am trying to understand the history of the Internet and the web, and this statement is hard to understand. I have read elsewhere that the Internet is now used for very different things than it was designed for, and so perhaps that factors in.

What makes the Internet so well done, and what makes the web so amateurish?

(Of course, Alan Kay is fallible, and no one here is Alan Kay, so we can't know precisely why he said that, but what are some possible explanations?)

*See also the original interview*.

答:
It seems to be due to a fundamental disagreement between Alan Kay versus the people (primarily Tim Berners-Lee) who designed the web, about how such a system should work.

The ideal browser, according to Kay, should really be a mini operating system with only one task: To safely execute code downloaded from the internet. In Kays design, the web does not consist of pages, but of black box "objects" which can contain any kind of code (as long as it is safe). This is why he says a browser shouldn't have features. A browser wouldn't need say a HTML parser or a rendering engine, since all this should be implemented by the objects. This is also the reason he doesn't seem to like standards. If content is not rendered by the browser but by the object itself, there is no need for a standard.

Obviously this would be immensely more powerful than the web today where pages are constrained by the bugs and limitations of the current browsers and web standards.

The philosophy of Tim Berners-Lee, the inventor of the web, is almost the exact opposite. The document "The Principle of Least Power" outline the design principles underlying HTTP, HTML, URL's etc. He points out the benefit of limitations. For example, having a well specified declarative language like HTML is easier to analyze, which makes search engines like Google possible. Indexing is not really possible in Kays web of turing-complete black-box objects. So the lack of constraints on the objects actually makes them much less useful. How valuable are powerful objects if you can't find them? And without a standard notion of links and URLS, Googles page rank algorithm couldn't work. And neither would bookmarks for that matter. Of course the black box web would be totally inaccessible for disabled users also.

Another issue is content production. Now we have various tools, but even from the beginning any amateur could learn to author a html page in notepad. This is what kickstarted the web and made it spread like wildfire. Consider if the only way you could make a web page required you to start programming you own rendering engine? The barrier to entry would be immense.

Java applets and Silverlight resemble to some extent to Kays vision. Both systems are much more flexible and powerful than the web (since you could implement a browser in them), but suffer from the problems outlined above. And both technologies are basically dead in the water.

Tim Berners-Lee was a computer scientist who had experience with networks and information systems before inventing the web. It seems that Kay does not understand the ideas behind the web, and therefore he believes the designers are amateurs without knowledge of computing history. But Tim Berners-Lee certainly wasn't an amateur.


问:
When do I reuse or create a new Builder
I've implemented a Builder Pattern in a project I'm working on.

I'm using this design pattern to created Fields and Components (div, tables, panel (boostrap)).

So I have a Director Component class. It makes a order for a Builder (in this case InputComponentBuilder)

class @DirectorComponent

    @builder = null

    @make = (args...)->
        @builder.make.apply(@builder, args)
        @setResult(result = @builder.getResult())
        return result

    @makeInput = (name, properties)->
        @builder = new InputComponentBuilder()
        return @make.apply(@, arguments)
```

<h3>Source of InputComponent Builder</h3>

<pre class="lang-javascript prettyprint-override"><code>class @InputComponentBuilder extends Builder

    constructor : ()->
        @input = new InputComponent()

    make : (name, properties)->
        @input.extend(properties)
        @input.setName(name)
        obj = $("<input />")
        obj.attr("name", name)
        obj.val(@input.value)
        if @input.placeholder
            obj.attr("placeholder", @input.placeholder)
        obj = BuilderHelper.applyProperties(@input, obj)
        obj = BuilderFieldHelper.applyProperties(@input, obj)
        @input.setObject(obj)
        @setResult(@input)
        return @input
</code>```

The InputComponentBuilder is for generic input fields. So if I want to create specific field like (EmailField, ZipCodeField.. etc) I will need to create another builder extended a InputComponetBuilder? or in class Director I will need to create another method makeZipCodeField and change the recipe sent to InputBuilder?

Base Class (Base class of Class Builder's result)

class @Component

    constructor : ()->
        @id = null
        @name = ""
        @obj = null
        @attrs = {}
        @classes = []
        @css = {}

    extend : (data)->
        $.extend(@, data)

    getObject : ()->
        return @obj

    setObject : (obj)->
        @obj = obj

    setName : (name)->
        @name = name

    getName : ()->
        return @name

    getPropertiesFromObjectComponent : (args...)->
        result = []
        console.log(args, arguments)
        for key, arg of args
            console.log key, arg
            result.push(if arg of @ then @[arg] else null)
        console.log(result)
        return result
```

<h1>Abstract Class for Fields</h1>

<pre class="lang-javascript prettyprint-override"><code>class @FieldComponentAbstract extends Component
    constructor : ()->
        super
        @label = null
        @placeholder = null
        @onclick = null
        @onchange = null
        @onfocus  = null
        @onkeypressed = null
        @onkeyup = null
        @onkeydown = null
        @oninsertednode = null
        @bootstrap = null
        @onblur = null
        @mask = null

    @validate : ()->
        return true
</code>```

InputComponent Class

    class @InputComponent extends FieldComponentAbstract

        constructor : ()->
            super
            @type = "text"
            @value = ""
```

<h1>Calling makeInput</h1>

<pre class="lang-javascript prettyprint-override"><code>@cpf_field = DirectorComponent.makeInput('cpf',
                placeholder: "CPF",
                mask : '999.999.999-99'
                bootstrap: true
            )
</code>```

答: To answer your original question (in title), a Builder is by definition a very stateful object, so after issuing the final "build" and obtaining the constructed object, the Builder is discarded - never re-used.</p>

Title: When do I reuse or create a new Builder


问:
Concurrent collections, should read methods allow multiple threads at one time?
I have custom collection and I want to add wrapper to allow concurrent access.

```<code>public class MyConcurrentCollection<T>
{
    private MyCollection _collection; // passed in constructor

    public void Add(T item)
    {
        //modifies and may temporarily "break" the collection while executing this method
    }

    public bool Contains(T item)
    {
        //only reads
    }

    // other read and write methods
}
</code>```

At this moment, I have object private member that acts as lock in every method, allowing only one thread at a time to access the collection, so every method looks like this:

```<code>public bool Contains(T item)
{
    lock(_lock)
    {
        return _collection.Contains(item);
    }
}
</code>```

However this seems really inefficient. Since Contains() only reads from the collection, should I allow multiple threads into it?

Of course, I need to lock access to Add() and other methods while there are threads in Contains() and I need to block access to Contains() if there is a thread wishing to modify the collection.

Is there any disadvantage of allowing multiple threads into read only methods, or should I stick with my basic solution?

答:
If one thread calls Add, and another thread calls Contains, at exactly the same time, and everything is implemented correctly, then Contains will return either the value that was correct before calling Add, or the value that was correct after calling Add. That's the best that we can expect.

If you can implement both the Add and the Contains method in a way that Contains will return one of these two results, without using a Lock in the contains method, even if it is called right in the middle of Add doing its thing, then you are fine. Typically that is done by Add creating data structures that are not part of the container yet, and then linking everything into the container using a single atomic operation.


问:
Third-party repositories in Subversion; local mods?
I'm building a small app as an interface to support functions, monitoring, web-based running of unit tests, etc. This will be checked into Subversion.

I want to include a third-party app which is also available via Subversion. Thus far I prefer to reference the remote repository to ease upgrades, particularly when I have made local modifications.

Now, I want the third-party app to be distributed alongside the parent app. Subversion externals are out, since I can't commit my local mods. git svn seems like it has potential, but I'm not sure on the details. (Seems dirty to have a .git directory with svn metadata stored in an svn repository.)

So how do you handle modifications to Subversion projects you can't commit to? I'm pretty open to any combination of git and svn, preferably allowing the code to live in our existing Subversion repository.

Update: I'm currently exploring vendor branches, which is more convention than feature. There is a tool called svn_load_dirs.pl to assist with the process.

答:
I use Subversion and what has worked best for me, is storing third party libraries within the repository in a standardised directory structure:

- Library1

-- v1.0

-- v2.0

etc

My goals are:

- ease of discovery

- change tracking

- simple checkout and build (for new Devs and Continuous Integration)

- having no external dependencies so you have everything required to run in the future

There's a good discussion over on SO for this too:

https://stackoverflow.com/questions/49196/storing-third-party-libraries-in-source-control

HTH!