答:
You can go really any way you want, but these are my thoughts on the subject:

I'd use Java as that allows you to be very high-level, and have user interface libraries (AWT, Swing) at your direct disposal. You can use an object-oriented approach to modeling the chess board and pieces. Other objects could stand in for the move history and scoring. Even the players could be objects, and then you might in the future extend your Player class to provide an artificial intelligent computer player.

You might want to take a look at model-view-controller (MVC) as that is a very nice approach in this case to tie your model objects (domain model) to the user interface (view) and to allow the user to manipulate the model (through the controller).

You may also want to apply test-driven development, which not only ensures that all methods behave the way you expect, but also forces you to write testable, modular code.

Title: Best approach for writing a chess engine?

Body:
I'm a chess enthusiast and a programmer. I recently decided to start making a chess engine using my chess and programming knowledge. So here's my question:

What language (I'm familiar with Java, C++ and Python) and methodology should I adapt while writing a chess engine?

A little guidance would be much appreciated.

Edit:

So I decided to make it in JavaScript. I download this Chess UI from github and now I'm all set! My first step would be to write legal moves for it. So can anybody point me in the right direction? (I'm new to jQuery but have alot of programming experience).

P.S: I'm not trying to make a very efficient engine (I know its way too difficult), I just want to get familiar with the process and learn some new techniques along the way.


问:
Why is Javascript used in MongoDB and CouchDB instead of other languages such as Java, C++?
I asked this question on SO but was suggested to try here. So here it goes:

My understanding of Javascript so far has been that it is a client-side language that capture events and makes a web-page dynamic.

But on reading the comparison between MongoDB and CouchDB I noticed that both are using Javascript. This makes me wonder the reason behind the choice of JavaScript over other conventional languages.

I guess I am trying to understand the role of JavaScript and its advantages over other languages.

Update: I am not asking about the languages / drivers supported by the two databases. The comparison says:

Both CouchDB and MongoDB make use of Javascript. CouchDB uses Javascript extensively including in the building of views.

MongoDB also supports running arbitrary javascript functions server-side and uses javascript for map/reduce operations.

My lack of understanding pertains to why is Javascript being used at all for the backend work. Why is it preferred for building views in CouchDB, or for using map/reduce operations? Why C/C++ or Java were not used? What are the advantages in using Javascript for such back-end work?

答:
This question is a little dated but the reason to use JavaScript vs Java/C++ is that neither Java or C++ easily support code fragments.

Even if JavaScript was never invented, Java nor C++ would of been a good choice for Source Code Fragments that will execute on the server side. They would of picked another language or invented their own. Back in the day products used to create their own language, define their own production rules, AST, interpreter etc. that specialized in their domain.

But with JavaScript it is extremely easy to create a Domain Specific Language (DSL) for your product and embed the engine without having to worry about creating all the other non-domain related infrastructure.

ContentLicense: CC BY-SA 3.0


答:
You can do less with more - There are a couple schools on this. The verbosity school wants everything spelled out in super-fine detail that any idiot can understand. JS is a member of the opposite school where you can layer complexity such that it's easier to get the big picture before understanding how the finer details operate. It is much easier to write to an interface in JS than in most languages, IMO.

First class functions, closures, prototypal inheritance - It's a really, really flexible combo. We can imitate classes if we want. But that's seen as a somewhat pointless endeavor by those who understand JS really well. Compositing suits JS much better than chained inheritance.

Blocking is useful at a higher level. Yes, you heard me. It helps you keep the focus on the JS as messenger rather than the workhorse and processes pretty much queue themselves while allowing for interruptions from asynchronous behavior between function calls.

I would say the learning curve is actually a little bit steep for writing powerful JS but once you're there, it's a hoot. It's not at all hard to implement pre-baked stuff in JS at the lower skill level, however.

Title: Why is Javascript used in MongoDB and CouchDB instead of other languages such as Java, C++?

Body:
I asked this question on SO but was suggested to try here. So here it goes:

My understanding of Javascript so far has been that it is a client-side language that capture events and makes a web-page dynamic.

But on reading the comparison between MongoDB and CouchDB I noticed that both are using Javascript. This makes me wonder the reason behind the choice of JavaScript over other conventional languages.

I guess I am trying to understand the role of JavaScript and its advantages over other languages.

Update: I am not asking about the languages / drivers supported by the two databases. The comparison says:

Both CouchDB and MongoDB make use of Javascript. CouchDB uses Javascript extensively including in the building of views.

MongoDB also supports running arbitrary javascript functions server-side and uses javascript for map/reduce operations.

My lack of understanding pertains to why is Javascript being used at all for the backend work. Why is it preferred for building views in CouchDB, or for using map/reduce operations? Why C/C++ or Java were not used? What are the advantages in using Javascript for such back-end work?


问:
Best approach for writing a chess engine?
I'm a chess enthusiast and a programmer. I recently decided to start making a chess engine using my chess and programming knowledge. So here's my question:

What language (I'm familiar with Java, C++ and Python) and methodology should I adapt while writing a chess engine?

A little guidance would be much appreciated.

Edit:

So I decided to make it in JavaScript. I download this Chess UI from github and now I'm all set! My first step would be to write legal moves for it. So can anybody point me in the right direction? (I'm new to jQuery but have alot of programming experience).

P.S: I'm not trying to make a very efficient engine (I know its way too difficult), I just want to get familiar with the process and learn some new techniques along the way.

答:
If you are familiar with the rules of chess, a good starting point about basic techniques is http://www.frayn.net/beowulf/theory.html
An extensive collection of Materials and links you can find here:
http://chessprogramming.wikispaces.com/
And third: Learn from others code. Have a look at the sources of Crafty. It's the leading open source engine.
Very important wil be to think about Test cases, to see if you make improvements: Start for example with some easy simple end-game positions with 3 or 4 figures.</p>


问:
Converting data-structure in Perl
A function produces this hash of arrays:

```<code>'KEYNAME1' => ARRAY(0x1edeeb0)
   0  'val11'
   1  'val12'
   2  'val13'
'KEYNAME2' => ARRAY(0x1efacb8)
   0  'val21'
   1  'val22'
   2  'val23'
</code>```

Another function requires an array of hashes containing arrays:

```<code>0  HASH(0x1f6df98)
   'KEYNAME1' => ARRAY(0x1f776b0)
      0  'val11'
      1  'val12'
      2  'val13'
1  HASH(0x1f6dfe0)
   'KEYNAME2' => ARRAY(0x1f6df80)
      0  'val21'
      1  'val22'
      2  'val23'
</code>```

This code converts the first to the second, but is there an easier way?

答:
This segment of code is redundant because @{$hash{$feld}} already contains exactly what you produce in @array.

```<code>my @array;
foreach my $wert (@ {$hash{$feld}}) {
    print "wert $wert";
    push @array, $wert;
}
</code>```

Here is a simpler solution.

```<code>use Data::Dumper;

my %hash = (
    KEYNAME1 => [qw( val11 val12 val12 )],
    KEYNAME2 => [qw( val21 val22 val23 )],
);
print Dumper \%hash;

my @array;
while ( my ($key, $val) = each %hash ) {
    push @array, {$key => $val};
}
print Dumper \@array;
</code>```

A map could be used instead of the while loop, but I think the loop is easier to read.

```<code>my @array = map { {$_ => $hash{$_}} } keys %hash;
</code>```

Title: Converting data-structure in Perl

Body:
This segment of code is redundant because @{$hash{$feld}} already contains exactly what you produce in @array.

my @array;
foreach my $wert (@ {$hash{$feld}}) {
    print "wert $wert";
    push @array, $wert;
}

Here is a simpler solution.

use Data::Dumper;

my %hash = (
    KEYNAME1 => [qw( val11 val12 val12 )],
    KEYNAME2 => [qw( val21 val22 val23 )],
);
print Dumper \%hash;

my @array;
while ( my ($key, $val) = each %hash ) {
    push @array, {$key => $val};
}
print Dumper \@array;

A map could be used instead of the while loop, but I think the loop is easier to read.

my @array = map { {$_ => $hash{$_}} } keys %hash;


问:
DI: Can a stable dependency have a volatile dependency?
I've recently been reading through Mark Seemann's Dependency Injection in .NET and have been attempting to apply some of what I've learned in a new project I'm working on, and I'm stumped on a particular scenario trying to determine what dependencies I should and should not inject. I've read several other questions on SO and elsewhere that discuss similar scenarios but in a roundabout manner, and I think I've narrowed the underlying conceptual question to that which is in the title:

Can a stable dependency have a volatile dependency? Put another way: If a stable dependency has a volatile dependency, is the stable dependency really stable?

A quick example:

```<code>public class MyClass
{
    private IVolatileDependency1 _one;
    private StableDependency _stable;

    public MyClass(IVolatileDependency1 one, IVolatileDependency2 two)
    {
        _one = one;
        _stable = new StableDependency(two)
    }
}

public class StableDependency
{
    private IVolatileDependency2 _two;

    public StableDependency(IVolatileDependency2 two)
    {
        _two = two;
    }
}
</code>```

In this situation, MyClass has a stable dependency which I've chosen not to inject but instead instantiate internally and hold via composition. However, that stable dependency has a volatile dependency, which I'm injecting into MyClass and passing through to StableDependency's constructor.

For whatever reason, this smells a little bit to me. It's fairly straightforward in such a simple contrived example, but I can see things getting out of hand quickly in a more complicated real-world situation.

Is StableDependency really stable, or should I be composing/resolving it prior to constructing MyClass and injecting it from there? I really don't foresee StableDependency changing or being replaced by another implementation, but on the other hand the practice of passing dependencies down through parent classes to their children (parent/child in the composition sense) seems to expose the details of the children up through the parent, which would be a violation of the Law of Demeter.

EDIT: Changed VolatileDependency1 and VolatileDependency2 to interfaces to clarify that they are intended to be satisfied by multiple possible implementations (LSP-compatible).

EDIT 2: Thinking on this some more, and reading KeithS's answer and default.kramer's comment below, make me realize that maybe I shouldn't have named StableDependency as I did, because I don't think it's a dependency in the first place. It's not something I ever expect to have multiple implementations for; it's merely an implementation detail that MyClass uses composition to contain a StableDependency, so MyClass's knowledge of how to construct a StableDependency isn't a problem I don't think. The big question is, StableDependency does have a dependency on IVolatileDependency2, so how do I inject that dependency? Do I reason that for all intents and purposes MyClass has a dependency on IVolatileDependency2, and the fact that it just passes that dependency down to StableDependency is an implementation detail unrelated to DI?

答:
If the StableDependency can accept any VolatileDependency2 implementation without knowing the difference between any two of them (Liskov Substitution Principle), and you don't need to be able to change StableDependency, then your snippet is perfectly fine.

Now, the DI purists might say that there should be no "stable" dependencies. If one class A depends on another class B, there is always a chance that B will have to be replaced with a C:B and thus you are going to want the flexibility to inject B so that you do not have to recompile A to make this change. In your case, by declaring StableDependency, you are asserting that you will never need a BetterStableDependency. Right or wrong, who knows; if you're right then the implementation never changes, but if you're wrong then the tightly-coupled implementation requires changes in more places.

When you use an IoC framework to automate your DI, you usually end up registering every dependency with the IoC no matter how likely it is to change; you have it, why not use it? So, I'd go ahead and register StableDependency with the IoC container as an IMaybeStableDependency.


问:
Which aspect of normal forms do entity-attribute-value tables violate, if any?
I'm not asking if EAV tables are good or bad. I'm wondering if they are considered "normalized", and if not, why? If they aren't normalized, which normal form are they violating and why?</p>

答:
An EAV (aka Key-Question-Answer) table is technically in 3NF:

1NF

Rows are order-independent - True, the rows can be stored in any order.

Columns are order-independent - True, the column ordering has no effect on the state of the contained data, and columns can be referenced independently of any other.

No duplicate rows - True, there exists a unique candidate key Entity+Attribute which cannot be duplicated.

Every field (every column of every row) contains one and only one value - True, provided that "value" does not contain a list of values or a compound "structure" in serialized format.

Nothing is hidden - true, the database contains all information necessary to follow the above four rules and does not hide any of it (it may hide implementation details not necessary to follow the above four rules).

2NF

In 1NF - True

All columns of the table that aren't the candidate key must have a relationship (direct or indirect) with the entire candidate key - True, the only column that isn't part of the key is related to the full key.

3NF

In 2NF - True

All columns of the table that aren't the candidate key are directly related to the entire candidate key - True, the only column that isn't part of the key is directly related to both parts of the key.

Thus, EAV adheres to third normal form. It does not meet 4NF, because the structure has multivalued dependencies (in fact it is designed to); adding a new Entity ID to the table requires creating a row for each Attribute, while adding a newly-supported Attribute requires adding a row for each Entity having that new Attribute. A more traditional "flattened" table structure may meet 4NF; adding a new Entity only requires adding one row, and that is the only reason to add a row to the table.

If there is an argument to say that it's not 3NF, it would be that it violates 1NF's "no hidden information" rule in that the structure of the data is not known to the DB. The "Value" field of an EAV table is required to be able to hold anything that may be used as a value; as such it is usually a string field of some type, holding string representations of data such as numbers. That data must be parsed into the proper types, and the knowledge to do so is not contained in an accessible place in the DB (unless incorporated into Value itself, violating 1NF's "one and only one value" rule, or included as an extra column, violating 3NF's "all fields directly related to candidate key" rule), therefore it is "hidden".


答:
As mentioned, there is nothing terribly hard about build a chess engine. Perhaps, you should concentrate on how wish to use and (potentially) deploy this application as this will probably determine your choice of language.

If this is just a fun exercise, you may want to code it in Javascript and deploy it as a web page. If you never want to make it into a expert chess game, at least others will be able to play with it and its source code.

If you wish to learn a particular technology at the same time, say WPF, then this might be a good way to kill two birds with one stone. MVVM could be overkill for this app, but you'd learn it at least.

If you wish to target android devices, then Java would be a good choice. Similarly, Objective-C for iOS devices.

Long and short, choice of language does not exist in a vacuum.


问:
How to introduce code to a colleague
How do you go about introducing the codebase, which may be rather complex and tangled with a lot of "gotchas," to a new member of your team?

I think the easiest way would be to have the overall architecture laid out with diagrams, and take a couple weeks (or months) giving the new person well defined (and well scoped) tasks as he becomes more accustomed to the code.

However, as a consultant (and junior employee, at that,) I can't always have that either due to time constraints or team role designations. (I have been on this particular project twice as long as anybody else, so "junior" is in no way "knows less about the code/project.")

I've been tasked quite a few times now to introduce a new member to the project and code, and sadly each time I find I'm not much better at it than the one before.  I love diagrams and pictures, but often feel that they don't adequately account for the complexity in a system.   (What about all the little's "gotchas"?)

The project is getting to a point where we will be handing it off to the client, and to make things more challenging, the person I'll be doing a knowledge transfer with is essentially just out of college.  (Not that I'm much better when doing knowledge transfers with senior developers.)

I attend a user group once a month and other opportunities as they arise, so I'm not unused to be being introduced to new topics, but feel my ability to replicate effective knowledge sharing woefully inadequate.

Any advice would be greatly appreciated.  I am looking mostly for a guideline I can follow.  For example: Where do you start? How do you proceed? How do you cover unfamiliar technologies or patterns on the listener's part without taking all day?  Where do you tie in business logic vs. code-structure?

Thank you!

(As always, please feel free to edit the question as you see fit.)

答:
You're not teaching them the code base, you're teaching them your job.  Don't try to think what they might need, look at what you have actually needed to know when doing your job.

Pull up the last few months of bug tracker history, scrum user stories, status reports, and source control commits.  What files did you touch the most?  What code is most problematic?  What tasks took you the longest?  Chances are, if you haven't touched it in the last few months, it's not as important as you might think it is.

Look at the stack of printouts on your desk.  Check your recent browser history.  Look for saved emails you refer to frequently, contacts you use, documents you have downloaded.  Some of the most useful references I have passed on to others are the notes I kept for myself when first learning or designing the system.  What reference material is most useful to you?

Next pull up your known backlog.  What things would you need to research in order to finish those tasks?  What areas of code most likely contain the problem?  Convey that information as if you were taking notes for yourself.

If you refer to charts or diagrams in your daily work, include those.  If you've never bothered making one, it's probably not going to be that useful to your successor/colleague either.

One of the most difficult tasks when teaching is trying to put yourself in their shoes.  In this case, you are in their shoes.  Make the most of it.

Title: How to introduce code to a colleague


问:
How do you deal with the costs of too-rapid change?
Like most modern developers I value Agile principals like customer collaboration and responding to change, but what happens when a product-owner (or whoever determines requirements and priorities) changes requirements and priorities too often? Like several times a day?

I recently inherited a smallish code base that was buggy, incomplete, and couldn't even handle the simplest scenario it was supposed to. I can deal with the technical issues but I get several emails, texts, or phone calls a day saying "OMG you MUST work on this RIGHT NOW! TOP PRIORITY! This is a MUST!!!oneone" (that's only a slight exaggeration) What makes it even worse is that most of the things are minor details that aren't even relevant to what the software is actually supposed to do and would take days to implement anyway. I've tried explaining that there's only so much time and that we should focus on the most important things first, but something seems to get lost in translation because the same thing happens a day or two later.

Is there some sort of Product-Owner-Handler role, in-depth study, metaphor, or quote that can help me reduce the amount of wasted effort or at least explain the costs of this chaotic behavior?

答: This is what the backlog is for.  New requests get put on the backlog, and priorities can only change on iteration boundaries.  An average of one week delay (half of a two-week sprint) is plenty agile enough to handle all but the most dire emergencies.</p>


答:
SOP. Standard Operating Procedure (or at least a loose protocol that is signed off by your management team). Your department needs to develop one, or work with your management team to develop one.  The people you need to talk to are above the product-owner/account manager.

Some examples of what your SOP should define.

What procedures are to be followed when a client or internal entity requests a change

What are the implications and/or impact on the quality control or verification of this product?

What is the method to reasonably determine a timeframe for delivery? This iteration? Next version?

Without such procedures in place, everyone is going to run at you like they are being chased by zombies and expect everything NOW NOW NOW.  People like that won't respect your polite 'no' or 'please wait's.  With a firm policy in place, these code-craving mutants will understand that they are in the wrong when asking for things on such a loose basis.

The end result is unhappy you, and that isn't in your companies best interest.

On a side note, you may have inherited someones mess caused by such blatant disrespect for his/her position and duty.  People in that situation tend to find it hard to produce quality product.  Is it any wonder?  Software engineering 101.

Title: How do you deal with the costs of too-rapid change?

Body:
Like most modern developers I value Agile principals like customer collaboration and responding to change, but what happens when a product-owner (or whoever determines requirements and priorities) changes requirements and priorities too often? Like several times a day?

I recently inherited a smallish code base that was buggy, incomplete, and couldn't even handle the simplest scenario it was supposed to. I can deal with the technical issues but I get several emails, texts, or phone calls a day saying "OMG you MUST work on this RIGHT NOW! TOP PRIORITY! This is a MUST!!!oneone" (that's only a slight exaggeration) What makes it even worse is that most of the things are minor details that aren't even relevant to what the software is actually supposed to do and would take days to implement anyway. I've tried explaining that there's only so much time and that we should focus on the most important things first, but something seems to get lost in translation because the same thing happens a day or two later.

Is there some sort of Product-Owner-Handler role, in-depth study, metaphor, or quote that can help me reduce the amount of wasted effort or at least explain the costs of this chaotic behavior?


问:
What is abstraction?
Is there a generally agreed upon definition for what a programming abstraction is, as used by programmers? [Note, programming abstraction is not to be confused with dictionary definitions for the word "abstraction."] Is there an unambiguous, or even mathematical definition? What are some clear examples of abstractions?

答: Well, mathematically, "integer" is an abstraction. And when you do formal proofs like that x+y = y+x for all integers, you're working with the abstraction "integer" rather than specific numbers like 3 or 4. That same thing happens in software development when you interact with the machine at a level above registers and memory locations. You can think more powerful thoughts at a more abstract level, in most cases.</p>

Title: What is abstraction?

ContentLicense: CC BY-SA 2.5


问:
What do you call an interface with no defining methods used as property setters
In ASP.NET and C# I've ran across this before.  Your class needs to implement interface ISomething in order for something in the super class to supply something to you.

I can't remember the details, as I ran across it quite a while ago, but it had something to do with session variables in ASP.NET C#.  It was part of the .NET framework.

At first, I thought this practice was rather silly and could be more gracefully implemented.  However now I'm finding myself implementing this in the architecture of a home-grown project I'm working on.  Using reflection, I detect the toggle a behavior on or off based on if it implements ISomething.  Just an empty interface with no methods at all.

What is the technical name for this and is it good practice?

答:
Are you thinking of accessing session state in an .ashx generic handler by implementing the (empty) IRequiresSessionState interface?

I don't know what the technical name for that is. Is it a good practice? Well, I'm not entirely sure why it wasn't done using an attribute.

e.g. instead of:

```<code>public class MyGenericHandler : IHttpHandler, IRequiresSessionState
{
}
</code>```

Doing:

```<code>[RequiresSessionState]
public class MyGenericHandler : IHttpHandler
{
}
</code>```

That certainly seems more intuitive, and more in line with more recently implemented features in ASP.NET and the .NET framework.

Body:
Are you thinking of accessing session state in an .ashx generic handler by implementing the (empty) IRequiresSessionState interface?

I don't know what the technical name for that is. Is it a good practice? Well, I'm not entirely sure why it wasn't done using an attribute.

e.g. instead of:

public class MyGenericHandler : IHttpHandler, IRequiresSessionState
{
}

Doing:

[RequiresSessionState]
public class MyGenericHandler : IHttpHandler
{
}

That certainly seems more intuitive, and more in line with more recently implemented features in ASP.NET and the .NET framework.


答:
Marker Interface

Is it good practice? Well, like many things some people love them and some people hate them. See the links in the Wikipedia article for discussion. Personally I think they are rarely useful. The presence of a marker is essentially only a Boolean. It seems preferable to me to define an interface that allows richer information flow and then to pass references using that actual type.

Title: What do you call an interface with no defining methods used as property setters

Body:
In ASP.NET and C# I've ran across this before.  Your class needs to implement interface ISomething in order for something in the super class to supply something to you.

I can't remember the details, as I ran across it quite a while ago, but it had something to do with session variables in ASP.NET C#.  It was part of the .NET framework.

At first, I thought this practice was rather silly and could be more gracefully implemented.  However now I'm finding myself implementing this in the architecture of a home-grown project I'm working on.  Using reflection, I detect the toggle a behavior on or off based on if it implements ISomething.  Just an empty interface with no methods at all.

What is the technical name for this and is it good practice?


答:
Here is how I dealt with a similar problem .. Back in the days when we were agile before Agile.

For any change request, the customer sets the priority. The developer can only, and must, stop work on a task to work on a higher priority task. Equal priority tasks are schedules in order of arrival. (Task Priority cannot be changed once work has started.)

It will hurt when you tell the customer that you cannot work on his task because you are working on unimportant task X that has the same priority as his latest request. You then tell him that at that priority level there are 50 trivial and unimportant tasks ahead of his latest request. Now the real catch - all these tasks are at priority level 1 (the Highest), set by ... HIM ... So he cannot bump you off the task you are doing. Now, when you have  finished moving the window frame 3 pixels to the left to make room for the  longer word in the Icelandic translation on the rarely used configuration option.....

I also close the door to the SD office, locked it and took the phones off the hook. Emails were ignored until at 10AM, 12PM and 2PM. Despite what people thought and felt, the world still went around the sun, we got our work done and the "Customers" got software delivered to them quicker and better than any time in the past.

It took a few weeks for the priorities to settle to something more realistic, we were able to unlock the door etc.... But the system remained for quite a long time. You may not need to be so extreme (we did), and will need support from Senior management. But it will work....


答:
The problem with "chess program" as a concept is that there are many pieces which can absorb a lot of time, and not necessarily interest you at the moment.   You can spend years just working on graphics, or an alpha-beta search, or a visualization to help develop for the search engine, or... well, there are lots of pieces.

I recommend finding an open source chess program (there must be many) and set about improving the parts of it that interest you the most.   You may eventually replace the entire program,
one function at a time, or you may learn enough and be motivated to throw it away and design your own program from scratch.   In any case, the key is to start "light" and learn the ropes before trying to architect an entire program.


问:
Multiple Same Object Instantiation
What exactly happens in Java when you instantiate the same object multiple times?

For example:

```<code>Test test = new Test();
</code>```

then later on I will call it again, Test test = new Test(); again or inside a loop. Will the previous instantiation be disposed?

答:
each call new Test() creates a new object instance of the Test class

test = new Test(); assigns a reference of that object to variable test

A repeated statement test = new Test() creates a second instance of Test and assigns the reference it to the variable test again, so the first reference is replaced.

If and when the first instantiation will be disposed, however, depends. The Java runtime environment traces references, so as long as there are any references to an object in use, the object won't be disposed. For example, if between step 2 and step 3 the reference to the first instantiation is stored somewhere else (like Test test2 = test;), and that variable is still in scope when step 3 occurs, then the first object is not disposed, since test2 is still holding a reference to it. However, when there is no such statement and step 3 omits the one-and-only reference to the first object, then a dispose of that object will happen.

Note that the dispose itself does not happen immediately, but sometimes later, the next time when the garbage collector is run. But that is independent from the semantics of the code discussed, thats only a question of memory and performance.

Title: Multiple Same Object Instantiation


问:
Wrapping REST based Web Service
I am designing a system that will be running online under Microsoft Windows Azure. One component is a REST based web service which will really be a wrapper (using proxy pattern) which calls the REST web services of a business partner, which has to do with BLOB storage (note: we are not using azure storage). The majority of the functionality will be taking a request, calling our partner web service, receiving the request and then passing that back to the client.

There are a number of reasons for doing this, but one of the big ones is that we are going to support three clients: our desktop application (win and mac), mobile apps (iOS), and a web front end. Having a single API which we then send to our partner protects us if that partner ever changes.

I want our service to support both JSON and XML for the data transfer format, JSON for web and probably XML for the desktop and mobile (we already have an XML parser in those products). Our partner also supports both of these formats.

I was planning on using ASP.NET MVC 4 with the Web API. As I design this, the thing that concerns me is the static type checking of C#. What if the partner adds or removes elements from the data? We can probably defensively code for that, but I still feel some concern. Also, we have to do a fair amount of tedious coding, to setup our API and then to turn around and call our partner’s API. There probably is not much choice on it though. But, in the back of my mind I wonder if maybe a more dynamic language would be a better choice.

I want to reach out and see if anybody has had to do this before, what technology solutions they have used to (I am not attached to this one, these days Azure can host other technologies), and if anybody who has done something like this can point out any issues that came up. Thanks!

Researching the issue seems to only find solutions which focus on connecting a SOAP web service over a proxy server, and not what I am referring to here.

Note: Cross posted (by suggestion) from https://stackoverflow.com/questions/11906802/wrapping-rest-based-web-service

Thank you!

答:
Although you say it's not what you need. Your question DOES suggest not creating a web service at all but to use a reverse proxy on their webservice. Any access will go through your reverse proxy which you could redirect at will.

Alternatively you could do some basic enveloping of their responses, wrap their XML or JSON in your own. You would not need to look at the XML or JSON at all or be effected by changes in it's schema.

On the other hand, if you were to switch to a different partner service. Do you think their data will look exactly the same? Would your clients be able to work with it without modification?

You could use your 'wrapper' service as a facade to make sure the data provided complies to your defined structure. In such a setup you would not automatically let through whatever field a partner may add. Your webservice would make a partners webservice comply to a certain contract. Basically protecting the client programs from unexpected changes.

Of course you could add a little pockets of key-value pairs here and there if it makes sense (the data being dynamic). Don't need a dynamic programming language for that.

Title: Wrapping REST based Web Service


问:
Project Management - Asana / activeCollab / basecamp / alternative / none
I don't know whether this should be on programmers - I've been looking at the above three apps over the past few weeks just for myself and I'm in two minds. All three look good, are easy to use, and I came to this conclusion;

Asana is the easiest to use

ActiveCollab is the feature rich and easiest flow

BaseCamp is the best UX / design

But I didn't really find my workflow was any more quicker / efficient, in fact it was a bit slower and organized.

Is there a realistic place for them in workflow - should programmers use them for themselves, or only when a project manager can take control of it?

答:
We use Basecamp. But for developers it's too flexible, everyone has almost the same rights. For example a developer can delete a task without anyone noticing it.
The same if you use Basecamp with your customers, they can delete a task without anyone knowing.

But the good thing is the UX and it's so easy and fast to use. And they have an API


问:
Limitations of Polymorphism in statically typed languages
I program mostly in statically typed languages, like C++ and Java.  A common strategy employed in languages like these to handle dealing with collections of objects which are related, but which need to employ specific behaviors, is to use polymorphism and inheritance hierarchies.  But Polymorphism only works when the Base class has a method (virtual function) which can then be overridden by every Derived class.  But there are often cases where a Derived class needs to have a method, and it doesn't make sense to place a method of the same name in the Base class, because it is very specific to the Derived class.

Let me give a concrete example that many of us can probably relate to: the HTML DOM.

Javascript programmers are quite used to doing things like iterating over collections of DOM nodes.  They take for granted the dynamically-typed nature of Javascript when they do something like:

```<code>node = document.getElementById("foo");
for (var i = 0; i < node.childNodes.length; ++i)
    doSomething(node.childNodes[i]);
</code>```

Something like this would be very messy to do in a statically typed language like Java, because inheritance-based polymorphism doesn't lend itself well to situations where Derived classes have methods which don't exist in the Base class.  For example, when iterating over the above HTML Nodes, we might find a DIV node, which has certain methods, and a Text node, which has certain different methods, and a TABLE node, which has its own unique methods - and it wouldn't make much sense for ALL of these various methods to exist in a common Base class "Node", because they are highly specific to each Derived type.  (e.g. a DIV node has no need of a "cells" method, but a TABLE node does.)

So, in a statically typed language, you'd be forced to fall back on something like Type Enums and a lot of messy down-casting to check what type of Node you have.  So basically you end up with messy code like:

```<code>Node node = document.getElementById("foo");
for (int i = 0; i < node.childNodes().length(); ++i)
{
   Node n = node.childNodes().elementAt(i);
   if (n.type() == Node.DIV_NODE) doSomethingWithDiv(((DivNode)(n)));
   else if (n.type() == Node.TABLE_NODE) doSomethingWithTable(((TableNode)(n)));
   /* etc... */
}
</code>```

This is similar to what C programmers do, and it's seemingly the sort of thing virtual functions were designed to avoid.  And yet, when you're faced with a situation where there are various different methods in a Derived class for which it doesn't make any sense to place in a common base class, you have no recourse but to resort to something like Type Enums.

So, how is this problem usually addressed in statically-typed languages?  Is there a better design pattern than Type Enums?

答:
To me it seems your problem is either a flaw in your understanding or a flaw in your design. Or both. :)

What your example attempts do (and does in JS) is to execute a method with the same name on each of a bunch of objects of unrelated types. That's one of those hacks you do when you knocking up a quick throw-away tool in some scripting language, and it has its place there.

But static languages are statically typed so that the compiler can catch simple errors like calling a non-existent method at compile time. When you are doing development in such a language, the assumption naturally is that you mean business, that your program is to be run at some customers, and that you want to weed out as many bugs as possible as early as possible.

One of the things a statically language requires in order to be able to hold your hand is that you express it in your design if a group of types support the same operation. You do this by deriving them from the same base class or interface, which declares that this operation is available in all derived classes. If you don't do this, your code will have to invent numerous hacks in order to achieve the same goal. (A wise man once said that a switch over types — which is what your if(n.type() == Node.SOME_TYPE) ... else if(n.type() == Node.SOME_OTHER_TYPE) ... really amounts to — is just unreasonable fear of virtual function.)

So: If those types support the same operation, and if you want to execute that operation on objects of any of those types without really caring which concrete type they're of, then you need to declare those operations available in some common base class or interface. (For the corner case that you have only a relatively small number of types, but a number of unrelated operations, which would unreasonably fatten a base class' interface, there's idioms like the Visitor Pattern which employ multiple dispatch to solve that problem.)


问:
Why this code create object as interface?
In am reading Spring in Action (3rd edition) and here a snippet from it:

```<code>ApplicationContext ctx=new ClassPathXmlApplicationContext("springidol.xml");
            Performer performer=(Performer)ctx.getBean("poeticDuke");
            performer.perform();
</code>```

It doesn't has any problem,however, when the author introduce the init-method and destroy-method:

```<code><bean id="poeticDuke"
        class="com.springinaction.springidol.PoeticJuggler"
        init-method="turnOnLights"
        destroy-method="turnOffLights">
</code>```

Somehow the output only got the init-method but not the destroy-method. Then I realized that the context call destroy-method upon its close and I tried to code as following:

```<code>    ApplicationContext ctx=new ClassPathXmlApplicationContext("springidol.xml");
                Performer performer=(Performer)ctx.getBean("poeticDuke");
                performer.perform();
ctx.close();
</code>```

It doesn't compile because the interface ApplicationContext doesn't have the method close. It only work as following:

```<code>ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("springidol.xml");
                Performer performer=(Performer)ctx.getBean("poeticDuke");
                performer.perform();
ctx.close();
</code>```

Why did the author wrote it that way?

答:
The init and destroy methods are called by the Spring application container. Application code should never call them, and since the ApplicationContext interface is meant to be used by applications, it does not contain the method.

That's the whole point of frameworks like Spring: "don't call us, we will call you".

Note that the close() method is included in the ConfigurableApplicationContext interface, which is the API for the application container to call.


问:
What degree of low-level programming can be achieved with Languages like Go?
Go and D provide garbage collection, and yet they claim to be system programming languages. What degree of low-level programming can be achieved with languages having garbage collection?

For low-level programming, I mean close to the hardware or being able to:

Runs directly in limited memory, with no latency, and performs well.  An example would be operating system kernels.

It runs on a software base, but still has to perform well. An example would be system utilities.

答:
I am not sure about go, but D clearly specifies which constructs may access the garbage collector (down at the end here; I actually think I saw a  more detailed explanation on the site, but can't quickly find it). So you can choose where gc can and can't operate.

Runs directly on the limited memory, with no latency means (hard) real time. Which means you can't use even C++'s new and delete nor C++ exceptions nor many other features of C++ or even C. The D subset that you can use in these cases is well defined and thanks to custom new/delete even quite capable.

Most OS kernels don't do hard real time at all and do soft real time ("with sufficiently rare latency") only in interrupt service routines. Many parts of an operating system could easily use a mark&sweep style collector and be more performant than current systems that usually reference-count. It would require carefully crafted two-phase parallel collector, but it's doable.

As for runs on a software base, but still have to perform well, while garbage collector always implies somewhat increased memory use, the performance is usually comparable and often even superior to explicit memory managed programs. That's because the individual operations under garbage collector are usually simpler and because the allocation patterns tend to result in better cache utilization.

Combined with the fact that despite all the research that went to decent memory allocators most standard C libraries in the wild still have malloc that plainly sucks, there is no handicap for Go or D here.


问:
Why is OOP difficult?
When I started using an object-oriented language (Java), I pretty much just went "Cool" and started coding. I've never really thought about it until only recently after having read lots of questions about OOP. The general impression I get is that people struggle with it. Since I haven't thought of it as hard, and I wouldn't say I'm any genius, I'm thinking that I must have missed something or misunderstood it.

Why is OOP difficult to understand? Is it difficult to understand?

答:
Object Oriented Programming in itself is not hard.

The hard part comes in doing it well.  Where to put the cut between code so you can easily move things to the common base object, and extend them later?  How to make your code usable by others (extend classes, wrap in proxies, override method) without jumping through hoops to do so.

That is the hard part, and if done right can be very elegant, and if done badly can be very clumsy.  My personal experience is that it requires a lot of practice to have been in all the situations where you would WISH that you did it differently, in order to do it well enough this time.

Title: Why is OOP difficult?


答:
There are several ways of handling this in statically typed languages. Probably the most elegant is pattern matching. Here’s Haskell:

```<code>doSomething (DivNode n)     = does something with a div node
doSomething (TableNode n)   = does something with a table node
doSomething _               = do nothing
</code>```

The same, or similar, mechanisms exist in other statically typed languages (F#, Scala as far as I know). In C++, the same can be emulated (albeit more verbosely) with the Boost.Variant and the static visitor:

```<code>struct visit_node : static_visitor<void> {
    void operator ()(DivNode const& n) {
        // Do something with a div node.
    }

    void operator ()(TableNode const& n) {
        // Do something with a table node.
    }

    template <typename T>
    void operator ()(T const& n) {
        // Do nothing.
    }
}
</code>```

(It’s worth noting that this looks like compile-time overload resolution but thanks to the magic of Boost.Variant, this will work at runtime, and be completely type safe.)

More generally, a visitor pattern can be used to implement it, but they are even more verbose than Boost’s static_visitor helper and (which essentially abstracts away the cruft) which makes them very unresponsive to changes in the class hierarchy.

And yes, you can obviously hard-code the dispatch via dynamic casts as some other answers have shown. That’s easily the worst possible solution, though. Like the above methods, it hard-codes the type hierarchy, but it does so in a particularly verbose way.

Title: Limitations of Polymorphism in statically typed languages

Body:
I program mostly in statically typed languages, like C++ and Java.  A common strategy employed in languages like these to handle dealing with collections of objects which are related, but which need to employ specific behaviors, is to use polymorphism and inheritance hierarchies.  But Polymorphism only works when the Base class has a method (virtual function) which can then be overridden by every Derived class.  But there are often cases where a Derived class needs to have a method, and it doesn't make sense to place a method of the same name in the Base class, because it is very specific to the Derived class.

Let me give a concrete example that many of us can probably relate to: the HTML DOM.

Javascript programmers are quite used to doing things like iterating over collections of DOM nodes.  They take for granted the dynamically-typed nature of Javascript when they do something like:

```<code>node = document.getElementById("foo");
for (var i = 0; i < node.childNodes.length; ++i)
    doSomething(node.childNodes[i]);
</code>```

Something like this would be very messy to do in a statically typed language like Java, because inheritance-based polymorphism doesn't lend itself well to situations where Derived classes have methods which don't exist in the Base class.  For example, when iterating over the above HTML Nodes, we might find a DIV node, which has certain methods, and a Text node, which has certain different methods, and a TABLE node, which has its own unique methods - and it wouldn't make much sense for ALL of these various methods to exist in a common Base class "Node", because they are highly specific to each Derived type.  (e.g. a DIV node has no need of a "cells" method, but a TABLE node does.)

So, in a statically typed language, you'd be forced to fall back on something like Type Enums and a lot of messy down-casting to check what type of Node you have.  So basically you end up with messy code like:

```<code>Node node = document.getElementById("foo");
for (int i = 0; i < node.childNodes().length(); ++i)
{
   Node n = node.childNodes().elementAt(i);
   if (n.type() == Node.DIV_NODE) doSomethingWithDiv(((DivNode)(n)));
   else if (n.type() == Node.TABLE_NODE) doSomethingWithTable(((TableNode)(n)));
   /* etc... */
}
</code>```

This is similar to what C programmers do, and it's seemingly the sort of thing virtual functions were designed to avoid.  And yet, when you're faced with a situation where there are various different methods in a Derived class for which it doesn't make any sense to place in a common base class, you have no recourse but to resort to something like Type Enums.

So, how is this problem usually addressed in statically-typed languages?  Is there a better design pattern than Type Enums?

Body:
There are several ways of handling this in statically typed languages. Probably the most elegant is pattern matching. Here’s Haskell:

doSomething (DivNode n)     = does something with a div node
doSomething (TableNode n)   = does something with a table node
doSomething _               = do nothing

The same, or similar, mechanisms exist in other statically typed languages (F#, Scala as far as I know). In C++, the same can be emulated (albeit more verbosely) with the Boost.Variant and the static visitor:

struct visit_node : static_visitor<void> {
    void operator ()(DivNode const& n) {
        // Do something with a div node.
    }

    void operator ()(TableNode const& n) {
        // Do something with a table node.
    }

    template <typename T>
    void operator ()(T const& n) {
        // Do nothing.
    }
}

(It’s worth noting that this looks like compile-time overload resolution but thanks to the magic of Boost.Variant, this will work at runtime, and be completely type safe.)

More generally, a visitor pattern can be used to implement it, but they are even more verbose than Boost’s static_visitor helper and (which essentially abstracts away the cruft) which makes them very unresponsive to changes in the class hierarchy.

And yes, you can obviously hard-code the dispatch via dynamic casts as some other answers have shown. That’s easily the worst possible solution, though. Like the above methods, it hard-codes the type hierarchy, but it does so in a particularly verbose way.


答:
I don't see where you have different problem in statically typed languages versus dynamically typed ones. Because the only difference in dynamically typed language is that you don't have to declare the interface and that an error is only detected at runtime.

However in both cases you have to either:

Check the actual type of the instance and only call the method you know it has. The only difference is that statically typed language will need a cast.

Have all the methods in all the types, even the ones where they don't make sense.

Use a Visitor Pattern, which is quite simple in statically typed languages, while it requires introspection in most dynamic ones.

There is a handful of languages that have dynamic multiple dispatch, but IIRC there are both dynamic and static ones that do (and none widely used).


问:
Are factors such as Intellisense support and strong typing enough to justify the use of an 'Anaemic Domain Model'?
It's easy to accept that objects should be used in all layers except a layer nominated as a data layer. However, it's just as easy to end-up with an 'anaemic domain model' that is just an object representation of data with no real functionality ( http://martinfowler.com/bliki/AnemicDomainModel.html ).

However, using objects in this fashion brings the benefit of factors such as Intellisense support, strong typing, readability, discoverability, etc.

Are these factors strong arguments for an otherwise, anaemic domain model?

答:
It all depends, surely, of what are your options.

You should understand that alternative to "(anemic) domain model" is not "something without strong-typing", but "data transfer objects". Both are strong-typed (with all included benefits), but there's strong semantic difference between them.


问:
Hiding away complexity with sub functions
I am having a discussion on code style, and it's starting to sound like a "matter of taste". I strongly believe otherwise, so I'm writing this to get your opinion and learn from your arguments for and against.

The issue is that of hiding complexity by replacing a bunch of lines of code with a method. This discussion is unrelated to reusable functions, and I'm trying to make the argument for simple code organization, not for factoring out common functionality.

So, take this example in loose java:

```<code>public void purchase(Customer customer, Set<Item> items, Warehouse warehouse){
     int credit = customer.getCredit();
     int orderPrice;

     for(Item item: items){
         orderPrice+=items.getPrice();
     }

     if(orderPrice + customer.getPendingPayments() > customer.getCredit()) {
           warehouse.reserveStock(items);
           transportCenter.allocateTransport();
           customer.bill(items, orderPrice);
     }
}
</code>```

As opposed to this:

```<code>public boolean isCreditOk(Customer customer, Set<Item> items){
     int credit = customer.getCredit();
     int orderPrice;

     for(Item item: items){
         orderPrice+=items.getPrice();
     }
     return  orderPrice + customer.getPendingPayments() > customer.getCredit();
}

public void purchase(Customer customer, Set<Item> items, Warehouse warehouse){
     if(isCreditOk(customer, items)){
           warehouse.reserveStock(items);
           transportCenter.allocateTransport();
           customer.bill(items, orderPrice);
     }
}
</code>```

The whole discussion now is: would you have created the isCreditOk method or would you have left if inline? When do you do one or the other? does it depend, in a general case, on:

The length of the function to extract

How many sub-functions and sub-subfunctions isCreditOk will end up having

Again, this is not done because isCreditOk will be used often, but because it makes the code easier to read (in my opinion).

Can I have your comments? Thanks!

Note: I have found this question to be related: Is there such a thing as having too many private functions/methods?

答: Your second example is more readable (although I would invert if to reduce nesting and rename isCreditOk to isPurchaseAllowed, and possibly moved the latter to Customer). First one hides code intent, exposing implementation, thus while it's clear what code exactly, it's not clear why it does those things.


答:
I was just watching a video by Richard Feynman discussing how people may actually have completely different methodologies going on in their head when thinking--I mean completely different.

When I do high-level design I happen to visualize objects, I can see them, see their interfaces and see what pathways information needs to traverse.

I also have trouble remembering details and found OO to be a great organizational aid--much easier to find functionality than scanning through a loosely-organized list of subroutines.

For me OO was a great benefit, but if you don't visualize the same way or don't do high-level architecture, it's probably pointless and annoying.

Title: Why is OOP difficult?

Body:
When I started using an object-oriented language (Java), I pretty much just went "Cool" and started coding. I've never really thought about it until only recently after having read lots of questions about OOP. The general impression I get is that people struggle with it. Since I haven't thought of it as hard, and I wouldn't say I'm any genius, I'm thinking that I must have missed something or misunderstood it.

Why is OOP difficult to understand? Is it difficult to understand?


答:
Here is what Robert C. Martin (the "clean code" guy) would do:

http://blog.objectmentor.com/articles/2009/09/11/one-thing-extract-till-you-drop

So I guess he would split up your isCreditOk function further like this

```<code>public int calculateOrderPrice(Set<Item> items)
{
     int orderPrice=0;
     for(Item item: items){
         orderPrice+=items.getPrice();
     }
     return orderPrice;
}

public boolean isCreditOk(Customer customer, Set<Item> items){
     int credit = customer.getCredit();
     int orderPrice = calculateOrderPrice(items);
     int totalPayments = orderPrice + customer.getPendingPayments();
     return totalPayments > credit;
}
</code>```

And indeed, I think this is a good thing - using functions not just for reuse, but also for building abstractions. The key factor here is good naming of the functions, so you can use them as small building blocks. Then it will increase the readability of the code a lot.

Of course, there are different opinions around how far one should go when refactoring to small functions, and to be honest, I am still not coding like Bob Martin. But the more I have focused the last years on creating small functions, the more I have made the experience that it pays off more or less immediately - my code becomes more readable, needs less comments, has less bugs and is more evolvable (which means, it gets easier to introduce new features into existing code).

Title: Hiding away complexity with sub functions

Body:
I am having a discussion on code style, and it's starting to sound like a "matter of taste". I strongly believe otherwise, so I'm writing this to get your opinion and learn from your arguments for and against.

The issue is that of hiding complexity by replacing a bunch of lines of code with a method. This discussion is unrelated to reusable functions, and I'm trying to make the argument for simple code organization, not for factoring out common functionality.

So, take this example in loose java:

```<code>public void purchase(Customer customer, Set<Item> items, Warehouse warehouse){
     int credit = customer.getCredit();
     int orderPrice;

     for(Item item: items){
         orderPrice+=items.getPrice();
     }

     if(orderPrice + customer.getPendingPayments() > customer.getCredit()) {
           warehouse.reserveStock(items);
           transportCenter.allocateTransport();
           customer.bill(items, orderPrice);
     }
}
</code>```

As opposed to this:

```<code>public boolean isCreditOk(Customer customer, Set<Item> items){
     int credit = customer.getCredit();
     int orderPrice;

     for(Item item: items){
         orderPrice+=items.getPrice();
     }
     return  orderPrice + customer.getPendingPayments() > customer.getCredit();
}

public void purchase(Customer customer, Set<Item> items, Warehouse warehouse){
     if(isCreditOk(customer, items)){
           warehouse.reserveStock(items);
           transportCenter.allocateTransport();
           customer.bill(items, orderPrice);
     }
}
</code>```

The whole discussion now is: would you have created the isCreditOk method or would you have left if inline? When do you do one or the other? does it depend, in a general case, on:

The length of the function to extract

How many sub-functions and sub-subfunctions isCreditOk will end up having

Again, this is not done because isCreditOk will be used often, but because it makes the code easier to read (in my opinion).

Can I have your comments? Thanks!

Note: I have found this question to be related: Is there such a thing as having too many private functions/methods?

Body:
Here is what Robert C. Martin (the "clean code" guy) would do:

http://blog.objectmentor.com/articles/2009/09/11/one-thing-extract-till-you-drop

So I guess he would split up your isCreditOk function further like this

public int calculateOrderPrice(Set<Item> items)
{
     int orderPrice=0;
     for(Item item: items){
         orderPrice+=items.getPrice();
     }
     return orderPrice;
}

public boolean isCreditOk(Customer customer, Set<Item> items){
     int credit = customer.getCredit();
     int orderPrice = calculateOrderPrice(items);
     int totalPayments = orderPrice + customer.getPendingPayments();
     return totalPayments > credit;
}

And indeed, I think this is a good thing - using functions not just for reuse, but also for building abstractions. The key factor here is good naming of the functions, so you can use them as small building blocks. Then it will increase the readability of the code a lot.

Of course, there are different opinions around how far one should go when refactoring to small functions, and to be honest, I am still not coding like Bob Martin. But the more I have focused the last years on creating small functions, the more I have made the experience that it pays off more or less immediately - my code becomes more readable, needs less comments, has less bugs and is more evolvable (which means, it gets easier to introduce new features into existing code).


答:
Your example begs the question: How do you KNOW that you are iterating over a set of DOMs?  How do you know something else didn't sneak in there?  How do you know the new hire from PoliticallyCorrectUniversity read the documentation closely enough, and didn't call your routine with the wrong list of stuff?

You want the compiler to catch these things for you.  That's what strong typing and static typing are all about.  (Recall the ALGOL committee's reply to Wirth's proposal for default type rules for ALGOL.)

You can tell the compiler what you are doing in one of two ways: put a virtual method in the base class (or in an interface), with an error barf for the default case that everyone EXCEPT the privileged derived class will inherit, or, as you said, "fall back on something like Type Enums and a lot of messy down-casting to check what type of Node you have".


答:
Divide into smaller functions is the best way for sure, at least for human readability.

By extracting a smaller function, you are naming a block of code. That really improves readability.

Readers can have a macro idea of what that function does, without having to bother with details of each step. If you want to see the details, than you look ate the sub-function. This is the Newspaper Metaphor in Uncle Bob's Clean Code.

Generally speaking, complex if statements should be extracted to their own methods. Those nasty ifs should be substituted by a meaningful name that explains what is being tested so readers don't have to parse those huge lines of code.

But besides that, there is more refactoring to be done there. If I were reading the purchase ou isCreditOk methods, I wouldn't want to see that for loop calculating the total value. That's not an easy-read. I'd have to stop my eyes at that point, mentally parse that block to try to figure out what it's doing. The for loop should be extracted to another method called getOrderPrice, getTotalPrice or something like that.

Better than that, the items set could be extract to it's own class: OrderItems. The class would have a method like getTotal that would return the sum of its own items. That's the Single Responsibility Principle, the OrderItems class is the one that handles its own items. In addition to that, the data structure (Set in this case) would be encapsulated and you are free to change to other data structures whenever you want (if you need to change it to a list, for example).


答:
I do prefer the second example. My reasoning is that even if this is the only place in the code you need to check the user's credit right now, does not mean that this will always be the case. Now that you have abstracted out this code it will be more reusable if you ever run into a situation where you do need it.

However, like anything else this can be taken too far. Personally I think that the final example in Robert Martin's site that @Doc Brown goes a bit too far.


问:
QoS implementation algorithm
I'm working on an application, that does IP routing and QoS. Today we have the QoS implemented, with 3 priorities (low, normal and high) and for each level we create a Queue and as soon as the packages are queued, we send it forward in a FIFO way (the scheduler spend 60% of time with the high queue, 30% the time with normal and 10% with the low queue). It works, but as FIFO it has some drawbacks like:

An aggressive traffic will fill in the queue and all other flows with the same priority will be stucked

under high usage, TCP will slow down and UDP will keep flooding our Queue. It means in the end UDP flows will have better priorization then TCP flows

I was thinking a way to improve it and my idea is to implement a SFQ with the following algorithm:

keep the high, normal, low, but they aren't just 3 queues, but one per (seen) protocol

The scheduler still spending 60% of time we spend with the high queues, 30% the time with normal and 10% with the low queues. But now, it does a round-robin between the queues with the same priority. The choosen Queue, will still forward the packets in a FIFO way.

drawbacks from this implementation:

it is more expensive to the CPU

Am I missing something? Any recommendation?

答: Have a look at Hurst or long range dependent network traffic for example this paper.  If it is your problem, then you cannot reduce long range dependent traffic with queueing policies.</p>

Title: QoS implementation algorithm

ContentLicense: CC BY-SA 4.0


答:
Abstraction is more focus on What and less on How. Or you can say, know only the things you need to, and just trust the provider for all other services. It sometimes even hides the identity of the service provider.

For example, this site provides a system for asking questions and answering them. Almost everyone here knows what are the procedures for asking, answering, voting and other things of this site. But very few knows what are the underlying technologies. Like whether the site was developed with ASP.net mvc or Python, whether this runs on a Windows or a Linux server etc. Because that is none of our business. So, this site is keeping an abstraction layer over its underlying mechanism to us providing the service.

Some other examples:

A car hides all its mechanisms but provides a way to drive, refuel and maintain it to it's owner.

Any API hides all its implementation details providing the service to other programmers.

A class in OOP hides its private members and implementation of public members providing the service to call the public members.

While using an object of type of an Interface or an abstract class in Java or C++, the real implementation is hidden. And not just hidden, the implementations of the methods declared in the Interface are also likely to be different in various implemented/inherited classes. But as you are getting the same service, just don't bother How it is implemented and exactly Who/What is providing the service.

Identity Hiding: For the sentence "I know Sam can write computer programs." the abstraction can be- "Sam is a programmer. Programmers know how to write computer programs." In the second statement, the person is not important. But his ability to do programming is important.

Title: What is abstraction?

Body: Is there a generally agreed upon definition for what a programming abstraction is, as used by programmers? [Note, programming abstraction is not to be confused with dictionary definitions for the word "abstraction."] Is there an unambiguous, or even mathematical definition? What are some clear examples of abstractions?


答:
I split up function even if I don't plan to reuse the functionality.
Also I try to keep function size smaller than the screen-size.

This brings 2 advantages, first I can grasp what the function does without scrolling and I can minimize the comments, because every function gets a speaking name.


答:
It is very difficult to work under these "ready, fire, aim" conditions.  It sounds to me like you are receiving requirements from a very insecure person, whose opinion changes each time a higher up person suggests a conceptual idea.

In these kinds of situations, I have found it valuable to wait AT LEAST an hour before responding to emails. (I'd ignore the texts, unless texting has widely replaced email by your organization as a whole.)  Read them, maybe, but not respond.  This way you can spend your time focusing on the actual work you need to do, not the discussion of random urgencies that may become irrelevant tomorrow, or even two or three emails later.  In my last job, if something was REALLY urgent, someone would come over and talk to me in person, assuming I hadn't seen the emails yet (if you work remotely, a phone call with an actual two-way conversation may be the equivalent).

When you have the face to face or phone conversation, it is helpful to repeat what the person is asking for in your own words, and then ask your questions about the new requirements and priority. "If I understand correctly, you're saying we should stop working on Current Top priority X and now focus on Priority of the Minute Y.  That's a big shift.  Can you explain the change in the business?  I might need to do more background work than just changing the UI.  Will there be changes in other business processes, like billing or inventory (for example)?  Are you going to expect these new data elements to appear on all the monthly reports?"  It is also useful to say something to the effect of " You understand that if we proceed with this new effort, it will delay the release of Current Top priority X by at least a (week, month, fill in WAG time estimate here), right?"

If it's a real emergency, the requestor should be able to answer these kinds of questions, or immediately refer you to someone who could.  If it's not a real emergency, this kind of conversation will force the requestor to slow down and determine how important the change really is, given that they need to get you more information.  Often they'll see that what's already in the pipe is more important, or at least not worth stopping, and the new request can go on the list.

If the changes are determined to be necessary, I've found it useful to write down what was requested and your understanding of the changes in an email, and send it to the original requestor, asking if they agree on the scope of the change, again, as clarification. This way you have written documentation of what needs to be done, and why it was requested, in case there is any blow back on why you are no longer working on Current Top Priority X, or need to explain why the original deadlines are not going to be met.

This should hopefully improve your relationship with the requestor, since you are demonstrating your knowledge, and making sure that you are working on what they want, but you are being honest about what it takes to make changes.  By asking about the request in detail, they see that you think ahead, and consider things they might not have originally.


问:
Can display issues affect SEO?
Can website display issues on certain platforms affect a website's search rankings and potentially hinder any SEO efforts?</p>

答:
I don’t know what you mean by “even perform SEO”

The fact of matter is that if the Site doesn’t render properly on Mobile devices it will affect your position on Mobile search results.

That beings said, if by performing SEO you mean she is editing your HTML, then yes She is right to ask you to finalize you HTML prior to her changing it (or making change recommendations).

Title: Can display issues affect SEO?


问:
Is it bad to use Unicode characters in variable names?
I recently tried to implement a ranking algorithm, AllegSkill, to Python 3.

Here's what the maths looks like:

No, really.

This is then what I wrote:

```<code>t = (µw-µl)/c  # those are used in
e = ε/c        # multiple places.
σw_new = (σw**2 * (1 - (σw**2)/(c**2)*Wwin(t, e)) + γ**2)**.5
</code>```

I actually thought it is unfortunate of Python 3 to not accept √ or ² as variable names.

```<code>>>> √ = lambda x: x**.5
  File "<stdin>", line 1
    √ = lambda x: x**.5
      ^
SyntaxError: invalid character in identifier
</code>```

Am I out of my mind? Should I have resorted for a ASCII only version? Why? Wouldn't an ASCII only version of the above be harder to validate for equivalence with the formulas?

Mind you, I understand some Unicode glyphs look very much like each other and some like     ▄ (or is that ▗▖ ) or ╦  just can't make any sense in written code. However, this is hardly the case for Maths or arrow glyphs.

Per request, the ASCII only version would be something along the lines of:

```<code>winner_sigma_new = ( winner_sigma ** 2 *
                    ( 1 -
                     ( winner_sigma ** 2 -
                       general_uncertainty ** 2
                     ) * Wwin(t,e)
                    ) + dynamics ** 2
                   )**.5
</code>```

...per each step of the algorithm.

答:
In this one case, a complex maths formula, I'd say go for it.

I can say in 20 years I've never had to code something this complex and greek letters keeps it close to the original maths. If you can't understand it, you shouldn't be maintaining it.

Saying that, if I ever have to maintain µ and σ in bog standard code that you bequeathed me, I will find out where you live...


问:
Can a function be too short?
Whenever I find myself writing the same logic more than once, I usually stick it in a function so there is only one place in my application I have to maintain that logic. A side effect is that I sometimes end up with one or two line functions such as:

```<code>function conditionMet(){
   return x == condition;
}
</code>```

OR

```<code>function runCallback(callback){
   if($.isFunction(callback))
     callback();
}
</code>```

Is this lazy or a bad practice? I only ask because this results in a greater number of function calls for very tiny pieces of logic.

答:
Too short never is a problem. Some reasons for short functions are:

Reusability

E.g. if you have a function, like a set method, you might assert it to be sure the parameters are valid. This checking has to be done everywhere the variable is set.

Maintainability

You might use some statement that you think in the future may change. E.g. you now show a symbol in a column, but later that might change to something else (or even a beep).

Uniformity

You are using e.g. the facade pattern and the only thing a function does is exactly passing the function to another without changing arguments.

Title: Can a function be too short?


问:
Using UML and Use Cases in Game Design
In the Use case you need to make all the activities the user can do. And then in the Activity diagram I need to explain the Use cases, show the steps that it handles.

But if this is all correct, where do I need to show the enemies? Like: Generate path, walk, etc...
Because it isn't controlled by the player, the player has almost no influence on the enemy.

答:
I apologize if this derails you a bit (and leads to any confusion), but my suggestion is don't worry about formal UML (or any other modelling tools for that matter). Put something together that makes sense to you, allows you to catch architecture issues early and allows you to convey your ideas to others. Of course, it's a good thing to follow some semblance of a known modelling tool, but it's not the end of the world if your entire architecture is drawn in crayon on a napkin (okay, so that's a bit of an exaggeration ;)).

One of the major points of using these tools is to fail fast and fail cheap (it's a lot better to catch logic/architecture issues up front and early rather than when you're knee deep in code that takes a tremendous amount of time to refactor). If you're spending more time trying to figure out how you should be using these tools rather than flushing out your logic, something sounds a little suspicious to me ;)

In over ten years professional experience with many people much smarter than myself, I have yet to encounter anyone who can remember ever syntactic element of UML when whiteboarding (or if they do, who care enough to use it).

Just go 'n get stuff done. Don't worry so much about the formal details.

Title: Using UML and Use Cases in Game Design


问:
Entity-Component-System architecture: interaction between systems
I am studying the Entity-Component-System architecture philosophy. As I have read about it, a typical entity system has:

1) Entities - which are merely ID tags which have a number of components

2) Components - which contain data on various aspects of an enity that the component is responsible for

3) Systems - which update relevant components of every entity. Say, a rendering system updates the rendering component, or simply saying, draws a picture that is stored in the data of that component. A positional and movement system handles position and movement of each entity who has a corresponding component.

These statements follow from this article which in my opition tries to be the most clear and pure in it's statements -

But the author did not explain how the interaction between systems should be realized. For example, the rendering system must know the data from the positional component of an entity in order to draw it in a correct position. And so on.

So the question is - how should I implement the interaction between the various systems?

答:
Systems and Components are not restricted to 1:1 relationship, though that is a desired trait that allows parallel processing without requiring synchronization. Generally a system can operate on any number of components attached to a entity. For example consider the following typical setup:

Components

Mass

Acceleration

Velocity

Position

BoundingVolume (for collision detection)

Model (visual representation)

Systems (with components they operate on)

Physics: Mass, Acceleration, Velocity, Position, BoundingVolume

Rendering: Position, Model

This gives every system access to all the components it requres, without the need for intersystem communication (actually this communication happens implicitly via components), but at the cost of sacrificing parallelization.


答:
This decision hinges on two (possibly contradictory) principles/guidelies: Single Responsibility Principle and You ain't gonna need it. Per SRP you should be thinking about class boundaries, and not method boundaries here, but for the sake of this question, let's just talk about methods. A huge benefit you get out of SRP is that each of your classes/methods only has a single reason to change.

Let's say that in the future, you add more warehouses, so you need to ask some order dispatcher object which warehouse has the stock necessary for the order. If you've gone with the giant method as implementation, that method is going to start growing. Not only are you now changing things that are unnecessarily and dangerously close to functionality that is already tested, it's going to be common to let some of this functionality bleed around the method, into unrelated code. The monolithic method will become a maintenance hassle when you decide you need to implement tax on some items, and charge shipping on orders as well, based on the total weight of the order. Breaking up this behavior into (initially) small methods with a single reason to change will make future modifications much easier and safer, because changes are made in small units of code, and invisible side effects are much more difficult to accidentally introduce.

The other side of this coin is the fact that you might not ever need this flexibility (YAGNI), and spiking up a quick and dirty solution for a proof of concept might be exactly what you really need. "Shipping your software" is a feature, some would argue the most important feature possible; spending hours of work on following principles when you don't ever see the upside just isn't worth it when you could ship instead.

The reality here is that it's a judgement call that's entirely up to you (or maybe your boss/tech lead). Modern IDEs make it really easy to navigate around multiple classes and methods, and good practices with namespaces and directory structure make it very easy to keep track of where everything is. If you just want to see all the functionality in one method in one class, then you may be a procedural programmer who doesn't want to do object-oriented design. That's fine, but you should make the decision deliberately. Any OO guideline can be abused and carried to an extreme, and learning when to apply various "rules" effectively can be a tricky skill to learn. If it were easy, everyone would do it, all you need to do is keep asking questions and reflecting on experience.


问:
Is it a good idea to install Mercurial on your server and hg pull to deploy?
I've just started at a new job this past month and looks like they have NO source control for their code. They are relying on the backups their hosting provider takes for them.

After talking a bit I convinced my boss that we should definitely be using source control and after I gave a short seminar on it, the entire team is on board; they loved Mercurial.

So right now this is the way we work:

```<code>º----------BitBucket
º---------/
º--------/
</code>```

Myself and the three other developers hg pull from BitBucket, make our changes, then hg push to BitBucket.

Now for deployment, someone would need to FTP the latest files towards the production server.

I was thinking of installing Mercurial on our server, and using hg clone (subsequently hg pull) to keep the versions up to date on production.

```<code>º---push->-----BitBucket----<-pull-----º (production server)
º---push->----/
º---push->---/
</code>```

Is this a good idea? Any potential pitfalls I may not be seeing? Has anybody here done something similar? How do you deploy a large PHP framework application (We're using Moodle)?

答:
This is certainly a good idea and it is a common method to use for deployment. You might want to use a stable branch for deployment purposes whilst keeping trunk for ongoing development so that you can test the stable branch before you deploy it into production.

The only problem can come when you have sensitive information in your code base (such as API keys etc) that you do not wish to upload to third party servers (in your case that would be Bitbucket). In this case a simple script that is run once you have pulled the data from the repository to restore the sensitive data in the correct place will solve that issue.


答:
I agree with @Demian Brecht.

It is really important to not get caught up in semantics.

What is really important is that you flesh out any design snags that
  you have yet to encounter.

In other words:

The value of UML is not just to write some precise model so that the world can understand your design, but it is a tool, so that... you can understand your design, then share with your colleagues.

So, just keep drawing. Ask the questions: "Does this accurately represent the Current State, or Future State?", "Are we leaving anything out?", "Does this pass the practicality test?".

With practice, it is possible to envision diagrams before fully understanding why they represent higher-orders of complexity. Comparing any diagram to reality can then reveal unexpected oversights or optimizations (hidden-fruit).

In all cases: it really doesn't matter if the arrow has a crows-foot pointing in the right direction or not. What matters is that you are fleshing out the design through a visual process, so as that aspects of the design challenge are not hidden from your awareness at development time (time-bomb).

To directly answer your question on Activity Diagram:
What you need to do is to find a way to make your activity diagram meaningful.
If you cannot see a way to fit the enemies into the UML prototype that you are looking at, consider how it may be adjusted so that they can fit in. Do not feel limited by tradition. The goal is to visualize the design of enemies on paper.

If it is meaningful, it is valuable - and can be re-used later. If it
  is meaningless, it is not valuable - ever.

So just put what you know down, and start to add on to it. When you realize that something is left out, figure out how to incorporate it visually into your diagram. This will lead you into new realms of awareness of your design that you did not originally conceive. Finding this awareness is the point of improving your designs. Only then do you finalize the diagram into a standard way that others can understand. Only then, is the Unified aspect of modeling applied. In the interim, it is up to you to discover what is unknown through iterative diagramming.

Hope that helps.

Title: Using UML and Use Cases in Game Design

Body:
In the Use case you need to make all the activities the user can do. And then in the Activity diagram I need to explain the Use cases, show the steps that it handles.

But if this is all correct, where do I need to show the enemies? Like: Generate path, walk, etc...
Because it isn't controlled by the player, the player has almost no influence on the enemy.


问:
What do you call an interface with no defining methods used as property setters
In ASP.NET and C# I've ran across this before.  Your class needs to implement interface ISomething in order for something in the super class to supply something to you.

I can't remember the details, as I ran across it quite a while ago, but it had something to do with session variables in ASP.NET C#.  It was part of the .NET framework.

At first, I thought this practice was rather silly and could be more gracefully implemented.  However now I'm finding myself implementing this in the architecture of a home-grown project I'm working on.  Using reflection, I detect the toggle a behavior on or off based on if it implements ISomething.  Just an empty interface with no methods at all.

What is the technical name for this and is it good practice?

答:
It's simple--it works with ordinary interfaces.  It's used in Java a lot, Java lacking all the bells and whistles of C#.  If you use it, you shouldn't even need reflection (unless "is" is part of reflection), just:

```<code>if (list is RandomAccess)  element = list[1000000005];
else Consol.WriteLine( "You do not have enough time to wait." )
</code>```

(The code's C#, RandomAccess is Java.  I think.)  It can be even simpler, as:

```<code>public int GetElement( RandomAccess list )  { ... }
</code>```

which means you never even have to check for a linked list sneaking though.

And no technology beyond interfaces is needed.  It is more of a Java-y thing than a .NET thing.  Simple, graceful, clever, and a bit sneaky.  Better?  Don't know.

Body:
It's simple--it works with ordinary interfaces.  It's used in Java a lot, Java lacking all the bells and whistles of C#.  If you use it, you shouldn't even need reflection (unless "is" is part of reflection), just:

if (list is RandomAccess)  element = list[1000000005];
else Consol.WriteLine( "You do not have enough time to wait." )

(The code's C#, RandomAccess is Java.  I think.)  It can be even simpler, as:

public int GetElement( RandomAccess list )  { ... }

which means you never even have to check for a linked list sneaking though.

And no technology beyond interfaces is needed.  It is more of a Java-y thing than a .NET thing.  Simple, graceful, clever, and a bit sneaky.  Better?  Don't know.


答: I would rather see IsCreditOK be a property of Customer rather than it's own method.  I think it's a cleaner approach...</p>


问:
When to use C over C++, and C++ over C?
I've been introduced to Computer Science for a little over a year now, and from my experience it seems that C and C++ are both considered to be "ultrafast" languages, whereas others such as Python and such scripting languages are usually deemed somewhat slower.

But I've also seen many cases where a software project or even a small one would interleave files where a certain number n of those files would be written in C, and a certain number m of those files would be written in C++.

(I also noticed that C++ files almost always have corresponding headers, while C files not so much). But my main point of inquiry is to get a general sense of intuition on when it is appropriate to use C over C++, and when it is better to use C++ over C. Other than the facts that (1) C++ is object-oriented whereas C is not, and (2) the syntaxes are very similar, and C++ was intentionally created to resemble C in many ways, I am not sure what their differences are. It seems to me that they are (almost) perfectly interchangeable in many domains.

So it would be appreciated if someone could clear up the situation! Thanks

答:
In my opinion there is one point missing in this discussion: It is simpler in C to provide a stable binary interface from a library. Both for usage with other languages as well as C++.

In C++ different compilers use different name mangling so consumers of a library compiled with a different compiler from the library might have issues using it. With C the binary interface, usually, is standardized for the platform.

I know that compilers nowadays often have switches to produce gcc-compatible things, but that doesn't always help.

I observe this on Solaris relatively often. The distribution and different software vendors typically use Sun Studio as, especially on Sparc systems, it often provides better results. Man open source projects are written with gcc-specific code though. Can be quite some pain to get those working together.

Title: When to use C over C++, and C++ over C?


答:
Mind that this deployment strategy is not atomic. It might happen that some files are already updated while other files might still be in the old state while the application is being hit. This can cause unexpected side effects.

A way to do atomic deployments is by i.e. using symlinks. Create a directory containing the new files. when everthing is ready change a symlink for the directory used. If you keep the old version around you can also easily rollback.

Title: Is it a good idea to install Mercurial on your server and hg pull to deploy?

Body:
I've just started at a new job this past month and looks like they have NO source control for their code. They are relying on the backups their hosting provider takes for them.

After talking a bit I convinced my boss that we should definitely be using source control and after I gave a short seminar on it, the entire team is on board; they loved Mercurial.

So right now this is the way we work:

```<code>º----------BitBucket
º---------/
º--------/
</code>```

Myself and the three other developers hg pull from BitBucket, make our changes, then hg push to BitBucket.

Now for deployment, someone would need to FTP the latest files towards the production server.

I was thinking of installing Mercurial on our server, and using hg clone (subsequently hg pull) to keep the versions up to date on production.

```<code>º---push->-----BitBucket----<-pull-----º (production server)
º---push->----/
º---push->---/
</code>```

Is this a good idea? Any potential pitfalls I may not be seeing? Has anybody here done something similar? How do you deploy a large PHP framework application (We're using Moodle)?


答:
Is this code just for your personal project?  If so, go nuts, use whatever you want.

Is this code meant for others to use?  i.e., and open source app of some sort?  If so, you're likely just asking for trouble because different programmers use different editors, and you cant be certain all editors will support unicode correctly.  Plus not all command shells will show it correctly when the source code file is type'd/cat'd, and you may run into issues if you need to display it within html.

Title: Is it bad to use Unicode characters in variable names?

Body:
I recently tried to implement a ranking algorithm, AllegSkill, to Python 3.

Here's what the maths looks like:

No, really.

This is then what I wrote:

```<code>t = (µw-µl)/c  # those are used in
e = ε/c        # multiple places.
σw_new = (σw**2 * (1 - (σw**2)/(c**2)*Wwin(t, e)) + γ**2)**.5
</code>```

I actually thought it is unfortunate of Python 3 to not accept √ or ² as variable names.

```<code>>>> √ = lambda x: x**.5
  File "<stdin>", line 1
    √ = lambda x: x**.5
      ^
SyntaxError: invalid character in identifier
</code>```

Am I out of my mind? Should I have resorted for a ASCII only version? Why? Wouldn't an ASCII only version of the above be harder to validate for equivalence with the formulas?

Mind you, I understand some Unicode glyphs look very much like each other and some like     ▄ (or is that ▗▖ ) or ╦  just can't make any sense in written code. However, this is hardly the case for Maths or arrow glyphs.

Per request, the ASCII only version would be something along the lines of:

```<code>winner_sigma_new = ( winner_sigma ** 2 *
                    ( 1 -
                     ( winner_sigma ** 2 -
                       general_uncertainty ** 2
                     ) * Wwin(t,e)
                    ) + dynamics ** 2
                   )**.5
</code>```

...per each step of the algorithm.


答:
When you give a code section a name, it is essentially for giving it a name.  This can be for any of several reasons, but the crucial point is if you can give it a meaningful name which adds to your program.  Names like "addOneToCounter" would not add anything, but conditionMet() would.

If you need a rule for finding out if the snippet is too short or too long, then consider how long time it takes you to find a meaningful name for the snippet.  If you cannot within a reasonable amount of time, then the snippet is not a suitable size.

Title: Can a function be too short?

Body:
Whenever I find myself writing the same logic more than once, I usually stick it in a function so there is only one place in my application I have to maintain that logic. A side effect is that I sometimes end up with one or two line functions such as:

```<code>function conditionMet(){
   return x == condition;
}
</code>```

OR

```<code>function runCallback(callback){
   if($.isFunction(callback))
     callback();
}
</code>```

Is this lazy or a bad practice? I only ask because this results in a greater number of function calls for very tiny pieces of logic.


答:
I think splitting up functions is a good idea. But you need to be careful. If you simply split functions for splitting's sake you end up with a bit of a mess. When I've seen Uncle Bob's stuff he often seems to be splitting without thought. Decomposing a function requires care and skill, and shouldn't be done lightly.

```<code>public boolean isCreditOk(Customer customer, Set<Item> items){
     int credit = customer.getCredit();
     int orderPrice;

     for(Item item: items){
         orderPrice+=items.getPrice();
     }
     return  orderPrice + customer.getPendingPayments() > customer.getCredit();
}
</code>```

I'm sure this is just an example, but I'm going to point out where I think it went wrong. You've combined two distinct tasks, calculating the total for an order, and checking for credit. This function would be better written as:

```<code>public boolean isCreditOk(Customer customer, int amount)
{
    return amount <= customer.getCredit() - customer.getPendingPayments();
}
</code>```

This also suggests that the function would do well to be a method on Customer. It'll be much easier to test this function if you can simply pass dollar amounts rather then constructing lists of items.

I aim to create functions which could in principle be reused. I don't necessarily expect to reuse them, but when a function is reusable that tells me I've a useful decomposition.

Body:
I think splitting up functions is a good idea. But you need to be careful. If you simply split functions for splitting's sake you end up with a bit of a mess. When I've seen Uncle Bob's stuff he often seems to be splitting without thought. Decomposing a function requires care and skill, and shouldn't be done lightly.

public boolean isCreditOk(Customer customer, Set<Item> items){
     int credit = customer.getCredit();
     int orderPrice;

     for(Item item: items){
         orderPrice+=items.getPrice();
     }
     return  orderPrice + customer.getPendingPayments() > customer.getCredit();
}

I'm sure this is just an example, but I'm going to point out where I think it went wrong. You've combined two distinct tasks, calculating the total for an order, and checking for credit. This function would be better written as:

public boolean isCreditOk(Customer customer, int amount)
{
    return amount <= customer.getCredit() - customer.getPendingPayments();
}

This also suggests that the function would do well to be a method on Customer. It'll be much easier to test this function if you can simply pass dollar amounts rather then constructing lists of items.

I aim to create functions which could in principle be reused. I don't necessarily expect to reuse them, but when a function is reusable that tells me I've a useful decomposition.