答:
Introduce your boss to Brook's Law.

"adding manpower to a late software project makes it later"

If your boss says that you should involve the coworker despite Brook's Law; congratulations, you just became a tutor.

Title: Adding a Short-Term Developer to a Rework of an Old Project

Body:
Background

I work in the Language Resource Center on my campus. It's a relatively small lab, and our job is to help students, not code software. Being a Computer Science student, I took the initiative to start coding useful utilities to make our jobs as lab assistants easier.

Recently, Google declared a shut-down of our data storage mechanism, so I decided that it was time to completely rework the entire system that I've built (alone) over the past year. I have more experience now, and I want to do it correctly with the (better) tools that are now available to us.

There is another CS student that works with me in this lab, who will continue working with me for one more semester (e.g. a 4-month period). I never asked him to contribute to the original project because I started it last summer when he wasn't scheduled to work.

The goal of this project is to build an integrated 'manager' application for our staff and my boss; the utility is a web service built using HTML/CSS/JavaScript. My coworker doesn't have any experience with JavaScript, HTML nor CSS. This developer also has no experience with the code base that I built previously (purely JavaScript), which would need to be re-worked (albeit slightly) to work with the new system.

Again, this is not a required duty in our positions. I enjoy coding things to automate menial tasks, and to make our jobs easier. It was never a requirement.

Deadlines

There is a hard deadline of mid-August, when faculty will start submitting requests to us again. The old system has to be rebuilt (some parts retrofitted) before then.

Why ask?

My boss suggested that this coworker of mine contribute to the new project to speed up development. I worry that my coworker (and boss, for that matter) might take it as a slight if he doesn't help develop this system. On the other hand, there was a 9-month period where he could have contributed to the previous project, and a 4-month period that he could have taken over management of said project (I was in France) - he has never shown interest in actively contributing to the previous project, and I have no problem with that.

I'm concerned because I feel that helping him learn HTML, CSS and JS, as well as Google's API and toolset will really slow things down. We essentially have two months to re-construct the old system, and I feel that the time it would take to get him acquainted with the tools and languages used in this project, I could have built it myself.

Is there a protocol?

I've come up with the following as my options in this situation:

Just start working on the new project alone, assuming that my coworker does not want and/or never wanted to contribute.

Ask my coworker if he wants me to help him learn HTML/CSS/JS and start showing him the previous code base as well as the current project's plan.

Ask my coworker if he has any interest in helping with the new project (he doesn't need to have an interest, but would he take that as You must work on this!?)

The question

Is it worth the time/effort, given the deadline, to have my coworker work on this project with me? Or would I detriment progress by having him co-develop?


问:
Who creates the agile definition of done(DoD)?
I believe that the "Definition of Done" is created by the Team and the "Acceptance Criteria" is created by the Customer. Am I correct?

Can a customer define the Definition of Done to the agile team?

答:
Yes, The Definition of Done is created by the Scrum team.

The Acceptance Criteria is created by the Product Owner.

They are orthogonal concepts, but both need to be satisfied to finish a story.

ContentLicense: CC BY-SA 3.0


问:
Coding and testing in the same sprint
How is testing handled within the same sprint as coding, if all or most of the coding is not done until the end of the sprint? (I'm referring to the "soup-to-nuts" development and testing of a single PBI within a sprint.)

Most of the answers I've seen online involve QA automation, but even that isn't really possible since you generally need a functional UI to record or create automated tests from. I only have storyboards that continue to evolve as I develop features and discover new requirements.

In my case, I am developing a new desktop application. Desktop apps don't generally lend themselves to automated testing very well. I have some automated unit tests, but they are not the manual functional/integration tests that a QA professional would perform.

So, where I'm at now is that my sprint ends tomorrow, I still have coding to finish, and my QA folks have nothing to test yet, and no idea how to test whatever I'd give them without me holding their hands.

I'm sure I'm not the first person to have this dilemma.

In the past, I've done a pipeline: in the current sprint the test team tests the features that have been implemented during the previous sprint. At my current job, the PM refers to this approach as "waterfall", and as such, unacceptable.

答:
My answer, which is probably quite strange at first, would be: you do not find time to test because you think testing must be done on the side effects of code. And with side effect I mean the computer science term:

a function (...) is said to have a side effect if, in addition to returning a value, it also (...) has an observable interaction with (...) the outside world.

I brought up the quote to emphasize the "interaction with the outer world" part:  you want testing to happen on the UI as it is printed on the screen ("[to start testing] isn't really possible since you generally need a functional UI to record or create automated tests from").

Other answers have told you to automate this "acceptance testing", so that it can happen quickly. This is right, but does not fully address your original problem: what if there is not enough time to write those acceptance tests?

You have to let go your view of testing once the code has interacted with the outside world, i.e. it has printed something out and expects some input in. The problem with side effects is that they are, in effect, untestable.  This dawned on me while reading an interview with Guido van Rossum, where he said that a statement that shuts down the computer can only be proved to work by executing it.

The solution to that "untestability" is to understand that, if you have proved once that the statement works, you can use it everywhere and rely on it to do its work.  Isolate it in a function and test everything else.

Bringing that example closer to your question, the function is now probably a whole library or framework, and instead of shutting down the computer, it prints something out: a user interface.  Keep the calls to it as dumb and as stable as possible, because once you enter that part of your application, you can only test via expensive acceptance tests, i.e. some kind of external observation.

Regarding the UI as "foreign territory" is actually a correct point of view, since you do not need to test the logic of a library that is not provided by you, and perhaps surprisingly, it is a realistic point of view: do you really expect to ever test that calling e.g. MyWidget.draw() does what you expect, to the level of a single pixel?

This is not to say that acceptance testing is not important, or that it can be skipped.  It is there to stay and automating it, as other answers suggest, has enormous benefits.  But if you want to find time to test and code in the same sprint, try to keep your code as side-effect free as possible.

Title: Coding and testing in the same sprint


问:
IllegalStateException vs. IllegalArgumentException
In have written a function which expects the caller to pass in a configuration file like XML. Then I parse this given file and extract something which i then return.

In this function (at least) two "bad" things can happen:

The given file does not exist or is not accessible in any way

While parsing/validating the file some unexpected content is found

The first thing is clearly an IllegalArgumentException. I am however not sure what kind of exception the second case would be. Is that also an IllegalArgumentException because i expect (by documentation-contract) that the input is in a valid form? Or is it rather an IllegalStateException as the given parameter is formal correct but only after parsing I can't do any further steps as it would result in unwanted behaviour?

Or is it even something else?

答:
Neither.  As others have pointed out, it is clearly not an IllegalStateException.

And better than IllegalArgument would be FileNotFoundException or ParseException, (or maybe XMLParseException) which exactly match your description of "bad things" 1 and 2.


问:
How often should a manager meet with his subordinate who is a team leader?
Ours is a software concern and we have a team structured like so: manager->team leads->team members. We are following the agile programming model and trying to develop a product in a collaborative fashion. We have daily morning meetings with team members and their team leads to discuss progress and issues.

When it comes to TL->Manager, most of the time they do not have items to discuss on a daily basis since TL goals would be for weekly plan and such. Most of the time, we just discuss about resources and it is less technical. I just want suggestions on how the manager & team lead interaction should be and whether the current system we have is fine. Please share your thoughts or ideas.

答: once per week, as per The One-Minute Manager

ContentLicense: CC BY-SA 2.5


问:
Algorithm for percentage without knowing total number
Suppose there are n lines for a hotline.

Whenever a customer calls the hotline, the call is forwarded to one of the n lines. And I want to assign  percentage of calling to each of the n lines. Suppose there are two lines and one line is assigned 60% and other is 40%, the total number of calls is 10 so the first line would receive 6 calls and second will get 4 calls.

I know the percentage of calling to each line in advance but the problem is that I don't know the number of calls that would be received in a day.

How can I distribute the number of calls without knowing the total calls?

答:
This is a naive solution and assumes nothing but would allow percentage based distribution. This solution could be improved upon in a lot of ways but this is the gist of it. I'm not sure if this is what you're looking for but it would give you true distribution.

psuedo code...

```<code>int running_total_of_calls = 0

//This is hard coded for clarity. You'd most likely want to dynamically populate this array depending and probably distribute the work by alternating workers. Notice how "worker1" appears 6 out of 10 times in the array.
string[] worker = new string[10]
workers[0] = "worker1"
workers[1] = "worker1"
workers[2] = "worker1"
workers[3] = "worker1"
workers[4] = "worker1"
workers[5] = "worker1"
workers[6] = "worker2"
workers[7] = "worker2"
workers[8] = "worker2"
workers[9] = "worker2"

while(1) //run forever
    //This is where the distribution occurs.
    //first iteration: 0 modulus 10 = 0.
    //second: 1 modulus 10 = 1
    //third: 2 modulus 10 = 2
    //...
    //10th: 10 modulus 10 = 0
    //11th: 11 modulus 10 = 1
    //12th: 12 modulus 10 = 2
    //...
    int assigned_number = running_total_of_calls % workers.Count //count of workers array
    string assigned_worker = workers[assigned_number]
    do_work(assigned_worker)
    running_total_of_calls = ++running_total_of_calls
</code>```

Body:
This is a naive solution and assumes nothing but would allow percentage based distribution. This solution could be improved upon in a lot of ways but this is the gist of it. I'm not sure if this is what you're looking for but it would give you true distribution.

psuedo code...

int running_total_of_calls = 0

//This is hard coded for clarity. You'd most likely want to dynamically populate this array depending and probably distribute the work by alternating workers. Notice how "worker1" appears 6 out of 10 times in the array.
string[] worker = new string[10]
workers[0] = "worker1"
workers[1] = "worker1"
workers[2] = "worker1"
workers[3] = "worker1"
workers[4] = "worker1"
workers[5] = "worker1"
workers[6] = "worker2"
workers[7] = "worker2"
workers[8] = "worker2"
workers[9] = "worker2"

while(1) //run forever
    //This is where the distribution occurs.
    //first iteration: 0 modulus 10 = 0.
    //second: 1 modulus 10 = 1
    //third: 2 modulus 10 = 2
    //...
    //10th: 10 modulus 10 = 0
    //11th: 11 modulus 10 = 1
    //12th: 12 modulus 10 = 2
    //...
    int assigned_number = running_total_of_calls % workers.Count //count of workers array
    string assigned_worker = workers[assigned_number]
    do_work(assigned_worker)
    running_total_of_calls = ++running_total_of_calls


问:
Is there a benefit in compiling your code as you go along?
I recently had a job interview in which they gave me an hour to write some real code.  It wasn't a huge amount, probably less than 100 lines.  After about 45 minutes, I compiled, ran it, and got it to work.  I may have spent 5-10 minutes working out compile errors and a couple minor bugs, but overall it was very smooth.  (Incidentally, I did get an offer from them.)

However, what puzzled me was that after I handed over the completed code, the interviewer told me that the only thing I did wrong was "not compiling as I go along".  I asked him what the difference is, and he said "what would you have done if you finished the code and it didn't compile in time".

In my understanding that's an invalid argument, because "getting code to compile" for a given length of code generally involves fixing a constant number of compile errors and takes a fairly constant amount of time, which should be the same whether you do it after you finish writing the code, or if you interleave it with your coding time.  If anything, interrupting your coding to search for missing semicolons would probably be detrimental to your efficiency.  Except in extreme circumstances when I'm experimenting with obscurities around edge-cases on things like virtual functions in derived classes, etc. it seems reasonable to expect that code written by a an experienced developer will compile, minus the occasional typing error, and even if it doesn't, it's not as if I would have to rewrite a portion of the code in order to fix the compile error.

In another similar incident, I was given an incomplete codebase in an interview, and asked to finish it and make necessary modifications to get it running.  I started by reading through the existing code, and then after a few minutes (even before I had finished looking at the code), the interviewer told me that's enough.  When I asked him what he would have done (i.e. "what did I do wrong"), he told me that he would have started by immediately getting the code to compile.

Why is that even relevant?  In my opinion and in my experience, whether or not a piece of code compiles is essentially random, involving things like whether or not semicolons are missing, and has little to do with the correctness of the underlying program.  (To me, focusing on compiling is like running an article through a spell-check without proofreading to check the grammar.)

If you give me a piece of incomplete code, the first thing I do will be to read it.  I won't even try to compile it until I know what the code is doing and I know the algorithm is correct.

Anyway, these have been just a couple recent incidents, but in general I've heard many developers talk about compiling their code as they go along, and yet nobody has been able to tell me the benefit of doing so.  I understand the benefits of testing your code as you go along, but why compiling?

So my question is this: Is there something I missed?  Is there actually a benefit to compiling as you go along?  Or is this some sort of myth propagated by the software community that you must compile your code frequently?

答:
Regarding the second interview, a benefit of compiling is that you can observe, within just a few seconds, what the programs does (or doesn't). From there it is easier to read the code and to focus your efforts on the relevant parts. Perhaps this is what the interviewer was expecting.

Reading an unknown code base like this from beginning to end can be quite unproductive (you're not a compiler), while compiling/running the application will quickly give you a bigger picture.


问:
Design Patterns for creating tasks
I am developing software where each action in my entities need create tasks that will be execute in my infrastructure. When I create a task it is only records in the database. Afterwards, a windows service will execute it.

Actually, I use a Service and my Entities are Anemic, then when I change the state of my entity I also create my tasks to infrastructure.

```<code>    public void CreateMachine(string name){
      var machine = new Machine(){
                          Name = name,
                          Status = Status.Releasing;
};
      var tasks = new List<Task>(){
                   new Task("CreateMachine", machine.Name),                       //infrastructure task
                   new Task("ChangeMachineSize", machine.Name, machine.Foo),      //infrastructure task
                   new Task("ActivateMachine", machine.Bar),                      //infrastructure task
                   new Task("SetMachineEntityStatusToReleased", machine.Name)     //business task (go to my database)
      _db.Task.Add(tasks);
      _db.Msachine.Update(machine);
      _db.SaveChanges();
     }
   }
</code>```

But I want use rich domain, because my services are getting too complex.

```<code>    Public Class Machine{

        public Machine(string name)
        {
          Name = name;
          Status = Status.Releasing;
          //Can I Create Tasks for create machine here?
        }

        public void Stop(){
          Status = Status.Releasing
          //Can I create Tasks for stop machine here?
        }

        [Required]
        [StringLength(50)]
        public string Name { get; set; }

        public Status Status { get; protected set; }
}
</code>```

Is there a design pattern or best practice for this design? I am violating the Single Responsibility Principle if I add the task creation inside my entity?

答: Publisher/Subscriber, also known as Observer comes to mind. A Task factory can subscribe to status changes published by your Entity and create the Task instances as dictated by the change in status of the Entity.</p>

Title: Design Patterns for creating tasks


问:
How could an expert system get some meaning from a sentence?
How could an expert system tell following scenarios apart? How could we include some meaning of a sentence, if at all?

```<code>A machine needs 1 day to produce x units, and,

we know that two machines like the first would need 1/2 day for x units.
</code>```

However, if:

```<code>a truck transports a container from a to b in 1 day,

but two trucks won't transport the same container in half the time.
</code>```

But how to establish a logical rule to exclude attaching a truth value to the second sentence? Hoe to process sentences that depict a process that can not be divided in pieces (that means, include the meaning of 'divisible'/'non-divisible'), and therefore, an expert system can't assign automatically a time value to a process that has to be performed. The enhanced expert system would then be able to avoid scheduling failures.

答:
It is very simple in order to get the meaning so that you can do what you want in the two cases above. You need to parse the sentences so that you can get the following semantics (together with built-in knowledge)

A machine has a production speed

A truck has a transportation speed

The inferred knowledge about the prime/atomic form of the production speed

The inferred knowledge about the prime/atomic form of the transportation speed

Multiplication rules on the speed

In your example, if the x is a concrete number say 24, you can infer (or already given the inference rules) that the atomic/prime forms of the speed for the machine is 24 units a day OR 1 unit every 1 hr. Using this you can infer, that two machines can produce 24 unit in half a day because one produces 12 and the other 12.

In the second case, the prime/atomic forms of the speed is:
a to b in one day, and probably a to c which is half way from a to b in half a day. So now when you use multiplication rule on this case, you have in half a day you get from a to c only, not to b and you have an increase in the number of containers if you have 2 trucks instead.

In other words, the atomic forms of the speed are different in 2 cases and the multiplication rules are also different.


问:
Good or bad practice to mask Java collections with meaningful class names?
Lately I've been in the habit of "masking" Java collections with human-friendly class names. Some simple examples:

```<code>// Facade class that makes code more readable and understandable.
public class WidgetCache extends Map<String, Widget> {
}
</code>```

Or:

```<code>// If you saw a ArrayList<ArrayList<?>> being passed around in the code, would you
// run away screaming, or would you actually understand what it is and what
// it represents?
public class Changelist extends ArrayList<ArrayList<SomePOJO>> {
}
</code>```

A colleague pointed out to me that this is bad practice, and introduces lag/latency, as well as being an OO anti-pattern.  I can understand it introducing a very tiny degree of performance overhead, but can't imagine it's at all significant. So I ask: is this good or bad to do, and why?

答:
Lag/Latency? I call BS on that. There should be exactly zero overhead from this practice. (Edit: It has been pointed out in the comments that this can, in fact, inhibit optimizations performed by the HotSpot VM. I don't know enough about VM implementation to confirm or deny this. I was basing my comment off of the C++ implementation of virtual functions.)

There is some code overhead. You have to create all the constructors from the base class that you want, forwarding their parameters.

I also don't see it as an anti-pattern, per se. However, I do see it as a missed opportunity. Instead of creating a class that derives the base class just for the sake of renaming, how about you instead create a class that contains the collection and offers a case-specific, improved interface? Should your widget cache really offer the full interface of a map? Or should it instead offer a specialized interface?

Furthermore, in the case of collections, the pattern simply doesn't work together with the general rule of using interfaces, not implementations - that is, in plain collection code, you would create a HashMap<String, Widget>, and then assign it to a variable of type Map<String, Widget>. Your WidgetCache cannot extend Map<String, Widget>, because that's an interface. It cannot be an interface that extends the base interface, because HashMap<String, Widget> doesn't implement that interface, and neither does any other standard collection. And while you can make it a class that extends HashMap<String, Widget>, you then have to declare the variables as WidgetCache or Map<String, Widget>, and the first loses you the flexibility to substitute a different collection (maybe some ORM's lazy loading collection), while the second kind of defeats the point of having the class.

Some of these counterpoints also apply to my proposed specialized class.

These are all points to consider. It may or may not be the right choice. In either case, your colleague's offered arguments are not valid. If he thinks it's an anti-pattern, he should name it.


问:
get all the combination of a given set of numbers
I m trying to get the possible combinations of a given set of numbers say for example 123

The possible combinations would be

123
132
213
231
312
321

For this i have written a code as below -

```<code>import java.util.ArrayList;

/* Name of the class has to be "Main" only if the class is public. */
public class Main {

/**
 * @param args the command line arguments
 */
static ArrayList list;

public static void main(String[] args) {
    // TODO code application logic here
    Main nm = new Main();
    nm.list = new ArrayList();
    /*
    for(int i=1; i<= 4; i++) {
        list.add(i);
    }

    list.remove(list.indexOf(1));

    for(int i=0; i<= 2; i++) {
        System.out.print(list.get(i));
    }
    */
    nm.test1();
}

public void test1() {
    for(int i=1; i<= 4; i++) {
        if(!list.contains(i)) {
            list.add(i);
            test1();
            list.remove(list.indexOf(i));
        }
    }
    if(list.size() == 4)
    {
        for(int i=0; i< 4; i++) {
            System.out.print(list.get(i));
        }
        System.out.println("");
    }
}
</code>```

}

This gives the correct output as shown here in the link

I was thinking about if this the right approach or if there can be any optimizations done so that this code may be used to get combinations of numbers of 10 to 20 digits or more.

Regards

答:
I was after the same thing a came to the conclusion that is it permutations that I wanted and this "algorithm to generate permutations explained" did what I wanted. The example is in Ruby but it is quite easy to understand (and quite simple).

Edit:

From the mentioned website above:

First things first, the basics: Permutations are how many times a set of items you have can be ordered.  For example, there are 24 permutations of 1234: 1234, 1243, 1324, 1342, 1423, 1432, 2134, 2143, 2314, 2341, 2413, 2431, 3124, 3142, 3214, 3241, 3412, 3421, 4123, 4132, 4213, 4231, 4312, 4321.  If some of the items are the same, then there are fewer permutations of sets of 4.  For example, there are only 4 permutations of 1112: 1112, 1121, 1211, 2111

The algorithm to generate all of the permutations requires a way of comparing and ordering the items.  The first permutation in the series is the one with all of the permutations in ascending order, for example, 12345 or ABCDE.  It then uses this permutation to generate the next permutation in the series until the last one which has all of the items in descending order: 54321 or EDCBA.

In words, the algorithm goes as follows:

Starting from the right hand side of the list, go backwards and find the first item which is less than the item immediately after it and let that be i. list[i] < list[i+1].  If none of the items satisfy the criteria (i.e. the whole list is in descending order, then you’ve finished).

Starting from the right hand side of the list, go backwards and find the first item which is larger than item i.  Mark this as j.

Swap the items at i and j.

Reverse the items from i+1 to the end of the list.


答:
The performance hit would be limited at most to a vtable lookup, which you are most likely already incurring.  That's not a valid reason to oppose it.

The situation is common enough that most all statically typed programming languages have special syntax for aliasing types, usually called a typedef.  Java probably didn't copy those because it originally didn't have parameterized types.  Extending a class isn't ideal, due to the reasons Sebastian covered so well in his answer, but it can be a reasonable workaround for Java's limited syntax.

Typedefs have a number of advantages.  They express the programmer's intent more clearly, with a better name, at a more appropriate level of abstraction.  They are easier to search for debugging or refactoring purposes.  Consider finding everywhere a WidgetCache is used versus finding those specific uses of a Map.  They are easier to change, for example if you later find you need a LinkedHashMap instead, or even your own custom container.

Title: Good or bad practice to mask Java collections with meaningful class names?

Body:
Lately I've been in the habit of "masking" Java collections with human-friendly class names. Some simple examples:

```<code>// Facade class that makes code more readable and understandable.
public class WidgetCache extends Map<String, Widget> {
}
</code>```

Or:

```<code>// If you saw a ArrayList<ArrayList<?>> being passed around in the code, would you
// run away screaming, or would you actually understand what it is and what
// it represents?
public class Changelist extends ArrayList<ArrayList<SomePOJO>> {
}
</code>```

A colleague pointed out to me that this is bad practice, and introduces lag/latency, as well as being an OO anti-pattern.  I can understand it introducing a very tiny degree of performance overhead, but can't imagine it's at all significant. So I ask: is this good or bad to do, and why?


答:
I see this as an example of a meaningful abstraction. A good abstraction has a couple of traits:

It hides implementation details which are irrelevant to the code consuming it.

It is only as complex as it needs to be.

By extending, you're exposing the entire interface of the parent, but in many cases much of that may be better hidden, so you'd want to do what Sebastian Redl suggests and favor composition over inheritence and add an instance of the parent as a private member of your custom class. Any of the interface methods that do make sense for your abstraction can be easily delegated to (in your case) the inner collection.

As for a performance impact, it's always a good idea to optimize code for readability first, and if a performance impact is suspected, profile the code to compare the two implementations.


问:
Code re-use in C++, via multiple inheritance or composition? Or...?
I originally asked this question on StackOverflow, but I was directed here, and I think my problem is perhaps as much conceptual as technical, so here goes.

If you’re defining a hierarchy of abstract class in C++, and then creating concrete subclasses with implementations, you could end up with abstract classes something like this, say:

```<code>  A
 / \
B1 B2
</code>```

So the concrete classes then inherit like so:

```<code>B1   B2        B1   B2
 |    |         |    |
C1   C2        D1   D2
</code>```

And this is all fine and dandy when Cn and Dn are just implementing the interfaces of Bn, or where say C1 and C2 implement the A interface differently.

However, if I want to have some shared functionality in C1 and C2, which comes from the A interface, where do I put it?

It can’t go in A, both because A is abstract and because Dn should not be inheriting it.

It seems like there’s a notional A_for_C implementation, but does this belong in another ancestor class? Or in a composed sibling class?

```<code>   _____A_____                       _____A_____
  /     |     \                     /     |     \
B1   A_for_C  B2        vs        B1     B2     A_for_C
 |_____/ \____ |                   |      |
C1            C2                  C1     C2

                               (C1 and C2 then each have an A_for_C and delegate)
</code>```

The first one seems conceptually accurate, but requires virtual inheritance, while the second requires delegation. So both impose a performance hit despite there not being any real ambiguity.

Reading around the web, on this website I find it said

Some people believe that the purpose of inheritance is code reuse. In C++, this is wrong. Stated plainly, “inheritance is not for code reuse.”

How then should the implementation be shared?

Further thoughts

I found some relevant discussion in these questions:

Where does this concept of "favor composition over inheritance" come from?

Interface and Inheritance: Best of both worlds?

Is there any "real" reason multiple inheritance is hated?

I think utnapistim’s answer below is much pithier and to the point than these, and helped me mentally cut through a lot of what these other questions/answers discuss.

Inheritance is about agreeing to fulfil a contract. Multiple inheritance is fine if the subclass really does guarantee fulfilling the parent contracts.

Implementation, however, is only really the concern of the final object. Yes, it might be convenient to inherit the implementation sometimes, but that’s actually orthogonal to the interface, and there are various techniques for pulling in an implementation other than the default v-table-based approach, including:

CRTP as per unaptism’s answer

The template method pattern

(Which are, I think, equivalent except that one is compile-time and one is run-time.)

答:
There are two aspects to your question:

§1. What is c++ inheritance for (if not for code reuse)?

The simplest answer to give here is "implementing a contract" (also see Liskov substitution principle and facade design pattern).

§2. How then should the implementation be shared?

Consider:

Encapsulation of an object, implementing common behavior to both branches (this is sometimes the best alternative to inheritance diamonds). Your A_for_C doesn't need to inherit from A.

Free functions (templated if your algorithm applies to multiple types).

Template classes (CRTP may be an alternative to a diamond inheritance pattern).


问:
Should a view call a function?
Should a view call a helper function?

Say I pass in data from the DB to the view. The data is a unix timestamp. Should I make a call in my view to convert it to a human readable TS or should I convert it in the controller before passing it in? OR should I make a method in the model that converts...

Looking for a "best practice" or "secure coding" concerned answer.

答: This seems like a fairly trivial calculation, indeed, you could implement it in a few lines of javascript.  It is your view that is in charge of displaying data; let it do its work.</p>

Title: Should a view call a function?


答:
+1 to the other answers here.  I'll also add that it's actually deemed to be very good practice by the Domain Driven Design (DDD) community.  They advocate that your domain and the interactions with it should have semantic domain meaning as opposed to the underlying data structure.  A Map<String, Widget> could be a cache, but it could also be something else, what you've correctly done In My Not So Humble Opinion (IMNSHO) is to model what the collection represents, in this case a cache.

I'll add an important edit in that the domain class wrapper around the underlying data structure should probably also have other member variables or functions which truly make it a domain class with interactions as opposed to just a data structure (if only Java had Value Types, we'll get them in Java 10 - promise!)

It will be interesting to see what impact Java 8's streams will have on all of this, I can imagine that perhaps some public interfaces will prefer to deal with a Stream of (insert common Java primitive or String) as opposed to a Java object.


问:
Could taking design lightly be a pitfall of agile methodologies causing constant rework or is it a misunderstanding of the methodology?
I've been working for a year now in an agile project to redesign an insurance application.
I really like working in an agile environment, although management and analysts I work with still have waterfall thinking ingrained and makes it a little complicated to embrace the new paradigm shift to agile.

From a developer standpoint sometimes I feel like since we're doing "agile" we don't over-think or think enough our designs and just go with the flow and refactor later. Many times that ends up in rework because we never put enough though to certain pieces of the application. As far as I understand, agile is like having small waterfalls and deliver small pieces at a time (iterations), but sometimes we lose the big picture and end up paying for it later with rework.

Are agile methodologies encouraging or tolerating procrastination more than traditional waterfall? Is this constant rework for pieces of software with defined requirements acceptable?

Is anyone else experiencing something similar in their projects?

答:
Agile its not about not designing, agile its about designing all the time!

In waterfall design is constrained to one phase, then programming, then testing... in agile you are designing/programming/testing all the time. If your problem its that your are taking poor design decisions that compromise the future extensibility or maintainability of the application learn from this mistakes and try to take better decisiones the next time.

but in agile you have a lot of time for designing, in fact, all the time its for design.


答:
The advantage of "compiling as you go along" is you get constant feedback, and won't have a chance to go far wrong before being pushed in the right direction. For a competent programmer like you, that's not a huge consideration, but for many others it is. Put another way, "compiling as you go along" is a way of "minimizing the maximum loss," even though there are some potential efficiency losses in your case.

Companies these days aren't just interested in a finished product. They want to know that it was "under control" all along. For them, "getting there is half the fun."

Title: Is there a benefit in compiling your code as you go along?

Body:
I recently had a job interview in which they gave me an hour to write some real code.  It wasn't a huge amount, probably less than 100 lines.  After about 45 minutes, I compiled, ran it, and got it to work.  I may have spent 5-10 minutes working out compile errors and a couple minor bugs, but overall it was very smooth.  (Incidentally, I did get an offer from them.)

However, what puzzled me was that after I handed over the completed code, the interviewer told me that the only thing I did wrong was "not compiling as I go along".  I asked him what the difference is, and he said "what would you have done if you finished the code and it didn't compile in time".

In my understanding that's an invalid argument, because "getting code to compile" for a given length of code generally involves fixing a constant number of compile errors and takes a fairly constant amount of time, which should be the same whether you do it after you finish writing the code, or if you interleave it with your coding time.  If anything, interrupting your coding to search for missing semicolons would probably be detrimental to your efficiency.  Except in extreme circumstances when I'm experimenting with obscurities around edge-cases on things like virtual functions in derived classes, etc. it seems reasonable to expect that code written by a an experienced developer will compile, minus the occasional typing error, and even if it doesn't, it's not as if I would have to rewrite a portion of the code in order to fix the compile error.

In another similar incident, I was given an incomplete codebase in an interview, and asked to finish it and make necessary modifications to get it running.  I started by reading through the existing code, and then after a few minutes (even before I had finished looking at the code), the interviewer told me that's enough.  When I asked him what he would have done (i.e. "what did I do wrong"), he told me that he would have started by immediately getting the code to compile.

Why is that even relevant?  In my opinion and in my experience, whether or not a piece of code compiles is essentially random, involving things like whether or not semicolons are missing, and has little to do with the correctness of the underlying program.  (To me, focusing on compiling is like running an article through a spell-check without proofreading to check the grammar.)

If you give me a piece of incomplete code, the first thing I do will be to read it.  I won't even try to compile it until I know what the code is doing and I know the algorithm is correct.

Anyway, these have been just a couple recent incidents, but in general I've heard many developers talk about compiling their code as they go along, and yet nobody has been able to tell me the benefit of doing so.  I understand the benefits of testing your code as you go along, but why compiling?

So my question is this: Is there something I missed?  Is there actually a benefit to compiling as you go along?  Or is this some sort of myth propagated by the software community that you must compile your code frequently?


答:
Let's suppose the number of workers is less than 100

Create an array of workers with a capacity of 100

Put in that array a worker a number of times equal to the percentage of calls he should get, for example if worker1 should get 30% of all calls, then put him in positions 0 to 29 of the array.

At the end every position of the array should be used, and workers should appear in the array as many times as the percentage of calls they should get.

In a loop, generate a random number between 0 and 99, and assign the incoming call to the worker in that position of the array. If worker is busy, repeat.

That way, out of sheer probability, the calls will be distributed as desired

In my example, worker1 has a 30/100 chance of getting chosen at any given iteration.

Title: Algorithm for percentage without knowing total number

Body:
Suppose there are n lines for a hotline.

Whenever a customer calls the hotline, the call is forwarded to one of the n lines. And I want to assign  percentage of calling to each of the n lines. Suppose there are two lines and one line is assigned 60% and other is 40%, the total number of calls is 10 so the first line would receive 6 calls and second will get 4 calls.

I know the percentage of calling to each line in advance but the problem is that I don't know the number of calls that would be received in a day.

How can I distribute the number of calls without knowing the total calls?


问:
usage of double pointers and n pointers?
I am familiar with basic C pointers. Just wanted to ask what is the actual use of double pointers or for that matter n pointer?

```<code>#include<stdio.h>
int main()
{
    int n = 10 , *ptr , **ptr_ptr ;
    ptr = &n;
    ptr_ptr = &ptr;
    printf("%d", **ptr_ptr);
    return(0);
}
</code>```

**ptr_ptr is printing 10 but how?

答:
Multiple indirection generally occurs in the following scenarios: writing to a parameter of pointer type, and building an N-dimensional array by pieces.

Writing to a parameter of pointer type

For any function parameter of type T, if you want the function to modify the value of the parameter and have that new value reflected in the caller, you must pass a pointer:

```<code>void foo( T *ptr )
{
  *ptr = new_value(); // writes new value to thing pointed to by ptr
}

void bar( void )
{
  T var;
  foo( &var ); // writes new value to var
}
</code>```

The expression *ptr in foo refers to the same object in memory as var in bar, so writing to *ptr is equivalent to writing to var.

If T is a pointer type Q *, then you wind up with a pointer to a pointer:

```<code>void foo( Q **ptr )
{
  *ptr = new_value(); // writes new value to thing pointed to by ptr
}

void bar( void )
{
  Q *var;
  foo( &var ); // writes new value to var
}
</code>```

In this second case, you want to modify the pointer value stored in var.  Again, both *ptr and var refer to the same memory location, but this time, var contains a pointer value.  You could replace Q with R *, giving

```<code>void foo( R ***ptr )
{
  *ptr = new_value(); // writes new value to thing pointed to by ptr
}

void bar( void )
{
  R **var;
  foo( &var ); // writes new value to var
}
</code>```

The semantics are the same in all three cases; we write a new value to var through the expression *ptr; it's just the type of var is a pointer type, meaning the type of ptr must be a pointer type with one more level of indirection.

Building an N-dimensional array by pieces

Suppose you want to allocate an NxM array of T, but you don't know the values of N or M at compile time.  One approach is to declare a pointer to a pointer, then allocate an array of pointers to it:

```<code>T **arr; // arr will point to an NxM array of T
size_t n, m;
/**
 * get values for n and m
 */
arr = malloc( sizeof *arr * n ); // allocate N objects of type T *
if ( arr )
{
  for ( size_t i = 0; i < n; i++ )
  {
    arr[i] = malloc( sizeof *arr[i] * m ); // allocate M objects of type T
    if ( arr[i] )
    {
      for ( size_t j = 0; i < m; i++ )
      {
        arr[i][j] = some_value();
      }
    }
  }
}
</code>```

The same general mechanism can be applied for higher-dimensioned arrays:

```<code>T ***arr3;
...
arr3 = malloc( sizeof *arr3 * n );
...
  arr3[i] = malloc( sizeof *arr3[i] * m );
  ...
    arr3[i][j] = malloc( sizeof *arr3[i][j] * k );
</code>```

There are a few other scenarios where you see multiple indirection, but those are the two main ones.

It's rare in practice to see more than three levels of indirection, though.

ContentLicense: CC BY-SA 4.0

Body:
Multiple indirection generally occurs in the following scenarios: writing to a parameter of pointer type, and building an N-dimensional array by pieces.

Writing to a parameter of pointer type

For any function parameter of type T, if you want the function to modify the value of the parameter and have that new value reflected in the caller, you must pass a pointer:

void foo( T *ptr )
{
  *ptr = new_value(); // writes new value to thing pointed to by ptr
}

void bar( void )
{
  T var;
  foo( &var ); // writes new value to var
}

The expression *ptr in foo refers to the same object in memory as var in bar, so writing to *ptr is equivalent to writing to var.

If T is a pointer type Q *, then you wind up with a pointer to a pointer:

void foo( Q **ptr )
{
  *ptr = new_value(); // writes new value to thing pointed to by ptr
}

void bar( void )
{
  Q *var;
  foo( &var ); // writes new value to var
}

In this second case, you want to modify the pointer value stored in var.  Again, both *ptr and var refer to the same memory location, but this time, var contains a pointer value.  You could replace Q with R *, giving

void foo( R ***ptr )
{
  *ptr = new_value(); // writes new value to thing pointed to by ptr
}

void bar( void )
{
  R **var;
  foo( &var ); // writes new value to var
}

The semantics are the same in all three cases; we write a new value to var through the expression *ptr; it's just the type of var is a pointer type, meaning the type of ptr must be a pointer type with one more level of indirection.

Building an N-dimensional array by pieces

Suppose you want to allocate an NxM array of T, but you don't know the values of N or M at compile time.  One approach is to declare a pointer to a pointer, then allocate an array of pointers to it:

T **arr; // arr will point to an NxM array of T
size_t n, m;
/**
 * get values for n and m
 */
arr = malloc( sizeof *arr * n ); // allocate N objects of type T *
if ( arr )
{
  for ( size_t i = 0; i < n; i++ )
  {
    arr[i] = malloc( sizeof *arr[i] * m ); // allocate M objects of type T
    if ( arr[i] )
    {
      for ( size_t j = 0; i < m; i++ )
      {
        arr[i][j] = some_value();
      }
    }
  }
}

The same general mechanism can be applied for higher-dimensioned arrays:

T ***arr3;
...
arr3 = malloc( sizeof *arr3 * n );
...
  arr3[i] = malloc( sizeof *arr3[i] * m );
  ...
    arr3[i][j] = malloc( sizeof *arr3[i][j] * k );

There are a few other scenarios where you see multiple indirection, but those are the two main ones.

It's rare in practice to see more than three levels of indirection, though.


问:
How much should Developers interact with Clients?
A philosophical discussion has come up in my department that I'd like p.se's opinion on. We're a 6 person development department inside a 60 person IT shop. All other departments are growing FAST, and ours has been the same size (and not fully booked at that size) for a few years.

My manager, and old-school mainframe guy, contends that developers should never ever have ANY client contact. That all interaction with the client should be mitigated by a Project Management layer. He asserts that this allows a coder the focus they need in order to CODE, and protects the business's relationship with the client from the autism-spectrum tendencies of Joe Average Code Monkey. (My words, not his.)

His boss, the owner of the company, told him this morning that every single person in the company needs to think of themselves as an extension of the sales department, and needs to be listening all the time for upsell opportunities. To this end, he thinks clients ought to have more or less full access to developers directly, in part so that devs have the opportunity to hear sales opportunities.

I'm somewhere in the middle, myself. I think it's nice to shield devs from clients to some extent, but in practice that will never be total. And yes, every single job in the company includes sales, but that doesn't necessarily mean that everyone has the same opportunity for it.

EDIT: We're not an agile shop. Some of us (cough) would like to head that direction, but for now assume this is a traditional fixed-bid-contract shop.

EDIT2: The autism joke wasn't funny. Got it. Entirely possible that autism jokes never are. That said: there are developers who have a capacity to represent themselves and their employers well and developers who don't (currently) have that capacity. My manager has a real concern about how the company would be represented if all developers were structurally empowered to be company representatives.

It's also getting increasingly clear from reading your responses that the real push-and-pull here is between waterfall and agile.

答:
I have seen instances where a developer has interacted with a client and had disastrous results. It depends on the developer's personality as well, some can be personable and tactful while others can drive the client to tears, where contracts are cancelled as a result.

The PM/Project Owner is the spoke in the wheel and if changes occur without his/her knowledge will result in time, cost and scope creep.


问:
Should I use check or checked?
I'm designing a library that binds to html elements on a page. In this particular case the input[type='checkbox'] will be checked if the likeItem property returns true and unchecked if the likeItem property returns false. What's the best practice for naming properties?

input { check: likeItem }

or

input { checked: likeItem }

This would also apply to other things like enable/enabled, disable/disabled, etc.

答:
For semantic reasons and best practice use checked.

input { checked: isTrue } will be processed after the input is checked. So, for me, I think checked get better this context.

Title: Should I use check or checked?


答:
This really depends on what you do if the property returns false. If the input happens to be checked, and you send input { checked: isFalse }, I would expect that the library will uncheck the checkbox - set it's checked property to false(even though the checked attribute in HTML doesn't uses present/absent and not true/false).

But if the input is checked, and you send input { check: isFalse }, I would expect that the library will not uncheck the checkbox, and that it'll remain checked! check is a verb, which means an action, so { check: isFalse } means either "call check with false"(which I don't think is the case here, since a function named check should not accept a boolean argument - if it does it should have been named setChecked or something) or "don't call check". So if the checkbox is unchecked sending { check: isFalse } will do nothing and the checkbox will remain unchecked, and if the checkbox is checked it'll still do nothing and the checkbox will remain checked. If you want to uncheck you should send input { uncheck: isTrue }.

Title: Should I use check or checked?

Body:
I'm designing a library that binds to html elements on a page. In this particular case the input[type='checkbox'] will be checked if the likeItem property returns true and unchecked if the likeItem property returns false. What's the best practice for naming properties?

input { check: likeItem }

or

input { checked: likeItem }

This would also apply to other things like enable/enabled, disable/disabled, etc.


问:
Why is subclassing TraversableOnce not recommended
Reading http://www.scala-lang.org/api/2.11.1/index.html#scala.collection.TraversableOnce:

Directly subclassing TraversableOnce is not recommended - instead, consider declaring an Iterator with a next and hasNext method, creating an Iterator with one of the methods on the Iterator object, or declaring a subclass of Traversable.

Why is subclassing TraversableOnce not recommended?

答: It's because you would have to implement 12 relatively complex abstract methods, whereas with the recommended alternatives, you get that functionality much more easily.  TraversableOnce is there to provide a convenient abstract type for a function argument.


问:
Checked vs Unchecked vs No Exception... A best practice of contrary beliefs
There are many requirements needed for a system to properly convey and handle exceptions.  There are also many options for a language to choose from to implement the concept.

Requirements for exceptions (in no particular order):

Documentation: A language should have a mean to document exceptions an API can throw.  Ideally this documentation medium should be machine usable to allow compilers and IDEs to provide support to the programmer.

Transmit Exceptional Situations:  This one is obvious, to allow a function to convey situations that prevent the called functionality from performing the expected action.  In my opinion there are three big categories of such situations :

2.1 Bugs in the code that cause some data to be invalid.

2.2 Problems in configuration or other external resources.

2.3 Resources that are inherently unreliable (network, file systems, databases, end-users etc).  These are a bit of a corner case since their unreliable nature should have us expect their sporadic failures.  In this case are these situations to be considered exceptional ?

Provide enough information for code to handle it: The exceptions should provide sufficient information to the callee so that it can react and possibly handle the situation.  the information should also be sufficient so that when logged this exceptions would provide enough context to a programmer to identify and isolate the offending statements and provide a solution.

Provide confidence to the programmer about the current status of his code's execution state:  The exception handling capabilities of a software system should be present enough to provide the needed safeguards while staying out of the way of the programmer so he can stay focused on the task at hand.

To cover these the following methods were implemented in various languages:

Checked Exceptions  Provide a great way to document exceptions, and theoretically when implemented correctly should provide ample reassurance that all is good.  However the cost is such that many feel it more productive to simply bypass either by swallowing exceptions or re-throw them as unchecked exceptions.  When used inappropriately checked exceptions pretty much looses all it's usefulness.  Also, checked exceptions make it difficult to create a API that is stable in time.  Implementations of a generic system within a specific domain will bring it's load of exceptional situation that would become hard to maintain using solely checked exceptions.

Unchecked Exceptions - much more versatile than checked exception they fail to properly document the possible exceptional situations of a given implementation.  They rely on ad-hoc documentation if at all.  This creates situations where the unreliable nature of a medium is masked by an API that gives the appearance of reliability.  Also when thrown these exceptions loose their meaning as they move back up through the abstraction layers.  Since they are poorly documented a programmer cannot target them specifically and often needs to cast a much wider net than necessary to ensure that secondary systems, should they fail, do not bring down the whole system.  Which brings us right back to the swallowing problem checked exceptions provided.

Multistate return types  Here it is to rely on a disjoint set, tuple, or other similar concept to return either the expected result or an object representing the exception.  Here no stack unwinding, no cutting through code, everything executes normally but the return value must be validated for error prior to continuing.  I have not really worked with this yet so cannot comment from experience I acknowledge it resolves some problems exceptions bypassing the normal flow but still it will suffer from much the same problems as the checked exceptions as being tiresome and constantly "in your face".

So the question is :

What is your experience in this matter and what, according to you is the best candidate to make a good exception handling system for a language to have ?

EDIT:
Few minutes after writing this question I came across this post, spooky !

答:
I have become a big fan of Checked Exceptions and I'd like to share my general rule on when to use them.

I have come to the conclusion that there are basically 2 types of errors that my code has to deal with.  There are errors that are testable before the code executes and there are errors that are non-testable before the code executes.  A simple example for an error that is testable before the code is executed in a NullPointerException.

```<code>//... bad code below.  the runnable variable
// tries to call the run() method before the variable
// is instantiated.  Running the code below will cause
// a NullPointerException.
Runnable runnable = null;
runnable.run();
</code>```

A simple test could have avoided the error such as...

```<code>Runnable runnable = null;
...
if (runnable != null)
{   runnable.run(); }
</code>```

There are times in computing where you can run 1 or more tests before executing the code to make sure you are safe AND YOU WILL STILL GET AN EXCEPTION.  For example, you can test a file system to be sure there is enough disk space on the hard drive before you write your data to the drive.  In a multiprocessing operating system, such as the ones used today, your process could test for disk space and the file system will return a value saying there is enough space, then a context switch to another process could write the remaining bytes available to the operating system.  When the Operating system context switches back to your running process where you write your contents to disk, an Exception will occur simply because there is not enough disk space on the file system.

I consider the scenario above as a perfect case for a Checked Exception.  It's an Exception in the code that forces you to deal with something bad even though your code could be perfectly written.  If you choose to do bad things like 'swallow the exception', you are the bad programmer.  By the way, I have found cases where it is reasonable to swallow the exception but please leave a comment in the code as to why the exception was swallowed.  The Exception handling mechanism is not to blame.  I commonly joke that I'd prefer my heart pacemaker to be written with a language that has Checked Exceptions.

There are times when it becomes tough to decide whether the code is testable or not.  For example, if you are writing an interpreter and a SyntaxException is thrown when the code fails to execute for some syntactical reason, should the SyntaxException be a Checked Exception or (in Java) a RuntimeException?  I would answer if the interpreter checks the syntax of the code before the code is executed then the Exception should be a RuntimeException.  If the interpreter simply runs the code 'hot' and simply hits a Syntax error, I'd say the exception should be a Checked Exception.

I will admit that I'm not always happy to have to catch or throw a Checked Exception because there are time where I'm not sure what to do.  Checked Exceptions are a way to force a programmer to be mindful of the potential problem that can occur.  One of the reasons why I program in Java is because it has Checked Exceptions.

Body:
I have become a big fan of Checked Exceptions and I'd like to share my general rule on when to use them.

I have come to the conclusion that there are basically 2 types of errors that my code has to deal with.  There are errors that are testable before the code executes and there are errors that are non-testable before the code executes.  A simple example for an error that is testable before the code is executed in a NullPointerException.

//... bad code below.  the runnable variable
// tries to call the run() method before the variable
// is instantiated.  Running the code below will cause
// a NullPointerException.
Runnable runnable = null;
runnable.run();

A simple test could have avoided the error such as...

Runnable runnable = null;
...
if (runnable != null)
{   runnable.run(); }

There are times in computing where you can run 1 or more tests before executing the code to make sure you are safe AND YOU WILL STILL GET AN EXCEPTION.  For example, you can test a file system to be sure there is enough disk space on the hard drive before you write your data to the drive.  In a multiprocessing operating system, such as the ones used today, your process could test for disk space and the file system will return a value saying there is enough space, then a context switch to another process could write the remaining bytes available to the operating system.  When the Operating system context switches back to your running process where you write your contents to disk, an Exception will occur simply because there is not enough disk space on the file system.

I consider the scenario above as a perfect case for a Checked Exception.  It's an Exception in the code that forces you to deal with something bad even though your code could be perfectly written.  If you choose to do bad things like 'swallow the exception', you are the bad programmer.  By the way, I have found cases where it is reasonable to swallow the exception but please leave a comment in the code as to why the exception was swallowed.  The Exception handling mechanism is not to blame.  I commonly joke that I'd prefer my heart pacemaker to be written with a language that has Checked Exceptions.

There are times when it becomes tough to decide whether the code is testable or not.  For example, if you are writing an interpreter and a SyntaxException is thrown when the code fails to execute for some syntactical reason, should the SyntaxException be a Checked Exception or (in Java) a RuntimeException?  I would answer if the interpreter checks the syntax of the code before the code is executed then the Exception should be a RuntimeException.  If the interpreter simply runs the code 'hot' and simply hits a Syntax error, I'd say the exception should be a Checked Exception.

I will admit that I'm not always happy to have to catch or throw a Checked Exception because there are time where I'm not sure what to do.  Checked Exceptions are a way to force a programmer to be mindful of the potential problem that can occur.  One of the reasons why I program in Java is because it has Checked Exceptions.


问:
Complexity of ArrayList of LinkedHashSet
I get input strings from the console like this:

```<code>while ((currentLine = bufferedReader.readLine()) != null ) {
    StringTokenizer string = new StringTokenizer(currentLine, " ");
    while (string.hasMoreTokens()) {
        // Create a new LinkedHashSet for every token and then add it to the ArrayList.
        LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();
        linkedHashSet.add(string.nextToken());
        setOfStrings.add(linkedHashSet);
    }
}
</code>```

I'm always getting different strings from input, never the same. After finishing filling in the data structures I have this situation:

An ArrayList<LinkedHashSet<String>> which contains one LinkedHashSet for each string split.

Inside each LinkedHashSet I have a string that is different from any other string present in the other LinkedHashSets - in other words, its unique. For example, I can't have this inside the ArrayList:

```<code>Set x : [foo]
...
Set y : [foo]
</code>```

After doing that, I call the function below many times
to make different merges.

```<code>public void mergeSets(ArrayList<String> operations, ArrayList<LinkedHashSet<String>> setOfStrings) {
    String toMerge = operations.get(1);
    String fromMerge = operations.get(2);
    boolean enteredFirstToMerge = false;
    boolean enteredFirstFromMerge = false;
    // Temporary LinkedHashSet reference used to merge two sets.
    LinkedHashSet<String> subSetToMerge = null;
    LinkedHashSet<String> subSetFromMerge = null;
    for (Iterator<LinkedHashSet<String>> iterator = setOfStrings.iterator();
            iterator.hasNext(); ) {
        LinkedHashSet<String> subSet = iterator.next();
        if (subSet.contains(toMerge) && subSet.contains(fromMerge))
            break;
        else {
            if (subSet.contains(toMerge) && !enteredFirstToMerge) {
                enteredFirstToMerge = true;
                subSetToMerge = subSet;
                iterator.remove();
            } else if (subSet.contains(fromMerge) && !enteredFirstFromMerge) {
                enteredFirstFromMerge = true;
                subSetFromMerge = subSet;
            }
        }
        if (enteredFirstFromMerge && enteredFirstToMerge)
            break;
        }
        if (enteredFirstFromMerge && enteredFirstToMerge) {
            subSetFromMerge.addAll(subSetToMerge);
        }
    }
</code>```

Explanation:

For example, if I have as operation merge foo bar, I have to do these steps:

First of all, I have to find where foo and bar are located:

Inside setOfStrings, I can have this situation:

```<code>    position x : [bar, tree, hotel]
    ...
    position y : [foo, lemon, coffee]
</code>```

When I find them, I have to combine the set which contains foo with the set that contains bar  this way:

```<code>            position x : {bar tree hotel foo lemon coffee}
            ...
            position y : {} -> deleted from the arrayList
</code>```

This function takes as parameters an arrayList of operations and an arrayList<LinkedHashSet<String>>:

For the ArrayList of operations, I always get a specific position:

operations.get(1) refers to the set to merge (foo in this example)

operations.get(2) refers to the set where to add the foo set (bar in this example)

With this for loop, I iterate the ArrayList to search the to sets,for (Iterator<LinkedHashSet<String>> iterator = setOfStrings.iterator(); iterator.hasNext(); )

This if statement checks if the iterator is in the specific set:

```<code>if (subSet.contains(toMerge) && !enteredFirstToMerge) {
    enteredFirstToMerge = true;
    subSetToMerge = subSet;
    iterator.remove();
} else if (subSet.contains(fromMerge) && !enteredFirstFromMerge) {
    enteredFirstFromMerge = true;
    subSetFromMerge = subSet;
}
</code>```

My question is: Could I have collisions with this type of algorithm that I implemented?

If not the time complexity is only O(n) -> the size of the arrayList.

答:
Your main question is whether you could have a collision, but it's first important to determine where you might have a collision. An ArrayList does not have collisions because it is an ordered list on top of an array. Your concern there would be more about how often it has to extend the capacity of the underlying array. You would feel this when you are reading the input only, though.

Where you might have collisions is in the LinkedHashSets. Since hash collisions are a function of the capacity of the underlying hash store, the hashing algorithm, and the data itself, there is always a possibility for a collisions, and there is no way to know if you'll have one except to run all of your data through. In the end, since these are all different strings, and the hashing algorithm for strings built into Java is pretty effective, the remaining factor to determine how many collisions you could potentially have is the capacity of the underlying hash store.

A default LinkedHashSet has an initial capacity of 16 and a load factor of 0.75. This means that once there are 12 elements in the LinkedHashSet, it will double its capacity to accommodate more elements. If we can assume that hashes are evenly distributed, a larger capacity means a lower probability of a collision. Resizing a LinkedHashSet is actually the most expensive activity. In order to resize the underlying hash store, it essentially must iterate through the current elements, rehash them, and re-insert them into the larger hash store. Your best strategy to avoid collisions and rehashing is to allocate large LinkedHashSets when you instantiate them. What "large" is depends on how much data you are inputting and how much of it will be combined. If you know the size and general shape of your data before hand, you could try to estimate a proper initial size large enough to accommodate the largest set (needed size / 0.75 to account for the load factor). This essentially becomes the old time vs. space trade-off, as larger initial sizes means more memory consumed.

Other general suggestions

StringTokenizer is deprecated, and string.split(" ") is generally recommended in its place. However, since you are getting your input from the console, I would suggest disposing of the buffered reader completely and wrapping System.in in a Scanner. Scanner has a next() method that fetches the next token, implicitly tokenizing the input for you with less effort.

Also, while you are using ArrayList and LinkedHashSet for their performance characteristics, it is probably still better to rely on their interfaces (List and Set respectively) than those specific implementations.

Third, instead of writing out all of the code to get an iterator and then looping over it, you can use the for-each construct to loop over any Iterable.

Fourth, you don't need boolean flags when you can just as easily get the same information from a null check. We can eliminate two variables right off the bat.

Here's a slightly rewritten version incorporating those suggestions:

Main.java

```<code>import java.io.*;
import java.util.*;

public class Main
{
    public static void main(String[] args) throws IOException {
        Scanner input = new Scanner(System.in);
        List<Set<String>> setOfStrings = new ArrayList<>();

        while (input.hasNext()) {
            Set<String> tokenSet = new LinkedHashSet<>();
            tokenSet.add(input.next());
            setOfStrings.add(tokenSet);
        }

        SetMerger sm = new SetMerger();
        sm.mergeSets("foo", "bar", setOfStrings);
        sm.mergeSets("bar", "baz", setOfStrings);
        System.out.println(setOfStrings.toString());
    }
}
</code>```

SetMerger.java

```<code>import java.util.*;

public class SetMerger
{
    public void mergeSets(String toMerge, String fromMerge, List<Set<String>> stringSets) {
        Set<String> setToMerge = null, targetSet = null;

        for (Set<String> subset : stringSets) {
            if(subset.contains(toMerge)) {
                if(subset.contains(fromMerge)) {
                    return;
                }

                setToMerge = subset;
                break;
            }
        }

        for (Set<String> subset : stringSets) {
            if(subset.contains(fromMerge)) {
                targetSet = subset;
                break;
            }
        }

        if(setToMerge != null && targetSet != null) {
            targetSet.addAll(setToMerge);
            stringSets.remove(setToMerge);
        }
    }
}
</code>```

Body:
Your main question is whether you could have a collision, but it's first important to determine where you might have a collision. An ArrayList does not have collisions because it is an ordered list on top of an array. Your concern there would be more about how often it has to extend the capacity of the underlying array. You would feel this when you are reading the input only, though.

Where you might have collisions is in the LinkedHashSets. Since hash collisions are a function of the capacity of the underlying hash store, the hashing algorithm, and the data itself, there is always a possibility for a collisions, and there is no way to know if you'll have one except to run all of your data through. In the end, since these are all different strings, and the hashing algorithm for strings built into Java is pretty effective, the remaining factor to determine how many collisions you could potentially have is the capacity of the underlying hash store.

A default LinkedHashSet has an initial capacity of 16 and a load factor of 0.75. This means that once there are 12 elements in the LinkedHashSet, it will double its capacity to accommodate more elements. If we can assume that hashes are evenly distributed, a larger capacity means a lower probability of a collision. Resizing a LinkedHashSet is actually the most expensive activity. In order to resize the underlying hash store, it essentially must iterate through the current elements, rehash them, and re-insert them into the larger hash store. Your best strategy to avoid collisions and rehashing is to allocate large LinkedHashSets when you instantiate them. What "large" is depends on how much data you are inputting and how much of it will be combined. If you know the size and general shape of your data before hand, you could try to estimate a proper initial size large enough to accommodate the largest set (needed size / 0.75 to account for the load factor). This essentially becomes the old time vs. space trade-off, as larger initial sizes means more memory consumed.

Other general suggestions

StringTokenizer is deprecated, and string.split(" ") is generally recommended in its place. However, since you are getting your input from the console, I would suggest disposing of the buffered reader completely and wrapping System.in in a Scanner. Scanner has a next() method that fetches the next token, implicitly tokenizing the input for you with less effort.

Also, while you are using ArrayList and LinkedHashSet for their performance characteristics, it is probably still better to rely on their interfaces (List and Set respectively) than those specific implementations.

Third, instead of writing out all of the code to get an iterator and then looping over it, you can use the for-each construct to loop over any Iterable.

Fourth, you don't need boolean flags when you can just as easily get the same information from a null check. We can eliminate two variables right off the bat.

Here's a slightly rewritten version incorporating those suggestions:

Main.java

import java.io.*;
import java.util.*;

public class Main
{
    public static void main(String[] args) throws IOException {
        Scanner input = new Scanner(System.in);
        List<Set<String>> setOfStrings = new ArrayList<>();

        while (input.hasNext()) {
            Set<String> tokenSet = new LinkedHashSet<>();
            tokenSet.add(input.next());
            setOfStrings.add(tokenSet);
        }

        SetMerger sm = new SetMerger();
        sm.mergeSets("foo", "bar", setOfStrings);
        sm.mergeSets("bar", "baz", setOfStrings);
        System.out.println(setOfStrings.toString());
    }
}

SetMerger.java

import java.util.*;

public class SetMerger
{
    public void mergeSets(String toMerge, String fromMerge, List<Set<String>> stringSets) {
        Set<String> setToMerge = null, targetSet = null;

        for (Set<String> subset : stringSets) {
            if(subset.contains(toMerge)) {
                if(subset.contains(fromMerge)) {
                    return;
                }

                setToMerge = subset;
                break;
            }
        }

        for (Set<String> subset : stringSets) {
            if(subset.contains(fromMerge)) {
                targetSet = subset;
                break;
            }
        }

        if(setToMerge != null && targetSet != null) {
            targetSet.addAll(setToMerge);
            stringSets.remove(setToMerge);
        }
    }
}


问:
What types of programming require practical category theory?
Category theory has applications in theoretical computer science and obviously is central to abstract mathematics.  I have heard that it also has direct practical applications in programming and software development.

What type of programming is practical category theory necessary for? What do programmers use category theory to accomplish?

Please note my use of "necessary" and "require" in this post.  I realize that in some sense most programmers will benefit from having experience in different types of theories, but I am looking for direct applications where the usage of category theory is essential, i.e. if you didn't know category theory, you probably couldn't do it.

Also, I'd like to clarify that by "what type of programming," I am hoping less for a broad answer like "functional programming," and more for specific applications like "writing bank software" or "making operating systems."

答:
It's like org-mode for banks.

I realise that's vague but you did say you wanted a practical answer..

Categories are all about duality (or at least that's how I see it) because of the axiom of choice, so personally I'd say it'd be a silly way to induct a unified type system although a type itself (an instance of a type) is basically a category.

Simply typed lambda calculi don't have an axiomatic type system, which is why they are said to be the foundation for type theory. This is different from lambda calculi that use a proper type system.

Simply typed lambda calculus strongly normalizes and although matching types is pretty boring, the logic is sound.

Also infinite/dependently typed lambda calculus (or purely typed) does not normalize properly as it has a type for all types, which is basically a church encoded type system.

Categories are everywhere but are by very nature almost impossible to see straight away.

OwnerDisplayName: Alexander Gruber


答:
A pointer-to-pointer simply means that you have an address of a memory location where some other pointer is stored. You dereference it twice to get to the final typed value.

```<code>int i = 123;
int* pi = &i;
int ** ppi = π
int j = **ppi;
</code>```

There are a surprising number of situations in which you need to use one of these beasties.

As an output argument of a function call, pass a pointer to the pointer you want output or modified.

Accessing an array of C null-terminated strings; each string is itself a pointer. The argc argument to main looks like that.

'Jagged' or N-dimensional arrays, stored as array of pointer to data. The data will usually be allocated with malloc().

A 'handle' for a memory block, so the owner of the block can move it without the user of the block needing to know.

Manipulating a structure that itself contains pointers, such as linked lists, trees and so on. It's basically impossible to insert an item into a linked list without them.

It's important to keep these conceptually separate. Although they all seem to use the same construct, in reality the underlying purpose is quite different. And I'm sure there are others I've missed.

I won't provide more code. There is an excellent example with diagrams and code here: http://www.eskimo.com/~scs/cclass/int/sx8.html.

Title: usage of double pointers and n pointers?

Body:
I am familiar with basic C pointers. Just wanted to ask what is the actual use of double pointers or for that matter n pointer?

```<code>#include<stdio.h>
int main()
{
    int n = 10 , *ptr , **ptr_ptr ;
    ptr = &n;
    ptr_ptr = &ptr;
    printf("%d", **ptr_ptr);
    return(0);
}
</code>```

**ptr_ptr is printing 10 but how?

Body:
A pointer-to-pointer simply means that you have an address of a memory location where some other pointer is stored. You dereference it twice to get to the final typed value.

int i = 123;
int* pi = &i;
int ** ppi = &pi;
int j = **ppi;

There are a surprising number of situations in which you need to use one of these beasties.

As an output argument of a function call, pass a pointer to the pointer you want output or modified.

Accessing an array of C null-terminated strings; each string is itself a pointer. The argc argument to main looks like that.

'Jagged' or N-dimensional arrays, stored as array of pointer to data. The data will usually be allocated with malloc().

A 'handle' for a memory block, so the owner of the block can move it without the user of the block needing to know.

Manipulating a structure that itself contains pointers, such as linked lists, trees and so on. It's basically impossible to insert an item into a linked list without them.

It's important to keep these conceptually separate. Although they all seem to use the same construct, in reality the underlying purpose is quite different. And I'm sure there are others I've missed.

I won't provide more code. There is an excellent example with diagrams and code here: http://www.eskimo.com/~scs/cclass/int/sx8.html.


答:
For a long time OO languages, the use of exceptions have been the de-facto standard for communicating errors. But functional programming languages provide the possibility of a different approach, e.g. using monads (which I have not been using), or the more lightweight "Railway Oriented Programming", as described by Scott Wlaschin.

In this blog post

In this presentation at NDC 2014

It is really a variant of the multistate result type.

A function returns either a success, or an error. It cannot return both (as is the case with a tuple).

All possible errors have been succinctly documented (At least in F# with result types as discriminated unions).

The caller cannot use the result without taking into consideration if the result was a success or a failure.

The result type could be declared like this

```<code>type Result<'TSuccess,'TFail> =
| Success of 'TSuccess
| Fail of 'TFail
</code>```

So the result of a function that returns this type would be either a Success or a Fail type. It cannot be both.

In more imperative oriented programming languages, this kind of style could require a large amount of code on the caller site. But functional programming allows you to construct binding functions or operators to tie together multiple functions so error checking doesn't take up half the code. As an example:

```<code>// Create an updateUser function that takes an id, and new state
// as input, and updates an existing user.
let updateUser id input =
    validateInput input
    >>= loadUser id
    >>= updateUser input
    >>= saveUser id
    >>= notifyAboutUserUpdated
</code>```

The updateUser function calls each of these functions in succession, and each of them could fail. If they all succeed, the result of the last called function is returned. If one of the functions fail, then the result of that function will be the result of the overall updateUser function. This is all handled by the custom >>= operator.

In the above example, the error types could be

```<code>type UserValidationErrorType =
| InvalidEmail of string
| MissingFirstName of string
... etc

type DbErrorType =
| RecordNotFound of int
| ConcurrencyError of int

type UpdateUserErrorType =
| InvalidInput of UserValidationErrorType
| DbError of DbErrorType
</code>```

If the caller of updateUser does not explicitly handle all possible errors from the function, the compiler will issue a warning. So you have everything documented.

In Haskell, there is a do notation that can make the code even cleaner.

Title: Checked vs Unchecked vs No Exception... A best practice of contrary beliefs

Body:
There are many requirements needed for a system to properly convey and handle exceptions.  There are also many options for a language to choose from to implement the concept.

Requirements for exceptions (in no particular order):

Documentation: A language should have a mean to document exceptions an API can throw.  Ideally this documentation medium should be machine usable to allow compilers and IDEs to provide support to the programmer.

Transmit Exceptional Situations:  This one is obvious, to allow a function to convey situations that prevent the called functionality from performing the expected action.  In my opinion there are three big categories of such situations :

2.1 Bugs in the code that cause some data to be invalid.

2.2 Problems in configuration or other external resources.

2.3 Resources that are inherently unreliable (network, file systems, databases, end-users etc).  These are a bit of a corner case since their unreliable nature should have us expect their sporadic failures.  In this case are these situations to be considered exceptional ?

Provide enough information for code to handle it: The exceptions should provide sufficient information to the callee so that it can react and possibly handle the situation.  the information should also be sufficient so that when logged this exceptions would provide enough context to a programmer to identify and isolate the offending statements and provide a solution.

Provide confidence to the programmer about the current status of his code's execution state:  The exception handling capabilities of a software system should be present enough to provide the needed safeguards while staying out of the way of the programmer so he can stay focused on the task at hand.

To cover these the following methods were implemented in various languages:

Checked Exceptions  Provide a great way to document exceptions, and theoretically when implemented correctly should provide ample reassurance that all is good.  However the cost is such that many feel it more productive to simply bypass either by swallowing exceptions or re-throw them as unchecked exceptions.  When used inappropriately checked exceptions pretty much looses all it's usefulness.  Also, checked exceptions make it difficult to create a API that is stable in time.  Implementations of a generic system within a specific domain will bring it's load of exceptional situation that would become hard to maintain using solely checked exceptions.

Unchecked Exceptions - much more versatile than checked exception they fail to properly document the possible exceptional situations of a given implementation.  They rely on ad-hoc documentation if at all.  This creates situations where the unreliable nature of a medium is masked by an API that gives the appearance of reliability.  Also when thrown these exceptions loose their meaning as they move back up through the abstraction layers.  Since they are poorly documented a programmer cannot target them specifically and often needs to cast a much wider net than necessary to ensure that secondary systems, should they fail, do not bring down the whole system.  Which brings us right back to the swallowing problem checked exceptions provided.

Multistate return types  Here it is to rely on a disjoint set, tuple, or other similar concept to return either the expected result or an object representing the exception.  Here no stack unwinding, no cutting through code, everything executes normally but the return value must be validated for error prior to continuing.  I have not really worked with this yet so cannot comment from experience I acknowledge it resolves some problems exceptions bypassing the normal flow but still it will suffer from much the same problems as the checked exceptions as being tiresome and constantly "in your face".

So the question is :

What is your experience in this matter and what, according to you is the best candidate to make a good exception handling system for a language to have ?

EDIT:
Few minutes after writing this question I came across this post, spooky !

Body:
For a long time OO languages, the use of exceptions have been the de-facto standard for communicating errors. But functional programming languages provide the possibility of a different approach, e.g. using monads (which I have not been using), or the more lightweight "Railway Oriented Programming", as described by Scott Wlaschin.

In this blog post

In this presentation at NDC 2014

It is really a variant of the multistate result type.

A function returns either a success, or an error. It cannot return both (as is the case with a tuple).

All possible errors have been succinctly documented (At least in F# with result types as discriminated unions).

The caller cannot use the result without taking into consideration if the result was a success or a failure.

The result type could be declared like this

type Result<'TSuccess,'TFail> =
| Success of 'TSuccess
| Fail of 'TFail

So the result of a function that returns this type would be either a Success or a Fail type. It cannot be both.

In more imperative oriented programming languages, this kind of style could require a large amount of code on the caller site. But functional programming allows you to construct binding functions or operators to tie together multiple functions so error checking doesn't take up half the code. As an example:

// Create an updateUser function that takes an id, and new state
// as input, and updates an existing user.
let updateUser id input =
    validateInput input
    >>= loadUser id
    >>= updateUser input
    >>= saveUser id
    >>= notifyAboutUserUpdated

The updateUser function calls each of these functions in succession, and each of them could fail. If they all succeed, the result of the last called function is returned. If one of the functions fail, then the result of that function will be the result of the overall updateUser function. This is all handled by the custom >>= operator.

In the above example, the error types could be

type UserValidationErrorType =
| InvalidEmail of string
| MissingFirstName of string
... etc

type DbErrorType =
| RecordNotFound of int
| ConcurrencyError of int

type UpdateUserErrorType =
| InvalidInput of UserValidationErrorType
| DbError of DbErrorType

If the caller of updateUser does not explicitly handle all possible errors from the function, the compiler will issue a warning. So you have everything documented.

In Haskell, there is a do notation that can make the code even cleaner.


答:
According to IBM this actually is an anti-pattern. These 'typedef' like classes are called psuedo types.

The article explains it a lot better than I do, but I'll try to summarize it in case the link goes down:

Any code that expects a WidgetCache cannot handle a Map<String, Widget>

These Pseudotypes are 'viral' when using multiple packages they lead to incompatibilities while the base type (just a silly Map<...>) would've worked in all cases in all packages.

Pseudo types are often to concrete, they do not implement specific interfaces because their base classes only implement the generic version.

In the article they propose the following trick to make life easier without using pseudo types:

```<code>public static <K,V> Map<K,V> newHashMap() {
    return new HashMap<K,V>();
}

Map<Socket, Future<String>> socketOwner = Util.newHashMap();
</code>```

Which works due to automatic type inference.

(I came to this answer via this related stack overflow question)

Body:
According to IBM this actually is an anti-pattern. These 'typedef' like classes are called psuedo types.

The article explains it a lot better than I do, but I'll try to summarize it in case the link goes down:

Any code that expects a WidgetCache cannot handle a Map<String, Widget>

These Pseudotypes are 'viral' when using multiple packages they lead to incompatibilities while the base type (just a silly Map<...>) would've worked in all cases in all packages.

Pseudo types are often to concrete, they do not implement specific interfaces because their base classes only implement the generic version.

In the article they propose the following trick to make life easier without using pseudo types:

public static <K,V> Map<K,V> newHashMap() {
    return new HashMap<K,V>();
}

Map<Socket, Future<String>> socketOwner = Util.newHashMap();

Which works due to automatic type inference.

(I came to this answer via this related stack overflow question)