答:
As far as I can tell, you want to provide an API allowing users of your library to build complex objects (Hexagons), having a set of attributes that potentially can be extended in the future (transparent, passable, passage cost etc).

Design issues like that are targeted by Builder pattern:

the builder pattern uses another object, a builder, that receives each initialization parameter step by step and then returns the resulting constructed object at once... Builders are good candidates for a fluent interface...

For your case, implementation could look as follows (assuming newAttribute being added in later version library):

```<code>public class HexagonBuilder {

    public Hexagon build() { /*...*/ }

    public HexagonBuilder transparent(boolean isTransparent) { /*...*/; return this }

    public HexagonBuilder passable(boolean isPassable) { /*...*/; return this }

    public HexagonBuilder passageCost(int cost) { /*...*/; return this }

    public HexagonBuilder newAttribute(Object attribute) { /*...*/; return this }
}
</code>```

As you can see, old code would compile just fine with newer version of your library, because it's only difference is compatible - it just doesn't invoke newAttribute method.

Note that for old code not only compile, but also work smoothly with newer version library, you will need to provide an appropriate default behavior for client code that doesn't set new attribute.

For the sake of completeness, consider taking a look at other creational patterns - Factory, Prototype etc, although per details provided in the question so far, Builder looks like the best fit.

Body:
As far as I can tell, you want to provide an API allowing users of your library to build complex objects (Hexagons), having a set of attributes that potentially can be extended in the future (transparent, passable, passage cost etc).

Design issues like that are targeted by Builder pattern:

the builder pattern uses another object, a builder, that receives each initialization parameter step by step and then returns the resulting constructed object at once... Builders are good candidates for a fluent interface...

For your case, implementation could look as follows (assuming newAttribute being added in later version library):

public class HexagonBuilder {

    public Hexagon build() { /*...*/ }

    public HexagonBuilder transparent(boolean isTransparent) { /*...*/; return this }

    public HexagonBuilder passable(boolean isPassable) { /*...*/; return this }

    public HexagonBuilder passageCost(int cost) { /*...*/; return this }

    public HexagonBuilder newAttribute(Object attribute) { /*...*/; return this }
}

As you can see, old code would compile just fine with newer version of your library, because it's only difference is compatible - it just doesn't invoke newAttribute method.

Note that for old code not only compile, but also work smoothly with newer version library, you will need to provide an appropriate default behavior for client code that doesn't set new attribute.

For the sake of completeness, consider taking a look at other creational patterns - Factory, Prototype etc, although per details provided in the question so far, Builder looks like the best fit.


问:
Searching integer sequences
I have a fairly complex search problem that I've managed to reduce to the following description. I've been googling but haven't been able to find an algorithm that seems to fit my problem cleanly. In particular the need to skip arbitrary integers. Maybe someone here can point me to something?

Take a sequence of integers A, for example (1 2 3 4)

Take various sequences of integers and test if any of them match A such that.

A contains all of the integers in the tested sequence

The ordering of the integers in the tested sequence are the same in A

We don't care about any integers in A that are not in the test sequence

We want all matching test sequences, not just the first.

An example

```<code>A = (1 2 3 4)
B = (1 3)
C = (1 3 4)
D = (3 1)
E = (1 2 5)
</code>```

B matches A

C matches A

D does not match A as the ordering is different

E does not match A as it contains an integer not in A

I hope that this explanation is clear enough. The best I've managed to do is to contruct a tree of the test sequences and iterate over A. The need to be able to skip integers leads to a lot of unsuccessful search paths.

Thanks

Reading some suggestions I feel that I have to clarify a couple of points that I left too vague.

Repeated numbers are allowed, in fact this is quite important as it allows a single test sequence to match A is multiple ways

A = (1234356), B = (236), matches could be either -23---6 or -2--3-6

I expect there to be a very large number of test sequences, in the thousands at least and sequence A will tend to have a max length of maybe 20. Thus simply trying to match each test sequence one by one by iterating becomes extremely inefficient.

Sorry if this wasn't clear.

答:
Here is a practical approach which avoids "the hard work" of implementing your own algorithm, and also avoids to "reinvent the wheel": utilize a regular expression engine for the problem.

Just put all numbers of A into a string, and all numbers of B into a string separated by the regular expression (.*). Add a ^ character at the beginning and $ at the end. Then let your favorite regular expression engine search for all matches. For example, when

A = (1234356), B = (236)

create a reg exp for B like ^(.*)2(.*)3(.*)6(.*)$. Now run a global regexp search. To find out at which positions in A your subsequence matches, just check the length of the first 3 submatches.

If your range of integers leaves 0 to 9, you may consider to encode them by single letters first to make this work, or you have to adapt the idea using a separation character.

Of course, the speed of that approach will depend a lot on the speed of the reg exp engine your are using, but there are highly optimized engines available, and I guess it will be hard to implement a faster algorithm "out of the box".

ContentLicense: CC BY-SA 3.0

Title: Searching integer sequences


问:
Should I continue learning a language if in the meanwhile I became interested in another language/platform?
I started learning Java a couple of months ago. I also wanted to become more exposed to linux so I installed ubuntu and started working with Java since then. In the meanwhile however I became more interested in C# and in learning the Windows platform. At this point I'm asking myself if I should stop learning Java and move to the .NET world. I don't hate or dislike Java by the way, I am just more curious about windows/.NET at this point in time. </p>

<p>My question is, should I remain with Java or go with C#/.NET? What is your advice?  </p>

答: You can use Java or C# on either Windows or Linux.  Look into Mono, for example, to use C# on other platforms.</p>

OwnerDisplayName: UML

ContentLicense: CC BY-SA 2.5


问:
Get entities ids from two similar collections using one method
I've got two lists:

```<code>List<Integer, ZooEntity> zoos;
List<Integer, List<ZooEntity>> groupOfZoos;
</code>```

These operations will return collections of values:

```<code>Collection<ZooEntity> cz = zoos.values();
Collection<List<ZooEntity>> czList = groupOfZoos.values();
</code>```

What I want to achieve is to get list of all zoo ids.

```<code>List<Integer> zooIds = cz ids + czList ids;
</code>```

Of course I can create two methods to do what I want:

```<code>public List<Integer> getIdsFromFlatList(Collection<ZooEntity> list) {
    List<Integer> ids = new ArrayList<Integer>();
    for (ZooEntity z : list) {
        ids.add(z.getId());
    }
    return ids;
}

public List<Integer> getIdsFromNestedList(Collection<List<ZooEntity>> list) {
    List<Integer> ids = new ArrayList<Integer>();
    for (List<ZooEntity> zList : list) {
        for (ZooEntity z : zList) {
            ids.add(z.getId());
        }
    }
    return ids;
}
</code>```

As you can see those two methods are very similar and here is my question:

Is it good to create one method (for example using generics) which will get ids from those two lists (zoos and groupOfZoos). If yes how it should look like? If no what is the best solution?

BTW. This is only the example. I've got very similar problem at job and I want to do it in preety way (I can't change enities, I can change only getIds...() methods).

答:
Generics aren't the answer here, because all your data objects are ZooEntity objects. If you had related classes such as Animal, Vegetable and Mineral it would make sense to have a generic method dealing with "something that has an ID", but that's not the case here.

What you do have is things, collections of things and nested collections of things. There is no natural interface that you could use or define to do the job at hand with one function - collections simply don't have a getId() method. You could simplify your code using recursion, but that would mean instanceof checks at every level of processing. As long as you only have linear lists and singly-nested lists, the most obvious route is simply to have your second method call the first one.


问:
Shuffling algorithm with no "self-mapping"?
To randomly shuffle an array, with no bias towards any particular permutation, there is the Knuth Fischer-Yeats algorithm. In Python:

```<code>#!/usr/bin/env python
import sys
from random import randrange

def KFYShuffle(items):
    i = len(items) - 1
    while i > 0:
        j = randrange(i+1)  # 0 <= j <= i
        items[j], items[i] = items[i], items[j]
        i = i - 1
    return items

print KFYShuffle(range(int(sys.argv[1])))
</code>```

There is also Sattolo's algorithm, which produces random cycles. In Python:

```<code>#!/usr/bin/env python
import sys
from random import randrange

def SattoloShuffle(items):
    i = len(items)
    while i > 1:
        i = i - 1
        j = randrange(i)  # 0 <= j <= i-1
        items[j], items[i] = items[i], items[j]
    return items

print SattoloShuffle(range(int(sys.argv[1])))
</code>```

I'm currently writing a simulation with the following specifications for a shuffling algorithm:

The algorithm is unbiased. If a true random number generator was used, no permutation would be more likely than any other.

No number ends up at its original index. The input to the shuffle will always be A[i] = i for i from 0 to N-1

Permutations are produced that are not cycles, but still meet specification 2.

The cycles produced by Sattolo's algorithm meet specification 2, but not specification 1 or 3. I've been working at creating an algorithm that meets these specifications, what I came up with was equivalent to Sattolo's algorithm.

Does anyone have an algorithm for this problem?

答:
By the way, a shuffling (permutation) that leaves no element in its original place is called a derangement.

A simple way is to just generate a random permutation, check to see if it's a derangement, and try again if it is not. The problem is that there is no upper bound on the time taken, but the expected number of shuffles is approximately e (2.718…), because the fraction of permutations that are also derangements approaches 1/e.


答:
The question I would ask myself, from a DDD perspective, is "does the address know it is a home or business or what have you?"

The answer is likely no. A slightly better model would be to have a user have an addresses collection like you are showing but also add a property pointing at the home / business / primary addresses as required.

One technical note is that, for package delivery purposes you should have an "Is Residential" flag on the address, as well as an "Is PO Box" flag to filter those out as they do materially change how one can deliver things which are the sorts of things an address object should understand.

Title: How to model an address type in DDD?

Body:
I have an User entity that has a Set of Address where Address is a value object:

```<code>class User{
    ...
    private Set<Address> addresses;
    ...
    public setAddresses(Set<Address> addresses){
        //set all addresses as a batch
    }
    ...
}
</code>```

A User can have a home address and a work address, so I should have something that acts as a look up in the database:

tbl_address_type

```
------------------------------------------------
|    address_type_id       | address_type      |
------------------------------------------------
|            1             |      work         |
------------------------------------------------
|            2             |      home         |
------------------------------------------------
```

and correspondingly tbl_address

```
-------------------------------------------------------------------------------------
|    address_id       |     address_description      |address_type_id|    user_id   |
-------------------------------------------------------------------------------------
|          1          |      123 main street         |      1        |      100     |
-------------------------------------------------------------------------------------
|          2          |      456 another street      |      1        |      100     |
-------------------------------------------------------------------------------------
|          3          |      789 long street         |      2        |      200     |
-------------------------------------------------------------------------------------
|          4          |      023 short street        |      2        |     200      |
-------------------------------------------------------------------------------------
```

Should the address type be modeled as an Entity or Value type? and Why?

Is it OK for the Address Value object to hold a reference to the Entity AdressType (in case it was modeled as an entity)? Is this something feasible using Hibernate/NHibernate?

If a user can change his home address, should I expose a User.updateHomeAddress(Address homeAddress) function on the User entity itself? How can I enforce that the client passes a Home address and not a work address in this case? (a sample implementation is most welcomed)

If I want to get the User's home address via User.getHomeAddress() function, must I load the whole addresses array then loop it and check each for its type till I find the correct type then return it? Is there a more efficient way than this?


答:
Does user need more than 3 addresses? Rarely. I recommend to denormalize the collection of addresses.

User will simply have fields address_home, address_work, address_other where all 3 will be of type Address, which will be value type.

This model covers 99.99% of use cases, is much easier to understand, is easily implemented in code and maps much better to both relational and document model.

And if you plan to use relational DB, you can have all data in User table, which will speed up retrieval significantly.

If denormalization is not an option, then I would model the addresses as Map/Dictionary with address as value and either string or some kind of enum as key. The Address would be immutable value object and the relational model will be single table with composite primary key from userId and map's key. Thus, the address itself would not have an identifier. Rest of the table would be data of the address. This still keeps the model simple and easy to understand. But the mapping between dictionary and relational table might not be that simple. But it is still doable.

Title: How to model an address type in DDD?


问:
What are the disadvantages of self-encapsulation?

Background

Tony Hoare's billion dollar mistake was the invention of null. Subsequently, a lot of code has become riddled with null pointer exceptions (segfaults) when software developers try to use (dereference) uninitialized variables.

In 1989, Wirfs-Brock and Wikerson wrote:

Direct references to variables severely limit the ability of programmers to reﬁne existing classes. The programming conventions described here structure the use of variables to promote reusable designs. We encourage users of all object-oriented languages to follow these conventions. Additionally, we strongly urge designers of object-oriented languages to consider the effects of unrestricted variable references on reusability.

Problem

A lot of software, especially in Java, but likely in C# and C++, often uses the following pattern:

```<code>public class SomeClass {
  private String someAttribute;

  public SomeClass() {
    this.someAttribute = "Some Value";
  }

  public void someMethod() {
    if( this.someAttribute.equals( "Some Value" ) ) {
      // do something...
    }
  }

  public void setAttribute( String s ) {
    this.someAttribute = s;
  }

  public String getAttribute() {
    return this.someAttribute;
  }
}
</code>```

Sometimes a band-aid solution is used by checking for null throughout the code base:

```<code>  public void someMethod() {
    assert this.someAttribute != null;

    if( this.someAttribute.equals( "Some Value" ) ) {
      // do something...
    }
  }

  public void anotherMethod() {
    assert this.someAttribute != null;

    if( this.someAttribute.equals( "Some Default Value" ) ) {
      // do something...
    }
  }
</code>```

The band-aid does not always avoid the null pointer problem: a race condition exists. The race condition is mitigated using:

```<code>  public void anotherMethod() {
    String someAttribute = this.someAttribute;
    assert someAttribute != null;

    if( someAttribute.equals( "Some Default Value" ) ) {
      // do something...
    }
  }
</code>```

Yet that requires two statements (assignment to local copy and check for null) every time a class-scoped variable is used to ensure it is valid.

Self-Encapsulation

Ken Auer's Reusability Through Self-Encapsulation (Pattern Languages of Program Design, Addison Wesley, New York, pp. 505-516, 1994) advocated self-encapsulation combined with lazy initialization. The result, in Java, would resemble:

```<code>public class SomeClass {
  private String someAttribute;

  public SomeClass() {
    setAttribute( "Some Value" );
  }

  public void someMethod() {
    if( getAttribute().equals( "Some Value" ) ) {
      // do something...
    }
  }

  public void setAttribute( String s ) {
    this.someAttribute = s;
  }

  public String getAttribute() {
    String someAttribute = this.someAttribute;

    if( someAttribute == null ) {
      someAttribute = createDefaultValue();
      setAttribute( someAttribute );
    }

    return someAttribute;
  }

  protected String createDefaultValue() { return "Some Default Value"; }
}
</code>```

All duplicate checks for null are superfluous: getAttribute() ensures the value is never null at a single location within the containing class.

Efficiency arguments should be fairly moot -- modern compilers and virtual machines can inline the code when possible.

As long as variables are never referenced directly, this also allows for proper application of the Open-Closed Principle.

Question

What are the disadvantages of self-encapsulation, if any?

(Ideally, I would like to see references to studies that contrast the robustness of similarly complex systems that use and don't use self-encapsulation, as this strikes me as a fairly straightforward testable hypothesis.)

答:
The disadvantages are the inefficiency of the extra indirection, as you pointed out, and the fact that the compiler doesn't enforce it.  All it takes is your worst programmer using one unencapsulated reference to destroy the benefits.

Also, the right way to solve a null pointer problem isn't to replace it with a non-null default value with essentially the same characteristics.  The problem with null pointer dereferences isn't that they cause a segfault.  That's just a symptom.  The problem is that the programmer might not always handle an unexpected default/uninitialized value.  That problem still must be handled separately with your self-encapsulation pattern.

The right way to solve a null pointer problem is to not create the object until a semantically valid non-null value can be put into the attribute, and to destroy the object before it is necessary to set any of its attributes to null.  If there is never the possibility for a pointer to be null, there is never a need to check it.

Usually when people think an attribute must be null, they are trying to do too much in one class.  It often makes the code much cleaner to split it into two classes.  You can also split functions to avoid null assignments.  Here's an example from another question where I refactored a function to avoid a problematic null assignment.


问:
it is a good approach to implement dependency injection in a desktop app?
Well, the thing is that I am just about to create a Desktop App (with .NET windows forms)

And now I just wonder if it would be really a wise choise to use any IoC (StructureMap,Ninject,Spring .Net), I have used them before for Asp.Net web applications but what makes me doubt now is the fact that working with windows forms my business entities will persist when I navigate through tabs and unlike than web forms or mvc apps  where it would be necesary to inject my business entity for every new request that is performed, I mean this because of the Asp.Net page life cycle where is performed the initialization and controls instantiation.

Maybe I am misunderstanding the point of using an IoC, so please tell me what do you think would be a better choise?

答:
If I am going to work on a desktop application or tool of a even a moderate size (but with potential to grow in functionality), I have started using a dependency injection framework. People may argue that this is overkill, but I am so used to it at this point it doesn't slow me down. You could still perform injection manually if you wanted, though. My personal favorite framework, Autofac, mostly stays out of the way, and I find that it actually makes my code simpler. I prefer keeping control of object creation and lifetimes in the container. Of course, I also write tests so that is a factor.

I would say that from your description and comments, the application will be complex enough that I personally feel it justifies using DI.


答: If it will help your decision, Java is a relatively stable language; it's speed of evolution is much slower than that of C#.  Consequently, C# is getting all of the cool new features more rapidly than Java.  Whether this is a good thing or not depends on your own point of view.</p>

Title: Should I continue learning a language if in the meanwhile I became interested in another language/platform?

Body:
I started learning Java a couple of months ago. I also wanted to become more exposed to linux so I installed ubuntu and started working with Java since then. In the meanwhile however I became more interested in C# and in learning the Windows platform. At this point I'm asking myself if I should stop learning Java and move to the .NET world. I don't hate or dislike Java by the way, I am just more curious about windows/.NET at this point in time. </p>

<p>My question is, should I remain with Java or go with C#/.NET? What is your advice?  </p>


问:
Is "If a method is re-used without changes, put the method in a base class, else create an interface" a good rule-of-thumb?
A colleague of mine came up with a rule-of-thumb for choosing between creating a base class or an interface.

He says:

Imagine every new method that you are about to implement. For each of them, consider this: will this method be implemented by more than one class in exactly this form, without any change? If the answer is "yes", create a base class. In every other situation, create an interface.

For example:

Consider the classes cat and dog, which extend the class mammal and have a single method pet(). We then add the class alligator, which doesn't extend anything and has a single method slither().

Now, we want to add an eat() method to all of them.

If the implementation of eat() method will be exactly the same for cat, dog and alligator, we should create a base class (let's say, animal), which implements this method.

However, if it's implementation in alligator differs in the slightest way, we should create an IEat interface and make mammal and alligator implement it.

He insists that this method covers all cases, but it seems like over-simplification to me.

Is it worth following this rule-of-thumb?

答:
Is it worth following this rule-of-thumb?

It is a decent rule of thumb, but I know of quite a few places where I violate it.

To be fair, I use (abstract) base classes a lot more than my peers. I do this as defensive programming.

To me (in many languages), an abstract base class adds the key constraint that there may only be one base class. By choosing to use a base class rather than an interface, you're saying "this is the core functionality of the class (and any inheritor), and it is inappropriate to mix willy-nilly with other functionality". Interfaces are the opposite: "This is some trait of an object, not necessarily its core responsibility".

These sort of design choices create implicit guides to your implementors about how they should use your code, and by extension write their code. Because of their greater impact to the codebase, I tend to take these things into consideration more strongly when making the design decision.


答:
No.

Interfaces are about how the methods are implemented. If you are basing your decision of whenever to use interface on how the methods will be implemented, then you are doing something wrong.

For me, difference between interface and base class is about where the requirements stand. You create interface, when some piece of code requires class with specific API and implied behavior that emerges from this API. You cannot create an interface without code that will actually call it.

On the other side, base classes are usually meant as way to reuse code, so you rarely bother with code that will call this base class and only take into account the hiearchy of objects that this base class is part of.

Title: Is "If a method is re-used without changes, put the method in a base class, else create an interface" a good rule-of-thumb?

Body:
A colleague of mine came up with a rule-of-thumb for choosing between creating a base class or an interface.

He says:

Imagine every new method that you are about to implement. For each of them, consider this: will this method be implemented by more than one class in exactly this form, without any change? If the answer is "yes", create a base class. In every other situation, create an interface.

For example:

Consider the classes cat and dog, which extend the class mammal and have a single method pet(). We then add the class alligator, which doesn't extend anything and has a single method slither().

Now, we want to add an eat() method to all of them.

If the implementation of eat() method will be exactly the same for cat, dog and alligator, we should create a base class (let's say, animal), which implements this method.

However, if it's implementation in alligator differs in the slightest way, we should create an IEat interface and make mammal and alligator implement it.

He insists that this method covers all cases, but it seems like over-simplification to me.

Is it worth following this rule-of-thumb?


问:
Updating password hashing without forcing a new password for existing users
You maintain an existing application with an established user base. Over time it is decided that the current password hashing technique is outdated and needs to be upgraded. Furthermore, for UX reasons, you don't want existing users to be forced to update their password. The whole password hashing update needs to happen behind the screen.

Assume a 'simplistic' database model for users that contains:

ID

Email

Password

How does one go around to solving such a requirement?

My current thoughts are:

create a new hashing method in the appropriate class

update the user table in the database to hold an additional password
field

Once a user successfully logs in using the outdated password hash, fill the second password field with the updated hash

This leaves me with the problem that I cannot reasonable differentiate between users who have and those who have not updated their password hash and thus will be forced to check both. This seems horribly flawed.

Furthermore this basically means that the old hashing technique could be forced to stay indefinitely until every single user has updated their password. Only at that moment could I start removing the old hashing check and remove the superfluous database field.

I'm mainly looking for some design tips here, since my current 'solution' is dirty, incomplete and what not, but if actual code is required to describe a possible solution, feel free to use any language.

答:
I did something like this and there is a way to tell if it's the new hash AND make it even more secure. I'm guessing more secure is a good thing for you if you are taking the time to update your hash ;-)

Add a new column to your DB table called "salt" and well, use it as a per user random generated salt. (pretty much prevents rainbow table attacks)

That way, if my password is "pass123" and random salt is 3333 my new password would be the hash of "pass1233333".

If the user has a salt you know it's the new hash. If the user's salt is null you know it's the old hash.


答:
I'm sort of watching the answers to this question myself, to see what other people have to say, but I will say three things that I'm inclined to think about this:

People put way too much faith into interfaces, and too little faith into classes.  Interfaces are essentially very watered down base classes, and there are occasions when using something lightweight can lead to things like excessive boilerplate code.

There is nothing wrong at all with overriding a method, calling super.method() within it, and letting the rest of its body just do things that don't interfere with the base class.  This does not violate the Liskov Substitution Principle.

As a rule of thumb, being this rigid and dogmatic in software engineering is a bad idea, even if something generally is a best practice.

So I would take what was said with a grain of salt.


答:
I don't think that this is a good rule of thumb. If you are concerned about code reuse, you can implement a PetEatingBehavior which role is to define the eating functions for cats and dogs. Then you can have IEat and code reuse together.

These days I see less and less reasons to use inheritance. One big advantage is the ease of use. Take a GUI framework. A popular way to design an API for this is to expose a huge base class, and document which methods the user can override. So we can ignore all the other complex things our application needs to manage, since a "default" implementation is given by the base class. But we can still customize things by reimplementing the correct method when we need to.

If you stick to interface for your api, your user has usually more work to do to make simple examples work. But API with interfaces are often less coupled and easier to maintain for the simple reason that IEat contains less information than the Mammal base class. So consumers will depend on a weaker contract, you get more refactoring opportunities, etc.

To quote Rich Hickey: Simple != Easy


答:
Examples rarely make a point, especially not when they are about cars or animals. An animal's way of eating (or processing food) is not really tied to its inheritance, there is no single way of eating that would apply to all animals. This is more dependent on its physical capabilities (the ways of input, processing and output so to say). Mammals can be carnivores, herbivores or omnivores for example, while birds, mammals and fish can eat insects. This behavior can be captured with certain patterns.

You're in this case better off by abstracting behavior, like this:

```<code>public interface IFoodEater
{
    void Eat(IFood food);
}

public class Animal : IFoodEater
{
    private IFoodProcessor _foodProcessor;
    public Animal(IFoodProcessor foodProcessor)
    {
        _foodProcessor = foodProcessor;
    }

    public void Eat(IFood food)
    {
        _foodProcessor.Process(food);
    }
}
</code>```

Or implement a visitor pattern where a FoodProcessor tries to feed compatible animals (ICarnivore : IFoodEater, MeatProcessingVisitor). The thought of live animals may hinder you in thinking about ripping their digestive track out and replacing it with a generic one, but you're really doing them a favor.

This will make your animal a base class, and even better, one you'll never have to change again when adding a new type of food and an according processor, so you can focus on the things that make this specific animal class you're working on so unique.

So yes, base classes have their place, the rule of thumb does apply (often, not always, as it is a rule of thumb) but keep looking for behavior you can isolate.

Body:
Examples rarely make a point, especially not when they are about cars or animals. An animal's way of eating (or processing food) is not really tied to its inheritance, there is no single way of eating that would apply to all animals. This is more dependent on its physical capabilities (the ways of input, processing and output so to say). Mammals can be carnivores, herbivores or omnivores for example, while birds, mammals and fish can eat insects. This behavior can be captured with certain patterns.

You're in this case better off by abstracting behavior, like this:

public interface IFoodEater
{
    void Eat(IFood food);
}

public class Animal : IFoodEater
{
    private IFoodProcessor _foodProcessor;
    public Animal(IFoodProcessor foodProcessor)
    {
        _foodProcessor = foodProcessor;
    }

    public void Eat(IFood food)
    {
        _foodProcessor.Process(food);
    }
}

Or implement a visitor pattern where a FoodProcessor tries to feed compatible animals (ICarnivore : IFoodEater, MeatProcessingVisitor). The thought of live animals may hinder you in thinking about ripping their digestive track out and replacing it with a generic one, but you're really doing them a favor.

This will make your animal a base class, and even better, one you'll never have to change again when adding a new type of food and an according processor, so you can focus on the things that make this specific animal class you're working on so unique.

So yes, base classes have their place, the rule of thumb does apply (often, not always, as it is a rule of thumb) but keep looking for behavior you can isolate.


答:
An interface is really a contract.  There is no functionality.  It is up to the implementor to implement.  There is no choice as one must implement the contract.

Abstract classes give implementors choices.  One can choose to have a method that everyone must implement, provide a method with base functionality that one could override, or provide some base functionality that all inheritors can use.

For example:

```<code>public abstract class Person
    {
        /// <summary>
        /// Inheritors must implement a hello
        /// </summary>
        /// <returns>Hello</returns>
        public abstract string SayHello();
        /// <summary>
        /// Inheritors can use base functionality, or override
        /// </summary>
        /// <returns></returns>
        public virtual string SayGoodBye()
        {
            return "Good Bye";
        }
        /// <summary>
        /// Base Functionality that is inherited
        /// </summary>
        public void DoSomething()
        {
            //Do Something Here
        }
    }
</code>```

I would say your rule of thumb could be handled by a base class as well.  In particular since many mammals probably "eat" the same then using a base class may be better than an interface, since one could implement a virtual eat method that most inheritors could use and then the exceptional cases could override.

Now if the defination of "eating" varies widely from animal to animal then perhaps and interface would be better.  This is sometimes a gray area and depends on the individual situation.

Body:
An interface is really a contract.  There is no functionality.  It is up to the implementor to implement.  There is no choice as one must implement the contract.

Abstract classes give implementors choices.  One can choose to have a method that everyone must implement, provide a method with base functionality that one could override, or provide some base functionality that all inheritors can use.

For example:

public abstract class Person
    {
        /// <summary>
        /// Inheritors must implement a hello
        /// </summary>
        /// <returns>Hello</returns>
        public abstract string SayHello();
        /// <summary>
        /// Inheritors can use base functionality, or override
        /// </summary>
        /// <returns></returns>
        public virtual string SayGoodBye()
        {
            return "Good Bye";
        }
        /// <summary>
        /// Base Functionality that is inherited
        /// </summary>
        public void DoSomething()
        {
            //Do Something Here
        }
    }

I would say your rule of thumb could be handled by a base class as well.  In particular since many mammals probably "eat" the same then using a base class may be better than an interface, since one could implement a virtual eat method that most inheritors could use and then the exceptional cases could override.

Now if the defination of "eating" varies widely from animal to animal then perhaps and interface would be better.  This is sometimes a gray area and depends on the individual situation.


答:
It's not really a good rule of thumb because if you want different implementations you could always have an abstract base class with an abstract method.  Every inheritor is guaranteed to have that method, but each defines their own implementation.  Technically you could have an abstract class with nothing but a set of abstract methods, and it'd be basically the same as an interface.

Base classes are useful when you want an actual implementation of some state or behavior that can be used across several classes.  If you find yourself with several classes that have identical fields and methods with identical implementations, you can probably refactor that into a base class.  You just have to be careful in how you inherit.  Every existing field or method in the base class must make sense in the inheritor, especially when it is cast as the base class.

Interfaces are useful when you need to interact with a set of classes in the same way, but you can't predict or don't care about their actual implementation.  Take for example something like a Collection interface.  Lord only knows all the myriad ways someone might decide to implement a collection of items.  Linked list?  Array list?  Stack?  Queue?  This SearchAndReplace method doesn't care, it just needs to be passed something that it can call Add, Remove, and GetEnumerator on.


问:
How accurate is "Business logic should be in a service, not in a model"?
Situation

Earlier this evening I gave an answer to a question on StackOverflow.

The question:

Editing of an existing object should be done in repository layer or in service?

For example if I have a User that has debt. I want to change his debt. Should I do it in UserRepository or in service for example BuyingService by getting an object, editing it and saving it ?

My answer:

You should leave the responsibility of mutating an object to that same object and use the repository to retrieve this object.

Example situation:

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}
```

<p><em>A comment I received:</em></p>

<blockquote>
  <p>Business logic should really be in a service. Not in a model.</p>
</blockquote>

<p><strong>What does the internet say?</strong></p>

<p>So, this got me searching since I've never really (consciously) used a service layer.
I started reading up on the Service Layer pattern and the Unit Of Work pattern but so far I can't say I'm convinced a service layer has to be used.</p>

<p>Take for example this article by Martin Fowler on the anti-pattern of an Anemic Domain Model:</p>

<blockquote>
  <p>There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters. Indeed often these models come with design rules that say that you are not to put any domain logic in the the domain objects. Instead there are a set of service objects which capture all the domain logic. These services live on top of the domain model and use the domain model for data.</p>

  <p>(...)  The logic that should be in a domain object is domain logic - validations, calculations, business rules - whatever you like to call it.</p>
</blockquote>

<p>To me, this seemed exactly what the situation was about: I advocated the manipulation of an object's data by introducing methods inside that class that do just that. However I realize that this should be a given either way, and it probably has more to do with how these methods are invoked (using a repository).</p>

<p>I also had the feeling that in that article (see below), a Service Layer is more considered as a façade that delegates work to the underlying model, than an actual work-intensive layer.</p>

<blockquote>
  <p>Application Layer [his name for Service Layer]: Defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems. The tasks this layer is responsible for are meaningful to the business or necessary for interaction with the application layers of other systems. This layer is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down. It does not have state reflecting the business situation, but it can have state that reflects the progress of a task for the user or the program.</p>
</blockquote>

<p>Which is reinforced here:</p>

<blockquote>
  <p>Service interfaces. Services expose a service interface to which all inbound messages are sent. You can think of a service interface as a façade that exposes the business logic implemented in the application (typically, logic in the business layer) to potential consumers.</p>
</blockquote>

<p>And here:</p>

<blockquote>
  <p>The service layer should be devoid of any application or business logic and should focus primarily on a few concerns. It should wrap Business Layer calls, translate your Domain in a common language that your clients can understand, and handle the communication medium between server and requesting client.</p>
</blockquote>

<p>This is a serious contrast to other resources that talk about the Service Layer:</p>

<blockquote>
  <p>The service layer should consist of classes with methods that are units of work with actions that belong in the same transaction.</p>
</blockquote>

<p>Or the second answer to a question I've already linked:</p>

<blockquote>
  <p>At some point, your application will want some business logic. Also, you might want to validate the input to make sure that there isn't something evil or nonperforming being requested. This logic belongs in your service layer.</p>
</blockquote>

<p><strong>"Solution"?</strong></p>

<p>Following the guidelines in this answer, I came up with the following approach that uses a Service Layer:</p>

<pre class="lang-cs prettyprint-override"><code>class UserController : Controller {
    private UserService _userService;

    public UserController(UserService userService){
        _userService = userService;
    }

    public ActionResult MakeHimPay(string username, int amount) {
        _userService.MakeHimPay(username, amount);
        return RedirectToAction("ShowUserOverview");
    }

    public ActionResult ShowUserOverview() {
        return View();
    }
}

class UserService {
    private IUserRepository _userRepository;

    public UserService(IUserRepository userRepository) {
        _userRepository = userRepository;
    }

    public void MakeHimPay(username, amount) {
        _userRepository.GetUserByName(username).makePayment(amount);
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}
</code>```

Conclusion

All together not much has changed here: code from the controller has moved to the service layer (which is a good thing, so there is an upside to this approach). However this doesn't look like it had anything to do with my original answer.

I realize design patterns are guidelines, not rules set in stone to be implemented whenever possible. Yet I have not found a definitive explanation of the service layer and how it should be regarded.

Is it a means to simply extract logic from the controller and put it inside a service instead?

Is it supposed to form a contract between the controller and the domain?

Should there be a layer between the domain and the service layer?

And, last but not least: following the original comment

Business logic should really be in a service. Not in a model.

Is this correct?

How would I introduce my business logic in a service instead of the model?

答:
In MVC Model is defined as the business logic.  Claiming it should be somewhere else is incorrect unless he is not using MVC. I view service layers as similar to a module system.  It allows you to bundle up a set of related functionality into a nice package.  The internals of that service layer would have a model doing the same work as yours.

The model consists of application data, business rules, logic, and functions.
  http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

ContentLicense: CC BY-SA 4.0


答:
As for your title, I don't think the question makes sense.  The MVC Model consists of data and business logic.  To say logic should be in the Service and not the Model is like saying, "The passenger should sit in the seat, not in the car".

Then again, the term "Model" is an overloaded term.  Perhaps you didn't mean MVC Model but you meant model in the Data Transfer Object (DTO) sense.  AKA an Entity.  This is what Martin Fowler is talking about.

The way I see it, Martin Fowler is speaking of things in an ideal world.  In the real world of Hibernate and JPA (in Java land) the DTOs are a super leaky abstraction.  I'd love to put my business logic in my entity.  It'd make things way cleaner.  The problem is these entities can exist in a managed/cached state that is very difficult to understand and constantly prevents your efforts.  To summarize my opinion: Martin Fowler is recommending the right way, but the ORMs prevent you from doing it.

I think Bob Martin has a more realistic suggestion and he gives it in this video that's not free.  He talks about keeping your DTOs free of logic.  They simply hold the data and transfer it to another layer that's much more object oriented and doesn't use the DTOs directly.  This avoids the leaky abstraction from biting you.  The layer with the DTOs and the DTOs themselves are not OO.  But once you get out of that layer, you get to be as OO as Martin Fowler advocates.

The benefit to this separation is it abstracts away the persistence layer.  You could switch from JPA to JDBC (or vice versa) and none of the business logic would have to change.  It just depends on the DTOs, it doesn't care how those DTOs get populated.

To slightly change topics, you need to consider the fact that SQL databases aren't object oriented.  But ORMs usually have an entity - which is an object - per table.  So right from the start you've already lost a battle.  In my experience, you can never represent the Entity the exact way you want in an object oriented way.

As for "a service", Bob Martin would be against having a class named FooBarService.  That's not object oriented.  What does a service do?  Anything related to FooBars.  It may as well be labeled FooBarUtils.  I think he'd advocate a service layer (a better name would be the business logic layer) but every class in that layer would have a meaningful name.

Title: How accurate is "Business logic should be in a service, not in a model"?

Body:
Situation

Earlier this evening I gave an answer to a question on StackOverflow.

The question:

Editing of an existing object should be done in repository layer or in service?

For example if I have a User that has debt. I want to change his debt. Should I do it in UserRepository or in service for example BuyingService by getting an object, editing it and saving it ?

My answer:

You should leave the responsibility of mutating an object to that same object and use the repository to retrieve this object.

Example situation:

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}
```

<p><em>A comment I received:</em></p>

<blockquote>
  <p>Business logic should really be in a service. Not in a model.</p>
</blockquote>

<p><strong>What does the internet say?</strong></p>

<p>So, this got me searching since I've never really (consciously) used a service layer.
I started reading up on the Service Layer pattern and the Unit Of Work pattern but so far I can't say I'm convinced a service layer has to be used.</p>

<p>Take for example this article by Martin Fowler on the anti-pattern of an Anemic Domain Model:</p>

<blockquote>
  <p>There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters. Indeed often these models come with design rules that say that you are not to put any domain logic in the the domain objects. Instead there are a set of service objects which capture all the domain logic. These services live on top of the domain model and use the domain model for data.</p>

  <p>(...)  The logic that should be in a domain object is domain logic - validations, calculations, business rules - whatever you like to call it.</p>
</blockquote>

<p>To me, this seemed exactly what the situation was about: I advocated the manipulation of an object's data by introducing methods inside that class that do just that. However I realize that this should be a given either way, and it probably has more to do with how these methods are invoked (using a repository).</p>

<p>I also had the feeling that in that article (see below), a Service Layer is more considered as a façade that delegates work to the underlying model, than an actual work-intensive layer.</p>

<blockquote>
  <p>Application Layer [his name for Service Layer]: Defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems. The tasks this layer is responsible for are meaningful to the business or necessary for interaction with the application layers of other systems. This layer is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down. It does not have state reflecting the business situation, but it can have state that reflects the progress of a task for the user or the program.</p>
</blockquote>

<p>Which is reinforced here:</p>

<blockquote>
  <p>Service interfaces. Services expose a service interface to which all inbound messages are sent. You can think of a service interface as a façade that exposes the business logic implemented in the application (typically, logic in the business layer) to potential consumers.</p>
</blockquote>

<p>And here:</p>

<blockquote>
  <p>The service layer should be devoid of any application or business logic and should focus primarily on a few concerns. It should wrap Business Layer calls, translate your Domain in a common language that your clients can understand, and handle the communication medium between server and requesting client.</p>
</blockquote>

<p>This is a serious contrast to other resources that talk about the Service Layer:</p>

<blockquote>
  <p>The service layer should consist of classes with methods that are units of work with actions that belong in the same transaction.</p>
</blockquote>

<p>Or the second answer to a question I've already linked:</p>

<blockquote>
  <p>At some point, your application will want some business logic. Also, you might want to validate the input to make sure that there isn't something evil or nonperforming being requested. This logic belongs in your service layer.</p>
</blockquote>

<p><strong>"Solution"?</strong></p>

<p>Following the guidelines in this answer, I came up with the following approach that uses a Service Layer:</p>

<pre class="lang-cs prettyprint-override"><code>class UserController : Controller {
    private UserService _userService;

    public UserController(UserService userService){
        _userService = userService;
    }

    public ActionResult MakeHimPay(string username, int amount) {
        _userService.MakeHimPay(username, amount);
        return RedirectToAction("ShowUserOverview");
    }

    public ActionResult ShowUserOverview() {
        return View();
    }
}

class UserService {
    private IUserRepository _userRepository;

    public UserService(IUserRepository userRepository) {
        _userRepository = userRepository;
    }

    public void MakeHimPay(username, amount) {
        _userRepository.GetUserByName(username).makePayment(amount);
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}
</code>```

Conclusion

All together not much has changed here: code from the controller has moved to the service layer (which is a good thing, so there is an upside to this approach). However this doesn't look like it had anything to do with my original answer.

I realize design patterns are guidelines, not rules set in stone to be implemented whenever possible. Yet I have not found a definitive explanation of the service layer and how it should be regarded.

Is it a means to simply extract logic from the controller and put it inside a service instead?

Is it supposed to form a contract between the controller and the domain?

Should there be a layer between the domain and the service layer?

And, last but not least: following the original comment

Business logic should really be in a service. Not in a model.

Is this correct?

How would I introduce my business logic in a service instead of the model?


答:
The problem with your friend's simplification is that determining whether or not a method will ever need to change is exceptionally difficult. It is better to use a rule that speaks to the mentality behind superclasses and interfaces.

Instead of figuring out what you should do by looking to what you think the functionality is, look to the hierarchy you are trying to create.

Here is how a professor of mine taught the difference:

Superclasses should be is a and interfaces are acts like or is. So a dog is a mammal and acts like an eater. This would tell us that mammal should be a class and eater should be an interface. An example of is would be The cake is eatable or The book is writable (making both eatable and writable interfaces).

Using a methodology like this is reasonably simple and easy, and causes you to code to the structure and concepts rather than to what you think the code will do. This makes maintenance easier, the code more readable, and the design simpler to create.

Regardless of what the the code might actually say, if you use a method like this you could come back five years from now and use the same method to retrace your steps and easily figure out how your program was designed and how it interacts.

Just my two cents.


问:
HTTP resource bundling/streaming practice
Our SPA (plain HTML and Javascript) makes use of huge volume of javascript and other resources that are downloaded via XHR. Given the sheer number of components and browser simultaneous request limits, we're thinking for ways to deliver our resources in a more efficient manner.

A method we're considering is bundling several resources that logically form a coherent group into a single file; thus reducing down to only one XHR (per group). Furthermore to make it more responsive, we'd like to constantly inspect the partial responseText during the LOADING state, determining if a usable chunk (atomic resource) has already been downloaded, and make it available for deserialization/processing even before the XHR is DONE. (a stream-like experience)

We're thinking surely somebody else would've considered roughly the same approach before, but haven't really come across any library/framework or container file format that is suitable for our scenario. Anybody else know of something similar?

答:
After studying a little about the Matroska .mkv specification, I ultimately came up with a simple custom file container format that is just enough to describe the various files contained within and their byte boundaries in the greater file.

A client-side Javascript component that uses XHR can progressively check the responseText on each progress event and attempt to extract out the segment that represents the next file in line. On availability of a file, an event (callback) will be triggered for the upper application to consume the file contents while the XHR is still midstream.


问:
Finish feature reverted commits from develop
I am using git as a version control system, and using git-flow as the branching model. I started a feature branch some weeks ago in order to maintain the system in a clean state while developping that feature. The main development continued on the develop branch, and changes from develop were merged periodically into the feature, to keep it up to date as much as possible.

However came the time where the feature was finished, and I used git-flow's finish feature to merge the feature back into develop. The merge was successfully done, but then I found out that some of the commits I made in develop were reverted by the merge commit!

Nowhere in develop or in the feature branch were these changes reverted, I can't see any commit that overwrote them. I just can't find anything. The only theory I have for the moment is that git is failing on me, but that would be extremely unlikely. Maybe I did some kind of wrong manipulation that made this situation come true?

I can trace back in the history when the commit was made. I can see that the changes from that commit were reverted by the merge commit. Nowhere in the branch I see a commit that reverts those changes. Yet they were reverted.

How is this even possible?

答:
I had also same problem, it is more safe to checkout a new temporary branch from your main branch, merge and test this temporary branch and merge, if you are sure you did not miss something, merge to your main branch.

If you have a working version of your code, convert it to a new release, or a branch with a descriptive tag and do not touch it, and go on with development branch.

And avoid direct merging as far as possible, instead use rebase command, before merging. it is like stash command.


问:
How do you name your private variables in C#?
What is the best practice, most commonly accepted naming conventions for private variables in C#?

private int myInteger;

private int MyInteger;

private int mMyInteger;

private int _myInteger;

private int _MyInteger;

Mysterious other option

Which do you use and why?  (My company is fairly new to C# and I would like to pick the most "industry accepted" method to try and get into our coding standard.)

答:
I do option #4 because that's what the SSCLI looks like, but honestly I don't care that much on naming of private variable. Public is a different story.

BTW you forgot m_MyInteger


问:
What Functional features are worth a little OOP confusion for the benefits they bring?
After learning functional programming in Haskell and F#, the OOP paradigm seems ass-backwards with classes, interfaces, objects.  Which aspects of FP can I bring to work that my co-workers can understand?  Are any FP styles worth talking to my boss about retraining my team so that we can use them?

Possible aspects of FP:

Immutability

Partial Application and Currying

First Class Functions (function pointers / Functional Objects / Strategy Pattern)

Lazy Evaluation (and Monads)

Pure Functions (no side effects)

Expressions (vs. Statements - each line of code produces a value instead of, or in addition to causing side effects)

Recursion

Pattern Matching

Is it a free-for-all where we can do whatever the programming language supports to the limit that language supports it?  Or is there a better guideline?

答:
As a programmer I think you should never stop learning. That said, it's very interesting that learning FP is tainting your OOP skills. I tend to think of learning OOP as learning how to ride a bike; you never forget how to do it.

As I learned the ins and outs of FP, I found myself thinking more mathematically and gained a better perspective of the means in which I write software. That's my personal experience.

As you gain more experience, core programming concepts will be much harder to lose. So I suggest you take it easy on the FP until OOP concepts are totally solidified in your mind. FP is a definite paradigm shift. Good luck!


问:
Should package structure closely resemble class hierarchy?
Pretty simple question.  Should package structure closely resemble class hierarchy?  If so, how closely?  Why or why not?

For instance, let's say you've got class A and class B, plus class AFactory and class BFactory.  You put class A and class B in the package com.something.elements, and you put AFactory and BFactory in com.something.elements.factories.  AFactory and BFactory would be further down the hierarchy package-wise, but they'd be further up class-wise.  Is this sort of thing a good idea or a bad idea?

答:
According to Uncle Bob, classes should be grouped together into packages if they change together.  Presumably, if class A changes, then class AFactory would need to change as well, but class BFactory would not.  So, if A and B are unrelated, then each should be in a separate package together with the corresponding factory.  On the other hand, if there is a dependency between A and B that forces you to change one when you change the other, then the two classes and the two factories should all be in the same package.

If you follow this pattern, then you should be able to build each package into a separate library, independently of the other one.


答:
Functional programming is a different paradigm from Object-Oriented programming (a different mindset, and a different way of thinking about programs).  You have begun to realize that here is more than one way (object-oriented) to think about problems and their solutions.  There are others (procedural and generic programming come to mind).  How you react to this new knowledge, whether you accept and integrate these new tools and approaches into your skill set, will determine whether you grow and become a more complete, skilled developer.

We are all trained to handle and are comfortable with a certain level of complexity.  I like to call this a person's hrair limit (from Watership Down, how high can you count).  It is a great thing to expand your mind, your ability to consider more options, and have more tools to approach and solve problems.  But it is a change, and it pulls you out of your comfort zone.

One problem you may encounter is that you will become less content to follow the "everything is an object" crowd.  You may have to develop patience as you work with people who may not understand (or want to understand) why a functional approach to software development works well for certain problems.  Just as a generic programming approach works well for certain problems.

Good Luck!

Title: What Functional features are worth a little OOP confusion for the benefits they bring?

Body:
After learning functional programming in Haskell and F#, the OOP paradigm seems ass-backwards with classes, interfaces, objects.  Which aspects of FP can I bring to work that my co-workers can understand?  Are any FP styles worth talking to my boss about retraining my team so that we can use them?

Possible aspects of FP:

Immutability

Partial Application and Currying

First Class Functions (function pointers / Functional Objects / Strategy Pattern)

Lazy Evaluation (and Monads)

Pure Functions (no side effects)

Expressions (vs. Statements - each line of code produces a value instead of, or in addition to causing side effects)

Recursion

Pattern Matching

Is it a free-for-all where we can do whatever the programming language supports to the limit that language supports it?  Or is there a better guideline?


问:
How do I cleanly design a central render/animation loop?
I'm learning some graphics programming, and am in the midst of my first such project of any substance. But, I am really struggling at the moment with how to architect it cleanly. Let me explain.

To display complicated graphics in my current language of choice (JavaScript -- have you heard of it?), you have to draw graphical content onto a <canvas> element. And to do animation, you must clear the <canvas> after every frame (unless you want previous graphics to remain).

Thus, most canvas-related JavaScript demos I've seen have a function like this:

```<code>function render() {
   clearCanvas();
   // draw stuff here
   requestAnimationFrame(render);
}
</code>```

render, as you may surmise, encapsulates the drawing of a single frame. What a single frame contains at a specific point in time, well... that is determined by the program state. So, in order for my program to do its thing, I just need to look at the state, and decide what to render. Right?

Right. But that is more complicated than it seems.

My program is called "Critter Clicker". In my program, you see several cute critters bouncing around the screen. Clicking on one of them agitates it, making it bounce around even more. There is also a start screen, which says "Click to start!" prior to the critters being displayed.

Here are a few of the objects I'm working with in my program:

```<code>StartScreenView  // represents the start screen
CritterTubView   // represents the area in which the critters live
CritterList      // a collection of all the critters
Critter          // a single critter model
CritterView      // view of a single critter
</code>```

Nothing too egregious with this, I think. Yet, when I set out to flesh out my render function, I get stuck, because everything I write seems utterly ugly and reminiscent of a certain popular Italian dish. Here are a couple of approaches I've attempted, with my internal thought process included, and unrelated bits excluded for clarity.

Approach 1: "It's conditions all the way down"

```<code>// "I'll just write the program as I think it, one frame at a time."

if (assetsLoaded) {
  if (userClickedToStart) {
    if (critterTubDisplayed) {
      if (crittersDisplayed) {
        forEach(crittersList, function(c) {
          if (c.wasClickedRecently) {
             c.getAgitated();
          }
        });
      } else {
        displayCritters();
      }
    } else {
      displayCritterTub();
    }
  } else {
    displayStartScreen();
  }
}
</code>```

That's a very much simplified example. Yet even with only a fraction of all the rendering conditions visible, render is already starting to get out of hand. So, I dispense with that and try another idea:

Approach 2: Under the Rug

```<code>// "Each view object shall be responsible for its own rendering.
// "I'll pass each object the program state, and each can render itself."

startScreen.render(state);
critterTub.render(state);
critterList.render(state);
</code>```

In this setup, I've essentially just pushed those crazy nested conditions to a deeper level in the code, hiding them from view. In other words, startScreen.render would check state to see if it needed actually to be drawn or not, and take the correct action. But this seems more like it only solves a code-aesthetic problem.

The third and final approach I'm considering that I'll share is the idea that I could invent my own "wheel" to take care of this. I'm envisioning a function that takes a data structure that defines what should happen at any given point in the render call -- revealing the conditions and dependencies as a kind of tree.

Approach 3: Mad Scientist

```<code>renderTree({
  phases: ['startScreen', 'critterTub', 'endCredits'],
  dependencies: {
    startScreen: ['assetsLoaded'],
    critterTub: ['startScreenClicked'],
    critterList ['critterTubDisplayed']
    // etc.
  },
  exclusions: {
    startScreen: ['startScreenClicked'],
    // etc.
  }
});
</code>```

That seems kind of cool. I'm not exactly sure how it would actually work, but I can see it being a rather nifty way to express things, especially if I flex some of JavaScript's events.

In any case, I'm a little bit stumped because I don't see an obvious way to do this. If you couldn't tell, I'm coming to this from the web development world, and finding that doing animation is a bit more exotic than arranging an MVC application for handling simple requests -> responses.

What is the clean, established solution to this common-I-would-think problem?

答:
The concept of a "scene" might be helpful. A scene could be an initial menu, a level among many levels, or the credits at the end of your game. Each scene has its own behaviors, state, and render-able entities. Some state may be shared between scenes (scores, character upgrades, etc), but most state is specific to a scene. Abstracting by scene makes a game easier to think about and is also handy for keeping system resources to a minimum - you only load the resources you need for the current scene. In pseudo code:

```<code>currentScene = nothing

game-start:
    currentScene = load-start-menu()

game-loop:
    currentScene.update()
    currentScene.render()

menu-start-button-clicked:
    currentScene = load-level1()
</code>```

Inside each scene, you have a collection of game entities. For simplicity, I'll show simple containers. In reality, you may want to split conceptual entities into a data-only model and a render-able view. Scenes may also delegate user interaction.

```<code>definition Critter:
    isAgitated = false
    x = get-appropriate-starting-x()
    y = get-appropriate-starting-y()

    update:
        if isAgitated:
            x = some-random-move(x)
            y = some-random-move(y)

    render:
        draw(image or whatever, x, y)

definition Level1:
    entities = new collection()

    init:
        for 1 to some-number:
            entities.add(new Critter)
        entities.add(new CritterTub) // definition not shown

    update:
        for each entity in entities:
            entity.update()

    render:
        for each entity in entities:
            entity.render()

    mouse-click(x,y):
        entity = find-entity(entities, x, y)
        if entity is Critter:
            entity.isAgitated = true
</code>```

There are many variations: Your game engine may allow entities to receive user actions directly. As mentioned earlier, your entities may only contain data and some other component is responsible for rendering. Your game may be more functional versus object-oriented, ex: render(entity) versus entity.render()

Once you've defined your scene, there are many interesting problems to solve: which entities are off-screen and shouldn't be rendered, in which order should entities be rendered, and how can I decide these things quickly? Take a look at scene graphs for more info. Gamerendering.com provides an overview of several techniques for scene management from simple to advanced.

For more information on the scene concept, the following offer high-level explanations:

Object-Oriented Game Programming: The Scene System

HTML5 Game Programming with Enchant.js

Simplify Flow Between Game Screens with the "Scene System"

Body:
The concept of a "scene" might be helpful. A scene could be an initial menu, a level among many levels, or the credits at the end of your game. Each scene has its own behaviors, state, and render-able entities. Some state may be shared between scenes (scores, character upgrades, etc), but most state is specific to a scene. Abstracting by scene makes a game easier to think about and is also handy for keeping system resources to a minimum - you only load the resources you need for the current scene. In pseudo code:

currentScene = nothing

game-start:
    currentScene = load-start-menu()

game-loop:
    currentScene.update()
    currentScene.render()

menu-start-button-clicked:
    currentScene = load-level1()

Inside each scene, you have a collection of game entities. For simplicity, I'll show simple containers. In reality, you may want to split conceptual entities into a data-only model and a render-able view. Scenes may also delegate user interaction.

definition Critter:
    isAgitated = false
    x = get-appropriate-starting-x()
    y = get-appropriate-starting-y()

    update:
        if isAgitated:
            x = some-random-move(x)
            y = some-random-move(y)

    render:
        draw(image or whatever, x, y)

definition Level1:
    entities = new collection()

    init:
        for 1 to some-number:
            entities.add(new Critter)
        entities.add(new CritterTub) // definition not shown

    update:
        for each entity in entities:
            entity.update()

    render:
        for each entity in entities:
            entity.render()

    mouse-click(x,y):
        entity = find-entity(entities, x, y)
        if entity is Critter:
            entity.isAgitated = true

There are many variations: Your game engine may allow entities to receive user actions directly. As mentioned earlier, your entities may only contain data and some other component is responsible for rendering. Your game may be more functional versus object-oriented, ex: render(entity) versus entity.render()

Once you've defined your scene, there are many interesting problems to solve: which entities are off-screen and shouldn't be rendered, in which order should entities be rendered, and how can I decide these things quickly? Take a look at scene graphs for more info. Gamerendering.com provides an overview of several techniques for scene management from simple to advanced.

For more information on the scene concept, the following offer high-level explanations:

Object-Oriented Game Programming: The Scene System

HTML5 Game Programming with Enchant.js

Simplify Flow Between Game Screens with the "Scene System"


答:
In addition to functional programming and object oriented programming, there's also declarative programming (SQL, XQuery). Learning each style helps you gain new insights, and you'll learn to pick the right tool for the job.

But yeah, it can be very frustrating to write code in a language, and know that if you were using something else, you could be way more productive for a particular problem domain. However, even if you're using a language like Java, it is possible to apply concepts from FP to your Java code, albeit in roundabout ways. The Guava framework for instance does some of this.


问:
How do we keep dependent data structures up to date?
Suppose you have a parse tree, an abstract syntax tree, and a control flow graph, each one logically derived from the one before. In principle it is easy to construct each graph given the parse tree, but how can we manage the complexity of updating the graphs when the parse tree is modified? We know exactly how the tree has been modified, but how can the change be propagated to the other trees in a way that doesn't become difficult to manage?

Naturally the dependent graph can be updated by simply reconstructing it from scratch every time the first graph changes, but then there would be no way of knowing the details of the changes in the dependent graph.

I currently have four ways to attempt to solve this problem, but each one has difficulties.

Nodes of the dependent tree each observe the relevant nodes of the original tree, updating themselves and the observer lists of original tree nodes as necessary. The conceptual complexity of this can become daunting.

Each node of the original tree has a list of the dependent tree nodes that specifically depend upon it, and when the node changes it sets a flag on the dependent nodes to mark them as dirty, including the parents of the dependent nodes all the way down to the root. After each change we run an algorithm that is much like the algorithm for constructing the dependent graph from scratch, but it skips over any clean node and reconstructs each dirty node, keeping track of whether the reconstructed node is actually different from the dirty node. This can also get tricky.

We can represent the logical connection between the original graph and the dependent graph as a data structure, like a list of constraints, perhaps designed using a declarative language. When the original graph changes we need only scan the list to discover which constraints are violated and how the dependent tree needs to change to correct the violation, all encoded as data.

We can reconstruct the dependent graph from scratch as though there were no existing dependent graph, and then compare the existing graph and the new graph to discover how it has changed. I'm sure this is the easiest way because I know there are algorithms available for detecting differences, but they are all quite computationally expensive and in principle it seems unnecessary so I'm deliberately avoiding this option.

What is the right way to deal with these sorts of problems? Surely there must be a design pattern that makes this whole thing almost easy. It would be nice to have a good solution for every problem of this general description. Does this class of problem have a name?

Let me elaborate on the troubles that this problem causes. This issue pops up in various places, whenever two parts of a project operate on graphs, with each graph being a different representation of the same thing that changes while the software is running. It's like making an adapter for an interface, but instead of wrapping a single object or a fixed number of objects, we need to wrap an entire graph of arbitrary size.

Every time I try this I end up with a confusing unmaintainable mess. The control flow of observers can be difficult to follow when it gets complicated, and the algorithm for converting one graph to another is usually tricky enough to follow when its laid out plainly and not spread across multiple classes. The problem is that there seems to be no way to use just a plain, straight-forward graph conversion algorithm when the original graph is changing.

Naturally we can't just use an ordinary graph conversion algorithm directly because that can't respond to changes in any way other than starting from scratch, so what are the alternatives? Perhaps the algorithm could be written in a continuation-passing style where each step of the algorithm is represented as an object with a method for each type of node in the original graph, like a visitor. Then the algorithm can be assembled by composing various simple visitors together.

Another example: Suppose you have a GUI that is laid out like you might in Java Swing, using JPanels and layout managers. You can simplify that process by using nested JPanels in place of complex layout managers, so you end up with a tree of various containers that includes nodes that exist only for layout purposes and are otherwise meaningless. Now suppose that the same tree that is used to generate your GUI is also used in another part of your application, but instead of laying the tree out graphically it is working with a library that will generate an abstract representation tree as a system of folders. In order to use this library, we need to have a version of the tree that doesn't have the layout nodes; the layout nodes need to be flattened into their parent nodes, but the library still needs to be notified each time the tree changes as though the two versions of the tree were a single data structure.

Another way to look at it: The very concept of working with mutable trees violates the Law of Demeter. It wouldn't really be a violation of the law if the tree were a value as parse trees and syntax trees normally are, but in that case there would be no problem since nothing would need to be kept up-to-date. So then this problem exists as a direct result of violating the Law of Demeter, but how do you avoid that in general when your domain seems to be about manipulating trees or graphs?

The Composite pattern is a wonderful tool for turning a graph into a single object and obeying the Law of Demeter. Is it possible to use the Composite pattern to effectively turn one kind of tree into another? Can you make a Composite parse tree so that it acts like an abstract syntax tree and even a control flow graph? Is there a way to do it without violating the single responsibility principle? The Composite pattern tends to cause classes to absorb every responsibility that they touch, but perhaps it could be combined with the Strategy pattern somehow.

答:
You mentioned you know exactly how the tree was modified, would you know when ?

How about experimenting with HashTrees or Hash chains ( Merkle Tree) or generally the concept of Error Detection.
If the trees are huge you could divide say, the first graph into say N/2 or root N zones and assign hashes/checksums to those zones. The dependent trees would maintain its own set of N/2 or root N zones which are dependent on the first trees' zones. When changes are detected in the first tree update the corresponding nodes in the dependent tree using simple lookup (as u know what has changed and subsequently the hash/checksum for that zone).


答:
The answer is that it depends on the use case. But in most generic scenarios, I would adhere to business logic laying in the service layer. The example that you have provided is a really simple one. However once you start thinking of decoupled systems or services and adding transactional behaviour on top of it you really want it to happen as part of the service layer.

The sources you have quoted for service layer being devoid of any business logic introduces another layer which is the business layer. In many scenarios the service layer and business layer are compressed into one. It really depends on how you want to design your system. You can get the job done in three layers and keep decorating on and adding noise.

What you can ideally do is model services which encompass business logic to work on domain models to persist state.  You should try to decouple services as much as possible.


问:
Web application / Domain model integration using JSON capable DTOs
I'm a bit confused about architectural choices for the web-applications/java/python world. For c/c++ world the available (open source) choices to implement web applications is pretty limited to zero, involving java or python the choices explode to a,- hard to sort out -, mess of available 'frameworks' and application approaches. I want to sort out a clean MVC model, where the M stands for a fully blown (POCO, POJO driven) domain model (according M.Fowler's EAA pattern) using a mature OO language (Java,C++) for implementation.

The background is: I have a system with certain hardware components (that introduce system immanent active behavior) and a configuration database for system meta and HW-components configuration data (these are even usually self contained, since the HW-components are capable to persist their configuration data anyway).

For realization of the configuration/status data exchange protocol with the HW-components we have chosen the Google Protobuf format, which works well for the directly wired communication with these components.

This protocol is already used successfully with a Java based GUI application via TCP/IP connection to the main system controlling HW-component. This application has some drawbacks and design flaws for historical reasons.

Now we want to develop an abstract model (domain model) for configuration and monitoring those HW-components, that represents a more use case oriented view to the overall system behavior. I have the feeling that a plain Java class model would fit best for this (c++ implementation seems to have too much implementation/integration overhead with viable language-bridge interfaces).

Google Protobuf message definitions could still serve well to describe DTO objects used to interact with a domain model API. But integrating Google Protobuf messages client side for e.g. data binding in the current view doesn't seem to be a good choice. I'm thinking about some extra serialization features, e.g. for JSON based data exchange with the views/controllers.

Most lightweight solutions seem to involve a python based presentation layer using WSGI or JSON based data transfer (I'm at least not sure to be fully informed about this).

Can someone give good advice about best practices or easy to integrate frameworks for such case?

UPDATE:

According to my recent research and comments of colleagues I've noticed that using Java (and some JVM) might not be the preferable choice for integration with python on a limited linux system as we have (running on ARM9 with hard to discuss memory and MCU costs), but C/C++ modules would do well for this (since this forms the native interface to python extensions, doesn't it?).

E.g. a pyramid based solution seems to provide a lightweight framework, that allows to integrate a domain model using an appropriate python facade. Protobuf also provides python class generation support, does someone have experience with integrating protobuf messages as DTO's with python?

I can imagine to provide a domain model from an appropriate C/C++ API (though I still think it's more efforts and higher skill requirements for the involved developers to do with these languages). Still I'm searching for a good approach that supports such architecture. I'll appreciate any pointers!

答:
It is hard to understand your exact question but generally speaking JSON would be a good choice to integrate with the client side in Java. You can serialize POJOs using jackson. But better yet you can deserialize proto buffers to JSON.

In terms of a framework for Java, I would recommend Spring MVC. You need an instance of an application server (tomcat, jetty etc.) i.e. a jvm in which to run. It has great RESTful support and provides to and fro conversion from POJO's to JSON by simply including jackson in the classpath.


问:
Why not expose a primary key
In my education I have been told that it is a flawed idea to expose actual primary keys (not only DB keys, but all primary accessors) to the user.

I always thought it to be a security problem (because an attacker could attempt to read stuff not their own).

Now I have to check if the user is allowed to access anyway, so is there a different reason behind it?

Also, as my users have to access the data anyway I will need to have a public key for the outside world somewhere in between. Now that public key has the same problems as the primary key, doesn't it?

There has been the request of an example on why do that anyway, so here is one.
Keep in mind that the question is meant to be about the principle itself not only if it applies in this example. Answers addressing other situations are explicitly welcome.

Application (Web, Mobile) that handles activity, has multiple UIs and at least one automated API for intersystem communication (e.G. the accounting department wants to know how much to charge the customer based on what has been done).
The Application has multiple customers so separation of their data (logically, the data is stored in the same DB) is a must have of the system. Each request will be checked for validity no matter what.

Activity is very fine granular so it is together in some container object, lets call it "Task".

Three usecases:

User A wants to send User B to some Task so he sends him a link (HTTP) to get some Activity done there.

User B has to go outside the building so he opens the Task on his mobile device.

Accounting wants to charge the customer for the Task, but uses a third party accounting system that automatically loads the Task / Activity by some code that refers to the REST - API of the Application

Each of the usecases requires (or gets easier if) the agent to have some addressable identifier for the Task and the Activity.

答:
Also, as my users have to access the data anyway I will need to have a public key for the outside world somewhere in between.

Exactly. Take the stateless HTTP, who would otherwise not know what resource it should request: it exposes your question's ID 218306 in the URL. Perhaps you're actually wondering whether an exposed identifier may be predictable?

The only places where I've heard a negative answer to that, used the rationale: "But they can change the ID in the URL!". So they used GUIDs instead of implementing proper authorization.

I can imagine one situation where you don't want your identifiers to be predictable: resource harvesting. If you have an site that publicly hosts certain resources others may be interesting in, and you host them like /images/n.jpg or /videos/n.mp4 where n just is an incrementing number, anyone looking at traffic to and from your website can harvest all your resources.

So, to directly answer your question: no, it is not bad to directly "expose" identifiers that only have meaning to your program, usually it is even required for your program to succesfully operate.

Title: Why not expose a primary key


问:
WCF or ASMX WebService
I have been asked to create a web service that communicates with Auth.NET CIM and Shipsurance API.  My web service will be used by multiple applications (one a desktop and another a web application).

I am confused whether I should build a WCF or an asmx web service.

Auth.NET CIM and Shipsurance API have asmx web services which I would be calling in my newly created web service. So is WCF the right approach or can I stay with asmx?

答:
You can go for WCF. If you read the differences between wcf and webservices you may understand the necessity of wcf over webservices.

WCF offers duplex communication with bindings and improved security. you can configure your data transfer mode and security. I suggest you to read WCF Bidnings.

First of all, wcf is webservice. you can either create a WCF Project library(creates a *.dll) or WCF service application (Appication that you can host).

You can communicate with WCF to a old webservices. WCF has better features and security which you may want to consider before going to web services

Title: WCF or ASMX WebService


答:
I think that the type is not a property of the Address, it's a property of the connection between a User and an Address.

An Address normally represents a specific location in the world, a type would be connected to the use that a User makes of the Address.

An Address might even be used for both Home and Business for some Users. Or be the Home of one User and the Workplace of another User.

So:

The Address should be a Value type.

It shouldn't be connected to the AddressType

For me it would depend on how many addresses the User is expected to have, and how static will the types be.

A kind of Map would be more efficient...

Title: How to model an address type in DDD?


答:
One reason I've found, in the fullness of time I've seen end users request that their identifier means something (like having a prefix, or an indicator of the year it was incepted). Changing a PK is hard, but a surrogate is much easier.

Your primary key will likely be something you want your database indexing on for performance reasons, and you may in time for technical reason change it for example from a number to a guid... you just don't know what reasons new technologies or knowledge might guide you down. Your pk is your technical item of data, the public key is for end users consumption.

Title: Why not expose a primary key

Body:
In my education I have been told that it is a flawed idea to expose actual primary keys (not only DB keys, but all primary accessors) to the user.

I always thought it to be a security problem (because an attacker could attempt to read stuff not their own).

Now I have to check if the user is allowed to access anyway, so is there a different reason behind it?

Also, as my users have to access the data anyway I will need to have a public key for the outside world somewhere in between. Now that public key has the same problems as the primary key, doesn't it?

There has been the request of an example on why do that anyway, so here is one.
Keep in mind that the question is meant to be about the principle itself not only if it applies in this example. Answers addressing other situations are explicitly welcome.

Application (Web, Mobile) that handles activity, has multiple UIs and at least one automated API for intersystem communication (e.G. the accounting department wants to know how much to charge the customer based on what has been done).
The Application has multiple customers so separation of their data (logically, the data is stored in the same DB) is a must have of the system. Each request will be checked for validity no matter what.

Activity is very fine granular so it is together in some container object, lets call it "Task".

Three usecases:

User A wants to send User B to some Task so he sends him a link (HTTP) to get some Activity done there.

User B has to go outside the building so he opens the Task on his mobile device.

Accounting wants to charge the customer for the Task, but uses a third party accounting system that automatically loads the Task / Activity by some code that refers to the REST - API of the Application

Each of the usecases requires (or gets easier if) the agent to have some addressable identifier for the Task and the Activity.