问:
How to organize Javascript and AJAX with PHP?
My javascript is getting out of hand for my PHP application. I have 20  tags that link to various javascript files in a javascript folder.
Each javascript file basically controls one element on the DOM. And, if the javascript file uses AJAX, then it will have a corresponding PHP file that the AJAX will call.

For example, a js file might control a button on the page:

```<code>$(document).ready(function () {
  $("#button").live('click', function() {
    $.ajax({
      type: "POST",
      data: ...
      url: "button_click.php",
    });
  });
});
</code>```

As you can see, this gets out of hand. What is the best way to organize all of the javascript?

答:
Can the data that you are posting be included in the markup? I.e.

```<code><form action="button_click.php" method="post">
    <input type="hidden" name="data1" value="foo" />
    <input type="hidden" name="data2" value="bar" />

    <button name="button1" class="ajax-button" value="foobar">Click Me!</button>
</form>
</code>```

If this is possible, you could then combine your click events into one dynamic event, like this:

```<code>$('.ajax-button').on('click', function() {
    var form = $(this).parent('form');

    $.ajax({
        type: "POST",
        data: form.serialize(),
        url: form.attr('action'),
    });

    return false;
});
</code>```

This example would POST the following data to button_click.php:

```<code>data1: foo,
data2: bar,
button1: foobar
</code>```

Body:
Can the data that you are posting be included in the markup? I.e.

<form action="button_click.php" method="post">
    <input type="hidden" name="data1" value="foo" />
    <input type="hidden" name="data2" value="bar" />

    <button name="button1" class="ajax-button" value="foobar">Click Me!</button>
</form>

If this is possible, you could then combine your click events into one dynamic event, like this:

$('.ajax-button').on('click', function() {
    var form = $(this).parent('form');

    $.ajax({
        type: "POST",
        data: form.serialize(),
        url: form.attr('action'),
    });

    return false;
});

This example would POST the following data to button_click.php:

data1: foo,
data2: bar,
button1: foobar


问:
Subset counting algorithm
I have a following problem i want to solve efficiently :

Input: Set s of {Pass,Fail}^k vectors, m - minimum percent of vectors

Output : Set of Sets of indexes: Where each set Contains indexes of Pass word in given vectors, and number of vectors that contains Pass in those indexes is over m percent from total vectors.

Example: {(Pass,Fail,Pass,Fail),(Pass,Fail,Pass,Pass)} where k is 4 and number of set elements is 2 and m 60% , output will be {{0,2},{0},{2}}

The output is group of sets where every set contains vector indexes that for at least 60% of vectors value was Pass

答:
This should give you the indices. The next step is to construct the power set out of these.

http://www.google.com/#sclient=psy&hl=en&source=hp&q=python+power+set+generator&pbx=1&oq=python+power+set&aq=1v&aqi=g1g-v1&aql=&gs_sm=e&gs_upl=771l3682l0l6333l16l13l0l2l2l0l263l1455l4.6.2l12l0&bav=on.2,or.r_gc.r_pw.&fp=116a3ca570808e30&biw=1536&bih=790

You can look up what enumerate and list comprehensions and tuples are. Let me know if you are stuck translating this into C#.

```<code>s = ((True,False,True,False),(True,False,True,True))
indecies = [0] + [i+1 for i, vctr in enumerate(s) if sum(vctr) >= 0.6 * len(el)]
indecies
[0, 2]
</code>```

Notes:
A) You always need to prepend the 0 index, which represents the empty set.
B) The way in which I prepended it here is inefficient, but you can find a better way.
C) The complexity so far is proportional to the total number of grades.
D) You can make 60% a parameter rather than a hard-coded constant.
E) It was hard to parse out your requirements, so I assumed that you wanted to filter out the loosing vectors, and then compute a power set of the remaining indices.

ContentLicense: CC BY-SA 3.0

Title: Subset counting algorithm

Body:
This should give you the indices. The next step is to construct the power set out of these.

http://www.google.com/#sclient=psy&hl=en&source=hp&q=python+power+set+generator&pbx=1&oq=python+power+set&aq=1v&aqi=g1g-v1&aql=&gs_sm=e&gs_upl=771l3682l0l6333l16l13l0l2l2l0l263l1455l4.6.2l12l0&bav=on.2,or.r_gc.r_pw.&fp=116a3ca570808e30&biw=1536&bih=790

You can look up what enumerate and list comprehensions and tuples are. Let me know if you are stuck translating this into C#.

s = ((True,False,True,False),(True,False,True,True))
indecies = [0] + [i+1 for i, vctr in enumerate(s) if sum(vctr) >= 0.6 * len(el)]
indecies
[0, 2]

Notes:
A) You always need to prepend the 0 index, which represents the empty set.
B) The way in which I prepended it here is inefficient, but you can find a better way.
C) The complexity so far is proportional to the total number of grades.
D) You can make 60% a parameter rather than a hard-coded constant.
E) It was hard to parse out your requirements, so I assumed that you wanted to filter out the loosing vectors, and then compute a power set of the remaining indices.


问:
Why (not) segmentation?
I am studying operating systems and the x86 architecture, and while I was reading about segmentation and paging I naturally was curious how modern OSes handle memory management. From what I found Linux and most other operating systems essentially shun segmentation in favor of paging. A few of the reasons for this that I found were simplicity and portability.

What practical uses are there for segmentation (x86 or otherwise) and will we ever see robust operating systems using it or will they continue to favor a paging based system.

Now I know this is a loaded question but I am curious how segmentation would be handled with newly developed operating systems. Does it make so much sense to favor paging that no one will consider a more 'segmented' approach? If so, why?

And when I say 'shun' segmentation I am implying that Linux only uses it as far as it has to. Only 4 segments for user and kernel code/data segments. While reading the Intel documentation I just got the feeling that segmentation was designed with more robust solutions in mind. Then again I was told on many occasions how over complicated the x86 can be.

I found this interesting anecdote after being linked to Linux Torvald's original 'announcement' for Linux. He said this a few posts later:

Simply, I'd say that porting is impossible.  It's mostly in C, but most
  people wouldn't call what I write C.  It uses every conceivable feature
  of the 386 I could find, as it was also a project to teach me about the
  386.  As already mentioned, it uses a MMU, for both paging (not to disk
  yet) and segmentation. It's the segmentation that makes it REALLY 386
  dependent (every task has a 64Mb segment for code & data - max 64 tasks
  in 4Gb. Anybody who needs more than 64Mb/task - tough cookies).

I guess my own experimentation with x86 led me to ask this question. Linus didn't have StackOverflow, so he just implemented it to try it out.

答:
Segmentation is a huge burden for applications developers.   This is where the big push came from to do away segmentation.

Interestingly I often wonder how much better i86 could be if Intel striped out all legacy support for these old modes.  Here better would imply lower power and maybe faster operation.

I guess one could argue that Intel soured the milk with 16bit segments leading to a developer revolt of sorts.  But let's face it a 64k address space is nothing especially when you look at modern app.  In the end they had to do something because the competition could and did market effectively against the address space issues of i86.

OwnerDisplayName: Mr. Shickadance

Title: Why (not) segmentation?


问:
Is SQL important if I know ORM frameworks well?
I don't have any serious experience in SQL and I even hate to write SQL instead of LINQ. I am happy enough with ORMs.

From the employers and sector view point, is it important to know SQL? Do I have to master on it? Are companies that prefer pure SQL over ORM frameworks a "dinosaur" in the programming world?

答:
I will admit that I am a die hard ORM fan and have been preaching the benefits of ORM for years and had a lot to say about why ORM trumps SQL.

BUT...

I have to admit SQL is totally and utterly required in the real world and every developer should have a good understanding of SQL.

SQL procs are faster than the ORM in almost all cases. Even though you can optimistic the ORM output in most cases too make it come in a close second to SQL procs.

On occasion, you require some heavy duty SQL to get the result you require, and these monster queries are easier and faster to create in SQL procs.

Just my two bits.


问:
Parallel programming library? (+ some features)
Note: this is a reposting as the question has been considered non-suitable for the Stack Overflow forum and should have been posted here. The original topic is there.

I'd like to talk of multithreading, parallelism and the libraries available today to achieve that work. I'm especially wondering whether an easy-to-use library to achieve this concept (given below) already exists, or whether it would have to be written, and how hard it would be.

The purposes of the library I'm looking for:

accessible to most developers, not only to engineers or highly graduated persons (this should mean developers WANT to use it, not being afraid of it)

available to C++ developers

portable (start with Windows, Mac OS X and Linux, then extend to mobile devices)

lightweight

easy-to-use (related to accessibility)

The most important features I'm looking for:

task parallelism

task cancellation (in a soft and abrupt manner)

task dependencies

The existing related libraries:

Thread Building Blocks : really complicated to use, and rather restrictive licence (GPL / commercial), it's the only library that I've found and that includes all of the features I'm looking for

Grand Central Dispatch : currently not portable, not too complicated, no task cancellation (once started), no task dependencies, no automatic dependency support (only manual)

PFunc : Unix only, still a bit complicated, no task dependency, no task cancellation

Microsoft Task Parallel Library : MS platform and .NET only, no hard cancellation, restricted and manual task dependencies (one task cannot wake up more than one other task)

OpenCL : not currently available on all platforms, not much more that an GPU parallel task library (not as high level as I would wish)

OpenMP : widely supported except free versions of Visual Studio, no task cancellation nor automatic task dependencies

So what are your thoughts about all of these? Why do you think there are so few libraries corresponding to these needs? Or did I miss some great library? And do you think it would mean too much work to achieve one? Or not interesting enough? Note that the lacks I wrote are those I found out with some searches, I'm not a expert in any of these libraries.

The final purpose of this library, even if it's rather a dream, would be programming in a parallelized way as easily as you usually do with sequential programming.

Ceylo

答:
TBB is pretty much all there is that comes close. boost::thread is much too low level. You're looking in the wrong place at the TPL, by the way- Microsoft ship a separate library called the PPL for native code. It, of course, only supports Windows.

However, if you find TBB to be complicated to use, I'd question whether or not the developers you're thinking about are actually capable of creating parallel applications. TBB has one of the friendliest interfaces around with simple things like parallel_for_each. If you can't cope with a couple of lambdas, I find it hard to see how you'll cope with concurrency.


问:
PHP framework most similar to ASP.NET MVC3?
I've done a bit of work with CodeIgniter and a lot with straight PHP...

I had the opportunity to use asp.net mvc3 recently and was absolutely blown away with my productivity. Despite not "knowing" the framework, the combination of scaffolding + intellisense + code generation through the context menus left me feeling just as productive with asp.net as with PHP.

I've evaluated YII, CakePHP, symfony (a long time ago, pre 2.0), and Kohana... and while YII seems most promising none quite matched up to my experience with mvc3.

答: Cakephp has scaffolding but it shouldn't be used for production. As far as IDE I am partial to NetBeans, its really great. I also use mercurial, and netbeans has the best mercurial support I've ever seen right out the box.</p>


问:
Is the 80 character limit still relevant in times of widescreen monitors?
on a widescreen monitor one can easily see more than 80 characters at a time, without scrollbars. even linus torvalds sees the 80 character limit as outdated.

so, is the 80 character limit still relevant in times of widescreen monitors?

答:
Having some limit certainly makes sense.  But 80 character limit is too constraining.  I prefer something like 96 character limit.  It's wide enough for most of the code I have to deal with and it's narrow enough so that two files can be put side by side for diff'ing (on a wide screen).

I believe code readability trumps all other concerns.  And with 96 characters per line code can be made much more readable than with 80.

I don't buy the argument that most people set their terminals to 80 characters wide, no that printers have to wrap lines longer than 80 characters.  It's not a hard limit as it used to be in the (distant) past.  You can easily set the terminal and the printer width to 100 characters.

ContentLicense: CC BY-SA 2.5


问:
Business Objects - Containers or functional?
This is a question I asked a while back on SO, but it may get discussed better here...

Where I work, we've gone back and forth on this subject a number of times and are looking for a sanity check. Here's the question: Should Business Objects be data containers (more like DTOs) or should they also contain logic that can perform some functionality on that object.

Example - Take a customer object, it probably contains some common properties (Name, Id, etc), should that customer object also include functions (Save, Calc, etc.)?

One line of reasoning says separate the object from the functionality (single responsibility principal) and put the functionality in a Business Logic layer or object.

The other line of reasoning says, no, if I have a customer object I just want to call Customer.Save and be done with it. Why do I need to know about another class to save a customer if I'm consuming the object?

Our last two projects have had the objects separated from the functionality, but the debate has been raised again on a new project.

Which makes more sense and why??

答:
I think both ways of doing it can have their benefits, but I would look at it from an object oriented or domain driven view: what are the responsibilities of the different classes and objects.

So, I would ask myself this, in your concrete case: should a customer know how to save itself?

To me, the answer would be no: logically to me it doesn't make sense, and a customer should not have to know anything about any persistence framework at all (separation of responsibilities).

As for SnOrfus' examples with Customer.UpgradeWarranty() or Customer.PromoteToPreferred(), they are obviously more business logic oriented than Customer.Save(). There are different approaches to this, but again if you ask yourself if a customer is supposed to be able to upgrade his warranty, the answer might be both yes or no, depending on how you look at it:

yes: a customer can of course upgrade his warranty

no: a customer could ask to be upgraded, but the upgrade is done by someone else

Back to your original question; which way makes more sense will probably depend on who you ask and their preferred method, but the most important thing is probably to stick to one way of doing it.

In my experience, though, separating data and (business) logic makes for a simpler architecture, although not as exciting.


问:
How to prevent deep indentations?
What steps and measures can I take to prevent deep indentations in my code?</p>

答:
Maybe you could consider guard clauses?

instead of

```<code>public void DoSomething(int value){
    if (someCondition){
           if(someOtherCondition){
                if(yetAnotherCondition){
                       //Finally execute some code
                }
           }
    }
}
</code>```

Do

```<code>public void DoSomething(int value){
    if(!(someCondition && someOtherCondition && yetAnotherCondition)){
        return;
        //Maybe throw exception if all preconditions must be true
    }
    //All preconditions are safe execute code
}
</code>```

If you ever get a chance I'd reccommend you read Code Complete by Steve McConnell. He's got a lot of great advise on these topics.

http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670/ref=pd_sim_b_6

For more about "guard clauses" see: https://sourcemaking.com/refactoring/replace-nested-conditional-with-guard-clauses

Title: How to prevent deep indentations?

Body:
Maybe you could consider guard clauses?

instead of

public void DoSomething(int value){
    if (someCondition){
           if(someOtherCondition){
                if(yetAnotherCondition){
                       //Finally execute some code
                }
           }
    }
}

Do

public void DoSomething(int value){
    if(!(someCondition && someOtherCondition && yetAnotherCondition)){
        return;
        //Maybe throw exception if all preconditions must be true
    }
    //All preconditions are safe execute code
}

If you ever get a chance I'd reccommend you read Code Complete by Steve McConnell. He's got a lot of great advise on these topics.

http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670/ref=pd_sim_b_6

For more about "guard clauses" see: https://sourcemaking.com/refactoring/replace-nested-conditional-with-guard-clauses


问:
What is the best practice for reading a large number of custom settings from a text file?
So I have been looking through some code I wrote a few years ago for an economic simulation program. Each simulation has a large number of settings that can be saved to a file and later loaded back into the program to re-run the same/similar simulation. Some of the settings are optional or depend on what is being simulated.

The code to read back the parameters is basically one very large switch statement (with a few nested switch statements). I was wondering if there is a better way to handle this situation.

One line of the settings file might look like this:

```<code>#RA:1,MT:DiscriminatoryPriceKDoubleAuction,OF:Demo Output.csv,QM:100,NT:5000,KP:0.5 //continues...
</code>```

And some of the code that would read that line:

```<code>switch( Character.toUpperCase( s.charAt(0) ) )
{
    case 'R':
         randSeed = Integer.valueOf( s.substring(3).trim() );
         break;
    case 'M':
          marketType = s.substring(3).trim();
          System.err.println("MarketType: " + marketType);
          break;
    case 'O':
          outputFileName = s.substring(3).trim() ;
          break;
    case 'Q':
          quantityOfMarkets = Integer.valueOf( s.substring(3).trim() );
          break;
    case 'N':
          maxTradesPerRound = Integer.valueOf( s.substring(3).trim() );
          break;
    case 'K':
          kParameter = Float.valueOf( s.substring(3).trim() );
          break;
 // continues...
}
</code>```

答:
From a code perspective, the cleanest method would be to switch to the Properties class. It's made for handling this, although you would either need to define all of your settings (even the unused ones) in the file it reads from or have predefined constants in a source file that you can use if the properties file returns null for a particular named property.

If you can't change the scheme, you could follow the general strategy of having a Hashtable, which is really what the Properties class does - it reads a file into a Hashtable conveniently. It would pretty much be rolling your own properties. Again, you would have to have preset values defined somehow to handle cases where a setting that you need might not exist in the file.

The way you would use either is to simply query the data structure any time you needed a value. You can either enforce that it exists in the data structure (throw an Exception and terminate it it doesn't) or define default values somehow (probably in a source file).


问:
What is understood under "unit" in unit testing
As I understand in theory under "unit" people mean method (in OOP). But in practice tests which verify some method in isolation are very fragile behaviour tests (verifying not the result but the fact that some dependency method was called). So I see a lot of people who by unit understand a small set of closely related classes. In this case only outer dependencies are mocked/stubbed and for dependencies which are inside unit real implementations are used. In this case there are more state, meaningful (according to specification) and not so fragile tests. So the question is how do you feel about these approaches and is it valid to call the second approach unit testing or may be it is some kind of low-level integration testing?

If you see some specific considerations about applying TDD by one of these ways of testing, I would be thankful for your thoughts.

答:
A unit is most commonly defined as "the smallest testable part of an application". More often than not, yes, this means a method. And yes, this means that you shouldn't test the result of a dependant method, but just that the method is called (and then only once, if possible, not in every test for that method).

You call this fragile. I think that is incorrect. Fragile tests are those that break under the slightest change to unrelated code. That is, those which rely on code that is irrelevant to the functionality being tested.

However, what I think you really mean to say is that testing a method with none of its dependencies is not thorough. On that point I would agree. You also need integration tests to make sure that the units of code are correctly hooked together to make an application.

This is exactly the problem that behaviour-driven development, and specifically acceptance-test-driven development, sets out to solve. But that doesn't remove the need for unit tests / test-driven development; it merely complements it.


答:
As the name suggests you are testing an atomic subject in each test. Such a subject is usually a single method. Multiple tests can test the same method, in order to cover the happy path, possible errors, etc. You are testing behaviour, not internal mechanics. So unit testing is really about testing a class' public interface, i.e. a specific method.

In unit testing, a method needs to be tested in isolation, that is, by stubbing/mocking/faking any dependencies. Otherwise, testing a unit with 'real' dependencies makes it an integration test. There is a time and place for both types of tests. Unit tests ensure a single subject works as expected, standalone. Integration tests ensure that 'real' subjects work together correctly.

Title: What is understood under "unit" in unit testing

Body:
As I understand in theory under "unit" people mean method (in OOP). But in practice tests which verify some method in isolation are very fragile behaviour tests (verifying not the result but the fact that some dependency method was called). So I see a lot of people who by unit understand a small set of closely related classes. In this case only outer dependencies are mocked/stubbed and for dependencies which are inside unit real implementations are used. In this case there are more state, meaningful (according to specification) and not so fragile tests. So the question is how do you feel about these approaches and is it valid to call the second approach unit testing or may be it is some kind of low-level integration testing?

If you see some specific considerations about applying TDD by one of these ways of testing, I would be thankful for your thoughts.


问:
What are some effective ways of helping someone learn a programming language/framework in a focused way?
Here's some background:

I have someone who is motivated to help me out on a project that already has a good chunk of code written

The person does not have a CS background, but knows the basics (functions, variables, objects, classes, etc)

The goal isn't to make this person a rockstar developer overnight - they just need to be able to pull their weight on this specific project.

The project is a Rails project, but if there are general responses, I'd like to favor them.

The current approach that is being taken is to give this person a simple feature (that has a similar feature already written). Then nudging them when they get confused, while trying not to give them full chunks of code.

Regardless, they're very confused and frustrated, and moving slowly. Not unexpected, but I'm wondering if there are any tips or tricks to help them learn more effectively, and get to the wonderful "ah-ha!" moments.

答:
I think the most important thing you can do is show them how to fix their own problems. There are so many threads on this site about interns or new workers or someone of that stature asking for help over every little issue. You also see the other side about young developers who just toil through and waste so much time because they refuse to ask for help.

The best way to help him is to show him resources. Tell him how you solve your problems. Talk about stack overflow, how to search google effectively, printf debugging, and stuff like that. Tell him that when he has an issue, he should basically go down this checklist and try to figure out what's going wrong and see if he can fix it, BUT that he shouldn't spend too much time on something potentially trivial. When he does come for help, make him tell you what all he's tried, what he figured out, and guide him from there.

When I was first starting programming, I learned a ton by trying to fix my errors. That's because oftentimes I'd try to fix "x" when my problem was really "y", but in the process I'd learn about both x and y. In the future, if I saw problems related to x or y, then I'd know where to go back to dig deeper. You pick up a lot just by reading, and by searching for answers, you can pick up what's wrong.

Just to reiterate an earlier point, show him how to use a debugger, or at least how to go through his code. To quote Alan Perlis:

To understand a program you must become both the machine and the program.

A lot of new programmers just stare at code trying to get an epiphany (turns out people try to solve a lot of problems this way), but that's unnecessary with the tools we have at our disposal. Tell him about how you read through a program and "imagine" it working, and help him think through his code. Show him how to either use a debugger, or how to insert print statements to confirm his understanding.

That'll put him way ahead of the curve. The rest will come with his own efforts.

OwnerDisplayName: Nevir


答: When we are introducing people to work on new areas in our software, we are usually doing some pair programming with a programmer, that has deeper knowledge in this particular field. (of course you would have to have the resources for that). This helps people to faster understand existing code.</p>

Title: What are some effective ways of helping someone learn a programming language/framework in a focused way?

Body:
Here's some background:

I have someone who is motivated to help me out on a project that already has a good chunk of code written

The person does not have a CS background, but knows the basics (functions, variables, objects, classes, etc)

The goal isn't to make this person a rockstar developer overnight - they just need to be able to pull their weight on this specific project.

The project is a Rails project, but if there are general responses, I'd like to favor them.

The current approach that is being taken is to give this person a simple feature (that has a similar feature already written). Then nudging them when they get confused, while trying not to give them full chunks of code.

Regardless, they're very confused and frustrated, and moving slowly. Not unexpected, but I'm wondering if there are any tips or tricks to help them learn more effectively, and get to the wonderful "ah-ha!" moments.


答:
When I started programming with Rails, not knowing the language, the framework or too much about web development, I had around two or three weeks on my own to explore all of this to some extend. I used the time mostly to develop a very simple web shop. This gave me the opportunity to get a good overview of the whole framework and experiment with the single elements like routing, models, views, validations, tests, ajax, layouts, partials and so on, without the risk to break anything. After this time I had at least seen each part and new very well, where it would fit into the whole system, what to expect from a Rails project and where to look for certain functionality. Of course I didn't know everything but I knew how to ask smart questions and was able to get a small prototype project successfully to a customer without bothering my new team mates with too many stupid ideas.

In my humble opinion Rails works as a whole. Trying to start working in a single area without knowing the connections won't work and he will lose time. Let him have at least one or two weeks to explore the framework without doing any serious work on an existing project. I was working on my own, I guess if he has some experienced people around him to ask questions and who can point out important concepts, he should be able to get into this fast enough.

Having a few good books available like those by David H. Black won't hurt either.


问:
How easy should a language development framework be to use?

This is part of a series of questions which focuses on a project called the Abstraction Project, which aims to abstract the concepts used in language design in the form of a framework.

Another page associated to it related to structural typing can be viewed here.  The meta-topic associated to an inquiry about the framework and the proper place to post can be found here.

How easy should it be to use a Language Development Framework?

I've written large scale code generation frameworks which also included the ability to send the result to the language-specific compiler. The topic of ease of use comes up from one such framework example: CodeDOM, or the Code Document Object Model.

It is a framework written by Microsoft that describes common code structures, but generally left a lot out (expression coercions) and tended to be a bit abstract in its representation of certain constructs, to downright emitting bad code based upon what you were doing: earlier CodeDOM poorly handled emitting PrivateImplementationType on CodeMemberMethod, when the type used was a generic interface.  CodeDOM was my original reason for writing my first code generator.

One thing I'm trying to do, to simplify the framework, is reduce the amount of work you need to do something, and focusing on actions versus the specific types that make up those actions.

Here's a side by side comparison of how the framework I'm writing works:

```<code>//Truncated...
/* *
 * From a project that generates a lexer, this is the
 * state->state transition character range selection logic.
 * */
var nextChar = nextMethod.Parameters.Add(new TypedName("currentChar", typeof(char).GetTypeReference()));
//...
char start = rangeElement.B.Value.Start;
char end = rangeElement.B.Value.End;
/* *
 * 'start' <= nextChar && nextChar <= 'end'
 * */
currentExpression = start.LessThanOrEqualTo(nextChar).LogicalAnd(nextChar.LessThanOrEqualTo(end));
</code>```

Versus CodeDOM:

```<code>//Truncated...
var nextChar = new CodeVariableReferenceExpression("nextChar");
//...
var start = new CodePrimitiveExpression(rangeElement.B.Value.Start);
var end = new CodePrimitiveExpression(rangeElement.B.Value.End);
currentExpression = new CodeBinaryOperatorExpression(new CodeBinaryOperatorExpression(start, CodeBinaryOperatorType.LessThanOrEqual, nextChar), CodeBinaryOperatorType.BooleanAnd, new CodeBinaryOperatorExpression(nextChar, CodeBinaryOperatorType.LessThanOrEqual, end));
</code>```

The focus of the framework is language enthusiasts, as well as those interested in generating code or applications. Given its focus on compilation, code generation, and language development, should the framework focus on ease of use or raw power?

My primary goal is to increase the availability of such tools, so those interested in the domain don't require a lot of experience in the language theory domain before they can start to work on their own language-centric projects.

Given that I'm the author of the framework, my view of "usability" is biased.  Thus, I must ask another if the focus and goal make sense to others who aren't associated to the project.

答:
This question may have been answered in The Mythical Man Month, the "Conceptual Integrity" section.   If not, it is at least highly relevant to your question.  Even though Brooks describes architecting a whole computing system, the essay applies perfectly well to frameworks and new languages.

I believe a positive correlation exists between rate of adoption of any technology and its conceptual integrity and ease of use.  There should be a case study of recent technologies like languages, frameworks, and OSs, to prove this correlation, but know of none yet.


问:
How to balance code quality vs strong developer personalities
On code reviews at work I have been seeing code & patterns that I consider "clever" though not necessarily adding to the overall quality or maintainability of the code base. I point this out on my feedback and am unconvinced by the counterarguments. I am a bit concerned when this code makes into into the repo and later to production.

I want to maintain a cohesive team, so I dont want to create tension by being too vocal about my reservations. I also want to create a great product for our customers without being too leninent.

Traditionally, who has 'veto' power on what gets checked in and how?

How can code that works, but its too involved/clever be removed without stepping on toes?

答:
In my experience, It's typically very difficult to get code that suffices all requirements out of the code base.

However, next time the code is to be maintained, you can easily argue for it's replacement as a future cost saving measure because the old code was harder to maintain.

As far as veto power, management obviously has that.

Sometimes their are teams or committees that are in charge of code quality, in which case they would have this power as well.

It also would be helpful if you give an example of a 'clever' pattern. Maybe you're just overreacting...

'clever' is almost never a bad thing in my book, but I can agree that there can be a slippery slope between clever and convoluted.


问:
How far can I push refactoring without changing external behavior?
According to Martin Fowler, code refactoring is (emphasis mine):

Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior. Its heart is a series of small behavior preserving transformations. Each transformation (called a 'refactoring') does little, but a sequence of transformations can produce a significant restructuring. Since each refactoring is small, it's less likely to go wrong. The system is also kept fully working after each small refactoring, reducing the chances that a system can get seriously broken during the restructuring.

What is "external behaviour" in this context? For example, if I apply move method refactoring and move some method to other class, it looks like I change external behaviour, doesn't it?

So, I'm interested in figuring out at what point does a change stop being a refactor and becomes something more. The term "refactoring" may be misused for larger changes: is there a different word for it?

Update. A lot of interesting answers about interface, but wouldn't move method refactoring change the interface?

答:
"External" in this context means "observable to users". Users may be humans in case of an application, or other programs in case of a public API.

So if you move method M from class A to class B, and both classes are deep inside an application, and no user can observe any change in the behaviour of the app due to the change, then you can rightly call it refactoring.

If, OTOH, some other higher level subsystem/component changes its behaviour or breaks due to the change, that is indeed (usually) observable to users (or at least to sysadmins checking logs). Or if your classes were part of a public API, there may be 3rd party code out there which depends on M being part of class A, not B. So neither of these cases are refactoring in the strict sense.

there is a tendency to call any code rework as refactoring which is, I guess, incorrect.

Indeed, it is a sad but expected consequence of refactoring becoming fashionable. Developers have been doing code rework in an ad hoc manner for ages, and it is certainly easier to learn a new buzzword than to analyse and change ingrained habits.

So what is the right word for reworks which change external behaviour?

I would call it redesign.

Update

A lot of interesting answers about interface, but wouldn't move method refactoring change the interface?

Of what? The specific classes, yes. But are these classes directly visible to the outside world in any way? If not - because they are inside your program, and not part of the external interface (API / GUI) of the program - no change made there is observable by external parties (unless the change breaks something, of course).

I feel that there is a deeper question beyond this: does a specific class exist as an independent entity by itself? In most cases, the answer is no: the class only exists as part of a larger component, an ecosystem of classes and objects, without which it can't be instantiated and/or is unusable. This ecosystem does not only include its (direct/indirect) dependencies, but also other classes / objects which depend on it. This is because without these higher level classes, the responsibility associated with our class may be meaningless/useless to the users of the system.

E.g. in our project which deals with car rentals, there is a Charge class. This class has no use to the users of the system by itself, because rental station agents and customers can't do much with an individual charge: they deal with rental agreement contracts as a whole (which include a bunch of different kinds of charges). The users are mostly interested in the sum total of these charges, that they are to pay in the end; the agent is interested in the different contract options, the length of the rental, the vehicle group, insurance package, extra items etc. etc. selected, which (via sophisticated business rules) govern what charges are present and how the final payment is calculated out of these. And country representatives / business analysts care about the specific business rules, their synergy and effects (on the income of the company, etc.). A single charge by itself has no meaning without the bigger picture.

Recently I refactored this class, renaming most of its fields and methods (to follow the standard Java naming convention, which was totally neglected by our predecessors). I also plan further refactorings to replace String and char fields with more appropriate enum and boolean types. All this will certainly change the interface of the class, but (if I do my job correctly) none of it will get visible to the users of our app. None of them cares about how individual charges are represented, even though they surely know the concept of charge. I could have selected as example a hundred other classes not representing any domain concept, so being even conceptually invisible to the end users, but I thought it is more interesting to pick an example where there is at least some visibility at the concept level. This shows nicely that class interfaces are only representations of domain concepts (at best), not the real thing*. The representation can be changed without affecting the concept. And users only have and understand the concept; it is our task to do the mapping between concept and representation.

*And one can easily add that the domain model, which our class represents, is itself only an approximate representation of some "real thing"...


答:
The boundary would be the line that tells between who develop, maintain, support the project and those who are its users other than the supporters, maintainers, developers.  So, to the external world, the behaviour looks the same whereas the internal structures behind the behaviour have changed.

So it should be OK to move functions between classes as long as they are not the ones that the users see.

As long as the code rework does not change external behaviours, add new functions or remove existing functions, I guess it is OK to call the rework a refactoring.

Title: How far can I push refactoring without changing external behavior?

Body:
According to Martin Fowler, code refactoring is (emphasis mine):

Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior. Its heart is a series of small behavior preserving transformations. Each transformation (called a 'refactoring') does little, but a sequence of transformations can produce a significant restructuring. Since each refactoring is small, it's less likely to go wrong. The system is also kept fully working after each small refactoring, reducing the chances that a system can get seriously broken during the restructuring.

What is "external behaviour" in this context? For example, if I apply move method refactoring and move some method to other class, it looks like I change external behaviour, doesn't it?

So, I'm interested in figuring out at what point does a change stop being a refactor and becomes something more. The term "refactoring" may be misused for larger changes: is there a different word for it?

Update. A lot of interesting answers about interface, but wouldn't move method refactoring change the interface?


答:
Your organization should have a coding guidelines/standards document that's periodically updated with input from the development team. That document can spell out specifics, like: how to name variables, how to format code, and so on. The document should also explain the values that the organization expects programmers to adopt in writing code, including the relative importance of things like readability, maintainability, correctness, efficiency, and adherence to standards.

Code reviews should be conducted using that coding standards document. If the coding standards say that programmers should prefer readability to brevity when the two are in conflict, then you'll have some support in arguing against the "clever" code. If the standards don't say that and you think they should, then you can argue about it in the abstract at the coding standards meeting rather than trying to figure it out when somebody's ego is on the line.

Ultimately, it does sometimes come down to a judgement call, and in those cases the final word should go to the person that's ultimately responsible for the code and/or product. That's usually someone like a senior developer, technical lead, project manager, or director of engineering. If you're the guy in charge and you feel that certain code isn't sufficiently maintainable, you shouldn't be afraid to say so. You can be diplomatic about that:

Sam, I'm impressed with your ingenuity here, but I'm concerned that it
  may be just a little too clever. I'll need you to be working on new
  development a year from now rather than maintaining this, and I'm
  concerned that whoever does have to maintain it may not fully
  comprehend its awesomeness. I know you hate to do it, but I'd
  appreciate it if you'd go back to the straightforward implementation
  that we discussed.

On the other hand, if you're not the guy in charge, then the best you can do is explain your position clearly and try to convince the rest of the team. If you're not getting support from the manager, then accept that it's not your call and move on.

Title: How to balance code quality vs strong developer personalities

Body:
On code reviews at work I have been seeing code & patterns that I consider "clever" though not necessarily adding to the overall quality or maintainability of the code base. I point this out on my feedback and am unconvinced by the counterarguments. I am a bit concerned when this code makes into into the repo and later to production.

I want to maintain a cohesive team, so I dont want to create tension by being too vocal about my reservations. I also want to create a great product for our customers without being too leninent.

Traditionally, who has 'veto' power on what gets checked in and how?

How can code that works, but its too involved/clever be removed without stepping on toes?


问:
How to enter flow experience for SW development?
What are your strategies to improve the flow experience when doing work?</p>

答:
It's a bit like creativity. You can't force it, you can only prepare conditions favorable for it to appear. Some of the most important requirements:

Distraction-free environment (you'll need hours of uninterrupted concentration).

Clear goal.

Genuine, intrinsic interest in that goal.

Clear mind; not too much "should do this, should do that" issues nagging in the  background.

So, before starting to actually work to problem, be sure to define the goal clearly, complete or at least write down other to do -items so that they don't disturb your mind, and go somewhere where you can concentrate. If you're interested in what you're doing, you now have a good chance of getting into flow.


问:
What is the biggest obstacle ASP.NET MVC ever had for you? Why and how it can be fixed?
What aspects of ASP.NET MVC can be considered bad practices of Microsoft or problematic? In ASP.NET web forms, thing like ViewState, Automatically generated Id and names, single form usage and pattern like this are many times problematic. As no claim should be reason-less, so, it's better to mention why that aspect is an obstacle. Also finding any problem intrinsically means that we like to solve it. Therefore, Please also recommend ways to solve that issue. </p>

答:
Html.DropDownList Because you can't override it's value if the name matches a property in the model.

Multiple forms on the same page with separate validation.


答:
My advice is to play the idiot, when its time to do code reviews feel free to say you don't have a clue how it works (if your ego needs a massage, you can say you didn't have time to figure it out) and get the developer to explain it. When he's finished you can suggest he writes all that down as a comment for future maintenance, with the implied hint that its too convoluted to be considered 'good' code.

If its good code that's just a bit too complicated, most people will get the hint, without anything having been said about code quality or developer expertise.

PS. Obviously most of this code will be subjective anyway, so one person's impossibly-clever code might be a reasonable and maybe even industry-standard algorithm to another dev, so you can't accuse anyone directly of writing bad code (except when its fricking obvious like the contractor who copied a byte array into a stl list, passed it into an encryption routine and then converted it back into a byte array!)


问:
How do you keep your unit tests working when refactoring?
In another question, it was revealed that one of the pains with TDD is keeping the testing suite in sync with the codebase during and after refactoring.

Now, I'm a big fan of refactoring. I'm not going to give it up to do TDD. But I've also experienced the problems of tests written in such a way that minor refactoring leads to lots of test failures.

How do you avoid breaking tests when refactoring?

Do you write the tests 'better'? If so, what should you look for?

Do you avoid certain types of refactoring?

Are there test-refactoring tools?

Edit: I wrote a new question that asked what I meant to ask (but kept this one as an interesting variant).

答:
I assume your unit tests are of a granularity that I would call "stupid" :) ie, they test the absolute minutiae of each class and function. Step away from the code-generator tools and write tests that apply to a bigger surface, then you can refactor the internals as much as you want, knowing that the interfaces to your applications have not changed, and your tests still work.

If you want to have unit tests that test each and every method, then expect to have to refactor them at the same time.


答:
I love this quote:

"Debugging is twice as hard as writing the code in the first place.
  Therefore, if you write the code as cleverly as possible, you are, by
  definition, not smart enough to debug it." – Brian W. Kernighan

On one side, this makes you weary of too clever code, since it will be hard to debug and extend later.

On the other hand, clever code that does work is a great way to learn.  Probably for the whole team.  What about encouraging the author to give a small informal talk about the code to their colleagues?  Just be sure that it really works as intended and that it does makes sense in the project as a whole.  You don't want to turn it into a pointless competition!

If you don't think it adds value, then place the counterchallenge asking: "How can you refactor this part (you have tests in place, right?) so that it's more readable?"  Be sure to point that it's harder to make clever, readable code that to make impenetrable nuggets.


答:
Like many other practices I think the answer is it depends.

If it is a defect then it definitely needs to be fixed.

If the code works you have to balance the value of insisting the the code be changed vs. the future cost of the clever code.  While there are rules of thumb regarding the ratio between development work and maintenance work they will vary a lot from project to project.  Be reasonable.

Consider why are you unable to convince your team mate that the code needs to be simplified?

You don't always have to get everything perfect.  That would mean code reviews in an infinite loop and nothing checked in because nothing (except my code, haha) is perfect.

My personal preferrence is for the author of the code to have the final say.  Obviously if they are continously doing a very poor job then some other action has to be taken but as you say the negative value of forcing the developer to change the code may be higher than the gain made by fixing it if this is a very rare situation.


问:
What constitutes proper use of threads in programming?
I am tired of hearing people recommend that you should use only one thread per processor, while many programs use up to 100 per process!
take for example some common programs

```<code>vb.net ide uses about 25 thread when not debugging
System uses about 100
chrome uses about 19
Avira uses more than about 50
</code>```

Any time I post a thread related question, I am reminded almost every time that I should not use more that one thread per processor, and all the programs I mention above are ruining on my system with a single processor.

答:
You should use one thread for:

Each processor you need to keep busy.

Each I/O you can usefully pend concurrently that you cannot perform in a non-blocking way. (For example, reads from a local disk.)

Each task that requires a dedicated thread, for example calling into a library that has no non-blocking interface or where non-blocking interfaces aren't appropriate. This includes tasks like monitoring the system clock, firing timers, and so on.

A few extra to protect against unexpected blocking such as page faults.

A few extra to protect against expected blocking that's not worth optimizing out, for example in non-critical code. (For example, if you might very rarely need to do a DNS request, it's probably not worth the effort to do DNS requests asynchronously. Just create a few extra threads and make your life easier.)

If you follow the "one thread per processor" rule, then all your code is performance critical. Any code that blocks for some reason means your process cannot use that processor. That makes programming much harder for no good reason.


答:
With all due respect, we must remember that the users of a class are not the end-users of the applications that are built with the class, but rather the classes which are implemented by utilizing - either calling or inheriting from - the class being refactored.

When you say that "external behavior should not change" you mean that as far as the users are concerned, the class behaves exactly as it it did before. It may be that the original (un-refactored) implementation was a single class, and the new (refactored) implementation has one or more super-classes upon which the class is built, but the users never see the inside (the implementation) they only see the interface.

So if a class has a method called "doSomethingAmazing" it doesn't matter to the user if that is implemented by the class they are referring to, or by a superclass upon which that class is built. All that matters to the user is that the new (refactored) "doSomethingAmazing" has the same result as the old (unrefactored) "doSomethingAmazing.

However, what is called refactoring in many cases isn't true refactoring, but perhaps a reimplmentation that is done to make the code easier to modify to add some new feature. So in this later case of (pseudo)-refactoring, the new (refactored) code actually does something different, or perhaps something more than the old.


问:
What is an effective way to familiarize yourself with a new application in a new language (and still look productive at a new job)?
I started a new job working on an application I'm vaguely familiar with, and it's in Perl! I come from a PHP and Java background, so while I understand the basics, there are lot of nuances in Perl that make it troublesome.

I'm supposed to be a UI developer, but the smallness of the office requires me to learn and do a lot more than just javascript. So that was slightly unexpected in some aspects and I'm just thinking about what approach to take with this

So far I've been sifting through the code to understand what each part does, printed out copies of code and try to lookup APIs I'm not familiar with, and so I dunno how effective this process is -- I feel like it's going to take some time -- and I don't want my new employers to feel like I'm not being productive.

Anyone have some ideas or approaches for this kind of situation?

I read some of the questions about learning new languages, but I'm curious to see if anyone's had experience with this with Perl.

答:
Ask as many questions as possible (within reason)

As long as you didn't lie on your resume saying you knew Perl or something.

Why should asking be a problem? It shows initiative and a willingness to learn new tech...

Never, ever, ever be afraid to ask questions.


答:
Chances are that your new employers have hired you for you; the potential they see in you and what you've achieved in the past. If they wanted a Perl guru, they would've specified that in the job description and you wouldn't have been hired. I'm sure they're understanding of the fact that it takes new members time to accustom themselves with the innards of the company (including learning new languages and practices).

While you may not be crunching out any new code for the development team, it would be a great idea to note down what you have spent your time doing. Write down what you have familiarised yourself with, so you show to youself that you're not wasting time and that you can show to anyone else what you've been doing.

Spend this time learning about your new teammates and discern who you can turn to for advice and teaching.

Title: What is an effective way to familiarize yourself with a new application in a new language (and still look productive at a new job)?

Body:
I started a new job working on an application I'm vaguely familiar with, and it's in Perl! I come from a PHP and Java background, so while I understand the basics, there are lot of nuances in Perl that make it troublesome.

I'm supposed to be a UI developer, but the smallness of the office requires me to learn and do a lot more than just javascript. So that was slightly unexpected in some aspects and I'm just thinking about what approach to take with this

So far I've been sifting through the code to understand what each part does, printed out copies of code and try to lookup APIs I'm not familiar with, and so I dunno how effective this process is -- I feel like it's going to take some time -- and I don't want my new employers to feel like I'm not being productive.

Anyone have some ideas or approaches for this kind of situation?

I read some of the questions about learning new languages, but I'm curious to see if anyone's had experience with this with Perl.


答: I'm not one who usually likes learning programming languages from books, but Perl is kind of an eccentric language where it really helps to understand the design philosophies behind it.  I highly recommend the Camel Book in this case.</p>


答:
Dealing with programmers who don't know MVC although they think that they do, and the problem that even a good MVC programmer can have keeping current as Microsoft gets up to speed with MVC in ASP.NET.

Programmers who can draw a diagram of Model-View-Controller adequate for a job interview question and give a memorized explanation of each part, but lack actual experience with MVC. This is particularly a problem in ASP.NET MVC, because it is such a new part of ASP.NET, so someone with ASP.NET experience may convince themself they have MVC experience. No, they have ASP.NET experience and can draw an MVC diagram.

Add to this, ASP.NET MVC 1, MVC 2, MVC 3 (and... MVC 4) come rolling out at the hapless programmer, who is too busy coding in MVC n to learn version n+1. (The MVC 3 books are finally coming out). Also, those great NuGet packages that you can just pop into your MVC project and perhaps solve a big problem, but you need to know and learn those NuGet packages, too.

Don't let any of this keep you from using ASP.NET MVC.

Title: What is the biggest obstacle ASP.NET MVC ever had for you? Why and how it can be fixed?

Body: What aspects of ASP.NET MVC can be considered bad practices of Microsoft or problematic? In ASP.NET web forms, thing like ViewState, Automatically generated Id and names, single form usage and pattern like this are many times problematic. As no claim should be reason-less, so, it's better to mention why that aspect is an obstacle. Also finding any problem intrinsically means that we like to solve it. Therefore, Please also recommend ways to solve that issue. </p>


问:
Should 'mathematical' functions follow mathematical notation?
I suppose this question is going to be immediately flagged as subjective, but which do you think is better:

```<code>double volume(double pressure, double n_moles, double temperature) {
  return n_moles * BOLTZMANN_CONSTANT * temperature / pressure;
}
</code>```

or

```<code>double volume(double P, double n, double T) {
  return n*R*T/P;
}
</code>```

In other words, should functions that implement some equation follow that equation's notation, or should they use more verbose names?

答:
Depends on who is reading it. If you can guarantee that for all eternity, the next programmer who reads your code is also familiar with thermodynamics, then yes, go for the truncated version.

My personal style is to use such variables (whose abbreviations are commonly known in the field), but include their description in comments.

```<code>/* P : Pressure
   V : Volume
   n : Number of moles
   R : Boltzmann constant
   T : Temperature (in K)
*/
double compute_V(double P, double n, double T) {
  return n*R*T/P;
}
</code>```

OwnerDisplayName: lindelof

Body:
Depends on who is reading it. If you can guarantee that for all eternity, the next programmer who reads your code is also familiar with thermodynamics, then yes, go for the truncated version.

My personal style is to use such variables (whose abbreviations are commonly known in the field), but include their description in comments.

/* P : Pressure
   V : Volume
   n : Number of moles
   R : Boltzmann constant
   T : Temperature (in K)
*/
double compute_V(double P, double n, double T) {
  return n*R*T/P;
}

OwnerDisplayName: Jacob


答:
I prefer this:

```<code>/* This function calculates volume using the following formula:
 *
 *     n * R * T
 * v = ---------
 *         P
 */
double volume(double pressure, double n_moles, double temperature) {
    return n_moles * BOLTZMANN_CONSTANT * temperature / pressure;
}
</code>```

In other words, explain the meaning of the code in the comment in English (and mathematics; it's comments, you can expand on it as much as necessary), but use descriptive variable names so that anyone reading the only code still is able to comprehend it easily - especially with larger functions. Another reason why I'd use real words as variable names is that the interface is much clearer if you need to copy the function declaration to a header file.

Title: Should 'mathematical' functions follow mathematical notation?

Body:
I suppose this question is going to be immediately flagged as subjective, but which do you think is better:

```<code>double volume(double pressure, double n_moles, double temperature) {
  return n_moles * BOLTZMANN_CONSTANT * temperature / pressure;
}
</code>```

or

```<code>double volume(double P, double n, double T) {
  return n*R*T/P;
}
</code>```

In other words, should functions that implement some equation follow that equation's notation, or should they use more verbose names?

Body:
I prefer this:

/* This function calculates volume using the following formula:
 *
 *     n * R * T
 * v = ---------
 *         P
 */
double volume(double pressure, double n_moles, double temperature) {
    return n_moles * BOLTZMANN_CONSTANT * temperature / pressure;
}

In other words, explain the meaning of the code in the comment in English (and mathematics; it's comments, you can expand on it as much as necessary), but use descriptive variable names so that anyone reading the only code still is able to comprehend it easily - especially with larger functions. Another reason why I'd use real words as variable names is that the interface is much clearer if you need to copy the function declaration to a header file.

OwnerDisplayName: Antti


答: Depends on how "far away" from the business layer the code is... The furthur back in the stack the code is, the more targeted it is towards the abstract mathematical function is implements, the more I would try to emulate the generally accepted matehmatical notation and naming conventions.. The closer to the front end or to the business layer, the more I would conform to the conventions established in the problem domain.</p>

OwnerDisplayName: Charles Bretana


答:
Toss the coin.

Do you also sometimes spend more time thinking about how to name a variable than you spend on the coding itself?

OwnerDisplayName: Tomas Telensky


答:
IMHO it's always better to use the established notation of the problem domain you're working in if the function is very domain-specific.  Someone who doesn't understand the problem domain has no chance of successfully maintaining your code anyhow, and for someone who is familiar with the domain, the long names will just be noise, as well as more typing for you.

OTHO, I will say that I wish conventional mathematical notation were more verbose and descriptive at times, but regardless I think mathematical code should stick to mathematical convention.

Edit:  This answer applies only if there is a very strong convention on notation when writing the formula mathematically.  If there isn't one, and you'd have to explain what the variables represent in a comment even assuming that the reader is familiar with the domain, then it's best to err on the side of a more descriptive convention.

OwnerDisplayName: dsimcha


答: Pure opinion, but always use the words over the single-letter symbols. If you use words, everybody will understand; if you use symbols, only subject-matter experts are guaranteed to follow. Even then, some people use different symbols for the same physical quantities. You have nothing to lose by using the longer names.</p>


答:
Just throwing it out there, you have another option:

```<code>Volume ComputeVolume(Pressure p, Moles m, Temperature t) { ... }
</code>```

This is somewhat similar to what F# does with units of measure, and has the benefit of avoiding issues like replacing inadvertently a pressure by a temperature. It's difficult to eyeball what arguments should go where when the signature is like (double, double, double)

Body:
Just throwing it out there, you have another option:

Volume ComputeVolume(Pressure p, Moles m, Temperature t) { ... }

This is somewhat similar to what F# does with units of measure, and has the benefit of avoiding issues like replacing inadvertently a pressure by a temperature. It's difficult to eyeball what arguments should go where when the signature is like (double, double, double)

OwnerDisplayName: Mathias


答:
Your concern should be clarity then correctness (incorrect but clear code is easily corrected) therefore your function should be written for maintainability by a generic coder as far as possible. The function header comments should explain the formula and its usage and describe in/out parameters. Thereafter how the function body is layed-out shouldn't matter too much as long as it's consistent with the header comments.

(I know this is not a discussion but - my personal preference would be to give explicit names to the varaibles although in this case a one-liner could suffice as it's a 'pure' function; a call with the same parameters would yield the same result always so there should be no state-related complexity requiring explanation)

Re other languages supporting dimensional analysis, this can be implemented e.g. in C++ with templates, the Boost Units library uses this approach I believe.

OwnerDisplayName: daz azemoon


答:
The correct format for a programming equation is one that you still understand after not having seen it for six months.

If you come back to:

```<code>n*R*T/P;
</code>```

And you recognize what's going on, then it's probably fine. Typically for advanced formulas I wont remember what each part was unless I'm actively using it. For me:

```<code>n_moles * BOLTZMANN_CONSTANT * temperature / pressure;
</code>```

is a much better equation format specifically because I can easily understand each part, even if I don't necessarily know why the equation is written as it is.

Body:
The correct format for a programming equation is one that you still understand after not having seen it for six months.

If you come back to:

n*R*T/P;

And you recognize what's going on, then it's probably fine. Typically for advanced formulas I wont remember what each part was unless I'm actively using it. For me:

n_moles * BOLTZMANN_CONSTANT * temperature / pressure;

is a much better equation format specifically because I can easily understand each part, even if I don't necessarily know why the equation is written as it is.


答: I like to think of it this way - Mathematicians got it wrong with short variables and physicists followed suit. Why repeat their mistake? We now know that longer names are more descriptive and produce less confusion, so stick with improvement. On a lighter note, I sometimes try to sneak it longer variables into my maths, at which everyone is appalled.


问:
Are static classes with static methods considered SOLID?
SOLID includes the Liskov substitution princicple
which has the notion that “objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program”.

Since static classes with static methods (a bit like the Math class) does not have instances at all, is my system considered SOLID if I have static classes with static methods?

答:
LSP applies to passing an instance of a class into a method, having the method do some stuff with that instance, and often produce some sort of result. This doesn't matter for static classes since in C# you cannot create an instance of a static class.

Even more importantly, static classes are sealed and therefore cannot be inherited. This makes your question moot far as C# goes.

You could say that static classes are always LSP-compliant since you cannot ever produce a subclass that would violate that principle. You could also say that static classes are never LSP-compliant for the same reason.

In Java, static classes are slightly different. You cannot mark a top-level class as "static", so if you want to create a utility class similar to C#'s static classes you have to declare it as final and hide its constructor. Once you do that, though, they behave similarly to C# - you cannot instantiate them or subclass them. You can declare an inner class as static, but that does not mean the same thing as it does in C#: it simply denotes a nested top-level class.

VB.NET behaves exactly the same way as C# in this case, far as I know.

You didn't mention whether you're interested in the other principles, but I'm going to include them anyway for completeness.

Single responsibility principle: a static class easily follow this principle.

Open/closed principle: since static classes are sealed, they cannot ever follow this principle.

Liskov substitution principle: as above.

Interface segregation principle: doesn't apply to a single class, but splitting one large static class into smaller, more specialized ones could be a step towards following this principle.

Dependency inversion principle: static classes cannot implement interfaces, so any class using it will always depend on whatever implementation exists at the time. Static classes therefore violate this principle.

Since static classes do not satisfy all 5 criteria, they are not SOLID.


答:
I follow a two-step process when moving to a new language or other technology:

Curl up with a good book for a few hours.

Start working.

It has been a while, but this is how I started writing Perl.  I read the Camel book, and then started using Perl instead of writing shell scripts.  At first I was pretty slow, and was constantly referring to the documentation.  Gradually I got faster.

Since the majority of developers skip step 1, and just cut-and-paste examples, reading one good book will put you ahead of about 90% of your competition.


答: External simply means interface in its true lingual meaning. Consider a cow for this example. As long as you feed some vegetables and get milk as the return value, you don't care how its internal organs work. Now if God change cows internal organs, so that its blood become blue in color, as long as the entry point and exit point (mouth and milk) don't change, it can be considered refactoring.


答:
I would not classify such a class as object-orientated and therefore I would say that it cannot (and should not try to) meet the principals of object-orientated design.

These classes are merely a workaround to the inability to provide code outside of a class in languages like Java and C#. If they could be, they should be defined as standalone functions since they do not gain any benefits from object-orientation.

Title: Are static classes with static methods considered SOLID?

Body:
SOLID includes the Liskov substitution princicple
which has the notion that “objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program”.

Since static classes with static methods (a bit like the Math class) does not have instances at all, is my system considered SOLID if I have static classes with static methods?


问:
What exactly undefined means in JavaScript? Why it's there? What usages it has? How it could be useful?
In JavaScript, we have something called undefined. I said something, because I really don't know if it's a base class, or a built-in variable, or a keyword, or anything else. I just know that it's there.

To see it in action, you can simply write:

```<code>undefined;
typeof undefined;
</code>```

Can anyone please explain to me why this thing has been inserted into JavaScript? We have null value in this language, thus it shouldn't be something like null. In other languages, when we don't know the value of a property or variable, we simply set it to null. Here we can do the same thing.

How we can use this thing in JavaScript?

答:
There are two things you should understand about undefined:

the type undefined that can have only one value

the variable undefined

To explain:

There are so many values of type number (10, 10.01, 1e1). But there can be only one value of type undefined, and that value is stored in the variable undefined.

That value has no literal representation either. For example, number values 1, 100, 1e-1 are all literals of type number, but the value stored in the variable undefined has no literal form.

undefined is a variable, just a normal variable, that JavaScript declares and assigns it the value of type undefined in the global scope. So you can do all the following...

typeof undefined;                       // "undefined"

undefined = 100;
typeof undefined;                       // "number"

undefined = void 0;
typeof undefined;                       // "undefined"

window.undefined === undefined;         // true
window.undefined === void 0;            // true
```

if you don't want to use the variable undefined, you can generate the value of type undefined by the expression void 0 -- whose sole purpose is to return a value of type undefined.

...can anyone please explain to me why this thing has been inserted into JavaScript...

JavaScript has had a history of bad design - not because of the people who designed it but because no one could foresee that this little scripting capability they were adding to Netscape would one day underpin the business of billion dollar companies.

...we have null value...

Although null can do things undefined does, it is more or less related to objects rather than scalars. Indeed, JavaScript considers null itself an object -- typeof null returns "object".

Body:
There are two things you should understand about undefined:

the type undefined that can have only one value

the variable undefined

To explain:

There are so many values of type number (10, 10.01, 1e1). But there can be only one value of type undefined, and that value is stored in the variable undefined.

That value has no literal representation either. For example, number values 1, 100, 1e-1 are all literals of type number, but the value stored in the variable undefined has no literal form.

undefined is a variable, just a normal variable, that JavaScript declares and assigns it the value of type undefined in the global scope. So you can do all the following...

typeof undefined;                       // "undefined"

undefined = 100;
typeof undefined;                       // "number"

undefined = void 0;
typeof undefined;                       // "undefined"

window.undefined === undefined;         // true
window.undefined === void 0;            // true

if you don't want to use the variable undefined, you can generate the value of type undefined by the expression void 0 -- whose sole purpose is to return a value of type undefined.

...can anyone please explain to me why this thing has been inserted into JavaScript...

JavaScript has had a history of bad design - not because of the people who designed it but because no one could foresee that this little scripting capability they were adding to Netscape would one day underpin the business of billion dollar companies.

...we have null value...

Although null can do things undefined does, it is more or less related to objects rather than scalars. Indeed, JavaScript considers null itself an object -- typeof null returns "object".

ContentLicense: CC BY-SA 4.0


问:
Is SQL important if I know ORM frameworks well?
I don't have any serious experience in SQL and I even hate to write SQL instead of LINQ. I am happy enough with ORMs.

From the employers and sector view point, is it important to know SQL? Do I have to master on it? Are companies that prefer pure SQL over ORM frameworks a "dinosaur" in the programming world?

答:
I find myself manually forcing queries in ORM frameworks more often than not. And while most have their own query language, those are all inspired by sql, the code gets turned into sql, and you need to understand what's going wrong by reading that sql when (not if, when) things go wrong or perform poorly.

So even if you're not writing sql directly, understanding it beyond a basic level (though you probably won't need to learn things about writing stored procedures, triggers, etc. if all you're going to do is access databases) you should know the language enough to understand the generated code and tweak it as needed.


问:
Which framework should a ruby beginner start with: rails or sinatra?
What is the best framework for start: rails or sinatra? I heard that sinatra is more flexible but rails has a lot of documentation and tutorials. What's your choice?</p>

答:
First off this may or may not apply to you (I'm answering for any future readers who ask the same question), but I'd recommend getting a solid grasp of Ruby before you start learning a framework.

That being said, here's my thoughts on both frameworks for a beginner.

Sinatra is the easiest to get something working. You can get hello world, and very simple sites going with very little code.

However, once you get past that into moderately complex applications, you'll need to start adding stuff that comes baked into Rails. For a beginner that can be a bit daunting.

I'd check out Michael Hartl's Rails tutorial http://ruby.railstutorial.org/ for more hands on Rails information.


答:
Well, undefined is a sentinel value obtained by evaluating something that is not defined as opposed to null, which is the value exactly defined to represent nothing.

```<code>var o = { };
> undefined
o
> Object {}
o.foo
> undefined
function f() {}
> undefined
function r() { return null; }
> undefined
f()
> undefined
r()
> null
</code>```

So for example, the return value of a function, that doesn't define a return value is undefined. The value of a property not defined on an object is undefined. The return value of a statement, that is not an expression is undefined (although you will not see this occur other than in the console).

Please note, that you can create a function, that explicitly returns undefined and you can explicitly define a property with the value of undefined on an object, because in the end it is a valid value. You would do so in order to explicitly communicate, that something is not defined.

You could think of the relationship of undefined and null as that between NaN and 0.

Title: What exactly undefined means in JavaScript? Why it's there? What usages it has? How it could be useful?

Body:
In JavaScript, we have something called undefined. I said something, because I really don't know if it's a base class, or a built-in variable, or a keyword, or anything else. I just know that it's there.

To see it in action, you can simply write:

```<code>undefined;
typeof undefined;
</code>```

Can anyone please explain to me why this thing has been inserted into JavaScript? We have null value in this language, thus it shouldn't be something like null. In other languages, when we don't know the value of a property or variable, we simply set it to null. Here we can do the same thing.

How we can use this thing in JavaScript?

Body:
Well, undefined is a sentinel value obtained by evaluating something that is not defined as opposed to null, which is the value exactly defined to represent nothing.

var o = { };
> undefined
o
> Object {}
o.foo
> undefined
function f() {}
> undefined
function r() { return null; }
> undefined
f()
> undefined
r()
> null

So for example, the return value of a function, that doesn't define a return value is undefined. The value of a property not defined on an object is undefined. The return value of a statement, that is not an expression is undefined (although you will not see this occur other than in the console).

Please note, that you can create a function, that explicitly returns undefined and you can explicitly define a property with the value of undefined on an object, because in the end it is a valid value. You would do so in order to explicitly communicate, that something is not defined.

You could think of the relationship of undefined and null as that between NaN and 0.


问:
Is it practical to use Twitter for service logs?
Recently my boss suggested that we post logs of our service that is hosted on Windows Azure into twitter. His idea is that it's conveniently readable and if Azure cloud fails logs persist. He also said, lots of people do this, I Googled and couldn't find any data about this.

Currenly my concerns are the following. First, perhaps twitter is not very convenient for logging something that can happen very frequently (for example, when our service role starts each instance writes tens of records over several minutes). Second, even if twitter EULA allows such use at this moment it might be changed in future to cut off tweets that occur too often to be human-originated.

Is it practical to post service logs on twitter? What to consider if we implement this?

答:
Personally I don't like being dependent on external services when it isn't absolutely necessary. As you say, if one day the EULA changes, APIs change, anonymous hacks twitter or twitter stops its services entirely, then you'll have to deal with it. It could essentially boil down to higher costs in support and in maintenance one day. Also, it's not easily extensible.

Things which can easily done by yourself shouldn't be outsourced. I'd rather stay in control over the whole process, especially if it's as simple as sending a notification.

I don't say you should reinvent the wheel, but I'm pretty sure it's easy to use something else, be it custom or premade.

Edit: I think the 140 characters limit of a twitter message severely limits it as a reliable carrier. You most likely have to dis- and reassemble messages that are longer than the limit. What if parallel services twitter via the same account and the messages don't arrive in order? You'll have to use a custom format just for twitter. I bet there're more technical limitations like that.


答:
No. Watch the Twitter engineering talks they openly admit that they can accept some failure in some case loss of messages and no-notifications without incident. Also I would be concerned about the account being auto-blocked for what looks like abuse (breaking a certain rate-limit trigger etc..) Not a good idea, </p>

<p>Although what you could do, is after you capture/process the messages in your own logging persistence service, you could filter some out to twitter as secondary (aka not really critical) store.. </p>

Title: Is it practical to use Twitter for service logs?

Body:
Recently my boss suggested that we post logs of our service that is hosted on Windows Azure into twitter. His idea is that it's conveniently readable and if Azure cloud fails logs persist. He also said, lots of people do this, I Googled and couldn't find any data about this.

Currenly my concerns are the following. First, perhaps twitter is not very convenient for logging something that can happen very frequently (for example, when our service role starts each instance writes tens of records over several minutes). Second, even if twitter EULA allows such use at this moment it might be changed in future to cut off tweets that occur too often to be human-originated.

Is it practical to post service logs on twitter? What to consider if we implement this?

Body:
No. Watch the Twitter engineering talks they openly admit that they can accept some failure in some case loss of messages and no-notifications without incident. Also I would be concerned about the account being auto-blocked for what looks like abuse (breaking a certain rate-limit trigger etc..) Not a good idea,

Although what you could do, is after you capture/process the messages in your own logging persistence service, you could filter some out to twitter as secondary (aka not really critical) store..


答: If twitter decide they dont like you using their service to keep your business logs (I wouldent blame them) then they are well within their rights to just shut your user account even if it dosent breach the EULA. Do you really want to keep all your logs on something so volatile? Its hardly expensive to impliment your own logging system.</p>


答:
The apps you mention are rarely running all those tens of threads simultaneously. Most of them just sit there because they're in a thread pool. The app send various tasks to a queue, which is purged by threads in the thread pool.

Why is the pool sized so large then? Because, often threads have to wait for other resources such as disk, network, the user, some other thread, etc. While a thread is waiting, it's appropriate to run other threads to fully utilize the processor. Sizing the pool appropriately is tricky, though. Too few threads, and you'll lose performance because the processor is not fully utilized while waiting for something. Too many threads, and you'll lose performance because of switching between them.

Title: What constitutes proper use of threads in programming?

Body:
I am tired of hearing people recommend that you should use only one thread per processor, while many programs use up to 100 per process!
take for example some common programs

```<code>vb.net ide uses about 25 thread when not debugging
System uses about 100
chrome uses about 19
Avira uses more than about 50
</code>```

Any time I post a thread related question, I am reminded almost every time that I should not use more that one thread per processor, and all the programs I mention above are ruining on my system with a single processor.


答:
I would not be in favour of this either. I don't see why you'd want to do it either. </p>

<p>It might be worth asking him who actually uses twitter for automated logging - I haven't come across it myself and as far as twitter is used as an update for service issues for some suppliers, it is run by a human in the company's service desk for the purposes of information to end user, not as a service logging objective. IF Azure Cloud fails, nothing's going to be logging anything anyway. </p>

Body:
I would not be in favour of this either. I don't see why you'd want to do it either.

It might be worth asking him who actually uses twitter for automated logging - I haven't come across it myself and as far as twitter is used as an update for service issues for some suppliers, it is run by a human in the company's service desk for the purposes of information to end user, not as a service logging objective. IF Azure Cloud fails, nothing's going to be logging anything anyway.


答:
I can't find the original document I was reading (possibly even a response to another question on here?) but I have heard that fixing problems is a good way to start in a new environment.

Find out what minor problems need fixing and fix them to gain some knowledge of how the system (or some small part of it) actually works and make it feel like you are doing something productive.

Sorry if this response is too general and not specific to the language you are asking about.


问:
Company wants thoughts about their site during interview
I have an initial phone interview coming up with a company for a Senior Web Developer position and in the email they asked to prepare by signing up on their site because they'd like to hear my thoughts about it and suggestions for improvement.

I've heard stories before of companies that do this.  They interview 10 people and then if everyone gives advice, then they've got a lot of free consultation.

I believe this is the first time I've ever been asked to do something like this so I wanted to hear other people's thoughts of whether it is free consulting or if I'm just being paranoid.

答:
I think you are being paranoid.

If they are interviewing phone screening 10 people, that's roughly 10 man-hours they are spending in on this phase of the interviewing.  Plus the cost of advertizing the job, reading a bunch of resumes, etc.  And they are getting random ideas from 10 developers, many of whom are probably "also rans" in the employment race.

Then ask yourself:

What is an hour of your time really worth?

How much are your ideas really worth?

Do you want the job or not?

So, they might end up using some ideas from people who they don't employ.  It could be construed as free (albeit slap-dash, second rate, etc) consulting ...

But so what?!  Ideas are easy to have.  Successful execution of the ideas that is the hard (and expensive) part.


答:
If the company looks so dodgy that you expect this to be the type of scam you expect, then why interview for them in the first place?

Otherwise, if they look OK and you have done a little background research - run the risk, the worst case scenario is you waste a couple of hours, which is a risk you run with any interview process.

Title: Company wants thoughts about their site during interview

Body:
I have an initial phone interview coming up with a company for a Senior Web Developer position and in the email they asked to prepare by signing up on their site because they'd like to hear my thoughts about it and suggestions for improvement.

I've heard stories before of companies that do this.  They interview 10 people and then if everyone gives advice, then they've got a lot of free consultation.

I believe this is the first time I've ever been asked to do something like this so I wanted to hear other people's thoughts of whether it is free consulting or if I'm just being paranoid.


答: Yes it is free consulting. Does that matter? I dont think it should. Its a constructive question that helps them get to know how you analyse and improve sites. The fact that it points up a few things they may need to consider improving isnt a bad thing. </p>


答:
There was a similar question recently about submitting code for an interview.

So, what does their web site look like? Does it look like the web site of a company that's so desperate for help that they have to rely on a sham interview process to get good advice, or does it look like they have a pretty strong clue about web design? And are your suggestions for improvement so deeply insightful that you're loathe to give away your secrets?

It's a judgement call. You'll probably be able to tell if they're just fishing for free advice -- they'll be less interested in you and your experience and eager to talk only about their web site. Don't be so concerned about looking for that that you screw up the rest of the interview.


答: It's worth mentioning, since you specified no language, that in C++ you can pass classes around which have only static members and access those members via template, and therefore it is possible to substitute for a class with only static members, and arguably, the methods called form it's "interface".


问:
What is the best practice for reading a large number of custom settings from a text file?
So I have been looking through some code I wrote a few years ago for an economic simulation program. Each simulation has a large number of settings that can be saved to a file and later loaded back into the program to re-run the same/similar simulation. Some of the settings are optional or depend on what is being simulated.

The code to read back the parameters is basically one very large switch statement (with a few nested switch statements). I was wondering if there is a better way to handle this situation.

One line of the settings file might look like this:

```<code>#RA:1,MT:DiscriminatoryPriceKDoubleAuction,OF:Demo Output.csv,QM:100,NT:5000,KP:0.5 //continues...
</code>```

And some of the code that would read that line:

```<code>switch( Character.toUpperCase( s.charAt(0) ) )
{
    case 'R':
         randSeed = Integer.valueOf( s.substring(3).trim() );
         break;
    case 'M':
          marketType = s.substring(3).trim();
          System.err.println("MarketType: " + marketType);
          break;
    case 'O':
          outputFileName = s.substring(3).trim() ;
          break;
    case 'Q':
          quantityOfMarkets = Integer.valueOf( s.substring(3).trim() );
          break;
    case 'N':
          maxTradesPerRound = Integer.valueOf( s.substring(3).trim() );
          break;
    case 'K':
          kParameter = Float.valueOf( s.substring(3).trim() );
          break;
 // continues...
}
</code>```

答:
An excellent library for this sort of work is Apache Commons Configuration

provides a generic configuration interface which enables a Java application to read configuration data from a variety of sources. Commons Configuration provides typed access to single, and multi-valued configuration parameters as demonstrated by the following code:

```<code>    Double double = config.getDouble("number");
    Integer integer = config.getInteger("number");
</code>```

Configuration parameters may be loaded from the following sources:

Properties files

XML documents

Windows INI files

Property list files (plist)

JNDI

JDBC Datasource

System properties

Applet parameters

Servlet parameters

Different configuration sources can be mixed using a ConfigurationFactory and a CompositeConfiguration. Additional sources of configuration parameters can be created by using custom configuration objects. This customization can be achieved by extending AbstractConfiguration or AbstractFileConfiguration.

The full Javadoc API documentation is available here...

Body:
An excellent library for this sort of work is Apache Commons Configuration

provides a generic configuration interface which enables a Java application to read configuration data from a variety of sources. Commons Configuration provides typed access to single, and multi-valued configuration parameters as demonstrated by the following code:

    Double double = config.getDouble("number");
    Integer integer = config.getInteger("number");

Configuration parameters may be loaded from the following sources:

Properties files

XML documents

Windows INI files

Property list files (plist)

JNDI

JDBC Datasource

System properties

Applet parameters

Servlet parameters

Different configuration sources can be mixed using a ConfigurationFactory and a CompositeConfiguration. Additional sources of configuration parameters can be created by using custom configuration objects. This customization can be achieved by extending AbstractConfiguration or AbstractFileConfiguration.

The full Javadoc API documentation is available here...


答: Would you feel better about this company if they didn't ask you to review theirs or any other side, solve a coding problem, or mock up some sort of design? They could use any of this as free advice. Others have mentioned it would be cheaper to find some focus group to review their site. </p>


问:
How to prevent deep indentations?
What steps and measures can I take to prevent deep indentations in my code?</p>

答:
Invert your ifs.

Instead of:

```<code>if (foo != null)
{
    something;
    something;
    if (x)
    {
       something;
    }
    something;
}
else
{
    boohoo;
}
</code>```

I'd write:

```<code>if (foo == null)
{
    boohoo;
    return;
}
something;
something;
if (x)
{
   something;
}
something;
</code>```

The same applies to if-else blocks. If else is shorter / less nested, then revert them.

Check parameters' values in one place

Check all the parameters for illegal values as soon as you enter your method, then proceed knowing that you're safe. It makes for more readable code, but it also saves you piling up conditional blocks later on and spreading these checks all over the subroutine.

Title: How to prevent deep indentations?

Body:
Invert your ifs.

Instead of:

if (foo != null)
{
    something;
    something;
    if (x)
    {
       something;
    }
    something;
}
else
{
    boohoo;
}

I'd write:

if (foo == null)
{
    boohoo;
    return;
}
something;
something;
if (x)
{
   something;
}
something;

The same applies to if-else blocks. If else is shorter / less nested, then revert them.

Check parameters' values in one place

Check all the parameters for illegal values as soon as you enter your method, then proceed knowing that you're safe. It makes for more readable code, but it also saves you piling up conditional blocks later on and spreading these checks all over the subroutine.


答: I would only use it as an email substitute to distribute administrative or trouble-shooting messages. It is not suited for critical transactions.</p>


问:
Multiple inheritance use cases
Java omits multiple inheritance on the grounds that it obviates the design goal of keeping the language simple.

I wonder if Java (with its eco-system) is really "simple". Python is not complex and has multiple inheritance. So without being too subjective, my question is...

What are the typical problem patterns that benefit from a code designed to make heavy use of multiple inheritance

答: One place where multiple inheritance would be useful is a situation where a class implements several interfaces, but you would like to have some default functionality built in to each interface.  This is useful if most of the classes that implement some interface want to do something the same way, but occasionally you need to do something different.  You can have each class with the same implementation, but it makes more sense to push it up into one location.</p>

Title: Multiple inheritance use cases


答: There is a concept called mixins that is used heavily in more dynamic languages.  Multiple inheritance is one way in which mixins can be supported by a language.  Mixins are generally used as a way for a class to accumulate different pieces of functionality.  Without multiple inheritance, you have to use aggregation / delegation to get mixin type behavior with a class, which is a bit more syntax heavy.</p>

Title: Multiple inheritance use cases

Body:
Java omits multiple inheritance on the grounds that it obviates the design goal of keeping the language simple.

I wonder if Java (with its eco-system) is really "simple". Python is not complex and has multiple inheritance. So without being too subjective, my question is...

What are the typical problem patterns that benefit from a code designed to make heavy use of multiple inheritance


答:
At most I can see Twitter or similar services being useful to point notices of high priority incidents, things that in older applications would generate an automatic text message or beeper message to a sysadmin or dba (and probably still should).

Using it as a replacement for your application logs? Idiotic idea.