答:
Actually this can be relatively simply resolved with the C# trick of using dynamic to do double dispatch. You simply need a method on base class I like:

```<code>public R Foo(I i)
{
    return (i as dynamic).Foo(this as dynamic);
}
</code>```

The viewer can call this, because it knows it has an instance of I. The trick here is that when you cast to dynamic, you always pick the appropriate overload for the runtime type of the object (see the above link if it's not clear what that means).

Note that this also solves your problem of adding new classes. Say you have A,B,C,D and you add E. E has an explicit Foo override for all the previous ones, but none of them have an explicit override for E.

Now you do:

```<code>I e == new E();
I a = new A();
a.Foo(e);
</code>```

This will call E.Foo(A a). Alternatively, if you do:

```<code>e.Foo(a);
</code>```

This will first call A.Foo(I i) (Since there's no A.Foo(E e)). This will then call E.Foo(A a), which is the same as above.

As usual with dynamic, the downsides are:

Loss of type safety

Performance

Because you're using it within such a specific scope, I'd say the first point is pretty much irrelevant here. It doesn't force you to use dynamic anywhere else.

How relevant performance is is up to you to find for your specific code. If these methods aren't called in a tight loop, it's unlikely to matter, and if you're not sure, you should profile.

Note also that if you call this for two classes where neither can convert to the other, you'll recurse infinitely and overflow the stack!

Body:
Actually this can be relatively simply resolved with the C# trick of using dynamic to do double dispatch. You simply need a method on base class I like:

public R Foo(I i)
{
    return (i as dynamic).Foo(this as dynamic);
}

The viewer can call this, because it knows it has an instance of I. The trick here is that when you cast to dynamic, you always pick the appropriate overload for the runtime type of the object (see the above link if it's not clear what that means).

Note that this also solves your problem of adding new classes. Say you have A,B,C,D and you add E. E has an explicit Foo override for all the previous ones, but none of them have an explicit override for E.

Now you do:

I e == new E();
I a = new A();
a.Foo(e);

This will call E.Foo(A a). Alternatively, if you do:

e.Foo(a);

This will first call A.Foo(I i) (Since there's no A.Foo(E e)). This will then call E.Foo(A a), which is the same as above.

As usual with dynamic, the downsides are:

Loss of type safety

Performance

Because you're using it within such a specific scope, I'd say the first point is pretty much irrelevant here. It doesn't force you to use dynamic anywhere else.

How relevant performance is is up to you to find for your specific code. If these methods aren't called in a tight loop, it's unlikely to matter, and if you're not sure, you should profile.

Note also that if you call this for two classes where neither can convert to the other, you'll recurse infinitely and overflow the stack!

ContentLicense: CC BY-SA 4.0


问:
Cleanest way to represent three states, where one can hold a Key/Value pair, and the other two are empty markers
I'm writing a Hash Table that uses linear probing to resolve collisions.

I looked over how linear probing works, and it seems like to allow for deletions, I can't simply remove an element, since that may prevent a previously-collided element from being found post-deletion (since searching ends on an unoccupied cell).

I thought of wrapping the Key,Value pair in a class that just represents a state. 2 of the 3 states (say, Deleted and UnOccupied) are just acting as "markers"; they don't hold anything. The third state however (Occupied) needs to hold the pair.

The goal of this is to differentiate between cells that have always been empty, and cells that have have data previously deleted from them.

To illustrate what I wanted to do, if I were writing this in Haskell, I'd set it up as:

```<code>data CellState k v = Occ k v | Deleted | UnOcc
</code>```

Then I'd just need to pattern match against it to tell what the state of the cell is, and easily extract the pair if the cell is occupied.

I have to write this in Java though. I started writing up a set of classes for the 3 states that all inherit from a base class CellState, but then I thought it through, and I'm not sure how I would even use it since pattern-matching isn't supported in Java.

My second idea was to define 1 class that has key and value fields, and has a enumerated State field, with "getters" that can be used to check what the state of the cell is. If the user attempts to "get" from a CellState that isn't occupied, an exception would be thrown (similar to the behavior of Optional). The user could then use either an if-tree, or a switch to act on the cell based on its internal state.

The second idea seems more imperitive-styled, but still seems clumsy. This also allows for the possibility of an inconsistent state where a key and value are available, but it's marked as non-Occupied, or where it's marked as Occupied, but doesn't contain a pair. This isn't possible in the "Haskell solution".

By the way, this is for homework, so I can't simply not use linear probing, since that is an assignment requirement.

Is there a better way to go about doing this?

答:
I have my doubts about the occupied vs deleted tracking.

Perhaps you should instead move elements coming after the deleted element one down, similar to what you do when deleting in the middle of an array like collection. To determine how many elements you need to delete you could use a similar condition as you use to determine when the linear scan in finished.

To implement your first approach (different classes), I see several possible ways to replace pattern matching:

Add a method abstract State getState() where state is an enum to the base class which you then override in the derived classes. Then you can switch on its result.

The instanceof operator

Since the special values are stateless, you could create canonical instances and compare with them (reference equality works).

The first of these is the proper OOP approach, so it's probably the best choice for a homework assignment.

As a variant of your second approach, one could switch column-major-order. That way you don't need to allocate an object per slot, only a few per collection.

Something like

```<code>public class Dictionary<K, V>
{
    K[] keys;
    V[] values;
    State[] states;
}
</code>```

But I wouldn't use this approach in a homework assignment. The potential performance gain isn't worth the complexity.

Instead of scanning through the array, I'd rather keep a linked list (containing slot indices) for each bucket and a linked list for the free slots. Much simpler and better performance. But if the homework requires the dumb approach, it can't be helped.

ContentLicense: CC BY-SA 3.0

Body:
I have my doubts about the occupied vs deleted tracking.

Perhaps you should instead move elements coming after the deleted element one down, similar to what you do when deleting in the middle of an array like collection. To determine how many elements you need to delete you could use a similar condition as you use to determine when the linear scan in finished.

To implement your first approach (different classes), I see several possible ways to replace pattern matching:

Add a method abstract State getState() where state is an enum to the base class which you then override in the derived classes. Then you can switch on its result.

The instanceof operator

Since the special values are stateless, you could create canonical instances and compare with them (reference equality works).

The first of these is the proper OOP approach, so it's probably the best choice for a homework assignment.

As a variant of your second approach, one could switch column-major-order. That way you don't need to allocate an object per slot, only a few per collection.

Something like

public class Dictionary<K, V>
{
    K[] keys;
    V[] values;
    State[] states;
}

But I wouldn't use this approach in a homework assignment. The potential performance gain isn't worth the complexity.

Instead of scanning through the array, I'd rather keep a linked list (containing slot indices) for each bucket and a linked list for the free slots. Much simpler and better performance. But if the homework requires the dumb approach, it can't be helped.


答:
Cocoa NSDictionary uses an array containing hash values (which is useful anyway, because that way looking up a key doesn't require calculation of any hash code except the one of the key that is looked up), with two special hash values reserved to indicate an unused and a previously used cell. These special values are not constants but stored in the hash table. If you try to add a key/value pair where the hash code matches one of these two special values (which would be very, very rare), the code picks two other special values randomly until it picks two that are not used in the hash table, then replaces all the special values. </p>

<p>I don't know how good this approach is, but it is used by any single application on about a billion devices, so it better be good. </p>

Title: Cleanest way to represent three states, where one can hold a Key/Value pair, and the other two are empty markers

Body:
I'm writing a Hash Table that uses linear probing to resolve collisions.

I looked over how linear probing works, and it seems like to allow for deletions, I can't simply remove an element, since that may prevent a previously-collided element from being found post-deletion (since searching ends on an unoccupied cell).

I thought of wrapping the Key,Value pair in a class that just represents a state. 2 of the 3 states (say, Deleted and UnOccupied) are just acting as "markers"; they don't hold anything. The third state however (Occupied) needs to hold the pair.

The goal of this is to differentiate between cells that have always been empty, and cells that have have data previously deleted from them.

To illustrate what I wanted to do, if I were writing this in Haskell, I'd set it up as:

```<code>data CellState k v = Occ k v | Deleted | UnOcc
</code>```

Then I'd just need to pattern match against it to tell what the state of the cell is, and easily extract the pair if the cell is occupied.

I have to write this in Java though. I started writing up a set of classes for the 3 states that all inherit from a base class CellState, but then I thought it through, and I'm not sure how I would even use it since pattern-matching isn't supported in Java.

My second idea was to define 1 class that has key and value fields, and has a enumerated State field, with "getters" that can be used to check what the state of the cell is. If the user attempts to "get" from a CellState that isn't occupied, an exception would be thrown (similar to the behavior of Optional). The user could then use either an if-tree, or a switch to act on the cell based on its internal state.

The second idea seems more imperitive-styled, but still seems clumsy. This also allows for the possibility of an inconsistent state where a key and value are available, but it's marked as non-Occupied, or where it's marked as Occupied, but doesn't contain a pair. This isn't possible in the "Haskell solution".

By the way, this is for homework, so I can't simply not use linear probing, since that is an assignment requirement.

Is there a better way to go about doing this?

Body:
Cocoa NSDictionary uses an array containing hash values (which is useful anyway, because that way looking up a key doesn't require calculation of any hash code except the one of the key that is looked up), with two special hash values reserved to indicate an unused and a previously used cell. These special values are not constants but stored in the hash table. If you try to add a key/value pair where the hash code matches one of these two special values (which would be very, very rare), the code picks two other special values randomly until it picks two that are not used in the hash table, then replaces all the special values.

I don't know how good this approach is, but it is used by any single application on about a billion devices, so it better be good.


问:
How to use Guice for an effective API Design?
I am creating a base API in JavaSE, which includes modules like MVP architecture, Service & Repository Layer, Event Model to fire events between presenter etc.

I am trying to implement all best practices of Software Design. Recently, I read about Dependency Injection & its advantages and decided to use Guice as DI framework.

After spending two days learning Guice, I am still confused with some design issues.

If I create an injector using Guice.createInjector(modules) with the core modules of my API,

How to make this injector instance available to my other API classes? Can an injector be injected and is it a good practice?

How to make this injector instance available to API user, so that they can use this injector to create instances?

Should I even make it available to API user, as it may be a bad practice?

Hence using it for AOP approach like this and custom injections

Is creating injectors a heavyweight operation, if so should there be only a few injectors per application?

Should injectors be created on startup stage of the application or could be created in between without affecting the application performance?

Edit

To understand usage of Provider instead of injecting injector here is an short MVP example:

```<code>interface ProductModel {

  // Some method declarations

}

interface ProductView {

  // Some method declarations

}

class ProductPresenter {

  // Using Guice for constructor injection
  @Inject
  ProductPresenter(ProductModel model, ProductView view) {
    this.model = model;
    this.view = view;
  }

}

class ProductViewImpl implements ProductView {

  // Method Implementations

}

class ProductModelImpl implements ProductModel {

  // Method Implementations

}
</code>```

Now, as understood from below answers to use Provider<X> instead of injecting injector, here is the Provider class.

```<code>class ProductPresenterProvider implements Provider<ProductPresenter> {

  ProductPresenter get() {
    // But, How to provide the ProductPresenter without model and view instances!
  }

}
</code>```

答:
I will give a second answer, but you really should have opened a second question...

First of all: you rarely ever implement a provider. Guice will automagically create them for you. To explain this:
When I bind a class Foo as follows:

```<code>bind(Foo.class).to(FooImpl.class)
</code>```

You can inject in you class either Foo or Provider<Foo>. Guice will create the provider for you.

The reason why you should not implement the provider yourself, is that AOP is not working on instances that where created with a call to new. When you use a debugger to look at the run time instance of an injected object which uses interceptors you will notice that Guice created a subclass on the fly allowing it to intercept the method calls.

To your example:

The main problem is, that ProductModel should not be injected. It is a domain object and holds data. These kind of objects should not be created/managed by DI. Instead you code is responsible to create/retrieve and store the model from its persistent state. The presenter has now two different dependencies. One is the model which lives outside of DI and one is the view which can be handled by DI (just as a side note: if you need the same instance of the view to be injected on more than one object you must place it in a (custom-) scope. But answers to scopes deserve a new question).

To solve the above dilemma Guice offers assisted injection. This allows you to write a code like to following:

```<code>public class ProductPresenter {

    public interface Factory {
        createPresenter(ProductModel model);
    }

    @Inject
    ProductPresenter(@Assisted ProductModel model, ProductView view) {
        this.model = model;
        this.view = view;
    }
}
</code>```

you then bind the factory as follows:

```<code>install(new FactoryModuleBuilder().build(ProductPresenter.Factory.class));
</code>```

Guice will create an implementation of the ProductPresenter.Factory interface on the fly. The created instance will get the arguments passed to the factory method put into the constructor. Also AOP is working on the created instance. This way you can mix DI with non DI objects.

Body:
I will give a second answer, but you really should have opened a second question...

First of all: you rarely ever implement a provider. Guice will automagically create them for you. To explain this:
When I bind a class Foo as follows:

bind(Foo.class).to(FooImpl.class)

You can inject in you class either Foo or Provider<Foo>. Guice will create the provider for you.

The reason why you should not implement the provider yourself, is that AOP is not working on instances that where created with a call to new. When you use a debugger to look at the run time instance of an injected object which uses interceptors you will notice that Guice created a subclass on the fly allowing it to intercept the method calls.

To your example:

The main problem is, that ProductModel should not be injected. It is a domain object and holds data. These kind of objects should not be created/managed by DI. Instead you code is responsible to create/retrieve and store the model from its persistent state. The presenter has now two different dependencies. One is the model which lives outside of DI and one is the view which can be handled by DI (just as a side note: if you need the same instance of the view to be injected on more than one object you must place it in a (custom-) scope. But answers to scopes deserve a new question).

To solve the above dilemma Guice offers assisted injection. This allows you to write a code like to following:

public class ProductPresenter {

    public interface Factory {
        createPresenter(ProductModel model);
    }

    @Inject
    ProductPresenter(@Assisted ProductModel model, ProductView view) {
        this.model = model;
        this.view = view;
    }
}

you then bind the factory as follows:

install(new FactoryModuleBuilder().build(ProductPresenter.Factory.class));

Guice will create an implementation of the ProductPresenter.Factory interface on the fly. The created instance will get the arguments passed to the factory method put into the constructor. Also AOP is working on the created instance. This way you can mix DI with non DI objects.


问:
Do my "dal" and "fileHandler" interfaces overlap?
I want my program to:

read some input lines from CSV file

write the output lines to plain string file

read some input from the same file in (2)
and compare it to some calculated data

I want to consider these abstraction levels:

create Dal interface with CRUD operations

implement Dal<T1>, Dal<T2>, Dal<T3>

create FileHandler interface with read and save operations

implement CsvFileHandler, StringFileHandler

And then:

Dal<T1> will implement read with a member of CsvFileHandler

Dal<T2> will implement read and write with a member of StringFileHandler

Dal<T3> will implement write with a member of StringFileHandler

Is it OK that Dal<T1> and Dal<T3> really implement Dal only partially (not all CRUD). Or should I choose other abstractions?

I'm using guice DI and I need to differentiate Dal<T1> and Dal<T2> even though they both read / write type String. So I created a dummy different classes for T1, T2.

Do you think I use too much abstraction? Are FileHandler and Dal overlapping?

Any other way to differentiate Guice injection rather than create dummyTypes?

答:
If you follow the Liskov Substitution Principle you should not have implementations which do not fully implement an interface.

I rather have two or three different interfaces which state exactly what they can. Maybe a class will at the end implement more than one interface...

The other benefit you gain is that when you have specific interfaces they do not need to be further qualified in order for Guice to know which instance you need. If you still have more than one implementation of an interface you can use annotation to qualify them. See Binding Annotations


问:
What design pattern is this?
I'm struggling to come up with the name of a design pattern that I need to write about. I've been lead to think it was abstraction but apparently not.

Let's say I had a driver class which has a Drive method:

```<code>public void Drive()
{
    if(IsOnGasPedal)
    {
        //Lots of code
    }
    if(IsOnBrake)
    {
        //Lots of code
    }
    if(IsOnClutch)
    {
        //Lots of code
    }
}
</code>```

And I change the method to:

```<code>public void Drive()
{
    if(IsOnGasPedal)
    {
        Car.Gas()
    }
    if(IsOnBrake)
    {
        Car.Brake()
    }
    if(IsOnClutch)
    {
        Car.Clutch()
    }
}
</code>```

I have moved the complex and long code into separate methods in my Car property so that the Drive method is more organised. This is an example of refactoring but that is not the word. I thought it was either encapsulation or abstraction but I can't get any solid answers. What is this pattern called?

答: Well I think people are missing the point that you're delegating the behavior that was once in the Driver class into the Car class, so it's not really Extract Method because otherwise it would be in the same class. This is either simple composition (not a DP) but if you want to be kind, it might be an implementation of Strategy, which some people do consider a design pattern. </p>

Title: What design pattern is this?


问:
Why do I need unit tests for testing repository methods?
I need to play devils advocate on this question a bit because I cannot defend it well because of lack of experience. Here is the deal, I get conceptually the differences between unit testing and integration testing. When specifically focusing in on persistence methods and the repository, a unit test would use a mock possibly via a framework like Moq to assert that say an order searched for was returned as expected.

Let's say I have built the following unit test:

```<code>[TestMethod]
public void GetOrderByIDTest()
{
   //Uses Moq for dependency for getting order to make sure
   //ID I set up in 'Arrange' is same one returned to test in 'Assertion'
}
</code>```

So if I set up OrderIdExpected = 5 and my mock object returns 5 as the ID my test will pass. I get it. I unit tested the code to make sure what my code preforms returns the expected object and ID and not something else.

The argument I will get is this:

"Why not just skip the unit tests and do integration tests? It's
  testing the database stored procedure and your code together that's
  important. It seems like too much extra work to have unit tests and
  integration tests when ultimately I want to know if the database calls
  and the code work. I know the tests take longer, but they have to be run and tested regardless so it seems pointless to me to have both. Just test against what matters."

I could defend it with a text book definition like: "Well that's an integration test and we need to test the code separately as a unit test and, yada, yada, yada..." This is a case where a purist explanation of practices vs. reality is loosing out. I run into this sometimes and if I can't defend the reasoning behind unit testing code that ultimately relies on external dependencies, than I can't make a case for it.

Any help on this question is greatly appreciated, thanks!

答:
Tests are useful when they break: Proactively or Re-actively.

Unit Tests are proactive and may be a continuous functional verification while Integration Tests are reactive on a staged/fake data.

If the system under consideration is close to/dependent on data more than computation logic, Integration Tests should get more importance.

For example, if we are building an ETL system, the most relevant tests will be around data (staged, faked or live). The same system will have some Unit Tests, but only around validation, filtering etc.

Repository pattern shouldn't have computational or business logic. It is very close to the database. But repository is also close to the business logic that uses it. So it is a question of striking a BALANCE.

Unit Tests can test HOW the Repository behaves.
Integration Tests can test WHAT REALLY HAPPENED when the repository was called.

Now, "WHAT REALLY HAPPENED" might seem to be very enticing. But this could be very expensive for running consistently and repeatedly. Classic definition of brittle tests applies here.

So most of the time, I just find it good enough to write Unit test on an object that uses the repository. This way we test if proper repository method got called and proper Mocked results are returned.


问:
Tricky architecture in C# involving a symmetric operation and a viewing class
I'm trying to build an architecture in C#, and I can't figure out a way to accomplish the task. Basically, there's a set of classes A, B, C and D that inherit from I. Each of these classes has an operation Foo that operates on one of the other classes, and returns an object of type R:

```<code>class A : I
{
    public R Foo(A a);
    public R Foo(B b);
    public R Foo(C c);
    public R Foo(D d);
}
class B : I
{
    public R Foo(A a);
    public R Foo(B b);
    public R Foo(C c);
    public R Foo(D d);
}
class C : I
{
    public R Foo(A a);
    public R Foo(B b);
    public R Foo(C c);
    public R Foo(D d);
}
class D : I
{
    public R Foo(A a);
    public R Foo(B b);
    public R Foo(C c);
    public R Foo(D d);
}
</code>```

This operation Foo is symmetric (i.e. a.Foo(b) == b.Foo(a), d.Foo(a) == a.Foo(d), etc.). (Of course, this means that we really only need to define Foo(A a) in A, Foo(A a) and Foo(B b) in B, and so on, but you get the idea).

If we introduce a new class E, it has to implement Foo for types A, B, C, D, and E.

```<code>class E : I
{
    public R Foo(A a);
    public R Foo(B b);
    public R Foo(C c);
    public R Foo(D d);
    public R Foo(E e);
}
</code>```

Obviously we can't externally add an implementation for public R Foo(E e) in each of the classes A, B, C, and D (well, not without extension methods), but since Foo is symmetric, a.Foo(e) == e.Foo(a), so we only really need to implement Foo(A a) in E.

Now the part that makes this really difficult for me at least, is there's also a "viewer" object V that contains a list of I's. V has to be able to perform the Foo operation between two I's without knowing their actual types. V only knows that the operation Foo exists between two I's. Theoretically, this is what it would look like:

```<code>class V {
    public R Foo(I i1, I i2)
    {
        // Check if i1 has an implementation for Foo taking
        // the type of i2.
        if (!i1.HasFoo(i2.GetType()))
        {
            // Do the same for i2 on i1.
            if (!i2.HasFoo(i1.GetType()))
                return null;
            return i2.Foo(i1);
        }
        return i1.Foo(i2);
    }
}
</code>```

Obviously this would never work, for the same reasons this doesn't work. I've thought about this for quite some time now, and I can't think of an architecture that satisfies these requirements in a clean way. I've thought up a number of convoluted methods that abuse generic types and strategy patterns and visitor patterns and the whole sh'bang, but nothing that isn't prone to bugs or overcomplicated.

How should I implement this, if it's even possible?

This is the actual, non-abstracted application. It's a collision detection engine, where the classes A, B, etc. are different geometries with fundamentally different properties (circle vs infinite line vs polygon, etc.). The different Foos are the different algorithms that test if two geometric shapes are colliding. V is an algorithmic container for a large number of these geometric objects (a quadtree or something).

答:
I just realized, C# has dynamic types!

```<code>interface I
{
    int Precedence { get; }
}

class A : I
{
    public int Precedence { get { return 0; } }
    public R Foo(A a) { return ...; }
}

class B : I
{
    public int Precedence { get { return 1; } }
    public R Foo(A a) { return ...; }
    public R Foo(B b) { return ...; }
}

class C : I
{
    public int Precedence { get { return 2; } }
    public R Foo(A a) { return ...; }
    public R Foo(B b) { return ...; }
    public R Foo(C c) { return ...; }
}

class D : I
{
    public int Precedence { get { return 3; } }
    public R Foo(A a) { return ...; }
    public R Foo(B b) { return ...; }
    public R Foo(C c) { return ...; }
    public R Foo(D d) { return ...; }
}

using Microsoft.CSharp.RuntimeBinder;
class V
{
    public R Foo(I i1, I i2)
    {
        try
        {
            if (i1.Precedence >= i2.Precedence)
                return DynamicFoo(i1, i2);
            return DynamicFoo(i2, i1);
        }
        catch (RuntimeBinderException)
        {
            return null;
        }
    }

    private R DynamicFoo(dynamic a, dynamic b)
    {
        return a.Foo(b);
    }
}
</code>```

Here we use the convention that any class with a precedence of n must implement Foo for all classes with precedence less than or equal to n.

The problems with this solution are that if you want to implement a new class E you have to know what the previous highest precedence value was (in this case 3), and the user has to understand the precedence convention in the first place. You could also argue that catching an exception is an inefficient method of detecting when no Foo exists, but that feels like premature optimization.

An example of implementing E:

```<code>class E : I
{
    public int Precedence { get { return 4; } }
    public R Foo(A a) { return ...; }
    public R Foo(B b) { return ...; }
    public R Foo(C c) { return ...; }
    public R Foo(D d) { return ...; }
    public R Foo(E e) { return ...; }
}
</code>```

Body:
I just realized, C# has dynamic types!

interface I
{
    int Precedence { get; }
}

class A : I
{
    public int Precedence { get { return 0; } }
    public R Foo(A a) { return ...; }
}

class B : I
{
    public int Precedence { get { return 1; } }
    public R Foo(A a) { return ...; }
    public R Foo(B b) { return ...; }
}

class C : I
{
    public int Precedence { get { return 2; } }
    public R Foo(A a) { return ...; }
    public R Foo(B b) { return ...; }
    public R Foo(C c) { return ...; }
}

class D : I
{
    public int Precedence { get { return 3; } }
    public R Foo(A a) { return ...; }
    public R Foo(B b) { return ...; }
    public R Foo(C c) { return ...; }
    public R Foo(D d) { return ...; }
}

using Microsoft.CSharp.RuntimeBinder;
class V
{
    public R Foo(I i1, I i2)
    {
        try
        {
            if (i1.Precedence >= i2.Precedence)
                return DynamicFoo(i1, i2);
            return DynamicFoo(i2, i1);
        }
        catch (RuntimeBinderException)
        {
            return null;
        }
    }

    private R DynamicFoo(dynamic a, dynamic b)
    {
        return a.Foo(b);
    }
}

Here we use the convention that any class with a precedence of n must implement Foo for all classes with precedence less than or equal to n.

The problems with this solution are that if you want to implement a new class E you have to know what the previous highest precedence value was (in this case 3), and the user has to understand the precedence convention in the first place. You could also argue that catching an exception is an inefficient method of detecting when no Foo exists, but that feels like premature optimization.

An example of implementing E:

class E : I
{
    public int Precedence { get { return 4; } }
    public R Foo(A a) { return ...; }
    public R Foo(B b) { return ...; }
    public R Foo(C c) { return ...; }
    public R Foo(D d) { return ...; }
    public R Foo(E e) { return ...; }
}


问:
Table design for holidays
I'm creating a system to store holidays and events. I have a basic understanding of the schema for the static dates (every 23rd of march for instance).

My trouble lies with the relative dates (i.e. : every 3rd friday of march).

For the static dates we can safely have a schema that looks like this :

```<code>+----------+--------------+
| Col Name |     Type     |
+----------+--------------+
| Id       | Int          |
| Name     | varchar(255) |
| Month    | Int          |
| Day      | Int          |
+----------+--------------+
</code>```

How would it be possible to add the relative dates in this schema ?

答:
What you have is not flexible enough.

The basic requires are you need to be able to express e.g. the following:

U.S. Memorial Day is the last Monday of May.

U.S. Thanksgiving is the fourth Thursday of November.

Christmas is the 25th day of December.

Easter is... maybe just scrape Wikipedia?

One simple way to express this is to add fields for the possible ways to define holidays:

Month

Day of Week

Week of Month (use negative to count backward for e.g. Memorial Day)

Day of Month

This is not ideal because one can easily put bad data in (e.g. Monday, first week, and 25th day), but it is simple and easy to understand.

There are other ways to define holidays that I have seen elsewhere, but they basically require implementing a rules engine which is very complex and easy to misuse. These behemoths have a bad reputation that is well-earned, but sometimes they really are the best tool for the job.

Title: Table design for holidays


答:
I have figured that it's best to store the day count which the event/holiday is on. I had a look at the Queens birthday in Australia and its every 2nd Monday of June, it doesn't move on to the next month. For most of Australia accept Western Australia that's the queen's birthday. in western Australia the queen's birth day is on every 5th Monday of September, but it sometimes falls on to October as well.

Looking at your problem I think it would be reason to store count of day of which the holiday is to fall on given a base month. If the base month is exceeded move to the next month and continue the count.

Title: Table design for holidays

Body:
I'm creating a system to store holidays and events. I have a basic understanding of the schema for the static dates (every 23rd of march for instance).

My trouble lies with the relative dates (i.e. : every 3rd friday of march).

For the static dates we can safely have a schema that looks like this :

```<code>+----------+--------------+
| Col Name |     Type     |
+----------+--------------+
| Id       | Int          |
| Name     | varchar(255) |
| Month    | Int          |
| Day      | Int          |
+----------+--------------+
</code>```

How would it be possible to add the relative dates in this schema ?


答:
You've got a holiday and the basic information about it.

```<code>Holiday:
  holidayId (pk)
  name
</code>```

What types of holidays do we have? There are the fixed holidays, the moving holidays and the "I'm not even going to bother calculating" holidays (Easter, I'm looking at you).

For this, you would have subtables.

There are the fixed, repeating holidays. Things like Christmas and the Forth of July.  These are holidays that fall on the same day of the month each year.

```<code>FixedHoliday
  FixedHoldiayId (pk)
  HolidayId (fk)
  MonthOfYear
  DayOfMonth
</code>```

Then you've also got the movable ones. Labor day (first Monday in September), Memorial day (last Monday in May), Thanksgiving (forth Thursday in November).

The easiest way to approach this is to give a day range for the day.

```<code>MoveableHoliday
  MoveableHoldaiYid (pk)
  HolidayId (fk)
  MonthOfYear
  DayOfWeek
  EarliestDay
  LatestDay
</code>```

If your database supports a range type you may wish to use that. Not all do, and thus the two date approach.

Why two days?  Lets look at Labor day.  The earliest it can be is September 1st - if Monday falls on the first.  The latest that the first Monday can fall is September 6th.  Monday on September 7th would mean that September 1st was a Monday and that was Labor Day.

For Memorial day, the last Monday in May (which has 31 days), the range for valid dates is the 25th through the 31st.

Some example rows:

```<code>MoveableHoliday | Labor | Memorial | Thanksgiving
  MonthOfYear   | Sep   | May      | Nov
  DayOfWeek     | Mon   | Mon      | Thurs
  EarliestDay   | 1     | 25       | 22
  LatestDay     | 6     | 31       | 28
</code>```

This brings us to the "I'm not even going to calculate that" approach - it's the first Sunday after the first full moon that occurs on or after the 21st of March... and yea.  If you really dug into it, you might write a stored procedure that has the calculation in it for full moon (or have that in another table - again, needing to populate that table), or you can just say "there aren't enough of these to really make a difference" and just populate it.

This is very much like the fixed holiday, except that its for one year only.

```<code>SpecificDayHoliday
  SpecificDayHolidayId (pk)
  HolidayId (fk)
  MonthOfYear
  DayOfMonth
  Year
</code>```

At this point, you just populate the table however you want for however far you want.

Now, you could put the SpecificDayHoliday and the FixedHoldiay tables together, and make Year optional. However, I feel that this makes it an easier to work with each table - they each have a single type of value that goes into them.  In particular, SpecificDayHoliday allows for multiple HolidayId values to be the same in the table. FixedHoliday and MoveableHoliday should have a constraint on the table that makes HolidayId unique within the table.

Title: Table design for holidays

Body:
You've got a holiday and the basic information about it.

Holiday:
  holidayId (pk)
  name

What types of holidays do we have? There are the fixed holidays, the moving holidays and the "I'm not even going to bother calculating" holidays (Easter, I'm looking at you).

For this, you would have subtables.

There are the fixed, repeating holidays. Things like Christmas and the Forth of July.  These are holidays that fall on the same day of the month each year.

FixedHoliday
  FixedHoldiayId (pk)
  HolidayId (fk)
  MonthOfYear
  DayOfMonth

Then you've also got the movable ones. Labor day (first Monday in September), Memorial day (last Monday in May), Thanksgiving (forth Thursday in November).

The easiest way to approach this is to give a day range for the day.

MoveableHoliday
  MoveableHoldaiYid (pk)
  HolidayId (fk)
  MonthOfYear
  DayOfWeek
  EarliestDay
  LatestDay

If your database supports a range type you may wish to use that. Not all do, and thus the two date approach.

Why two days?  Lets look at Labor day.  The earliest it can be is September 1st - if Monday falls on the first.  The latest that the first Monday can fall is September 6th.  Monday on September 7th would mean that September 1st was a Monday and that was Labor Day.

For Memorial day, the last Monday in May (which has 31 days), the range for valid dates is the 25th through the 31st.

Some example rows:

MoveableHoliday | Labor | Memorial | Thanksgiving
  MonthOfYear   | Sep   | May      | Nov
  DayOfWeek     | Mon   | Mon      | Thurs
  EarliestDay   | 1     | 25       | 22
  LatestDay     | 6     | 31       | 28

This brings us to the "I'm not even going to calculate that" approach - it's the first Sunday after the first full moon that occurs on or after the 21st of March... and yea.  If you really dug into it, you might write a stored procedure that has the calculation in it for full moon (or have that in another table - again, needing to populate that table), or you can just say "there aren't enough of these to really make a difference" and just populate it.

This is very much like the fixed holiday, except that its for one year only.

SpecificDayHoliday
  SpecificDayHolidayId (pk)
  HolidayId (fk)
  MonthOfYear
  DayOfMonth
  Year

At this point, you just populate the table however you want for however far you want.

Now, you could put the SpecificDayHoliday and the FixedHoldiay tables together, and make Year optional. However, I feel that this makes it an easier to work with each table - they each have a single type of value that goes into them.  In particular, SpecificDayHoliday allows for multiple HolidayId values to be the same in the table. FixedHoliday and MoveableHoliday should have a constraint on the table that makes HolidayId unique within the table.


问:
How do I make this functional DSL written in an imperative language more efficient?
Suppose I create a simple functional Domain-specific language (DSL) using an imperative language, in this case C++. Here is a simple implementation of a DSL that can has the notion of a simple value and operator (in this case the addition operator):

```<code>// some operator
template <typename LHS, typename RHS>
struct OpImpl
{
    Op(LHS lhs, RHS rhs) : mLhs(lhs), mRhs(rhs) {}
    auto operator()() const
    {
      return mLhs() + mRhs(); // let's say it's a non-trivial operation, and can't be optimised away but also has no side effects.
    }
    LHS mLhs;
    RHS mRhs;
};

template <typename LHS, typename RHS>
auto Op(LHS&& lhs, RHS&& rhs) { return Op<LHS, RHS>(lhs, rhs); }

struct Value
{
    Value(int value) : mValue(value) {}
    auto operator()() const
    {
        return mValue;
    }
    const int mValue;
};
</code>```

Disregarding other problems with this, if I try to create a nested expression using this "language" I will very quickly end up with redundant leaf nodes:

```<code>int main()
{
    auto Res0 = Op(Value(1), Value(2)); // 1 + 2
    auto Res1 = Op(Res0, Res0); // (1 + 2) + (1 + 2)
    auto Res2 = Op(Res1, Res1); // ((1 + 2) + (1 + 2) + (1 + 2) + (1 + 2))
    auto Res3 = Op(Res2, Res2); // etc.
    auto Res4 = Op(Res3, Res3);
    auto Res5 = Op(Res4, Res4);
    auto Res6 = Op(Res5, Res5);
    auto Res7 = Op(Res6, Res6);
    auto Res8 = Op(Res7, Res7);
    auto Res9 = Op(Res8, Res8);
    auto Res10 = Op(Res9, Res9);
    auto Res11 = Op(Res10, Res10);
    auto Res12 = Op(Res11, Res11);
    auto Res13 = Op(Res12, Res12);
    auto Res14 = Op(Res13, Res13);
    auto Res15 = Op(Res14, Res14);
    auto Res16 = Op(Res15, Res15);
    auto Res17 = Op(Res16, Res16);
    auto Res18 = Op(Res17, Res17);
    auto Res19 = Op(Res18, Res18);
    auto Res20 = Op(Res19, Res19);
}
</code>```

The above code in any normal language will have linear complexity on the number of "Res" depths (in this case 21), and presumably functional language implementations do as well.

However, in the above example, my program will call the () operator  on the Value class 2^21 times. If Value is not trivial to calculate, this could make my program tremendously inefficient!

I can reduce the number of calls to Value by introducing a cache:

```<code>template <
struct OpImpl
{
    Op(LHS lhs, RHS rhs) : mLhs(lhs), mRhs(rhs) {}
    auto operator()() const
    {
        // some unique identifier
        auto cacheIndex = findMyIndex(this) // this could be a typeid, etc.

        if (!cache.count(cacheIndex))
            cache[cacheIndex] = mLhs() + mRhs();
        return cache[cacheIndex];
    }

    LHS mLhs;
    RHS mRhs;
};
</code>```

The above reduces the number of calls to the parenthesis operator of Value to 2 and the number of calls to OpImpl to 21. With some tweaking (figuring out the cache position at construction, using an efficient lookup, memory pools, etc.) we can probably make these lookups quite cheap, but we're still doing 21 lookups / pointer indirection for a series of operations that would be much more efficient in bespoke c++ or with a real functional language.

So, to get to my question; how do functional languages solve this problem, and, more importantly, how do I apply such a solution to the simple DSL example given above, such that the code exhibits a reasonable amount of efficiency?

Note that I am not asking about making the above algorithm perform more quickly, I want to find a better algorithm.

答:
You seems to want to make some optimization (e.g. common subexpression extraction, as commented by rwong) in your interpreter.

Notice also that a language (even a domain-specific language) is never defined by some internal representation, but a computer language is defined by its syntax and its semantics (so you'll better define them first, at least on paper, before any implementation effort).

The syntax defines what are the valid sentences or phrases of your language, and the semantics defines what are their behavior or meaning.

Actually, interpreters vs compilers does not mean much, and there is a continuum between them.

The most inefficient interpreters are like the BASIC interpreters on original PC in the 1980: they are rescanning and reparsing and interpreting the source code of every statement every time they need to interpret it. So when interpreting a loop they are repeatedly reparsing the text of each statement.

Then you have interpreters which are parsing into some abstract syntax trees (AST) and later evaluating (recursively) the ASTs.

It is usually more efficient to have the interpreter transforming (usually once) the AST into some lower form, often some bytecode interpreted by a virtual machine and doing some optimizations on it (many efficient interpreters are doing that, e.g. Ocaml, Lua, etc...). You could consider translating your DSL into some existing bytecode VM like Parrot. Actually efficient compilers and interpreters are transforming the AST into bytecode (or object code, or C code) using several passes (FYI the GCC compiler has several hundreds of passes).

Finally, you can transform the AST or the bytecode (or some other internal representation) into machine code using e.g. Just-In-Time translation techniques (e.g. with JIT libraries like libjit, libgccjit, LLVM, ...)

At last, ordinary ahead-of-time compilers exist. BTW, you could compile to e.g. C code (see this) and dynamically load (e.g. with dlopen on POSIX systems) and execute it. I'm doing that in MELT (and it is actually compatible with an interactive REPL loop).

At least if you know a tiny bit of Lisp or Scheme, you should read Queinnec's Lisp In Small Pieces book, which covers most of the spectrum outlined above.

Compilers and interpreters have a lot of things in common, and there is a continuum between them. So you should dive into a good compiler book.

BTW, why don't you reuse some existing embeddable language implementation like GUILE?

Notice that your example is very artificial in practice. People usually don't have a very deep arithmetic expressions like you are showing. I guess that if you do something equivalent with the C preprocessor or with C++ templates the C or C++ compiler would need a lot of CPU time to compile it (so in my opinion you are wrong in believing that "any normal language will have linear complexity").

In your example, your AST is not a tree but a DAG, which is somehow unusual. Unless your DSL is homoiconic and/or have sophisticated macro-programming or metaprogramming (e.g. multi-staged programming) facilities, your DSL script source text won't get parsed into a DAG, but into a tree (and your issue won't happen at all).

BTW, a possible solution might be to have let  like expression binding a local variable (see what let is in Ocaml or Scheme) in your DSL, e.g. something like (using Ocaml syntax):

```<code>let x1 = 1 in
 let x2 = x1 + x1 in
  let x3 = x2 + x2 in
   let x4 = x3 + x3 in
    x4 + x4
</code>```

Notice that you might spend several months or even years to implement your efficient DSL. Are you sure that it is worth the effort? Can't you embed some existing interpreter?

Reading some books comparing several programming languages (and knowing several of thems), e.g. Scott's Programming Language Pragmatics, will certainly improve your thinking about your DSL design (before any implementation effort).

Body:
You seems to want to make some optimization (e.g. common subexpression extraction, as commented by rwong) in your interpreter.

Notice also that a language (even a domain-specific language) is never defined by some internal representation, but a computer language is defined by its syntax and its semantics (so you'll better define them first, at least on paper, before any implementation effort).

The syntax defines what are the valid sentences or phrases of your language, and the semantics defines what are their behavior or meaning.

Actually, interpreters vs compilers does not mean much, and there is a continuum between them.

The most inefficient interpreters are like the BASIC interpreters on original PC in the 1980: they are rescanning and reparsing and interpreting the source code of every statement every time they need to interpret it. So when interpreting a loop they are repeatedly reparsing the text of each statement.

Then you have interpreters which are parsing into some abstract syntax trees (AST) and later evaluating (recursively) the ASTs.

It is usually more efficient to have the interpreter transforming (usually once) the AST into some lower form, often some bytecode interpreted by a virtual machine and doing some optimizations on it (many efficient interpreters are doing that, e.g. Ocaml, Lua, etc...). You could consider translating your DSL into some existing bytecode VM like Parrot. Actually efficient compilers and interpreters are transforming the AST into bytecode (or object code, or C code) using several passes (FYI the GCC compiler has several hundreds of passes).

Finally, you can transform the AST or the bytecode (or some other internal representation) into machine code using e.g. Just-In-Time translation techniques (e.g. with JIT libraries like libjit, libgccjit, LLVM, ...)

At last, ordinary ahead-of-time compilers exist. BTW, you could compile to e.g. C code (see this) and dynamically load (e.g. with dlopen on POSIX systems) and execute it. I'm doing that in MELT (and it is actually compatible with an interactive REPL loop).

At least if you know a tiny bit of Lisp or Scheme, you should read Queinnec's Lisp In Small Pieces book, which covers most of the spectrum outlined above.

Compilers and interpreters have a lot of things in common, and there is a continuum between them. So you should dive into a good compiler book.

BTW, why don't you reuse some existing embeddable language implementation like GUILE?

Notice that your example is very artificial in practice. People usually don't have a very deep arithmetic expressions like you are showing. I guess that if you do something equivalent with the C preprocessor or with C++ templates the C or C++ compiler would need a lot of CPU time to compile it (so in my opinion you are wrong in believing that "any normal language will have linear complexity").

In your example, your AST is not a tree but a DAG, which is somehow unusual. Unless your DSL is homoiconic and/or have sophisticated macro-programming or metaprogramming (e.g. multi-staged programming) facilities, your DSL script source text won't get parsed into a DAG, but into a tree (and your issue won't happen at all).

BTW, a possible solution might be to have let  like expression binding a local variable (see what let is in Ocaml or Scheme) in your DSL, e.g. something like (using Ocaml syntax):

let x1 = 1 in
 let x2 = x1 + x1 in
  let x3 = x2 + x2 in
   let x4 = x3 + x3 in
    x4 + x4

Notice that you might spend several months or even years to implement your efficient DSL. Are you sure that it is worth the effort? Can't you embed some existing interpreter?

Reading some books comparing several programming languages (and knowing several of thems), e.g. Scott's Programming Language Pragmatics, will certainly improve your thinking about your DSL design (before any implementation effort).


问:
Should you write your back-end as an API?
I had a heated discussion today about our MVC application. We have a website written in MVC (ASP.NET), and it usually follows the pattern of do something in the view -> hit the controller -> controller builds a model (calls a Manager that gets the data, builds the model in the controller method itself) -> model goes to view -> rinse & repeat.

He said that our code was too tightly coupled. For example, if we wanted a desktop application as well, we would not be able to use our existing code.

The solution and best practice he said is to build an API, and then build your website on top of your API, and then building a desktop application, mobile app, etc. is very simple.

This seems like a bad idea to me for various reasons.

Anyway I can't seem to find anything by googling that might discuss this practice. Does anyone have any information about pros, cons, why you should, why you shouldn't or further reading?

Some reasons I think it's a bad idea:

It's way too abstract to run your backend off an API. You're trying to make it too flexible which will make it an unmanagable mess.

All the stuff built into MVC seems useless, like roles and authentication. For example, [Authorize] attributes and security; you will have to roll your own.

All your API calls will require security information attached, and you will have to develop a token system and whatnot.

You will have to write complete API calls for every single function your program will ever do. Pretty much every method you want to implement will need to be ran off an API. A Get/Update/Delete for every user, plus a variant for each other operation eg update user name, add user to a group, etc. etc. and each one would be a distinct API call.

You lose all kinds of tools like interfaces and abstract classes when it comes to APIs. Stuff like WCF has very tenuous support for interfaces.

You have a method that creates a user, or performs some task. If you want to create 50 users, you can just call it 50 times. When you decide to do this method as an API your local webserver can named-pipes connect to it and no problem - your desktop client can hit it too, but suddenly your bulk user creation will involve hammering the API over the Internet 50 times which isn't good. So you have to create a bulk method, but really you're just creating it for desktop clients. This way, you end up having to a) modify your API based on what's integrating with it, and you can't just directly integrate with it, b) do a lot more work to create an extra function.

YAGNI. Unless you're specifically planning to write two identically functioning applications, one web and one Windows application for example, it is a huge amount of extra development work.

Debugging is much harder when you can't step through end-to-end.

Lots of independent operations that will require lots of back and forth, for example some code might get the current user, check the user is in the administrator role, get the company the user belongs to, get a list of other members, send them all an email. That would require a lot of API calls, or writing a bespoke method the specific task you want, where that bespoke method's only benefit would be speed yet the downside would be it would be inflexible.

Probably some more reasons these are just off the top of my head.

It just seems to me like unless you really need two identical applications, then it's really not worth it. I've never seen an ASP.NET application built like this either, you'd have to write two separate applications (the API and your code) and version control them both as well (if your user page gets a new field, you'd have to update the API and your consuming code simultaneously to ensure no ill-effects or put lots of extra work into keeping it robust).

Edit: Some great responses, really starting to get a good idea of what this all means now. So to expand on my question, how would you structure an MVC app to follow this API structure?

For example, you have a website that displays info about a user. Under MVC, you have:

View - (CS)HTML page that displays a UserViewModel
Controller - Calls GetUser() and creates a UserViewModel that it passes to the view
Manager class (sort of your API) that has a GetUser method.

The controller does GetUser() but you want a desktop app too. This means your GetUser needs to be exposed via some kind of API. You might want a TCP connection, either WCF, or perhaps Remoting. You also want a mobile app which will be RESTful since persistent connections are flaky.

So would you then write an API for each one, a WCF web service that has a method GetUser() and the code just does return new UserManager().GetUser() ? And an mvc 4 web api method that does the same thing? While continuing to call GetUser directly in your MVC controller method?

Or would you choose the solution that would work for all three (web api REST service) and build everything on that, so all three apps make API calls (the mvc ones, to the local machine).

And is this just a theoretical perfect scenario? I can see large overheads in developing this way, especially if you have to develop in a way that will let you do operations in a RESTful manner. I think some of this has been covered in the replies.

Edit 2: After reading more stuff, I've put a comment below that I think might explain it. The question is a bit of a trick question I think. Should you write your back-end as an API had me confused thinking there should be a single webservice that everything (mvc app, desktop app, mobile app) calls to do stuff.

The conclusion I have come to is that what you should really do is make sure your business logic layer is correctly decoupled. Looking at my code, I do this already - the controller will call GetUser() on a manager, then create a view model from it to render with a View. So really, the business logic layer is an API. If you want to call it from a desktop app though, you'll need to write something like a WCF service to facilitate calling it. Even just having a WCF method called GetUser() that contains the code return MyBusinessLayer.GetUser() would be sufficient. So the API is the business logic, and WCF / web api etc. are just titbits of code to let external applications in to call it.

So there is some overhead, in that you have to wrap your business logic layer in different APIs depending on what you need, and you will have to write an API method for each operation you want your other apps to do, plus you will need to sort out a way to do authentication, but for the most part it's the same. Stick your business logic in a separate project (class library), and you will probably have no issue!

Hopefully this interpretation is correct. Thanks for all the discussion/comments it has generated.

答:
There's a good deal of good answers here so I'll just add my implementation experience.

This how I do things:

Create a Database Access Layer that handles all/only DB interaction (usually manual SQL is used for speed and control, no ORM). Insert, Update, Delete, Select...

Create an interface (virtual class) that exposes/enforces the API functions I need. They will, when implemented, use the highly specialized DBAL functions to achieve the results. It also helps me to enforce the API at compiler level so I make sure the Server + API implementation have all the functions built in.

Create a Second Layer that implements the interface (this is the actual API) and enforces security restrictions. You also interact with external APIs here.

The Website will use the Second Layer directly (for performance) without going though a remote-accessible API (like SOAP, JSON).

A standalone Server is build that implements the interface and exposes the Second Layer as an actual remote-accessible API to external desktop/mobile clients (non-website access). All it does is decode requests and encode responses and manage/disconnect clients. It also supports pushback capabilities to mass-notify clients of events generated by other connected peers (functionality that a website does not usually require).

So, technically, the API is the Second Layer. You use directly it with the website and expose it to remote clients through a server. Code is reused and no reusable chunk of code is ever inline. (live and die by this rule and everything is awesome) Helps with maintainability, testing... everything.

You never connect the website to the desktop/mobile API server (unless your site is AJAX and runs on JSON). But if the site renders dynamic content in the markup, going through an intermediate API will shoot your performance. The website needs to be fast! Remote client access can be a tiny bit more slow.

PS: Yes, maintenance is a bit more complex as more wheels work together but it's easier in the long run. So if your project is meant to live for a while and is slightly complex, always have an API. It's also much easier to test each layer on its own.


问:
Reducing boilerplate in class that implements interfaces through composition
I have a class: A that is a composite of a number of smaller classes, B, Cand D.

B, C, and D implement interfaces IB, IC, and ID respectively.

Since A supports all the functionality of B, C and D, A implements IB, IC and ID as well, but this unfortunately leads to a lot of re-routing in the implementation of A

Like so:

```<code>interface IB
{
    int Foo {get;}
}

public class B : IB
{
    public int Foo {get {return 5;}}
}

interface IC
{
    void Bar();
}

public class C : IC
{
    public void Bar()
    {
    }
}

interface ID
{
    string Bash{get; set;}
}

public class D: ID
{
    public string Bash {get;set;}
}

class A : IB, IC, ID
{
    private B b = new B();
    private C c = new C();
    private D d = new D();

    public int Foo {get {return b.Foo}}

    public A(string bash)
    {
        Bash = bash;
    }

    public void Bar()
    {
        c.Bar();
    }

    public string Bash
    {
         get {return d.Bash;}
         set {d.Bash = value;}
    }
}
</code>```

Is there a way to get rid of any of this boilerplate redirection in A? B, C and D all implement different but common functionality, and I like that A implements IB, IC and ID because it means I can pass in Aitself as a dependency matching those interfaces, and don't have to expose the inner helper methods.

答:
What you are looking for is commonly called mixins. Sadly, C# doesn't natively support those.

There are few workarounds : one, two , three, and many more.

I actually really like the last one. The idea of using automatically generated partial class to generate the boilerplate is probably closest you can get to actually good solution :

[pMixins] is a Visual Studio plug-in that scans a solution for partial classes decorated with pMixin attributes. By marking your class partial, [pMixins] can create a code-behind file and add additional members to your class


答:
What you encountered is called double dispatch and what you have implemented is some form of Visitor pattern. The problem you encountered is one of the limitations of Visitor pattern. You usually have to choose between inheritance and visitor. When you have one, it makes the other harder. C#'s type and method dispatch system is simply not powerful enough to support both at the same time.

The only possible solution is to give up on having compiler check if every pair of possibilities is implemented and just keep dictionary where the two types are key and operation is the value. (its the same as you are doing it in your own answer, but your solution "hides" this fact). The confidence, that all permutations are implemented can be regained if you write an automated test, that checks if all permutations have valid calculation.

And I would say that there is no need to bring generics into mix. You would still need to convert both values into object type before passing them into the double-dispatch routine.

Title: Tricky architecture in C# involving a symmetric operation and a viewing class

Body:
I'm trying to build an architecture in C#, and I can't figure out a way to accomplish the task. Basically, there's a set of classes A, B, C and D that inherit from I. Each of these classes has an operation Foo that operates on one of the other classes, and returns an object of type R:

```<code>class A : I
{
    public R Foo(A a);
    public R Foo(B b);
    public R Foo(C c);
    public R Foo(D d);
}
class B : I
{
    public R Foo(A a);
    public R Foo(B b);
    public R Foo(C c);
    public R Foo(D d);
}
class C : I
{
    public R Foo(A a);
    public R Foo(B b);
    public R Foo(C c);
    public R Foo(D d);
}
class D : I
{
    public R Foo(A a);
    public R Foo(B b);
    public R Foo(C c);
    public R Foo(D d);
}
</code>```

This operation Foo is symmetric (i.e. a.Foo(b) == b.Foo(a), d.Foo(a) == a.Foo(d), etc.). (Of course, this means that we really only need to define Foo(A a) in A, Foo(A a) and Foo(B b) in B, and so on, but you get the idea).

If we introduce a new class E, it has to implement Foo for types A, B, C, D, and E.

```<code>class E : I
{
    public R Foo(A a);
    public R Foo(B b);
    public R Foo(C c);
    public R Foo(D d);
    public R Foo(E e);
}
</code>```

Obviously we can't externally add an implementation for public R Foo(E e) in each of the classes A, B, C, and D (well, not without extension methods), but since Foo is symmetric, a.Foo(e) == e.Foo(a), so we only really need to implement Foo(A a) in E.

Now the part that makes this really difficult for me at least, is there's also a "viewer" object V that contains a list of I's. V has to be able to perform the Foo operation between two I's without knowing their actual types. V only knows that the operation Foo exists between two I's. Theoretically, this is what it would look like:

```<code>class V {
    public R Foo(I i1, I i2)
    {
        // Check if i1 has an implementation for Foo taking
        // the type of i2.
        if (!i1.HasFoo(i2.GetType()))
        {
            // Do the same for i2 on i1.
            if (!i2.HasFoo(i1.GetType()))
                return null;
            return i2.Foo(i1);
        }
        return i1.Foo(i2);
    }
}
</code>```

Obviously this would never work, for the same reasons this doesn't work. I've thought about this for quite some time now, and I can't think of an architecture that satisfies these requirements in a clean way. I've thought up a number of convoluted methods that abuse generic types and strategy patterns and visitor patterns and the whole sh'bang, but nothing that isn't prone to bugs or overcomplicated.

How should I implement this, if it's even possible?

This is the actual, non-abstracted application. It's a collision detection engine, where the classes A, B, etc. are different geometries with fundamentally different properties (circle vs infinite line vs polygon, etc.). The different Foos are the different algorithms that test if two geometric shapes are colliding. V is an algorithmic container for a large number of these geometric objects (a quadtree or something).


问:
What is the best way to create DTOs from entities and update entities from DTOs in a layered architecture?
Option 1:

At first I would make a call to my service layer, which served as an API for my core domain, to get a domain object or a list of domain objects and then pass them into the assembler which would construct the DTOs I needed for my view. The problem I have with this approach are cases where the domain object is large and I don't want to load in the whole object just to copy a few fields needed for the DTO (ie showing a list of summaries entities).

Option 2:

The next approach I used was to wire in a repository (for read-only purposes) into my assembler so that I could only query the database for the fields I need in the DTO. I can also use this repository when I get a DTO and need to use it to update and entity. For example, a DTO filled will values I need to update on my entity comes into my assembler, the assembler looks up the entity from a repository and then overlays the information from the DTO on the entity and then returns the entity. The controller then calls the service layer to save the entity that the assembler returned.

Option 3:

I could wire in the repositories directly into the controllers but something about exposing the repository in the controller seems wrong to me because the service layer should be handling transactions and security, but then again, if I put a repository in the assembler I am basically doing the same thing.

Any thoughts are welcome. I just want to understand pros and cons and what has worked well for others.

答:
Ok. Problem 1: getting DTO's from entities:

Since your entities can expose their data publicly you can access their properties and instantiate DTO object or simply serialise the entity directly

Problem 2 : Entities from DTO's:

A constructor method which takes a list of the properties to be set can be called using the properties of the DTO

Problem 3 : large entities when you only need summary info

Create a new summary object which you can retrieve from the repository. Note I suggest you make strongly typed repositories with methods like Repo.GetMyObjectById(string id) rather than expose a generic ORM.

Problem 4 : where to orchestrate all this.

My recommendation is to have a service class one level below your hosting service/app/website.

This has access to the repositories DTO's and entities and its methods map to the controllers/service calls of your application so that you do not need any code at the top level and can host the same service in multiple ways.

Giving it access to the repos is not an issue when you can only use them to retireve entities rather than doing any query they like.

Putting this assembly/orchestration logic inside the entity is usually bad as you will want the entity to be reused for other purposes.

This top level service should be very light. Just, get these objects, call this method, create and return the result/DTO/viewmodel

Because its so light its not a massive prob if you skip the layer and put the code in your controller. But it will save you time if you change the hosting layer and help with testing etc


问:
what is the difference between overengineering, underengineering and rightengineering?
What is the difference between over-engineering, under-engineering and right-engineering at coding/design perspective?

I found over-engineering: Coding too much like doing future requirement code and implementing simple logic as very complex code. Am I right?

and I do not understand under-engineering and right-engineering.

This terminology helps us to understand a design how is implemented in single word.

terms I found in this link

答:
When you're doing too much design to solve a basic problem, you're over-engineering. For example, when you're using an abstract factory pattern “just in case” in order to create a very simple object where the business logic is easy enough to fit in four-five LOC, you're over-thinking the design (and violating KISS and YAGNI).

Note that it doesn't necessarily need to be overly complex. An abstract factory pattern has nothing complex in it as soon as classes are named correctly and the other members of the team know the pattern. This being said, it's still too much classes and code for a problem which can be solved without recurring to any specific pattern.

When you're not doing enough, you're under-engineering. For instance, if most of your Java code base is in static methods within static classes and the major part is in utility classes, you are not thinking enough about the design.

Notice that over-engineering and under-engineering is usually done by inexperienced programmers, through two different patterns:

The most inexperienced ones don't know design patterns enough and tend to not use them and not think too much about the design. They let their code grow with little or no design, finding such code simpler to read and understand.

Slightly more experienced ones who started to learn design patterns have a tendency of applying those patterns everywhere to show they know them. Should we create an object? Let's use a builder pattern with an abstract builder and a concrete one. Need to communicate between two objects? Let's use adapter pattern! And, obviously, fluent interfaces are fun, since it makes us write code like this:

Product product = ProductBuilder()
    .setId(39)
    .setPrice(new PriceFactory().usingAmount(59).usingUnit(Unit.Dollar))
    .setTitle("Product 1"),
    .setDescription("Description goes here")
    .getResult()
```

<p>instead of:</p>

<pre class="lang-java prettyprint-override"><code>Price price = new Price(59, Unit.Dollar);
Product product = new Product(39, price, "Product 1", "Description goes here");
</code>```

It requires much more skill and experience to find the golden middle, that is to use as much design as needed, but absolutely no more. This is what right-engineering term is about, although it's not used that much in the industry, for a good reason.

Over-engineering and under-engineering are the terms which are used to criticize someone else's code, like in “Dude, stop over-engineering your code, we can barely find our way through dozens of classes you add unnecessarily!” On the other hand, the golden middle of right-engineering of a developer won't necessarily be the same (and is usually not the same) for others. A recent answer shows how non-obvious is it to determine where to put a frontier between using a factory or moving the logic in a constructor. Thus, one can't assert that his code is right-engineered, because at least some of his colleagues would disagree.

Body:
When you're doing too much design to solve a basic problem, you're over-engineering. For example, when you're using an abstract factory pattern “just in case” in order to create a very simple object where the business logic is easy enough to fit in four-five LOC, you're over-thinking the design (and violating KISS and YAGNI).

Note that it doesn't necessarily need to be overly complex. An abstract factory pattern has nothing complex in it as soon as classes are named correctly and the other members of the team know the pattern. This being said, it's still too much classes and code for a problem which can be solved without recurring to any specific pattern.

When you're not doing enough, you're under-engineering. For instance, if most of your Java code base is in static methods within static classes and the major part is in utility classes, you are not thinking enough about the design.

Notice that over-engineering and under-engineering is usually done by inexperienced programmers, through two different patterns:

The most inexperienced ones don't know design patterns enough and tend to not use them and not think too much about the design. They let their code grow with little or no design, finding such code simpler to read and understand.

Slightly more experienced ones who started to learn design patterns have a tendency of applying those patterns everywhere to show they know them. Should we create an object? Let's use a builder pattern with an abstract builder and a concrete one. Need to communicate between two objects? Let's use adapter pattern! And, obviously, fluent interfaces are fun, since it makes us write code like this:

Product product = ProductBuilder()
    .setId(39)
    .setPrice(new PriceFactory().usingAmount(59).usingUnit(Unit.Dollar))
    .setTitle("Product 1"),
    .setDescription("Description goes here")
    .getResult()

instead of:

Price price = new Price(59, Unit.Dollar);
Product product = new Product(39, price, "Product 1", "Description goes here");

It requires much more skill and experience to find the golden middle, that is to use as much design as needed, but absolutely no more. This is what right-engineering term is about, although it's not used that much in the industry, for a good reason.

Over-engineering and under-engineering are the terms which are used to criticize someone else's code, like in “Dude, stop over-engineering your code, we can barely find our way through dozens of classes you add unnecessarily!” On the other hand, the golden middle of right-engineering of a developer won't necessarily be the same (and is usually not the same) for others. A recent answer shows how non-obvious is it to determine where to put a frontier between using a factory or moving the logic in a constructor. Thus, one can't assert that his code is right-engineered, because at least some of his colleagues would disagree.


问:
Programming to an Interface and Interface Segregation in the Context of a User Class
I try to program to an interface whenever possible, but its not clear to me how I could apply it to a model as broad as a user. Which can hold many disparate fields (name, age, phone number, ssn, etc.) or be composed of many modules.

I could design a general purpose library of functionality for use across applications, that would take in an ICallable to make a phone call or INameable to display a name to the console. But in the end the user class (how the data is accessed and/or stored) would be unique to an application and its needs.

If I try to design the user and consumers in the library (stated above) to communicate by interface, I get an "interface soup" (or something "hydra-esque") on the user class. Where it feels like I'm extending an interface for almost every attribute or module.

```<code>public class Employee : INameable, ICallable, IAgeable, IPayable ...
</code>```

Is this particularly wrong? Am I taking interface use too far by completely avoiding the injection of concrete classes into the consumer (and preventing more general use)?

Whats a better approach to this problem?

答:
It's not wrong. It might be a hint that your class is too big for its shoes in the first place and you should refactor it, but that has nothing to do with programming against interfaces.

If you follow the principle that complex functionality should deal with interface types rather than concrete types, then your concrete class must wear all those interface "hats". The fact that it declares a long list of them is just an expression of the fact that it does many things.

As it is, the interfaces you're extending are all different things, so this long list is not a violation of DRY that you might somehow get rid off.


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答:
Empty generic exception handlers i.e. :

```<code>catch(Exception ex)
{
}
</code>```

I don't doubt that someone can give me a valid use case - but, to be honest, its going to be seriously creative... and at the very least you need an explanation.

ContentLicense: CC BY-SA 2.5

Title: Is anything in programming truly evil?

Body:
Empty generic exception handlers i.e. :

catch(Exception ex)
{
}

I don't doubt that someone can give me a valid use case - but, to be honest, its going to be seriously creative... and at the very least you need an explanation.


答:
I call the two extremes described "under-engineering" and "over-engineering"

They seem to refer to the sentence in the link above:

In my experience there are two developer character type extremes: the ones that always seek and settle with the simplest solution, and the ones that seek the perfect solution, perfect in terms of efficiency, readability or code elegance.

Seems like these aren't widely used terms, he's using them to explain the concepts in the rest of the post.

I could argue that:

The ones that always seek and settle with the simplest solution [...] constantly create mess

This is clearly not the definition I give to "simple solution".

These are interesting readings, thanks.  I'm currently reading a book called "Just enough Software Architecture", by George Fairbanks.  In that context I would probably define over-engineering (engineer too much) as spending too long in the design phase, although, you can engineer while coding too.  The book emphasises a risk driven approach.  Identify the risk, estimate the risk, prioritise tasks and engineer accordingly.  You might find that interesting too.

Title: what is the difference between overengineering, underengineering and rightengineering?

Body:
What is the difference between over-engineering, under-engineering and right-engineering at coding/design perspective?

I found over-engineering: Coding too much like doing future requirement code and implementing simple logic as very complex code. Am I right?

and I do not understand under-engineering and right-engineering.

This terminology helps us to understand a design how is implemented in single word.

terms I found in this link


问:
How do I design a subclass whose method contradicts its superclass?
How do I design a subclass whose method contradicts its superclass? Let's say we have this example:

```<code># Example 1

class Scissor
  def right_handed?
    true
  end
end

class LeftHandedScissor < Scissor
  def right_handed?
    false
  end
end
</code>```

Let's assume that the inheritance is necessary in this example e.g. that there might be other methods aside from right_handed? that are being inherited.

So a LeftHandedScissor is a Scissor. Its method right_handed? matches the signature and return value type of its superclass's method. However, the subclass method contradicts the return value of the superclass method.

This bothers me because it looks like a logical contradiction:

All scissors are right-handed.

A left-handed scissor is a scissor.

Therefore, a left-handed scissor is right-handed.

I considered introducing an AbstractScissor to avoid this contradiction:

```<code># Example 2

class AbstractScissor
  def right_handed?
    raise NotImplementedError
  end
end

class RightHandedScissor < AbstractScissor
  def right_handed?
    true
  end
end

class LeftHandedScissor < AbstractScissor
  def right_handed?
    false
  end
end
</code>```

My colleague says the downside to this solution is that it's more verbose. Aside from adding an extra class, it requires us to call scissors "right-handed scissors", which no one does in the real world.

This leads me to my last solution:

```<code># Example 3

class AbstractScissor
  def right_handed?
    raise NotImplementedError
  end
end

class Scissor < AbstractScissor
  def right_handed?
    true
  end
end

class LeftHandedScissor < AbstractScissor
  def right_handed?
    false
  end
end
</code>```

It's nearly the same as example 2 but I just renamed RightHandedScissor as Scissor. There's a chance that someone might assume LeftHandedScissor is a subclass of Scissor based solely on the class names, but at least the code makes it obvious that that's not the case.

Any other ideas?

答: "All scissors are right-handed"? Where do you get that idea from? Your code only expresses "scissors are right-handed by default". It's a default value, not a design decision. If there were no  way of having a different value, what's the point in programming a boolean accessor function?</p>


答:
You don't. It's like saying that all animals are dogs, and then asking how to make cats meow instead of bark. If you were naming your classes properly, your Scissor class would rather be named RightHandedScissor; now does it make sense to inherit LeftHandedScissor from RightHandedScissor?

One possible approach is to make Scissor class abstract, and right_handed would be abstract as well (unlike your example 2).

Then, you may have RightHandedScissor and LeftHandedScissor if it makes sense (although I can't find an example where it would make sense).

The major issue here is that you are repeating yourself. The property right_handed is barely rephrasing the type of the object. This leads to two issues:

Some developers using your code will use right_handed property, while others will do if scissor.is_a?(RightHandedScissor). Why not keeping only one way of doing this?

What if, one day, a change is made to the classes, and there is a contradiction between what property says and the type of the object?

If the business logic dictates that the type is the proper location for separating right handed from left handed scissors, then either remove the property, or at least make its value automatically computed based on the type of the object.

A better approach is to have a concrete Scissor class where the property right_handed, and not the actual class type determines whether the scissor is right handed or left handed.

This makes it easier to deal with the code: you have two classes less and don't have the redundancy (that is a property which barely rephrases the type). If you don't want a left handed scissor to become right handed, you may consider a read-only/constant property instead (i.e. the one which can be set only by the constructor, and cannot be changed after that; the terminology may change from a language to another).

Body:
How do I design a subclass whose method contradicts its superclass? Let's say we have this example:

```<code># Example 1

class Scissor
  def right_handed?
    true
  end
end

class LeftHandedScissor < Scissor
  def right_handed?
    false
  end
end
</code>```

Let's assume that the inheritance is necessary in this example e.g. that there might be other methods aside from right_handed? that are being inherited.

So a LeftHandedScissor is a Scissor. Its method right_handed? matches the signature and return value type of its superclass's method. However, the subclass method contradicts the return value of the superclass method.

This bothers me because it looks like a logical contradiction:

All scissors are right-handed.

A left-handed scissor is a scissor.

Therefore, a left-handed scissor is right-handed.

I considered introducing an AbstractScissor to avoid this contradiction:

```<code># Example 2

class AbstractScissor
  def right_handed?
    raise NotImplementedError
  end
end

class RightHandedScissor < AbstractScissor
  def right_handed?
    true
  end
end

class LeftHandedScissor < AbstractScissor
  def right_handed?
    false
  end
end
</code>```

My colleague says the downside to this solution is that it's more verbose. Aside from adding an extra class, it requires us to call scissors "right-handed scissors", which no one does in the real world.

This leads me to my last solution:

```<code># Example 3

class AbstractScissor
  def right_handed?
    raise NotImplementedError
  end
end

class Scissor < AbstractScissor
  def right_handed?
    true
  end
end

class LeftHandedScissor < AbstractScissor
  def right_handed?
    false
  end
end
</code>```

It's nearly the same as example 2 but I just renamed RightHandedScissor as Scissor. There's a chance that someone might assume LeftHandedScissor is a subclass of Scissor based solely on the class names, but at least the code makes it obvious that that's not the case.

Any other ideas?


答:
You are thinking too logically! There is no logical contradiction because class definitions are not logical propositions.

Having the Scissor base class return true does not correspond to saying that all scissors are right-handed. It just means that a scissor instance is right-handed unless the method is overridden in a subclass.

Title: How do I design a subclass whose method contradicts its superclass?


答:
Another option is to introduce the handed-ness as a dependency with a default value of right-handed. In pseudocode here as I am not familiar with Ruby:

```<code>class Scissors {
    Scissors(isRightHanded = true) {
        _isRightHanded = isRightHanded
    }

    IsRightHanded() {
        return _isRightHanded
    }
}

class LeftHandedScissors : Scissors {
    LeftHandedScissors() : Scissors(isRightHanded: false) { }
}
</code>```

In fact, you then don't even need the LeftHandedScissors class - you can just create Scissors(isRightHanded: false) when you need a left-handed scissor.

This approach is called preferring composition over inheritance

Body:
Another option is to introduce the handed-ness as a dependency with a default value of right-handed. In pseudocode here as I am not familiar with Ruby:

class Scissors {
    Scissors(isRightHanded = true) {
        _isRightHanded = isRightHanded
    }

    IsRightHanded() {
        return _isRightHanded
    }
}

class LeftHandedScissors : Scissors {
    LeftHandedScissors() : Scissors(isRightHanded: false) { }
}

In fact, you then don't even need the LeftHandedScissors class - you can just create Scissors(isRightHanded: false) when you need a left-handed scissor.

This approach is called preferring composition over inheritance


问:
Black box or white box testing - which do you do first?
On a very small team, where the black box and white box testing is done by the same person, which should the tester do first?</p>

答:
Black box testing, because you are writing tests before the code exists.  The tester needs to be developing time-consuming automatic tests in parallel with the developer writing code to be efficient on a small team.

If the code is already written, I would suggest you spend some time sketching out test coverage from a black-box point of view to make sure you get some time brainstorming before you clutter your brain with the actual code.  However, you can then switch to white-box and look at the code before you get too far along with actual testing to get a feel for the risky areas and to prioritize those tests you brainstormed earlier (and augment them with new tests thought up by looking at parts of the code that seem complicated or questionable).


答:
There is nothing wrong with the design shown in the question.  While one could also introduce abstract Scissor with two concrete subclasses, and maybe more overall clarity, it's also common to do it like shown (especially when the hierarchy is a result of years of incremental development, with Scissor being around for much longer than the concept of handedness).

"Okay, I guess the lesson here is that you don't make assumptions about the subclasses based solely on the superclass?"

You do make such assumptions based on the contracts (method signatures) of the base class, but not based on method implementations.  In this case the contract says that right_handed is a Boolean method which can be true or false, so it can be either.  You should ignore the fact that the base class implementation always returns true, especially if you allowed to derive from the base class by not freezing it.  The base class implementation is then just a default, and the method right_handed exists exactly because the scissor could also be left handed.