问:
How to display/clarify the licence for code in a blog
Let's say I have a blog available under one of the Creative Commons licences.
Such type of licence would be displayed at the bottom of each page with a link
to the actual licence, etc..

However, apparently, the Creative Commons licences are not really suitable for
software nor for distribution of source code, so, what about any code
(e.g. snippet/fragment or even full programs) that can be part of a blog post?

If I would choose to release this code as GPLv3, would it be acceptable and
clear enough to say, at the bottom of the page, something like: "This website
by Mr. Foo is released under a Creative Commons blah blah, except for any source code in the form of code snippets/fragments/samples, which are released
under GPLv3"?

Or are there better/different/more formal ways to clarify such
situation?

答:
In general, there are three types of content on a development-oriented web page which may be covered by different licenses:

The textual content itself, that is the text of the blog,

The source code,

The visual design (the design itself and the graphical elements, such as the logo).

What I used on many sites (example) and which can be used for a blog as well is the header similar to:

Copyright © 2015 Example Corp. All Rights Reserved, except for the parts enumerated below:

The source code of the product is covered by BSD 3-Clause License.

This page content, excluding the visual design and the logotype, is covered by Creative Commons Attribution/Share-Alike License.

which actually means that:

Content and code are covered by two different licenses,

Everything else that wasn't explicitly mentioned has all rights reserved.

Note that:

If the piece of code on your blog is small, chances are that there is no need for a specific license (and even if there is, it will be dismissed by the readers and you won't be able to enforce its terms anyway in a court).

For instance, snippets such as in this MSDN article can hardly be covered by a license: anybody who have never read the article could be writing the exact same pieces of code by themselves, and it would be practically impossible to prove to a judge that the code was actually copy-pasted.

If the piece of code on your blog is large, the license may be included in the header. Not the full text (please, don't; licenses in the header of the file, written in all capitals, are terribly ugly), but just the mention with eventually the link. This has a benefit compared to mentioning the license in the footer of the page: if the code is copy-pasted, the license has better chance to remain.

/**
 * Author: Somebody <somebody@example.com>
 * Original source: http://blog.example.com/123/
 * License: BSD 3-Clause License (http://opensource.org/licenses/BSD-3-Clause)
 **/
// Code goes here.
```

Also, if you want your code to actually be used, consider a license different from GPL. Since GPL is a very restrictive license, this may not be suited for pieces of code put in your blog.

Body:
In general, there are three types of content on a development-oriented web page which may be covered by different licenses:

The textual content itself, that is the text of the blog,

The source code,

The visual design (the design itself and the graphical elements, such as the logo).

What I used on many sites (example) and which can be used for a blog as well is the header similar to:

Copyright © 2015 Example Corp. All Rights Reserved, except for the parts enumerated below:

The source code of the product is covered by BSD 3-Clause License.

This page content, excluding the visual design and the logotype, is covered by Creative Commons Attribution/Share-Alike License.

which actually means that:

Content and code are covered by two different licenses,

Everything else that wasn't explicitly mentioned has all rights reserved.

Note that:

If the piece of code on your blog is small, chances are that there is no need for a specific license (and even if there is, it will be dismissed by the readers and you won't be able to enforce its terms anyway in a court).

For instance, snippets such as in this MSDN article can hardly be covered by a license: anybody who have never read the article could be writing the exact same pieces of code by themselves, and it would be practically impossible to prove to a judge that the code was actually copy-pasted.

If the piece of code on your blog is large, the license may be included in the header. Not the full text (please, don't; licenses in the header of the file, written in all capitals, are terribly ugly), but just the mention with eventually the link. This has a benefit compared to mentioning the license in the footer of the page: if the code is copy-pasted, the license has better chance to remain.

/**
 * Author: Somebody <somebody@example.com>
 * Original source: http://blog.example.com/123/
 * License: BSD 3-Clause License (http://opensource.org/licenses/BSD-3-Clause)
 **/
// Code goes here.

Also, if you want your code to actually be used, consider a license different from GPL. Since GPL is a very restrictive license, this may not be suited for pieces of code put in your blog.


问:
Design pattern for ensuring the "signature" of generic lists is equal
I have an interface, Attribute, that is going to be implemented in various ways,

```<code>class AttributeA implements Attribute{\\..}
class AttributeB implements Attribute{\\..}
</code>```

Then I'm planning to have a class containing a list of interface members

```<code>class Example {
    List<Attribute> attributes;
    //..
}
</code>```

And then I'm planning to have a class containing a list of those

```<code>class ExamplesAndMore {
    List<Example> examples;
    //..
}
</code>```

But, I want any instatiation of ExamplesAndMore to make sure that it only takes examples of the same type or signature. That is, I want to make sure the examples list doesn' t contain one member whose attributes list is of the form <AttributeA, AttributeA, AttributeB> while another is of the <AttributeA, AttributeA, AttributeA> or <AttributeA, AttributeA, AttributeB, AttributeB>.

I could just check everywhere I modify the examples list.

A comment asked me to be more specific, so I'll give code for how I could do this.

```<code>class Example {
    List<Attribute> attributes;

    public List<Class<? extends Attribute>> getSignature(){
        List<Class<? extends Attribute>> result = new ArrayList<Class<? extends Attribute>>();
        for(Attribute attribute : attributes){
            result.add(attribute.getClass());
        }

        return result;
    }

    //..
}

public class ExamplesAndMore {
    List<Example> examples;
    List<Class<? extends Attribute>> signature;

    public ExamplesAndMore(List<Class<? extends Attribute>> signature){
        this.signature = signature;
        this.examples = new ArrayList<Example>();
    }

    public void addExample(Example example){
        if(!example.getSignature().equals(signature)){
            throw new IllegalArgumentException(String.format("This takes examples with signature %s", signature.toString()));
        }
        examples.add(example);
    }

    //..
}
</code>```

But I wonder if this is a good way of going about this, checking for types at runtime doesn't feel nice. Basically I think this code smells a bit. One way this smell might manifest as an actual problem is when I create

```<code>class GenericAttribute<T> implements Attribute{\\..}
</code>```

with the intention of not having an example with an attribute of type GenericAttribute<ClassA> and one of type GenericAttribute<ClassB> in the same list. Then type erasure ruins my day.

Also, when I don't need examples to contain arbitrarily many attributes but only a fixed number (say 3), then my problem goes away entirely and I can even check at compile-time by having

```<code>class Example<T1, T2, T3> {
    //..
}

public class ExamplesAndMore<T1,T2,T3> {
    List<Example<T1,T2,T3> examples;

    public void addExample(Example<T1,T2,T3> example){\\..}
    //..
}
</code>```

However this approach obviously doesn't extend to examples with arbitrarily many attributes.

Anyway, I feel that I'm missing some obvious technique or something. Is there a nice pattern that deals with this, am I designing this badly? Chances are I'm not the first one doing this.

Also sorry for the lousy title, If I had a better description for my problem I'd probably have better luck searching for an answer and wouldn't have to ask...

答:
It seems slightly odd that Example.attributes can contain a mixture of AttributeA and AttributeB objects, but ExamplesAndMore.examples must contain a 'homogenous' (using that loosely) List of Example objects. How are these supposed to be used, for both Example and ExamplesAndMore classes? Is there also some kind of implied ordering/equivalence between the entries of ExamplesAndMore.examples? Could that be another code-smell?

Staying on topic though, you may want a method inside Example that can reasonably describe the contents of itself... this can be as simple as concatenating the class names of its own entries, as illustrated below. I think that is safe enough since List have a predictable iteration order.

```<code>public String getEntriesDescription() {
    return attributes.stream().map(v -> v.getClass().getName())
                        .collect(Collectors.joining(";"));
}
</code>```

When you are adding an Example object to ExamplesAndMore, you can use that to perform the comparison you want...

```<code>public void addExample(Example example) {
    // assuming you have a field exampleDescription
    if (!exampleDescription.equals(example.getEntriesDescription()) {
        throw new IllegalArgumentException("Example description does not match.");
    }
    examples.add(example);
}
</code>```

This is quite similar to what you have in mind.

ContentLicense: CC BY-SA 3.0

Body:
It seems slightly odd that Example.attributes can contain a mixture of AttributeA and AttributeB objects, but ExamplesAndMore.examples must contain a 'homogenous' (using that loosely) List of Example objects. How are these supposed to be used, for both Example and ExamplesAndMore classes? Is there also some kind of implied ordering/equivalence between the entries of ExamplesAndMore.examples? Could that be another code-smell?

Staying on topic though, you may want a method inside Example that can reasonably describe the contents of itself... this can be as simple as concatenating the class names of its own entries, as illustrated below. I think that is safe enough since List have a predictable iteration order.

public String getEntriesDescription() {
    return attributes.stream().map(v -> v.getClass().getName())
                        .collect(Collectors.joining(";"));
}

When you are adding an Example object to ExamplesAndMore, you can use that to perform the comparison you want...

public void addExample(Example example) {
    // assuming you have a field exampleDescription
    if (!exampleDescription.equals(example.getEntriesDescription()) {
        throw new IllegalArgumentException("Example description does not match.");
    }
    examples.add(example);
}

This is quite similar to what you have in mind.


问:
Is this the solution to static inheritance?
I've seen a lot of posts recently on why Singletons should be avoided. However, I can't see any of those problems with the following solution to a common problem: static inheritance.

For example, I was recently working on a library that scrapes the HTML source of a website and parses its contents into objects. The problem here is, the site has different types of content- articles, videos, etc. In my initial code, I had several different static 'supplier' classes- i.e. ArticleSupplier- that I quickly found shared a lot of boilerplate code (i.e. argument checks).

I could have made the classes instance-based, but it seems pointless: new ArticleSupplier() has no state; all its methods depend on the arguments passed to them. Instantiating another one is just a waste of memory.

This has brought me to thinking about using the Singleton pattern: a base class could perform boilerplate code checks and then call the derived class' implementation; the derived class could then control access with a singleton. Here's a simple example in C#:

```<code>abstract class Supplier
{
    IEnumerable<IModel> RecentModels(int amount)
    {
        return ModelsBefore(DateTime.Now, amount);
    }
    IEnumerable<IModel> ModelsBefore(DateTime date, int amount)
    {
        CheckDate(date);
        CheckAmount(amount);
        return InternalBefore(date, amount);
    }
    abstract IEnumerable<IModel> InternalBefore(DateTime date, int amount);
}

class ArticleSupplier
{
    private static readonly ArticleSupplier _Instance = new ArticleSupplier();
    private ArticleSupplier() { }
    public static ArticleSupplier Instance { get { return _Instance; } }
    override IEnumerable<IModel> InternalBefore(DateTime date, int amount)
    {
        // implementation
    }
}
</code>```

Now, you can focus on the implementation within ArticleSupplier without writing the same boilerplate code, and at the same time control instantiation of the object. I'd like to emphasize again that this is completely thread-safe because the singleton has no state, which is why the method was static in the first place.

Is this an appropriate use of the Singleton pattern, or are there still some pitfalls that I'm missing?

答:
What you are looking for is not a singleton, but a factory. The reason is you have a single object that figures out which logic to execute, then executes it. As you say in your comment, it is functionally similar to a switch statement: figure out which branch to execute, then execute it.

That works fine if your logic is simple, but once it grows in complexity, the switch or cascaded if grows cumbersome. Furthermore, you want the code to load implementations dynamically, not via compile-time selection. It is better to bury this logic in an object instead of one long method. I recommend the following components:

Each "method" or algorithm, i.e. each "supplier" in your example, has a pair of classes:

An actual supplier that does whatever your problem needs it to do.

A service provider that determines if this particular supplier can handle the input, and is able to create the supplier.

One class that represents input data for easy passing between methods (no overloading necessary).

One factory class that accepts input and returns an object capable of processing it.

Example in pseudocode:

```<code>class Input {
  public DateRange range;
  public int quantity;
}

interface ServiceProvider {
  boolean canHandle(Input i);
  object newHandler(object o);
}

class Factory {
  List<ServiceProvider> sps = new ArrayList<>();

  public static void register(ServiceProvider sp) {
    sps.add(sp);
  }

  public static Supplier getSupplier(Input i) {
    for (ServiceProvider sp in sps) {
      if (sp.canHandle(i)) {
        return sp.newHandler(i);
      }
    }
    return null;
  }
}
</code>```

Notes:

This replaces switch with dynamic dispatch via traversing the list and finding an instance that can handle the input.

This is a simple example to give you the idea. Depending on the specific problem at hand, it may be better to use a hash table or other data structure.

Service providers need to register themselves. The specific mechanism to do this is dependent on the language (your question is not tagged with a specific language).

Java can use the Service Provider Interface.

C++, static linking: just call an initialization function to set this up before use.

C++, dynamic linking: set it up in DllMain or the equivalent entry point for your platform.

C#: you can implement the IServiceProvider interface.

Body:
What you are looking for is not a singleton, but a factory. The reason is you have a single object that figures out which logic to execute, then executes it. As you say in your comment, it is functionally similar to a switch statement: figure out which branch to execute, then execute it.

That works fine if your logic is simple, but once it grows in complexity, the switch or cascaded if grows cumbersome. Furthermore, you want the code to load implementations dynamically, not via compile-time selection. It is better to bury this logic in an object instead of one long method. I recommend the following components:

Each "method" or algorithm, i.e. each "supplier" in your example, has a pair of classes:

An actual supplier that does whatever your problem needs it to do.

A service provider that determines if this particular supplier can handle the input, and is able to create the supplier.

One class that represents input data for easy passing between methods (no overloading necessary).

One factory class that accepts input and returns an object capable of processing it.

Example in pseudocode:

class Input {
  public DateRange range;
  public int quantity;
}

interface ServiceProvider {
  boolean canHandle(Input i);
  object newHandler(object o);
}

class Factory {
  List<ServiceProvider> sps = new ArrayList<>();

  public static void register(ServiceProvider sp) {
    sps.add(sp);
  }

  public static Supplier getSupplier(Input i) {
    for (ServiceProvider sp in sps) {
      if (sp.canHandle(i)) {
        return sp.newHandler(i);
      }
    }
    return null;
  }
}

Notes:

This replaces switch with dynamic dispatch via traversing the list and finding an instance that can handle the input.

This is a simple example to give you the idea. Depending on the specific problem at hand, it may be better to use a hash table or other data structure.

Service providers need to register themselves. The specific mechanism to do this is dependent on the language (your question is not tagged with a specific language).

Java can use the Service Provider Interface.

C++, static linking: just call an initialization function to set this up before use.

C++, dynamic linking: set it up in DllMain or the equivalent entry point for your platform.

C#: you can implement the IServiceProvider interface.


答:
Is this an appropriate use of the Singleton pattern, or are there still some pitfalls that I'm missing?

No, this has almost all of the pitfalls of singletons and even that assumes that you actually use Supplier almost everywhere and have other implementations. I'm not going to go into the various pitfalls of singletons as they have been covered well elsewhere.

Instantiating another one is just a waste of memory.

4 bytes. You are limiting your design for 4 bytes? Yes, it currently has no state. Yes it is currently threadsafe. It seems entirely plausible that a future version will need to parameterize the location of your articles, or perhaps some info about how the articles are sharded by creation time, or by any number of things. But you want to hamstring yourself because of 4 bytes?

The singleton is an antipattern. You are not going to change that.

Title: Is this the solution to static inheritance?

Body:
I've seen a lot of posts recently on why Singletons should be avoided. However, I can't see any of those problems with the following solution to a common problem: static inheritance.

For example, I was recently working on a library that scrapes the HTML source of a website and parses its contents into objects. The problem here is, the site has different types of content- articles, videos, etc. In my initial code, I had several different static 'supplier' classes- i.e. ArticleSupplier- that I quickly found shared a lot of boilerplate code (i.e. argument checks).

I could have made the classes instance-based, but it seems pointless: new ArticleSupplier() has no state; all its methods depend on the arguments passed to them. Instantiating another one is just a waste of memory.

This has brought me to thinking about using the Singleton pattern: a base class could perform boilerplate code checks and then call the derived class' implementation; the derived class could then control access with a singleton. Here's a simple example in C#:

```<code>abstract class Supplier
{
    IEnumerable<IModel> RecentModels(int amount)
    {
        return ModelsBefore(DateTime.Now, amount);
    }
    IEnumerable<IModel> ModelsBefore(DateTime date, int amount)
    {
        CheckDate(date);
        CheckAmount(amount);
        return InternalBefore(date, amount);
    }
    abstract IEnumerable<IModel> InternalBefore(DateTime date, int amount);
}

class ArticleSupplier
{
    private static readonly ArticleSupplier _Instance = new ArticleSupplier();
    private ArticleSupplier() { }
    public static ArticleSupplier Instance { get { return _Instance; } }
    override IEnumerable<IModel> InternalBefore(DateTime date, int amount)
    {
        // implementation
    }
}
</code>```

Now, you can focus on the implementation within ArticleSupplier without writing the same boilerplate code, and at the same time control instantiation of the object. I'd like to emphasize again that this is completely thread-safe because the singleton has no state, which is why the method was static in the first place.

Is this an appropriate use of the Singleton pattern, or are there still some pitfalls that I'm missing?


答: You could keep your code snippets in an online repository somewhere with its own LICENSE file, so people know how they may reuse it. You can also write your code snippets as Github Gists, and then embed them into your blog posts: since each Gist can have multiple files and you can embed them separately (as described in this SO answer), you could add a separate license file into each Gist, or have a single large Gist with multiple code snippets.</p>

Title: How to display/clarify the licence for code in a blog

Body:
Let's say I have a blog available under one of the Creative Commons licences.
Such type of licence would be displayed at the bottom of each page with a link
to the actual licence, etc..

However, apparently, the Creative Commons licences are not really suitable for
software nor for distribution of source code, so, what about any code
(e.g. snippet/fragment or even full programs) that can be part of a blog post?

If I would choose to release this code as GPLv3, would it be acceptable and
clear enough to say, at the bottom of the page, something like: "This website
by Mr. Foo is released under a Creative Commons blah blah, except for any source code in the form of code snippets/fragments/samples, which are released
under GPLv3"?

Or are there better/different/more formal ways to clarify such
situation?


问:
What is the most efficient way to find a set of locations within a radius of a certain point?
Imagine a dataset of all the restaurants in the US (similar to Yelp, etc), how would you return a set of restaurants within a certain range of a particular zip code.  (Assuming you have already a function, distanceBetweenZipCodes, which figures out the distance for you.)

The brute force method would be

```<code>For each restaurant in restaurantsInUSA
  if(distanceBetweenZipCodes(restaurant.zipcode, user.zipcode) < walkingDistance)
    save restaurant
</code>```

However, it seems fairly inefficient to include New York restaurants in the search if the user is in California.  But, it is possible that a restaurant is located close to a state line so segmenting the data by state would be problematic.  You get the same problem if trying to segment by counties, cities or any other administrative boundary.

What would be the most appropriate way to segment the data to avoid having to check each and every record for all searches?

答: A quadtree (or octree in 3 dimensions) is also good for spatial indexing.</p>


问:
Passing same argument to multiple small functions versus doing everything in one big function?
I have inherited a class method from another developer, which looks like below:
(Note: Class:X means X is a member of Class in the OOP paradigm.)

```<code>Class:BigFunction()
{
    ImportantValue = calculateImportantValue()

    Iterate over Class:Foo from 1 to ImportantValue
    Iterate over Class:Bar from 1 to ImportantValue
    Iterate over Class:Baz from 1 to ImportantValue

    # ... and so on ...
}
</code>```

I am considering refactoring this to something like:

```<code>Class:WrapSeveralSmallFunctions()
{
    ImportantValue = calculateImportantValue()

    IterateFoo(ImportantValue)
    IterateBar(ImportantValue)
    IterateBaz(ImportantValue)

    # ... and so on ...
}

Class:IterateFoo(ImportantValue)
{
    Iterate over Foo from 1 to ImportantValue
}

Class:IterateBar(ImportantValue)
{
    Iterate over Bar from 1 to ImportantValue
}

Class:IterateBaz(ImportantValue)
{
    Iterate over Baz from 1 to ImportantValue
}
</code>```

Per Single Responsibility Principle, the refactored code looks better to me.

However, I am also concerned about passing the ImportantValue as an argument to every such "small" function. Is my concern valid? Is the proposed refactoring considered a good coding practice, or is there any better way of writing this code?

答:
In term of performance, there will be virtually no difference between the two considered options.

Theoretically, the Single Responsibility Principle suggests that the solution with several small functions called by the big one is preferable if the small functions make sense. Are there semantically well defined? When you read the function names and the for-loops in the execution flow, do you read a consistent story?

If, taken individually, the small functions don't have a clear, well defined goal, your refactoring is probably too fine grained and counterproductive. Depending on your programming language, you can then consider to use advanced list comprehension or functional style coding for reducing verbosity.

For instance, the following code limits the handling of each collection to a single line, which is as simple to understand as a call to a small function with a for-loop.

```<code>Class:BigFunction()
{
    ImportantValue = calculateImportantValue()

    Class:Foo.take(ImportantValue).foreach(f => apply(f))
    Class:Bar.take(ImportantValue).foreach(f => apply(f))
    Class:Baz.take(ImportantValue).foreach(f => apply(f))
}
</code>```

If you systematically have to process your three lists in multiple "big" functions, it can be an evidence that the class itself violates the SRP. You therefore should consider to split the class. This operation is also a refactoring.

Body:
In term of performance, there will be virtually no difference between the two considered options.

Theoretically, the Single Responsibility Principle suggests that the solution with several small functions called by the big one is preferable if the small functions make sense. Are there semantically well defined? When you read the function names and the for-loops in the execution flow, do you read a consistent story?

If, taken individually, the small functions don't have a clear, well defined goal, your refactoring is probably too fine grained and counterproductive. Depending on your programming language, you can then consider to use advanced list comprehension or functional style coding for reducing verbosity.

For instance, the following code limits the handling of each collection to a single line, which is as simple to understand as a call to a small function with a for-loop.

Class:BigFunction()
{
    ImportantValue = calculateImportantValue()

    Class:Foo.take(ImportantValue).foreach(f => apply(f))
    Class:Bar.take(ImportantValue).foreach(f => apply(f))
    Class:Baz.take(ImportantValue).foreach(f => apply(f))
}

If you systematically have to process your three lists in multiple "big" functions, it can be an evidence that the class itself violates the SRP. You therefore should consider to split the class. This operation is also a refactoring.


问:
"Hand written" recursive descent parser with "catch all" rule
I'm trying to write a (scannerless) recursive descent parser with a "catch all" rule for the following "Mustache template" grammar (simplified here):

```<code>       content : (variable_tag | section_tag | static)*
  variable_tag : mustache_open id mustache_close
   section_tag : mustache_open '#' id mustache_close
                 content mustache_open '/' id mustache_close
 mustache_open : '{{'
mustache_close : '}}'
            id : [a–zA–Z$_][a–zA–Z0–9$_]*
        static : .+  // "catch all"
</code>```

The static production would have to stop before the next matched production. And I can't come to a solution for this that would not break the grammar structure.

A valid input is:

```<code>You have just won {{value}} dollars!
{{#in_ca}}
Well, {{taxed_value}} dollars, after taxes.
{{/in_ca}}
</code>```

The output for that would be an abstract syntactic tree like:

```<code>                           +-------+
                           |Content|
                           +-------+
                               |
        +---------------+------+--------+--------------+
        |               |               |              |
+--------------+  +-----------+  +-------------+  +----------+
|Static        |  |VariableTag|  |Static       |  |SectionTag|
|"\nYou...won "|  |value      |  |" dollars"\n"|  |in_ca     |
+--------------+  +-----------+  +-------------+  +----------+
                                                       |
                                                   +-------+
                                                   |Content|
                                                   +-------+
                                                       |
                                    +-------------+----+--------------+
                                    |             |                   |
                              +----------+  +-----------+  +---------------------+
                              |Static    |  |VariableTag|  |Static               |
                              |"\nWell, "|  |taxed_value|  |" dollars...taxes.\n"|
                              +----------+  +-----------+  +---------------------+
</code>```

Any reference to a implementation of a "catch all" rule for a recursive descent parser?

答:
Your grammar will be correct if your catch-all rule only consumes a single character and if you use prioritized choice in the grammar so that static is only attempted as a last resort. Of course, these single-character tokens are terribly inefficient. There are two ways to fix this:

let the catch-all rule be static : [^\{]+ | .

have your parser store a pointer to the previous token. If you are reading a static token and the previous token was static, then append the string rather than creating a new item in your AST. This can actually be a bit tricky to pull off, since in a RecDesc parser each rule would usually fail or return an AST subtree. It might make sense to introduce a pseudo-token signifying “success, but no action needes” since the token would already reside in the AST in case of a fixup and should not be added two times.

There is a problem with this: since at no point do you commit to one alternative, this parser involves a lot of backtracking. I would expect this to cause exponential complexity, unless you use a Packrat strategy (or use a parsing technique that is actually suited for ambiguous grammars). Here's an example input for such behaviour:

```<code>{{#foo}} {{#a}} {{#a}} {{#a}} {{/foo} sic!
</code>```

According to your grammar, this input would be completely static, but the parser would recurse four times into the section rule.

Body:
Your grammar will be correct if your catch-all rule only consumes a single character and if you use prioritized choice in the grammar so that static is only attempted as a last resort. Of course, these single-character tokens are terribly inefficient. There are two ways to fix this:

let the catch-all rule be static : [^\{]+ | .

have your parser store a pointer to the previous token. If you are reading a static token and the previous token was static, then append the string rather than creating a new item in your AST. This can actually be a bit tricky to pull off, since in a RecDesc parser each rule would usually fail or return an AST subtree. It might make sense to introduce a pseudo-token signifying “success, but no action needes” since the token would already reside in the AST in case of a fixup and should not be added two times.

There is a problem with this: since at no point do you commit to one alternative, this parser involves a lot of backtracking. I would expect this to cause exponential complexity, unless you use a Packrat strategy (or use a parsing technique that is actually suited for ambiguous grammars). Here's an example input for such behaviour:

{{#foo}} {{#a}} {{#a}} {{#a}} {{/foo} sic!

According to your grammar, this input would be completely static, but the parser would recurse four times into the section rule.


问:
Application development with fully dynamic controls and processes based on database
All software development projects are moving into separation of design, logic , data in patterns like MVC , MVVM and others.

Strangely i got a very strange requirement for a new software; that is :

It is required to have all controls/fields of the screen to be based in the database with their access rules which user is allowed to see which field or control

This is requested so the clients DB Admin be able to remove any field from the screen or change access level(view edit,none) of any field to a user!

I have suggested other ways of maintaining user access and roles, but the client is insisting of having everything each and every single screen control in the database to have full control on the software's screen content by their DB admin.

Is this way of maintaining screen and their content and controls in database has a name or is there a design pattern for that ?!
i know doing the software in this will harm the client but can't provide enough justification for that.

My question is : Is doing software in the described way is recommended or not and why?

答:
I have experience with big CRM/ERP product created this way. It is doable, but takes considerable more time and functionality will be limited. If this kind of thing is proposed only for access control, I don't think it's worth it.

Some downsides:

All types of controls you want to use, must be custom coded to
support persisting info into database. If it is more than couple
types of text boxes, then your are looking at huge effort.

Dependencies between controls are difficult to implement and will be
limited in functionality.

More difficult to debug and more complicated codebase.

I recomend you to fight harder with client and persuade him, that its a lot better to save only refference of controll to database. For example, you can add layer to your software, which prevents displaying control when its name was not found in DB and the same goal will be achieved.


问:
Is it good that testers are competing to see who opens more bugs?
I'm a software developer. There is a team of testers who follow and run test cases written by the analyst, but also perform exploratory testing. It seems like the testers have been competing to see who opens more bugs, and I've noticed that the quality of bug reports has decreased. Instead of testing functionality and reporting bugs related to the operation of the software, the testers have been submitting bugs about screen enhancements, usability, or stupid bugs.

Is this good for the project? If not, how can I (as a software developer), try to change the thinking and attitudes of the team of testers?

Another problem is because the deadline is estimated and cannot change, so as the deadline nears, the testers will be scrambling to finish their test cases, and this will cause the quality of the tests decrease. This will cause legitimate bugs to be in the final product received by the client.

OBS: This competition is not a practice of the company! It is a competition between only the testers organized by them, and without any prizes.

答:
I think how it will be(or how it already is) if it goes on like this, you wont necessarily get lower quality. Al though I think it will decrease the quantity to quality ratio. It depends if this is a bad thing or not. It depends if

reporting bugs about screen enhancements, usability, or stupid bugs.

is something you really dont want.
If this is clear with the testers, I would just tell them not to do the things you dont want reported but be clear about it. Do it when one of those reports show up again.

The reason they have a competition is probably to have fun while working, so they are probably not intending to do bad work(if this is considered bad).


问:
Changing license of personal GitHub repository
I know you can't take someone else's code and change it from GPL to MIT, but if you are the only contributor to a repository can you freely switch it from GPL to MIT?</p>

答:
If you published code once under GPL, that version of your code is GPL code, that is nothing you can change again. Someone else (in fact, thousands of people) could have made a copy, that copy is under GPL, the GPL text is part of the code, and you cannot enforce anybody to change his copies "just because you wish to".

However, if you create and publish a new version of the code, you can change your license to whatever your want for that newer version. That is true even if the only effective code change is the license itself. IANAL, but as long as you are the one and only copyright holder (which I assume, since you wrote you are the only contributor), you can do with your code and the usage rights you grant to others whatever you want.


问:
CentOS/RedHat devtoolset license implications
Can I use the RedHat devtoolset to build non-GPL-ed software?
Do I have to mind any caveats?

From my understanding, the devtoolset knows the limitations of the standard libraries shipped with older RedHat-Distributions. It links those missing parts of glibc and libstdc++ statically into otherwise dynamically linked code. Namely, the RedHat documentation states: "Some newer library features are statically linked into applications built with Red Hat Developer Toolset to support execution on multiple versions of Red Hat Enterprise Linux."

In case of glibc (LGPL) this would be problematic, because static linking would require to make at least the object files of the proprietary software available.

A senior developer thus claims, using the devtoolset would/might put our code under GPL and thus we have to stick with CentOS 5 and gcc 4.1 (for many years to come).

答:
It seems, one can use the devtoolset to build non-GPL-ed software. Because no plain-GPL or LGPL-libraries are linked statically.

At last I found an official presentation that specifies what exactly is linked dynamically:

All of C Library (glibc - libm, libc, etc)

All of OpenMP (libgomp)

Most of libstdc++

Most of libgcc

Based on this presentation, one can assume:

The LGPL-ed libraries like glibc are not linked statically.

The GPL-ed libgomp, libstdc++ and libgcc are linked (partially) statically.

But for those GPL-ed license, the GCC Runtime Library Exception applies.

I'd still preferred making such decisions based on parts of the official documentations, rather than a presentation slide.


答:
There is nothing wrong with making a game out of finding bugs.  You have found a way to motivate people.  This is good.  It's also revealed a failure to communicate priorities.  Ending the contest would be a waste.  You need to correct the priorities.

Few real games have a simple scoring system.  Why should the bug hunt?

Rather than score the game simply by number of bugs you need to provide a measure of bug report quality.  Then the contest is less about number of bugs.  It'll be more like a fishing contest.  Everyone will be looking to find the big bug that'll get a high priority score.  Make the quality of the bug report part of the score.  Have the developers provide the testers with feedback on the quality of the bug report.

Fine tuning game balance is not a simple task so be prepared to spend some time getting this right.  It should communicate your goals clearly and it should be fun.  It'll also be something you can adjust as business needs change.

Title: Is it good that testers are competing to see who opens more bugs?

Body:
I'm a software developer. There is a team of testers who follow and run test cases written by the analyst, but also perform exploratory testing. It seems like the testers have been competing to see who opens more bugs, and I've noticed that the quality of bug reports has decreased. Instead of testing functionality and reporting bugs related to the operation of the software, the testers have been submitting bugs about screen enhancements, usability, or stupid bugs.

Is this good for the project? If not, how can I (as a software developer), try to change the thinking and attitudes of the team of testers?

Another problem is because the deadline is estimated and cannot change, so as the deadline nears, the testers will be scrambling to finish their test cases, and this will cause the quality of the tests decrease. This will cause legitimate bugs to be in the final product received by the client.

OBS: This competition is not a practice of the company! It is a competition between only the testers organized by them, and without any prizes.


问:
Middleware dependencies
I'm trying to convert a legacy PHP app to use the middleware paradigm, similar to connect/express.js.

I've started porting the code into separate middlewares so that every feature is neatly self contained and can be easily add/removed/re-arranged as needed going forward.

However, I'm finding that many of these middlewares depend on other middlewares. For example, I have a DebugBar middleware which adds a bar at the bottom of every page if you're either on dev (which is determined via an environment middleware), or if you're a super user (determined by auth middleware).

Our site also has a link menu which changes based on your user permissions. Your user permissions can't be determined until you're authenticated, and I don't want to authentic at all unless you're on a page that requires it (basically anything except the login/logout page and 1 or 2 other pages) -- so there's also conditional middleware based on what page you're viewing.

Up until now I've been more or less copying how express does things, but as far as I can tell, they don't really have any examples of middleware depending on each other, and if they do, you would just monkey-patch the response object and subsequent middlewares would either depend on it or crash, which doesn't seem like a great way of doing things.

Questions:

What's the best way to share data between middlewares? Monkey-patching a response object seems very fragile.

How can I make it clear which middleware depends on what? There are a number of devs here, they can't all know the exact order that the app.uses must happen in.

答:
(Disclaimer: I don't know any of the technologies mentioned in the question; I'm just inferring from the descriptions on the question itself and the linked articles.)

Dependency and the order of execution. Based on the linked documentation,

It seems you can control the order of execution of middlewares simply by calling app.use(...) in a particular order.

It can be documented clearly inside your project.

There is a way to make it work correctly; whether it can be done in a maintainable (non-fragile) way is a matter of

Your design, and

Your (or programmer's) discipline in following the guidelines

There are some relevant design patterns and techniques that will help you maintain the correct dependency and order of execution.

Command pattern

Chain of responsibility pattern

Decorator pattern

Topological sorting, which can be used to calculate the order of execution based on their dependencies. You will likely do this with pen and paper, since you have control over what middlewares will be executed and there are no new middlewares to be added.

Regarding "monkey-patch(ing) the response object",

A middleware that is executed early can insert some placeholders in the response, which will be replaced by real content by another middleware that is executed later.

There can also be a final middleware that strips out any placeholders that were unprocessed (i.e. as a catch-all in case of a programming mistake), and replace that with error message.

To prevent injection attacks (the user somehow manipulating user-submitted content to look indistinguishable from a placeholder), you can sanitize (remove) such placeholders from the response in the beginning, before any genuine placeholders are added.

Anything else that do not belong to the response might be better written to the request object, or the session middleware instead.

To resolve circular dependencies between middleware, one can implement a middleware that would be executed at the very beginning. This middleware can do a "requirements gathering" on the request, to decide what other middleware will be potentially activated, and then set various flags on the request object.

This "requirements gathering" middleware should avoid doing the actual work that causes the circular dependency.

The authentication issue is not unique to any paradigm. It is a general user interface design issue that affects every application where the user doesn't need to authenticate up-front.

The core issue is this. After the user navigated to a page, and that page contains elements that will potentially require authentication, the questions are:

How to let the user easily find out whether the app is in an authenticated state or not (i.e. let the user see whether it's "logged in" or not)

How to convey to the user that there are such elements (that would require authentication)?

Completely hiding it?

Show a pane that blurs over it (but still hints at the existence of what's below), and put a login button on top? (There would be no user-specific information in the blurred content.)

Show the element with placeholder strings

Should the user be forced to authenticate? If so,

Should this happen when the page is being loaded?

Or only when the user clicks on the element (or a "Login" button?)

Are there less intrusive ways to authenticate the user?

Will this compromise security? Does the benefit outweigh the risks?

Title: Middleware dependencies


问:
Identifier vs domain object as a method parameter
Are there any objective arguments for or against using objects vs unique ID as method/function parameters? (and members of other objects?). Specially in the context of statically typed languages (C#/Java/Scala)

Pros of object itself:

More typesafe calls. With IDs there is a risk of wrong ordering of arguments. This can be mitigated though by keeping a 'mini' class for each class that only stores the ID of that class.

Get once from persistence, no need to get again

With ID, if the id type changes, say int -> long, then would require change across the board with possibility of mistakes.. (courtsey: https://softwareengineering.stackexchange.com/a/284734/145808)

Pros of using ID:

Most of the time no need for the actual object, just uniqueid would do, so having ID saves time from getting it from persistence.

A mixture of these techniques, as far as I can see, would only have cons of both and pros of neither.

Given that this is a concretely defined problem, I hope there are objective answers and not- "I think" or "I like" types... :-).

EDIT: Context on the suggestion of a commenter- The only restriction is a statically typed languages. The application is a general purpose application, although happy to get answers based on specific usage scenarios as well.

EDIT: Some more context. Say I have a book management system. My model is:

```<code>Book: { id: Int, isbn: String, donatedBy: Member, borrowedBy: Member }
Member: {id: Int, name: String}

Table- wishlist: { isbn: String, memberId: Int}
Table- borrows:  { id: Int, memberId: Int}

Method:
isInWishList( book: Book, member: Member ) vs isInWishList( bookId: Int,  memberId: Int)

handleBorrowRequest( memberId: Int, book: Book ){
   //the login system doesn't actually get the entire member structure, only the member id. I don't need the full member yet. can run a query to verify that the memberId has less than max allowed books for borrowing.
}
</code>```

Why would I want to keep only id and not the full member? Say when I get info about book, I rarely need to know about who has donated or borrowed it. Getting their full information to populate the donatedBy and borrowedBy fields is an overkill.

Ofcourse, these are only my points. I'm sure I'm missing things so wanted to know what are the points in favour/against.

答:
Depending on your environment and problem context, the need to go the database can be mitigated, and as a result (IMO) the argument for using id's only is lost.

For example, PHP's Doctrine2 ORM has EntityManager::getReference which produces a lazily loaded proxy to an entity using the provided id; I don't know how many other ORM's do that, but it matches roughly the notion of a "mini-class" you mention. For most intents and purposes, this is a fully hydrated entity, so you can pass it around and use it like any other.

The only case in which it's not is when it's given an invalid id, and in that case you'd want to go to the database anyway to validate; plus, to reduce the cost of getting entities, most ORM's have (first & second level) caching functionality available in some form.

Once we reduce the need and cost of going to database, we're left largely with pro's of using the entity as a parameter:

Type safety.

Less knowledge required by the caller. A developer 6 months down the line can't mistakenly pass in the id of the wrong entity.

Reduced refactoring cost. If a method were to change to require 2 pieces of information from the entity, there's no cost in changing the caller to provide it, presuming the caller got the fully hydrated entity to begin with.

Less validation required per method. Many methods can assume that the entity they're given exists in the database (because it came from the ORM), and so no longer have to validate the id.

(Potentially) fewer database calls. If you're passing id's to 3 methods, and each one has to validate it or fetch more data on the entity, that's 3 times as many database calls as 1 method fetching the entity and 2 operating on it.

Of course, there are cases where one might want to pass an id only: for example when crossing a bounded context boundary (in domain driven design speak). If we consider two bounded contexts with differing notions of what makes up an account (eg finance vs customer relations), then we can't pass context A's account to context B. Instead, an account id (in the language of the domain) can be passed across.


答:
Among other things (a template engine, an OO language, an application container etc. ) php functions quite well as middleware.

A simple php class/script that maps your functionality to php classes or scripts or resources would work fine. ( After all this is the paradigm used by the most successful and admired Python frameworks!)

Java, J2EE etc. need template engines, complex middleware , application containers etc. because it is not supported natively. PHP on the other hand supports everything you need to present web pages in a controlled manner.

Any middleware you use will be more complex and harder to maintain than simply coding a plain old PHP script which does the same thing.

Title: Middleware dependencies

Body:
I'm trying to convert a legacy PHP app to use the middleware paradigm, similar to connect/express.js.

I've started porting the code into separate middlewares so that every feature is neatly self contained and can be easily add/removed/re-arranged as needed going forward.

However, I'm finding that many of these middlewares depend on other middlewares. For example, I have a DebugBar middleware which adds a bar at the bottom of every page if you're either on dev (which is determined via an environment middleware), or if you're a super user (determined by auth middleware).

Our site also has a link menu which changes based on your user permissions. Your user permissions can't be determined until you're authenticated, and I don't want to authentic at all unless you're on a page that requires it (basically anything except the login/logout page and 1 or 2 other pages) -- so there's also conditional middleware based on what page you're viewing.

Up until now I've been more or less copying how express does things, but as far as I can tell, they don't really have any examples of middleware depending on each other, and if they do, you would just monkey-patch the response object and subsequent middlewares would either depend on it or crash, which doesn't seem like a great way of doing things.

Questions:

What's the best way to share data between middlewares? Monkey-patching a response object seems very fragile.

How can I make it clear which middleware depends on what? There are a number of devs here, they can't all know the exact order that the app.uses must happen in.


问:
Use the company style guide or try to match the incorrect source files?
I'm currently working on a large project in C++. The style guide for this language has been well defined by my company and is available for everyone to see. This particular code-base is being developed by two separate teams and has been developed by many different people over time.

Much of the code written by developers does not follow the company style guide, each developer has applied some of their own style in naming, comments, formatting etc. When writing new code should I follow the company style guide (but have code that looks stylistically out of place in many of the source files) or do I try to mirror the style of the code I'm currently working with?

答: Conforming to the style guide is important, but unless you have the necessary resources to adapt the entire code base to the standard on paper, it could create more disorder than it removes. In general, I wouldn't reformat less than an entire file merely to conform to any standard, and then only if it isn't clearly a business-value-negative proposition (i.e. it costs more than it will ever earn in productivity).


答:
If all the code is in one consistent style, or if the code base is very big, or if there's no budget, then I choose the battles I can win and adapt to the other style.

If I'm not the only person actively working on the project I would talk to the other developers and reach a shared agreement.

I would aim at writing all the new code following the guides. Any line I touch should follow the style guide, but I would not mix commits where I change the logic in one line and just the style in another part of the code.  It makes the review process very boring and confusing.

If I have some easy wins (like find / replace), I would coordinate with the team actively working on the code and apply them in bulk, then send a pull request containing only those changes. This should get merged asap, or I might end up with tons of conflicts.

Title: Use the company style guide or try to match the incorrect source files?

Body:
I'm currently working on a large project in C++. The style guide for this language has been well defined by my company and is available for everyone to see. This particular code-base is being developed by two separate teams and has been developed by many different people over time.

Much of the code written by developers does not follow the company style guide, each developer has applied some of their own style in naming, comments, formatting etc. When writing new code should I follow the company style guide (but have code that looks stylistically out of place in many of the source files) or do I try to mirror the style of the code I'm currently working with?


答:
First, you say that there are two teams currently working in the code, so the obvious answer is "ask whoever is in charge". It makes no sense doing the effort of adapting the code to the company styles if the other teams do not try to adapt it, too.

If you were alone maintaining some other people old code, probably most of your time you will be modifying only a small portion of it (there are parts of an IS that change more than others). There, I would go this way:

First and foremost, make it visible. Talk to your boss and ask him what to do; explain him that you sometimes will last a little longer doing changes but in the long run it will be profitable. He will decide if he cares most for short or long term.

Do not get sucked into a full refactoring! A good rule of thumb is restricting the changes to methods/classes that you have modified as part of the system changes. If you need to do "secondary" changes due to refactoring (v.g., modifying other class because you changed a method name due to refactoring), make those secondary changes but do not touch anything more.

Clean the parts of the application that you modify more first. No need to modify code that "just works" and nobody is going to read again.

After doing the functional changes and before doing the cleanup, do a commit in case something goes wrong (unmatched brackets, etc.).

(If rebuild time is low enough) If you make changes that affect other parts of the code (name of classes or methods), make the changes, recompile the system and decide if the change is worth changing all those "symbol not found" error.

Beware of inheritance! Remember that if you modify a method in a class, maybe there are no symbol not found errors because the compiler is using the parent class implementation of that method!


答:
I think it depends on a lot of social factors. For one, does it even affect you or your position if you do not adhere to the style guide? After all, a lot of code has been written by others with this guide in place already. If it does not really affect you, do you (for whatever reason) want to champion the style guide?

Most of the times, I found that once a style guide was ignored by one or more teams without serious repercussions, then the guide may as well be removed. It simply is not sufficient to write a document that explains the style guide, one needs to enforce it as well.

Hence, a more fundamental issue is present here: Does your company's style guide still have supporters, and why did they not enforce it?

You can think of it the other way round: You wouldn't have even bothered with this question, if your boss told you that must write any and all code for all projects in correspondence with this style guide. Apparently though, you have doubts as to the applicability of the guide instead.

In summary, what can you do? Given the above, these are a few possible ways, but in the end it is up to you to choose:

Ignore the style guide completely, because everyone else does so as well, and matter-of-factly it is no longer relevant.

Silently apply the style guide to your modifications and if someone complains simply point to the guide. You're not doing anything wrong, but you're also not doing much more than the minimum.

Champion the style guide. Bring up the problem that this code has ignored the guide, and that this fact in itself, is a problem that should be addressed. Get your voice heard and be part of the group that actually enforces the style guide, because you think it is important.

Challenge the style guide. Almost as above, but you don't agree with the guide and want to get rid of it.


问:
Design pattern for mapping data fields
I have seen this problem a few times and never can come up with a solution i like.

```<code>System A
    Sales Order Entity
        order_id
        created
        line_items_count

System B
    Sales Order Entity
        sales_order_id
        created_At
        num_line_items
</code>```

The problem is, that sales orders are created in System A - for example an e-commerce website.  The sales orders need to be exported and stored in another system, for example a warehouse system - System B.  They both store the same data but under different field names.

Is there a design pattern or collection of patterns typically used to solve such problem?

I always end up with an associative array containing the mapped fields - but it feels like there must be a better solution.

In the example above, not only sales orders might require this, also customers, products, inventory levels etc - so a generic pattern would be best.

答:
The Web Ontology Language (OWL) implements a description logic with sameAs and other relations between descriptions of entity types as a solution for this problem. 'Description logic' is arguably the design pattern for two-way mappings, as other representations are sub-sets of what a description logic can describe.

If the mapping is single way, then there are many transformation languages in which it can be specified, for example XSLT if the data has an XML representation.

Title: Design pattern for mapping data fields


问:
CI Server vs Build Server
Forgive my ignorance, but I'm having a difficult time finding an answer to this. We currently use TFS and a TFS Build server. I was looking at other build server options and was wondering if products like Jenkins and Teamcity serve the same purpose as TFS Build.</p>

答:
Basically, a build would be limited to:

Check out,

Compilation (or more generally, build, which includes more tasks, such as setting up proper configuration),

Unit testing,

while continuous integration will walk through the same three steps, plus:

Integration of the project within the larger system,

Integration testing,

(Eventually system testing).

Continuous delivery would add one additional step:

Packaging of the solution (in a form of an .msi file, a pip package, whatever).

Finally, continuous deployment will do all six steps and additionally:

The actual deployment of the solution in production.

In practice, there is no strict separation between build and continuous integration for many products. For instance, TFS build is hardly limited to the first three steps. It can perfectly well be configured to do the actual integration, the packaging and the deployment itself, making the terminology irrelevant in this case.

Jenkins is in fact a direct competitor of the build part of TFS. It has the same purpose, and works similarly.

Title: CI Server vs Build Server


问:
Why can a constructor be used without `new` keyword in Javascript?
I found Date can be used without the new keyword.

```<code>Date(1)
> "Thu May 28 2015 15:54:20 GMT+0800 (CST)"
new Date(1)
> Thu Jan 01 1970 08:00:00 GMT+0800 (CST)
</code>```

I was wondering whether there is any side-effect of using it without new.. Why would it be designed like this?

答:
In JavaScript a constructor is just an ordinary function. Any function which can be called as a constructor with 'new' can be called as an ordinary function. But functions will almost always be written as either a constructor or non-constructor function, and using it the other way is an error.

The built-in objects however are specifically designed so that you can use them both ways (as constructor and as ordinary functions) with two different results. For example new Date(1) creates a new Date object (as you would expect for a constructor) while Date(1) returns a string representation of the corresponding date, which is perhaps more surprising.


问:
How to deal with different programming styles in a team?
We have a small dev team (only 3 developers) and we recently got
a new team member. While he is a smart coder, his coding style is
completely different from ours. Our existing code base contains
mostly readable, clean and maintainable code, but the new team
member is quickly changing many files, introducing ugly hacks and
shortcuts, using defines all over the place, adding functions in
the wrong places, etc.

My question is if others have experienced such a situation
before, and if anyone has tips on how to talk to him.

答:
Consider using pull requests for new code into the repository. This gives a convenient place to do code review. Code that fails the code review is not merged into the repository until it is up to shape.

Just be careful not to make the pull requests too large. In my experience they shouldn't be bigger than between half a day to max two days or you will have too many merge conflicts.

Online vcs systems like bitbucket or github support this funtionality. If you prefer an on-premise approach stash seems like the best bet currently.


问:
Multiple if in comparison function vs chain of || or &&
I'm writing a function (or operator==() in C++), comparing two objects. The code looks like this:

```<code>bool operator==(const Obj& copy1, const Obj& copy2)
{
    if(copy1.a!=copy2.a)
        return false;
    if(copy1.b!=copy2.b)
        return false;
    if(copy1.c!=copy2.c)
        return false;
    return true;
}
</code>```

There may be many more data members to compare, and not all members present in Obj are to be compared, so using memcmp() isn't an option. There also might be more complicated tests than just equality of the members. Now there's another way:

```<code>bool operator==(const Obj& copy1, const Obj& copy2)
{
    return (copy1.a==copy2.a &&
            copy1.b==copy2.b &&
            copy1.c==copy2.c);
}
</code>```

The first way seems more verbose, but also easier to modify, while the second seems somewhat fragile (can't explain why, just gut feeling), but looks a lot simpler.

What is a better way? Is there any real difference in readability or maintainability of these approaches?

答: The first example is bad/fragile due to a lack of braces. Such code would not pass code review at the majority of places I've worked. If you add braces (making the conditional a single line if preferred), then they're fairly equivalent from what I've seen. Many places will prefer the first since conditionals can be used everywhere, but the complex expression can only be used when its parts are relatively simple/similar. But they wouldn't object to the second version in this sort of case, and it won't lead to maintenance problems.</p>


问:
How do you avoid getters and setters?
I'm having something of a hard time with designing classes in an oo way. I've read that objects expose their behavior, not their data; therefore, rather than using getter/setters to modify data, the methods of a given class should be "verbs" or actions operating on the object. For example, in an 'Account' object, we would have the methods Withdraw() and Deposit() rather than setAmount() etc. See: Why getter and setter methods are evil.

So for example, given a Customer class that keeps alot of information about the customer, e.g. Name, DOB, Tel, Address etc., how would one avoid getter/setters for getting and setting all those attributes? What 'Behavior' type method can one write to populate all that data?

答:
As stated in quite a few answers and comments, DTOs are appropriate and useful in some situations, especially in transferring data across boundaries (e.g. serializing to JSON to send through a web service). For the rest of this answer, I'll more or less ignore that and talk about domain classes, and how they can be designed to minimize (if not eliminate) getters and setters, and still be useful in a large project. I also won't talk about why remove getters or setters, or when to do so, because those are questions of their own.

As an example, imagine that your project is a board game like Chess or Battleship. You might have various ways of representing this in a presentation layer (console app, web service, GUI,etc.), but you also have a core domain. One class you might have is Coordinate, representing a position on the board. The "evil" way to write it would be:

```<code>public class Coordinate
{
    public int X {get; set;}
    public int Y {get; set;}
}
</code>```

(I'm going to be writing code examples in C# rather than Java, for brevity and because I'm more familiar with it. Hopefully that's not a problem. The concepts are the same and the translation should be simple.)

Removing Setters: Immutability

While public getters and setters are both potentially problematic, setters are the far more "evil" of the two. They're also usually the easier to eliminate. The process is a simple one- set the value from within the constructor. Any methods which previously mutated the object should instead return a new result. So:

```<code>public class Coordinate
{
    public int X {get; private set;}
    public int Y {get; private set;}

    public Coordinate(int x, int y)
    {
        X = x;
        Y = y;
    }
}
</code>```

Note that this doesn't protect against other methods in the class mutating X and Y. To be more strictly immutable, you could use readonly (final in Java). But either way- whether you make your properties truly immutable or just prevent direct public mutation through setters- it does the trick of removing your public setters. In the vast majority of situations, this works just fine.

Removing Getters, Part 1: Designing for Behavior

The above is all well and good for setters, but in terms of getters, we actually shot ourselves in the foot before even starting. Our process was to think of what a coordinate is- the data it represents- and create a class around that. Instead, we should have started with what behavior we need from a coordinate. This process, by the way, is aided by TDD, where we only extract classes like this once we have a need for them, so we start with the desired behavior and work from there.

So let's say that the first place you found yourself needing a Coordinate was for collision detection: you wanted to check if two pieces occupy the same space on the board. Here's the "evil" way (constructors omitted for brevity):

```<code>public class Piece
{
    public Coordinate Position {get; private set;}
}

public class Coordinate
{
    public int X {get; private set;}
    public int Y {get; private set;}
}

    //...And then, inside some class
    public bool DoPiecesCollide(Piece one, Piece two)
    {
        return one.X == two.X && one.Y == two.Y;
    }
</code>```

And here's the good way:

```<code>public class Piece
{
    private Coordinate _position;
    public bool CollidesWith(Piece other)
    {
        return _position.Equals(other._position);
    }
}

public class Coordinate
{
    private readonly int _x;
    private readonly int _y;
    public bool Equals(Coordinate other)
    {
        return _x == other._x && _y == other._y;
    }
}
</code>```

(IEquatable implementation abbreviated for simplicity). By designing for behavior rather than modelling data, we've managed to remove our getters.

Note this is also relevant to your example. You may be using an ORM, or display customer information on a website or something, in which case some kind of Customer DTO would probably make sense. But just because your system includes customers and they are represented in the data model does not automatically mean you should have a Customer class in your domain. Maybe as you design for behavior, one will emerge, but if you want to avoid getters, don't create one pre-emptively.

Removing Getters, Part 2: External Behaviour

So the above is a good start, but sooner or later you will probably run into a situation where you have behavior which is associated with a class, which in some way depends on the class's state, but which doesn't belong on the class. This sort of behavior is what typically lives in the service layer of your application.

Taking our Coordinate example, eventually you'll want to represent your game to the user, and that might mean drawing to the screen. You might, for example, have a UI project which uses Vector2 to represent a point on the screen. But it would be inappropriate for the Coordinate class to take charge of converting from a coordinate to a point on the screen- that would be bringing all sorts of presentation concerns into your core domain. Unfortunately this type of situation is inherent in OO design.

The first option, which is very commonly chosen, is just expose the damn getters and say to hell with it. This has the advantage of simplicity. But since we're talking about avoiding getters, let's say for argument's sake we reject this one and see what other options there are.

A second option is to add some kind of .ToDTO() method on your class. This- or similar- may well be needed anyway, for example when you want to save the game you need to capture pretty much all of your state. But the difference between doing this for your services and just accessing the getter directly is more or less aesthetic. It still has just as much "evil" to it.

A third option- which I've seen advocated by Zoran Horvat in a couple of Pluralsight videos- is to use a modified version of the visitor pattern. This is a pretty unusual use and variation of the pattern and I think people's mileage will vary massively on whether it's adding complexity for no real gain or whether it's a nice compromise for the situation. The idea is essentially to use the standard visitor pattern, but have the Visit methods take the state they need as parameters, instead of the class they're visiting. Examples can be found here.

For our problem, a solution using this pattern would be:

```<code>public class Coordinate
{
    private readonly int _x;
    private readonly int _y;

    public T Transform<T>(IPositionTransformer<T> transformer)
    {
        return transformer.Transform(_x,_y);
    }
}

public interface IPositionTransformer<T>
{
    T Transform(int x, int y);
}

//This one lives in the presentation layer
public class CoordinateToVectorTransformer : IPositionTransformer<Vector2>
{
    private readonly float _tileWidth;
    private readonly float _tileHeight;
    private readonly Vector2 _topLeft;

    Vector2 Transform(int x, int y)
    {
        return _topLeft + new Vector2(_tileWidth*x + _tileHeight*y);
    }
}
</code>```

As you can probably tell, _x and _y aren't really encapsulated any more. We could extract them by creating an IPositionTransformer<Tuple<int,int>> which just returns them directly. Depending on taste, you may feel this makes the entire exercise pointless.

However, with public getters, it's very easy to do things the wrong way, just pulling data out directly and using it in violation of Tell, Don't Ask. Whereas using this pattern it's actually simpler to do it the right way: when you want to create behaviour, you'll automatically start by creating a type associated with it. Violations of TDA will be very obviously smelly and probably require working around a simpler, better solution. In practice, these points make it much easier to do it the right, OO, way than the "evil" way that getters encourage.

Finally, even if it isn't initially obvious, there may in fact be ways to expose enough of what you need as behavior to avoid needing to expose state. For example, using our previous version of Coordinate whose only public member is Equals() (in practice it would need a full IEquatable implementation), you could write the following class in your presentation layer:

```<code>public class CoordinateToVectorTransformer
{
    private Dictionary<Coordinate,Vector2> _coordinatePositions;

    public CoordinateToVectorTransformer(int boardWidth, int boardHeight)
    {
        for(int x=0; x<boardWidth; x++)
        {
            for(int y=0; y<boardWidth; y++)
            {
                _coordinatePositions[new Coordinate(x,y)] = GetPosition(x,y);
            }
        }
    }

    private static Vector2 GetPosition(int x, int y)
    {
        //Some implementation goes here...
    }

    public Vector2 Transform(Coordinate coordinate)
    {
        return _coordinatePositions[coordinate];
    }
}
</code>```

It turns out, perhaps surprisingly, that all the behavior we really needed from a coordinate to achieve our goal was equality checking! Of course, this solution is tailored to this problem, and makes assumptions about acceptable memory usage/performance. It's just an example that fits this particular problem domain, rather than a blueprint for a general solution.

And again, opinions will vary on whether in practice this is needless complexity. In some cases, no such solution like this might exist, or it might be prohibitively weird or complex, in which case you can revert to the above three.

Title: How do you avoid getters and setters?

Body:
As stated in quite a few answers and comments, DTOs are appropriate and useful in some situations, especially in transferring data across boundaries (e.g. serializing to JSON to send through a web service). For the rest of this answer, I'll more or less ignore that and talk about domain classes, and how they can be designed to minimize (if not eliminate) getters and setters, and still be useful in a large project. I also won't talk about why remove getters or setters, or when to do so, because those are questions of their own.

As an example, imagine that your project is a board game like Chess or Battleship. You might have various ways of representing this in a presentation layer (console app, web service, GUI,etc.), but you also have a core domain. One class you might have is Coordinate, representing a position on the board. The "evil" way to write it would be:

public class Coordinate
{
    public int X {get; set;}
    public int Y {get; set;}
}

(I'm going to be writing code examples in C# rather than Java, for brevity and because I'm more familiar with it. Hopefully that's not a problem. The concepts are the same and the translation should be simple.)

Removing Setters: Immutability

While public getters and setters are both potentially problematic, setters are the far more "evil" of the two. They're also usually the easier to eliminate. The process is a simple one- set the value from within the constructor. Any methods which previously mutated the object should instead return a new result. So:

public class Coordinate
{
    public int X {get; private set;}
    public int Y {get; private set;}

    public Coordinate(int x, int y)
    {
        X = x;
        Y = y;
    }
}

Note that this doesn't protect against other methods in the class mutating X and Y. To be more strictly immutable, you could use readonly (final in Java). But either way- whether you make your properties truly immutable or just prevent direct public mutation through setters- it does the trick of removing your public setters. In the vast majority of situations, this works just fine.

Removing Getters, Part 1: Designing for Behavior

The above is all well and good for setters, but in terms of getters, we actually shot ourselves in the foot before even starting. Our process was to think of what a coordinate is- the data it represents- and create a class around that. Instead, we should have started with what behavior we need from a coordinate. This process, by the way, is aided by TDD, where we only extract classes like this once we have a need for them, so we start with the desired behavior and work from there.

So let's say that the first place you found yourself needing a Coordinate was for collision detection: you wanted to check if two pieces occupy the same space on the board. Here's the "evil" way (constructors omitted for brevity):

public class Piece
{
    public Coordinate Position {get; private set;}
}

public class Coordinate
{
    public int X {get; private set;}
    public int Y {get; private set;}
}

    //...And then, inside some class
    public bool DoPiecesCollide(Piece one, Piece two)
    {
        return one.X == two.X && one.Y == two.Y;
    }

And here's the good way:

public class Piece
{
    private Coordinate _position;
    public bool CollidesWith(Piece other)
    {
        return _position.Equals(other._position);
    }
}

public class Coordinate
{
    private readonly int _x;
    private readonly int _y;
    public bool Equals(Coordinate other)
    {
        return _x == other._x && _y == other._y;
    }
}

(IEquatable implementation abbreviated for simplicity). By designing for behavior rather than modelling data, we've managed to remove our getters.

Note this is also relevant to your example. You may be using an ORM, or display customer information on a website or something, in which case some kind of Customer DTO would probably make sense. But just because your system includes customers and they are represented in the data model does not automatically mean you should have a Customer class in your domain. Maybe as you design for behavior, one will emerge, but if you want to avoid getters, don't create one pre-emptively.

Removing Getters, Part 2: External Behaviour

So the above is a good start, but sooner or later you will probably run into a situation where you have behavior which is associated with a class, which in some way depends on the class's state, but which doesn't belong on the class. This sort of behavior is what typically lives in the service layer of your application.

Taking our Coordinate example, eventually you'll want to represent your game to the user, and that might mean drawing to the screen. You might, for example, have a UI project which uses Vector2 to represent a point on the screen. But it would be inappropriate for the Coordinate class to take charge of converting from a coordinate to a point on the screen- that would be bringing all sorts of presentation concerns into your core domain. Unfortunately this type of situation is inherent in OO design.

The first option, which is very commonly chosen, is just expose the damn getters and say to hell with it. This has the advantage of simplicity. But since we're talking about avoiding getters, let's say for argument's sake we reject this one and see what other options there are.

A second option is to add some kind of .ToDTO() method on your class. This- or similar- may well be needed anyway, for example when you want to save the game you need to capture pretty much all of your state. But the difference between doing this for your services and just accessing the getter directly is more or less aesthetic. It still has just as much "evil" to it.

A third option- which I've seen advocated by Zoran Horvat in a couple of Pluralsight videos- is to use a modified version of the visitor pattern. This is a pretty unusual use and variation of the pattern and I think people's mileage will vary massively on whether it's adding complexity for no real gain or whether it's a nice compromise for the situation. The idea is essentially to use the standard visitor pattern, but have the Visit methods take the state they need as parameters, instead of the class they're visiting. Examples can be found here.

For our problem, a solution using this pattern would be:

public class Coordinate
{
    private readonly int _x;
    private readonly int _y;

    public T Transform<T>(IPositionTransformer<T> transformer)
    {
        return transformer.Transform(_x,_y);
    }
}

public interface IPositionTransformer<T>
{
    T Transform(int x, int y);
}

//This one lives in the presentation layer
public class CoordinateToVectorTransformer : IPositionTransformer<Vector2>
{
    private readonly float _tileWidth;
    private readonly float _tileHeight;
    private readonly Vector2 _topLeft;

    Vector2 Transform(int x, int y)
    {
        return _topLeft + new Vector2(_tileWidth*x + _tileHeight*y);
    }
}

As you can probably tell, _x and _y aren't really encapsulated any more. We could extract them by creating an IPositionTransformer<Tuple<int,int>> which just returns them directly. Depending on taste, you may feel this makes the entire exercise pointless.

However, with public getters, it's very easy to do things the wrong way, just pulling data out directly and using it in violation of Tell, Don't Ask. Whereas using this pattern it's actually simpler to do it the right way: when you want to create behaviour, you'll automatically start by creating a type associated with it. Violations of TDA will be very obviously smelly and probably require working around a simpler, better solution. In practice, these points make it much easier to do it the right, OO, way than the "evil" way that getters encourage.

Finally, even if it isn't initially obvious, there may in fact be ways to expose enough of what you need as behavior to avoid needing to expose state. For example, using our previous version of Coordinate whose only public member is Equals() (in practice it would need a full IEquatable implementation), you could write the following class in your presentation layer:

public class CoordinateToVectorTransformer
{
    private Dictionary<Coordinate,Vector2> _coordinatePositions;

    public CoordinateToVectorTransformer(int boardWidth, int boardHeight)
    {
        for(int x=0; x<boardWidth; x++)
        {
            for(int y=0; y<boardWidth; y++)
            {
                _coordinatePositions[new Coordinate(x,y)] = GetPosition(x,y);
            }
        }
    }

    private static Vector2 GetPosition(int x, int y)
    {
        //Some implementation goes here...
    }

    public Vector2 Transform(Coordinate coordinate)
    {
        return _coordinatePositions[coordinate];
    }
}

It turns out, perhaps surprisingly, that all the behavior we really needed from a coordinate to achieve our goal was equality checking! Of course, this solution is tailored to this problem, and makes assumptions about acceptable memory usage/performance. It's just an example that fits this particular problem domain, rather than a blueprint for a general solution.

And again, opinions will vary on whether in practice this is needless complexity. In some cases, no such solution like this might exist, or it might be prohibitively weird or complex, in which case you can revert to the above three.


答:
There's a simple rule that you can follow: If you modify a file with code, you use the coding standard used in that file. If you create a new file, you use any good coding standard. (Plus: If your compiler can give warnings, you enable all reasonable warnings, turn warnings = error on if possible, and don't allow any code with warnings. Plus: If you use tools that make wholesale changes in a file, like changing tabs to spaces or the like, DO NOT use them).

The reason why there are huge arguments about coding standards is that one standard isn't better or worse than another (usually) but just different. The only really bad thing is mixing coding styles.

Obviously I expect that any decent programmer can write code following any coding standard, whether they prefer that particular standard or not.

And on the other hand, there are quality standards. Never accept code that doesn't meet your quality standards.

Title: How to deal with different programming styles in a team?

Body:
We have a small dev team (only 3 developers) and we recently got
a new team member. While he is a smart coder, his coding style is
completely different from ours. Our existing code base contains
mostly readable, clean and maintainable code, but the new team
member is quickly changing many files, introducing ugly hacks and
shortcuts, using defines all over the place, adding functions in
the wrong places, etc.

My question is if others have experienced such a situation
before, and if anyone has tips on how to talk to him.


答:
In short yes.

TFS is a broad term for the TFS suite of products that are bundled together, but its basically a version control system and a build server (TFS and TFS Build, if you like).

There are many competing systems, some are bundled together like TFS, some come separately. So a system that used, say, Subversion and Jenkins provides the same functionality as TFS and TFSBuild.

In many respects, the separates is better - you can pick and choose the one that works best for you. Jenkins for example is awesome, or you could pick Mercurial or git for your source control needs. You can then add other features such as a requirements management package, a Kanban workflow tool, a better bugtracker, or a document repository to the suite which you cannot easily do with TFS as it tries to lock you in to its way of doing things.

Title: CI Server vs Build Server

Body: Forgive my ignorance, but I'm having a difficult time finding an answer to this. We currently use TFS and a TFS Build server. I was looking at other build server options and was wondering if products like Jenkins and Teamcity serve the same purpose as TFS Build.</p>


问:
Good way to program an orchestration / processflow
I'm programming a process in which clients will be separated in 3 different groups, and for every group a different action will be performed.

My question concerns the process of deciding which client will be in which group.

As input I received a flow diagram with 7 decision blocks.

I think you can imagine the flow chart:

If A and B and Not C and F then you are in group 1.

If A and not B and C and E you are in group B. If A and not B and C and not E but F you also are in group B.

Anyway, you probably get what I mean.

What I'm searching for is what is a good way to implement this?

We've come up with the following solutions

1 program the code like I've typed it:

```<code>if A() && !B() && C() || (D() && E()) groupA.Add(client)
if A() && !B() && C() && F()) groupB.Add(client)
</code>```

2 program a BIG if / if / else

```<code>if A()
    if B()

    else
        if ! C()

        else
else
    if C()

    else
</code>```

etc.

But.... both don't make me happy, so I was wondering if there was a better way of solving this?

答:
There are definitely solutions out there which attempt to model flow charts in a generic way.

Things like windows workflow foundation, SSIS, routing in message queues etc.

But in my experience, unless the requirement comes from a technical source. ie IP routing, fail over dns etc where a technical spec for the form of the logic exists. Its best to make your code match the requirement document as closely to the way it describes the logic as possible

You will have holes in the logic and results that seem inconsistent, but your code will meet the requirement, and when the requirement changes in some weird way, you wont find yourself shoehorning it into a clever generic system which expects the logic to be expressed in a particular way.

This usually boils down to a big if block. but it will be easy to read and easy to change

Update: here's ways I've done it/seen it done in the past and regretted it

OOP approach, persist logic objects in XML doc, data in another, with elements like <addPercentage conditional="xpath refernce to data doc" value="10">

the xpath soon got super complicated with custom expressions, users never bothered to use the interface, so devs get requests to change logic anyway.

eval vb script stored in db

users cant do vb script, working out how a decision was made, next to impossible.

eval SQL (because we know that)

users can't do sql either, same probs as with vb script

websphere java orchestration with wcf services (because the consultants will setup a 'domain language'

users can't do java/'domain language' once the consultants leave. Hire new team of java devs, deployment/source control issues with web based IDE

lisp interpreter. OMG No.

windows workflow foundation

out of date even when we used it, over complicated for small tasks. difficult to explain to users

SSIS/DTS packages because they have a drag and drop interface!

hacky tool for non programming db admins, version control, deployment, debugging, performance difficulties. not scalable.


问:
Should a developer also act as a tester?
We're a scrum team of 3 developers, 1 designer, the scrum master, and the product owner. However, we don't have official tester in our team. A problem that is always with us, is that, testing the application and passing those tests and removing bugs has been defined as one of the criteria to consider a PBI (Product Backlog Item) as done.

But the problem is that, no matter how much we (3 developers and 1 designer) try to test the application and implemented use cases, still some bugs are not seen and ruin our presentation (Murphy's law) to stakeholders.

As a remedy, we recommended that the company hire a new tester. Someone who's job would be testing, and testing only. An official professional tester.

However, the problem is that, scrum master and stakeholders believe that a developer (or a designer) should also be a tester.

Are they right? Should we developers (also designers) be testers too?

答:
Testing software is a full time professional job. It needs a good brain, talent, and lots of experience to become a good tester. It's ridiculous to assume that a software developer, no matter how clever, can come close to a professional tester when testing is just a small component of his daily work.

On top of that comes the problem that subconsciously the software developer doesn't want to find bugs.


问:
Functional programming and Text adventures
This is mostly a theoretical question about FP, but I'll take text adventures (like old-school Zork) to illustrate my point. I'd like to know your opinions on how would you model a stateful simulation with FP.

Text adventures really seem to call for OOP. For example, all the "rooms" are instances of a Room class, you can have a basic Item class and interfaces like Item<Pickable> for things you can carry and so on.

World modeling in FP works differently, especially if you want to enforce immutability in a world that must mutate as the game progresses (objects are moved, enemies are defeated, the scoring grows, the player changes its location). I imagine a single big object World that has it all: what are the rooms you can explore, how they are linked, what the player is carrying, what levers have been triggered.

I think that a pure approach would be to basically pass this big object to any function and have it returned by them (possibly modified). For example, i have a moveToRoom function that gets World and returns it with World.player.location changed to the new room, World.rooms[new_room].visited = True and so on.

Even if this is the more "correct" way, it seems to be enforcing pureness for the sake of it. Depending on the programming language, passing this potentially very big World object back and forth may be expensive. Also, every function may need to have access to any World object. For example, a room may be accessible or not depending on a lever triggered in another room because it may be flooded, but if the player carries a life jacket, it can enter it anyway. A monster may be aggressive or not depending on whether the player has slayered his cousin in another room . This means that the roomCanBeEntered function needs to access World.player.invetory and World.rooms, describeMonster needs to access World.monsters and so on (basically, you must pass the whole load around). This really seems to me to call for a global variable, even if this is all but good programming style especially in FP.

How would you solve this problem?

答:
Mind that functional languages use data structures and separated functions instead of objects. For example you would have a set of rooms and a list of inventory items as a world instead.

Ideally you would also limit the amount of data you give to functions to how much they actually require as much as possible instead of passing the entire world (say you extract a single relevant room from your world; of course completely interdependent worlds can be hard to separate). The result would be reincorporated into the world data structure, creating a new state.
You cannot model state without using state; as you say some things inherently require mutation.

Most practical functional languages provide a way to realize mutation either directly (say the ST monad in Haskell or transients in Clojure), or simulate it efficiently (often by reusing unchanged parts of the data structure (Clojure's default data structures are a good example here)). Either way purity is maintained.

Since the amount of state that needs to be mutated seems limited, I wouldn't worry too much about performance issues and go with the (possibly already optimized) naive functional approach.

A different option I have seen would be returning only instructions to change some part of the world from your individual functions, and then updating your world according to these. A series of blog posts describing this is available at http://prog21.dadgum.com/23.html.

Both of these answers deal more with how to organize changes than to not pass your entire world to functions, because a perfectly interdependent one cannot be segmented by definition - but try and do so as best as you can in your case, which is not only functional, but also good practice.

ContentLicense: CC BY-SA 4.0


问:
Best solution to switch between new and deprecated code
We have a feature that is currently implemented, let's call it implA.

ImplA works but can't do many things. So we have decided to rewrite it. But we can't just replace it right away, so we will need to go through another implementation, implB, as a temporary solution to do the transition between implA and implC.

Even when implC is available, many people will still be using implA because it relies on hardware that needs to be updated to use implC. Anyway, from there, we will try to use implC anytime possible but we still need to support implA for some time.

This feature is used across the rest of the application, and I'm wondering the best course of action to make is as painless as possible in the code. So we will end up with implA, implB and implC.

I'm wondering if there is a pattern for this, or just a simple solution I don't think about.

I was thinking of wrapping it in a class that would then call the right impl. But my issue is that implC will have many more functionalities and the logic is different than in implA and implB. So I find it difficult to create a common interface for the 3 classes.

What would be the best solution?

答:
With the details given, i find difficult to justify the need for temporary implementation - ImplB. Anyway, am parking that here.

As all the 3 are implemented for a specific purpose, though there could be added functionality for implC, I believe that there could be a certain abstract type for these 3 - interface or an abstract class. Once that is in place you could use factory pattern to supply the right instance to the caller depending on certain parameter / set of parameters.

Reference:
Factory pattern - http://en.wikipedia.org/wiki/Factory_method_pattern