答:
In REST, resource definition is very broad. It's really however you want to bundle some data.

It's useful to think of a search resource as a collection resource. The query parameters, sometimes called the searchable portion of the URI, narrow the resource down to the items the client is interested in.

For example, the main Google URI points to a collection resource of "links to every site on the Internet". Query parameters narrow that to the sites you want to see.

(URI = universal resource identifier, of which URL = universal resource locator, where the familiar "http://" is the default format for a URI. So URL is a locator, but in REST its good to generalize that to a resource identifier. People use them interchangably, though.)

Since the resource you're searching on in your example is the jobs collection, it makes sense to search with

GET site/jobs?type=blah&location=here&etc=etc

(return) {jobs: [{job: ...}]}

And then use POST, which is the append or process verb to add new items to that collection:

POST site/jobs

{job: ...}

Note that it's the same structure for the job object in each case. A client can GET a collection of jobs, using query params to narrow the search, and then use the same format for one of the items to POST a new job. Or it can take one of those items and PUT to its URI to update that one.

For really long or complicated query strings, convention makes it OK to send those as POST requests instead. Bundle the query paramters up as name/value pairs, or nested objects in a JSON or XML structure and send it in the body of the request. For example, if your query has nested data instead of a bunch of name/value pairs. The HTTP spec for POST describes it as the append or process verb. (If you want to sail a battleship through a loophole in REST, use POST.)

I'd use that as the fallback plan, though.

What you lose when you do that though is a) GET is nullipotent -- that is, it doesn't change anything -- POST is not. So if the call fails, middleware won't automatically retry or cache results, and 2) with the search parameters in the body, you can't cut and paste the URI anymore. That is, the URI isn't a specific identifier for the search you want.

To differntiate between "create" from "search". There are a couple of options that are consistent with REST practice:

You could do it in the URI by adding something to the name of the collection, like job-search instead of jobs. That just means you're treating the search collection as a separate resource.

Since the semantics of POST is both append OR process, you could identify search bodies with the payload. Like {job: ...} vs. {search: ...}. It's up to the POST logic to post or process it appropriately.

That's pretty much a design/implementation preference. I don't think there's a clear convention.

So, like you've already laid out, the idea is to define a collection resource for jobs

site/jobs

Search with GET + query params to narrow the search. Long or structured data queries go into the body of a POST (possibly to a separate search collection). Create with POST to append to the collection. And update with PUT to a specific URI.

(FWIW the style convention with URIs is to use all lowercase with words separated by hyphens. But that doesn't mean you have to do it that way.)

(Also, I should say that from your question, it's clear that you're a long way down this road. I spelled things out kind of explicitly just to line them up, but your question had already addressed most of the semantic issues in this answer. I was just lacing it with some convention and practice.)


问:
How can I pull data from PeopleSoft on demand?
I work in IT at a university and I'm working with about 5 different departments to develop a new process for students to apply to a specific school within the university (not the university as a whole).  We're using a  web-based college application vendor and adding the applicant questions for the school itself to the main university application.  Currently the main application feeds into PeopleSoft.  The IT staff here is building a new table to hold just our school's applicant data.  I want to be able to access that data from PeopleSoft for use in external applications, but our IT staff doesn't really seem to understand what I'm requesting, as they simply tell me I can have access to the PS query tools.  The problem is, I don't want to run just ad hoc queries, I want to be able to connect from outside PeopleSoft and show current data within the external app.

I am unable to find documentation or get a clear answer to my question.  Does PeopleSoft support access via a web services API or anything similar, and does that sound like the right direction for me to take?

答: Would a delivered query work? The can create an SQR which will process the query at any given time through process scheduler and delivered it to your email</p>

ContentLicense: CC BY-SA 3.0


问:
Factory Method vs. Factory Method design pattern
I am currently studying design patterns from the book (which, although I didn't try anything else, I find excellent) Head First Design Patterns.

I'm confused about two concepts: The Factory Method, and the Factory Method Design Pattern.

I was trying to understand what each one means, and I came to some conclusion. I'd like to know if my definitions are exact.

The Factory Method is a method that is meant to do one thing: Create an object of a specific supertype and return it. It may or may not take a parameter, and may or may not 'decide' using if statements what kind of concrete object to create.

For example, this is a factory method:

```<code>public Hat createHat(String hatColor){

    Hat hat;

    if (hatColor.equals("red")) hat = new RedHat();
    else if (hatColor.equals("blue")) hat = new BlueHat();
    else if (hatColor.equals("green")) hat = new GreenHat();
    else hat = new DefaultHat();

    return hat;

}
</code>```

The Factory Method Design Pattern is named after the Factory Method.

This pattern provides a specific way to encapsulate object creation from the client.

It works like so: The pattern is a system of two classes, the Creator and the ConcreteCreator. The Creator is an abstract class, and the ConcreteCreator is a subclass of that class.

The job of the ConcreteCreator - create an object and return it using a factory method. It only has to contain this one method.

The job of the Creator - manipulate and use the object received from it's subclass, the ConcreteCreator, and usually return it to the client.

It is done like so:

The Creator contains an abstract method, it's signature something like SupertypeObject createObject(). Whenever it needs an object of type SupertypeObject, it calls createObject().

Thing is, createObject() is as I said abstract. It's the ConcreteCreator's job to implement this method.

This way, the implementation of createObject() is hidden from the Creator. It doesn't know what concrete object it gets, but it knows for sure that it's of type SypertypeObject.

This way, a client can use the Creator object to create objects of some supertype, but the concrete objects created will depend on the subclass. Thus declaring ShoeFactory factory = new CaliforniaStyleShoesFactory(), will make the factory produce california style shoes, while ShoeFactory factory = new NYStyleShoesFactory() will make the factory produce NY style shoes. Since the implementation of creating the concrete objects depends on the ConcreteCreator.

Code to demonstrate:

```<code>Class Client(){

    public static void main(String[] args){

        ShoeFactory factory;
        Shoe shoe;

        factory = new NYStyleShoeFactory();
        shoe = factory.makeShoe();
        System.out.println(shoe.getDescription()); // "A NY style shoe".

        // ShoeFactory's makeShoe() invokes createShoe() in the subclass, receives a Shoe
        // (doesn't know the concrete type of the Shoe. Depends on the subclass) and
        // does manipulations on it.
        // Returns the Shoe to the client.

        factory = new CaliforniaStyleShoeFactory():
        shoe = factory.makeShoe();
        System.out.println(shoe.getDescription()); // "A California style shoe".

}

}
</code>```

Is my understanding of the two concepts accurate? Thanks

答:
Yes, you are right.

The pattern is called like that because it describes a known, well accepted solution using a factory method.

The pattern could have been named "XXXX". That doesn't matter.

Regarding @pdr's comment about what you describe being really an "Abstract Factory", the following images clarify the  difference, Factory Method is exactly what you describe:

The images are taken from this PDF taken from this site. It was maded by a software engineer by the name of Jason McDonald.


问:
Print bottom view of a binary tree
For a binary tree we define horizontal distance as follows:

```<code>    Horizontal distance(hd) of root = 0
    If you go left then hd = hd(of its parent)-1, and
    if you go right then hd = hd(of its parent)+1.
</code>```

The bottom view of a tree then consists of all the nodes of the tree, where there is no node with the same hd and a greater level. (There may be multiple such nodes for a given value of hd. In this case all of them belong to the bottom view.) I'm looking for an algorithm that outputs the bottom view of a tree.

Examples:

Suppose the binary tree is:

```<code>         1
        /  \
       2    3
      / \  / \
     4   5 6  7
            \
             8
</code>```

Bottom view of the tree is: 4 2 5 6 8 7

```<code>    Ok so for the first example,
    Horizontal distance of node with value 1: 0, level = 1
    Horizontal distance of node with value 2: 0 - 1 = -1, level = 2
    Horizontal distance of node with value 3: 0 + 1 = 1, level = 2
    Horizontal distance of node with value 4: -1 - 1 = -2, level = 3
    Horizontal distance of node with value 5: -1 + 1 = 0, level = 3
    Horizontal distance of node with value 6: 1 - 1 = 0, level = 3
    Horizontal distance of node with value 7: 1 + 1 = 2, level = 3
    Horizontal distance of node with value 8: 0 + 1 = 1, level = 4

    So for each vertical line that is for hd=0, print those nodes which appear in the last level of that line.
    So for hd = -2, print 4
    for hd = -1, print 2
    for hd = 0, print 5 and 6 because they both appear in the last level of that vertical line
    for hd = 1, print 8
    for hd = 2, print 7
</code>```

One more example for reference :

```<code>         1
      /     \
    2         3
   / \       / \
  4   5     6     7
 / \ / \   / \    / \
8  9 10 11 12 13 14 15
</code>```

So the output for this will be :
8 4 9 10 12 5 6 11 13 14 7 15

```<code>Similarly for this example
hd of node with value 1: 0, , level = 1
hd of node with value 2: -1, level = 2
hd of node with value 3: 1, level = 2
hd of node with value 4: -2, level = 3
hd of node with value 5: 0, , level = 3
hd of node with value 6: 0, level = 3
hd of node with value 7: 2, level = 3
hd of node with value 8: -3, level = 4
hd of node with value 9: -1, level = 4
hd of node with value 10: -1, level = 4
hd of node with value 11: 1, level = 4
hd of node with value 12: -1, level = 4
hd of node with value 13: 1, level = 4
hd of node with value 14: 1, level = 4
hd of node with value 15: 3, level = 4

So, the output will be:
hd = -3, print 8
hd = -2, print 4
hd = -1, print 9 10 12
hd = 0, print 5 6
hd = 1, print 11 13 14
hd = 2, print 7
hd = 3, print 15

So the ouput will be:
8 4 9 10 12 5 6 11 13 14 7 15
</code>```

I already know a method in which I can do it using a lot of extra space (a map, and a 1-D array for storing the level of the last element in that vertical line) and with time complexity of $O(N \log N)$.
And this is the implementation of this method:

```<code>#include <iostream>
#include <cstdio>
#include <map>
#include <vector>

using namespace std;

struct Node{
       int data;
       struct Node *left, *right;
};

Node* newNode(int data)
{
    Node *temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}

int height(Node *node)
{
    if(node == NULL)
            return 0;
    else{
         int lh = height(node->left);
         int rh = height(node->right);

         if(lh > rh)
               return (lh+1);
         else
               return (rh+1);
    }
}

void printBottom(Node *node, int level, int hd, int min, map< int, vector<int> >& visited, int lev[], int l)
{
     if(node == NULL)
             return;
     if(level == 1){
              if(lev[hd-min] == 0 || lev[hd-min] == l){
                      lev[hd-min] = l;
                      visited[hd-min].push_back(node->data);
              }
     }
     else if(level > 1)
     {
          printBottom(node->left, level-1, hd-1, min, visited, lev, l);
          printBottom(node->right, level-1, hd+1, min, visited, lev, l);
     }
}

void findMinMax(Node *node, int *min, int *max, int hd)
{
     if(node == NULL)
             return;

     if(hd < *min)
          *min = hd;
     else if(hd > *max)
          *max = hd;

     findMinMax(node->left, min, max, hd-1);
     findMinMax(node->right, min, max, hd+1);
}

int main()
{
    Node *root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->left = newNode(6);
    root->right->right = newNode(7);
    root->left->left->left = newNode(8);
    root->left->left->right = newNode(9);
    root->left->right->left = newNode(10);
    root->left->right->right = newNode(11);
    root->right->left->left = newNode(12);
    root->right->left->right = newNode(13);
    root->right->right->left = newNode(14);
    root->right->right->right = newNode(15);

    int min = 0, max = 0;

    findMinMax(root, &min, &max, 0);

    int lev[max-min+1];
    map < int, vector<int> > visited;
    map< int,vector<int> > :: iterator it;

    for(int i = 0; i < max-min+1; i++)
            lev[i] = 0;

    int h = height(root);

    for (int i=h; i>0; i--){
        printBottom(root, i, 0, min, visited, lev, i);
    }

    for(it = visited.begin() ; it != visited.end() ; it++) {
        for(int i=0 ; i < it->second.size() ; i++) {
            cout << it->second[i] << " ";
        }
    }

    return 0;
}
</code>```

I am seeking help to do this in more optimized way, which used less space or time. Is there any other efficient method for this problem?

答:
First, you can get the time complexity down to O(n), while keeping the same space complexity. You can do this by filling visited in a single run of printBottom:

```<code>void printBottom(Node *node, int level, int hd, int min, map< int, vector<int> >& visited, int lev[])
{
     if(node == NULL)
             return;
     if(lev[hd-min] < level){
         lev[hd-min] = level;
         visited[hd-min] = new vector<int>; //erase old values, they are hidden by the current node
     }
     if(lev[hd-min] <= level){
         visited[hd-min].push_back(node->data);
     }
     printBottom(node->left, level+1, hd-1, min, visited, lev);
     printBottom(node->right, level+1, hd+1, min, visited, lev);
}
</code>```

with the initial call printBottom(root, 1, 0, min, visited, lev);

If you insist on the nodes beig output in order of increasing value of hd, I don't think you can improve space consumption. However, if you allow a different order of output, you can get rid of visited, by first determining for each value of 'hd', which level should be output and then making another pass, printing the values that match:

```<code>void fillLev(Node *node, int level, int hd, int min, int lev[])
{
     if(node == NULL)
             return;
     if(lev[hd-min] < level){
         lev[hd-min] = level;
     }
     fillLev(node->left, level+1, hd-1, min, lev);
     fillLev(node->right, level+1, hd+1, min, lev);
}
void printBottom(Node *node, int level, int hd, int min, int lev[])
{
     if(node == NULL)
             return;
     if(lev[hd-min] == level){
         cout << node->data;
     }
     printBottom(node->left, level+1, hd-1, min, lev);
     printBottom(node->right, level+1, hd+1, min, lev);
}
</code>```

with calls fillLev(root, 1, 0, min, lev); and printBottom(root, 1, 0, min, lev);.

Title: Print bottom view of a binary tree

Body:
First, you can get the time complexity down to O(n), while keeping the same space complexity. You can do this by filling visited in a single run of printBottom:

void printBottom(Node *node, int level, int hd, int min, map< int, vector<int> >& visited, int lev[])
{
     if(node == NULL)
             return;
     if(lev[hd-min] < level){
         lev[hd-min] = level;
         visited[hd-min] = new vector<int>; //erase old values, they are hidden by the current node
     }
     if(lev[hd-min] <= level){
         visited[hd-min].push_back(node->data);
     }
     printBottom(node->left, level+1, hd-1, min, visited, lev);
     printBottom(node->right, level+1, hd+1, min, visited, lev);
}

with the initial call printBottom(root, 1, 0, min, visited, lev);

If you insist on the nodes beig output in order of increasing value of hd, I don't think you can improve space consumption. However, if you allow a different order of output, you can get rid of visited, by first determining for each value of 'hd', which level should be output and then making another pass, printing the values that match:

void fillLev(Node *node, int level, int hd, int min, int lev[])
{
     if(node == NULL)
             return;
     if(lev[hd-min] < level){
         lev[hd-min] = level;
     }
     fillLev(node->left, level+1, hd-1, min, lev);
     fillLev(node->right, level+1, hd+1, min, lev);
}
void printBottom(Node *node, int level, int hd, int min, int lev[])
{
     if(node == NULL)
             return;
     if(lev[hd-min] == level){
         cout << node->data;
     }
     printBottom(node->left, level+1, hd-1, min, lev);
     printBottom(node->right, level+1, hd+1, min, lev);
}

with calls fillLev(root, 1, 0, min, lev); and printBottom(root, 1, 0, min, lev);.


问:
Should I use HTTP search
I am working on a web api and I am curios about the HTTP SEARCH verb and how you should use it.

My first approach was, well you could use it surely for a search. But asp.net WebApi doesn't support the SEARCH verb.

My question is basically, should I use SEARCH or is it not important?

PS: I found the SEARCH verb in fiddler2 from telerik.

答:
The HTTP protocol is defined by RFC documents.  RFC2616 defines HTTP/1.1 the current release.

SEARCH is not documented as a verb in this document.

Title: Should I use HTTP search


问:
How should I organize programming files into directories?
Sometimes, one creates a exploratory prototype and forgets about structure in the directories...

What are good tips on dividing the programming files over (several levels of) directories?

答:
If your language is OOP and package based (Eg Java), then you should probably keep each package in its own folder (eg my/package/name) to keep with the convention.

If your language isn't package based (Eg PHP), then organize by what each file does. Here's an example

Does this do utility functions? Goes in /util

Is this a 3rd party plugin? Goes in /plugin

Is this part of the admin panel? Goes in /admin, along with ALL supporting files

Is this Javascript? Goes in /javascript

Is this CSS? Goes in /css

Is this a template? Goes in /templates/templateName

etc

Language agnostic, Most people have a /src directory for all source files, a /lib directory for libraries, and a /bin or /dist directory for builds.

ContentLicense: CC BY-SA 2.5


答:
You said something in a comment that bears highlighting and explanation.

How can one method be a pattern?

While most design patterns are templates of classes or objects and how they all relate to each other, that's really only true of object oriented design patterns.  The topic of design patterns has applicability far beyond that, and there are some design patterns, like factory or interface, that apply very well to implementations using a single method or function.

For example, we can use both in a simple functional JavaScript program.  Let's say we have something like what follows, to call an ActiveX object our company uses on an Intranet.

```<code>var oNeat = new ActiveXObject("OurCompany.NeatThing");
oNeat.DoStuff();
</code>```

Seems simple, except we can wrap both lines above in a pair of respective pattens.

```<code>function GetNeatThing() {
  return new ActiveXObject("OurCompany.NeatThing");
}

function DoStuff(onWhat) {
  if(onWhat && onWhat.DoStuff) {
    onWhat.DoStuff();
  }
}
</code>```

and then our call becomes simply:

```<code>var oNeat = GetNeatThing();
DoStuff(oNeat);
</code>```

While this doesn't get us a lot by itself, we do get significantly better modularity.  If we move the GetNeatThing and DoStuff functions into their own js file, and use them instead of the hard-coded references, we wind up with all of the benefits of having a Factory and an Interface.

(Specifically, we could change the progID of our NeatThing, or even move it away from ActiveX to something like a web server.  And we could even change how it works, by re-naming the atrocious "DoStuff" method to something more descriptive, while not breaking existing code.)

Title: Factory Method vs. Factory Method design pattern

Body:
I am currently studying design patterns from the book (which, although I didn't try anything else, I find excellent) Head First Design Patterns.

I'm confused about two concepts: The Factory Method, and the Factory Method Design Pattern.

I was trying to understand what each one means, and I came to some conclusion. I'd like to know if my definitions are exact.

The Factory Method is a method that is meant to do one thing: Create an object of a specific supertype and return it. It may or may not take a parameter, and may or may not 'decide' using if statements what kind of concrete object to create.

For example, this is a factory method:

```<code>public Hat createHat(String hatColor){

    Hat hat;

    if (hatColor.equals("red")) hat = new RedHat();
    else if (hatColor.equals("blue")) hat = new BlueHat();
    else if (hatColor.equals("green")) hat = new GreenHat();
    else hat = new DefaultHat();

    return hat;

}
</code>```

The Factory Method Design Pattern is named after the Factory Method.

This pattern provides a specific way to encapsulate object creation from the client.

It works like so: The pattern is a system of two classes, the Creator and the ConcreteCreator. The Creator is an abstract class, and the ConcreteCreator is a subclass of that class.

The job of the ConcreteCreator - create an object and return it using a factory method. It only has to contain this one method.

The job of the Creator - manipulate and use the object received from it's subclass, the ConcreteCreator, and usually return it to the client.

It is done like so:

The Creator contains an abstract method, it's signature something like SupertypeObject createObject(). Whenever it needs an object of type SupertypeObject, it calls createObject().

Thing is, createObject() is as I said abstract. It's the ConcreteCreator's job to implement this method.

This way, the implementation of createObject() is hidden from the Creator. It doesn't know what concrete object it gets, but it knows for sure that it's of type SypertypeObject.

This way, a client can use the Creator object to create objects of some supertype, but the concrete objects created will depend on the subclass. Thus declaring ShoeFactory factory = new CaliforniaStyleShoesFactory(), will make the factory produce california style shoes, while ShoeFactory factory = new NYStyleShoesFactory() will make the factory produce NY style shoes. Since the implementation of creating the concrete objects depends on the ConcreteCreator.

Code to demonstrate:

```<code>Class Client(){

    public static void main(String[] args){

        ShoeFactory factory;
        Shoe shoe;

        factory = new NYStyleShoeFactory();
        shoe = factory.makeShoe();
        System.out.println(shoe.getDescription()); // "A NY style shoe".

        // ShoeFactory's makeShoe() invokes createShoe() in the subclass, receives a Shoe
        // (doesn't know the concrete type of the Shoe. Depends on the subclass) and
        // does manipulations on it.
        // Returns the Shoe to the client.

        factory = new CaliforniaStyleShoeFactory():
        shoe = factory.makeShoe();
        System.out.println(shoe.getDescription()); // "A California style shoe".

}

}
</code>```

Is my understanding of the two concepts accurate? Thanks

Body:
You said something in a comment that bears highlighting and explanation.

How can one method be a pattern?

While most design patterns are templates of classes or objects and how they all relate to each other, that's really only true of object oriented design patterns.  The topic of design patterns has applicability far beyond that, and there are some design patterns, like factory or interface, that apply very well to implementations using a single method or function.

For example, we can use both in a simple functional JavaScript program.  Let's say we have something like what follows, to call an ActiveX object our company uses on an Intranet.

var oNeat = new ActiveXObject("OurCompany.NeatThing");
oNeat.DoStuff();

Seems simple, except we can wrap both lines above in a pair of respective pattens.

function GetNeatThing() {
  return new ActiveXObject("OurCompany.NeatThing");
}

function DoStuff(onWhat) {
  if(onWhat && onWhat.DoStuff) {
    onWhat.DoStuff();
  }
}

and then our call becomes simply:

var oNeat = GetNeatThing();
DoStuff(oNeat);

While this doesn't get us a lot by itself, we do get significantly better modularity.  If we move the GetNeatThing and DoStuff functions into their own js file, and use them instead of the hard-coded references, we wind up with all of the benefits of having a Factory and an Interface.

(Specifically, we could change the progID of our NeatThing, or even move it away from ActiveX to something like a web server.  And we could even change how it works, by re-naming the atrocious "DoStuff" method to something more descriptive, while not breaking existing code.)


问:
Isolating unit tests in python
As a 30-year software developer, mostly in OO languages, but a newbie at python, I'm looking to find what is best practise for isolating unit tests in python.

Let's say I have the following, semi-pseudo-code. I know some_database_client isn't a real database client:

```<code>from some_database_client import connection

connection.connect('server_id', 'username', 'password')

def function_under_test():
    return connection.get_value('some_value_reference') + 10
</code>```

If I write a test for function_under_test(), then I'm effectively testing the potentially enormous amount of logic in connecting and retrieving the data from connection.

Instead, I really want to test that function_under_test() adds ten to the value retrieved.

This relates to a practical real-world example where the module-level variable connection (or it's real-world equivalent) is referenced heavily all over the code.

Therefore, it would involve a large and therefore very risky change to pass connection as an argument to all the functions that use it. Without doing this though, I can't easily separate the variable connection when I'm trying to unit-test the functions that use it. connection is instantiated before I even get to run the unit-test.

Is there a recommended way to isolate functions like this for testing? I can certainly think of many, many ways, but I suspect that some have more of the "Zen of Python" about them than others. e.g. Wrapping everything in classes is a possibility, but that is perhaps moving too far away from keeping stuff simple, which is a goal of python.

答:
This relates to a practical real-world example where the module-level variable connection (or it's real-world equivalent) is referenced heavily all over the code. Therefore, while it would involve a large and therefore very risky change to pass connection as an argument to all the functions that use it.

That's the only clean solution. Too late now, but in the future avoid such hidden dependencies if possible. The only other option I can think of is to change the Python path to point to an alternate some_database_client with a stub connection when you run your unit tests.

However...

Instead, I really want to test that function_under_test() adds ten to the value retrieved.

You don't really need to test this. You can prove the correctness of such a trivial function by inspection. Writing unit tests to show it adds ten regardless of whether the return value of connection is 0, positive, negative, odd or even is slower than just looking at it and it still doesn't guarantee correctness. Knowing what not to test is just as important as knowing what to test.

Title: Isolating unit tests in python


问:
Is better Show() + Hide() or SetVisible(bool visible)?
What is better and why? (From interface-design point of view) :

a) To have two Show() and Hide() functions

b) To have one SetVisible(bool visible) function

EDIT: For example some object have visibility state and this functions is used to change it.

c) To have all three Show(), Hide(), SetVisible(bool visible) functions

答:
I'd suggest a slightly modified interface:

```<code>Show();
Hide();
ToggleVisible();
ToggleVisible(bool visible);
</code>```

Better names

These method names help the developer to decide which method to use based on what needs to be done.  Whereas SetVisible(bool visible) can confuse a developer because it conveys the same semantic meaning as Show() and Hide(), Toggle() implies the existence of a condition that determines the action.  It thus becomes intuitive to the developer when to use each method.

Reduced code redundancy

The benefit to having multiple methods in your interface is that it simplifies the calling code.  You could just expose Show() and Hide(), but:

You'd probably require some kind of SetVisible() private method to do the real work behind the scenes (or write redundant code for Show() and Hide()).

The calling code might have many redundant if/else blocks just to choose which method to use.  This bloats the code in my opinion.

If I were the consumer, I'd likely just write my own wrapper function that does what SetVisible() (or Toggle()) already does in order to avoid code bloat (I hate redundant code).  Thus duplicating a method that probably already exists as a private method in the implementation.

Body:
I'd suggest a slightly modified interface:

Show();
Hide();
ToggleVisible();
ToggleVisible(bool visible);

Better names

These method names help the developer to decide which method to use based on what needs to be done.  Whereas SetVisible(bool visible) can confuse a developer because it conveys the same semantic meaning as Show() and Hide(), Toggle() implies the existence of a condition that determines the action.  It thus becomes intuitive to the developer when to use each method.

Reduced code redundancy

The benefit to having multiple methods in your interface is that it simplifies the calling code.  You could just expose Show() and Hide(), but:

You'd probably require some kind of SetVisible() private method to do the real work behind the scenes (or write redundant code for Show() and Hide()).

The calling code might have many redundant if/else blocks just to choose which method to use.  This bloats the code in my opinion.

If I were the consumer, I'd likely just write my own wrapper function that does what SetVisible() (or Toggle()) already does in order to avoid code bloat (I hate redundant code).  Thus duplicating a method that probably already exists as a private method in the implementation.


答:
First, initializing a global connection at the module level is really, really bad practice. Rather, if you have to do that, you should have something like

```<code>def connect():
   connection.connect('server_id', 'username', 'password')

if __name__ == '__main__':
   connect()
</code>```

So that you only actually connect in main execution.

Fortunately, from your code example, even if you connect to the database at the start of the module, you can just ignore that assignment and assign a new mock connection in your test.

```<code>def my_test():
   connection = MockConnection()
   function_under_test()
   assert(...)
</code>```

FWIW I found Python really easy to test because if there's some artifact, dependency, or function that was hard to work with, I'd just shove in an implementation that let me focus on the test.

Title: Isolating unit tests in python

Body:
As a 30-year software developer, mostly in OO languages, but a newbie at python, I'm looking to find what is best practise for isolating unit tests in python.

Let's say I have the following, semi-pseudo-code. I know some_database_client isn't a real database client:

```<code>from some_database_client import connection

connection.connect('server_id', 'username', 'password')

def function_under_test():
    return connection.get_value('some_value_reference') + 10
</code>```

If I write a test for function_under_test(), then I'm effectively testing the potentially enormous amount of logic in connecting and retrieving the data from connection.

Instead, I really want to test that function_under_test() adds ten to the value retrieved.

This relates to a practical real-world example where the module-level variable connection (or it's real-world equivalent) is referenced heavily all over the code.

Therefore, it would involve a large and therefore very risky change to pass connection as an argument to all the functions that use it. Without doing this though, I can't easily separate the variable connection when I'm trying to unit-test the functions that use it. connection is instantiated before I even get to run the unit-test.

Is there a recommended way to isolate functions like this for testing? I can certainly think of many, many ways, but I suspect that some have more of the "Zen of Python" about them than others. e.g. Wrapping everything in classes is a possibility, but that is perhaps moving too far away from keeping stuff simple, which is a goal of python.

Body:
First, initializing a global connection at the module level is really, really bad practice. Rather, if you have to do that, you should have something like

def connect():
   connection.connect('server_id', 'username', 'password')

if __name__ == '__main__':
   connect()

So that you only actually connect in main execution.

Fortunately, from your code example, even if you connect to the database at the start of the module, you can just ignore that assignment and assign a new mock connection in your test.

def my_test():
   connection = MockConnection()
   function_under_test()
   assert(...)

FWIW I found Python really easy to test because if there's some artifact, dependency, or function that was hard to work with, I'd just shove in an implementation that let me focus on the test.


问:
Using Python/Ruby/Lua for Java startup scripts
I have a number of distinct Java utilities that are shipped together. Currently there are two startup scripts for each utility: a .sh one for Linux and a .bat for Windows.

I'm thinking of rewriting the startup scripts using Python, or perhaps Ruby, Perl, Lua or other scripting language. This way I avoid having different versions for each OS.

Is this a good idea? Are there projects that already use this approach? What scripting language would be best suited for the task?

What other alternatives exist to avoid having separate .sh, .bat files for this group of utilities?

答: In such cases, I use python scripts compiled for end-users. This ensures sufficient portability and project's simplicity. In addition, scripts shares this same configuration files as the products. It's not an answer. It's just suggestion. Your question isn't precise.</p>


问:
Which features of shell scripting are relevant for PHP/Python development?
I'm a PHP/Python programmer learning Java and C#(.NET).

My main development OS is windows 7 but I've used Linux and I currently dual-boot with Ubuntu. My Linux knowledge however, is pretty limited. I can work with the command line on simple tasks but that's pretty much it. I don't do any shell scripting and I don't know many important commands.

My interests are web development, mobile apps and maybe some embedded stuff in the future.  Will shell scripting skills be useful for these interests and if so, how?

答:
You don't have to learn it but it will make you a better programmer.  You will learn how to do things in a different way than the Windows way.  Using any of the *sh shells will eventually lead to scripting and using regular expressions, automating installations, parsing large files, etc.

I don't care about being mocked for not knowing it, as much as I care about how cool it is every time I learn how to do something else in Linux.  It just keeps getting better and better with each new bit.

Powershell has a lot that comes from the nix world, they finally realized that in order to have automation you need a good console (kudos to MS for that).  Both Perl and Python seem to be a mixture of C, bash, sed, awk, all meshed into a good thing in their own way.

At the very least you will have something else to put in your resume but that really is not the best thing you will get out of it.

I'm sure you will find on your own things that will make you go: "Wow, that is so cool!"  My first was being able to "kill" Apache using a USR1 signal to get it to reload a new config file and restart the logs, without ever stopping the service and continuing to receive connections.  Also ssh and rsync, good grief why wouldnt MS port them is beyond me.


答:
There is no way to accomplish what you want to do unless you are willing to have the users potentially install another language just to run your software. You can't guarantee that your users are going to have a scripting language installed. You are essentially pushing the inconvenience onto your users by asking them to install something extra just so your start-up scripts are easier for you to manage.

There is a solution to this however: continue to ship your .sh and .bat files so your software is more convenient to use but instead of maintaining them separately write a script to generate them for you in {scripting language of your choice}, possibly using {templating engine of your choice}, and have your build process run that script to generate your .bat/.sh files for you. That ensures that the logic is consistent between the platforms and you only have to maintain that logic in a single place.

Title: Using Python/Ruby/Lua for Java startup scripts

Body:
I have a number of distinct Java utilities that are shipped together. Currently there are two startup scripts for each utility: a .sh one for Linux and a .bat for Windows.

I'm thinking of rewriting the startup scripts using Python, or perhaps Ruby, Perl, Lua or other scripting language. This way I avoid having different versions for each OS.

Is this a good idea? Are there projects that already use this approach? What scripting language would be best suited for the task?

What other alternatives exist to avoid having separate .sh, .bat files for this group of utilities?


问:
Should I expose a "computed" value as a property or a method?
I have a C# class that represents a content type in a web content management system.

We have a field that allows a web content editor to enter an HTML template for how the object is displayed.  It basically uses the handlebars syntax for substituting object property values into the HTML string:

```<code><h1>{{Title}}</h1><p>{{Message}}</p>
</code>```

From a class design perspective, should I expose the formatted HTML string (with substitution) as a property or method?

Example as property:

```<code>public class Example
{
  private string _template;
  public string Title { get; set; }
  public string Message { get; set; }
  public string Html
  {
    get
    {
      return this.ToHtml();
    }
    protected set { }
  }

  public Example(Content content)
  {
    this.Title = content.GetValue("title") as string;
    this.Message = content.GetValue("message") as string;
    _template = content.GetValue("template") as string;
  }

  private string ToHtml()
  {
    // Perform substitution and return formatted string.
  }
}
</code>```

Example as method:

```<code>public class Example
{
  private string _template;
  public string Title { get; set; }
  public string Message { get; set; }

  public Example(Content content)
  {
    this.Title = content.GetValue("title") as string;
    this.Message = content.GetValue("message") as string;
    _template = content.GetValue("template") as string;
  }

  public string ToHtml()
  {
    // Perform substitution and return formatted string.
  }
}
</code>```

I'm not sure from a design standpoint does it make a difference or are there reasons why one approach is better than the other?

答:
ToHtml is correctly a method, as you have written it in both cases.  Just expose it publicly.

Knerd makes a good point: properties can be serialized.  You would never deserialize from the HTML, so it doesn't make much sense to make it a property from that perspective.

Consistent with the way ORM's and repository objects work: fields in a record or tuple are represented with properties, but you retrieve the record (or some form of it) using a method.


问:
Why write tests for code that I will refactor?
I am refactoring a huge legacy code class.  Refactoring (I presume) advocates this:

write tests for the legacy class

refactor the heck out of the class

Problem:  once I refactor the class, my tests in step 1 will need to be changed.  For example, what once was in a legacy method, now may be a separate class instead.  What was one method may be now several methods.  The entire landscape of the legacy class may be obliterated into something new, and so the tests I write in step 1 will almost be null and void.
In essence I will be adding Step 3. rewrite my tests profusely

What is the purpose then to write tests before refactor?  It sounds more like an academic exercise of creating more work for myself.  I am writing tests for the method now and I am learning more about how to test things and how the legacy method works.  One can learn this by just reading the legacy code itself, but writing tests is almost like rubbing my nose in it, and also documenting this temporary knowledge in separate tests.  So this way I almost have no choice but to learn what the code is doing.  I said temporary here, because I will refactor the heck out of the code and all my documentation and tests will be null and void for a significant part, except my knowledge will stay and allow me to be fresher on the refactoring.

Is that the real reason to write tests before refactor - to help me understand the code better?  There's got to be another reason!

Please explain!

Note:

There is this post: Does it make sense to write tests for legacy code when there is no time for a complete refactoring? but it say "write tests before refactor", but doesn't say "why", or what to do if "writing tests" seems like "busy work that will be destroyed soon"

答:
Ah, maintaining legacy systems.

Ideally your tests treat the class only through its interface with the rest of the code base, other systems, and/or user interface.  Interfaces. You can't refactor the interface without affecting those upstream or downstream components. If it's all one tightly coupled mess then you might as well consider the effort a re-write rather than refactoring, but it's largely semantics.

Edit:  Let's say part of your code measures something and it has a function that simply returns a value. The only interface is calling the function/method/whatnot and receiving the returned value. This is loose coupling and easy to unit test. If your main program has a sub-component that manages a buffer, and all calls to it depend on the buffer itself, some control variables, and it kicks back error messages through another section of code, then you could say that's tightly coupled and it's hard to unit test. You can still do it with sufficient amounts of mock objects and whatnot, but it gets messy. Especially in c. Any amount of refactoring how the buffer works will break the sub-component.

End Edit

If you're testing your class through interfaces that remain stable then your tests should be valid before and after the refactoring. This lets you make changes with confidence that you didn't break it. At least, more confidence.

It also lets you make incremental changes. If this is a big project, I don't think you're going to want to just tear it all down, build up a brand new system and then start developing tests. You can change one part of it, test it, and make sure that change doesn't bring the rest of the system down. Or if it does, you can at least see the giant tangled mess developing rather than be surprised by it when you release.

While you might split a method into three, they're still going to do the same thing the previous method did, so you can take the test for the old method, and split it into three. The effort of writing the first test isn't wasted.

Also, treating the knowledge of the legacy system as "temporary knowledge" isn't going to go well. Knowing how it previously did it's thing is vital when it comes to legacy systems. Vastly useful for the age old question of "why the hell does it do that?"


答:
Refactoring is cleaning up a piece of code (e.g. improving the style, design, or algorithms), without changing (externally visible) behavior. You write tests not to make sure that the code before and after refactoring is the same, instead you write tests as an indicator that your application before and after refactoring behaves the same: The new code is compatible, and no new bugs were introduced.

Your primary concern should be to write unit tests for the public interface of your software. This interface should not change, so the tests (that are an automated check for this interface) shouldn't change either.

However, tests are also useful to locate errors, so it can make sense to write tests for private parts of your software as well. These tests are expected to change throughout refactoring. If you want to change an implementation detail (like the naming of a private function), you first update the tests to reflect your changed expectations, then make sure that the test fails (your expectations are not fulfilled), then you change the actual code and check that all tests pass again. At no point should the tests for the public interface start to fail.

This is more difficult when performing changes on a larger scale, e.g. redesigning multiple codependent parts. But there will be some kind of boundary, and at that boundary you'll be able to write tests.

Title: Why write tests for code that I will refactor?

Body:
I am refactoring a huge legacy code class.  Refactoring (I presume) advocates this:

write tests for the legacy class

refactor the heck out of the class

Problem:  once I refactor the class, my tests in step 1 will need to be changed.  For example, what once was in a legacy method, now may be a separate class instead.  What was one method may be now several methods.  The entire landscape of the legacy class may be obliterated into something new, and so the tests I write in step 1 will almost be null and void.
In essence I will be adding Step 3. rewrite my tests profusely

What is the purpose then to write tests before refactor?  It sounds more like an academic exercise of creating more work for myself.  I am writing tests for the method now and I am learning more about how to test things and how the legacy method works.  One can learn this by just reading the legacy code itself, but writing tests is almost like rubbing my nose in it, and also documenting this temporary knowledge in separate tests.  So this way I almost have no choice but to learn what the code is doing.  I said temporary here, because I will refactor the heck out of the code and all my documentation and tests will be null and void for a significant part, except my knowledge will stay and allow me to be fresher on the refactoring.

Is that the real reason to write tests before refactor - to help me understand the code better?  There's got to be another reason!

Please explain!

Note:

There is this post: Does it make sense to write tests for legacy code when there is no time for a complete refactoring? but it say "write tests before refactor", but doesn't say "why", or what to do if "writing tests" seems like "busy work that will be destroyed soon"


问:
Moving Old Projects To Newer IDE's and Libraries
At work we have a few older projects that are stuck on .NET 1.1 and VS 2003. While these are probably to much work now to move forward I'm wondering if the effort to keep our newer projects up to date will be worth it. Specifically we would be looking at moving about 30 projects from .NET 3.5 to .NET 4.0 and VS2008 to VS2010.

My Questions for the community are:

Do you move your projects along as new tools and libraries become available or just start the newest stuff in the newest versions?

If you do move forward have you found the benefits out weigh the cost of the upgrade?

答:
We have about 30 small and medium sized projects, and generally take the approach that we migrate projects when we do non-trivial work on them. Occasionally, we undertake a consolidation exercise to move the oldest projects to the latest versions.

Of course, this means that our dev environments have multiple versions of Visual Studio, the .Net framework, SQL Server, IIS, Source Control, browser, etc.

Despite having to keep all these different tools up to date, this ad hoc approach actually works quite well.

Migrations that usually go very wel:

Visual Studio Versions (but see below)

Core SQL Server functions

.Net Versions

Source control (from VSS to Vault)

We don't usually migrate between languages unless the application is trivial.

Migrations that have been problematic:

DTS to SSIS

Reporting Servives. Different versions of SSRS are supported by different versions of Visual Studio.


答:
Use your tests to drive your code as you do it.  In the of legacy code this means writing tests for the code you are going to change.  That way they are not a separate artifact.  Tests should be about what the code needs to achieve and not about the inner guts of how it does it.

Generally you want to add tests on code that has none) for code you are going to refactor to make sure that the codes behaviour continues to work as anticipated.  Thus continually running the test suite while refactoring is a fantastic safety net.  The thought of changing code without a test suite to confirm the changes aren't affecting something unanticipated is scary.

As for the nitty gritty of updating old tests, writing new tests, deleting old tests, etc. I just see that as part of the cost of modern professional software development.


问:
How to write descriptive conditionals for ifs?
I've gotten into the habit of using excessively descriptive names.  In addition, I've also gotten into the habit of creating the conditions for ifs like so:

```<code>bool user_is_female  = user.get_gender() == GENDER_FEMALE;
bool user_is_warrior = user.get_unit_class() == CLASS_WARRIOR;
bool user_can_wear_battle_skirt = user_is_female && user_is_warrior;

if (user_can_wear_battle_skirt) {
    user.equip(EQUIPMENT_BATTLE_SKIRT);
}
</code>```

So, yeah, I dropped the "== true" or "true ==" that I've been taught was good practice. It seems to need less comments too. It is quite wordy/lengthy though. I was going for making the code more readable. So should I continue using this method? Any alternatives?

```<code>if (user.can_wear(battle_skirt)) {
    user.equip(battle_skirt);
}
</code>```

Was a suggestion that I had to delete because I posted in the wrong place.

答:
Conventionally, boolean variables start with verbs is, has or can.  This provides you with a visual marker that the variable is boolean.  You can use camelCase to distinguish between words.  So:

```<code>canWearBattleSkirt
isWarrior
hasMojo
</code>```

And so on.

Your mileage may vary; each programming language has its own conventions for naming things, and sometimes they are similar, but not always.

That said, things like BattleSkirt, Warrior and Mojo might be a better fit as parameters to some function like HasCapability(someCapability).  That way, you can treat the capabilities as data and not have them hard-coded.

Body:
Conventionally, boolean variables start with verbs is, has or can.  This provides you with a visual marker that the variable is boolean.  You can use camelCase to distinguish between words.  So:

canWearBattleSkirt
isWarrior
hasMojo

And so on.

Your mileage may vary; each programming language has its own conventions for naming things, and sometimes they are similar, but not always.

That said, things like BattleSkirt, Warrior and Mojo might be a better fit as parameters to some function like HasCapability(someCapability).  That way, you can treat the capabilities as data and not have them hard-coded.


答:
One approach is to move the decision to the individual item. Something along those lines:

```<code>class BattleSkirt : Item {
    bool mayUse(User user) {
        if (user.get_gender() != GENDER_FEMALE) {
            return false;
        }
        /* ... */
        return true;
    }
}

if (skirt.may use(user)) {
        user.equip(skirt);
}
</code>```

Now this leads to some duplication in different items. An approach there is to put those in some form of requirement classes. An item then can define its requirements and those can be checked.

```<code>class requireFemale : requirement {
    book check(User user) {
        return user.get_gender() != GENDER_FEMALE;
    }
};

class Item {
    book checkRequirements(User user) {
        for each requirement in requirements {
            If (!requirement.check(user)) {
                Return false;
            }
    }
};

class WarriorSkirt : Item {
     Vector<requirement> requirements = { require female() };
}
</code>```

At first this is more complex but can make this way more re maintainable especially if you allow requirements to inherit from each other.

Title: How to write descriptive conditionals for ifs?

Body:
I've gotten into the habit of using excessively descriptive names.  In addition, I've also gotten into the habit of creating the conditions for ifs like so:

```<code>bool user_is_female  = user.get_gender() == GENDER_FEMALE;
bool user_is_warrior = user.get_unit_class() == CLASS_WARRIOR;
bool user_can_wear_battle_skirt = user_is_female && user_is_warrior;

if (user_can_wear_battle_skirt) {
    user.equip(EQUIPMENT_BATTLE_SKIRT);
}
</code>```

So, yeah, I dropped the "== true" or "true ==" that I've been taught was good practice. It seems to need less comments too. It is quite wordy/lengthy though. I was going for making the code more readable. So should I continue using this method? Any alternatives?

```<code>if (user.can_wear(battle_skirt)) {
    user.equip(battle_skirt);
}
</code>```

Was a suggestion that I had to delete because I posted in the wrong place.

Body:
One approach is to move the decision to the individual item. Something along those lines:

class BattleSkirt : Item {
    bool mayUse(User user) {
        if (user.get_gender() != GENDER_FEMALE) {
            return false;
        }
        /* ... */
        return true;
    }
}

if (skirt.may use(user)) {
        user.equip(skirt);
}

Now this leads to some duplication in different items. An approach there is to put those in some form of requirement classes. An item then can define its requirements and those can be checked.

class requireFemale : requirement {
    book check(User user) {
        return user.get_gender() != GENDER_FEMALE;
    }
};

class Item {
    book checkRequirements(User user) {
        for each requirement in requirements {
            If (!requirement.check(user)) {
                Return false;
            }
    }
};

class WarriorSkirt : Item {
     Vector<requirement> requirements = { require female() };
}

At first this is more complex but can make this way more re maintainable especially if you allow requirements to inherit from each other.


问:
Is there a canonical resource on R programming?
Considering I have no programming background, Is there a resource out there that's the de-facto standard for describing best practices, design methodologies, and other helpful information on R programming? What about that resource makes it special?</p>

答:
I think the biggest challenge for me when I was learning R (and still learning) is the vast amount of information available for R (information overload really). I would suggest you purchase a book and use that as your defacto standard until you have a solid footing in R and handling data in R. There is literally a ton of information and help for using R. That is a huge benefit, but also can be a drawback. Especially if every example you come across by searching these forums or The Google uses different packages. The authors of most R books tend to be consistent and use the base R packages, or their favorite packages available form cran. The key to learning is consistency.

Although the references below are not specific to "programming" in R, and not "canonical" they are a great resource nonetheless and I will add them to supplement my answer.

The R Book - Michael J Crawley

R in a Nutshell


答:
It won't hurt you. Even in an all Microsoft company, it is becoming more and more increasingly likely that you'll run into at least a few Linux servers. Stack Overflow, for instance, uses Linux for their load balancers. This is especially true when virtualization comes into play.

As a programmer, you might do better by considering getting familiar with POSIX, not just a single UNIX-like variant. While it does have some quirks, it represents a lot of effort that went into an incredible attempt to establish a standard interface that is (mostly) portable across all UNIX like environments. Note, many UNIX like systems aren't 100% "posixly correct", but it is a good starting point.

As just a casual user, I can only suggest that it is fun to poke around in something new and learn new things. I guess it is possible to be a 'guru' with every single operating system one could think of, but I don't think that is the most useful endeavour for a programmer. Still, a working knowledge of stuff that you might encounter is good .. and from your question, you seem likely to encounter Linux in the future.

Title: Which features of shell scripting are relevant for PHP/Python development?

Body:
I'm a PHP/Python programmer learning Java and C#(.NET).

My main development OS is windows 7 but I've used Linux and I currently dual-boot with Ubuntu. My Linux knowledge however, is pretty limited. I can work with the command line on simple tasks but that's pretty much it. I don't do any shell scripting and I don't know many important commands.

My interests are web development, mobile apps and maybe some embedded stuff in the future.  Will shell scripting skills be useful for these interests and if so, how?


问:
Server side C# MVC with AngularJS
I like using .NET MVC and have used it quite a bit in the past.  I have also built SPA's using AngularJS with no page loads other than the initial one.  I think I want to use a blend of the two in many cases.  Set up the application initially using .NET MVC and set up routing server side.  Then set up each page as a mini-SPA.  These pages can be quite complex with a lot of client side functionality.

My confusion comes in how to handle the model-view binding using both .NET MVC and the AngularJS scope.  Do I avoid the use of razor Html helpers?  The Html helpers create the markup behind the scene so it could get messy trying to add angularjs tags using the helpers.  So how to add ng-model for example to @Html.TextBoxFor(x => x.Name).  Also ng-repeat wouldn't work because I'm not loading my model into the scope, right?  I'd still want to use a c# foreach loop?

Where do I draw the lines of separation?  Has anyone gotten .NET MVC and AngularJS to play nicely together and what are your architectural suggestions to do so?

答:
A bit of an outsider comment/answer, I'm not a .NET MVC programmer but have done a lot of PHP, Java, and AS3 programming and relatively recently switched to AngularJS as well.

My general feeling is that the back end should just be RESTful and shouldn't touch the front-end really and the front-end should only depend on the back end for data.  There are some exceptions for when it'd be better to create views server side (perhaps for consistent export for example or when caching of views will help significantly).

The advantage of the clear line of separation is allowing your teams to work independently or if you're a one man shop to allow you to focus on one task/problem at a time (can debug the back end separately from the front-end).  Furthermore if your project expands and the clients are needing a native application solution you can still re-use your RESTful (REST isn't purely necessary but seems the way to go) back end and just re-write the front end.

OwnerDisplayName: Ryan Langton

Title: Server side C# MVC with AngularJS


问:
To make a class function or not?
I'm wondering about functions used like this:

```<code>object1->objectMethod1(arg1, arg2);
</code>```

if objectMethod1:

- does not change the object state

- does not use the object's state at all

- is used by the class extensively

- logically fits as being used by the class

should it be made into a member function?

example:

```<code>class CSVFile {
private:
  filestream stream
  string header
  int num_columns
public:
  CSVFile(string filename)
  CSVFile() throws DefaultConstructorException()
...
CSVFile::initHeader() {
  header = stream.getLine()
  assert(isInCSVFormat(header)) <-- that
</code>```

should isInCSVFormat(string) be a member function or not?

答:
The usual argument against what you call class functions (some languages use the static keyword for these) is that they are not easily mockable, and are therefore not testable.  But that's an argument for making your class functions pure, not avoiding making them at all.  Class functions do not require a mock for the same reasons that they do not require an object instantiation.

Since you've already established that the class functions you are writing are going to be pure (by virtue of the conditions you have placed on them, like not changing state and not causing side-effects), I regard this as a perfectly sensible use case for them.

Class methods are especially useful as factory methods.

Title: To make a class function or not?


答:
Given those criteria, no. The fact that it does not access the object's private fields means it's not an essential part of your abstraction. Keeping such functions out of your class is better for encapsulation - you're limiting the amount of code that could potentially be affected by a change in the implementation. See this article.

Moreover, there's an unlimited number of ways you might use your class. If you shove a new function in there every time you find a common way to use it, the class will grow indefinitely. In a language like C++, you'd have to recompile everything that included the header file of your class.

Title: To make a class function or not?

Body:
I'm wondering about functions used like this:

```<code>object1->objectMethod1(arg1, arg2);
</code>```

if objectMethod1:

- does not change the object state

- does not use the object's state at all

- is used by the class extensively

- logically fits as being used by the class

should it be made into a member function?

example:

```<code>class CSVFile {
private:
  filestream stream
  string header
  int num_columns
public:
  CSVFile(string filename)
  CSVFile() throws DefaultConstructorException()
...
CSVFile::initHeader() {
  header = stream.getLine()
  assert(isInCSVFormat(header)) <-- that
</code>```

should isInCSVFormat(string) be a member function or not?


答: To keep things simpler and easier to understand, I try to reduce the number of features that my code uses (or could potentially use). If that subroutine is not going to need to be dynamically dispatched (for polymorphism or inheritance) then it should not be a member function and is perhaps better off as just a static method. If in addition to that you also don't need to access any private variables then you can safely put that subroutine in a totally separate class.</p>

Title: To make a class function or not?


问:
Programmers forgetting syntax
Do good programmers need to have syntax at the tip of their tongue when writing code? What do you make of them if they google for simple stuff online?  Are they good or bad(maybe they know where to look for)? Should programmers have a good memory? Is this a trait for a good programmer?</p>

答: I would definitely be surprised if an otherwise good programmer had to routinely look up syntax for a language that they were fluent in. Of course there may be corner cases that don't actually get used a lot in practice such that it would be perfectly acceptable for a good programmer to not know them but, as a general rule, a fluent programmer doesn't have to look up syntax. S/he has to lookup functions and classes from libraries :)</p>

Title: Programmers forgetting syntax


问:
Why did the Sun engineers decided to make Java only call by value?
Is there any specific reason they decided to go with Call by value? Is it for simplicity?</p>

答:
The terms "Call by Value" and "Call By Reference" are sometimes used a bit loosely by programmers, and the use of those terms doesn't always reflect the underlying reality.

When you hear someone refer to Call By Value and Call By Reference, what they are usually saying is that primitive values are Call By Value, whereas objects are Call By Reference.  You can tell the difference, in part, because when you pass a parameter by value, you always get the original value back.  In other words, when you Call by Value, your function is getting a copy of the primitive, not the actual primitive.*

Call by Reference is different.  When you Call by Reference, the object you are passing can be modified by the function, and the object will retain those changes when the function returns.  Java works like this; objects passed to a function retain changes made to the objects by the function.

So why isn't Java Call by Reference, then?

Because, when you pass an object to the parameter list of a function, you're not actually passing the object by reference.  What you are actually doing is passing the reference to the object, by value.

I know this may seem like splitting hairs, but think about it.  Does Java create a copy of the object before it passes it to you, like it does with primitives?  No; it creates a copy of the reference, and passes that to the function.  Can you modify the reference to point to a different object, and expect that change to be retained when the function returns?  No, you can't.

* If a variable containing a primitive is passed as a function parameter, the value of the variable is passed, not the actual variable. If a mathematical expression is passed to the function, the expression is evaluated first, and the result is passed to the function by value.


答:
Java is heavily influenced by Objective-C. Objective-C is heavily influenced by Smalltalk. Smalltalk is heavily influenced by Lisp. All of those are call-by-value.

Or, more, specifically, it is call-by-object-sharing (aka call-by-sharing or call-by-object), which is a special case of call-by-value, where the value is a pointer to a (potentially mutable) object.

For primitives, Java actually uses call-by-value without a pointer, however, since primitives are immutable, you cannot tell the difference anyway. (You can only observe the difference when you have two pointers to a mutable object and mutations performed by following one pointer can be observed by following another pointer, but primitives aren't mutable.)

So, to answer your question: history and heritage.

Title: Why did the Sun engineers decided to make Java only call by value?

Body: Is there any specific reason they decided to go with Call by value? Is it for simplicity?</p>


问:
How can you estimate time for tasks which primarily consist of figuring out a problem?
While it is relatively possible for an experienced developer to estimate how long it will take to implement code when the pattern and problem the code is solving is well understood, how can you make a good estimate when, while the end goal is well understood, the implementation is 95% theoretical/problem solving and has very small amounts of implementation?

My work often consists of tasks to accomplish well defined goals, however I have to find the way to reach that goal and until I understand the solution, it i6sn't clear what additional barriers there may be.  More specifically, I'm often working on code generation or automated code manipulation tools.  Once the solution is fully solved and the tool perfected, it will directly do 95% of the actual changes very quickly.  I don't, however, have any way to estimate how many additional issues may have to be resolved to make the generation or analysis tool deal with unforeseeable edge cases.

For planning purposes, my company wants a better idea of how long it will take, but since I don't know how many additional problems may come up while working through solving each step of the solution.  I'm not sure how I can approach giving a better estimate.

答:
Before I get too far, let me say that Software Estimation: Demystifying the Black Art is an excellent resource for people looking at and thinking about estimations.  Both of the images below are from that book as are the core if the ideas presented following.

As you've noted, estimations are an important part in being able to accurately predict and plan work.  Not having estimations makes the business blind about how long something will take.  It is not uncommon for business to have a completely mistaken idea on how long things will take - what they think is easy takes six to eight weeks and what is thought to be hard is a friday afternoon hack.

The first thing is to give an estimate.  An estimate itself is not a single number - thats a commitment.  "How long will ABC take" --> "About 5 days" means that its about 5 days.  However, a good estimate is a range where you are 90% confident that you will have it in that range.  If you mean to say "I am 90% confident that it will take betwene 1 and 5 days" then say that.  Don't work from "I think it will take between 1 and 10 days, so 5 days is probably about average" - thats not an estimate and you'll be wrong 50% of the time.

Well, 50% or more of the time, programmers are notorious underestimators for task times.

Consider the Cone of Uncertainty:

Image from http://www.construx.com - full article at http://www.construx.com/Thought_Leadership/Books/The_Cone_of_Uncertainty/

Realize that the first estimate in that range is 16x.  This is akin to saying "I think it will take between an afternoon and two weeks" - but you don't know yet.  As you go forward with the design a bit, the range narrows down to 4x.  This does not mean that it will take one week, it means that you would instead be saying "after looking at this a bit, it will take between three weeks" - yes, the estimate went up, but also the range of the estimate went down.

With each estimate you give, you need to be 90% sure that the estimate is within that range.  You can be wrong - 10% of the time it will fall out of that range.

There are many ways to estimate the size of projects.  Comparing it to past projects, using a proxy (I think it would take 1000 lines of code which would take this long to write), using function points (to convert into LOC...), getting estimates from a number of people and then refining it iteratively... some work for some projects, some work for other projects.

A very important chapter in this book that I mentioned at the top is #23 that deals with the politics of estimation and dealing with managers and executives.

The key to an estimation is the iterative process of refining it after working on it a bit.

Giving a too precise of an estimate too early in the process can be very error prone.  If you aren't sure about it, give the wide estimate and then come back with another estimate after some period of time for more introspection into the problem and possibly sketching out how you will do it, looking at how much code you wrote it for the last similar problem and other factors that will impact the estimate.

Estimates require some thought - don't give off the cuff estimates.  These often have huge errors associated with them compared to what it takes when you think about it a bit.

From How to respond when you are asked for an estimate?

What to Say When Asked for an Estimate

You say "I'll get back to you."

You almost always get better results if you slow the process down and spend some time going through the steps we describe in this section. Estimates given at the coffee machine will (like the coffee) come back to haunt you.

From Chapter 4 of Software Estimation:

Note that in this, the estimates after a bit of review are systematically less wild and error prone than the off the cuff estimates. Don't do off the cuff estimates.  Sit down and think about the task and estimate it after a bit of thought on it.

ContentLicense: CC BY-SA 4.0


答:
Boss: AJ, We have 3 dogs, 2 rabbits, a catapult, and a nun. We need to find a way to get all 7 (yes, the catapult too) over a 20-foot wall and into the lake on the other side without the dogs eating any rabbits, and without drowning the nun. How long will it take you to come up with the solution?

See, the problem estimating how long it will take to solve a problem is that it takes different people a different amount of time. If you have a history of solving similar problems, you can estimate based on how long it has taken you in times before. If you don't, then you're not estimating, you're just guessing.

Furthermore, the problem may not even have an acceptable solution. Or perhaps the solution will require further authorization which could throw off the whole project. Or perhaps the solution changes the whole perceived nature of the problem such that the solution becomes entirely unnecessary.

The moral of the story is, if you don't have enough information to make a reasonable estimation, then don't. Not yet. Get more information. Research more. Typically it's perfectly OK to say, "I'll get back to you in 2 days with some more solid numbers."

When designing a solution for I client, I won't sign a contract till I have enough of the general design complete that I know what the solution will look like and how long the project will take. This means that I'm at risk of having done initial design work that I don't get paid for (if the project doesn't go through), but that's better than being at risk of significantly under-billing for the work being done.

Title: How can you estimate time for tasks which primarily consist of figuring out a problem?

Body:
While it is relatively possible for an experienced developer to estimate how long it will take to implement code when the pattern and problem the code is solving is well understood, how can you make a good estimate when, while the end goal is well understood, the implementation is 95% theoretical/problem solving and has very small amounts of implementation?

My work often consists of tasks to accomplish well defined goals, however I have to find the way to reach that goal and until I understand the solution, it i6sn't clear what additional barriers there may be.  More specifically, I'm often working on code generation or automated code manipulation tools.  Once the solution is fully solved and the tool perfected, it will directly do 95% of the actual changes very quickly.  I don't, however, have any way to estimate how many additional issues may have to be resolved to make the generation or analysis tool deal with unforeseeable edge cases.

For planning purposes, my company wants a better idea of how long it will take, but since I don't know how many additional problems may come up while working through solving each step of the solution.  I'm not sure how I can approach giving a better estimate.


问:
Patterns for propagating changes up an object model..?
Here's a common scenario that's always frustrating for me to deal with.

I have an object model with a parent object. The parent contains some child objects. Something like this.

```<code>public class Zoo
{
    public List<Animal> Animals { get; set; }
    public bool IsDirty { get; set; }
}
</code>```

Each child object has various data and methods

```<code>public class Animal
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void MakeMess()
    {
        ...
    }
}
</code>```

When the child changes, in this case when the MakeMess method is called, some value in the parent needs to be updated. Let's say when a certain threshold of Animal's have made a mess, then the Zoo's IsDirty flag needs to be set.

There are a few ways to handle this scenario (that I know of).

1) Each Animal can have a parent Zoo reference in order to communicate changes.

```<code>public class Animal
{
    public Zoo Parent { get; set; }
    ...

    public void MakeMess()
    {
        Parent.OnAnimalMadeMess();
    }
}
</code>```

This feels like the worst option since it couples Animal to its parent object. What if I want an animal who lives in a house?

2) Another option, if you're using a language that supports events (like C#) is to have the parent subscribe to change events.

```<code>public class Animal
{
    public event OnMakeMessDelegate OnMakeMess;

    public void MakeMess()
    {
        OnMakeMess();
    }
}

public class Zoo
{
    ...

    public void SubscribeToChanges()
    {
        foreach (var animal in Animals)
        {
            animal.OnMakeMess += new OnMakeMessDelegate(OnMakeMessHandler);
        }
    }

    public void OnMakeMessHandler(object sender, EventArgs e)
    {
        ...
    }
}
</code>```

This seems to work but from experience gets hard to maintain. If Animals ever change Zoo's you have to unsubscribe events at the old Zoo and resubscribe at the new Zoo. This only gets worse as the composition tree gets deeper.

3) The other option is to move the logic up to the parent.

```<code>public class Zoo
{
    public void AnimalMakesMess(Animal animal)
    {
        ...
    }
}
</code>```

This seems very unnatural and causes duplication of logic. For example, if I had a House object that doesn't share any common inheritance parent with Zoo..

```<code>public class House
{
    // Now I have to duplicate this logic
    public void AnimalMakesMess(Animal animal)
    {
        ...
    }
}
</code>```

I have not yet found a good strategy for dealing with these situations. What else is available? How can this be made simpler?

答:
I had to deal with this a couple times.  The first time I used option 2 (events) and as you said it became really complicated.  If you go that route, I highly suggest you need very thorough unit tests to make sure the events are done correctly and you're not leaving dangling references, otherwise it's a really big pain to debug.

The second time, I just implemented the parent property as a function of the children, so keep a Dirty property on each animal, and let Animal.IsDirty return this.Animals.Any(x => x.IsDirty).  That was in the model.  Above the model there was a Controller, and the controller's job was to know that after I changed the model (all actions on the model were passed through the controller so it knew that something had changed), then it knew it had to call certain re-evaluation functions, like triggering the ZooMaintenance department to check if the Zoo was dirty again.  Alternatively I could just push the ZooMaintenance checks off until some scheduled later time (every 100 ms, 1 second, 2 minutes, 24 hours, whatever was necessary).

I found the latter has been much simpler to maintain, and my fears of performance problems never materialized.

Edit

Another way of dealing with this is a Message Bus pattern.  Rather than using a Controller like in my example, you inject every object with an IMessageBus service.  The Animal class can then publish a message, like "Mess Made" and your Zoo class can subscribe to the "Mess Made" message.  The message bus service will take care of notifying the Zoo when any animal publishes one of those messages, and it can re-evaluate its IsDirty property.

This has the advantage that Animals no longer need a Zoo reference, and the Zoo doesn't need to worry about subscribing and unsubscribing from events from every single Animal.  The penalty is that all Zoo classes subscribing to that message will have to re-evaluate their properties, even if it wasn't one of its animals.  That may or may not be a big deal.  If there's only one or two Zoo instances, it's probably fine.

Edit 2

Don't discount the simplicity of option 1.  Anyone revisiting the code won't have much problem understanding it.  It'll be obvious to someone looking at the Animal class that when  MakeMess is called that it propagates the message up to the Zoo and it'll be obvious to the Zoo class where it gets its messages from.  Remember that in object-oriented programming, a method call used to be called a "message".  In fact, the only time it makes much sense to break from option 1 is if more than just the Zoo has to be notified if the Animal makes a mess.  If there were more objects that needed to be notified, then I would probably move to a message bus or a controller.


问:
Why aren't databases integrated as a language feature?
Are there any programming languages that have a built-in database as a first-class language feature rather than connecting to an external SQL (or other) database? What would be the drawbacks and benefits to such a feature? What would such a feature look like and how would it change the way we program?</p>

答: Languages are "small" and databases are "big"; so whenever the two are combined, it's not a language with the database as a features, but a database with the language as a feature. Many databases have some proprietary languages tacked to them, e.g. PL/SQL, T-SQL.</p>


答:
What is the goal of refactoring in your specific case?

Presume for the purposes of putting up with my answer that we all believe (to some degree) in TDD (Test-Driven Development).

If the purpose of your refactoring is to clean up existing code without changing existing behavior, then writing tests before refactoring is how you ensure that you have not changed the behavior of the code, if you succeed, then the tests will succeed both before and after you refactor.

The tests will help you ensure that your new work actually works.

The tests will probably also uncover cases where the original work does not work.

But how do you really do any significant refactoring without affecting behavior to some degree?

Here is a short list of a few things that might happen during refactoring:

rename variable

rename function

add function

delete function

split function into two or more functions

combine two or more functions into one function

split class

combine classes

rename class

I'm going to argue that every single one of those listed activities changes behavior in some way.

And I'm going to argue that if your refactoring changes behavior, your tests are still going to be how you ensure that you have not broken anything.

Maybe the behavior doesn't change at a macro level, but the point of unit testing is not to ensure macro behavior. That's integration testing. The point of unit testing is to ensure that the individual bits and pieces you build your product out of aren't broken. Chain, weakest link, etc.

How about this scenario:

Presume you have function bar()

function foo() makes a call to bar()

function flee() also makes a call to function bar()

Just for variety, flam() makes a call to foo()

Everything works splendidly (apparently, at least).

You refactor...

bar() is renamed to barista()

flee() is changed to call barista()

foo() is not changed to call barista()

Obviously, your tests for both foo() and flam() now fail.

Maybe you didn't realize foo() called bar() in the first place. You certainly didn't realize that flam() was dependent on bar() by way of foo().

Whatever. The point is that your tests will uncover the newly broken behavior of both foo() and flam(), in an incremental fashion during your refactoring work.

The tests end up helping you refactor well.

Unless you don't have any tests.

That's a bit of a contrived example. There are those who would argue that if changing bar() breaks foo(), then foo() was too complex to begin with and should be broken down. But procedures are able to call other procedures for a reason and it's impossible to eliminate all complexity, right? Our job is to manage complexity reasonably well.

Consider another scenario.

You're constructing a building.

You build a scaffolding to help ensure that the building is built correctly.

The scaffolding helps you build an elevator shaft, among other things. Afterward, you tear down the scaffolding, but the elevator shaft remains. You have destroyed "original work" by destroying the scaffolding.

The analogy is tenuous, but the point is that it is not unheard-of to build tools to help you build product. Even if the tools aren't permanent, they are useful (even necessary). Carpenters make jigs all the time, sometimes only for one job. Then they tear the jigs apart, sometimes using the parts to build other jigs for other jobs, sometimes not. But that doesn't make the jigs useless or wasted effort.


答:
Option 1 is actually pretty straightforward. That's just a back-reference. But generalize it with interface called Dwelling and provide a MakeMess method on it. That breaks the circular dependency. Then when the animal makes a mess, it calls dwelling.MakeMess() too.

In the spirit of lex parsimoniae, I'm going to go with this one, although I'd probably use the chain solution below, knowing me. (This is just the same model that @Benjamin Albert suggests.)

Note that if you were modelling relational database tables, the relation would go the other way: Animal would have a reference to Zoo, and the collection of Animals for a Zoo would be a query result.

Taking that idea farther, you could use a chained architecture. That is, create an interface Messable, and in each messable item, include a reference to next. After creating a mess, call MakeMess on the next item.

So Zoo here is involved in making a mess, because it gets messy too. Have:

```<code>Zoo implements Messable
House implements Messable
Animal implements Messable
   Messable next

   MakeMess()
       messy = true
       next.MakeMess
</code>```

So now you have a chain of things that get the message that a mess has been created.

Option 2, a publish/subscribe model could work here, but feels really heavyweight. The object and container have a known relationship, so it seems a little heavy-handed to use something more general than that.

Option 3: In this particular case, calling Zoo.MakeMess(animal) or House.MakeMess(animal) isn't actually a bad option, because a house may have different semantics for getting messy than a Zoo.

Even if you don't go down the chain route, it sounds like there are two issues here: 1) the issue is about propagating a change from an object to its container, 2) It sounds like you want to spin off an interface for the container to abstract where the animals can live.

...

If you have first-class functions, you can pass a function (or delegate) into Animal to call after it makes a mess. That's a little like the chain idea, except with a function instead of an interface.

```<code>public Animal
    Function afterMess

    public MakeMess()
        messy = true
        afterMess()
</code>```

When the animal moves, just set a new delegate.

Taken to the extreme, you could use Aspect Oriented Programming (AOP) with "after" advice on MakeMess.

Title: Patterns for propagating changes up an object model..?

Body:
Here's a common scenario that's always frustrating for me to deal with.

I have an object model with a parent object. The parent contains some child objects. Something like this.

```<code>public class Zoo
{
    public List<Animal> Animals { get; set; }
    public bool IsDirty { get; set; }
}
</code>```

Each child object has various data and methods

```<code>public class Animal
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void MakeMess()
    {
        ...
    }
}
</code>```

When the child changes, in this case when the MakeMess method is called, some value in the parent needs to be updated. Let's say when a certain threshold of Animal's have made a mess, then the Zoo's IsDirty flag needs to be set.

There are a few ways to handle this scenario (that I know of).

1) Each Animal can have a parent Zoo reference in order to communicate changes.

```<code>public class Animal
{
    public Zoo Parent { get; set; }
    ...

    public void MakeMess()
    {
        Parent.OnAnimalMadeMess();
    }
}
</code>```

This feels like the worst option since it couples Animal to its parent object. What if I want an animal who lives in a house?

2) Another option, if you're using a language that supports events (like C#) is to have the parent subscribe to change events.

```<code>public class Animal
{
    public event OnMakeMessDelegate OnMakeMess;

    public void MakeMess()
    {
        OnMakeMess();
    }
}

public class Zoo
{
    ...

    public void SubscribeToChanges()
    {
        foreach (var animal in Animals)
        {
            animal.OnMakeMess += new OnMakeMessDelegate(OnMakeMessHandler);
        }
    }

    public void OnMakeMessHandler(object sender, EventArgs e)
    {
        ...
    }
}
</code>```

This seems to work but from experience gets hard to maintain. If Animals ever change Zoo's you have to unsubscribe events at the old Zoo and resubscribe at the new Zoo. This only gets worse as the composition tree gets deeper.

3) The other option is to move the logic up to the parent.

```<code>public class Zoo
{
    public void AnimalMakesMess(Animal animal)
    {
        ...
    }
}
</code>```

This seems very unnatural and causes duplication of logic. For example, if I had a House object that doesn't share any common inheritance parent with Zoo..

```<code>public class House
{
    // Now I have to duplicate this logic
    public void AnimalMakesMess(Animal animal)
    {
        ...
    }
}
</code>```

I have not yet found a good strategy for dealing with these situations. What else is available? How can this be made simpler?

Body:
Option 1 is actually pretty straightforward. That's just a back-reference. But generalize it with interface called Dwelling and provide a MakeMess method on it. That breaks the circular dependency. Then when the animal makes a mess, it calls dwelling.MakeMess() too.

In the spirit of lex parsimoniae, I'm going to go with this one, although I'd probably use the chain solution below, knowing me. (This is just the same model that @Benjamin Albert suggests.)

Note that if you were modelling relational database tables, the relation would go the other way: Animal would have a reference to Zoo, and the collection of Animals for a Zoo would be a query result.

Taking that idea farther, you could use a chained architecture. That is, create an interface Messable, and in each messable item, include a reference to next. After creating a mess, call MakeMess on the next item.

So Zoo here is involved in making a mess, because it gets messy too. Have:

Zoo implements Messable
House implements Messable
Animal implements Messable
   Messable next

   MakeMess()
       messy = true
       next.MakeMess

So now you have a chain of things that get the message that a mess has been created.

Option 2, a publish/subscribe model could work here, but feels really heavyweight. The object and container have a known relationship, so it seems a little heavy-handed to use something more general than that.

Option 3: In this particular case, calling Zoo.MakeMess(animal) or House.MakeMess(animal) isn't actually a bad option, because a house may have different semantics for getting messy than a Zoo.

Even if you don't go down the chain route, it sounds like there are two issues here: 1) the issue is about propagating a change from an object to its container, 2) It sounds like you want to spin off an interface for the container to abstract where the animals can live.

...

If you have first-class functions, you can pass a function (or delegate) into Animal to call after it makes a mess. That's a little like the chain idea, except with a function instead of an interface.

public Animal
    Function afterMess

    public MakeMess()
        messy = true
        afterMess()

When the animal moves, just set a new delegate.

Taken to the extreme, you could use Aspect Oriented Programming (AOP) with "after" advice on MakeMess.


答:
Two options I often use.  You can use the second approach and put the logic for wiring up the event in the collection itself on the parent.

An alternate approach (which can actually be used with any of the three options) is to use containment.  Make an AnimalContainer (or even make it a collection) that can live in the house or the zoo or anything else.  It provides the tracking functionality associated with the animals, but avoids inheritance issues since it can be included in any object that needs it.


问:
Is storing software in the cloud with reputable vendors secure?
I have a team member who refuses to use any form of private source code repository on Github or Bitbucket due to "security concerns".  As a result, we have a hard time sharing code with him.  He appears to be concerned about source code theft by some party.  To me, using cloud based source code repos is fairly standard industry practice.  But does this individual have a point?  Vendors do steal from customers in other industries.  Should a multimillion dollar idea not be stored on a third party cloud service like AWS, Github, Bitbucket, App Engine, etc?</p>

答:
I think there is some legitimacy to the concern, but at the same time, there are ways to safeguard against it.

On the legal side, clear legal terminology in the terms of service can make the host liable for any such theft.

On the technical side, client records could be encrypted to prevent offline access by the cloud provider.  They could still alter their code to steal keys if they wanted to, but it would prevent random Joe Shmoe in IT from walking off with your data since it would require a user password to be able to decrypt the data if encryption is properly used.

Cloud services provide a lot of value when it is cheaper to have them handle it than to run it yourself, but you do give up control and need to make sure sufficient safeguards are in place to protect your business.


问:
Architectural problem for Activity communication in an Android app
I maintain an open source Flickr app Glimmr for Android.  There is currently an architectural issue around pagination that I've been trying to solve for quite a while, and would appreciate ideas.

Here are the components involved:

Tasks - various subclasses of AsyncTask that fetch photos from sources such as a users photostream (LoadPhotoStreamTask), photoset (LoadPhotoSetTask), etc.

PhotoGridFragment - a fragment that displays photos fetched by the Tasks in a grid.  Subclasses of this exist matching each task, e.g. PhotoStreamGridFragment, PhotoSetGridFragment, etc.  The grid is paginated, so that when the user scrolls to the end of the photos, the task is triggered to go and fetch the next page of photos.

PhotoViewerActivity - responsible for displaying a list of photos from the grid in fullscreen.  This is started from the PhotoGridFragments with two pieces of info, a) the list of photos currently in the grid, and b) an index at which to start viewing at.

The issue arises when the user reaches the end of the list from within the PhotoViewerActivity.  This activity does not have the info required to start the correct task and update the list of photo's it has been passed.

I want to figure out a way of doing this while keeping the coupling between the PhotoGridFragment and PhotoViewerActivity as low as possible.  People who are familiar with Android will know that because we're dealing with two separate Activities, all communication between them must take place via Intents with data having to be persisted or serialised.  Afaik the PhotoViewerActivity can not easily call back to the Grid and ask for more photos.

Things are complicated by the fact that each task requires different pieces of state and info to do it's work. e.g. a LoadPhotosetTask requires the set id, LoadPhotoStreamTask requires a specific user
but doesn't care about sets, etc.  So just passing the task name required to fetch more photos to the viewer activity isn't enough.

Another solution could be to abstract the common pieces of functionality from the PhotoViewer into an abstract class, and then create specific photo viewers for each source, similar to the way we have specific PhotoGridFragments for each source.  This feels overkill, but is probably the solution at the front of my mind right now.

How would you solve this?

答:
Do you have a model/businscomponent/service that is responsible for managing the data? for me your description sounds as if your gui elements (activity/fragment) are doing the work.

The usual way would be to have a model/businscomponent/service that handles the data and is used by different gui components.


答:
You start with a basic failure: child objects shouldn't know about their parents.

Do strings know that they're in a list? No. Do dates know they exist in a calendar? No.

The best option is to change your design so that this sort of scenario doesn't exist.

After than, consider inversion of control. Instead of MakeMess on Animal with a side effect or event, pass Zoo into the method. Option 1 is fine if you need to protect the invariant that Animal always needs to live somewhere. It's not a parent, but a peer association then.

Occasionally 2 and 3 will go okay, but the key architectural principle to follow is that children don't know about their parents.