答:
You could push both makeASandwich and contactAliens into the base class and then implement them with dummy implementations. Since the return types/arguments can't be resolved to a common base class.

```<code>class Sub1 extends Base{
    Sandwich makeASandwich(Ingredients i){
        //Normal implementation
    }
    boolean contactAliens(Frequency onFrequency){
        return false;
    }
 }
class Sub2 extends Base{
    Sandwich makeASandwich(Ingredients i){
        return null;
    }
    boolean contactAliens(Frequency onFrequency){
       // normal implementation
    }
 }
</code>```

There are obvious downsides to this sort of thing, like what that means for the contract of the method and what you can and cannot infer about the context of the result. You can't think since I failed to make a sandwich the ingredients got used up in the attempt etc.

Title: Is it okay to have objects that cast themselves, even if it pollutes the API of their subclasses?

Body:
I have a base class, Base.  It has two subclasses, Sub1 and Sub2.  Each subclass has some additional methods.  For example, Sub1 has Sandwich makeASandwich(Ingredients... ingredients), and Sub2 has boolean contactAliens(Frequency onFrequency).

Since these methods take different parameters and do entirely different things, they're completely incompatible, and I can't just use polymorphism to solve this problem.

Base provides most of the functionality, and I have a large collection of Base objects.  However, all Base objects are either a Sub1 or a Sub2, and sometimes I need to know which they are.

It seems like a bad idea to do the following:

```<code>for (Base base : bases) {
    if (base instanceof Sub1) {
        ((Sub1) base).makeASandwich(getRandomIngredients());
        // ... etc.
    } else { // must be Sub2
        ((Sub2) base).contactAliens(getFrequency());
        // ... etc.
    }
}
</code>```

So I came up with a strategy to avoid this without casting.  Base now has these methods:

```<code>boolean isSub1();
Sub1 asSub1();
Sub2 asSub2();
</code>```

And of course, Sub1 implements these methods as

```<code>boolean isSub1() { return true; }
Sub1 asSub1();   { return this; }
Sub2 asSub2();   { throw new IllegalStateException(); }
</code>```

And Sub2 implements them in the opposite way.

Unfortunately, now Sub1 and Sub2 have these methods in their own API.  So I can do this, for example, on Sub1.

```<code>/** no need to use this if object is known to be Sub1 */
@Deprecated
boolean isSub1() { return true; }

/** no need to use this if object is known to be Sub1 */
@Deprecated
Sub1 asSub1();   { return this; }

/** no need to use this if object is known to be Sub1 */
@Deprecated
Sub2 asSub2();   { throw new IllegalStateException(); }
</code>```

This way, if the object is known to be only a Base, these methods are un-deprecated, and can be used to "cast" itself to a different type so I can invoke the subclass's methods on it.  This seems elegant to me in a way, but on the other hand, I'm kind of abusing Deprecated annotations as a way to "remove" methods from a class.

Since a Sub1 instance really is a Base, it does make sense to use inheritance rather than encapsulation.  Is what I'm doing good?  Is there a better way to solve this problem?

Body:
You could push both makeASandwich and contactAliens into the base class and then implement them with dummy implementations. Since the return types/arguments can't be resolved to a common base class.

class Sub1 extends Base{
    Sandwich makeASandwich(Ingredients i){
        //Normal implementation
    }
    boolean contactAliens(Frequency onFrequency){
        return false;
    }
 }
class Sub2 extends Base{
    Sandwich makeASandwich(Ingredients i){
        return null;
    }
    boolean contactAliens(Frequency onFrequency){
       // normal implementation
    }
 }

There are obvious downsides to this sort of thing, like what that means for the contract of the method and what you can and cannot infer about the context of the result. You can't think since I failed to make a sandwich the ingredients got used up in the attempt etc.


问:
Is it okay to have objects that cast themselves, even if it pollutes the API of their subclasses?
I have a base class, Base.  It has two subclasses, Sub1 and Sub2.  Each subclass has some additional methods.  For example, Sub1 has Sandwich makeASandwich(Ingredients... ingredients), and Sub2 has boolean contactAliens(Frequency onFrequency).

Since these methods take different parameters and do entirely different things, they're completely incompatible, and I can't just use polymorphism to solve this problem.

Base provides most of the functionality, and I have a large collection of Base objects.  However, all Base objects are either a Sub1 or a Sub2, and sometimes I need to know which they are.

It seems like a bad idea to do the following:

```<code>for (Base base : bases) {
    if (base instanceof Sub1) {
        ((Sub1) base).makeASandwich(getRandomIngredients());
        // ... etc.
    } else { // must be Sub2
        ((Sub2) base).contactAliens(getFrequency());
        // ... etc.
    }
}
</code>```

So I came up with a strategy to avoid this without casting.  Base now has these methods:

```<code>boolean isSub1();
Sub1 asSub1();
Sub2 asSub2();
</code>```

And of course, Sub1 implements these methods as

```<code>boolean isSub1() { return true; }
Sub1 asSub1();   { return this; }
Sub2 asSub2();   { throw new IllegalStateException(); }
</code>```

And Sub2 implements them in the opposite way.

Unfortunately, now Sub1 and Sub2 have these methods in their own API.  So I can do this, for example, on Sub1.

```<code>/** no need to use this if object is known to be Sub1 */
@Deprecated
boolean isSub1() { return true; }

/** no need to use this if object is known to be Sub1 */
@Deprecated
Sub1 asSub1();   { return this; }

/** no need to use this if object is known to be Sub1 */
@Deprecated
Sub2 asSub2();   { throw new IllegalStateException(); }
</code>```

This way, if the object is known to be only a Base, these methods are un-deprecated, and can be used to "cast" itself to a different type so I can invoke the subclass's methods on it.  This seems elegant to me in a way, but on the other hand, I'm kind of abusing Deprecated annotations as a way to "remove" methods from a class.

Since a Sub1 instance really is a Base, it does make sense to use inheritance rather than encapsulation.  Is what I'm doing good?  Is there a better way to solve this problem?

答:
What you are doing is perfectly legitimate.  Do not pay attention to the naysayers who merely reiterate dogma because they read it in some books.  Dogma has no place in engineering.

I have employed the same mechanism a couple of times, and I can say with confidence that the java runtime could have also done the same thing in at least one place that I can think of, thus improving performance, usability, and readability of code that uses it.

Take for example java.lang.reflect.Member, which is the base of java.lang.reflect.Field and java.lang.reflect.Method.  (The actual hierarchy is a bit more complicated than that, but that's irrelevant.)  Fields and methods are vastly different animals: one has a value that you can get or set, while the other has no such thing, but it can be invoked with a number of parameters and it may return a value. So, fields and methods are both members, but the things you can do with them are about as different from each other as making sandwiches vs. contacting aliens.

Now, when writing code that uses reflection we very often have a Member in our hands, and we know that it is either a Method or a Field, (or, rarely, something else,) and yet we have to do all the tedious instanceof to figure out precisely what it is and then we have to cast it to get a proper reference to it.  (And this is not only tedious, but it also does not perform very well.) The Method class could have very easily implemented the pattern that you are describing, thus making the life of thousands of programmers easier.

Of course, this technique is only viable in small, well-defined hierarchies of closely coupled classes that you have (and will always have) source-level control of: you don't want to be doing such a thing if your class hierarchy is liable to be extended by people who are not at liberty to refactor the base class.

Here is how what I have done differs from what you have done:

The base class provides a default implementation for the entire asDerivedClass() family of methods, having each one of them return null.

Each derived class only overrides one of the asDerivedClass() methods, returning this instead of null.  It does not override any of the rest, nor does it want to to know anything about them. So, no IllegalStateExceptions are thrown.

The base class also provides final implementations for the entire isDerivedClass() family of methods, coded as follows: return asDerivedClass() != null;  This way, the number of methods that need to be overriden by derived classes is minimized.

I have not been using @Deprecated in this mechanism because I did not think of it.  Now that you gave me the idea, I will put it to use, thanks!

C# has a related mechanism built-in via the use of the as keyword.  In C# you can say DerivedClass derivedInstance = baseInstance as DerivedClass and you will get a reference to a DerivedClass if your baseInstance was of that class, or null if it was not. This (theoretically) performs better than is followed by cast, (is is the admittedly better named C# keyword for instanceof,) but the custom mechanism that we have been hand-crafting performs even better: the pair of instanceof-and-cast operations of Java, as well as the as operator of C# do not perform as fast as the single virtual method call of our custom approach.

I hereby put forth the proposition that this technique should be declared to be a pattern and that a nice name should be found for it.

Gee, thanks for the downvotes!

A summary of the controversy, to save you from the trouble of reading the comments:

People's objection appears to be that the original design was wrong, meaning that you should never have vastly different classes deriving from a common base class, or that even if you do, the code which uses such a hierarchy should never be in the position of having a base reference and needing to figure out the derived class. Therefore, they say, the self-casting mechanism proposed by this question and by my answer, which improves the use of the original design, should never have been necessary in the first place. (They don't really say anything about the self-casting mechanism itself, they only complain about the nature of designs that the mechanism is meant to be applied to.)

However, in the example above I have already shown that the creators of the java runtime did in fact choose precisely such a design for the java.lang.reflect.Member, Field, Method hierarchy, and in the comments below I also show that the creators of the C# runtime independently arrived at an equivalent design for the System.Reflection.MemberInfo, FieldInfo, MethodInfo hierarchy.  So, these are two different real world scenarios which are sitting right under everyone's nose and which have demonstrably workable solutions using precisely such designs.

That's what all the following comments boil down to.  The self-casting mechanism is hardly mentioned.

ContentLicense: CC BY-SA 3.0


答:
It's a little hard to imagine a circumstance where you have a group of things and want them to either make a sandwich or contact aliens. In most cases where you find such casting you will operate with one type - e.g. in clang you filter a set of nodes for declarations where getAsFunction returns non-null, rather than doing something different for each node in the list.

It might be that you need a perform a sequence of action and it's not actually relevant that the objects performing the action are related.

So instead of a list of Base, work on the list of actions

```<code>for (RandomAction action : actions)
   action.act(context);
</code>```

where

```<code>interface RandomAction {
    void act(Context context);
}

interface Context {
    Ingredients getRandomIngredients();
    double getFrequency();
}
</code>```

You can, if appropriate, have Base implement a method to return the action, or whatever other means you need to select the action from the instances in your base list (since you say you can't use polymorphism, so presumably the action to take is not a function of the class but some other property of the bases; otherwise you'd just give Base the act(Context) method )

Body:
It's a little hard to imagine a circumstance where you have a group of things and want them to either make a sandwich or contact aliens. In most cases where you find such casting you will operate with one type - e.g. in clang you filter a set of nodes for declarations where getAsFunction returns non-null, rather than doing something different for each node in the list.

It might be that you need a perform a sequence of action and it's not actually relevant that the objects performing the action are related.

So instead of a list of Base, work on the list of actions

for (RandomAction action : actions)
   action.act(context);

where

interface RandomAction {
    void act(Context context);
}

interface Context {
    Ingredients getRandomIngredients();
    double getFrequency();
}

You can, if appropriate, have Base implement a method to return the action, or whatever other means you need to select the action from the instances in your base list (since you say you can't use polymorphism, so presumably the action to take is not a function of the class but some other property of the bases; otherwise you'd just give Base the act(Context) method )


问:
Top-down vs Bottom-up approach when designing a class library
I am designing a class library to represent western equal temperament music theory concepts for the purpose of composing notated music with code (I realize there are other libraries and programs for this but I want to design my own).  The problem I am having is that when I start with the most fundamental concept (PitchClass) and start building upwards, I very quickly spiral out of control with too much complexity in the design.  I end up scrapping it and starting over.

I am thinking about a new approach.  Start by writing a program (which will not compile) that demonstrates how I want to use the library in the end.  For example write the sample programs that might accompany a library first, as a part of the design process.  I am hoping that doing so might help me with lower-level design decisions so that I do not lose myself in design complexity.

This approach is analogous to test driven design, but different in that the sample program is not isolated to a single class or function, but instead demonstrates the interface of many high-level classes.

Question

Is the top-down design methodology I am describing here a valid approach?  Does it have a name?  I am working alone, but do teams ever use an approach like this?

This does not answer the question because it is specifically about designing a web UI and dealing with browser differences.

This is not relevant because it is about back-end vs front-end specifications.

This is not a duplicate because it is specifically about approaching an MVC stack.

答:
You're describing Acceptance Test-Driven Development.

The basic principle behind ATDD is that each software requirement is accompanied by an acceptance test that, when executed, provides proof that the requirement has been satisfied.

Acceptance tests are created when the requirements are analyzed and prior to coding. They can be developed collaboratively by requirement requester (product owner, business analyst, customer representative, etc.), developer, and tester. Developers implement the system using the acceptance tests. Failing tests provide quick feedback that the requirements are not being met.

The tests are specified in business domain terms. The terms then form a ubiquitous language that is shared between the customers, developers, and testers.

Tests and requirements are interrelated.  A requirement that lacks a test may not be implemented properly. A test that does not refer to a requirement is an unneeded test. An acceptance test that is developed after implementation begins represents a new requirement.

I'm personally a big fan of ATDD.  Requirements that are not accompanied by an acceptance test are not requirements at all; they're wishes.


问:
How can I approach application programming from a database background?
I have a lot of database experience, but virtually no application programming experience.  At work, we have an EDMX? model generated from entities in the database, and we transform T4 templates to create what I assume are classes.  I think this is the Entity Framework?  From there, the application (in C#) takes the data and (uses an MVC structure?) to bind the data to XAML (it is a Silverlight application).  I assume the XAML is embedded into the webpage using Javascript, which is contained in HTML.

I struggle to find a generic top-down roadmap online that can explain how data gets passed around in such a structure, but I was wondering if anyone had a good solid explanation of how this generally works?  If I can get a clearer picture of how data is passed, I can figure out what areas I need to improve on, knowledge-wise.

答:
Entity Framework is an Object-Relational Mapper; it translates the results of SQL queries into objects and collections.  For example, this query:

```<code>SELECT name, address, city, state, zip FROM customers;
</code>```

might produce a collection

```<code>IEnumerable<customer> result
</code>```

of objects that looks like this:

```<code>public class Customer
{
    public string Name { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}
</code>```

What happens from there depends on your application's structure.  The ASP.NET server may expose a series of REST services that produce JSON or XML that is consumed by the Silverlight app (the usual arrangement):

```<code> {
     "firstName": "John",
     "lastName": "Smith",
     "age": 25,
     "address":
     {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": "10021"
     },
     "phoneNumber":
     [
         {
           "type": "home",
           "number": "212 555-1234"
         },
         {
           "type": "fax",
           "number": "646 555-4567"
         }
     ]
 }
</code>```

Body:
Entity Framework is an Object-Relational Mapper; it translates the results of SQL queries into objects and collections.  For example, this query:

SELECT name, address, city, state, zip FROM customers;

might produce a collection

IEnumerable<customer> result

of objects that looks like this:

public class Customer
{
    public string Name { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}

What happens from there depends on your application's structure.  The ASP.NET server may expose a series of REST services that produce JSON or XML that is consumed by the Silverlight app (the usual arrangement):

 {
     "firstName": "John",
     "lastName": "Smith",
     "age": 25,
     "address":
     {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": "10021"
     },
     "phoneNumber":
     [
         {
           "type": "home",
           "number": "212 555-1234"
         },
         {
           "type": "fax",
           "number": "646 555-4567"
         }
     ]
 }


问:
Dealing with states in a immutable approach
I want to know how to deal when you have some states in a program, with functions that depends on them, but with a immutable approach. I read some examples and questions, but all focus in a small scenario, I want to understand this in a bigger program, close to real world.

My question isn't about some programming language or paradigm (it could be done with Java for eg. since we don't change variables values), so I'll illustrate a simple problem with this pseudo code:

```<code>--some states of my program
playerOne = {
  cards :: [Card]
  score :: Int
}
playerTwo = {
  cards :: [Card]
  score :: Int
}
tableCards :: [Card]

--a function that will perform a move in a game
--it needs to move a card from player to tableCards
--it needs to change the other player score with -1
doSomeMove()

--moves
doSomeMove(playerOne)
showScore() --p1: 10 p2: 9 tableCards: 1
doSomeMove(playerTwo)
showScore() --p1: 9 p2: 9 tableCards: 2
doSomeMove(playerOne)
showScore() --p1: 9 p2: 8 tableCards: 3
doSomeMove(playerTwo)
showScore() --p1: 8 p2: 8 tableCards: 4
</code>```

First: in "doSomeMove()" I need to read a player cards. Since I'll call this function in the middle of the game I can't read from "playerOne" variable, since it's immutable and won't change in the middle of the game! So how can I solve this? To read actual program current states? do I need to always receive the actual player cards states by parameter?

Second: I'll change cards (both player and table) and other player score in this function. As I can't really change the variables (since it's immutable) I'll clone them, and set the changed state in a local variable inside the function, right? But how can next function (doSomeMove() or others) will know about this change?

Basically, the only thing that I can think to solve is: getting whole program state by parameter, do some changes, and return everything as parameter as well to next function use and be aware of state changes. But I think this is very unpractical, since if I have 20 states, and 50 functions, do I need to all 50 functions passing and return all 20 states each one?

I don't want to solve this problem, just to understand how to solve programs like this or bigger with immutability. And I hope this question helps another people, since I asked to some people how to solve this and no one answered surely! Thanks!

答:
At the topmost level, you can use a fold to feed the output of the last step into the input of the next step without having to give it an intermediate name that gets reassigned.  Basically, at each step you create a whole new scope.  This part is a lot easier with functional reactive programming or actors.

Below that level, the key insight is because of immutability, your state variables do not always have to stay grouped together.  You can sort of deconstruct your state on the way down the stack, creating as many copies or slices as you need, then you reconstruct it on the way back up.  That way the functions you create do not need to be aware of the entire state, just what gets passed in as their arguments.

Your doSomeMove example would take in a player's hand, the table cards, and the opposing player's score, and return new values for all those.  It might be implemented like this:

```<code>doSomeMove(hand, table, score)
    (newHand, removedCard) = removeCard(hand)
    newTable = addCard(table, removedCard)
    return (newHand, newTable, decrementScore(score))
</code>```

Then the code that calls doSomeMove would take in all the players' hands, and all their scores, deconstruct it to make the call, then reconstruct it:

```<code>callingCode(hands, scores, table)
    (playerHand, opponentHand) = hands
    (playerScore, opponentScore) = scores
    (newPlayerHand, newTable, newOpponentScore) = doSomeMove(playerHand, table, opponentScore)
    return ((newPlayerHand, opponentHand), (playerScore, newOpponentScore), newTable)
</code>```

There are patterns that can simplify this, and you can split this out into multiple levels of abstraction, but my point was to show the basic approach to take such that doSomeMove doesn't need to be aware of your entire state, just what's relevant.  The lower down in the call stack you go, the less state you need.  For example, removeCard has no idea whose card is being removed.  It takes some practice to be able to avoid passing all your state all over the place, but it is doable.

Body:
At the topmost level, you can use a fold to feed the output of the last step into the input of the next step without having to give it an intermediate name that gets reassigned.  Basically, at each step you create a whole new scope.  This part is a lot easier with functional reactive programming or actors.

Below that level, the key insight is because of immutability, your state variables do not always have to stay grouped together.  You can sort of deconstruct your state on the way down the stack, creating as many copies or slices as you need, then you reconstruct it on the way back up.  That way the functions you create do not need to be aware of the entire state, just what gets passed in as their arguments.

Your doSomeMove example would take in a player's hand, the table cards, and the opposing player's score, and return new values for all those.  It might be implemented like this:

doSomeMove(hand, table, score)
    (newHand, removedCard) = removeCard(hand)
    newTable = addCard(table, removedCard)
    return (newHand, newTable, decrementScore(score))

Then the code that calls doSomeMove would take in all the players' hands, and all their scores, deconstruct it to make the call, then reconstruct it:

callingCode(hands, scores, table)
    (playerHand, opponentHand) = hands
    (playerScore, opponentScore) = scores
    (newPlayerHand, newTable, newOpponentScore) = doSomeMove(playerHand, table, opponentScore)
    return ((newPlayerHand, opponentHand), (playerScore, newOpponentScore), newTable)

There are patterns that can simplify this, and you can split this out into multiple levels of abstraction, but my point was to show the basic approach to take such that doSomeMove doesn't need to be aware of your entire state, just what's relevant.  The lower down in the call stack you go, the less state you need.  For example, removeCard has no idea whose card is being removed.  It takes some practice to be able to avoid passing all your state all over the place, but it is doable.


答:
Is the top-down design methodology I am describing here a valid
  approach? Does it have a name?

Yes, it is called top-down design, and there's a decent Wikipedia article. In particular, you're describing an informal variant where you figure out what you want the library to do and how you want it organized based on how you intend to use it.

do teams ever use an approach like this?

Yes, but the larger the team is, the more formality you need in order to keep everyone working toward the same goals. In the old days, the top-down design was done on paper before the programmers were hired.

Title: Top-down vs Bottom-up approach when designing a class library

Body:
I am designing a class library to represent western equal temperament music theory concepts for the purpose of composing notated music with code (I realize there are other libraries and programs for this but I want to design my own).  The problem I am having is that when I start with the most fundamental concept (PitchClass) and start building upwards, I very quickly spiral out of control with too much complexity in the design.  I end up scrapping it and starting over.

I am thinking about a new approach.  Start by writing a program (which will not compile) that demonstrates how I want to use the library in the end.  For example write the sample programs that might accompany a library first, as a part of the design process.  I am hoping that doing so might help me with lower-level design decisions so that I do not lose myself in design complexity.

This approach is analogous to test driven design, but different in that the sample program is not isolated to a single class or function, but instead demonstrates the interface of many high-level classes.

Question

Is the top-down design methodology I am describing here a valid approach?  Does it have a name?  I am working alone, but do teams ever use an approach like this?

This does not answer the question because it is specifically about designing a web UI and dealing with browser differences.

This is not relevant because it is about back-end vs front-end specifications.

This is not a duplicate because it is specifically about approaching an MVC stack.


答:
The approach can be a good one in cases where almost any type within a family will either be directly usable as an implementation of some interface which meets some criterion or can be used to create an implementation of that interface.  The built-in collection types would IMHO have benefited from this pattern, but since they don't for purposes of example I'll invent a collection interface BunchOfThings<T>.

Some implementations of BunchOfThings are mutable; some aren't.  In many cases, an object Fred might want to hold something it can use as a BunchOfThings and know that nothing other than Fred will be able to modify it.  This requirement may be satisfied in two ways:

Fred knows that it holds the only references to that BunchOfThings, and no outside reference to that BunchOfThings ir its internals exists anywhere in the universe.  If nobody else has a reference to the BunchOfThings or its internals, nobody else will be able to modify it, so the constraint will be satisfied.

Neither the BunchOfThings, nor any of its internals to which outside references exist, can be modified via any means whatsoever.  If absolutely nobody can modify a BunchOfThings, then the constraint will be satisfied.

One way of satisfying the constraint would be to unconditionally copy any object received (recursively processing any nested components).  Another would be to test whether a received object promises immutability and, if not, make a copy of it, and do likewise with any nested components.  An alternative, which is apt to be cleaner than the second and faster than the first, is to offer an AsImmutable method which asks an object to make an immutable copy of itself (using AsImmutable on any nested components that support it).

Related methods may also be provided for asDetached (for use when code receives an object and doesn't know if it will want to mutate it, in which case a mutable object should be replaced with a new mutable object, but an immutable object can be kept as-is), asMutable (in cases where an object knows that it will hold an object earlier returned from asDetached, i.e. either an unshared reference to a mutable object or a sharable reference to a mutable one), and asNewMutable (in cases where code receives an outside reference and knows it's going to want to mutate a copy of the data therein--if the incoming data is mutable there's no reason to start by making an immutable copy which is going to be immediately used to create a mutable copy and then abandoned).

Note that while the asXX methods may return slightly different types, their real role is to ensure that the returned objects will satisfy program needs.


答:
Put an abstract method in the base class which does one thing in Sub1 and the other thing in Sub2, and call that abstract method in your mixed loops.

```<code>class Sub1 : Base {
    @Override void doAThing() {
        this.makeASandwich(getRandomIngredients());
    }
}

class Sub2 : Base {
    @Override void doAThing() {
        this.contactAliens(getFrequency());
    }
}

for (Base base : bases) {
    base.doAThing();
}
</code>```

Note that this may require other changes depending on how getRandomIngredients and getFrequency are defined. But, honestly, inside the class that contacts aliens is probably a better place to define getFrequency anyway.

Incidentally, your asSub1 and asSub2 methods are definitely bad practice. If you're going to do this, do it by casting. There's nothing these methods give you that casting doesn't.

Body:
Put an abstract method in the base class which does one thing in Sub1 and the other thing in Sub2, and call that abstract method in your mixed loops.

class Sub1 : Base {
    @Override void doAThing() {
        this.makeASandwich(getRandomIngredients());
    }
}

class Sub2 : Base {
    @Override void doAThing() {
        this.contactAliens(getFrequency());
    }
}

for (Base base : bases) {
    base.doAThing();
}

Note that this may require other changes depending on how getRandomIngredients and getFrequency are defined. But, honestly, inside the class that contacts aliens is probably a better place to define getFrequency anyway.

Incidentally, your asSub1 and asSub2 methods are definitely bad practice. If you're going to do this, do it by casting. There's nothing these methods give you that casting doesn't.


问:
Increment or double problem
I have a problem with an assignment. In this assignment I have to create a program which needs to calculate how many different possibilities are there to get from number a to b. To get from a to b you can only D(double) the value or I(increment) the value.

So you can have a=3 and b=14. This will get you 8 different possibilities:

```<code>DDII = 3*2*2+2 = 14
DID = ((3*2)+1)*2 =14
DIIIIIIII = 3*2+8 =14
IDIIIIII=(3+1)*2+6=14
IIDIIII =(3+2)*2+4=14
IIIDII =(3+3)*2+2=14
IIIID =(3+4)*2+0=14
IIIIIIIIIII=3+11=14
</code>```

In my current solution I'm using a breadth-first search (BFS) to calculate all the possibilities only this is very slow, because sometimes there are many possibilities and with BFS you will go through all of them. So for example if want to calculate a=10 and b=1000, this will give me 74,116,423 possibilities.

This is almost impossible to calculate with my computer and the solution I'm currently using.

What is the proper approach to take to solve this problem? Being an assignment I am not looking for the answer, I need an algorithm or other push in the right direction.

答:
For example for the number of ways to go from 10 to 1000:

Let A (N) = number of ways to get from N to 1000. Calculate and store A (N) for N = 1000, 999, ..., 10.

For N = 1000, 999, ..., 501, A (N) = 1 because you cannot double the number.

For N ≤ 500, A (N) = A (2N) + A (N + 1), because you can either double and get from 2N to 1000, or increment and go from N+1 to 1000.

Title: Increment or double problem


问:
So what *did* Alan Kay really mean by the term "object-oriented"?
Reportedly, Alan Kay is the inventor of the term "object oriented". And he is often quoted as having said that what we call OO today is not what he meant.

For example, I just found this on Google:

I made up the term 'object-oriented', and I can tell you I didn't have C++ in mind

-- Alan Kay, OOPSLA '97

I vaguely remember hearing something pretty insightful about what he did mean. Something along the lines of "message passing".

Do you know what he meant? Can you fill in more details of what he meant and how it differs from today's common OO? Please share some references if you have any.

答:
One of the major points that I've picked up from following the works of Alan Kay and others such as Jim Coplien is that true "object" oriented programming is about modeling computers and software in terms of HUMAN/USER mental models, rather than being just a tool for PROGRAMMERS.

As I understand it, Alan's vision of OOP was making the computer a tool that allows a human user to make whatever they want: the full capabilities of the computer are directly exposed to the end user through an intuitive interactive model. I should be able view and sculpt runtime objects and interactions DIRECTLY, not just through code.

Here is a post about my plans to attempt a some version of this in JavaScript as a proof of concept:http://www.cemetech.net/forum/viewtopic.php?p=234494#234494

From a perspective of software development / programming, Jim Coplien talks about how code can and SHOULD resemble the users mental model of it. That is, the code reads much the same way as it would sound by a person describing it's behavior. This is largely accomplished by thinking in terms of OBJECTS, rather than in terms of CLASSES and TYPES. Behavior is described on terms of the ROLES played by objects, not as part of the definition of an object's IDENTITY.  You should be able to model interactions on terms of objects, which are identified by the ROLE they play in an interaction. This is how human mental models work: Waiter, Customer, Cashier, Source Account, Destination Account,... These are ROLES, not TYPES, and you want to the able to define methods for "whatever object is playing this role at the time", because  that behavior is part of a system interaction between many changing objects, rather than part of the definition of some TYPE.

OwnerDisplayName: Charlie Flowers

ContentLicense: CC BY-SA 4.0


问:
How to write a suitable recurrence relation for a python function?
I have an exercise in which I am require to build a recursive function that takes a natural number and returns "True" if it is divisible by 3, or "False" otherwise, using the 3-divisibility rule. Then I was asked to write a recurrence relation of this function. The function I wrote is:

```<code>def divide3(n):
    i=0
    while i in range(0,len(str(n))-1):
        if (sum(n, i))%3==0:
            if (divide3(int(str(n)[i+1:])))==True:
                return True
            else:
                return False
        continue
</code>```

What I don't understand is how I am supposed to write an n-depended recurrence relation, if the number of operations I make is related to the number of digits in n, and has nothing to do with n itself. I would appreciate any help in the subject.

答:
Sorry, but your code doesn't work at all and makes no sense whatsoever. If it gets into the loop at all, it immediately gets killed by an error. Did you even try it? I'd recommend first getting it right instead of trying to come up with a recurrence relation for something broken. Or did they ask you for the recurrence relation because they saw your code and also had no idea what you were doing, so this is their way of trying to get you to explain?

What's "the 3-divisibility rule"? You mean that a number is divisible by 3 if and only if its digit sum is? If so, then that directly tells you what to do: When asked whether some number is divisible by 3 and you don't know right away, ask yourself whether its digit sum is divisible by 3. If that number is still too large to see it directly, ask yourself whether the digit sum of that number is divisible by 3. And so on.

Straight-forward implementation then:

 def divide3(n): return n in (0, 3, 6, 9) if n < 10 else divide3(sum(map(int, str(n))))

Bit more interesting:

 def divide3(n): return n in (0, 3, 6, 9) if n < 10 else divide3(n//10 + n%10)

(Sorry about the formatting, don't know how to spoilerize code.)


问:
What is Weighted Round Robin Arbitration
In NVMe Protocol, NVMe Controller uses Weighted Round Robin Arbitration to select the Submission Queue, from which commands can be taken.

So what is exactly Weighted Round Robin Arbitration?

My understanding is that, suppose you have high priority class of weight 3, medium priority of weight 2 and low priority of weight 1. So in WRR Arbitration, in 6 rounds, Controller 3 times selects high priority class, 2 times medium priority class and 1 time low priority class, whereas in Round Robin Arbitration, it would be 2, 2, 2.

Kindly comment on my thoughts.

答:
You're exactly right. I'm not familiar with NVMe, so I can't comment on the specific weightings and number of queues, but the general technique is quite popular in process scheduling.

Note that the weighted technique differs from the "priority-based" round-robin technique, where all the higher-priority tasks will be run (using round robin between them) before moving onto a round-robin rotation of the lower priority tasks.

You might also find this page on process scheduling interesting.


问:
Commit at a logical checkpoint only, or also when you're at a stopping point?
Life, the work day, and personal projects don't always give us the opportunity the commit code at a logical completion (functionality subset programmed, bug fix completely patched, etc.).

Sometimes we need to stop working half way through a new method, or through a half-baked fix. Think... The work day ends, or it is time to shut down for the evening.

I feel guilty in doing a commit at this point. Mostly because my commit message is some daft comment saying "Started to do blah" or "Did this partially but need to complete".

Committing without a nice a logical stop feels sloppy, mostly for commit log and historical purposes.

But at the same time I don't like to "disconnect" from the code or call it quits with an uncommitted working directory. Maybe unfounded, but also for the sense of not having a dvcs backup at this point in case of a hardware failure.

What is the right approach here? When you are at a force programming stopping point but not a logical stopping point in the code, commit or wait until that logical containment is done to commit? Does the latter contradict the "commit often" mantra? It just seems history and diffing this could become difficult to understand after the fact.

答:
The concept of committing the code when it reached a 'milestone' is mostly due to, other developers/testers should be able to checkout the latest version without fearing that they can't compile / debug the code because it's broken.

When it comes to the distributed version control systems like Git, there is no such issue when checking in the code as it's committed to the local repo, but pushing that matters.

When you have a half baked code and when you have to stop work, I believe it would be fine to stop where it is and resume next day rather than committing, because the risk of hardware/software failure is minimal. Also it's important that the changes are reasonably small changes that even if you lose the change due to hardware/software failure, you should be able to redo it without a lot of effort.


问:
Copyright for collaborative group
Is there a recommended copyright (eg as BSD is to licensing) agreement type of template that could be used or altered for collaborative software work?

I aim to start a collaborative work that would potentially be non-open-source, but would like to ensure that all parties feel their work is protected and that all shared work is fairly benefited from.

I know there are documents out there, generally in the open source arena, for licensing or copyright of works; such as BSD, GPL.

Are there any of these already in existence that will apply to such a situation? (Please don't hate me if there are and its blindingly obvious! I know very little about such stuff ATM).

Are there known templates for such an agreement?

Or would a custom document be better?

Thanks

EDIT: I guess that as a portion of the work will be idea generation the agreement may need to include patent matters, or the like, and possibly non-disclosure terms as well?

答:
The problem starts with identifying who gets the rights. For open source it is easy—everybody. But if you want to restrict it, you need to identify the members somehow.

Having everybody grant rights to everybody else in the group is impractical, because everybody would have to update it when new members join the group and if some of the original members left (or worse, died), it won't be possible any more.

So you need a juristic person—corporation, association, foundation…, something. Then granting the rights becomes easy—the members simply sign that they grant exclusive rights for given works to the organization. And the hard part becomes defining how the organization accepts new members, how members leave it and how it decides which third parties it will sublicense the work.

Which is not something for which there can be a template, but organizational bylaws are usually public, so you might be able to find bylaws of organizations with similar issues for inspiration.

Title: Copyright for collaborative group


问:
Enterprise software: Where should the code go?
I recently went for an interview with a software company that claims to write enterprise level software. During the interview, the interviewer remarked that its better to use the database simply to store the data. No stored procedures or triggers (or rather they should be kept to an absolute minimum).

Now I thought that he mentioned this purely from a code maintenance point of view (as described in this PSE question, thanks @gnat), however he mentioned that it was for performance reasons. I know that the company uses C# and MSSQL server for a backend. Is his statement valid and how would the performance be increased by keeping all code logic off the database?

答:
Performance does neither increase or decrease because "you put most of the code into database" or because "you keep the code out of the database". The key point is to put the right parts of the code into the database (or to keep them out). Parts which helps to reduce the network traffic might be a good fit for stored procedures. Parts which do heavy calculations might be better kept out of the database (since otherwise you risk to make your database server a processing bottleneck).

For the remaining code (which is typically >90% for an enterprise system), a decision based on "what is better maintainable and evolvable" makes the most sense. And even that may be opionated.


问:
Is MVC controller an use case controller?
In GRASP (http://en.wikipedia.org/wiki/GRASP_(object-oriented_design) ), a controller (use case controller) is defined as:

A use case controller should be used to deal with all system events of
  a use case, and may be used for more than one use case (for instance,
  for use cases Create User and Delete User, one can have a single
  UserController, instead of two separate use case controllers)

I can see some similarities of this and MVC controller. However I don't see a standard guideline on how to design a MVC controller. Most of the time people just say it's up to the developer and the design of the application. So I'm wondering whether I can use guideline above to design MVC controller?

To be more specific, let's say an application has a page to display a list of products in a table. Each product is displayed as a row. Each row has a button to restock that product (or any other business operation that makes sense). So as I see, this page has 2 use cases (2 business operations): list products and restock product.

From the guideline above, probably I'll have 2 use case controllers for 2 use cases. Are those mapped to 2 MVC controllers? Or just need one Product controller with 2 actions for 2 use cases?

If just need one Product controller, how about a page that has many business operations in the same page? Soon the controller will become too big. Of course if a page has too many operations, it might not be a good UI design, but sometimes developers don't have a choice because clients want it that way to be convenient

答:
In MVC pattern, a controller mediates between view and model. Action methods in a controller should be thin and should not have logic embedded in them.In GRASP you can look for Indirection pattern (http://en.wikipedia.org/wiki/GRASP_(object-oriented_design))

So how many controllers should we create or how many action methods should be in one controller, general rule of thumb is to group related action methods in one controllers so that they look clean and well organized.

For your case, I think it would be best to create one controller with below two action methods, as they are very much related to each other. However, the logic for ReStock need not to be in the controller itself.

List

ReStock


答: The main reason for not having code in the database is testability and maintenance. It is relatively hard to test the database code and it is a kind of hidden logic, which will become hard to maintain as you logic is spread all over and regress especially in the maintenance phase of your project.</p>

Title: Enterprise software: Where should the code go?

Body:
I recently went for an interview with a software company that claims to write enterprise level software. During the interview, the interviewer remarked that its better to use the database simply to store the data. No stored procedures or triggers (or rather they should be kept to an absolute minimum).

Now I thought that he mentioned this purely from a code maintenance point of view (as described in this PSE question, thanks @gnat), however he mentioned that it was for performance reasons. I know that the company uses C# and MSSQL server for a backend. Is his statement valid and how would the performance be increased by keeping all code logic off the database?


问:
N-Layer architecture
I am attempting to structure my solution projects in such a manner as to improve testing, reuseability, separation of concerns and all that good stuff.  Whilst I understand these concepts in theory, I find myself going around in circles in regards to its implementation, specifically what goes where.

I have the following project structure within my solution:

Core references nothing (interfaces for repos and services, DTOs)

BLL references Core (my business logic)

DAL references Core & BLL (EF, EDMX [in my case] and repo implementations)

UI references Core & BLL (WPF, Winforms, Console, w/e)

Is my implementation correct, am I on the right track, or have a simply made a total hash of it?

答:
The implementation seems to be fine as in a traditional N-Layer architecture.

In strict layering your UI layer will always call BLL, which will then call DAL, UI cannot call DAL directly.

In case there is not much business logic you can directly call DAL from UI and completely avoid BLL.

You can also have a mix, business logic in BLL, UI calling both BLL and DAL directly in some scenarios where it makes more sense that is what is known as loose layering.

However regarding CORE (Interfaces), I think you should NOT have BLL and DAL interfaces grouped together. Imagine strict layering, in that case you will may not like to expose the DAL interfaces to UI.

Title: N-Layer architecture


答:
In my opinion, mixing interfaces for services and repositories in one project is not a good idea. Doing so will expose unnecessary interfaces to projects that don't need them (e.g. DAL doesn't need to know about service interfaces, UI doesn't need to know about repositories interfaces in strict layering)

Below is a common structure that I use frequently in my layered applications. It's a reference from books (Professional ASP.NET Design Patterns to be more specific) and some online articles with my own modification

This structure has 4 layers that commonly found in DDD: UI -> Application Services -> Domain (Entities + Domain Services) + Repositories. The central of the application is Core project where it contains all business logic, business entities and interfaces for repositories (to be used by application services). ORM/Data Access logic is encapsulated in Repository project. UI only depends on application services interfaces. Here I assume you use IoC container for dependency injection with UI project as composition root.

Beside the projects listed here, of course you can have additional projects like:

Infrastructure: infrastructure related, e.g. logging

DependencyResolution: move IoC container setup code here if you don't want to put in UI project

Title: N-Layer architecture

Body:
I am attempting to structure my solution projects in such a manner as to improve testing, reuseability, separation of concerns and all that good stuff.  Whilst I understand these concepts in theory, I find myself going around in circles in regards to its implementation, specifically what goes where.

I have the following project structure within my solution:

Core references nothing (interfaces for repos and services, DTOs)

BLL references Core (my business logic)

DAL references Core & BLL (EF, EDMX [in my case] and repo implementations)

UI references Core & BLL (WPF, Winforms, Console, w/e)

Is my implementation correct, am I on the right track, or have a simply made a total hash of it?


答:
Uncle Bob gives talks on Clean Architecture.

Because you actually want to improve your design, I strongly advise you to listen to his talk.

He advocated how the Single Responsibility Principle still applies not just to a class or method, but also to how we design our architecture.

Specifically, you should strive to group things together that typically change together and pull things that change for different reasons.

Consider this architecture:

```<code>- Core
   Dependencies
   class1
   class2
   .
   .
   .

- Stories
 - CreateUser
    Dependencies
    View
    ViewModel
    Repository
    Tests

 -  ShareStatusUpdate
    Dependencies
    View
    ViewModel
    Repository
    Tests
</code>```

The above architecture engages a developer to immediately comprehend the architecture's intent based on the functionality that the architecture clearly exposes.

Notice how this architecture does not obscure the functionality of the system through the use of "Controllers" "Models", "DAL" but instead exposes the user stories it supports in clear detail such as CreateUser and ShareStatusUpdate.

Hence, the architecture should convey the design of a system easily without the user having to dig through folders (i.e. Controller, Model, DAL) to understand the intended functionality. "Controllers", "Models" and "DAL" are low-level details of an architecture and not "the architecture" itself.

Title: N-Layer architecture

Body:
Uncle Bob gives talks on Clean Architecture.

Because you actually want to improve your design, I strongly advise you to listen to his talk.

He advocated how the Single Responsibility Principle still applies not just to a class or method, but also to how we design our architecture.

Specifically, you should strive to group things together that typically change together and pull things that change for different reasons.

Consider this architecture:

- Core
   Dependencies
   class1
   class2
   .
   .
   .

- Stories
 - CreateUser
    Dependencies
    View
    ViewModel
    Repository
    Tests

 -  ShareStatusUpdate
    Dependencies
    View
    ViewModel
    Repository
    Tests

The above architecture engages a developer to immediately comprehend the architecture's intent based on the functionality that the architecture clearly exposes.

Notice how this architecture does not obscure the functionality of the system through the use of "Controllers" "Models", "DAL" but instead exposes the user stories it supports in clear detail such as CreateUser and ShareStatusUpdate.

Hence, the architecture should convey the design of a system easily without the user having to dig through folders (i.e. Controller, Model, DAL) to understand the intended functionality. "Controllers", "Models" and "DAL" are low-level details of an architecture and not "the architecture" itself.


答:
It doesn't always make sense to add functions to the base class, as suggested in some of the other answers. Adding too many special case functions can result in binding otherwise unrelated components together.

For example I might have an Animal class, with Cat and Dog components. If I want to be able to print them, or show them in the GUI it might be overkill for me to add renderToGUI(...) and sendToPrinter(...) to the base class.

The approach you are using, using type-checks and casts, is fragile - but at least does keep the concerns separated.

However if you find yourself doing these types of checks/casts often then one option is to implement the visitor / double-dispatch pattern for it. It looks kind of like this:

```<code>public abstract class Base {
  ...
  abstract void visit( BaseVisitor visitor );
}

public class Sub1 extends Base {
  ...
  void visit(BaseVisitor visitor) { visitor.onSub1(this); }
}

public class Sub2 extends Base {
  ...
  void visit(BaseVisitor visitor) { visitor.onSub2(this); }
}

public interface BaseVisitor {
   void onSub1(Sub1 that);
   void onSub2(Sub2 that);
}
</code>```

Now your code becomes

```<code>public class ActOnBase implements BaseVisitor {
    void onSub1(Sub1 that) {
       that.makeASandwich(getRandomIngredients())
    }

    void onSub2(Sub2 that) {
       that.contactAliens(getFrequency());
    }
}

BaseVisitor visitor = new ActOnBase();
for (Base base : bases) {
    base.visit(visitor);
}
</code>```

The main benefit is that if you add a subclass, you'll get compile errors rather than silently missing cases. The new visitor class also becomes a nice target for pulling functions into. For example it might make sense to move getRandomIngredients() into ActOnBase.

You can also extract the looping logic: For example the above fragment might become

```<code>BaseVisitor.applyToArray(bases, new ActOnBase() );
</code>```

A little further massaging and using Java 8's lambdas and streaming would let you get to

```<code>bases.stream()
     .forEach( BaseVisitor.forEach(
       Sub1 that -> that.makeASandwich(getRandomIngredients()),
       Sub2 that -> that.contactAliens(getFrequency())
     ));
</code>```

Which IMO is pretty much as neat looking and succinct as you can get.

Here is a more complete Java 8 example:

```<code>public static abstract class Base {
    abstract void visit( BaseVisitor visitor );
}

public static class Sub1 extends Base {
    void visit(BaseVisitor visitor) { visitor.onSub1(this); }

    void makeASandwich() {
        System.out.println("making a sandwich");
    }
}

public static class Sub2 extends Base {
    void visit(BaseVisitor visitor) { visitor.onSub2(this); }

    void contactAliens() {
        System.out.println("contacting aliens");
    }
}

public interface BaseVisitor {
    void onSub1(Sub1 that);
    void onSub2(Sub2 that);

    static Consumer<Base> forEach(Consumer<Sub1> sub1, Consumer<Sub2> sub2) {

        return base -> {
            BaseVisitor baseVisitor = new BaseVisitor() {

                @Override
                public void onSub1(Sub1 that) {
                    sub1.accept(that);
                }

                @Override
                public void onSub2(Sub2 that) {
                    sub2.accept(that);
                }
            };
            base.visit(baseVisitor);
        };
    }
}

Collection<Base> bases = Arrays.asList(new Sub1(), new Sub2());

bases.stream()
     .forEach(BaseVisitor.forEach(
             Sub1::makeASandwich,
             Sub2::contactAliens));
</code>```

Body:
It doesn't always make sense to add functions to the base class, as suggested in some of the other answers. Adding too many special case functions can result in binding otherwise unrelated components together.

For example I might have an Animal class, with Cat and Dog components. If I want to be able to print them, or show them in the GUI it might be overkill for me to add renderToGUI(...) and sendToPrinter(...) to the base class.

The approach you are using, using type-checks and casts, is fragile - but at least does keep the concerns separated.

However if you find yourself doing these types of checks/casts often then one option is to implement the visitor / double-dispatch pattern for it. It looks kind of like this:

public abstract class Base {
  ...
  abstract void visit( BaseVisitor visitor );
}

public class Sub1 extends Base {
  ...
  void visit(BaseVisitor visitor) { visitor.onSub1(this); }
}

public class Sub2 extends Base {
  ...
  void visit(BaseVisitor visitor) { visitor.onSub2(this); }
}

public interface BaseVisitor {
   void onSub1(Sub1 that);
   void onSub2(Sub2 that);
}

Now your code becomes

public class ActOnBase implements BaseVisitor {
    void onSub1(Sub1 that) {
       that.makeASandwich(getRandomIngredients())
    }

    void onSub2(Sub2 that) {
       that.contactAliens(getFrequency());
    }
}

BaseVisitor visitor = new ActOnBase();
for (Base base : bases) {
    base.visit(visitor);
}

The main benefit is that if you add a subclass, you'll get compile errors rather than silently missing cases. The new visitor class also becomes a nice target for pulling functions into. For example it might make sense to move getRandomIngredients() into ActOnBase.

You can also extract the looping logic: For example the above fragment might become

BaseVisitor.applyToArray(bases, new ActOnBase() );

A little further massaging and using Java 8's lambdas and streaming would let you get to

bases.stream()
     .forEach( BaseVisitor.forEach(
       Sub1 that -> that.makeASandwich(getRandomIngredients()),
       Sub2 that -> that.contactAliens(getFrequency())
     ));

Which IMO is pretty much as neat looking and succinct as you can get.

Here is a more complete Java 8 example:

public static abstract class Base {
    abstract void visit( BaseVisitor visitor );
}

public static class Sub1 extends Base {
    void visit(BaseVisitor visitor) { visitor.onSub1(this); }

    void makeASandwich() {
        System.out.println("making a sandwich");
    }
}

public static class Sub2 extends Base {
    void visit(BaseVisitor visitor) { visitor.onSub2(this); }

    void contactAliens() {
        System.out.println("contacting aliens");
    }
}

public interface BaseVisitor {
    void onSub1(Sub1 that);
    void onSub2(Sub2 that);

    static Consumer<Base> forEach(Consumer<Sub1> sub1, Consumer<Sub2> sub2) {

        return base -> {
            BaseVisitor baseVisitor = new BaseVisitor() {

                @Override
                public void onSub1(Sub1 that) {
                    sub1.accept(that);
                }

                @Override
                public void onSub2(Sub2 that) {
                    sub2.accept(that);
                }
            };
            base.visit(baseVisitor);
        };
    }
}

Collection<Base> bases = Arrays.asList(new Sub1(), new Sub2());

bases.stream()
     .forEach(BaseVisitor.forEach(
             Sub1::makeASandwich,
             Sub2::contactAliens));


答:
A local commit can always be safely amended if it hasn't yet been pushed upstream, so you could commit at the end of the day and take it up again the next. However, this is of limited utility as far as code sharing and redundancy are concerned, unless working on a branch that's yours alone. In that case, you've got the right to push one day and force an update the next, which leaves anyone else who's pulled your branch responsible for dealing with the aftermath. Notably, this sacrifices a certain amount of automated revision management and leaves it up to the people involved.

As git is flexible enough to support various workflows, what commit & share schedule to use ultimately depends on your team's needs, so they can provide the exact answers you seek. It sounds like, at the very least, a local EOD commit will meet your individual need to keep changes organized in commits.

Title: Commit at a logical checkpoint only, or also when you're at a stopping point?

Body:
Life, the work day, and personal projects don't always give us the opportunity the commit code at a logical completion (functionality subset programmed, bug fix completely patched, etc.).

Sometimes we need to stop working half way through a new method, or through a half-baked fix. Think... The work day ends, or it is time to shut down for the evening.

I feel guilty in doing a commit at this point. Mostly because my commit message is some daft comment saying "Started to do blah" or "Did this partially but need to complete".

Committing without a nice a logical stop feels sloppy, mostly for commit log and historical purposes.

But at the same time I don't like to "disconnect" from the code or call it quits with an uncommitted working directory. Maybe unfounded, but also for the sense of not having a dvcs backup at this point in case of a hardware failure.

What is the right approach here? When you are at a force programming stopping point but not a logical stopping point in the code, commit or wait until that logical containment is done to commit? Does the latter contradict the "commit often" mantra? It just seems history and diffing this could become difficult to understand after the fact.


问:
Injecting collections as constructor dependencies
We are using constructor dependency injection in our application. Following that approach we inject everything using an injection container so we are able to replace any dependency with a Mock.

Some colleagues complain about this procedure as they say that injecting collections of any type is going too far with injection and they prefer to call a new() inside the constructor.

What do you think about this? What procedure do you follow if you are using dependency injection?

One example of a real use case. We have a Dictionary with an special behavior, it allows to add the same key several times and it just increments an internal counter and it decreases the counter when removing elements from it only removing the element from memory when the counter is 0 (the class has been simplified a bit but I think you can get the idea):

```<code>public class ExtendedDictionary<TValue> : IExtendedDictionary<TValue>
{
    private readonly IDictionary<CustomKey, TValue> dictionary;

    public ExtendedDictionary(IDictionary<CustomKey, TValue> dictionary)
    {
        this.dictionary = dictionary;
    }

    public void Add(ParameterBase parameter, DriveInformation driveInformation, TValue data)
    {
        CustomKey key = new CustomKey (driveInformation, parameter.Index);

        if (this.dictionary.ContainsKey(key))
        {
            this.dictionary.Single(p => p.Key == key).Key.Count++;
        }
        else
        {
            this.dictionary.Add(key, data);
        }
    }

    public void Remove(ParameterBase parameter, DriveInformation driveInformation, TValue data)
    {
        CustomKey key = new CustomKey (driveInformation, parameter.Index);

        if (this.dictionary.ContainsKey(key))
        {
            this.dictionary.Single(p => p.Key == key).Key.Count--;
        }
        else
        {
            this.dictionary.Remove(key);
        }
    }
}
</code>```

答:
Since you always pass an empty dictionary to the constructor,  in my opinions this is bit too extreme.

Only advantage I can see is that when you unit test, you can pass a mock dictionary and verify add/remove methods are called.

However same can be achieved by simply using count on the custom collection.

So I believe this is an overkill.


答:
Committing code is cheap in git. You have several options:

Commit and amend later

```<code>    $ git commit --all -m "WIP: half-implemented hack"
</code>```

... time passes ...

```<code>    $ # back to work
    $ git commit --all --amend -m "Nice logical atomic commit"
</code>```

Use git stash

Same as above, but using a stash:

Commands are a little shorter to write

A stash by nature looks like work in progress (stashes are named "WIP on master" by default).

```<code>$ git stash # must go home now
</code>```

... later ...

```<code>$ git stash pop # back to work
</code>```

Note that your work will temporarly be reverted, which could be confusing if you forget that you worked on something. It helps to work with gitk or magit (emacs) in order to see stashes.

Commit and rebase

You can split your work in different units and/or experiments. When you are done, do a git rebase --interactive (-i) to edit individual commits (the command expects a base commit as an argument). Then, you can push your changes upstream (or not; it helps to clean regularly).

Why commit?

You should commit, because even though failures are minimal, the cost of committing is so low that you don't have to take a risk. As noted in the comment, at any point you can choose to have a local branch to keep things organized, if it helps.

Basically, anything you do locally is good, as long as you don't push temporary commits.

That being said, you can push your half-worked changes to another server, provided you only do it in a personnal, private branch.

Body:
Committing code is cheap in git. You have several options:

Commit and amend later

    $ git commit --all -m "WIP: half-implemented hack"

... time passes ...

    $ # back to work
    $ git commit --all --amend -m "Nice logical atomic commit"

Use git stash

Same as above, but using a stash:

Commands are a little shorter to write

A stash by nature looks like work in progress (stashes are named "WIP on master" by default).

$ git stash # must go home now

... later ...

$ git stash pop # back to work

Note that your work will temporarly be reverted, which could be confusing if you forget that you worked on something. It helps to work with gitk or magit (emacs) in order to see stashes.

Commit and rebase

You can split your work in different units and/or experiments. When you are done, do a git rebase --interactive (-i) to edit individual commits (the command expects a base commit as an argument). Then, you can push your changes upstream (or not; it helps to clean regularly).

Why commit?

You should commit, because even though failures are minimal, the cost of committing is so low that you don't have to take a risk. As noted in the comment, at any point you can choose to have a local branch to keep things organized, if it helps.

Basically, anything you do locally is good, as long as you don't push temporary commits.

That being said, you can push your half-worked changes to another server, provided you only do it in a personnal, private branch.


答:
I can see few potential issues with this approach,

Having all DTOs in one project,
If you have a DTO used in your presentation layer why would you want to put it in your core assembly,  rather I'd put them where they belong

If the BLL is the domain model,  its fine, but if services are living there too, I'd rather move them to service layer between UI and DAO.

Ideally,

1. Domain (BLL)
2. Repositories (DAO)
3. Services (coordinator of BLL and DAO)
4. UI

Title: N-Layer architecture


问:
What languages should I know if I'm interested in building web applications?
I'm interested in developing for the web and I'm curious what languages should I know besides html, css, javascript, php/python/ruby. I don't know much about c# or java to make a decision whether to learn them or not, are they used much in the field I'm interested in?
What other technologies should I look into ?</p>

答:
HTML and CSS are not programming languages.

Google App Engine supports Java. Microsoft IIS supports C#. If you're already familiar with html, css, js, php, python, and ruby, don't bother learning any more langauges, start programming!

You need to learn some SQL to interact with database.

OwnerDisplayName: webguy

ContentLicense: CC BY-SA 2.5


答:
Generally if you push more code to DB and if you do it right, it should result in performance increase. And I don't see why the interviewer claim its other way round.

Personally I would not put any code into DB simply due to ease of maintenance and ease of unit testing. In most of the applications performance improvement due to moving logic into DB does not worth the headaches followed.


问:
How to distinguish whether a file is being saved or deleted? ("Save" in MS Word deletes then re-creates)
I maintain a tool that syncs files between a client computer and a document management server (using the CMIS protocol). Versions history (on the CMIS server) is important.

When saving a document locally, MS Word:

Writes to a temp file ~wrdxxxx.tmp

Deletes the original file Example.doc

Renames ~wrdxxxx.tmp to Example.doc

PROBLEM: At step 2, my sync tool deletes the file on the server, loosing all versions history.

QUESTION: From the point of view of my sync tool, is there a way to know whether the file has really been deleted, or whether it is just being saved?

Notes:

Waiting is probably not a good solution, as I can't be sure how much time steps 2 and 3 take.

Cheking for the presence of ~wrdxxxx.tmp files does not work when several documents are being edited in the same folder at the same time.

The tool works like Dropbox: Users don't have to "commit" changes, files are synchronized automatically as soon as possible.

答:
This is not "Word" specific, the same problem could occur when someone does this manually (make a backup of the file, rename or delete the original one, restore a backup etc.) Your sync tool cannot know which of these operations are creations of new documents, or just continuations of existing ones, and it cannot easily manage the version history correctly, since that would mean it had to "mindread" what the author/editor takes as "one" document.

Thus, all software VCS tools I know of expect the user to explicitly create a new revision, delete or rename the files explictly in the repository. If you are looking for a user-friendly solution, look how tools like TortoiseSVN or TortoiseGIT have solved that problem.

At step 2, my sync tool deletes the file on the server, loosing all versions history.

In case you still want to try an "automatic" approach, ignoring what I wrote above: when a file on the client is deleted, why is it really important to delete the history on the server? Can't you just mark it "deleted" as a special state, but still keep the history? When the file "reappears" in the next sync cycle at the same place on the client, you have to "revive" the file, undo the "deleted"  state and continue the history.


问:
Sharing core repository and object mapping logic between Unit of Work methods
I'm wondering if there is a better way to do this or if I'm doing some anti-pattern here. Like I say in the subject, I'm trying to share repository calls and object mapping logic between Unit of Work methods.

For example see my GetEnvelopeBody() method being used more than once.

```<code>public class EnvelopeService
{
    private EnvelopeRepository envelopeRepository;
    private RecipientRepository recipientRepository;
    private RecipientTabRepository recipientTabRepository;

    public Envelope GetEnvelope(int id)
    {
        using (var uow = UnitOfWorkFactory.Create())
        {
            envelopeRepository = new EnvelopeRepository(uow);
            recipientRepository = new RecipientRepository(uow);
            recipientTabRepository = new RecipientTabRepository(uow);

            // I'm extracting the repository calls and mapping
            // code into this GetEnvelopeBody() so other methods
            // that have their own Unit of Work can use it.
            // This is to avoid multiple Unit of Work sessions?
            // from colliding.
            var envelope = GetEnvelopeBody(id);

            uow.SaveChanges();

            return envelope;
        }
    }

    private Envelope GetEnvelopeBody(int id)
    {
        // repository calls and object mapping code goes here
    }

    public void SaveEnvelope(Envelope envelope)
    {
        using (var uow = UnitOfWorkFactory.Create())
        {
            envelopeRepository = new EnvelopeRepository(uow);
            recipientRepository = new RecipientRepository(uow);
            recipientTabRepository = new RecipientTabRepository(uow);

            SaveEnvelopeBody(envelope);

            uow.SaveChanges();
        }
    }

    private void SaveEnvelopeBody(Envelope envelope)
    {
        CleanEnvelope(envelope);

        // repository calls and object mapping code goes here
    }

    private void CleanEnvelope(Envelope newEnvelope)
    {
        var oldEnvelope = this.GetEnvelopeBody(newEnvelope.Id);
        // Do other fancy stuff ...
    }
}
</code>```

答:
The major problem I see is that your EnvelopeService class is not threadsafe.

Imagine two threads using a single instance of EnvelopeService.  Thread 1 calls GetEnvelope which creates a UnitOfWork. At the same time Thread 2 calls SaveEnvelope which creates a second UnitOfWork.  Whether those two operations are carried out using the appropriate UnitOfWork is not guaranteed.

This is because you're effectively storing your UnitOfWork at the class level (in your 3 repository instances) and then using it in subsequent helper method calls.  This is shared state and is unsafe.

A safer approach would be to remove the shared state:

```<code>public class EnvelopeService
{
        public Envelope GetEnvelope(int id)
        {
                using (var uow = UnitOfWorkFactory.Create())
                {
                        var envelopeRepository = new EnvelopeRepository(uow);
                        var recipientRepository = new RecipientRepository(uow);
                        var recipientTabRepository = new RecipientTabRepository(uow);

                        var envelope = GetEnvelopeBody(id, envelopeRepository, recipientRepository, recipientTabRepository);

                        uow.SaveChanges();

                        return envelope;
                }
        }

        private Envelope GetEnvelopeBody(
            int id,
            EnvelopeRepository envelopeRepository,
            RecipientRepository recipientRepository,
            RecipientTabRepository recipientTabRepository)
        {
                // repository calls and object mapping code goes here
        }

        public void SaveEnvelope(Envelope envelope)
        {
                using (var uow = UnitOfWorkFactory.Create())
                {
                        var envelopeRepository = new EnvelopeRepository(uow);
                        var recipientRepository = new RecipientRepository(uow);
                        var recipientTabRepository = new RecipientTabRepository(uow);

                        SaveEnvelopeBody(envelope, envelopeRepository, recipientRepository, recipientTabRepository);

                        uow.SaveChanges();
                }
        }

        private void SaveEnvelopeBody(
            Envelope envelope,
            EnvelopeRepository envelopeRepository,
            RecipientRepository recipientRepository,
            RecipientTabRepository recipientTabRepository)
        {
                CleanEnvelope(envelope, envelopeRepository, recipientRepository, recipientTabRepository);

                // repository calls and object mapping code goes here
        }

        private void CleanEnvelope(
            Envelope newEnvelope,
            EnvelopeRepository envelopeRepository,
            RecipientRepository recipientRepository,
            RecipientTabRepository recipientTabRepository)
        {
                var oldEnvelope = this.GetEnvelopeBody(newEnvelope.Id, envelopeRepository, recipientRepository, recipientTabRepository);
                // Do other fancy stuff ...
        }
}
</code>```

Notice that the repositories holding your your UnitOfWork are now passed into your helper methods as dependencies.

Whether you should be newing your repositories is another potential point of concern.  It might make testing the EnvelopeService class difficult.  Consider using a Factory to get your repository instances instead.  Then again, that might be overkill.  It really depends on your situation.

Body:
The major problem I see is that your EnvelopeService class is not threadsafe.

Imagine two threads using a single instance of EnvelopeService.  Thread 1 calls GetEnvelope which creates a UnitOfWork. At the same time Thread 2 calls SaveEnvelope which creates a second UnitOfWork.  Whether those two operations are carried out using the appropriate UnitOfWork is not guaranteed.

This is because you're effectively storing your UnitOfWork at the class level (in your 3 repository instances) and then using it in subsequent helper method calls.  This is shared state and is unsafe.

A safer approach would be to remove the shared state:

public class EnvelopeService
{
        public Envelope GetEnvelope(int id)
        {
                using (var uow = UnitOfWorkFactory.Create())
                {
                        var envelopeRepository = new EnvelopeRepository(uow);
                        var recipientRepository = new RecipientRepository(uow);
                        var recipientTabRepository = new RecipientTabRepository(uow);

                        var envelope = GetEnvelopeBody(id, envelopeRepository, recipientRepository, recipientTabRepository);

                        uow.SaveChanges();

                        return envelope;
                }
        }

        private Envelope GetEnvelopeBody(
            int id,
            EnvelopeRepository envelopeRepository,
            RecipientRepository recipientRepository,
            RecipientTabRepository recipientTabRepository)
        {
                // repository calls and object mapping code goes here
        }

        public void SaveEnvelope(Envelope envelope)
        {
                using (var uow = UnitOfWorkFactory.Create())
                {
                        var envelopeRepository = new EnvelopeRepository(uow);
                        var recipientRepository = new RecipientRepository(uow);
                        var recipientTabRepository = new RecipientTabRepository(uow);

                        SaveEnvelopeBody(envelope, envelopeRepository, recipientRepository, recipientTabRepository);

                        uow.SaveChanges();
                }
        }

        private void SaveEnvelopeBody(
            Envelope envelope,
            EnvelopeRepository envelopeRepository,
            RecipientRepository recipientRepository,
            RecipientTabRepository recipientTabRepository)
        {
                CleanEnvelope(envelope, envelopeRepository, recipientRepository, recipientTabRepository);

                // repository calls and object mapping code goes here
        }

        private void CleanEnvelope(
            Envelope newEnvelope,
            EnvelopeRepository envelopeRepository,
            RecipientRepository recipientRepository,
            RecipientTabRepository recipientTabRepository)
        {
                var oldEnvelope = this.GetEnvelopeBody(newEnvelope.Id, envelopeRepository, recipientRepository, recipientTabRepository);
                // Do other fancy stuff ...
        }
}

Notice that the repositories holding your your UnitOfWork are now passed into your helper methods as dependencies.

Whether you should be newing your repositories is another potential point of concern.  It might make testing the EnvelopeService class difficult.  Consider using a Factory to get your repository instances instead.  Then again, that might be overkill.  It really depends on your situation.


答:
Your question really depends on quite a few things: Code Base complexity, change complexity, people working on code base, people affected by your change, etc.

I personally avoid committing unfinished business, even if that means not committing for a few days (Many people will disagree here). And it certainly is good to stay "connected".

So in light of all that, I would say: If the task is too big to be accomplished before the end of the working day, then maybe the problem could be split into smaller problems, thus tasks, and each of these can be committed separately in a non-destructive manner.

Here are some other points which I like to remind myself when committing (they are just guidelines and do not apply everytime):

Commit working code - even if you have to make several separate commits (large code base, multiple working copies, etc) make sure you commit in such an order, which will not break the codebase, if someone was to update halfway through your commits.

Committing should NOT be the last thing you do - Avoid committing at the end of the day, without checking/testing/running/whatever. This, more often then not is a bad decision. You are tired, your mind is focused on what you are working on and doesn't always see the big picture... especially bad when working with other people, who will be affected by the change... Better commit in the morning, yesterdays work.

If you have multiple logical changes in a single file, commit them separately (when possible). You don't want to confuse people when they look back through your commits, especially when it is a complex one, involving many files, etc.

Break the big problem into smaller problems - It is far better and clearer to have  a few smaller commits with an encapsulated logic and a concise commit message (perhaps even linking to other related commits), than one huge commit with a message resembling an article.

Avoid committing commented-out code, avoid commenting out code and committing - that is why you use version control in the first place... If something is so far from being finished, that you need to comment it out, so that the project can build - DON'T commit it... If something needs to be removed from the code base, DON'T comment it out, but remove it.


答:
You have two things working against you:

First is a race condition, where the outcome of your sync operation depends on the timing of Word and that of your sync process.  (If you're using something event-driven, the timing is a bit more predictable, but it just means that you're going to delete your history all the time instead of just sometimes as you would if you're polling.)  As you observed, there's no way to know how much time will elapse between steps 2 and 3, so waiting to see if the file returns would create another race condition.

Second is uncertainty about whether a file you see as deleted will reappear because the OS can't predict what an application will do in the future.  It also can't tell you what application deleted a file, which you might be able to use to draw a reasonable conclusion that the file might reappear.

If Word actually saves files in the way Microsoft describes, that's a flaw in the implementation.  Windows has API calls to do atomic renames that would make the process go like this:

Create temporary file ~wrdxxxx.tmp

Atomically rename ~wrdxxxx.tmp to Example.doc

Because step 2 is atomic, your sync program would never see that Example.doc disappeared, just that its attributes or content changed.

Word's behavior isn't something you can change, so waiting is really your only option.

If the goal is not to lose version history, it's better to make deletions provisional and wait a fairly long time (say, 30 seconds) to make them permanent.  This will prevent most -- but not all -- of the problems caused by not knowing how long a save takes.  Obviously, it's possible for a save to take that long, but it's probably rare.  The bigger pitfall is that a long enough provisional period will treat a delete/create sequence done by a human in that time as a version change rather than what it actually was.  This doesn't reflect the reality of what happened, but it will preserve the version history.

The question only you can answer is whether having reality distorted like that on relatively rare occasions is acceptable in the face on not having your synchronizer blow away the history.

Title: How to distinguish whether a file is being saved or deleted? ("Save" in MS Word deletes then re-creates)

Body:
I maintain a tool that syncs files between a client computer and a document management server (using the CMIS protocol). Versions history (on the CMIS server) is important.

When saving a document locally, MS Word:

Writes to a temp file ~wrdxxxx.tmp

Deletes the original file Example.doc

Renames ~wrdxxxx.tmp to Example.doc

PROBLEM: At step 2, my sync tool deletes the file on the server, loosing all versions history.

QUESTION: From the point of view of my sync tool, is there a way to know whether the file has really been deleted, or whether it is just being saved?

Notes:

Waiting is probably not a good solution, as I can't be sure how much time steps 2 and 3 take.

Cheking for the presence of ~wrdxxxx.tmp files does not work when several documents are being edited in the same folder at the same time.

The tool works like Dropbox: Users don't have to "commit" changes, files are synchronized automatically as soon as possible.


问:
What is the "->" symbol called?
I have seen the -> operator/symbol in Java 8 predicates recently and wondered what its name is. I know that it is used in lambda expressions, but I know that the symbol for lambda is λ, so that's not it.

Any ideas?

答:
It's called arrow token

Here on wiki, this article  and that article or even on java website

Many years ago, before there were any computers, the logician Alonzo Church wanted to formalize what it means for a mathematical function to be effectively computable. (Curiously, there are functions that are known to exist, but nobody knows how to compute their values.) He used the Greek letter lambda (λ) to mark parameters.

Why the letter λ? Did Church run out of other letters of the alphabet? Actually, the venerable Principia Mathematica used the ˆ accent to denote free variables, which inspired Church to use an uppercase lambda (Λ) for parameters. But in the end, he switched to the lowercase version. Ever since, an expression with parameter variables has been called a "lambda expression."

Reference here

Title: What is the "->" symbol called?


答:
I say that not only you may commit unfinished changes when you need to stop working on it - you probably should do it. When you have to leave a task for a long time, always assume that you are going to "context-switch" by the time you're back. Now, if you are just going to make a coffee - or even take a launch break - you should be fine, but if you leave the office or switch to another task by the time you went back to the original task you'll have to make an effort to recall where exactly you have stopped.

This is where committing can help you - commit everything, write in the head "Temp" or "WIP" or whatever to indicate that it's not a fully baked commit, and write in the body notes to yourself regarding what were you doing, what were you planning to do next, what are the current unresolved problems you are encountering - whatever you think you'll need to quickly get back to that task.

Source control is not just for not losing your code - it's also for not losing track of your code.

Of course - never push these commits to one of the main shared branches(master, develop, release-### - whatever branches used by all developers). But if it's a private branch - go crazy. You can always force-push to it - you are the only one working on it.

And don't forget to amend these commits once you are done - you don't want all these temporary WIP commits laying in your graph...


答:
Commit away. Commit as often as possible. Commit when its incomplete, commit when its finished. It really doesn't matter. I even will commit and push to remote when I get up for a 1 hour meeting or lunch even...

The catch is you need to be in your own branch (one that no one else will be pulling from). This should be a part of your normal development cycle anyways and is the easiest way to keep git history clean. Before your merge into the parent development tree, clean up your history by squashing commits. It takes almost no extra time and really allows you to pick and choose what commits make it into what commits/pushes.

I will often work on several different bugs before squashing commits, rebasing on parent remote branch and merging with parent remote branch. My commit messages tell me when i've finished with one bug and have moved onto another. I will squash down the commits to 'single' commits that contain each 'fix' in one commit and merge them upstream. Commiting often and with good messages when necessary will allow you to not worry about semantics and get a move on with coding.


问:
Is it okay to have objects that cast themselves, even if it pollutes the API of their subclasses?
I have a base class, Base.  It has two subclasses, Sub1 and Sub2.  Each subclass has some additional methods.  For example, Sub1 has Sandwich makeASandwich(Ingredients... ingredients), and Sub2 has boolean contactAliens(Frequency onFrequency).

Since these methods take different parameters and do entirely different things, they're completely incompatible, and I can't just use polymorphism to solve this problem.

Base provides most of the functionality, and I have a large collection of Base objects.  However, all Base objects are either a Sub1 or a Sub2, and sometimes I need to know which they are.

It seems like a bad idea to do the following:

```<code>for (Base base : bases) {
    if (base instanceof Sub1) {
        ((Sub1) base).makeASandwich(getRandomIngredients());
        // ... etc.
    } else { // must be Sub2
        ((Sub2) base).contactAliens(getFrequency());
        // ... etc.
    }
}
</code>```

So I came up with a strategy to avoid this without casting.  Base now has these methods:

```<code>boolean isSub1();
Sub1 asSub1();
Sub2 asSub2();
</code>```

And of course, Sub1 implements these methods as

```<code>boolean isSub1() { return true; }
Sub1 asSub1();   { return this; }
Sub2 asSub2();   { throw new IllegalStateException(); }
</code>```

And Sub2 implements them in the opposite way.

Unfortunately, now Sub1 and Sub2 have these methods in their own API.  So I can do this, for example, on Sub1.

```<code>/** no need to use this if object is known to be Sub1 */
@Deprecated
boolean isSub1() { return true; }

/** no need to use this if object is known to be Sub1 */
@Deprecated
Sub1 asSub1();   { return this; }

/** no need to use this if object is known to be Sub1 */
@Deprecated
Sub2 asSub2();   { throw new IllegalStateException(); }
</code>```

This way, if the object is known to be only a Base, these methods are un-deprecated, and can be used to "cast" itself to a different type so I can invoke the subclass's methods on it.  This seems elegant to me in a way, but on the other hand, I'm kind of abusing Deprecated annotations as a way to "remove" methods from a class.

Since a Sub1 instance really is a Base, it does make sense to use inheritance rather than encapsulation.  Is what I'm doing good?  Is there a better way to solve this problem?

答:
How about if you have your subclasses implement one or more interfaces that define what they can do ? Something like this:

```<code>interface SandwichCook
{
    public void makeASandwich(String[] ingredients);
}

interface AlienRadioSignalAwarable
{
    public void contactAliens(int frequency);

}
</code>```

Then your classes will look like this:

```<code>class Sub1 extends Base implements SandwichCook
{
    public void makeASandwich(String[] ingredients)
    {
        //some code here
    }
}

class Sub2 extends Base implements AlienRadioSignalAwarable
{
    public void contactAliens(int frequency)
    {
        //some code here
    }
}
</code>```

And your for-loop will become:

```<code>for (Base base : bases) {
    if (base instanceof SandwichCook) {
        base.makeASandwich(getRandomIngredients());
    } else if (base instanceof AlienRadioSignalAwarable) {
        base.contactAliens(getFrequency());
    }
}
</code>```

Two major advantages to this approach:

no casting involved

you can have each subclass implement as many interfaces as you want, which does provide some flexibility for future changes.

PS: Sorry for the names of the interfaces, I couldn't think of anything cooler at that particular moment :D .

Body:
How about if you have your subclasses implement one or more interfaces that define what they can do ? Something like this:

interface SandwichCook
{
    public void makeASandwich(String[] ingredients);
}

interface AlienRadioSignalAwarable
{
    public void contactAliens(int frequency);

}

Then your classes will look like this:

class Sub1 extends Base implements SandwichCook
{
    public void makeASandwich(String[] ingredients)
    {
        //some code here
    }
}

class Sub2 extends Base implements AlienRadioSignalAwarable
{
    public void contactAliens(int frequency)
    {
        //some code here
    }
}

And your for-loop will become:

for (Base base : bases) {
    if (base instanceof SandwichCook) {
        base.makeASandwich(getRandomIngredients());
    } else if (base instanceof AlienRadioSignalAwarable) {
        base.contactAliens(getFrequency());
    }
}

Two major advantages to this approach:

no casting involved

you can have each subclass implement as many interfaces as you want, which does provide some flexibility for future changes.

PS: Sorry for the names of the interfaces, I couldn't think of anything cooler at that particular moment :D .


答:
From what I've observed, different people vary greatly in their commit frequency. Some people make frequent tiny commits, and others make rare big commits. I've seen people not commit until they finished several weeks of work, resulting in one gigantic commit that touches hundreds of files.

IMHO, huge commits are a bad idea. I like to think of commits as kind-of atomic units of work. I tend to make frequent small commits.

For example, if I rename a file, that probably means the filename has to change, the project file has to be updated to point to the new path, the name of the code inside the file probably changes, and therefore any code that refers to this must also change. That's quite a lot of changes, but conceptually I've only done one thing: rename this file. So I would make all of that stuff into one commit. So that anybody looking at the history can see that all thus stuff happened, but semantically it's just one trivial operation.

I often go to the point of changing a whole bunch of stuff, and once it compiles, actually going through the commit GUI and picking the changes apart into conceptually separate sets. So if the code wasn't quite working, and I try a bunch of stuff, and it turns out there were three unrelated problems that were stopping it working, I'll make that into three separate commits.

It's best if you can commit stuff at points where the code still works. But I don't always hold rigidly with that. Perhaps changing this interface and the code that uses it also breaks 3,000 unit tests. In that case, I probably commit the related changes to the code, and fix the unit tests in a later commit.

Another thing worth keeping in mind: Committing stuff isn't just about "saving your work". It's also a "safe point" to come back to if you end up screwing the code up so badly that it doesn't seem to work anymore, and you just want to revert it all to the last working point. If you have 6 weeks of uncommitted changes (!!) then this is very, very awkward to do. For this reason if nothing else, commit often. (But try to keep it as units that can have a meaningful commit message.)