问:
Mail Server Caching
I'm currently working on a web mail client. When a user logs in, I'm fetching all the mails from the INBOX from the beginning of time. As expected this is pretty darn slow. I'm planning to implement some sort of a filtering/caching technique and was looking for some ideas.

If I fetch all the message numbers, trim them and sort them in a descending order, will I have messages from the the last message received to the first? Also, would it be preferable to store mails in a intermediate database and fetch them from there?

答:
Why don't you reverse the order of your retrieval?  Instead of starting at the beginning of time, start at the end of time (ie. most recent) and then go back in time.

Users looking at mail want to see what's most recently come in, they don't care as much about what was sent to them last week or even last year.

Another option to consider is an skip-take fetch process.  Instead of waiting for everything to be fetched from the database.

Retrieve the 20 most recent messages

Return those to the client

Get the next 20 most recent messages

Return those to the client

Repeat as needed

Title: Mail Server Caching


问:
What is the point of a Gantt Chart, and will it help me?
My (non-technical) colleague has threatened me with a Gantt chart for a new project that we are currently planning.  What is this likely to provide for us, and will it be a helpful tool?</p>

答:
Gantt chart software allows complex inter dependencies to be analysed and to predict the effects of overruns and delays.

However, for most software projects, there are few inter dependencies and external inputs, so the key to prediction is knowing what the right multiplier to use when the software team say it will take 3 weeks.

ContentLicense: CC BY-SA 2.5


问:
Where should the ACL handler be called in a MVC architecture?
Thinking about Access Control Lists bound to a web MVC architecture, I have a doubt on where the verification should be done.

Within Models? Controllers? FrontController?

Imagine a multiple module web application (like a website). I have a public site and a restricted admin zone.

All public site pages are acessible by anyone.

The restricted admin area is only accessed by an authenticated user.

There are some access levels for the users, such as root, admin and regular user.

I gave this some thought during my lunch time today and some ideas came out.

First, I needed to ask myself this question:

Is access control part of business logic?

After some time, I figure out that the answer should be no for most cases. Normally, for the situation I described, the business logic of the public area is about the same of the restricted one. When is not exact the same, what I normally do is to create a superset of both business logic rules, that contains all logic needed. So, even if there are several modules in my application, I normally have only one model layer.

Doing the ACL within my controllers leads to code duplication, since I'd have to check it everytime I'd need. Also, I'd get a high coupling between controllers and the ACL component.

Thinking about putting it inside FrontController seems to be the right approach. In deed, my initial thought was to put the ACL handler as a dependency for the FrontController.

This approach would have controller methods (actions) as resources of the ACL, creating roles for my users.

Some pseudo-code (mixing Java, C#, PHP):

```<code>aclHandler = new DefaultAcl();
aclHandler.addRole('none'); // not authenticated
aclHandler.addRole('user');
aclHandler.addRole('admin', extend='user');
aclHandler.addRole('root', extend='admin');

aclHandler.addUser('john', 'root');
aclHandler.addUser('mary', 'admin');
aclHandler.addUser('jane', 'user');

aclHandler.addResource('admin.content.create'); // MODULE.CONTROLLER.ACTION
aclHandler.addResource('admin.content.view');
aclHandler.addResource('admin.content.edit');
aclHandler.addResource('admin.content.remove');

aclHandler.addResource('public.content.view');

aclHandler.allow('*', 'public.*');

aclHandler.deny('*', 'admin.*'); // deny from all
aclHandler.allow('user', 'admin.content.view'); // allow user to view content
aclHandler.allow('admin', 'admin.content.{edit,create}'); // allow admin to edit and create content
aclHandler.allow('root', '*'); // root can do anything
</code>```

This way, my FrontController would have something like:

```<code>class DefaultFrontController implements FrontControllerInterface {
    AclInterface acl {get};
    User currentUser {get;set};
    public DefaultFrontController(AclInterface acl, User user) {
        this.acl = acl;
        this.currentUser = user;
        // ...
    }

    public void dispatch(ControllerRequest request, ControllerResponse response) {
        try {
            this.acl.checkPrivileges(request.resource, this.currentUser);
        } catch (AclException e) {
            this.forbiddenAccessCallback(request, response, this.acl, this.currentUser);
            return;
        }

        // continue impl...
    }
}

fc = new FrontController(aclHandler, new User(name='John', role='root'));
fc.dispatch(...);  // ...
</code>```

This implementation makes an ACL component a mandatory parameter for the FrontController constructor, so, now it's part of its state. This could be a problem when I don't need an ACL, but can be overpassed by creating a mock implementation of ACL component, like AllowFromAllAcl, that would allow any users to do anything.

Any ideas? Corrections? Suggestions?

答:
Generally speaking, this sort of thing is built into MVC.

Adding an "Authorize" attribute to a controller class, restricts access to all methods of the controller to "Must be logged in". Adding Authorize(Roles="Admin") to specific controller methods further restricts access to that route to an authenticated user with Admin roles assigned to them.

There are a couple of built-in authentication mechanisms in MVC, including windows Forms, Basic, etc, as well as a few that can be easily enabled with nuget packages such as Oauth etc.

If you need a more custom authentication method, you can derive from the Authorize attribute, and add it to your global configuration. Another method I've used in the past when working with a custom REST api type scenario, is to add an "ActionFilter" that executes before calling the route on the controller.

More information:
http://msdn.microsoft.com/en-us/library/ff398049(v=vs.100).aspx
http://www.dotnetcurry.com/showarticle.aspx?ID=957

Related Stack Overflow:
https://stackoverflow.com/questions/18594316/custom-authentication-and-asp-net-mvc

Plenty of other information out there, just do some googling.

Around where to put your actual authentication logic, generally you will need to query users and roles from somewhere, if a custom scenario, add this logic to your data access layer, add sort of an "AuthorizationService" to your business logic, and consume it through your custom authorize attribute/filter.

ContentLicense: CC BY-SA 3.0


问:
Learning python functions and parameters
```<code>def printMax(a, b):
   if a > b:
   print(a, 'is maximum')
   elif a == b:
   print(a, 'is equal to', b)
   else:
   print(b, 'is maximum')

printMax(3, 4) # directly give literal values
x = 5
y = 7
printMax(x, y) # give variables as arguments
</code>```

I'm learning python via the byte of python book, and the author uses this example to introduce us to functions. When the author calls the function printMax, he does not use quotation for the numbers 3,4 i.e. he does not use printMax("3","4") which I thought was fine.

However, later on he defines a function like so

```<code>def say(message, times = 1)
   print(message * times)

say("hello", 3)
</code>```

why does he use the quotations for the message (i.e. why does he use say("hello", 3) instead of say(hello, 3)? How does python notice the difference?

答:
In your example, printMax is supposed to received integers. In python, and in many other language, literal integer are not expressed using quotation.

Consider this:

```<code>printMax(3, 4); ## ouput 4 is max
printMax(35, 4); ## output 35 is max
printMax("35", "4"); ## output 4 is max
</code>```

My last call to printMax uses quotation, and therefore the argument are now strings. If you do string comparaison, "4" > "35" is true.

He uses say("hello", 3) because hello is a string here, therefore it needs quotation. If he did use say(hello, 3) python would have complained about undefined variable.

Body:
In your example, printMax is supposed to received integers. In python, and in many other language, literal integer are not expressed using quotation.

Consider this:

printMax(3, 4); ## ouput 4 is max
printMax(35, 4); ## output 35 is max
printMax("35", "4"); ## output 4 is max

My last call to printMax uses quotation, and therefore the argument are now strings. If you do string comparaison, "4" > "35" is true.

He uses say("hello", 3) because hello is a string here, therefore it needs quotation. If he did use say(hello, 3) python would have complained about undefined variable.


答:
Python features a parser for figuring this out. The quotation marks tell Python that this object is a string, which is a different kind of object than an number. If you don't use quotation marks, Python will think it is a variable.

(Under the hood, all functions are code objects which get assigned to variables.)

Title: Learning python functions and parameters

Body:
```<code>def printMax(a, b):
   if a > b:
   print(a, 'is maximum')
   elif a == b:
   print(a, 'is equal to', b)
   else:
   print(b, 'is maximum')

printMax(3, 4) # directly give literal values
x = 5
y = 7
printMax(x, y) # give variables as arguments
</code>```

I'm learning python via the byte of python book, and the author uses this example to introduce us to functions. When the author calls the function printMax, he does not use quotation for the numbers 3,4 i.e. he does not use printMax("3","4") which I thought was fine.

However, later on he defines a function like so

```<code>def say(message, times = 1)
   print(message * times)

say("hello", 3)
</code>```

why does he use the quotations for the message (i.e. why does he use say("hello", 3) instead of say(hello, 3)? How does python notice the difference?


问:
Clarification about Polymorphism / Inheritance
I am trying to better my understanding of  polymorphism.

Say I have a base class called baseClass with one method called foo() and I have three derived classes called derived1 , derived2 and derived3 which all override the and implement their own versions of the foo() method.

If I have an array of baseClass objects can it contain objects that are derived from that base class like so:

```<code>baseClassArray: [ derivedObj1, derivedObj2, derivedObj3];
</code>```

Also if I pull an object out of this array and called the foo() method would it call the method defined in baseClass or the method defined in the respective derived class?

Or does this depend on the programming language this is implemented in?

答: The virtual method called always depends on type of concrete instance in memory and never on how this instance is accessed or type of variable the instance is accessed from. The type of variable just tells compiler what classes and it's subclasses can be saved and what virtual methods can be called. But what method is actually called is only known from memory at runtime.</p>


答:
This should work, but is language specific. what you are referring to is a "upcast", taking the derived objects and upcasting them back to the base class. Depending on your language you will have to perform the cast ex:

derived1 obj1 = new derived1();

baseClass base[10];

base[0] = (baseClass)obj1;

when you call the foo() method the baseClass foo() will be used unless you perform and additional "downcast"  ex:

derived1 sameobj1 = (derived1)base[0];

after performing the downcast the foo() method for derived1 will be called. some language can use the "typeOf" comparison operator instead of upcasting and downcasting ex:

if( obj1 typeOf baseClass)

base[0] = obj1; // no casting necessary

then when you pull them out of the array base just call the foo() and the foo() for each derived class will be called.

foreach( obj in base)

obj.foo()

this will call the foo() method for each derived class.

Title: Clarification about Polymorphism / Inheritance

Body:
I am trying to better my understanding of  polymorphism.

Say I have a base class called baseClass with one method called foo() and I have three derived classes called derived1 , derived2 and derived3 which all override the and implement their own versions of the foo() method.

If I have an array of baseClass objects can it contain objects that are derived from that base class like so:

```<code>baseClassArray: [ derivedObj1, derivedObj2, derivedObj3];
</code>```

Also if I pull an object out of this array and called the foo() method would it call the method defined in baseClass or the method defined in the respective derived class?

Or does this depend on the programming language this is implemented in?


答:
The actual method that is called will be determined at run time depending what the type of the object is. If you have an array of objects of type baseClass (which can include inherited types) the method that is called will be the foo() method of whichever type the object is.

So the objects that are of type baseClass will have the base class implementation of foo() called. If your objects are one of the derived types and the derived objects override the foo() method this will be called. If the derived objects do not override the foo() method then the base class method foo() will be called.


问:
In functional programming how does one achieve modularity through mathematical laws?
I read in this question that functional programmers tend to use mathematical proofs to ensure that their program is working correctly.  This sounds alot easier and faster than unit testing, but coming from an OOP / Unit Testing background I've never seen it done.

Can you explain it to me and give me an example?

答:
A proof is much harder in the OOP world because of side effects, unrestricted inheritance, and null being a member of every type. Most proofs rely on an induction principle to show that you've covered every possibility, and all 3 of those things make that harder to prove.

Let's say we're implementing binary trees that contain integer values (for the sake of keeping the syntax simpler, I won't bring generic programming into this, though it wouldn't change anything.) In Standard ML, I would define that like this:

datatype tree = Empty | Node of (tree * int * tree)

This introduces a new type called tree whose values can come in exactly two varieties (or classes, not to be confused with the OOP concept of a class) - an Empty value which carries no information, and Node values which carry a 3-tuple whose first and last elements are trees and whose middle element is an int. The closest approximation to this declaration in OOP would look like this:

```<code>public class Tree {
    private Tree() {} // Prevent external subclassing

    public static final class Empty extends Tree {}

    public static final class Node extends Tree {
        public final Tree leftChild;
        public final int value;
        public final Tree rightChild;

        public Node(Tree leftChild, int value, Tree rightChild) {
            this.leftChild = leftChild;
            this.value = value;
            this.rightChild = rightChild;
        }
    }
}
</code>```

With the caveat that variables of type Tree can never be null.

Now let's write a function to calculate the height (or depth) of the tree, and assume we have access to a max function that returns the larger of two numbers:

```<code>fun height(Empty) =
        0
 |  height(Node (leftChild, value, rightChild)) =
        1 + max( height(leftChild), height(rightChild) )
</code>```

We've defined the height function by cases - there's one definition for Empty trees and one definition for Node trees. The compiler knows how many classes of trees exist and would issue a warning if you didn't define both cases. The expression Node (leftChild, value, rightChild) in the function signature binds the values of the 3-tuple to the variables leftChild, value, and rightChild respectively so we can refer to them in the function definition. It's akin to having declared local variables like this in an OOP language:

```<code>Tree leftChild = tuple.getFirst();
int value = tuple.getSecond();
Tree rightChild = tuple.getThird();
</code>```

How can we prove we've implemented height correctly? We can use structural induction, which consists of:
1. Prove that height is correct in the base case(s) of our tree type (Empty)
2. Assuming that recursive calls to height are correct, prove that height is correct for the non-base case(s) (when the tree is actually a Node).

For step 1, we can see that the function always returns 0 when the argument is an Empty tree. This is correct by definition of the height of a tree.

For step 2, the function returns 1 + max( height(leftChild), height(rightChild) ). Assuming that the recursive calls truly do return the height of the children, we can see that this is also correct.

And that completes the proof. Steps 1 and 2 combined exhaust all the possibilities. Note, however, that we have no mutation, no nulls, and there are exactly two varieties of trees. Take away those three conditions and the proof quickly becomes more complicated, if not impractical.

EDIT: Since this answer has risen to the top, I'd like to add a less trivial example of a proof and cover structural induction a bit more thoroughly. Above we proved that if height returns, its return value is correct. We haven't proved it always returns a value, though. We can use structural induction to prove this, too (or any other property.) Again, during step 2, we're allowed to assume the property holds of the recursive calls as long as the recursive calls all operate on a direct child of the tree.

A function can fail to return a value in two situations: if it throws an exception, and if it loops forever. First let's prove that if no exceptions are thrown, the function terminates:

Prove that (if no exceptions are thrown) the function terminates for the base cases (Empty). Since we unconditionally return 0, it terminates.

Prove that the function terminates in the non-base cases (Node). There's three function calls here: +, max, and height. We know that + and max terminate because they're part of the language's standard library and they're defined that way. As mentioned earlier, we're allowed to assume the property we're trying to prove is true on recursive calls as long as they operate on immediate subtrees, so calls to height terminate too.

That concludes the proof. Note that you wouldn't be able to prove termination with a unit test. Now all that's left is to show that height doesn't throw exceptions.

Prove that height doesn't throw exceptions on the base case (Empty). Returning 0 can't throw an exception, so we're done.

Prove that height doesn't throw exception on the non-base case (Node). Assume once again that we know + and max don't throw exceptions. And structural induction allows us to assume the recursive calls won't throw either (because the operate on the tree's immediate children.) But wait! This function is recursive, but not tail recursive. We could blow the stack! Our attempted proof has uncovered a bug. We can fix it by changing height to be tail recursive.

I hope this shows proofs don't have to be scary or complicated. In fact, whenever you write code, you've informally constructed a proof in your head (otherwise, you wouldn't be convinced you just implemented the function.) By avoiding null, unnecessary mutation, and unrestricted inheritance you can prove your intuition is correct fairly easily. These restrictions are not as harsh as you might think:

null is a language flaw and doing away with it is unconditionally good.

Mutation is sometimes unavoidable and necessary, but it's needed a lot less often than you'd think - especially when you have persistent data structures.

As for having a finite number of classes (in the functional sense)/subclasses (in the OOP sense) vs an unlimited number of them, that's a subject too big for a single answer. Suffice to say there's a design trade off there - provability of correctness vs flexibility of extension.

Body:
A proof is much harder in the OOP world because of side effects, unrestricted inheritance, and null being a member of every type. Most proofs rely on an induction principle to show that you've covered every possibility, and all 3 of those things make that harder to prove.

Let's say we're implementing binary trees that contain integer values (for the sake of keeping the syntax simpler, I won't bring generic programming into this, though it wouldn't change anything.) In Standard ML, I would define that like this:

datatype tree = Empty | Node of (tree * int * tree)

This introduces a new type called tree whose values can come in exactly two varieties (or classes, not to be confused with the OOP concept of a class) - an Empty value which carries no information, and Node values which carry a 3-tuple whose first and last elements are trees and whose middle element is an int. The closest approximation to this declaration in OOP would look like this:

public class Tree {
    private Tree() {} // Prevent external subclassing

    public static final class Empty extends Tree {}

    public static final class Node extends Tree {
        public final Tree leftChild;
        public final int value;
        public final Tree rightChild;

        public Node(Tree leftChild, int value, Tree rightChild) {
            this.leftChild = leftChild;
            this.value = value;
            this.rightChild = rightChild;
        }
    }
}

With the caveat that variables of type Tree can never be null.

Now let's write a function to calculate the height (or depth) of the tree, and assume we have access to a max function that returns the larger of two numbers:

fun height(Empty) =
        0
 |  height(Node (leftChild, value, rightChild)) =
        1 + max( height(leftChild), height(rightChild) )

We've defined the height function by cases - there's one definition for Empty trees and one definition for Node trees. The compiler knows how many classes of trees exist and would issue a warning if you didn't define both cases. The expression Node (leftChild, value, rightChild) in the function signature binds the values of the 3-tuple to the variables leftChild, value, and rightChild respectively so we can refer to them in the function definition. It's akin to having declared local variables like this in an OOP language:

Tree leftChild = tuple.getFirst();
int value = tuple.getSecond();
Tree rightChild = tuple.getThird();

How can we prove we've implemented height correctly? We can use structural induction, which consists of:
1. Prove that height is correct in the base case(s) of our tree type (Empty)
2. Assuming that recursive calls to height are correct, prove that height is correct for the non-base case(s) (when the tree is actually a Node).

For step 1, we can see that the function always returns 0 when the argument is an Empty tree. This is correct by definition of the height of a tree.

For step 2, the function returns 1 + max( height(leftChild), height(rightChild) ). Assuming that the recursive calls truly do return the height of the children, we can see that this is also correct.

And that completes the proof. Steps 1 and 2 combined exhaust all the possibilities. Note, however, that we have no mutation, no nulls, and there are exactly two varieties of trees. Take away those three conditions and the proof quickly becomes more complicated, if not impractical.

EDIT: Since this answer has risen to the top, I'd like to add a less trivial example of a proof and cover structural induction a bit more thoroughly. Above we proved that if height returns, its return value is correct. We haven't proved it always returns a value, though. We can use structural induction to prove this, too (or any other property.) Again, during step 2, we're allowed to assume the property holds of the recursive calls as long as the recursive calls all operate on a direct child of the tree.

A function can fail to return a value in two situations: if it throws an exception, and if it loops forever. First let's prove that if no exceptions are thrown, the function terminates:

Prove that (if no exceptions are thrown) the function terminates for the base cases (Empty). Since we unconditionally return 0, it terminates.

Prove that the function terminates in the non-base cases (Node). There's three function calls here: +, max, and height. We know that + and max terminate because they're part of the language's standard library and they're defined that way. As mentioned earlier, we're allowed to assume the property we're trying to prove is true on recursive calls as long as they operate on immediate subtrees, so calls to height terminate too.

That concludes the proof. Note that you wouldn't be able to prove termination with a unit test. Now all that's left is to show that height doesn't throw exceptions.

Prove that height doesn't throw exceptions on the base case (Empty). Returning 0 can't throw an exception, so we're done.

Prove that height doesn't throw exception on the non-base case (Node). Assume once again that we know + and max don't throw exceptions. And structural induction allows us to assume the recursive calls won't throw either (because the operate on the tree's immediate children.) But wait! This function is recursive, but not tail recursive. We could blow the stack! Our attempted proof has uncovered a bug. We can fix it by changing height to be tail recursive.

I hope this shows proofs don't have to be scary or complicated. In fact, whenever you write code, you've informally constructed a proof in your head (otherwise, you wouldn't be convinced you just implemented the function.) By avoiding null, unnecessary mutation, and unrestricted inheritance you can prove your intuition is correct fairly easily. These restrictions are not as harsh as you might think:

null is a language flaw and doing away with it is unconditionally good.

Mutation is sometimes unavoidable and necessary, but it's needed a lot less often than you'd think - especially when you have persistent data structures.

As for having a finite number of classes (in the functional sense)/subclasses (in the OOP sense) vs an unlimited number of them, that's a subject too big for a single answer. Suffice to say there's a design trade off there - provability of correctness vs flexibility of extension.


答:
You're describing polymorphism. You're using the base class as the interface. So your example is like:

((BaseClass)baseClassArray[0]).foo()

or

((BaseClass)derivedObj1).foo()

The foo() method is defined by base class, but the implementation is in the subclass, at least in your example. In OO, if a subclass overrides a method, then that becomes the implementation that gets called.

Inheritance is a little different. Let's say you have a derivedObj4 which does not override foo(). Then you can call:

((SubClass)derivedObj4).foo()

which would first look in derivedObj4, see that foo() is not there, and then look to BaseClass for the implementation.

polymorphism can rely on inheritance, which makes it a little confusing.

The idea behind polymorphism is that the base class defines the methods, and the subclasses define the implementation. (Although they may still inherit the implementation.) In other words, the base class masks the subclass, but the subclass does the work.

The idea behind inheritance is that the subclass is the interface, but inherits the implementation from the base class, so it doesn't need to implement it. The subclass masks the base class, but the base class does the work.


答:
It is a lot easier to reason about code when everything is immutable. As a result, loops are more often written as recursion. In general, it's easier to verify correctness of a recursive solution. Often, such a solution will also read very similarly to a mathematical definition of the problem.

However, there is very little motivation to carry out an actual formal proof of correctness in most cases. Proofs are difficult, take a lot (human) time, and have a low ROI.

Some functional languages (esp. from the ML family) have extremely expressive type systems that can make much more complete guarantees that a C-style type system (but some ideas like generics have become common in mainstream languages as well). When a program passes a type check, this is a kind of automated proof. In some cases, this will be able to detect some errors (e.g. forgetting the base case in a recursion, or forgetting to handle certain cases in a pattern match).

On the other hand, these type systems have to be kept very limited in order to keep them decidable. So in a sense, we gain static guarantees by giving up flexibility – and these restrictions are a reason why complicated academic papers along the lines of “A monadic solution to a solved problem, in Haskell” exist.

I enjoy both very liberal languages, and very restricted languages, and both have their respective difficulties.  But it's not the case that one would be “better”, each is just more convenient for a different kind of task.

Then it has to be pointed out that proofs and unit testing are not interchangeable. They both allow us to put bounds on the correctness of the program:

Testing puts an upper bound on correctness: If a test fails, the program is incorrect, if no tests fail, we are certain that the program will handle the tested cases, but there may still be undiscovered bugs.

```<code>int factorial(int n) {
  if (n <= 1) return 1;
  if (n == 2) return 2;
  if (n == 3) return 6;
  return -1;
}

assert(factorial(0) == 1);
assert(factorial(1) == 1);
assert(factorial(3) == 6);
// oops, we forgot to test that it handles n > 3…
</code>```

Proofs put a lower bound on correctness: It may be impossible to prove certain properties. For example, it may be easy to prove that a function always returns a number (that's what type systems do). But it may be impossible to prove that the number will always be < 10.

```<code>int factorial(int n) {
  return n;  // FIXME this is just a placeholder to make it compile
}

// type system says this will be OK…
</code>```

Title: In functional programming how does one achieve modularity through mathematical laws?

Body:
I read in this question that functional programmers tend to use mathematical proofs to ensure that their program is working correctly.  This sounds alot easier and faster than unit testing, but coming from an OOP / Unit Testing background I've never seen it done.

Can you explain it to me and give me an example?

Body:
It is a lot easier to reason about code when everything is immutable. As a result, loops are more often written as recursion. In general, it's easier to verify correctness of a recursive solution. Often, such a solution will also read very similarly to a mathematical definition of the problem.

However, there is very little motivation to carry out an actual formal proof of correctness in most cases. Proofs are difficult, take a lot (human) time, and have a low ROI.

Some functional languages (esp. from the ML family) have extremely expressive type systems that can make much more complete guarantees that a C-style type system (but some ideas like generics have become common in mainstream languages as well). When a program passes a type check, this is a kind of automated proof. In some cases, this will be able to detect some errors (e.g. forgetting the base case in a recursion, or forgetting to handle certain cases in a pattern match).

On the other hand, these type systems have to be kept very limited in order to keep them decidable. So in a sense, we gain static guarantees by giving up flexibility – and these restrictions are a reason why complicated academic papers along the lines of “A monadic solution to a solved problem, in Haskell” exist.

I enjoy both very liberal languages, and very restricted languages, and both have their respective difficulties.  But it's not the case that one would be “better”, each is just more convenient for a different kind of task.

Then it has to be pointed out that proofs and unit testing are not interchangeable. They both allow us to put bounds on the correctness of the program:

Testing puts an upper bound on correctness: If a test fails, the program is incorrect, if no tests fail, we are certain that the program will handle the tested cases, but there may still be undiscovered bugs.

int factorial(int n) {
  if (n <= 1) return 1;
  if (n == 2) return 2;
  if (n == 3) return 6;
  return -1;
}

assert(factorial(0) == 1);
assert(factorial(1) == 1);
assert(factorial(3) == 6);
// oops, we forgot to test that it handles n > 3…

Proofs put a lower bound on correctness: It may be impossible to prove certain properties. For example, it may be easy to prove that a function always returns a number (that's what type systems do). But it may be impossible to prove that the number will always be < 10.

int factorial(int n) {
  return n;  // FIXME this is just a placeholder to make it compile
}

// type system says this will be OK…


答:
I don't exactly understand what the linked answer means by "achieve modularity through mathematical laws", but I think I have an idea of what is meant.

Check out Functor:

The Functor class is defined like this:

```<code> class Functor f where
   fmap :: (a -> b) -> f a -> f b
</code>```

It doesn't come with test cases, but rather, with a couple of laws that must be satisfied.

All instances of Functor should obey:

```<code> fmap id = id
 fmap (p . q) = (fmap p) . (fmap q)
</code>```

Now let's say you implement Functor (source):

```<code>instance  Functor Maybe  where
    fmap _ Nothing       = Nothing
    fmap f (Just a)      = Just (f a)
</code>```

The problem is to verify that your implementation satisfies the laws.  How do you go about doing that?

One approach is to write test cases.  The fundamental limitation of this approach is that you're verifying the behavior in a finite number of cases (good luck exhaustively testing a function with 8 parameters!), and so passing tests can't guarantee anything but that the tests pass.

Another approach is to use mathematical reasoning, i.e. a proof, based on the actual definition (instead of on the behavior in a limited number of cases).  The idea here is that a mathematical proof may be more effective; however, this depends on how amenable your program is to mathematical proof.

I can't guide you through an actual formal proof that the above Functor instance satisfies the laws, but I'll try and give an outline of what the proof might look like:

fmap id = id

if we have Nothing

fmap id Nothing = Nothing by part 1 of the implementation

id Nothing = Nothing by the definition of id

if we have Just x

fmap id (Just x) = Just (id x) = Just x by part 2 of the implementation, then by the definition of id

fmap (p . q) = (fmap p) . (fmap q)

if we have Nothing

fmap (p . q) Nothing = Nothing by part 1

(fmap p) . (fmap q) $ Nothing = (fmap p) $ Nothing = Nothing by two applications of part 1

if we have Just x

fmap (p . q) (Just x) = Just ((p . q) x) = Just (p (q x)) by part 2, then by the definition of .

(fmap p) . (fmap q) $ (Just x) = (fmap p) $ (Just (q x)) = Just (p (q x)) by two applications of part two

Body:
I don't exactly understand what the linked answer means by "achieve modularity through mathematical laws", but I think I have an idea of what is meant.

Check out Functor:

The Functor class is defined like this:

 class Functor f where
   fmap :: (a -> b) -> f a -> f b

It doesn't come with test cases, but rather, with a couple of laws that must be satisfied.

All instances of Functor should obey:

 fmap id = id
 fmap (p . q) = (fmap p) . (fmap q)

Now let's say you implement Functor (source):

instance  Functor Maybe  where
    fmap _ Nothing       = Nothing
    fmap f (Just a)      = Just (f a)

The problem is to verify that your implementation satisfies the laws.  How do you go about doing that?

One approach is to write test cases.  The fundamental limitation of this approach is that you're verifying the behavior in a finite number of cases (good luck exhaustively testing a function with 8 parameters!), and so passing tests can't guarantee anything but that the tests pass.

Another approach is to use mathematical reasoning, i.e. a proof, based on the actual definition (instead of on the behavior in a limited number of cases).  The idea here is that a mathematical proof may be more effective; however, this depends on how amenable your program is to mathematical proof.

I can't guide you through an actual formal proof that the above Functor instance satisfies the laws, but I'll try and give an outline of what the proof might look like:

fmap id = id

if we have Nothing

fmap id Nothing = Nothing by part 1 of the implementation

id Nothing = Nothing by the definition of id

if we have Just x

fmap id (Just x) = Just (id x) = Just x by part 2 of the implementation, then by the definition of id

fmap (p . q) = (fmap p) . (fmap q)

if we have Nothing

fmap (p . q) Nothing = Nothing by part 1

(fmap p) . (fmap q) $ Nothing = (fmap p) $ Nothing = Nothing by two applications of part 1

if we have Just x

fmap (p . q) (Just x) = Just ((p . q) x) = Just (p (q x)) by part 2, then by the definition of .

(fmap p) . (fmap q) $ (Just x) = (fmap p) $ (Just (q x)) = Just (p (q x)) by two applications of part two


问:
Why develop free, open source programs?
Why would someone use his own time to develop an open-source project for free and without compensation?</p>

答: You can release it under a restrictive Free licence, such as the GNU AGPL, and then charge for exceptions.</p>

Title: Why develop free, open source programs?


问:
Indirection: Readability vs Performance
(I see there are a lot of similar questions, but answers are not really what I am interested at.)

The thing that is bugging me is indirection. If I'm writing something, I do tend to inline as much stuff as possible. I might be less strict about it in compiled language hoping that compiler will do all the inlining for me. Still adding layers of indirection feels to me like "I'll just add some more burden onto user in runtime so that I could have nicer code here" - something that could be solved with either a comment or a different design (which I would actually prefer but it would take some more time). Seeing a small function that is used only once I have to actually fight the urge to inline it. Having a multitude of single-use classes makes me want to create a different (and usually totally procedure-oriented) solution.

How bad is that? How many layers of indirection are actually OK to have?

答:
There is no question that indirection (of the type you describe) is for the programmers benefit.  What you may not be considering is this:

Programmer time is very expensive, but

Method calls are not.

Nicer code isn't just a conceit; it has profound practical concerns.  Every minute that you spend comprehending a piece of code that you didn't refactor into a method (accompanied by its own small collection of unit tests to prove that it still works) is one less minute that you can spend making improvements to the software or adding new features.

Title: Indirection: Readability vs Performance


答:
Access control is part of business logic. If you look at use cases, or even user stories, you will see that there are actors involved in any business process. The access control lists are a method to ensure that all and only the actors CAN be involved with the business process.

Access control needs to be supported in the model, the view and the controller.

Access control is part of the model: By limiting the ability to change or view columns or records per the business logic, you necessarily prevent many failures. If only system administrators can change a secondary key field, then it won't be accidentally changed because someone implemented a form incorrectly. Now, I also suggest that you don't specify the restriction as based on "system_administrator" privilege but rather "change_secondary_key" privilege, which system_adminstrators have by design. This separates role from function.

Access control is part of the view. By not enabling form fields to edit data for which the person doesn't have the privileges, you prevent both confusion and errors.

Access control is part of the controller. The controller adjusts the page flow to present only the information appropriate to the user at a time and place that is appropriate.

Certainly, you want to have central management of access controls, on the principle of DNRY (Don't Needlessly Repeat Yourself). Access control is a cross-cutting concern.

Title: Where should the ACL handler be called in a MVC architecture?

Body:
Thinking about Access Control Lists bound to a web MVC architecture, I have a doubt on where the verification should be done.

Within Models? Controllers? FrontController?

Imagine a multiple module web application (like a website). I have a public site and a restricted admin zone.

All public site pages are acessible by anyone.

The restricted admin area is only accessed by an authenticated user.

There are some access levels for the users, such as root, admin and regular user.

I gave this some thought during my lunch time today and some ideas came out.

First, I needed to ask myself this question:

Is access control part of business logic?

After some time, I figure out that the answer should be no for most cases. Normally, for the situation I described, the business logic of the public area is about the same of the restricted one. When is not exact the same, what I normally do is to create a superset of both business logic rules, that contains all logic needed. So, even if there are several modules in my application, I normally have only one model layer.

Doing the ACL within my controllers leads to code duplication, since I'd have to check it everytime I'd need. Also, I'd get a high coupling between controllers and the ACL component.

Thinking about putting it inside FrontController seems to be the right approach. In deed, my initial thought was to put the ACL handler as a dependency for the FrontController.

This approach would have controller methods (actions) as resources of the ACL, creating roles for my users.

Some pseudo-code (mixing Java, C#, PHP):

```<code>aclHandler = new DefaultAcl();
aclHandler.addRole('none'); // not authenticated
aclHandler.addRole('user');
aclHandler.addRole('admin', extend='user');
aclHandler.addRole('root', extend='admin');

aclHandler.addUser('john', 'root');
aclHandler.addUser('mary', 'admin');
aclHandler.addUser('jane', 'user');

aclHandler.addResource('admin.content.create'); // MODULE.CONTROLLER.ACTION
aclHandler.addResource('admin.content.view');
aclHandler.addResource('admin.content.edit');
aclHandler.addResource('admin.content.remove');

aclHandler.addResource('public.content.view');

aclHandler.allow('*', 'public.*');

aclHandler.deny('*', 'admin.*'); // deny from all
aclHandler.allow('user', 'admin.content.view'); // allow user to view content
aclHandler.allow('admin', 'admin.content.{edit,create}'); // allow admin to edit and create content
aclHandler.allow('root', '*'); // root can do anything
</code>```

This way, my FrontController would have something like:

```<code>class DefaultFrontController implements FrontControllerInterface {
    AclInterface acl {get};
    User currentUser {get;set};
    public DefaultFrontController(AclInterface acl, User user) {
        this.acl = acl;
        this.currentUser = user;
        // ...
    }

    public void dispatch(ControllerRequest request, ControllerResponse response) {
        try {
            this.acl.checkPrivileges(request.resource, this.currentUser);
        } catch (AclException e) {
            this.forbiddenAccessCallback(request, response, this.acl, this.currentUser);
            return;
        }

        // continue impl...
    }
}

fc = new FrontController(aclHandler, new User(name='John', role='root'));
fc.dispatch(...);  // ...
</code>```

This implementation makes an ACL component a mandatory parameter for the FrontController constructor, so, now it's part of its state. This could be a problem when I don't need an ACL, but can be overpassed by creating a mock implementation of ACL component, like AllowFromAllAcl, that would allow any users to do anything.

Any ideas? Corrections? Suggestions?


答:
There's a good reason Knuth said premature optimization is the root of all evil:

If your program isn't correct, it doesn't matter how fast it runs.

Most performance gains come from optimizing a small amount of code (the 80-20 rule).

The compiler is probably better at inlining and other such mechanical optimizations than you.

Write for correctness and clarity first. Measure. Decide if you actually have a performance problem. If you do, find the bottleneck. Then you may optimize.

Title: Indirection: Readability vs Performance

Body:
(I see there are a lot of similar questions, but answers are not really what I am interested at.)

The thing that is bugging me is indirection. If I'm writing something, I do tend to inline as much stuff as possible. I might be less strict about it in compiled language hoping that compiler will do all the inlining for me. Still adding layers of indirection feels to me like "I'll just add some more burden onto user in runtime so that I could have nicer code here" - something that could be solved with either a comment or a different design (which I would actually prefer but it would take some more time). Seeing a small function that is used only once I have to actually fight the urge to inline it. Having a multitude of single-use classes makes me want to create a different (and usually totally procedure-oriented) solution.

How bad is that? How many layers of indirection are actually OK to have?


问:
Call the database every time, or create an object in memory, and if so, how and how often to update?
I'm creating an app in javascript/nodejs and using neo4j as database.

Let's say I have an entity User in my database. It has a bunch of properties, like boxes_collected and places_visited, which keep updating independently of one another throughout the course of running my app.

So far I have functions that talk to the database to update these properties directly. But it's getting a bit messy and I'm thinking of making a single high level object/class that handles everything in a much cleaner, nicer, and eloquent way.

Here's a tiny version of my "model" to better explain what I mean:

Suppose I have a function like this

```<code>function UpdateUserValue_plants(number) {// update database}
</code>```

But then if were to create a User object and incorporate the above into it,

```<code>var User = function User(plants, other...) {
    this.plants= plants;
}

User.prototype.updateValue_plants = function(number) {
    this.plants += number; // first update the model itself
}
</code>```

Then when am I supposed to update the database? And wouldn't I be doing the updatation twice that way: first the object's property, then the database?

Is there an elegant solution to this?

答: Implement additional persist() method which will persist object into db and also save object into database in updateValue_plants(). You are trying to do a Domain-driven design https://en.wikipedia.org/wiki/Domain-driven_design. By creating a persist() method for saving object and saving also in updateValue_plants you are on a good way to do that.</p>


答:
Seeing a small function that is used only once I have to actually fight the urge to inline it.

That's bad. It's usually bad for readability and sometimes also bad for performance.

The following is rather Java specific, but may apply to other compilers working with statistics.

If you don't inline a method, the compiler may chose to do it or not. If the method gets called rarely, it won't get inlined and it doesn't make the code larger. This leaves more room for inlining of more important methods and also loop unrolling.

If you inline it, it can't be "out-lined" and can hinder the optimizations. This is no theory, see e.g. the comment at line 269 of this library class.

Title: Indirection: Readability vs Performance


问:
Coming up with a valid ranking algorithm for articles
I'm creating a website which will publish one or more articles a week.

I'd like to be able to rank the articles based on popularity. In order to do this, I need a formula to calculate a score for each article. This formula should reward popular articles (those that receive many views), while also bringing new articles closer to the top in order to keep the content fresh and interesting.

The website doesn't support voting on the articles. The readers will be able to comment and I can have the site track the amount of unique views the article gets.

My attempt

I have come up with a way to calculate a score for each article but I'm not sure if it's the right way to do it, or if it will work at all.

This formula calculates the score:

```<code>score = unique_views / ( hours_since_release * 4 )
</code>```

The formula keeps articles with many views afloat, while also making sure that they'll eventually subside to leave space for new articles.

I wrote a small program to test this formula. Here is the output of one run.

This script generates between 0 and 2 articles every day, and simulates their score as time progresses.

When an article is created, it chooses a random number (M) between 100 and 1000, representing its popularity. Every "day", the script adds a random number of views between 0 and M to each article.

The actual views shown in the output (V) are the result of this formula:

```<code>view_count = ( 10 * log10( view_count ) ) ^ 2
</code>```

I used this to make sure the view count doesn't keep growing forever. Instead, its growth will slow down as time goes, as it might in real life.

The values A and S in the output represent respectively the age in days of the article and its score, based on the formula shown above.

This formula causes some interesting behavior: if you look at the game Tomb Raider: Anniversary, it spawns with a big Mnumber, which means it's going to be very popular. It gets to the top on the first day, goes down in the next 2 days and then comes back to the top for 3 days in a row due to the amount of views it gets.

This seems to be the behavior I'm looking for, but I'm not sure if it will work in practice, or even if this is the right approach at all.

You can find the source of my rough prototype here if you'd like to run it yourself.

Here comes the question:

How can you come up with and test ranking algorithms so that they satisfy the conditions of the problem, using the available variables?

Secondary question: Is my ranking algorithm appropriate, and would it work in the situation I described?

EDIT: From the links in maythesource.com's answer, I just realized there's also the issue of score gaming. Would only considering unique visits somehow prevent gaming, or is it a weak countermeasure?

答:
Your problem is similar to application markets. Take for example google play - they don't use only one list.

```<code>Featured: new apps hand-picked by Google Play team.
Staff Picks: rotating set of apps chosen by Google Play team.
Top Free: most popular free apps of all time.
Top New Free: most popular free apps less than 30 days old.
...
Trending Apps: apps showing growth in installs in the last 24 hours.
</code>```

See: https://support.google.com/googleplay/android-developer/answer/1295940?hl=en

In the same way, I don't think it's enough to only have one list and one algorithm. As it is, your list may get into a feedback loop and cause higher ranked articles to be pushed even higher.

If however, you created two lists (or three) you could offset this.

Examples:

Top New Articles- Scan all articles within the last week that have more than X rating and Y viewes and order with following algorithm: Group applications by day, then order applications within day by views+rating.

Overall Top Articles - Display articles based on their all time views/rating/popularity.

Featured/Editor's picks - Select the articles that really stand out and display these.

It's good if you have some control over what is featured and have a minimum level of quality in what is featured/sponsored to your viewers.

Also have a look at some articles such as:

https://stackoverflow.com/questions/3934579/algorithm-to-determine-most-popular-article-last-week-month-and-year

http://www.michael-noll.com/blog/2013/01/18/implementing-real-time-trending-topics-in-storm/

https://www.facebook.com/business/news/News-Feed-FYI-A-Window-Into-News-Feed

Body:
Your problem is similar to application markets. Take for example google play - they don't use only one list.

Featured: new apps hand-picked by Google Play team.
Staff Picks: rotating set of apps chosen by Google Play team.
Top Free: most popular free apps of all time.
Top New Free: most popular free apps less than 30 days old.
...
Trending Apps: apps showing growth in installs in the last 24 hours.

See: https://support.google.com/googleplay/android-developer/answer/1295940?hl=en

In the same way, I don't think it's enough to only have one list and one algorithm. As it is, your list may get into a feedback loop and cause higher ranked articles to be pushed even higher.

If however, you created two lists (or three) you could offset this.

Examples:

Top New Articles- Scan all articles within the last week that have more than X rating and Y viewes and order with following algorithm: Group applications by day, then order applications within day by views+rating.

Overall Top Articles - Display articles based on their all time views/rating/popularity.

Featured/Editor's picks - Select the articles that really stand out and display these.

It's good if you have some control over what is featured and have a minimum level of quality in what is featured/sponsored to your viewers.

Also have a look at some articles such as:

https://stackoverflow.com/questions/3934579/algorithm-to-determine-most-popular-article-last-week-month-and-year

http://www.michael-noll.com/blog/2013/01/18/implementing-real-time-trending-topics-in-storm/

https://www.facebook.com/business/news/News-Feed-FYI-A-Window-Into-News-Feed


答:
A word of warning may be in order here:

While it is generally true what others write here - in short, that advanced type systems, immutablity and referential transparency contribute a lot to correctness - it is not the case that testing is not done in the functional world. To the contrary!

This is because we have tools like Quickcheck, that generate test cases automatically and randomly. You merely state the laws that a function must obey, and then quickcheck will check these laws for hundreds of random test cases.

You see, this is a bit higher level than trivial equality checks on a handful of test cases.

Here is an example from an implementation of an AVL tree:

```<code>--- A generator for arbitrary Trees with integer keys and string values
aTree = arbitrary :: Gen (Tree Int String)

--- After insertion, a lookup with the same key yields the inserted value
p_insert = forAll aTree (\t ->
             forAll arbitrary (\k ->
               forAll arbitrary (\v ->
                lookup (insert t k v) k == Just v)))

--- After deletion of a key, lookup results in Nothing
p_delete = forAll aTree (\t ->
            not (null t) ==> forAll (elements (keys t)) (\k ->
                lookup (delete t k) k == Nothing))
</code>```

The second law (or property) we can read as follows: For all arbitrary trees t, the following holds: if  t is not empty, then for all the keys k of that tree it will hold that looking up k in the tree that is the result of deleting k from t, the result will be Nothing (which indicates: not found).

This checks proper functionality for deletion of an existing key. What laws should govern the deletion of a non-existing key? We certainly want the resulting tree to be the same as the one we deleted from. We can express this easily:

```<code>p_delete_nonexistant = forAll aTree (\t ->
                          forAll arbitrary (\k ->
                              k `notElem` keys t ==> delete t k == t))
</code>```

This way, testing is really fun. And besides, once you learn to read quickcheck properties, they serve as a machine testable specification.

Body:
A word of warning may be in order here:

While it is generally true what others write here - in short, that advanced type systems, immutablity and referential transparency contribute a lot to correctness - it is not the case that testing is not done in the functional world. To the contrary!

This is because we have tools like Quickcheck, that generate test cases automatically and randomly. You merely state the laws that a function must obey, and then quickcheck will check these laws for hundreds of random test cases.

You see, this is a bit higher level than trivial equality checks on a handful of test cases.

Here is an example from an implementation of an AVL tree:

--- A generator for arbitrary Trees with integer keys and string values
aTree = arbitrary :: Gen (Tree Int String)

--- After insertion, a lookup with the same key yields the inserted value
p_insert = forAll aTree (\t ->
             forAll arbitrary (\k ->
               forAll arbitrary (\v ->
                lookup (insert t k v) k == Just v)))

--- After deletion of a key, lookup results in Nothing
p_delete = forAll aTree (\t ->
            not (null t) ==> forAll (elements (keys t)) (\k ->
                lookup (delete t k) k == Nothing))

The second law (or property) we can read as follows: For all arbitrary trees t, the following holds: if  t is not empty, then for all the keys k of that tree it will hold that looking up k in the tree that is the result of deleting k from t, the result will be Nothing (which indicates: not found).

This checks proper functionality for deletion of an existing key. What laws should govern the deletion of a non-existing key? We certainly want the resulting tree to be the same as the one we deleted from. We can express this easily:

p_delete_nonexistant = forAll aTree (\t ->
                          forAll arbitrary (\k ->
                              k `notElem` keys t ==> delete t k == t))

This way, testing is really fun. And besides, once you learn to read quickcheck properties, they serve as a machine testable specification.


问:
Scrum for Embedded system devices
In our company, we are going to deliver a new product which will be used for mass notification, so it is an embedded software project and we are going to use the SCRUM as a framework for the product.

We have started to write down the product backlog. Based on what I understood the product backlog should reflect a business value for each item. The nature of embedded software is that it has a lot of technical details that will consume a large amount of time to create drivers for microcontrollers, like the SPI, UART, ethernet, WIFI, so on.

for example the System is sounding by playing message for notification, so it is pretty obvious that playing a message is a business value but to achieve this goal i have to write down the -requirements which are what also not how - for many drivers like the SPI, MP3 decoder chip driver, SD card driver and finally the FAT, so all of the previous drivers have requirements that should be written in the product backlog, such that the requirements started with a one business value requirement while it has a lot of technical sub-requirements.

These don't reflect a business value for the client; can someone tell me how am I going to create my product backlog?

答:
Don't get hung up on scrum dogma. Scrum exists to make you more agile. Anything that gets in the way of that can be ignored.

It is true you shouldn't do work that doesn't give business value, but value comes in many forms. Do you derive value from having an ethernet driver? I suspect you do, because without it you can't deliver certain features. "As a developer, I need an ethernet driver so that I can implement the features that require internet connectivity".

So, don't look at value only as user-visible features. Value is anything that makes your product better, even if it is invisible to the end user.

Some will say that's not a valid story, and stories should only have user visible features. I think that's ok too, right up to the point where it causes you problems like this. Again, the goal of scrum is to help you, and to improve focus and communication. Don't let what you think you're supposed to do get in the way of you getting things done. Be pragmatic, and be honest. If you think you need to develop a certain thing, answer the question "why", and "who is this for?". The answer doesn't always have to be the same person.

Title: Scrum for Embedded system devices


问:
How to manage focus for a small set of simple widgets
I'm developing a set of simple widgets for a small (128x128) display.

For example I'd like to have a main screen with an overlay menu which I can use to toggle visibilty of main screen elements. Each option would be an icon with a box around it while it is selected. Button (left, up, right, down, enter) events should be given to the widget that has "focus".

Focus is a simple thing to understand when using a GUI, but I'm having trouble implementing this. Can you suggest a simple concept for managing focus and input events? I have these simple ideas:

Only one widget can have focus, so I need a single pointer to that widget.

When this widget gets some kind of "cycle" input (as in "highlight the next item in this list"), the focus is given to a different widget.

a widget must have a way of telling the application which widget the focus is given to next.

if a widget cannot give a "next focus" hint, the application must be able to figure out where the focus should go.

Widgets are currently structured like this:

A widget can have a parent, which is passed to the constructor. Widgets are created statically, as I want to avoid dynamic memory allocation (I only have 16kB of RAM and I'd like to have control over that).

widgets have siblings, implemented as an intrusive linked list (they have a next member). A parent has a pointer to the head of its list of children.

Input events are arguments to the widgets buttonEvent methods which can accept or ignore that event. If it ignores the event, it can pass the event to its parent.

My Questions:

How can I manage focus for these widgets?

Am I making this too complicated?

答:
I implemented a system like this in the past and your design is very similar to mine. A hierarchy of widgets (widgets can contain child widgets), child widgets know who their parents are, there is only one globally focused widget at any time and it must be a leaf widget (no children).

The difference in my design was it was possible to specify which widgets would come into focus by populating each widget with a map to other siblings.

For example. My input allowed up, down, left and right so each widget had up to 4 siblings mapped to each of those commands. Widget A could have a "right sibling" that was Widget B and Widget B could have a "left sibling" that was Widget A. Any command issued would check the current focused widget's sibling for that command. If it did not exist, focus did not change. If the sibling mapping did exist, the focus was changed.

If this proves too expensive for you memory wise you could store the sibling mappings in the parent somehow.


答:
Where I work, we create embedded systems and are also using scrum for our development. You're looking at things from a technical perspective, not a feature perspective.

The first thing you should ask is "Why do we need to implement this?" For example:
Why do you need SPI? Is it going to be used for EEPROM so you can store serial numbers? Or maybe hook up to a display controller so users can see items on a display? There are a lot of good reasons to create an SPI driver, but creating it just to have it isn't one of those reasons.

With Scrum you should be adopting a "We don't need it until we need it" policy, which is to say that you shouldn't waste time with SPI or wifi or anything else until there is a business need which requires those technologies to accomplish. Then that business need becomes the story.

Try "Add on EEPROM for configuration storage" instead of "Create SPI Code"

and "Create connection to server for remote management" instead of "Find documentation for WIFI and implement"

Title: Scrum for Embedded system devices

Body:
In our company, we are going to deliver a new product which will be used for mass notification, so it is an embedded software project and we are going to use the SCRUM as a framework for the product.

We have started to write down the product backlog. Based on what I understood the product backlog should reflect a business value for each item. The nature of embedded software is that it has a lot of technical details that will consume a large amount of time to create drivers for microcontrollers, like the SPI, UART, ethernet, WIFI, so on.

for example the System is sounding by playing message for notification, so it is pretty obvious that playing a message is a business value but to achieve this goal i have to write down the -requirements which are what also not how - for many drivers like the SPI, MP3 decoder chip driver, SD card driver and finally the FAT, so all of the previous drivers have requirements that should be written in the product backlog, such that the requirements started with a one business value requirement while it has a lot of technical sub-requirements.

These don't reflect a business value for the client; can someone tell me how am I going to create my product backlog?


问:
How do I document roles and responsiblites
When working on a requirements document, how do I capture system roles and responsibilities?

E.g. "I'm a manager and I will only use the system to generate reports on xyz".

I was looking for an example online but couldn't find one.

答:
You may benefit from reading up on Agile Development Methodology. In this methodology requirements gathering is done in the form of "User Stories". For example:

"As a manager I want to be able to generate reports on XYZ"

"As a customer I want to be able to see my recent transactions"

etc.


答:
A proper use case should clearly state the Actors involved.

In your case "Manager" is the actor in a "Manager receives daily reports" use case.

Also note that use case Actors just like actors in a theater company may have several roles.

So "Manager" is also an "Employee" and perhaps a "C.C. for CIO".

Title: How do I document roles and responsiblites

Body:
When working on a requirements document, how do I capture system roles and responsibilities?

E.g. "I'm a manager and I will only use the system to generate reports on xyz".

I was looking for an example online but couldn't find one.


答:
Inheritance

```<code>// this is pseudo code - isn

// base class references to derived-type objects.
BaseClass thing1 = new Derived1();
BaseClass thing2 = new Derived2();
BaseClass thing3 = new Derived3();

// assume the array elements must be of the same type
baseClassArray : [thing1, thing2, thing3];

for (int i-0; i< baseClassArray.Length; i++) {
    baseClassArray[i].Foo(); // base.Foo() is called.
}

for (int i=0; i< baseClassArray.Length; i++) {
    if (baseClassArray[i] is Derived1) {
        Derived1 thingy1 = (Derived1)baseClassArray[i];
        thingy1.Foo();   // the over-ride Foo() called
    }else if ....
}
</code>```

Polymorphism

```<code>// this is pseudo code - ish

public abstract class AbstractPainter {
   public abstract void Style();
}

public class Dali : AbstractPainter {
    public override Style() {
        console.writeline("floppy clocks lying about");
}

public class Warhol : AbstractPainter {
    public override Style() {
        console.writeline("High contrast soup cans");
    }
}

// cannot instantiate abstract classes
// ie.  new AbstractPainter() is not allowed.

AbstractPainter Salvador = new Dali();
AbstractPainter Andy = new Warhol();

AbstractPainterArray = [Salvador, Andy];

for (int i=0; i< AbstractPainterArray.Length; i++) {
    AbstractPainterArray[i].Style();
}

output:
    "floppy clocks lying about"
    "High contrast soup cans"
</code>```

Take Away?

Inheritance: Same-type references + derived objects, same method call.

polymorphism: Same-type references + derived objects, different method call.

Body:
Inheritance

// this is pseudo code - isn

// base class references to derived-type objects.
BaseClass thing1 = new Derived1();
BaseClass thing2 = new Derived2();
BaseClass thing3 = new Derived3();

// assume the array elements must be of the same type
baseClassArray : [thing1, thing2, thing3];

for (int i-0; i< baseClassArray.Length; i++) {
    baseClassArray[i].Foo(); // base.Foo() is called.
}

for (int i=0; i< baseClassArray.Length; i++) {
    if (baseClassArray[i] is Derived1) {
        Derived1 thingy1 = (Derived1)baseClassArray[i];
        thingy1.Foo();   // the over-ride Foo() called
    }else if ....
}

Polymorphism

// this is pseudo code - ish

public abstract class AbstractPainter {
   public abstract void Style();
}

public class Dali : AbstractPainter {
    public override Style() {
        console.writeline("floppy clocks lying about");
}

public class Warhol : AbstractPainter {
    public override Style() {
        console.writeline("High contrast soup cans");
    }
}

// cannot instantiate abstract classes
// ie.  new AbstractPainter() is not allowed.

AbstractPainter Salvador = new Dali();
AbstractPainter Andy = new Warhol();

AbstractPainterArray = [Salvador, Andy];

for (int i=0; i< AbstractPainterArray.Length; i++) {
    AbstractPainterArray[i].Style();
}

output:
    "floppy clocks lying about"
    "High contrast soup cans"

Take Away?

Inheritance: Same-type references + derived objects, same method call.

polymorphism: Same-type references + derived objects, different method call.


问:
How do you deal with time estimates?
If given too little time, quality suffers. If given too much time, developers will find a way to use all alloted time, no matter what. What would be a good way with dealing with estimates? Are they a necessary evil?</p>

答:
Estimates are not a necessary evil.  If they're evil, you should question if they're necessary.

One of significant recent trends in software engineering is the proliferation of Lean software development philosophies, particularly Kanban.  And - don't shoot the messenger -- the proponents of Lean and Kanban put it bluntly: "Estimation is waste."  What do you do with waste?  "Eliminate it."

(Henrik Kniberg, the famous author of Scrum and XP from the Trenches, has gotten into Kanban.  His latest book, Lean from the Trenches is coming out soon.  In the book, he contends that story-point, relative size estimation is a waste of time.)

What they do instead of estimation is a huge, separate topic, but the gist of it is: they embrace variability, optimize the flow of valuable features to the users, measure the lead time and optimize the whole system for lead time or throughput -- instead of controlling the time it takes to execute individual tasks.

If you visualize the journey of a user requirement from the point when it's identified to when it's delivered to the user, you can see how little of it actually involves typing code.  Even in the development phase, lots of time can be lost while in-progress work items are:

in blocked state (how effective is
your escalation process?)

waiting for non-instantly available resources

getting thorough other bottlenecks

reworked

A less-than-superefficient software development team can easily waste (as far as the customer is concerned, that's all waste) several days on any of the above causes, which brings into question whether a precise estimate that it would take 5 days instead of 2 to code some feature adds any value.  Remember the customer doesn't care how many of 45 days from the feature request to delivery was spent on coding or something else and in what order.

To use an analogy, an Amazing Race contestant adds value by getting to the finish first.  Estimating how long it would take him to eat 1 kilogram of local food is not a value-adding activity.

I don't know whether you can implement any of this thinking at your workplace, I contend this is a useful perspective.

Title: How do you deal with time estimates?


问:
What were the Design Patterns of the procedural programming era?
Similar: How was programming done 20 years ago?

OOP is quite fashionable nowadays, having its roots in Simula 67 in the 1960s, and later made popular by Smalltalk and C++. We have DRY, SOLID, many books about design patterns in the object-oriented world.

But what were the main principles in programming prior to the OOP paradigm wide adoption? And what were the major design patterns?

答:
A "finite state machine" may count as a Pattern, and FSMs were written (e.g. for communications protocols) using pre-OO languages.

Also "interrupt handlers" and TSRs used to be popular e.g. on DOS.


问:
Objects as parameters: Is there a simple way that explain this?
I tried to understand how objects can be passed as parameters but it was difficult for me. How can we pass an object as a parameter to a method of another object? I need to understand the idea behind this.

updated:

```<code>public class Student {}

public class Admin {

    private ArrayList<Student> students;

    public void enrollStudent(Student newStudent)
    {
       students.add(newStudent);
    }
}
</code>```

答:
Write a class with methods that take (i.e. has parameters) variables of specific type.

int, string, double, etc. are all types built-into Java.

Any class you write is also a type. The type kind/name is the name of your class

Create variables of whatever type, or class, you want.

Pass around variables of "your class name" type just like you pass around variables of int or string.

When you pass a variable of type int to a method the whole int goes.

When you pass a variable of type "your class name" to a method the whole thing goes.

A variable of type Student is like a suitcase. You grab hold of the Student by it's handle - the variable name. You pick up the suitcase by the handle and everything in it goes along for the ride. I.E. You pass the variable name (the handle) to a method and everything inside it goes along for the ride.

.

```<code>public class Student {
    public string Name;     //Name is a variable of type string
    public int Age;         //Age is a variable of type int

    public Student(string name, int age) {
        this.Name = name;
        this.Age = age;
    }
}

public string EinsteinName;    //EinsteinName is a variable of type string
public int EinsteinAge;    //EinsteinAge is a variable of type int
public Student Albert;     //Albert is a variable of type Student

EinsteinName = "Albert Einstein"; //the variable named EinsteinName is given a value
EinsteinAge = 114;   //the variable named EinsteinAge is given a value

Albert = new Student(EinsteinName, EinsteinAge);
     //the variable named Albert is given a value.

     // above, the variables EinsteinName(a string) and EinsteinAge (an int)
     // are passed into the method Student. This method creates a Student object. It's a constructor.
     // Thus the variable Albert (a Student) is given a value.

// then some other stuff happens.

EnrollStudent(Albert);

// above, Albert (a variable of type Student)
//is passed to the EnrollStudent method. Albert has details
//inside like Name and Age -  but all that is inside the suitcase
//so when we pass Albert all the stuff inside goes along.
</code>```

Body:
Write a class with methods that take (i.e. has parameters) variables of specific type.

int, string, double, etc. are all types built-into Java.

Any class you write is also a type. The type kind/name is the name of your class

Create variables of whatever type, or class, you want.

Pass around variables of "your class name" type just like you pass around variables of int or string.

When you pass a variable of type int to a method the whole int goes.

When you pass a variable of type "your class name" to a method the whole thing goes.

A variable of type Student is like a suitcase. You grab hold of the Student by it's handle - the variable name. You pick up the suitcase by the handle and everything in it goes along for the ride. I.E. You pass the variable name (the handle) to a method and everything inside it goes along for the ride.

.

public class Student {
    public string Name;     //Name is a variable of type string
    public int Age;         //Age is a variable of type int

    public Student(string name, int age) {
        this.Name = name;
        this.Age = age;
    }
}

public string EinsteinName;    //EinsteinName is a variable of type string
public int EinsteinAge;    //EinsteinAge is a variable of type int
public Student Albert;     //Albert is a variable of type Student

EinsteinName = "Albert Einstein"; //the variable named EinsteinName is given a value
EinsteinAge = 114;   //the variable named EinsteinAge is given a value

Albert = new Student(EinsteinName, EinsteinAge);
     //the variable named Albert is given a value.

     // above, the variables EinsteinName(a string) and EinsteinAge (an int)
     // are passed into the method Student. This method creates a Student object. It's a constructor.
     // Thus the variable Albert (a Student) is given a value.

// then some other stuff happens.

EnrollStudent(Albert);

// above, Albert (a variable of type Student)
//is passed to the EnrollStudent method. Albert has details
//inside like Name and Age -  but all that is inside the suitcase
//so when we pass Albert all the stuff inside goes along.


问:
Is array dependence on previous terms considered recursive?
For example, take the case of Fibonacci number to calculate nth number you require n-1 and n-2 term.

If I do it with bottom up approach, is it recursion as f(n) depends on f(n-1)?

答:
There are several slightly different meanings to the term "recursive":

The definition of Fibonacci sequence is recurrent. This is property of the definition, no matter how you implement it.

The function to calculate it is totally recursive, i.e. computable.

The implementation of the function is recursive if it actually calls itself. If you create the array manually and convert the recursion to a loop, it usually is not called recursive.

The bottom-up approach is (without unnecessarily wasting space for n values when last two is all that's required):

```<code>def fib(n):
   f_2, f_1 = 0, 1
   for _ in xrange(1, n):
       f_2, f_1 = f_1, f_2 + f_1
   return f_1
</code>```

and that's not recursive.

However any loop can be rewritten as recursive, which would look like:

```<code>def fib(n):
   def f(n, f_2, f_1):
      if n == 1:
         return f_1
      else:
         return f(n, f_1, f_2 + f_1)
   return f(n, 0, 1)
</code>```

It's getting somewhat convoluted by now though, but in functional languages (like Haskell) and mostly functional ones (like Lisp/Scheme) it would probably be the more natural definition. And in those languages with tail-recursion optimization (like Haskell or Scheme) it is just as efficient.

Body:
There are several slightly different meanings to the term "recursive":

The definition of Fibonacci sequence is recurrent. This is property of the definition, no matter how you implement it.

The function to calculate it is totally recursive, i.e. computable.

The implementation of the function is recursive if it actually calls itself. If you create the array manually and convert the recursion to a loop, it usually is not called recursive.

The bottom-up approach is (without unnecessarily wasting space for n values when last two is all that's required):

def fib(n):
   f_2, f_1 = 0, 1
   for _ in xrange(1, n):
       f_2, f_1 = f_1, f_2 + f_1
   return f_1

and that's not recursive.

However any loop can be rewritten as recursive, which would look like:

def fib(n):
   def f(n, f_2, f_1):
      if n == 1:
         return f_1
      else:
         return f(n, f_1, f_2 + f_1)
   return f(n, 0, 1)

It's getting somewhat convoluted by now though, but in functional languages (like Haskell) and mostly functional ones (like Lisp/Scheme) it would probably be the more natural definition. And in those languages with tail-recursion optimization (like Haskell or Scheme) it is just as efficient.


答:
I would consider it "recursion" if you call a function calls itself.

Something like this:

```<code>f(n) {
   ....
   return f(n-2) + f(n-1);
}
</code>```

You do the same thing with a loop and it wouldn't be recursion

```<code>f(n) {
  .....
  for ( i =2 ; i< n ;i++)
     arr[i] = arr[i-1] + arr[i-2]
}
</code>```

Title: Is array dependence on previous terms considered recursive?

Body:
For example, take the case of Fibonacci number to calculate nth number you require n-1 and n-2 term.

If I do it with bottom up approach, is it recursion as f(n) depends on f(n-1)?

Body:
I would consider it "recursion" if you call a function calls itself.

Something like this:

f(n) {
   ....
   return f(n-2) + f(n-1);
}

You do the same thing with a loop and it wouldn't be recursion

f(n) {
  .....
  for ( i =2 ; i< n ;i++)
     arr[i] = arr[i-1] + arr[i-2]
}


问:
Is there a difference between declaring variables outside or inside a loop?
Is there any difference if I were to write something like this:

```<code>int row,col;
    for(row = 0; row < data.length; row++){
        for(col = 0; col < data[row].length;col++){
            //do something
        }//end for loop(columns)
    }//end for loop(rows)
    for(row = 0; row < data.length; row++){
        for(col = 0; col < data[row].length;col++){
            //do something
        }//end for loop(columns)
    }//end for loop(rows)
</code>```

compared to:

```<code>    for(int row = 0; row < data.length; row++){
        for(int col = 0; col < data[row].length;col++){
            //do something
        }//end for loop(columns)
    }//end for loop(rows)
    for(int row = 0; row < data.length; row++){
        for(int col = 0; col < data[row].length;col++){
            //do something
        }//end for loop(columns)
    }//end for loop(rows)
</code>```

Are there any bennefits from either one?

答:
Quick answer: most of the time I don't care about the value outside the loop, so I use the second form.

Occasionally I'll want the "first index" where I'll put a break (or an exit condition on the loop) so that the value represents as far as I got. Then I'll use the first form, but with a break or a loop condition that causes it to stop early.

...e.g. find the index of the first non-zero value in an array.

EDIT: I just looked more closely at your code... I would NEVER reuse the same index variable just for the sake of preserving variable declarations ;) lol!


答:
Terms like "Spaghetti Code" and "Single Point of Exit" are actually throwbacks to that era. Nowadays we call code we don't like "spaghetti code", but really that's a reference to code tied together (badly) with GOTOs and JMPs.

(Today we suffer "ravioli code", in which the code is like a bunch of unrelated, tightly packaged classes, much like a plate of ravioli. However, some OO experts ask justifiably, "But isn't that what OO is supposed to look like?")

"Single Point of Exit" today is just a frustrating refactoring roadbump. A lot of devs I talk to haven't even heard of it, and are aghast when I explain it. But in the old days it meant don't jump out of a code block suddenly & into spaghetti code. Jump forward to the end of the logic, then exit gracefully.

Stretching my memory way, way back, I seem to remember that the idea of bundling code up into procedures was a big leap forward. The idea that you could package procedures into inter-operable, reusable Modules was kind of the Holy Grail of programming.

EDIT: "Self-modifying code" was also a pattern used notably on the original Doom. That's where the program would actually overwrite its instructions with faster instructions based on it's state. When I was a tyke taking a programming course at the Science Museum, my instructor warned us sternly, "Don't write self-modifying code!"

EDIT EDIT: However, before the Internet, word travelled a lot more slowly. The idea of implementing Algorithms and Data Structures used to be a much bigger deal. Today I do sort all the time without even knowing what sort I'm using. But back then you had to code it up yourself. I remember one article talking about programming challenges that used to take days that today we knock out in a half hour, or less. So really concious "algorithmic" and "data stucture" programming would probably be on the list, much more than today.

Title: What were the Design Patterns of the procedural programming era?

Body:
Similar: How was programming done 20 years ago?

OOP is quite fashionable nowadays, having its roots in Simula 67 in the 1960s, and later made popular by Smalltalk and C++. We have DRY, SOLID, many books about design patterns in the object-oriented world.

But what were the main principles in programming prior to the OOP paradigm wide adoption? And what were the major design patterns?


答:
Both versions may have a specific purpose.

1 Variables inside

Used for iterating(yes, I know about iterators and enhanced loop, but let's use the old for)

2 Variables outside

Let's say we want to find the index of an item from some array and we want that index to use for something else. You can't use the variables for the loop scope because you will need the index so your index must be outside the loop scope.

Example:

```<code>int i;
for (i = 0; i < length; i++) {
  if (someConditionAppliedForAnElement(arr[i])) {
    break;
  }
}
if (i != length) { /* logic here */ }
</code>```

Of course, this is just an example, there are better ways to do this task, but I just wanted to point that sometimes, loop scope doesn't fit.

By the way, for your sample I'd use loop scope indexes.

Title: Is there a difference between declaring variables outside or inside a loop?

Body:
Is there any difference if I were to write something like this:

```<code>int row,col;
    for(row = 0; row < data.length; row++){
        for(col = 0; col < data[row].length;col++){
            //do something
        }//end for loop(columns)
    }//end for loop(rows)
    for(row = 0; row < data.length; row++){
        for(col = 0; col < data[row].length;col++){
            //do something
        }//end for loop(columns)
    }//end for loop(rows)
</code>```

compared to:

```<code>    for(int row = 0; row < data.length; row++){
        for(int col = 0; col < data[row].length;col++){
            //do something
        }//end for loop(columns)
    }//end for loop(rows)
    for(int row = 0; row < data.length; row++){
        for(int col = 0; col < data[row].length;col++){
            //do something
        }//end for loop(columns)
    }//end for loop(rows)
</code>```

Are there any bennefits from either one?

Body:
Both versions may have a specific purpose.

1 Variables inside

Used for iterating(yes, I know about iterators and enhanced loop, but let's use the old for)

2 Variables outside

Let's say we want to find the index of an item from some array and we want that index to use for something else. You can't use the variables for the loop scope because you will need the index so your index must be outside the loop scope.

Example:

int i;
for (i = 0; i < length; i++) {
  if (someConditionAppliedForAnElement(arr[i])) {
    break;
  }
}
if (i != length) { /* logic here */ }

Of course, this is just an example, there are better ways to do this task, but I just wanted to point that sometimes, loop scope doesn't fit.

By the way, for your sample I'd use loop scope indexes.


问:
Declaring functions in order to avoid explicit nested loops
My programming professor has told me that it is a good programming practice (at least in C/C++) to declare a function with the inner loop when nesting loops (not for loops, since when, i.e. looping through a multidimensional array this is very intuitive). For example, if I write

```<code>int main()
{
    while (cond1)
    {
        // ...(1)...
        while (cond2)
        {
            // ...(2)...
        }
    }
}
</code>```

then it is better:

```<code>type inner_loop(param)
{
    // ...(1)...

    while (cond2)
    {
        // ...(2)...
    }
}

int main()
{
    while (cond1)
    {
        inner_loop(param);
    }
}
</code>```

What improvements do imply this method? Is there any case in which this way of programming nested loops can be counterproductive? Thanks in advance.

答:
The more general advice is: watch out for deep levels of nesting. I've heard it called the "arrowhead" or "mountain range" anti-pattern, because that's what the code starts to look like. If you're nesting 2 levels for loops, then another level for if...then, and then if..thens inside the if...thens, the level of nesting can make the code really hard to follow.

I read an article where a team had huge maintenance problems with their code, so they implemented a policy of a maximum depth of nesting. Their bug rate dropped to almost nothing.

Someone famous once said, any code nested more than 3 layers deep is incomprehensible.

Hm. I can't find that quote now, but I did find a related article about nesting if...thens:

http://www.drdobbs.com/architecture-and-design/refactoring-deeply-nested-code/231500074

EDIT: here it is: "if you need more than 3 levels of indentation, you're screwed anyway, and should fix your program."

https://www.kernel.org/doc/Documentation/CodingStyle


问:
How to convey lifetime requirements?
Usually I use std::unique_ptr to convey ownership and pass in raw pointers as parameters when no ownership is implied. However, I almost never consider a nullptr to be acceptable as an argument, so it would be nice to use references to avoid this, but I'm not sure most people would expect that the object the parameter references needs to exist for the lifetime of the struct A without looking at the source code.

```<code>struct A {
    A(B& b)
    :  bPtr(&b) {;}

    void method() {
        // use bPtr
    }

    B* bPtr;
};
</code>```

The questions are:

1) Is the only option here to stick with pointers and always check for nullptr?

3) Does the fact that A needs bPtr to be valid mean it should take a shared_ptr? If so I feel like I would use shared pointers practically everywhere.

2) Are there conventions that can help convey lifetime requirements for parameters to users besides comments and documentation?

答:
From a C++ language standpoint, your code is fine.

As a C++ user, it depends very much on the semantics of struct A if I would expect it to maintain a reference/pointer to B, make a copy of it or to use the constructor parameter only in the constructor.

My general expectations are (all unless indicated otherwise):

If a parameter is passed by (smart) pointer, then the class will likely keep a reference to it

If a parameter is passed by (smart) pointer and there is no setter for it, then the class will likely not deal well with null pointers. This can be reinforced by a comment.

If a parameter is passed by const reference, then it is safe to pass a temporary object. The receiving object will either make a copy or not use the parameter beyond the constructor.

Title: How to convey lifetime requirements?


问:
How to design routes for generalized/specialized resources
I hope I can explain what is troubling me.

Example: I have an object basket with a list of fruit objects. So normally I would build my routes like this baskets/{basketId}/fruits/{fruitId). But fruit is an interface and there are different implementations like apples and oranges that all require their own resource representation.

So how do I build my routes now?

Like one of those?:

baskets/{basketId}/fruits/{fruitId}/apple,

baskets/{basketId}/fruits/{fruitId)/orange and so on

baskets/{basketId}/fruits/{fruitId}/apples/{fruitId} ,
baskets/{basketId}/fruits/{fruitId}/oranges/{fruitId}

baskets/{basketId}/apples/{fruitId},

baskets/{basketId}/oranges/{fruitId}

What would be the restful way?

答:
The point of an interface is to hide the fact that there are different possible implementations. When you sit in a restaurant, basically you care only that you'll get service from someone. You may or may not be aware that you might get service from Jose, Marcia, or Stephanie, and you definitely don't want to have to do different things in order to get the same cheeseburger from different waiters. Your view of the transaction as a consumer is "get a cheeseburger", not "talk to Jose"/"talk to Marcia"/"talk to Stephanie".

If the consumer has to know about all the possible implementations, and which one he wants to access, then for purposes of your API you might just as well not have an interface, since you're not actually saving the effort that it's supposed to save. It can still be useful to make details of the implementation easier, but as long as the difference between the alternative object classes is externally visible, the interface ceases to be a useful API component.


答:
I assume all the fruits, apples, oranges, and so one, all have fruit ids. So if you want to reference a specific fruit in a basket, then:

/baskets/{basketId}/fruits/{fruitId)

is still valid. However, if the "fruitId" is unique, it would me much better to just use

/fruits/{fruitId)

However, if you only want to see certain types of fruits in a basket, then you can take advantage of the query string in it's role of "narrowing" the resource:

baskets/{basketId}?fruits=mango

or

baskets/{basketId}?fruits=apple&fruits=banana

Once you get that list of items, each should have it's own ID & you can get them individually if you like.

From a RESTful point of view, there are two resources here:

a collection of the fruits in a given basket

an individual fruit

Use the query string to limit the collection resource, and use the (shorter) fruitId once you know which specific one you want.

BTW The problem remains the same if you are selecting fruits from someone's hat:

/hat/{hatId}?fruits=bananas&fruits=pineapples

EDIT: (taken from comments so it will be more readable)

To add an apple

POST /basket/{id}

(the apple representation)

POST is often considered the "append" verb, but you could use PUT. Note that you're appending the apple to the basket collection, so you use the collection URI.

To find the apples in the basket:

GET /basket/{id}?fruits=apple

EDIT EDIT: If you have some other code/value/attribute in mind, just support that in the query string:

GET /basket/{id}?color=red

Title: How to design routes for generalized/specialized resources

Body:
I hope I can explain what is troubling me.

Example: I have an object basket with a list of fruit objects. So normally I would build my routes like this baskets/{basketId}/fruits/{fruitId). But fruit is an interface and there are different implementations like apples and oranges that all require their own resource representation.

So how do I build my routes now?

Like one of those?:

baskets/{basketId}/fruits/{fruitId}/apple,

baskets/{basketId}/fruits/{fruitId)/orange and so on

baskets/{basketId}/fruits/{fruitId}/apples/{fruitId} ,
baskets/{basketId}/fruits/{fruitId}/oranges/{fruitId}

baskets/{basketId}/apples/{fruitId},

baskets/{basketId}/oranges/{fruitId}

What would be the restful way?


问:
When to use Interface variable = new class variable OOP
I saw often people use this code like

```<code>interface IAnimal
{
    void die();
}

class Cat : IAnimal
{
    void die() { ... }
    void meow() { ... }
}

IAnimal anAnimal = new Cat();
Cat aCat= new Cat();
</code>```

C# knows for sure anAnimal.die() works, because die() is defined in IAnimal. But it won't let you do anAnimal.meow() even though it's a Cat, whereas aCat can invoke both methods.

Why and when we should write this kind of code:

```<code>IAnimal anAnimal = new Cat();
</code>```

What is the advantage?

答:
Because although the compiler could deduce that the meow() call would succeed in this case, it can't do so in every conceivable program, and it's much better to have a simple, easy-to-remember policy of "no type inference" than "I'm going to try some type inference for ya, but I'm warnin' you, I'm not gonna find all the demonstrably legal calls you might expect, so no guarantees."

Therefore, if you're going to call meow() anyway, there is no point whatsoever in declaring something as Animal. Just go ahead and admit that it's a Cat. Interfaces are a useful construct, but they can earn their pay only if you're willing to let them do their abstraction thing, and forget about the exact species.

In general, it rarely makes any sense to declare something as an abstract supertype when you then immediately assign it to a constructor call, i.e. a concrete type. But imagine you had a DogFactory, a CatFactory and a BirdFactory, all of which implement a common PetFactory interface. The PetFactory would contain a method Animal getPet(), and each concrete factory would do something like return new Cat(). The concrete type is needed to actually construct an object; the interface is needed so that different providers can all satisfy the same interface, which simplifies weaving together the application at a higher level.

ContentLicense: CC BY-SA 4.0